Canvas 对象沿对角线移动,而不是垂直移动

Canvas Object moving diagonally, not vertically

为了学校,我需要做一个游戏,所以我有了做一个类似于“租用魔法 touch:wizard”的游戏的想法,这是一个气球从天上掉下来的游戏,而且你需要画图来弹出它们,这就是我想要的想法。

但是现在,我的问题是: 我的想法是让气球在 x 轴上随机出现(因此它总是会在 y=0 处生成并且 x 轴是随机的),但这就是我的问题所在。我为它做了树函数: 这是创建随机数的函数:

function aleatorizar() {
let random= Math.floor(Math.random()*canvas.width);
return random;
}

这是绘制带有文本的气球的函数:

function desenharbombas(x){
ctx.beginPath();
ctx.arc(x,posição,50,0,2*Math.PI);
ctx.stroke();
ctx.fillStyle= "#000000";
ctx.fill();
function escrever(){
    ctx.font="17px Arial Black";
    ctx.fillStyle="#ffffff";
    ctx.fillText("texto",x,posição );
}
escrever()
}

这是制作气球落下动画的函数:

function animar(y){
ctx.clearRect(0,0,canvas.width,canvas.height);
posição=posição+1;
desenharbombas(y)
requestAnimationFrame(animar);
}

在我的逻辑中(以及经过数小时的测试),我不能将随机函数放入我的炸弹绘图函数中,因为它会使随机函数在每次调用绘图函数时发生变化,这样会使炸弹在屏幕上左右闪烁。

所以我创建了这个逻辑,当调用 animate 函数时,炸弹绘图函数只会收到一个随机数,但它不起作用,因为现在炸弹是斜着落的。我知道这真的很难理解,但如果有人知道如何提供帮助或想跳上 discord 来帮助我...(caue#7600)

这样的事情怎么样:

const canvas = document.getElementById("c");
const ctx = canvas.getContext("2d");
ctx.textAlign = 'center';
ctx.textBaseline = 'middle'
var bombas = []

class bomba {
  constructor(name, x, y, speed, radius) {
    this.name = name
    this.x = x
    this.y = y
    this.speed = speed
    this.radius = radius
  }
  draw() {
    ctx.beginPath();
    ctx.arc(this.x += this.speed, this.y, this.radius, 0, 2 * Math.PI);
    ctx.stroke();
    ctx.fillText(this.name, this.x, this.y);
  }
}

function aleatorizar() {
  return Math.floor(Math.random() * canvas.width);
}

bombas.push(new bomba("A", aleatorizar()/4, 10, 0.20, 8))
bombas.push(new bomba("B", aleatorizar()/4, 40, 0.25, 12))
bombas.push(new bomba("C", aleatorizar()/4, 70, 0.15, 10))

function animar() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  bombas.forEach(b => b.draw())
  requestAnimationFrame(animar);
}
animar()
<canvas id="c"></canvas>

你可以看到我们有一个 class bomba 并且在构造函数上我们传递了绘制我们需要的所有初始参数,然后在 draw() 函数中我们增加了 x 的值以给定的速度,绘制圆弧和文字。

有了这个新的 class 你可以添加更多的随机参数,现在只是 Y 是随机的,但你可以用同样的方法来增加速度和半径


如果你真的想制作游戏,你应该看看游戏引擎,有很多好的开源,github 有一个很好的知名集合:
https://github.com/collections/javascript-game-engines
随着您的游戏变得越来越复杂,您将 运行 解决游戏引擎中已经解决的问题,这仅取决于您希望在这款游戏中走多远