wp7使用Cocos2d-X for XNA制作一個塔防類游戲 (二)在游戲中加入地圖和怪物。(下)
上會書剛說到加載地圖,還沒有說完現在補上。。完整源代碼下載

怪物從a點移動到b點他需要經過1234567點,a123467b就是移動的路徑。
有了路徑下面來看下怪物。我這里有一張石器時代的豆丁圖它是4*4 4個方向的圖。

在GameScreen的構造函數中添加如下測試代碼,只是為了看個效果。
//318 ,451 CCTexture2D mode = CCTextureCache.sharedTextureCache().addImage("Images/Sprite/20011"); List<CCSpriteFrame> frames = new List<CCSpriteFrame>(); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { CCSpriteFrame frame = CCSpriteFrame.frameWithTexture(mode, new CCRect(j * 318 / 4, j * 451 / 4, 318 / 4, 451 / 4)); frames.Add(frame); } } CCAnimation ani = CCAnimation.animationWithFrames(frames); CCSprite enemy = CCSprite.spriteWithSpriteFrame(frames[0]); CCAnimate action = CCAnimate.actionWithDuration(.8f, ani, true); enemy.runAction(CCRepeatForever.actionWithAction(action)); enemy.position = new CCPoint(400, 240); addChild(enemy);
運行效果圖:

怪物有了,地圖有了,現在只需要讓怪物按照a1234567b的方式執行MoveTo就完成了今天的任務了。
首先把地圖顯示和怪物顯示的兩端代碼放到相應的兩個類AAMap AAEnemy中,讓他們都繼承CCNode.

我們的地圖是由60*60的14*8的小方格組成,的描述路徑就只需要把a1234567b這幾個點記錄起來文件什么都好自己能讀取就行了我這里怎么快怎么來了。

通過地圖編輯器我們可以很方便的找到點的位置。
我的記錄方式代碼:
public List<CCPoint> Path { get; set; } public AAMap() { CCTMXTiledMap tmxmap = CCTMXTiledMap.tiledMapWithTMXFile("Map/Level1"); addChild(tmxmap); Path = new List<CCPoint>(); Path.Add(new CCPoint(0, 5)); Path.Add(new CCPoint(1, 5)); Path.Add(new CCPoint(1, 2)); Path.Add(new CCPoint(2, 2)); Path.Add(new CCPoint(2, 3)); Path.Add(new CCPoint(7, 3)); Path.Add(new CCPoint(7, 6));
Path.Add(new CCPoint(11, 6)); Path.Add(new CCPoint(11, 0)); }
敵人動畫有四個狀態,AAEnemy的四個行為橫向縱向移動四個方法在合適的時候調用相應的動畫并且一直執行移動。
public void Run(List<CCPoint> points) { CCPoint startPoint = points[0]; sprite.position = ConvertViewPoint(startPoint); List<CCFiniteTimeAction> acs = new List<CCFiniteTimeAction>(); for (int i = 1; i < points.Count; i++) { float length = CCPointExtension.ccpLength(CCPointExtension.ccpSub(points[i], points[i - 1])) * 60; float time = length / 100; CCFiniteTimeAction action = CCMoveTo.actionWithDuration(time, ConvertViewPoint(points[i])); acs.Add(action); } CCAction move = CCSequence.actions(acs.ToArray()); sprite.runAction(move); } public CCPoint ConvertViewPoint(CCPoint p) { return CCDirector.sharedDirector().convertToGL(new CCPoint(p.x * 60 + 30, p.y * 60 + 30)); } public void RightMove() { List<CCSpriteFrame> temp = new List<CCSpriteFrame>(); for (int i = 8; i < 12; i++) { temp.Add(frames[i]); } CCAnimation ani = CCAnimation.animationWithFrames(temp); CCAnimate action = CCAnimate.actionWithDuration(.2f, ani, true); sprite.runAction(CCRepeatForever.actionWithAction(action)); }
最終效果路上奔跑的豆丁:


浙公網安備 33010602011771號