I have 2 balls in game enemy and Player whenever i want to change coordinates i clear player rect but for some reasons enemy disappears. Does anyone have some tips what to do? maybe it's because i'm doing wrong making functions moveleft moveright.if you also see something bad with code please provide tips.
var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
var Player1 = {
x: 150,
y: 70,
velX: 20,
velY: 12,
hp: 20,
startAngle: 40,
};
var Enemy = {
x: 200,
y: 150,
velX: 12,
velY: 12,
hp: 20,
startAngle: 40,
};
function drawPlayer1() {
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(Player1.x, Player1.y, Player1.startAngle, 0, 2 * Math.PI);
ctx.fill();
}
function drawEnemy() {
ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(Enemy.x, Enemy.y, Enemy.startAngle, 0, 2 * Math.PI);
ctx.fill();
}
function move(event) {
// the event.keyCode is Deprecated, use event.code or event.key
if (event.keyCode == '39' || event.key === ' ') {
if (Player1.x < c.width - Player1.startAngle) {
updatePositionRight();
}
}
if (event.keyCode == '37' || event.key == ' ') {
if (Player1.x > 0 + Player1.startAngle) {
updatePositionLeft();
}
}
if (event.keyCode == '38' || event.key == ' ') {
if (Player1.y > 0 + Player1.startAngle) {
updatePositionUp();
}
}
if (event.keyCode == '40' || event.key == ' ') {
if (Player1.y < c.height - Player1.startAngle) {
updatePositionDown();
}
}
}
function updatePositionRight() {
// update Player1's property
Player1.x += Player1.velX;
// erase the canva
ctx.clearRect(0, 0, c.width, c.height);
// redraw Player1
drawPlayer1();
}
function updatePositionLeft() {
// update Player1's property
Player1.x -= Player1.velX;
// erase the canvas
ctx.clearRect(0, 0, c.width, c.height);
// redraw Player1
drawPlayer1();
}
function updatePositionDown() {
// update Player1's property
Player1.y += Player1.velY;
// erase the canvas
ctx.clearRect(0, 0, c.width, c.height);
// redraw Player1
drawPlayer1();
}
function updatePositionUp() {
// update Player1's property
Player1.y -= Player1.velY;
// erase the canvas
ctx.clearRect(0, 0, c.width, c.height);
// redraw Player1
drawPlayer1();
}
// bind event
window.addEventListener('keydown', move, false);
// initialize
function drawEntities() {
drawPlayer1();
drawEnemy();
}
drawEntities();
<canvas id="myCanvas" width="600" height="600" style="border:1px solid black"></canvas>