简体   繁体   中英

C# / XNA Line Rectangle Collision/Response

To start with, I have a simple class, Line ;

public class Line
{
    public Vector2 P1 = Vector2.Zero;
    public Vector2 P2 = Vector2.Zero;

    public Line(Vector2 p1, Vector2 p2)
    {
        P1 = p1;
        P2 = p2;
    }
}

A list of all lines in the game, and my sprites bounding rectangle. I'm trying to find whether or not this rectangles bottom middle is below the point on the line it's directly above, and update it to the point on the line it's at. This picture might help you understand what I mean; 在此处输入图片说明

The rectangle is moving down, passes it's intersection point, then updates accordingly.

Any ideas on how you could go about this? I can easily find which line it's currently above, but I don't know how to get the point on the line it's above and keep it from falling past that point.

Code samples or references would be great.

If you know the locations of the endpoints of the line, then it's pretty trivial to get the equation of that line in the form y = mx + c. Then you need to find the midpoint of the bottom of that rectangle - seeing as the XNA rectangle gives you its height, width and centre point location, this is also trivial. From there, you take the x co-ordinate of your rectangle centre point, use the y = mx + c equation to work out the y co-ordinate of your line at that point. Then you just need to check whether the rectangle's bottom centre is below that point, and if it is, use your rectangle's height value to work out how far above that y co-ordinate you need to put the rectangle so that it appears to sit on the line. Should be simple enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM