簡體   English   中英

為什么我不能將變量 x 和 y 更改為 0? (x 和 y 是蛇頭坐標)

[英]Why can't I change the variables x and y to 0? (x and y are snake head coords)

當 x 和 y 到達 canvas 的末尾時,它們並沒有變為 0,而是繼續增加。 canvas 的大小為 300 x 300。當我將 x 和 y 的 position 更改為 1 之類的數字時,它正在改變。 我嘗試了很多東西,但它不起作用。 即使在 Chrome 控制台中將它們的值更改為 0,它們仍然保持不變。

let x = 150, y = 150;
/* main game loop */ {
    // ...
    if (x >= canvas.width) {
        x = 0;
    }
    if (x <= 0) {
        x = canvas.width;
    }
    if (y >= canvas.height) {
        y = 0;
    }
    if (y <= 0) {
        y = canvas.height;
    }
    // ...
}

你忘了使用else if 這應該解決它:

            if (x >= canvas.width) {
                x = 0;
            }
            else if (x <= 0) {
                x = canvas.width;
            }
            if (y >= canvas.height) {
                y = 0;
            }
            else if (y <= 0) {
                y = canvas.height;
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM