我想用Sublime創建一個使用HTML和Javascript的遊戲。 但是我試圖創建一個嵌套的數組與Javascript,但後來我運行的代碼,它不適用於瀏覽器。數組「圈子」應該包含「球」(如果你刪除這條線,遊戲只包含一個球並且它有效)。在javascript中創建嵌套數組
這是遊戲的代碼:
<!DOCTYPE html>
<html>
<head>
<title>Canvas Tutorial</title>
<script type="text/javascript">
window.onload = draw;
x = 200;
y = 150;
r = 40;
direction = 1;
speedX = 1;
speedY = 2;
var circles = [{x:200,y:150,r:40,d:1,speedX=1,speedY=2},{x:200,y:150,r:40,d:1,speedX=1,speedY=2}];
function bottomRight() {
x += speedX;
y += speedY;
}
function upLeft() {
x -= speedX;
y -= speedY;
}
function upRight() {
x += speedX;
y -= speedY;
}
function bottomLeft() {
x -= speedX;
y += speedY;
}
function draw() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "black";
ctx.fillRect(0,0,400,300);
ctx.fillStyle = "yellow";
ctx.beginPath();
ctx.arc(x,y,r,0,Math.PI*2,false);
ctx.fill();
if((y > 300 - r) && direction ===1){
direction = 2;
} else if((x > 400 - r) && (direction===2)) {
direction = 3;
} else if ((y > 300 - r) && (direction===4)) {
direction = 3;
} else if ((y <= r) && direction === 3) {
direction = 4;
} else if ((x < r) && direction === 4){
direction = 1;
} else if ((y < r) && direction === 2) {
direction = 1;
}
if (direction === 1) {
bottomRight();
} else if (direction === 2) {
upRight();
} else if (direction === 3) {
upLeft();
} else {
bottomLeft();
}
}
setInterval(draw, 10);
</script>
</head>
<body>
<canvas id="canvas" width="400" height="300"></canvas>
</body>
</html>
我怎樣才能修復代碼?
聽衆有點適得其反。可以使用'window.addEventListener(「load」,function(){draw(); setInterval(draw,10);});'或者將'setTimeout(draw,10);'''draw'內部並去掉間隔。 – Xufox
我看不出在代碼中如何使用'circles'。你能澄清嗎? –