I am trying to move a triangle in the direction which the triangle is rotated by. When I press the key to move it, it doesn't move, but when I rotate it, its center of rotation shifts because of the key I pressed to move it previously.
I tried checking the formulas to determine the direction to move the triangle, but those seemed correct, and the translation point to rotate it is not moving based on those formulas.
Expected results: On click of the up arrow key, triangle moves in rotation angle direction.
Actual results: On click of up arrow key, triangle doesn't move in the direction, but if I click up arrow key, then left or right arrow key to rotate, triangle rotates away from center of rotation.
Here's my code:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let ship_width = 20;
let ship_height = 20;
let angle = 0;
let ship_velocity_change = {
x: 0,
y: 0
}
//initial center coordinates of triangle
let ship_center = {
x: 450,
y: 300
};
let ship_points = [
//coordinates for vertices of triangle
{
x: ship_center.x - ship_width / 2,
y: ship_center.y +
ship_height / 2
},
{
x: ship_center.x + ship_width / 2,
y: ship_center.y +
ship_height / 2
},
{
x: ship_center.x,
y: ship_center.y - ship_height / 2
}
];
function drawRect(x, y, width, height, color) {
ctx.rect(x, y, width, height);
ctx.fillStyle = color;
ctx.fill();
}
//vertices for triangle as parameters
function drawTriangle(bottom_left, bottom_right, top, color) {
ctx.beginPath();
ctx.moveTo(top.x, top.y);
ctx.lineTo(bottom_left.x, bottom_left.y);
ctx.lineTo(bottom_right.x, bottom_right.y);
ctx.lineTo(top.x, top.y);
ctx.strokeStyle = color;
ctx.stroke();
}
//rotate triangle by an angle in degrees
function rotate(angle) {
ctx.translate(ship_center.x, ship_center.y);
ctx.rotate(Math.PI / 180 * angle);
ctx.translate(-ship_center.x, -ship_center.y);
drawTriangle(ship_points[2], ship_points[1], ship_points[0],
"white");
}
document.addEventListener('keydown', function(event) {
//rate of degree change per 10 milliseconds
if (event.keyCode === 37) {
angle = -2;
} else if (event.keyCode === 38) {
//move triangle by direction of angle
ship_center.x += Math.cos(Math.PI / 180 * angle) * 5;
ship_center.y += Math.sin(Math.PI / 180 * angle) * 5;
} else if (event.keyCode === 39) {
angle = 2;
}
});
document.addEventListener('keyup', function(event) {
if (event.keyCode === 37 || event.keyCode === 39) {
angle = 0;
}
});
function game() {
drawRect(0, 0, 900, 600, "black");
rotate(angle);
}
let gameLoop = setInterval(game, 10);
<canvas id="canvas" width="900" height="600"></canvas>