T
T
Triborg-3332019-07-12 17:58:35
JavaScript
Triborg-333, 2019-07-12 17:58:35

How to make a smooth movement of the tank?

Hello, programmers!) how to make a smooth movement of the tank in the game?)

spoiler
sU5gB54.png

window.addEventListener(`keydown`, (event) => {
const keyCode = event.keyCode || event.which;
switch(keyCode) {
case 40: {
thank_settings[i].y+= 35;
} break;
case 38: {
thank_settings[i].y-= 35;
} break;
case 37: {
thank_settings[i].x-= 35;
} break;
case 39: {
thank_settings[i].x+= 35;
} break;
}

});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2019-07-12
@Triborg-333

jsfiddle.net/loktar/dMYvG

spoiler
var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");

canvas.width = canvas.height = 300;

var x = 150,
    y = 150,
    velY = 0,
    velX = 0,
    speed = 2,
    friction = 0.98,
    keys = [];

function update() {
    requestAnimationFrame(update);
    
    if (keys[38]) {
        if (velY > -speed) {
            velY--;
        }
    }
    
    if (keys[40]) {
        if (velY < speed) {
            velY++;
        }
    }
    if (keys[39]) {
        if (velX < speed) {
            velX++;
        }
    }
    if (keys[37]) {
        if (velX > -speed) {
            velX--;
        }
    }

    velY *= friction;
    y += velY;
    velX *= friction;
    x += velX;

    if (x >= 295) {
        x = 295;
    } else if (x <= 5) {
        x = 5;
    }

    if (y > 295) {
        y = 295;
    } else if (y <= 5) {
        y = 5;
    }

    ctx.clearRect(0, 0, 300, 300);
    ctx.beginPath();
    ctx.arc(x, y, 5, 0, Math.PI * 2);
    ctx.fill();
}

update();

document.body.addEventListener("keydown", function (e) {
    keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function (e) {
    keys[e.keyCode] = false;
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question