I have this function to get the rotation angle from my sprite and a target:

getAngle( spr:Sprite, x:number, y:number ):number
    let vx:number = x - ( spr.getX() + spr.w / 2 );
    let vy:number = y - ( spr.getY() + spr.h / 2 );
    let angle = Math.atan2( vy, vx ) * (180 / Math.PI);
    return angle;

Basically this is:

target.x - sprite.centerX;

target.y - sprite.centerY;

Then i use atan2 and multiply by radians. The way I use that angle is:

ctx.translate( this.getX() + centerX, this.getY() + centerY );
ctx.rotate( this.angle );
ctx.scale( this.xScale, this.yScale );
ctx.translate( - ( this.getX() + centerX ), -( this.getY() + centerY ) );

However, the above is not working. I have been investigating this and it seems to be okay, but it still does not work for me. Any ideas?


after i posted the question i was looking a little deeper, the code seems to work fine, however works if the canvas element has a position of x:0 & y:0, so if is in a different place like mine which is centered and has margings/paddings then the coordinates of the canvas are different. to fix this i had to correct mouseMove.clientX & mouseMove.clientY values not passing them directly:

        let boundingRect = canvas.getBoundingClientRect();
        let eX = event.clientX - boundingRect.left;
        let eY = event.clientY - boundingRect.top;
        this.arrowShooter.angle =getAngle(this.arrowShooter, eX, eY);

so substracting left and top from canvas.getBoundingClientRect() to event.clientX/Y fixed mouse canvas coordinates.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.