【发布时间】:2011-07-13 19:59:46
【问题描述】:
我是 cocos2d 的新手,正在阅读很多教程 我想做的是触摸屏幕,让精灵跟随我的触摸。 松开触摸时,精灵停止 当触摸远离精灵时,即使我的手指连续移动,精灵也应该开始移动。 我该怎么做?
我尝试不同的方式:
-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
isMoving = YES;
[self schedule:@selector(moveSprite:)];
return YES;
}
-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
isMoving = NO;
[self unschedule:@selector(moveSprite:)];
}
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
if (isMoving)
{
touchLocation = [touch locationInView: [touch view]];
touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
touchLocation = [self convertToNodeSpace:touchLocation];
}
}
-(void)moveSprite:(ccTime) dt {
CGPoint moveVector = ccpSub(touchLocation, mySprite.position);
float distanceToMove = ccpLength(moveVector);
float velo = 480.0/3.0;
float moveDuration = distanceToMove / velo;
self.moveAction = [CCSequence actions:
[CCMoveTo actionWithDuration:moveDuration position:touchLocation],
nil
];
[mySprite runAction:_moveAction];
}
或再次使用:
- (void)handlePanFrom:(UIPanGestureRecognizer *)recognizer {
CGPoint touchLocation = [recognizer locationInView:recognizer.view];
touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
touchLocation = [self convertToNodeSpace:touchLocation];
moveAction = [CCSequence actions:
[CCMoveTo actionWithDuration:2.0f position:touchLocation],
nil
];
[mySprite runAction:moveAction];
}
或者简单的
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
touchLocation = [touch locationInView: [touch view]];
touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
touchLocation = [self convertToNodeSpace:touchLocation];
[_mySprite stopAction:_moveAction];
_moveAction = [CCMoveTo actionWithDuration:1 position:touchLocation];
[_mySprite runAction:_moveAction];
}
有人可以帮忙吗? 非常感谢!
【问题讨论】:
-
第三个在我看来应该可以工作。它实际上在做什么?
标签: iphone xcode cocos2d-iphone touch sprite