TransWikia.com

Rotating and moving object (follow into mouse) - Javascript

Stack Overflow Asked by Karlos Margaritos on January 8, 2021

everybody!

I want to make a small tank that will follow the mouse and turn its cannon towards the mouse.

I made a deal following the mouse, but there is no way I can turn the gun towards the mouse.
My code:

// canvas variable
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

// browser window size
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;

//set canvas size
canvas.width = windowWidth;
canvas.height = windowHeight;

var mouseX = 0;
var mouseY = 0;
var baseAngle = 1;

class Cannon {
    constructor(x,y, angle, size, speed){
        this.x = x;
        this.y = y;
        this.angle = angle;
        this.size = size;
        this.speed = speed;
    }

    draw() {
        // bullet
        ctx.setTransform(1, 0, 0, 1, this.x, this.y - (this.size/2));
        ctx.translate(this.x, this.y);
        ctx.rotate(baseAngle);
        
        ctx.beginPath();
        ctx.rect(this.x, this.y - (this.size/2), this.size*2, this.size);
        ctx.fillStyle = 'rgb(192,192,192)';
        ctx.fill();
        ctx.lineWidth = 3;
        ctx.strokeStyle = 'rgba(128,128,128)';
        ctx.stroke();
        ctx.closePath();

        //body
        
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
        ctx.fillStyle = 'rgb(0,96,255)';
        ctx.fill();
        ctx.lineWidth = 3;
        ctx.strokeStyle = 'rgba(128,128,128)';
        ctx.stroke();
        ctx.closePath();
    }

    update() {
        // mooving
        var dx = (mouseX - this.x)*.125;
        var dy = (mouseY - this.y)*.125;

        var dist = Math.sqrt(dx*dx + dy*dy);

        if(dist > this.speed){
            dx *= this.speed / dist;
            dy *= this.speed / dist;    
        }

        this.x += dx;
        this.y += dy;

        // rootating

        baseAngle = Math.atan2(mouseY - this.y, mouseX - this.x);
    }
}

const newCannon = new Cannon(80,60, 1, 20, 7);
onmousemove = function(e){
    mouseX = e.clientX;
    mouseY = e.clientY;
}


function gameUpdate() {
    ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    newCannon.draw();
    newCannon.update();
    requestAnimationFrame(gameUpdate);
}
gameUpdate();
<!DOCTYPE html>
<html>
<head>
    <title>CRUSH DEMO</title>
</head>
<body>


<canvas id="canvas"></canvas>

</body>
</html>

The cannon must be rotated in the direction of the mouse (the circle itself must not be rotated).

help me please fix the code!

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP