使用矩形时的碰撞检测 [英] Collision detection while using rectangles

查看:154
本文介绍了使用矩形时的碰撞检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我了解到我目前并未以最佳方式进行编码;这是一种测试运行。我想做的是使用矩形和intersects属性进行墙面碰撞(很抱歉,如果我使用的术语不正确)。到目前为止,我在屏幕上有2个矩形。 1个由玩家控制,另一个与游戏发生冲突。当它们碰撞时,播放器停止移动。问题是,如果玩家在已经碰撞的情况下尝试移入矩形,则玩家无法沿垂直于移动方向的任何方向移动,即如果玩家按住向右箭头键移入矩形,则他们不能上下移动。游戏的前提是,如果您的x或y坐标无效,那么您将被移回到记录的最后一个有效坐标,但是我无法分别检测有效的x和y坐标。下面是代码:

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;
    }

}

中的Collision()方法男生班是我遇到麻烦的地方。是的,我的代码现在很混乱,但这只是一个测试。

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.

谢谢大卫。

推荐答案

您可以通过在此处执行额外的逻辑来实现您正在描述的内容(即检测一种情况为假而另一种情况为真的情况):

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;
}

但是,似乎您不应该允许使用矩形首先处于碰撞状态。例如,您可以将 Move 方法更改为类似

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;
    }
}

这篇关于使用矩形时的碰撞检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆