【问题标题】:How to get a CCSprite to follow users touch with ccTouchMoved如何使用 ccTouchMoved 让 CCSprite 跟随用户触摸
【发布时间】:2011-03-21 10:40:38
【问题描述】:

我希望能够在用户触摸时移动某些精灵图像。 大致如下:

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    for (UITouch *touch in touches)
    {
        CGPoint *location = [touch locationInView:[touch view]];
        location = [[CCDirector sharedDirector] convertToGL: location];
        if (CGRectContainsPoint(sprite.boundingBox, location)
        {
            sprite.location = ccp(location.x, location.y);
        }
    }
}

当然,这对我不起作用,因为没有运行此方法的 tick 方法来不断移动 CCSprite。我知道方法 ccTouchMoved,但我不确定如何实现它,任何示例将不胜感激。

【问题讨论】:

    标签: objective-c xcode cocos2d-iphone ccsprite


    【解决方案1】:

    只有 CClayer 能够检测到触摸,它是自动的。因此,您将需要处理每个滴答声。它应该是 ccTouchesMove.. 类似:

    -(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        NSLog(@"begin");
    }
    
    -(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
    {    
        UITouch *touch = [touches anyObject];
        CGPoint location = [touch locationInView: [touch view]];
        location = [[CCDirector sharedDirector] convertToGL:location];
    
        sprite.position = location;
    }
    
    -(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    {
        NSLog(@"Ended");
    }
    

    当然,在你的init中,你必须设置self.isTouchEnabled = YES;

    【讨论】:

      【解决方案2】:

      您可以在场景中使用以下方法拖动精灵图像:

      -(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
      {
          CGPoint location = [self convertTouchToNodeSpace: touch];
          sprite.position = location;
      }
      

      【讨论】:

        【解决方案3】:

        请按照以下代码修改您的代码,它对我有用。

        UITouch * touch = [touches anyObject];
        CGPoint location = [touch locationInView:[touch view]];
        location = [[CCDirector sharedDirector] convertToGL:location];
        if (CGRectContainsPoint(sprite.boundingBox,location)){
            [sprite setPosition:location];
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-04-14
          • 1970-01-01
          相关资源
          最近更新 更多