CCSprite跟随用户触摸
问题描述:
到目前为止,我已经使用CCActionMoveTo
将我的CCSprite
移动到用户在屏幕上的触摸位置,但是我只有在用户简单点击时才能使用它。CCSprite跟随用户触摸
我希望CCSprite在用户拖动手指时移动,而不是随着用户拖动方向改变方向一起轻敲和移动方向 - 我对cocos2d相当陌生,并且搜索类似的问题但一直无法找到任何。我已经发布了我的代码如下:
- (id)init
{
self = [super init];
if (!self) return(nil);
self.userInteractionEnabled = YES;
// Player sprite
_playerSprite = [CCSprite spriteWithImageNamed:@"PlayerSprite.png"];
_playerSprite.scale = 0.5;
_playerSprite.position = ccp(self.contentSize.width/2, 150);
[self addChild:_playerSprite];
return self;
}
-(void) touchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint touchLoc = [touch locationInNode:self];
CCActionMoveTo *actionMove = [CCActionMoveTo actionWithDuration:0.2f position:ccp(touchLoc.x, 150)];
[_playerSprite runAction:actionMove];
}
答
您将需要实现touchMoved方法并在那里设置你的精灵位置。事情是这样的:
- (void)touchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint touchLocation = [touch locationInNode:self];
_playerSprite.position = touchLocation;
}
答
试试这个(添加CGPoint属性调用previousTouchPos):
-(void) touchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchLoc = [touch locationInNode:self];
self.previousTouchPos = touchLoc;
CCActionMoveTo *actionMove = [CCActionMoveTo actionWithDuration:1.0f position:touchLoc];
[_playerSprite runAction:actionMove];
}
-(void) touchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchLoc = [touch locationInNode:self];
CGPoint delta = ccpSub(touchLoc, self.previousTouchPos);
_playerSprite.position = ccpAdd(_playerSprite.position, delta);
self.previousTouchPos = touchLoc;
}
答
这听起来像是一个理想的用例CCActionFollow:
https://www.makegameswith.us/gamernews/365/make-two-nodes-follow-each-other-in-cocos2d-30
如果您使用通过块提供目标位置的变体,您可以使用最新的触摸位置作为目标位置。
完美的作品,谢谢!知道这很容易。在精灵移动之前,有什么方法将运动延迟一秒左右? –
随着这些事情一直发射,你需要小心,但你可以创建一个延迟时间的动作序列。 – microslop