如何制作子弹动画? (射击游戏)
我正在尝试制作一款射击游戏,但我在子弹动画方面遇到了一些麻烦。每次我单击时,都会创建一个新的项目符号对象并开始动画,但每次单击后创建的项目符号都会消失,并且相同的项目符号会重新开始,这比以前的项目符号更快。所以我试图在每次点击后创建新的项目符号。基本的射击游戏逻辑。这是我的代码:
function newBullet(x,y,angle,speed,id,type) {
this.x = x;
this.y = y;
this.speed = speed;
this.angle = angle;
this.radians = this.angle * Math.PI / 180;
this.id = id;
this.type = type;
this.drawBullet = drawBullet;
this.moveBullet = moveBullet;
}
function moveBullet() {
this.x = this.x + Math.cos(this.radians) * this.speed ;
this.y = this.y + Math.sin(this.radians) * this.speed;
ctx.drawImage( bulletImg, this.x, this.y);
}
function drawBullet() {
bullet = new newBullet(playerX,playerY,getAngle(),2,1,1);
bullets[bullets.length] = bullet;
setInterval("bullets[bullets.length - 1].moveBullet()", 25);
}
canvas.addEventListener("mousedown",drawBullet,false);
I am trying to make a shooter game, but I have got some troubles with bullet animation. Each time I click, a new bullet object created and animation starts, but after each click the created bullet disappears and same bullet starts over again which is faster than previous bullet. So I am trying to create new bullet after each click. A basic shooter game logic. Here is my code:
function newBullet(x,y,angle,speed,id,type) {
this.x = x;
this.y = y;
this.speed = speed;
this.angle = angle;
this.radians = this.angle * Math.PI / 180;
this.id = id;
this.type = type;
this.drawBullet = drawBullet;
this.moveBullet = moveBullet;
}
function moveBullet() {
this.x = this.x + Math.cos(this.radians) * this.speed ;
this.y = this.y + Math.sin(this.radians) * this.speed;
ctx.drawImage( bulletImg, this.x, this.y);
}
function drawBullet() {
bullet = new newBullet(playerX,playerY,getAngle(),2,1,1);
bullets[bullets.length] = bullet;
setInterval("bullets[bullets.length - 1].moveBullet()", 25);
}
canvas.addEventListener("mousedown",drawBullet,false);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试在此处添加
var
:Try adding
var
here:如果您想向数组添加项目符号,您应该使用
push
。这将更新bullets.length
:您创建的子弹消失的原因:您每次都替换
bullets[0]
。新子弹比旧子弹更快,因为bullets[0].moveBullet
在每 25 毫秒间隔内被调用 n 次,其中 n 是您“创建”的子弹数量。If you want to add a bullet to an array you should use
push
. This will updatebullets.length
:The reason your created bullet disappeared: you replaced
bullets[0]
each time. And the new bullet was faster then the old one becausebullets[0].moveBullet
was called n-times in each 25ms interval, where n is the number of bullets you "created".