简体   繁体   English

C#/ XNA线矩形碰撞/响应

[英]C# / XNA Line Rectangle Collision/Response

To start with, I have a simple class, Line ; 首先,我有一个简单的类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. 如果您知道直线端点的位置,那么以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. 然后,您需要找到该矩形底部的中点-看到XNA矩形为您提供了其高度,宽度和中心点位置,这也是不重要的。 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. 从此处开始,获取矩形中心点的x坐标,使用y = mx + c方程计算出该点处线的y坐标。 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. 然后,您只需要检查矩形的底部中心是否在该点以下,如果是,请使用矩形的高度值计算出要放置的矩形的y坐标上方的距离,以使其看起来像在线。 Should be simple enough. 应该足够简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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