How do I use an if condition to tell whether two lines intersect?
3 views (last 30 days)
Show older comments
I'm trying to use an if statement to plot a balls entire trajectory if it goes through a hole in the wall, and to plot the trajectory only up to the wall if it doesn't go through the hole. Is there a way to tell if the path of the ball intersects with the line of the wall?
Is there a way to see if this plot:
BallPositionX=function of t
BallPositionY=function of t
plot(BallPositionX,BallPositionY)
intersects with a vertical line (the wall)?
I've tried so many things, maybe I am overthinking it? Any help is much appreciated!
2 Comments
Mandar Patwardhan
on 6 Sep 2016
Refer to the following MathWorks blog link which talks in detail about various ways to check if the two lines are intersecting each other.
You can write a function using the algorithms discussed in the blog and check the output of this function in an if condition.
Answers (1)
Image Analyst
on 6 Sep 2016
I assume you're looking at this only in 2-D so you have only x and y. You need to know the bottom y coordinate of the hole, and the top y coordinate of the hole. And you said you have (BallPositionX, BallPositionY) as a function of t. You must also know the radius of the ball so you know if it can fit through the hole or not, and you must know the x position of the wall, xWall. With all that you can do:
% Find index where the ball is at or to the right of the wall,
% assuming the ball is moving from left to right.
index = find(BallPositionX > xWall, 1, 'first');
% Find the y position of the center of the ball at that time.
yBallAtWall = BallPositionY(index);
% See if yBallAtWall is within the hole
if (yBallAtWall - ballRadius) > yHoleBottom && (yBallAtWall + ballRadius) < yHoleTop
% It went through the hole.
else
% It hit the wall.
end
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!