第四回主要讲熊移动碰到边界时的反弹处理
预期达到效果:http://www.html5china.com/html5games/mogu/index3.html
一、写一个碰撞处理函数
JavaScript Code复制内容到剪贴板
function HasAnimalHitEdge()
{
//熊碰到右边边界
if(animal.x>screenWidth - animal.image.width)
{
if(horizontalSpeed > 0)//假如向右移动
horizontalSpeed =-horizontalSpeed;//改变水平速度方向
}
//熊碰到左边边界
if(animal.x<-10)
{
if(horizontalSpeed < 0)//假如向左移动
horizontalSpeed = -horizontalSpeed;//改变水平速度方向
}
//熊碰到下面边界
if(animal.y>screenHeight - animal.image.height)
{
//2秒钟后从新开始
setTimeout(function(){
horizontalSpeed = speed;
verticalSpeed = -speed;
animal.x = parseInt(screenWidth/2);
animal.y = parseInt(screenHeight/2);
gameLoop();
}, 2000);
}
//熊碰到上边边界
if(animal.y<0)
{
verticalSpeed = -verticalSpeed;
}
}
二、在游戏循环GameLoop()尾部中加入检测边界函数,如下
JavaScript Code复制内容到剪贴板
function GameLoop()
{
//清除屏幕
ctx.clearRect(0, 0, screenWidth, screenHeight);
ctx.save();
//绘制背景
ctx.drawImage(backgroundForestImg, 0, 0);
//绘制蘑菇
ctx.drawImage(mushroom.image, mushroom.x, mushroom.y);
//绘制熊
//改变移动动物X和Y位置
animal.x += horizontalSpeed;
animal.y += verticalSpeed;
//改变翻滚角度
animal.angle += bearAngle;
//以当前熊的中心位置为基准
ctx.translate(animal.x + (animal.image.width/2), animal.y + (animal.image.height/2));
//根据当前熊的角度轮换
ctx.rotate(animal.angle * Math.PI/180);
//描绘熊
ctx.drawImage(animal.image, - (animal.image.width/2), - (animal.image.height/2));
ctx.restore();
//检测是否碰到边界
HasAnimalHitEdge();
}
到此第四回的完整代码如下:
展开XML/HTML Code复制内容到剪贴板
第四回就讲到这了,第五回讲熊碰撞蘑菇的事件
大家有什么建议的话,可以到论坛留言讨论:http://bbs.html5china.com/read.php?tid=2
转载请注明:睿美印象
网站建设工作室www.ruimeiyx.com