javascript - 我的射弹系统不工作,它有什么问题,我该如何解决?

标签 javascript canvas draw projectile

我正在制作一个小行星射击系统,它可以向玩家面向的方向发射射弹,但是,当您射击(按空格键)时,射弹不会移动。

我曾尝试将余弦和正弦添加到 X 和 Y,但这显然行不通。我尝试添加打印语句以查看哪里出错了,看起来 X 和 Y 根本没有递增。我怎样才能使它正确且准确地按照我想要的方式递增?

circle.x += Math.cos(circle.direction) * circle.speed;
circle.y += Math.sin(circle.direction) * circle.speed;

完整代码:

const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var projectileArray = []
var keydown = false
const gamePlaying = true

const kbd = {
  ArrowLeft: false,
  ArrowUp: false,
  ArrowRight: false,
  ArrowDown: false,
};

const noHoldDown = {
  Space: false,
}

const ship = {
  angle: 0,
  color: "white",
  x: canvas.width / 2,
  y: canvas.height / 2,
  width: 10,
  height: 12,
  drag: 0.9,
  accSpeed: 0.025,
  rotSpeed: 0.007,
  rotv: 0,
  ax: 0,
  ay: 0,
  vx: 0,
  vy: 0,
  rotateLeft() {
    this.rotv -= this.rotSpeed;
  },
  rotateRight() {
    this.rotv += this.rotSpeed;
  },
  accelerate() {
    this.ax += this.accSpeed;
    this.ay += this.accSpeed;
  },
  decelerate() {
    this.ax -= this.accSpeed;
    this.ay -= this.accSpeed;
  },
  shoot() {
    projectileArray.push([this.x, this.y, this.angle])
  },
  move() {
    this.angle += this.rotv;
    this.rotv *= this.drag;
    this.vx += this.ax;
    this.vy += this.ay;
    this.ax *= this.drag;
    this.ay *= this.drag;
    this.vx *= this.drag;
    this.vy *= this.drag;
    this.x += Math.cos(this.angle) * this.vx;
    this.y += Math.sin(this.angle) * this.vy;
  },
  draw(ctx) {
    ctx.save();
    ctx.lineWidth = 3;
    ctx.translate(this.x, this.y);
    ctx.rotate(this.angle);
    ctx.beginPath();
    ctx.moveTo(this.height, 0);
    ctx.lineTo(-this.height, this.width);
    ctx.lineTo(-this.height, -this.width);
    ctx.closePath();
    ctx.strokeStyle = this.color;
    ctx.stroke();
    ctx.restore();
  }
};

document.addEventListener("keydown", event => {
  if (event.code in kbd) {
    event.preventDefault();
    kbd[event.code] = true;
  }
});
document.addEventListener("keydown", event => {
  if (event.code in noHoldDown) {
    if (!keydown) {
      keydown = true;
      ship.shoot();
    }
  }
});

document.addEventListener('keyup', event => {
  if (event.code in noHoldDown) {
    keydown = false;
  }
});

document.addEventListener("keyup", event => {
  if (event.code in kbd) {
    event.preventDefault();
    kbd[event.code] = false;
  }
});

(function update() {
  ctx.fillStyle = "black";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  const shipActions = {
    ArrowLeft: "rotateLeft",
    ArrowUp: "accelerate",
    ArrowDown: "decelerate",
    ArrowRight: "rotateRight",
  };

  for (const key in shipActions) {
    if (kbd[key]) {
      ship[shipActions[key]]();
    }
  }
  ship.move();
  ship.draw(ctx);
  for (var i = 0; i < projectileArray.length; i++) {
    function MovableCircle() {
      this.x = projectileArray[i][0];
      this.y = projectileArray[i][1];
      this.speed = 1;
      this.direction = projectileArray[i][1];

      this.draw = () => {
        ctx.arc(this.x, this.y, 3.75, 0, 2 * Math.PI);
        ctx.fillStyle = 'white';
        ctx.fill();
      }
    }
    var circle = new MovableCircle();
    ctx.beginPath();
    circle.x += Math.cos(circle.direction) * circle.speed;
    circle.y += Math.sin(circle.direction) * circle.speed;
    circle.draw();
    console.log(circle.x, circle.y)
  }
  requestAnimationFrame(update);
})();

最佳答案

我在 Asteroids 中投入了这么多季度,我在这里做出了贡献!问题源于抛射物的持久性:在 update 循环的每一轮重建它们会忘记先前迭代中所做的任何状态更改。

弹射物应该是一流的物体,由游戏或飞船持有。下面是对 OP 原本不错的脚本的两个更改:

  1. 一个 Projectile 类,主要使用 OP 代码:
function Projectile(x,y,speed,direction,duration) {
  Object.assign(this, {x,y,speed,direction,duration});
  this.draw = ctx => {
    ctx.arc(this.x, this.y, 3.75, 0, 2 * Math.PI);
    ctx.fillStyle = 'white';
    ctx.fill();
  }
  this.update = ctx => {
    ctx.beginPath();
    this.x += Math.cos(this.direction) * this.speed;
    this.y += Math.sin(this.direction) * this.speed;
    this.draw(ctx);
    this.duration--;
  }
  this.isDone = () => this.duration <= 0;
}

在功能上,我唯一添加的是一个持续时间,因为我想我记得在原著中没有击中任何东西的射弹最终会消失。

  1. 由于飞船已经有一个射弹阵列,在这里,它被修改为容纳射弹实例:

shoot 方法更改为

  shoot() {
    let mySpeed = Math.sqrt(this.vx*this.vx + this.vy*this.vy)
    let bullet = new Projectile(this.x, this.y, 1+mySpeed, this.angle, 500);
    projectileArray.push(bullet);
  },

旁注:我想,在原版游戏中,炮弹的速度被固定为大于船的最高速度,但我记不太清了。在上面,我将射弹速度设置为 +1,比飞船的当前速度 高。这在物理上更正确(在亚相对论速度下 :-)),但可能不准确。

并且 draw 方法进行了显着清理,因为我们将状态遗忘射弹代码移到了它自己的类中

  ship.draw(ctx);
  for (var i = 0; i < projectileArray.length; i++) {
    let bullet = projectileArray[i];
    bullet.update(ctx)
  }
  projectileArray = projectileArray.filter(bullet => !bullet.isDone());

旁注:从 ES5/ES6 开始的 Javascript 类在语法上有了很大的改进。值得熟悉这一点。

演示

const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var projectileArray = []
var keydown = false
const gamePlaying = true

const kbd = {
  ArrowLeft: false, 
  ArrowUp: false, 
  ArrowRight: false,
  ArrowDown: false,
};

const noHoldDown = {
  Space: false,
}

function Projectile(x,y,speed,direction,duration) {
  Object.assign(this, {x,y,speed,direction,duration});
  this.draw = ctx => {
    ctx.arc(this.x, this.y, 3.75, 0, 2 * Math.PI);
    ctx.fillStyle = 'white';
    ctx.fill();
  }
  this.update = ctx => {
    ctx.beginPath();
    this.x += Math.cos(this.direction) * this.speed;
    this.y += Math.sin(this.direction) * this.speed;
    this.draw(ctx);
    this.duration--;
  }
  this.isDone = () => this.duration <= 0;
}


const ship = {
  angle: 0,
  color: "white",
  x: canvas.width / 2,
  y: canvas.height / 2,
  width: 10,
  height: 12,
  drag: 0.9,
  accSpeed: 0.025,
  rotSpeed: 0.007,
  rotv: 0,
  ax: 0,
  ay: 0,
  vx: 0,
  vy: 0,
  rotateLeft() {
    this.rotv -= this.rotSpeed;
  },
  rotateRight() {
    this.rotv += this.rotSpeed;
  },
  accelerate() {
    this.ax += this.accSpeed;
    this.ay += this.accSpeed;
  },
  decelerate() {
    this.ax -= this.accSpeed;
    this.ay -= this.accSpeed;
  },
  shoot() {
    let mySpeed = Math.sqrt(this.vx*this.vx + this.vy*this.vy)
    let bullet = new Projectile(this.x, this.y, 3+mySpeed, this.angle, 500)
    projectileArray.push(bullet);
    // projectileArray.push([this.x, this.y, this.angle])
  },
  move() {
    this.angle += this.rotv;
    this.rotv *= this.drag;
    this.vx += this.ax;
    this.vy += this.ay;
    this.ax *= this.drag;
    this.ay *= this.drag;
    this.vx *= this.drag;
    this.vy *= this.drag;
    this.x += Math.cos(this.angle) * this.vx;
    this.y += Math.sin(this.angle) * this.vy;
  },
  draw(ctx) {
    ctx.save();
    ctx.lineWidth = 3;
    ctx.translate(this.x, this.y);
    ctx.rotate(this.angle);
    ctx.beginPath();
    ctx.moveTo(this.height, 0);
    ctx.lineTo(-this.height, this.width);
    ctx.lineTo(-this.height, -this.width);
    ctx.closePath();
    ctx.strokeStyle = this.color;
    ctx.stroke();
    ctx.restore();
  }
};

document.addEventListener("keydown", event => {
  if (event.code in kbd) {
    event.preventDefault();
    kbd[event.code] = true;
  }
});
document.addEventListener("keydown", event => {
  if (event.code in noHoldDown) {
    if (!keydown) {
      keydown = true;
      ship.shoot();
    }
  }
});

document.addEventListener('keyup', event => {
  if (event.code in noHoldDown) {
    keydown = false;
  }
});

document.addEventListener("keyup", event => {
  if (event.code in kbd) {
    event.preventDefault();
    kbd[event.code] = false; 
  }
});

(function update() {
  ctx.fillStyle = "black";
  ctx.fillRect(0, 0, canvas.width, canvas.height);  

  const shipActions = {
    ArrowLeft: "rotateLeft",
    ArrowUp: "accelerate",
    ArrowDown: "decelerate",
    ArrowRight: "rotateRight",
  };

  for (const key in shipActions) {
    if (kbd[key]) {
      ship[shipActions[key]]();
    }
  }
  ship.move();
  ship.draw(ctx);
  for (var i = 0; i < projectileArray.length; i++) {
    let bullet = projectileArray[i];
    bullet.update(ctx)
  }
  projectileArray = projectileArray.filter(bullet => !bullet.isDone());
  requestAnimationFrame(update);
})();

关于javascript - 我的射弹系统不工作,它有什么问题,我该如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73515642/

相关文章:

javascript - 在javascript中反向按位移位

javascript - 循环 JSON 对象并绘图到 map

javascript - FabricJS Canvas drawImage 不显示图像

javascript - ESRI API 中的toolbar.deactivate() 出现问题

javascript - 我可以将 javascript 绘制函数更改为图像吗?

java 从点数组列表中绘制折线

javascript - 如果用户导航到其他路线, Electron reactjs 应用程序在重新加载后显示空页面

javascript - 如何使用 jQuery 对动态生成的 SELECT 元素中的数据进行排序?

Javascript 绘制 Canvas 内存泄漏

canvas - 在 Canvas 上进行交互式控件的能力