【问题标题】:2D rectangle should stop moving when colliding碰撞时二维矩形应停止移动
【发布时间】:2014-12-13 04:54:18
【问题描述】:

我已经创建了两个矩形,你可以用其中一个移动和跳跃,另一个作为障碍物静止在 Form 上。 我希望障碍物作为障碍物(或墙壁,如果你愿意),基本上我希望可移动矩形在其右侧与障碍物的左侧碰撞时停止(等等)。

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

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”的布尔值,当我按下键盘上的“A”时它变为真(“D”向右移动,“W”跳转)当它为真时,它将矩形移动 10 个像素到left(在 Timer_Tick 事件中)。

编辑:

"rect1.IntersectsWith(rect2)" 用于检测碰撞。但是,如果我想让可移动矩形停止向右移动(但仍然能够跳跃和向左移动),如果它的右侧与障碍物的左侧碰撞,我将如何使用它(if 语句中应该包含什么)侧面(等等)?

【问题讨论】:

  • Rectangle.Intersects() 实现中是否有 Rectangle.Intersects() 方法?如果是这样:bool collided = rect1.Intersects(rect2);
  • “因为不检测碰撞显然更容易”。不会说它更容易,但更快。它停止检查其余的值。每次更新持续检查 1 个条件比 4 个更快。

标签: c# collision detection rectangles


【解决方案1】:

//更新 假设您有继承自 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;
  }

}

在我给你的代码中,在角色向右移动的情况下,x 值为正,角色将面向另一个方向。如果他向左移动,如果他遇到障碍物,他就会面向另一个方向。

使用 StopMoving,即使您制作了一个循环运行的脚本,它也永远不会让角色移动。

我认为这应该为您的工作奠定基础。如果有任何问题,请对我写的解决方案发表评论,如果可以,我会尽力帮助您。

【讨论】:

  • @Anders23 通常,当您移动对象时,这是因为您正在修改其位置的像素值。当您使用我的代码时,您可以停止该过程。
  • 如果我想让可移动矩形停止向右移动(但仍然能够跳跃和向左移动),如果它的右侧与障碍物的左侧碰撞,代码会是什么样子(等等)?
  • 如果提供的答案对您有任何帮助,或者确实是您正在寻找的答案,请将其标记为答案,以便其他人将来知道! :) @Anders23
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多