首页 > 解决方案 > 如何在到达 mouseX 和 mouseY 后删除“子弹”精灵?[P5.播放]

问题描述

我正在使用 P5.Play 制作游戏,其中有 3 个方尖碑;一个在左边,一个在右边,一个在中间。我已经做到了,所以如果我的鼠标位置在画布的特定区域内,最近的方尖碑将朝我的鼠标位置射击。但是,我正在努力寻找一种方法来让精灵在到达我单击鼠标时的 x 和 y 点后爆炸。我不会发布我的完整代码,因为它是为了分配,但这里是一个片段。

function mousePressed() { 
    if (mouseX < width / 3) {
        bullet = createSprite(obelisks[0].position.x, obelisks[0].position.y - 60, 20, 20)
    } else if (mouseX > width / 3 && mouseX < width - width / 3) {
        bullet = createSprite(obelisks[1].position.x, obelisks[1].position.y - 60, 20, 20)
    } else {
        bullet = createSprite(obelisks[2].position.x, obelisks[2].position.y - 60, 20, 20)
    }

    // if bullet position is less than the distance between firing point and cursor position, then remove bullet??

    bullet.addImage(bulletSprite);
    bullet.attractionPoint(10, mouseX, mouseY);
    bullet.rotateToDirection = true;
}

标签: p5.js

解决方案


首先,感谢您向我介绍 p5.play!

这里有几件事要考虑,但你已经很接近了。通过阅读文档,对象上有一个函数,sprite称为overlapPoint(pointX, pointY)

检查给定点是否在精灵的碰撞器内。

这将返回一个布尔值。我们可以利用它来确定我们的子弹是否已经到达目的地。

首先,让我们在对象上定义destinationXdestinationY属性:

function mousePressed() {
  ...
  bullet = createSprite(width/2, height, 10, 10);
  let destinationX = mouseX;
  let destinationY = mouseY;
  
  bullet.attractionPoint(10, destinationX, destinationY);
  bullet.destinationX = destinationX;
  bullet.destinationY = destinationY;
}

现在,我们可以使用这些属性来确定我们是否达到了重叠点:

function draw() {
  background(220);
  drawSprite(obelisk);
  
  if (bullet) {
    drawSprite(bullet);
    if (bullet.overlapPoint(bullet.destinationX, bullet.destinationY)) {
      bullet.remove();
    }
  }
}

这是一个有效的简化示例:

let obelisk;
let bullet;

function setup() {
  createCanvas(400, 400);
  obelisk = createSprite(width/2, height, 50, 200);
}

function draw() {
  background(220);
  drawSprite(obelisk);
  
  if (bullet) {
    drawSprite(bullet);
    if (bullet.overlapPoint(bullet.destinationX, bullet.destinationY)) {
      bullet.remove();
    }
  }
}


function mousePressed() {
  bullet = createSprite(width/2, height, 10, 10);
  let destinationX = mouseX;
  let destinationY = mouseY;
  
  bullet.attractionPoint(10, destinationX, destinationY);
  bullet.destinationX = destinationX;
  bullet.destinationY = destinationY;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js"></script>
        <script src="https://cdn.jsdelivr.net/gh/molleindustria/p5.play/lib/p5.play.js"></script>

    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="utf-8" />

  </head>
  <body>
    <script src="sketch.js"></script>
  </body>
</html>

这是我创建的 p5.js 草图的链接,可进一步帮助您。

希望这会为您指明正确的方向。我可能还建议您创建一个子弹数组,例如:let bullets = []并在射击时添加到该数组中,这样可以防止在快速连续射击时删除子弹。或者您甚至可以查看 p5.play 的分组对象


推荐阅读