所以我正在制作一个非常基本的Javascript游戏。有一个用箭头键控制的用户球,屏幕周围有敌人的球。
然而,我遇到了一个问题。当我用箭头键移动自己的球时,敌人的球只会移动。因此,如果我没有按下任何东西,那么敌人的球只会坐在那里并且也不会移动。
以下是我的javascript代码。所以基本上我希望敌球在它自己的画布上移动。非常感谢提前!
<script type="text/javascript">
// Gets a handle to the element with id gameCanvas.
var canvas = document.getElementById("gameCanvas");
// Get a 2D context for the canvas.
var ctx = canvas.getContext("2d");
var userBall = {
x: canvas.width / 2
, y: canvas.height / 2
, r: 13
}
var enemyBall1 = { // Create object for enball1
x: canvas.width / 5,
y: canvas.height / 5,
radius: 8 , // Set radius of ball to 12
acceleration: { // Determines ball acceleration
x: 5,
y: 3
}
} // End ball1
function drawCircle() {
ctx.fillStyle = "rgb(255, 255, 0)"; // Color
ctx.beginPath();
ctx.arc(userBall.x, userBall.y, userBall.r, 0, 2 * Math.PI);
ctx.fill();
}
function drawEnemyBall1() {
ctx.fillStyle = "rgb(255, 25, 100)"; // Color
ctx.beginPath(); // Begin path
ctx.arc(enemyBall1.x, enemyBall1.y, enemyBall1.radius, 0, 2 * Math.PI);
ctx.fill(); // Fills ball
enemyBall1.x += enemyBall1.acceleration.x; // Update y location
enemyBall1.y += enemyBall1.acceleration.y;
// Keep animation going while ball1 hasn't hit the canvas
if ((enemyBall1.x >= canvas.width - enemyBall1.radius) || (enemyBall1.x <= enemyBall1.radius))
enemyBall1.acceleration.x =- enemyBall1.acceleration.x;
if ((enemyBall1.y >= canvas.height - enemyBall1.radius) || (enemyBall1.y <= enemyBall1.radius))
enemyBall1.acceleration.y =- enemyBall1.acceleration.y;
} // End function drawball
drawCircle(); // call function
drawEnemyBall1();
function repeatme() {
// clears the screan/canvas i.e. where the ball was previously does not show up.
ctx.clearRect(0, 0, canvas.width, canvas.height);
// calls the enemyBall function
drawEnemyBall1();
//calls the userBall function
drawCircle();
// gets the animation going
window.requestAnimationFrame(repeatme);
}
// Add an event listener to the keypress event.
window.addEventListener("keydown", function(event) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (event.keyCode == 39 && userBall.x < canvas.width - userBall.r)
userBall.x += Math.min(10, canvas.width - userBall.x - userBall.r);
else if (event.keyCode == 37 && userBall.x > userBall.r)
userBall.x -= 10;
else if (event.keyCode == 40 && userBall.y < canvas.height - userBall.r)
userBall.y += 10;
else if (event.keyCode == 38 && userBall.y > userBall.r)
userBall.y -= 10;
drawCircle(); // call function
drawEnemyBall1();
});
</script>
答案 0 :(得分:0)
您在底部缺少一行代码,再次调用requestAnimation。
window.requestAnimationFrame(repeatme);
在</script>
之前添加此行,它应该有效。