0
所以我正在製作一個非常基本的Javascript遊戲。有一個用箭頭鍵控制的用戶球,屏幕上浮動着一個敵人的球。如何讓球在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>
你可以給出處理用戶輸入(按鍵)的代碼部分嗎? –
我做了,它在底部沒有? – Neilk
哎呀,對不起,我有麻煩加載頁面,沒關係! :) 這裏的想法是製作一個獨立的代碼塊,每隔X毫秒執行一次,以使敵方的球移動。 你可能想爲此使用'setInterval'。 –