矩形碰撞

4

我正在用Javascript制作一个游戏,玩家试图收集硬币。当前,两者都是具有不同尺寸的rect(),我正在尝试加入一个函数,在玩家得到硬币时向用户发出提示。目前,这是我关于玩家与硬币碰撞检测的代码。

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

编程中的一项重要规则:不要重复造轮子。如果有适合您需求的库,请使用它。如果您将其用作学习经验,那也可以。为了避免我们浏览所有已存在的代码,请考虑提供一个 [MCVE],以演示问题。 - Jon P
抱歉,这是为了一个项目而进行的,我试图减少使用库的数量,这意味着我需要编写自己的函数。尽管如此,我尝试使用之前在另一个项目中有效的库(bmoren的p5collide2d),但也没有起作用。我已经编辑了原始帖子并包含了我的新代码。 - Bubbly
1个回答

4

我刚刚阅读了你的全部代码。我已经使得"coin alert"可以工作了,这是你需要更改的内容:

在game.engine.js文件中,修改setup函数。在这里,我已经更新了你的循环,问题是需要将金币的随机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
}

做了这两件事情后,应该就可以正常工作了。

我附上修改过的程序压缩包。 https://www.mediafire.com/file/4krl9e0trdxlcx3/game.zip/file


1
没有问题。祝你的项目顺利。 - Anshul Rasiwasia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接