Collision detection while using rectangles

五迷三道 提交于 2019-12-13 04:37:57

问题


So I understand that I'm not coding this the best way possible at the moment; this is a sort of test run. What I'm trying to do is wall collisions using rectangles and the intersects property (sorry if I'm not using the correct terminology). So far I have 2 rectangles on screen. 1 the player controls and the other which the play is colliding with. When they collide the player stops moving. The problem is that if the player is trying to move into the rectangle while they are already colliding then the player can't move in any direction perpendicular to the movement ie if the player is holding the right arrow key moving into the rectangle, then they cannot move up or down. The game works on the premise that if your x or y coordinates aren't valid, then you will be moved back to the last valid coordinate recorded but I'm having trouble detecting the valid x and y coordinate separately. Here is the code:

public void Collision() 
{

    if(x < 0)
        x = 0;

    if(x > 400 - width)
        x = 400 - width;

    if(y < 0)
        y = 0;

    if(y > 300 - height)
        y = 300 - height;


    rect1 = new Rectangle(x, y, 16, 16);
    rect2 = new Rectangle(sx, sy, wid, hei);

    if(!rect1.intersects(rect2))
    {
        validX = true;
        validY = true;
    }
    else
    {
        validX = false;
        validY = false;
    }


    if(validX)
    {
        lastValidX = x;
    }

    if(validY)
    {
        lastValidY = y;
    }

    if(!validX)
    {
        x = lastValidX;
    }

    if(!validY)
    {
        y = lastValidY;
    }

}

The Collision() method in the Guy class is where I'm having the trouble I believe. Yes my code is pretty messy right now but this is only a test.

Thanks, David.


回答1:


You can implement what you're describing by doing extra logic around here (i.e. detecting cases when one is false and the other is true):

if(!rect1.intersects(rect2))
{
    validX = true;
    validY = true;
}
else
{
    validX = false;
    validY = false;
}

However, it seems like maybe you shouldn't be allowing the rectangles to ever be in a "colliding" state in the first place. For example, you can change the Move method to do something like

public void Move()
{
    int oldX = x, oldY = y;
    x += dx;
    y += dy;
    if (Collision()) {
        x = oldX;
        y = oldY;
    }
}


来源:https://stackoverflow.com/questions/18231685/collision-detection-while-using-rectangles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!