睿美印象网络欢迎您的到来,并真诚的希望能与您合作!
睿美印象网络
返回上一页
客服QQ
点击这里给我发消息
客服QQ
点击这里给我发消息
一切从沟通开始……

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

作者:睿美印象网站建设工作室  发布日期:2012-12-06
第四回主要讲熊移动碰到边界时的反弹处理

预期达到效果: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
分享到:
已有 0 条评论
暂无评论
睿美印象在线客服
客服部小睿:
点击这里给我发消息
设计部小美:
点击这里给我发消息
技术海绵哥:
点击这里给我发消息
在线淘客服:
睿美印象网络
淘客服小睿:
睿美印象小睿
淘客服小美:
睿美印象小美