2014-10-17 68 views
1

我已经创建了两个矩形,可以随其中一个移动并跳起,另一个静止在窗体上作为障碍物。 我希望障碍物作为障碍物(或者墙壁,如果你愿意的话),基本上我想让活动矩形在其右侧碰撞障碍物左侧(等等)时停止。二维矩形在碰撞时应该停止移动

我发现这个代码如何检测碰撞(因为它显然更容易不进行碰撞检测)的一篇文章中两个矩形之间:

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语句中应该包含的内容)方(等等)?

+4

在那个Rectangle实现中有一个'Rectangle.Intersects()'方法吗?如果是这样:'bool collided = rect1.Intersects(rect2);' – itsme86 2014-10-17 15:03:23

+0

“,因为它显然更容易检测不到碰撞”。不会说这更容易,但更快。它停止检查其余的值。更快速地连续检查每个更新的1个条件与4. – TyCobb 2014-10-17 15:26:55

回答

1

// UPDATE 假设您有从Rectangle继承的PlayableCharacter类。

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

}

在代码I`ve给你,在一个情况,当角色是要正确的,这是肯定的x值,该角色会面对另一个方向。如果他在左边移动,如果他碰到障碍物,他将面对另一个方向。

使用StopMoving,即使您制作的脚本随时间在循环中运行,但它不会让角色移动。

我认为这应该为您的工作奠定基础。如果有任何问题,请对我写的解决方案发表评论,我会尽我所能帮助你,如果它在我的范围内。

+0

@ Anders23通常,当您使对象移动时,这是因为您正在修改其位置的像素值。当你使用我的代码时,你可以停止这个过程。 – 2014-10-17 15:47:25

+0

如果我想要可移动矩形停止向右移动(但仍然能够跳跃并移动到左侧),代码将如何显示(如果其右侧与障碍物左侧碰撞)(等等)? – Anders23 2014-10-17 16:09:19

+0

如果提供的答案以任何方式帮助您,或者实际上您是在寻找答案,请将其标记为答案,以便其他人在未来知道! :) @ Anders23 – 2014-10-19 00:57:03