我是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];
}
有人可以帮忙吗? 非常感谢!
答案 0 :(得分:0)
第三个效果不好,即使我检查'moveDuration'并将其置于动作中,动作也不顺畅