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.height/2));
22. ctx.restore();
23. //检测是否碰到边界
24. HasAnimalHitEdge();
25. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值