-1
我的代碼給出了600 * 800尺寸的黑盒輸出,沒有其他顯示。使用Javascript編碼pong遊戲時不顯示
我試圖編寫一個基本乒乓球比賽的匿名函數調用update()函數週期性它調用復位()相應
<canvas id = "gc" width = "640" height = "480"> </canvas>
<script>
userPlankYPosition =40;
computerPlankYPosition = 40;
plankWidth = 10;
plankHeight =100;
ballPositionX=ballPositionY=50;
ballDimension =6;
XVelocity=YVelocity=4;
playerScore=ComputerScore=0;
computerPlankSpeedinY=4;
var canvas,canvasContext;
window.onload=function() {
canvas=document.getElementById('gc');
canvasContext=canvas.getContext('2d');
setInterval(update, 1000/30);
canvas.addEventListener('mousemove',function(e){
userPlankYPosition = e.clientY-plankHeight/2;
});
};
function reset(){
ballPositionX=canvas.width/2;
ballPositionY=canvas.height/2;
XVelocity-=XVelocity;
YVelocity=3;
};
function update(){
canvasContext.fillstyle='black';
canvasContext.fillRect(0,0,canvas.width,canvas.height);
canvasContext.fillstyle='white';
canvasContext.fillRect(0,userPlankYPosition,plankWidth,plankHeight);
canvasContext.fillRect(canvas.width-plankWidth,computerPlankYPosition,plankWidth,plankHeight);
canvasContext.fillRect(ballPositionX-ballDimension/2,ballPositionY-ballDimension/2,ballDimension,ballDimension);
canvasContext.fillText(playerScore,100,100);
canvasContext.fillText(ComputerScore,canvas.width-100,100);
ballPositionX+=XVelocity;
ballPositionY+=YVelocity;
if(ballPositionY<0 && YVelocity <0){
YVelocity-=YVelocity;
}
if(ballPositionY>canvas.height && YVelocity <0){
YVelocity-=YVelocity;
}
if(ballPositionX<0)
{
if(ballPositionY>userPlankYPosition && ballPositionY<userPlankYPosition+plankHeight){
XVelocity-=XVelocity;
dy=ballPositionY-(userPlankYPosition+plankHeight/2);
YVelocity = dy*0.3;
}
else{
ComputerScore++;
reset();
}
}
if(ballPositionX>canvas.width)
{
if(ballPositionY>computerPlankYPosition && ballPositionY<computerPlankYPosition+plankHeight){
XVelocity-=XVelocity;
dy=ballPositionY-(computerPlankYPosition+plankHeight/2);
YVelocity = dy*0.3;
}
else{
playerScore++;
reset();
}
};
if(computerPlankYPosition+plankHeight/2<ballPositionY){
computerPlankYPosition+=computerPlankSpeedinY;
}
else{
computerPlankYPosition-=computerPlankSpeedinY;
}
// canvasContext.fillstyle='black';
// canvasContext.fillRect(0,0,canvas.width,canvas.height);
// canvasContext.fillstyle='white';
// canvasContext.fillRect(0,userPlankYPosition,plankWidth,plankHeight);
// canvasContext.fillRect(canvas.width-plankWidth,computerPlankYPosition,plankWidth,plankHeight);
// canvasContext.fillRect(ballPositionX-ballDimension/2,ballPositionY-ballDimension/2,ballDimension,ballDimension);
// canvasContext.fillText(playerScore,100,100);
// canvasContext.fillText(ComputerScore,canvas.width-100,100);
};
並且輸出是:output
您應該使用有意義的變量名稱。這是痛苦的閱讀... – Badacadabra
好的,我應該編輯代碼和帖子? –
我這麼認爲。如果我們無法理解您的代碼在做什麼,那麼很難爲您提供幫助。 – Badacadabra