2D矩形碰撞时应停止移动
本文关键字:移动 碰撞 2D | 更新日期: 2023-09-27 18:26:57
我创建了两个矩形,你可以用其中一个移动和跳跃,另一个作为障碍物静止在Form上。我希望障碍物作为障碍物(或者墙,如果你愿意的话),基本上我希望可移动的矩形在其右侧与障碍物的左侧碰撞时停止(以此类推)。
我在一篇文章中发现了如何NOT检测两个矩形之间的碰撞(因为不检测碰撞显然更容易)的代码:
OutsideBottom = Rect1.Bottom < Rect2.Top
OutsideTop = Rect1.Top > Rect2.Bottom
OutsideLeft = Rect1.Left > Rect2.Right
OutsideRight = Rect1.Right < Rect2.Left
//or
return NOT (
(Rect1.Bottom < Rect2.Top) OR
(Rect1.Top > Rect2.Bottom) OR
(Rect1.Left > Rect2.Right) OR
(Rect1.Right < Rect2.Left) )
但我不知道如何实现它。我有一个名为"player1.left"的bool,当我按下键盘上的"a"时("D"向右移动,"W"跳跃),它将变为true,当变为true时,矩形将向左移动10个像素(在Timer_Tick事件中)。
编辑:
"rect1.IntersectsWith(rect2)"用于检测碰撞。但是,如果我希望可移动矩形的右侧与障碍物的左侧碰撞(依此类推),它停止向右移动(但仍然可以跳跃并向左移动),我该如何使用它(if语句中应该包含什么)?
//更新假设你有一个类PlayableCharacter,它继承自Rectangle。
public class PlayableCharacter:Rectangle {
//position in a cartesian space
private int _cartesianPositionX;
private int _cartesianPositionY;
//attributes of a rectangle
private int _characterWidth;
private int _characterHeight;
private bool _stopMoving=false;
public PlayableCharacter(int x, int y, int width, int height)
{
this._cartesianPositionX=x;
this._cartesianPositionY=y;
this._chacterWidth=width;
this._characterHeight=height;
}
public bool DetectCollision(PlayableCharacter pc, PlayableCharacter obstacle)
{
// this a test in your method
int x=10;
if (pc.IntersectsWith(obstacle)){
Console.Writeline("The rectangles touched");
_stopMoving=true;
ChangeMovingDirection(x);
StopMoving(x);
}
}
private void ChangeMovingDirection(int x)
{
x*=-1;
cartesianPositionX+=x;
}
private void StopMoving(int x)
{
x=0;
cartesianPositionX+=x;
}
}
在我给你的代码中,当字符向右,x值为正时,字符将面向另一个方向。如果他向左移动,如果他与障碍物相撞,他将面向另一个方向。
使用StopMoving,即使你制作了一个在循环中随时间运行的脚本,它也永远不会让角色移动。
我认为这应该是你工作的基础。如果有任何问题,请对我写的解决方案发表评论,如果我力所能及,我会尽我所能帮助您。