【发布时间】:2015-10-17 14:57:47
【问题描述】:
这是我的html:
<html lang="en-US">
<head>
<meta charset ="UTF-8"/>
<title>Pong</title>
<link rel="stylesheet" type="text/css" href="pong.css"/>
</head>
<body>
<canvas id="mainCanvas" width="700" height="710"></canvas>
<script type="text/javascript" src="pong.js"></script>
</body>
</html>
这是我的 CSS:
#mainCanvas{
width: 700px;
height: 710px;
background-color: black;
}
这是我的 js:
//variables
var canvas = document.getElementById('mainCanvas');
var ctx = canvas.getContext('2d');
var keys = [];
var speed = 12,
playerWidth = 8,
playerHeight = 75,
canvasW = 700,
canvasH = 710,
player1X = canvasW - 670,
player2X = canvasW - 30,
ballS = 15,
running = true,
acc = 0,
ranNum = Math.floor(Math.random() * 10 + 1);
var requestAnimFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
//objects
function player(x,y,width,height){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
function gameObj(x,y,vel,side,speed){
this.x = x;
this.y = y;
this.side = side;
this.speed = speed;
}
var player1 = new player(player1X,canvasH/2-playerHeight/2,playerWidth,playerHeight);
var player2 = new player(player2X,canvasH/2-playerHeight/2,playerWidth,playerHeight);
var ball = new gameObj(canvasW/2-ballS/2,canvasH/2-ballS/2,ballS,15);
//Events
window.addEventListener("keydown", function(e){
keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e){
delete keys[e.keyCode];
}, false);
/*
keys
up-38
down-40
*/
//functions
function game(){
update();
render();
}
function update(){
if(keys[38])player1.y -=speed;
if(keys[40])player1.y +=speed;
if(keys[87])player2.y -=speed;
if(keys[83])player2.y +=speed;
if(player1.y <0) player1.y=0;
if(player1.y >= canvasH - player1.height) player1.y = canvasH - player1.height;
if(player2.y <0) player2.y=0;
if(player2.y >= canvasH - player2.height) player2.y = canvasH - player2.height;
console.log("player1.y: " + player1.y);
console.log("player2.y: " + player2.y);
}
function render(){
ctx.clearRect(0,0,canvasW,canvasH);
ctx.fillStyle="white";
ctx.fillRect(player1.x, player1.y, player1.width, player1.height);
ctx.fillStyle="white";
ctx.fillRect(player2.x, player2.y, player2.width, player2.height);
ctx.fillStyle="white";
ctx.fillRect(canvasW/2-3, 0, 3, canvasH);
ctx.fillStyle="white";
ctx.fillStyle="red";
ctx.fillRect(ball.x,ball.y,ball.side,ball.side);
}
function animate() {
if (running) {
game();
}
requestAnimFrame(animate);
}
animate();
我在乒乓球比赛中无法让球移动。我没有太多经验。我知道你可以做到ball.x += ball.speed,但我不确定如何让它在墙壁和桨上反弹。我试图做到这一点,所以当球与桨碰撞时,它等于它的 x 和 y 值,但随后球跟随桨。当我尝试通过使速度与碰撞速度相反来改变方向时,球在碰撞时只是保持静止。请帮忙。
欢迎任何帮助。
对不起,如果我的代码有点草率,我没有经过正式培训。
【问题讨论】:
-
也许把它放在 sn-p 中?编辑器左起第 7 个图标 :)
标签: javascript html css game-physics pong