简体   繁体   English

Javascript HTML5 Canvas子弹指向鼠标

[英]Javascript HTML5 Canvas bullets towards mouse

Im trying to make a game in Javascript to learn something new and so far i've figured out how to make the player sprite look at the mouse however I cant make the bullets work the same way, i've tried adding translate but it just bugs out. 我试图用Javascript开发游戏以学习新知识,到目前为止,我已经弄清楚了如何让玩家精灵看着鼠标,但是我无法使子弹以相同的方式工作,我尝试添加了笔译,但是它只是臭虫出来。 I would very much appreciate some help :) https://jsfiddle.net/x9heq7qa/ 我非常感谢您的帮助:) https://jsfiddle.net/x9heq7qa/

this.update = function(){
    for (var i = 0, len = playerBullets.length; i < len; i++) {
        if(playerBullets[i].x >= 400 || playerBullets[i].y >= 400){continue;}

        Context.context.rotate(playerBullets[i].angle);
        playerBullets[i].x += playerBullets[i].vel;
        Context.context.fillRect(playerBullets[i].x,playerBullets[i].y,4,1);
        Context.context.rotate(-playerBullets[i].angle);
    }
} 

Bullets fly in a strait line that goes from the initial point {x, y} of the bullet creation. 子弹以从子弹创建的初始点{x,y}开始的海峡线飞行。 So, the canvas should be rotated around the initial bullet point. 因此,画布应绕初始项目符号点旋转。 Bullet position can be described by another property: traveled distance. 子弹位置可以用另一个属性来描述:行进距离。

To rotate objects it is not needed to translate and rotate canvas back to initial state. 要旋转对象,不需要平移画布并将其旋转回初始状态。 It is possible to use Context.context.save(); 可以使用Context.context.save(); and then Context.context.restore(); 然后是Context.context.restore(); :

this.update = function(){
    for (var i = 0, len = playerBullets.length; i < len; i++) {
        // XXX: Check that bullet is out of canvas
        if(playerBullets[i].distance >= 600) {continue;}

        playerBullets[i].distance += playerBullets[i].vel;

        Context.context.save();
        Context.context.translate(playerBullets[i].x, playerBullets[i].y);
        Context.context.rotate(playerBullets[i].angle);
        Context.context.fillRect(playerBullets[i].distance,0,4,1);
        Context.context.restore();
    }
}

There is another bug. 还有另一个错误。 Mouse mouse handler is attached during drawing each frame. 绘制每个框架时,将附加鼠标处理程序。 So, number of attached mouse handlers continuously grow. 因此,附加的鼠标处理程序的数量持续增长。 The handler should be attached only once in the function ready() . 处理程序应仅在函数ready()附加一次。

Note that the sprite function rotate() does not really have to draw that sprite. 注意,精灵函数rotate()并不一定要绘制该精灵。 It is enough to store new angle. 足以存储新角度。 The sprite is refreshed by the frame animation handler animloop() . 通过帧动画处理程序animloop()刷新精灵。

Of course it makes sense to think about deletion of bullets that are already not active. 当然,考虑删除已经不活动的项目符号是有意义的。

Fixed runable example: https://jsfiddle.net/5cmn9s86/ 固定的可运行示例: https//jsfiddle.net/5cmn9s86/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM