0

我有一个似乎无法解决的问题。我想根据手指移动在屏幕上移动精灵,但不是让精灵触摸位置移动,我希望精灵以与手指在屏幕上移动相同的方式移动。

示例:用户将手指放在屏幕上(任意位置),然后将手指在屏幕上向左拖动 200 像素,精灵也应该向左移动 200 像素。

我的方法是存储玩家在开始时的位置,然后计算开始位置与手指当前位置之间的差异,以添加到精灵本身的开始位置。

这是我的代码

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
if([touches count] == 1){
    UITouch *touch = [touches anyObject];
    CGPoint startPos = [touch locationInView:[touch view]];
    startPosition = startPos;
}

}

-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    if([touches count] == 1){
        UITouch *touch = [touches anyObject];
        CGPoint touchPos = [touch locationInView:[touch view]];
        CGPoint playerPos = player.position;

        float yDifference = startPosition.y - touchPos.y;
        playerPos.y = playerPos.y - yDifference;

        // just to change to GL coordinates instead of the ones used by Cocos2D
        // still doesn't work even if I remove this...
        CGPoint convertedPoint = [[CCDirector sharedDirector] convertToGL:playerPos];
        [player setPosition:convertedPoint];
    }

}

我希望我遇到的问题很清楚,但如果不是,请不要犹豫,提出问题或进一步解释。我已经坚持了很长一段时间:'(

4

2 回答 2

1

此外,如果您希望它“相对”移动到它开始的位置,而不是触摸的确切位置:

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    if([touches count] == 1){
      UITouch *touch = [touches anyObject];
      CGPoint startPos = [touch locationInView:[touch view]];
      startPosition = startPos;
      playerStartPos = playerPos;
    }
 }

-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    if([touches count] == 1){
      UITouch *touch = [touches anyObject];
      CGPoint touchPos = [touch locationInView:[touch view]];

      CGPoint newPlayerPos;
      newPlayerPos.x = playerStartPos.x + (touchPos.x - startPosition.x);
      newPlayerPos.y = playerStartPos.y + (touchPos.y - startPosition.y);

      // just to change to GL coordinates instead of the ones used by Cocos2D
      // still doesn't work even if I remove this...
      CGPoint convertedPoint = [[CCDirector sharedDirector] convertToGL:newPlayerPos];
      [player setPosition:convertedPoint];
}

您的代码看起来像是通过不断将差异添加到 playerPos.y 来“反馈”到自身

于 2012-08-08T07:00:33.313 回答
0

所以不要使用差异,使用当前的触摸位置:

-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    if([touches count] == 1){
        UITouch *touch = [touches anyObject];
        CGPoint playerPos = [touch locationInView:[touch view]];

        // just to change to GL coordinates instead of the ones used by Cocos2D
        // still doesn't work even if I remove this...
        CGPoint convertedPoint = [[CCDirector sharedDirector] convertToGL:playerPos];
        [player setPosition:convertedPoint];
    }
于 2012-08-08T06:45:25.253 回答