新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
蘑菇與熊游戲開發(fā)第四回(熊碰撞邊界處理)
第四回主要講熊移動碰到邊界時的反彈處理

預(yù)期達(dá)到效果:http://www.html5china.com/html5games/mogu/index3.html
一、寫一個碰撞處理函數(shù)
- 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;
- }
- }
二、在游戲循環(huán)GameLoop()尾部中加入檢測邊界函數(shù),如下
- 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;
- //以當(dāng)前熊的中心位置為基準(zhǔn)
- ctx.translate(animal.x + (animal.image.width/2), animal.y + (animal.image.height/2));
- //根據(jù)當(dāng)前熊的角度輪換
- ctx.rotate(animal.angle * Math.PI/180);
- //描繪熊
- ctx.drawImage(animal.image, - (animal.image.width/2), - (animal.image.height/2));
- ctx.restore();
- //檢測是否碰到邊界
- HasAnimalHitEdge();
- }
到此第四回的完整代碼如下:
蘑菇動起來-html5中文網(wǎng)
第四回就講到這了,第五回講熊碰撞蘑菇的事件
【編輯推薦】
- 蘑菇與熊游戲開發(fā)***回(游戲分析)
- 蘑菇與熊游戲開發(fā)第二回(讓蘑菇動起來)
- 蘑菇與熊游戲開發(fā)第三回(讓熊動起來)
- 蘑菇與熊游戲開發(fā)第五回(熊碰撞蘑菇處理)
- 蘑菇與熊游戲開發(fā)第六回(繪制獎品)
- 蘑菇與熊游戲開發(fā)第七回(熊碰到獎品處理)
- 蘑菇與熊游戲開發(fā)第八回(完善游戲)
當(dāng)前標(biāo)題:蘑菇與熊游戲開發(fā)第四回(熊碰撞邊界處理)
文章網(wǎng)址:http://fisionsoft.com.cn/article/dhcgpgj.html


咨詢
建站咨詢
