【问题标题】:Rect Collisions矩形碰撞
【发布时间】:2021-04-30 10:50:33
【问题描述】:

我正在开发一个使用 Javascript 的游戏,其中我有一个玩家尝试收集硬币。两者目前都是具有不同尺寸的 rects(),我正在尝试合并一个功能,在用户收到硬币时提醒他们。目前,这是我的玩家和硬币碰撞检测代码。

isTouching(player) {

        return player.x + player.width > this.x &&
               this.x + this.width > player.x &&
               player.y + player.height > this.y &&
               this.y + this.height > player.y;

    }

但是,当我遍历我的硬币数组并检查碰撞时,什么也没有发生。为什么是这样?这是我与此相关的代码:

for (let x = 0; x < 5; x ++) { coins[x].collisions(); }

还有……

collisions() {

        if (this.isTouching(player)) {

            alert("you got a coin!");

        }

    }

我的硬币和玩家都有自己的类,我的硬币存储在一个数组中。

let player;
let coins = [];
player =    new Player();
for (let x = 0; x < 5; x ++) { coins.push(new Coin()); }

即使玩家触摸硬币,也不会发出警报。我该如何解决这个问题?

附:我知道有很多库能够检查矩形之间的碰撞,但我想利用我自己的函数来检查碰撞。请告诉我如何/如果我需要更改我的碰撞检测系统。

另外,如果我提供的代码不清楚,这里是一个包含我的程序代码的 .zip(下载链接):https://www.mediafire.com/file/00rz1ta5s55rvzf/game.zip/file

编辑:一条评论建议我使用库来检查冲突,我在技术上不允许这样做,但为了测试,我尝试了。我导入了过去对我有用的bmoren's p5.collide2D 库,并使用了这段代码(如下)。但是问题依然存在,根本没有检测到物体之间的碰撞。

利用库的新代码:

if (this.touched()) {
        
     alert("you got a coin!");
        
}
        
touched() {
        
     return collideRectRect(this.x, this.y, this.width, this.height, player.x, player.y, player.width, player.height);
        
}

【问题讨论】:

  • 编程中最重要的规则之一:不要重新发明轮子。如果那里有适合您需要的图书馆,请使用它。如果您将其用作学习经验,那就足够了。为了避免我们在其他地方的所有代码中费力,请考虑在此处提供 minimal reproducible example 来演示问题
  • 对不起,这是一个我试图减少使用库的项目,这意味着我需要编写自己的函数。尽管如此,我尝试在之前的项目(bmoren 的 p5collide2d)中使用对我有用的库,但这也不起作用。我已经编辑了我的原始帖子并包含了我的新代码。

标签: javascript collision-detection p5.js


【解决方案1】:

只需阅读您的所有代码。我能够让硬币警报正常工作,这是您需要更改的内容

在 game.engine.js 中,更改函数设置。在这里我更新了你的循环,问题是你的随机 x 和 y 硬币需要传递给你的硬币类实例。

function setup() {

  // Apply classes to empty variables
  console.log("Creating player...");
  player =    new Player();

  console.log("Creating world...");
  world  =    new World();

  console.log("Creating coins...");
  for (let i = 0; i < number_of_coins; i++) { coins.push(new Coin(coin_cords_X[i], coin_cords_Y[i])); }

  console.log("Creating controller...");
  controller = new Controller();

  // Draw canvas with set size
  console.log("Creating game screen...");
  createCanvas(1250, 750);

}

现在,您的 game.coin.js 需要在构造函数中获取传递的 x 和 y 并使用它。

class Coin {

    // Setup player attributes
    x;
    y;
    width;
    height;

    constructor(x, y) {

        this.x = x;
        this.y = y;
        this.width = 30;
        this.height = 30;

    }

    show(x) {
        fill(player.color);

        rect(this.x, this.y, this.width, this.height);

    }

  // rest of the methods will be as is
}

已经完成了这两件事,它应该可以正常工作。

我附上了修改后的程序 zip。 https://www.mediafire.com/file/4krl9e0trdxlcx3/game.zip/file

【讨论】:

  • 没问题。祝你的项目伙伴好运?
猜你喜欢
  • 2023-03-16
  • 2014-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多