简体   繁体   中英

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. I would very much appreciate some help :) 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. 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(); and then 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() .

Note that the sprite function rotate() does not really have to draw that sprite. It is enough to store new angle. The sprite is refreshed by the frame animation handler animloop() .

Of course it makes sense to think about deletion of bullets that are already not active.

Fixed runable example: https://jsfiddle.net/5cmn9s86/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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