首页
学习
活动
专区
圈层
工具
发布

Rect冲突
EN

Stack Overflow用户
提问于 2021-04-30 10:01:36
回答 1查看 50关注 0票数 4

我正在用Javascript开发一个游戏,在这个游戏中我有一个玩家试图收集硬币。这两个函数目前都是不同维度的rects(),我正在尝试加入一个函数,当用户得到硬币时提醒他们。目前,这是我的播放器代码&硬币碰撞检测。

代码语言:javascript
复制
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;

    }

然而,当我循环我的coins数组并检查冲突时,什么也没有发生。为什么会这样呢?以下是与此相关的代码:

代码语言:javascript
复制
for (let x = 0; x < 5; x ++) { coins[x].collisions(); }

还有..。

代码语言:javascript
复制
collisions() {

        if (this.isTouching(player)) {

            alert("you got a coin!");

        }

    }

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

代码语言:javascript
复制
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库,并使用了下面的代码(如下所示)。但是,问题仍然存在,并且根本检测不到对象之间的碰撞。

新代码使用库:

代码语言:javascript
复制
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);
        
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-30 10:50:34

只需阅读所有代码即可。我能让硬币报警器正常工作,这是你需要改变的

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

代码语言:javascript
复制
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,并使用它。

代码语言:javascript
复制
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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67327270

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档