14564人加入学习
(31人评价)
C#编程-第三季-坦克大战-宇宙最简单2021最新版

使用VS2019 制作完成于2021年11月12日

价格 免费

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)
 

操作步骤总结

  1. 理解碰撞检测原理

    • 通过判断两个矩形(Rectangle)是否相交来确定碰撞。

    • 系统提供的 Rectangle 类(位于 System.Drawing)用于表示游戏物体的位置和大小。

  2. 为游戏物体添加矩形获取方法

    • 在每个游戏物体类中实现 GetRectangle() 方法,返回其对应的矩形:

      csharp

      public Rectangle GetRectangle() {
          return new Rectangle(X, Y, Width, Height);
      }
  3. 在游戏管理类中实现碰撞检测方法

    • 方法名: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; // 无碰撞
      }
  4. 预判未来位置避免穿透

    • 在移动前,根据移动方向(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() 检测碰撞。

  5. 处理碰撞结果

    • 如果返回非 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)需提前定义。

[展开全文]

授课教师

问问题加入A计划,有专门负责答疑的老师哦!!!

课程特色

图文(1)
下载资料(1)
视频(35)

学员动态

SH1RO111 加入学习
ZWen 开始学习 素材.zip
ZWen 加入学习
gravity9 加入学习