簡體   English   中英

不確定為什么我的變量不起作用

[英]Not sure why my variables aren't working

我之前有變量“ ballX”和“ ballY”。 但是,當我嘗試使用console.log查看它們的值時,它們現在顯示為“未定義”,所以我必須弄亂了它們。 我花了2-3個小時的時間遍歷我的代碼並在線查找無濟於事的修復方法,我們將不勝感激。

 <html> <canvas id="gameCanvas" width = "600" height = "250"></canvas> <script> //Calling technical stuff var canvas; var canvasContext; canvas = document.getElementById('gameCanvas'); canvasContext = canvas.getContext('2d'); // Initial values var ballX = (canvas.width-20)/2; var ballY = (canvas.height-20)/2; var yDirection = 2; var xDirection = 2; var PositionY; var drawEverythingCount = 0; // Constants var ballSize = 20; var panelHeight = 100; var panelWidth = 10; window.onload = function(){ // Calls the main draw function and has the interval for repeating set to 10 ms setInterval(function() {drawEverything(PositionY)}, 10); } //Adds the event for mousemove to record the Y position of the mouse document.addEventListener("mousemove",function(event){ PositionY = (event.clientY-(panelHeight/2)); }); function drawEverything(PositionY) { drawEverythingCount = drawEverythingCount + 1; // Draws the canvas, ball and panel canvasContext.fillStyle = 'black'; canvasContext.fillRect(0,0,canvas.width,canvas.height); canvasContext.fillStyle = 'red'; canvasContext.fillRect(ballX,ballY,ballSize,ballSize); canvasContext.fillStyle = 'green'; canvasContext.fillRect(canvas.width-panelWidth,PositionY,panelWidth,panelHeight); // Resets the game if the ball goes out of the Right side of the canvas if (ballX > canvas.width) { alert('You scored:' + (xDirection - 2) + '!') var ballX = (canvas.width - 20)/2; var ballY = (canvas.height-20)/2; var yDirection = 2; var xDirection = 2; } // Checks to see if the ball is about to hit the left-hand wall if (ballX - xDirection < 0) {(xDirection = (xDirection*-1) + 1); ballX = 0;}; // Checks to see whether or not the ball is about to go off of the canvas' y-axis and changes its // direction if ((ballY+20) > canvas.height || ballY < 0){ if ((ballY+20) > canvas.height){yDirection = -1;} else {yDirection = 1;} } // Checks to see if the ball is hitting the panel if ((ballX + xDirection) > (canvas.width - 10)){ var y for (y = PositionY; y < (PositionY + 101);y++){ if(y == ballY) {xDirection = xDirection * -1;break;} }}; // Movement of the ball ballY = ballY + yDirection; ballX = ballX + xDirection; } </script> </html> 

if (ballX > canvas.width)語句中,您重新聲明了變量,這就是if (ballX > canvas.width)了。 這會將變量提升到函數drawEverything頂部,並drawEverything在頂部范圍中聲明的變量。 在您的情況下,它將被聲明為undefined

如果刪除變量前面的var關鍵字,則它將按預期工作,因為您將依賴於變量的全局狀態。

if (ballX > canvas.width) {
    alert('You scored:' + (xDirection - 2) + '!')
    ballX = (canvas.width - 20)/2;
    ballY = (canvas.height-20)/2;
    yDirection = 2;
    xDirection = 2; 

}

這是JavaScript提供的易於使用的全局狀態所固有的問題。 但是,您可以使用一些技巧來減輕將來的這些問題。 使用letconst關鍵字將在這里極大地幫助您。

這里的工作代碼

暫無
暫無

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

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