i'm new to Javascript and i want to built a game like Arkanoid(Breakout). I already got my paddle to move, and let my ball move towards the top of the field, but when it comes to the collision, it does not bounce of. i've already tried my best to solve the problem, but i guess there is a problem inside my if function.
I only want to use normal Javascript without the Element and JQuery.
function initGame() {
movePlayer();
moveBall();
};
function movePlayer() {
var player = document.getElementById("player")
var keyCodes = { left: 37, right: 39}
var keys = [];
window.addEventListener('keydown', function (event) {
keys[event.keyCode] = true;
});
window.addEventListener('keyup', function (event) {
keys[event.keyCode] = false;
});
setInterval(function (event) {
var x = parseInt(player.style.left);
if (keys[keyCodes.left]) {
x -= 1;
} else if (keys[keyCodes.right]) {
x += 1;
}
if (x >= 606) {
x = 606;
} else if ( x <= 2) {
x = 2;
}
player.style.left = x + 'px';
}, 1/100);
};
function moveBall() {
var ball = document.getElementById("ball");
setInterval(function() {
var x = parseInt(ball.style.left);
var y = parseInt(ball.style.top);
var playerx = parseInt(player.style.left);
var playery = parseInt(player.style.top);
ball.style.left = x + 'px';
ball.style.top = y + 'px';
x++;
y--;
ball.style.left = x+ 'px';
ball.style.top = y+ 'px';
if (x <= 0 && y >= 0 || x <= 0 && y <= 400) {
ball.style.left = x*(-1) + 'px';
ball.style.top = y* + 'px';
} else if (x >= 0 && y <= 0 || x <= 700 && y <= 0) {
ball.style.left = x + 'px';
ball.style.top = y*(-1) + 'px';
} else if (x >= 700 && y <= 400 || x >= 700 && y >= 0 ) {
ball.style.left = x*(-1) + 'px';
ball.style.top = y* + 'px';
}
}, 10);
};
<!doctype html>
<html>
<head>
<title>ARKAN0ID</title>
<style>
body {
background: lightgrey;
}
#field {
width: 700px;
height: 400px;
border: 1px solid grey;
border-radius: 10px;
margin: 30px auto auto auto;
background: #eee;
}
#player {
position: relative;
width: 90px;
height: 15px;
top: 350px;
border: 1px solid black;
border-radius: 25px;
background: black;
}
#ball {
position: relative;
width: 20px;
height: 20px;
border-radius: 25px;
background: red;
}
</style>
<script type="text/javascript" src="arkanoid.js"></script>
</head>
<body onload="initGame()">
<div id="field">
<div id="player" style="left: 305px;"></div>
<div id="ball" style="left: 340px; top: 200px;"></div>
</div>
</body>
</html>
Aucun commentaire:
Enregistrer un commentaire