我使用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;
}
}
你会注意到我确实得到了触摸位置,这目前没有用于任何东西,但在样本中。
确保层已启用触摸事件isTouchEnabled
是否覆盖:
-(void) registerWithTouchDispatcher {
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
}
在接收触摸的层/节点中?
您也可以尝试在不覆盖registerWithTouchDispatcher
的情况下从代码addTargetedDelegate:self
调用,但我从未尝试过
Sergio解决了您的触摸未注册问题。我最近也遇到了类似的问题。如果用户在哪里触摸屏幕并不重要,那么吞咽触摸:是可以,但如果你有几个层需要注册触摸,你可能需要将其设置为否。
我还没有测试过这个。
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]];
}