我目前正在使用Javascript制作迷宫球赛。首先,我在画布上画一个迷宫图像。迷宫看起来像这样:
然后我有一个加速球(x,y参数使用navigator.accelerometer.watchAcceleration
函数,并使用RequestAnimationFrame
每33.3毫秒绘制一次。最难的部分是验证墙碰撞。
以下是代码:
function draw(){
switch(state)
{
case 'start' :
posX=150; //start pos of the ball
posY=30;
drawStart();
break;
case 'initgame' :
initGame();
break;
case 'game':
drawGame(); //draw the image canvas
update(acceleration);
break;
case 'end':
drawEnd();
break;
}
requestAnimationFrame(draw);
};
function update(acceleration){
animate(posX+(acceleration.x)*10, posY(acceleration.y)*10);
};
function checkCollision(x,y) {
var canvas=document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//get 5x5 pixels data of next position of the ball
var imgd = ctx.getImageData(x, y, 5,5);
var pix = imgd.data; //pix is 5x5x4=100 array length
for (var i = 0; n = pix.length, i < n; i += 4) {
if (pix[i] == 0) //first of every four arrays is "black(0,0,0,255)"
{
collision = 1;
break;
}
}
}
function animate(newX, newY){
var canvas=document.getElementById('canvas');
var context=canvas.getContext('2d');
drawGame(); //draw the image canvas
posX=newX;
posY=newY;
checkCollision(posX,posY);
if(collision==1)
{
//hit wall, need proper code
}
else{
//move freely
context.moveTo(posX,posY);
context.beginPath();
context.arc(posX, posY, 5, 0,2*Math.PI),false;
context.closePath();
context.fillStyle='green';
context.fill()
context.lineWidth=5;
context.strokeStyle='#003300';
context.stroke();
}
当球击中墙壁时我需要一个合适的代码。从逻辑上讲,例如,如果球击中垂直墙,并且球员加速x位置(向上和向下),球仍然会移动(向上或向下),但是y位置会粘在墙上。
我该怎么办?感谢您的帮助和关注!