0
我在做一個Pong-like的遊戲,在這裏你控制兩個paddels以保持球彈跳的牆壁。
一切都非常好,直到我到了碰撞檢測點。碰撞檢測Javascript
我只得到它工作時槳有沒有從牆上的空間,但對於一個更好看我想保留他們和畫布邊界20像素之間的距離。
這裏是我的代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title> Pong Game </title>
<style>
* { padding: 0; margin: 10; }
canvas { background:#94ADEE ; display: block; margin: 0 auto; }
</style>
</head>
<body>
<canvas id="mainCanvas" width="800" height="600" />
<script>
var canvas = document.getElementById("mainCanvas");
var ctx = canvas.getContext("2d");
/* paddle */
var paddleHeight = 100;
var paddleWidth = 10;
var paddleY = (canvas.height-paddleHeight)/2;
/* paddle movement */
var upPressed = false;
var downPressed = false;
/* ball */
var ballRadius = 15;
var xBall = canvas.width/2;
var yBall = canvas.height/2;
/* ball movement */
var dxBall = 3.5;
var dyBall = 3.5;
var score = 0;
function drawBall(){
ctx.beginPath();
ctx.arc(xBall,yBall, ballRadius, 0,Math.PI*2);
ctx.fillStyle = "#2c3347";
ctx.fill();
ctx.closePath();
}
function drawPaddleOne(){
ctx.beginPath();
ctx.rect(0, paddleY,paddleWidth,paddleHeight);
ctx.fillStyle = "#2c3347"
ctx.fill();
ctx.closePath();
}
function drawPaddleTwo(){
ctx.beginPath();
ctx.rect(canvas.width-10,paddleY,paddleWidth,paddleHeight);
ctx.fillStyle = "#2c3347";
ctx.fill();
ctx.closePath();
}
function draw(){
ctx.clearRect(0,0, canvas.width, canvas.height);
drawPaddleOne();
drawPaddleTwo();
drawBall();
xBall += dxBall;
yBall += dyBall;
ctx.font = "20px Cursive";
ctx.textAlign = "center";
ctx.fillText("Score: " + score, canvas.width/2,canvas.height-550);
if(xBall + dxBall > canvas.width || xBall + dxBall < ballRadius){
if(yBall > paddleY && yBall < paddleY + paddleHeight){
dxBall = -dxBall;
score++;
if(dxBall < 0){
dxBall = dxBall - 0.5;
}
else {
dxBall = dxBall + 0.5;
}
if(dyBall < 0){
dyBall = dyBall - 0.5;
}
else {
dyBall = dyBall + 0.5;
}
}
else{
alert("GAME OVER! ");
document.location.reload();
}
}
if(yBall + dyBall > canvas.height || yBall + dyBall < ballRadius){
dyBall = -dyBall;
}
if(upPressed && paddleY > 0){
paddleY = paddleY - 5;
}
if(downPressed && paddleY < canvas.height-paddleHeight){
paddleY = paddleY + 5;
}
}
document.addEventListener("keydown", keyDownHandlerOne, false);
document.addEventListener("keyup", keyUpHandlerOne, false);
function keyDownHandlerOne (x){
if(x.keyCode == 38){
upPressed = true;
}
else if(x.keyCode == 40){
downPressed = true;
}
}
function keyUpHandlerOne (x){
if(x.keyCode == 38){
upPressed = false;
}
else if(x.keyCode == 40){
downPressed = false;
}
}
setInterval(draw, 10);
</script>
</body>
</html>
因爲撥片是固定的x軸的位置,我試圖與canvas.width
幫助檢查科裏森。 類似於xBall < canvas.width-10 && xBall > canvas.width-30
(右槳的示例)。 這是一個可行的方法?