我将 CCSprite 子类化为一个僵尸对象。它只是加载一个僵尸图像并让用户移动它:
@implementation Zombie
@synthesize speed; // CGFloat
- (id) initWithPosition: (CGPoint) position
{
if(self= [super initWithFile: @"zombie_icon.png"])
{
CCTouchDispatcher* dispatcher=[CCTouchDispatcher sharedDispatcher];
self.position=position;
self.scale= 0.25;
speed= 50.0;
[dispatcher addTargetedDelegate: self priority: 0 swallowsTouches: YES];
}
return self;
}
#pragma - mark Movements
- (NSTimeInterval) timeFromDestination: (CGPoint) destination
{
CGFloat distance= sqrt( pow (fabs(self.position.x-destination.x),2) + pow (fabs(self.position.y-destination.y),2));
return distance/speed;
}
- (BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
return YES;
}
- (void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint location=[self convertTouchToNodeSpace: touch];
NSTimeInterval duration= [self timeFromDestination: location];
[self runAction: [CCMoveTo actionWithDuration: duration position: location]];
}
@end
所以在我的层我这样做:
Zombie* zombie=[[Zombie alloc]initWithPosition: CGPointMake(200, 250)];
[self addChild: zombie];
[zombie release];
僵尸有时移动正确,有时不正确。
例如僵尸在 (100,100),我点击 (200,200),它朝那个方向移动,但是当它到达 (200,200) 时,它会继续前进,直到它离开屏幕。
如果您说问题的描述不是很清楚,稍后我可以上传视频。