日期:2014-05-17  浏览次数:20693 次

html5 手把手教你做游戏《熊和蘑菇》(四)

第四回主要讲熊移动碰到边界时的反弹处理
预期达到效果:http://www.html5china.com/html5games/mogu/index3.html
一、写一个碰撞处理函数
JavaScript Code复制内容到剪贴板
1. function HasAnimalHitEdge()  
2. {  
3.     //熊碰到右边边界  
4.     if(animal.x>screenWidth - animal.image.width)  
5.     {  
6.         if(horizontalSpeed > 0)//假如向右移动  
7.             horizontalSpeed =-horizontalSpeed;//改变水平速度方向  
8.     }  
9.     //熊碰到左边边界  
10.     if(animal.x<-10)  
11.     {  
12.         if(horizontalSpeed < 0)//假如向左移动  
13.             horizontalSpeed = -horizontalSpeed;//改变水平速度方向  
14.     }  
15.     //熊碰到下面边界  
16.     if(animal.y>screenHeight - animal.image.height)  
17.     {  
18.         //2秒钟后从新开始  
19.         setTimeout(function(){  
20.             horizontalSpeed = speed;  
21.             verticalSpeed = -speed;  
22.             animal.x = parseInt(screenWidth/2);  
23.             animal.y = parseInt(screenHeight/2);  
24.             gameLoop();  
25.         }, 2000);  
26.     }  
27.     //熊碰到上边边界  
28.     if(animal.y<0)  
29.     {  
30.         verticalSpeed = -verticalSpeed;  
31.     }  
32. } 
二、在游戏循环GameLoop()尾部中加入检测边界函数,如下
JavaScript Code复制内容到剪贴板
1.   function GameLoop()     
2.   {     
3.       //清除屏幕     
4.       ctx.clearRect(0, 0, screenWidth, screenHeight);     
5.       ctx.save();     
6.       //绘制背景     
7.       ctx.drawImage(backgroundForestImg, 0, 0);     
8.       //绘制蘑菇     
9.       ctx.drawImage(mushroom.image, mushroom.x, mushroom.y);   
10. //绘制熊  
11. //改变移动动物X和Y位置  
12. animal.x += horizontalSpeed;  
13. animal.y += verticalSpeed;  
14. //改变翻滚角度  
15. animal.angle += bearAngle;  
16. //以当前熊的中心位置为基准  
17.         ctx.translate(animal.x + (animal.image.width/2), animal.y + (animal.image.height/2));  
18. //根据当前熊的角度轮换  
19.     ctx.rotate(animal.angle * Math.PI/180);  
20. //描绘熊  
21.     ctx.drawImage(animal.image, - (animal.image.width/2), - (animal.image.h