GameObject
1、p v GetRectangle
Rectangle rectangle = new X Y Width Height
GameObjectManager
1、bool isCollidedWall(rectangle rt)
for each nomovething wall
if wall.GetRectangle().IntersectsWith(rt) return true
2、gai
static nomovething
return wall
MyTank
1、if (GameObjectManager.isCollidedWall =/ null
ismoving false
2、rectangle rect = getRectangle()
switch case
rect.Y -= speed
向上:rect.Y += speed
向下:rect.X -= speed
向左:rect.X += speed
向右:
3 isCollidedWall(rect)
操作步骤总结
-
理解碰撞检测原理
-
通过判断两个矩形(
Rectangle)是否相交来确定碰撞。 -
系统提供的
Rectangle类(位于System.Drawing)用于表示游戏物体的位置和大小。
-
-
为游戏物体添加矩形获取方法
-
在每个游戏物体类中实现
GetRectangle()方法,返回其对应的矩形:csharp
public Rectangle GetRectangle() { return new Rectangle(X, Y, Width, Height); }
-
-
在游戏管理类中实现碰撞检测方法
-
方法名:
IsCollideWithWall(Rectangle rect) -
功能:检测传入的矩形是否与任意墙体的矩形相交。
-
关键函数:
Rectangle.IntersectsWith()csharp
public Wall IsCollideWithWall(Rectangle rect) { foreach (Wall wall in wallList) { if (wall.GetRectangle().IntersectsWith(rect)) { return wall; // 返回碰撞的墙体 } } return null; // 无碰撞 }
-
-
预判未来位置避免穿透
-
在移动前,根据移动方向(
Direction)计算下一步的矩形位置:csharp
Rectangle futureRect = currentRect; switch (direction) { case Direction.Up: futureRect.Y -= speed; break; case Direction.Down: futureRect.Y += speed; break; // 处理 Left/Right 方向... } -
用
futureRect调用IsCollideWithWall()检测碰撞。
-
-
处理碰撞结果
-
如果返回非
null,则禁止移动:csharp
if (GameObjectManager.IsCollideWithWall(futureRect) != null) { isMoving = false; return; }
-
关键函数与类
-
Rectangle类-
命名空间:
System.Drawing -
构造方法:
new Rectangle(x, y, width, height) -
碰撞检测方法:
IntersectsWith(Rectangle other)
-
-
自定义方法
-
GetRectangle():返回游戏物体的矩形区域。 -
IsCollideWithWall(Rectangle rect):检测与墙体的碰撞,返回碰撞的墙体对象或null。
-
-
注意事项
-
碰撞检测需基于“未来位置”而非当前位置,避免穿透。
-
方向枚举(如
Direction.Up)需提前定义。
-
