一步一步学干游戏 第四回:熊碰撞边界处理

一步一步学做游戏 第四回:熊碰撞边界处理

第四回主要讲 熊 移动碰到边界时的反弹处理 预期达到效果: http://www.html5china.com/html5games/mogu/index3.html 一、写一个碰撞处理函数 JavaScript Code 复制内容到剪贴板 function HasAnimalHitEdge() {…

第四回主要讲熊移动碰到边界时的反弹处理

预期达到效果: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.height/2));   
  22.       ctx.restore();   
  23. //检测是否碰到边界   
  24. HasAnimalHitEdge();   
  25.       }     

到此第四回的完整代码如下:

展开XML/HTML Code复制内容到剪贴板

第四回就讲到这了,第五回讲熊碰撞蘑菇的事件

大家有什么建议的话,可以到论坛留言讨论:http://bbs.html5china.com/read.php?tid=2

希望大家在其他地方引用的时候,注明引用来自html5中文网

 --作者:深邃老马    

-----------------逆水行舟,不进则退