【问题标题】:Cocos2d iPhone Game touch screen to make a character moveCocos2d iPhone游戏触屏让人物动起来
【发布时间】:2011-06-06 10:47:11
【问题描述】:

我使用 cocos2d 编写了一些游戏,但它们都是由加速度计控制的,并且只使用简单的触摸事件。我需要做的就是在任何地方触摸屏幕时进行注册。我不需要有关位置或速度的任何信息。角色当前在屏幕上移动,用户应该能够触摸以使角色在屏幕上向上移动。当前代码无法按预期工作。角色不受触摸的影响,它只是继续向下移动屏幕。请指教。下面是我现在尝试使用的代码。

在游戏更新方法中:

if (IsTouched == TRUE) {
    SealPositionBasedOnTouchInt = SealPositionBasedOnTouchInt - (100*dt);
}

else {
    SealPositionBasedOnTouchInt = SealPositionBasedOnTouchInt + (100*dt);
}

SealSwimming.position = ccp(SealPositionBasedOnTouchInt, SealSwimming.position.y);

触摸事件:

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{


    for( UITouch *touch in touches ) 
    {
    CGPoint location = [touch locationInView: [touch view]];
    location = [[CCDirector sharedDirector] convertToGL: location];
    IsTouched = TRUE;
}  
}

你会注意到我确实得到了触摸位置,这目前没有用于任何事情,但在示例中。

【问题讨论】:

    标签: iphone objective-c xcode cocos2d-iphone


    【解决方案1】:

    确保图层启用了触摸事件isTouchEnabled

    【讨论】:

    • 天哪,多么愚蠢的错误。有时让别人看一下会有所帮助。就是这样,我没有在 init 方法中启用触摸。谢谢!!
    【解决方案2】:

    你是否被覆盖了:

    -(void) registerWithTouchDispatcher {
        [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
    }
    

    在接收触摸的层/节点中?

    您也可以尝试从您的代码addTargetedDelegate:self 调用而不覆盖registerWithTouchDispatcher,但我从未尝试过。

    【讨论】:

      【解决方案3】:

      Sergio 可以解决您的触摸未注册问题。我最近遇到了类似的问题。如果用户触摸屏幕的位置无关紧要,则可以使用 SwallowsTouches: YES,但如果您有几层需要注册触摸,则可能需要将其设置为 NO。

      【讨论】:

        【解决方案4】:

        我还没有测试过。

        in .h
        
        CCSprite *sprite;
        
        
        in .m
        
        -(id)init
        {
            if ((self=[super init))
            {
                   CGSize s = [[CCDirector sharedDirector] winSize];
        
                   sprite = [CCSprite spriteWithFile:@"imagename.png"];
                   sprite.position = ccp(s.width/2, s.height/2);
                   [self addChild:sprite];
            }
            return self;
        }
        
            - (void) ccTouchesBegan: (NSSet *)touches withEvent: (UIEvent *)event
        {
        
            UITouch *touch = [touches anyObject];
        
            CGPoint touchLocation = [touch locationInView: [touch view]];   
            touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
        
            [sprite setPosition:touchLocation];
        
            //OR YOU CAN RUN AN ANIMATION TO MAKE IT LOOK LIKE IT'S WALKING
            //[sprite runAction:[CCMoveTo actionWithDuration:5 position:touchLocation]];
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-20
          • 1970-01-01
          • 2011-11-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多