cocos2d学习笔记第三章 让精灵按指定的路径来运动

1. 因为要自己写一个塔防的游戏,因此在之前我们创建的关卡1场景文件checkpoints_layer1.m中, 做一下地图的初始化,也就是我们要让精灵行走的路径预先定义下来。

-(void)initWayPoint
{
m_WayPoint = [[NSMutableArray alloc] initWithCapacity:500];

CGPoint point;

point = CGPointMake(0, 190);
[m_WayPoint addObject:[NSValue valueWithCGPoint:point]];
point = CGPointMake(220, 190);
[m_WayPoint addObject:[NSValue valueWithCGPoint:point]];
point = CGPointMake(220, 220);
[m_WayPoint addObject:[NSValue valueWithCGPoint:point]];
point = CGPointMake(380, 220);
[m_WayPoint addObject:[NSValue valueWithCGPoint:point]];
point = CGPointMake(380, 100);
[m_WayPoint addObject:[NSValue valueWithCGPoint:point]];
point = CGPointMake(60, 100);
[m_WayPoint addObject:[NSValue valueWithCGPoint:point]];
point = CGPointMake(60, 20);
[m_WayPoint addObject:[NSValue valueWithCGPoint:point]];
point = CGPointMake(390, 20);
[m_WayPoint addObject:[NSValue valueWithCGPoint:point]];

}

因为我这边背景是在www.300day.com 上下载的内裤的背景图, 我让精灵按这个路径进行运动,一共分为上面几个步骤,

当然该文件在正式编写的场合应该从一个配置文件中读取, 不应该写成死的, 这里只是为了学习用, 读文件将路径生成array应该很简单了,就不用写了。

上面函数将在该场景的init方法中调用。也就是说场景初始化完毕后,马上就要做运动路径的初始化。注意我们是将每一个行走的拐点存在了array中。

并不是把所有像 素都存在里面,因为那样完全没有必要。


2. 另外我们还要做一个方法,供我们的精灵使用, 那就是让他可以通过当前的位置来取得下次要到达的拐点的位置,这样他就可以按此函数一个一个的拐点走下去。

-(CGPoint) getPositionWithPosIndex:(NSInteger)posIdx
{
NSAssert(posIdx>=0 && posIdx<[m_WayPoint count], @"getPositionWithPosIndex posIdx=%d [L%d]",posIdx,__LINE__);

return [[m_WayPoint objectAtIndex:posIdx] CGPointValue];
}


3.接下来要创建一个怪物的类名字叫monster 继承自CCSprite

@interface Monster : CCSprite
{
NSInteger m_curPosIndex; //当前怪位所在的拐点ID
NSInteger m_maxPosIndex; //最大的拐点ID数量
}
+(id) monster:(NSRange)posIndexRange; //用来初始化上面两个信息
@end


在initWithPosIndexRange的实现文件中, 调用[self goFollowPath], 该函数的做用是让我们的怪物运动起来,原理如下,注释很清楚。

-(void)goFollowPath
{
checkpoints_layer1 *lay1 = [checkpoints_layer1 sharecheckpoints_layer1];

m_curPosIndex++; //当前的位置ID后移
if(m_curPosIndex < m_maxPosIndex)
{
CGPoint point = [lay1 getPositionWithPosIndex:m_curPosIndex];
int delta = ABS(point.x - self.position.x);
if(delta == 0)
{
delta = ABS(point.y - self.position.y);
}
//速度每秒钟所移动的像素值35
float moveDuration = delta/35.0;

id actionMove = [CCMoveTo actionWithDuration:moveDuration position:point];
id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:@selector(goFollowPath)];

//让当前怪物按上面的action进行移动,移动完了后调用我们指定的函数,即他自己,直到走完所有路径
[self runAction:[CCSequence actions:actionMove, actionMoveDone, nil]];
}
else
{
//超出范围删除
[self removeFromParentAndCleanup:YES];
}
}


4.添加怪物可以在checkpoints_layer1.m中起动一个schedule,在里面来添加怪物

NSRange range;
range.location = 0;
range.length = [m_WayPoint count];
Monster* monster = [Monster monster:range];
[m_batchSprite addChild:monster];


5. 编译, 运行, 怪物就可以按我们指定的路径行走了。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值