-(void)touchBegan:(UITouch*)touch withEvent:(UIEvent*)event {
CGPoint touchPoint = [touch locationInNode:self];
[_gameBall setPosition:CGPointMake(touchPoint.x,self.gameBall.position.y)];
}
触摸后,_gameball sprite不再可见,出现这种情况的原因是什么?我记录了它并且可以看到游戏球是真的,接触点总是在我的CCNode的内容大小内。
#import "GameScene.h"
@interface GameScene()
@property (nonatomic,strong) CCSprite* gameBall;
@end
@implementation GameScene
@synthesize gameBall = _gameBall;
+(GameScene*)gameInstance
{
return [[self alloc]init];
}
-(id)init
{
self = [super init];
if (self) {
//Implement
//user interaction
self.userInteractionEnabled = YES;
//Create the ball
_gameBall = [CCSprite spriteWithImageNamed:@"small_blue_ball.png"];
_gameBall.position = ccp(0.5f,0.1f);
_gameBall.positionType = CCPositionTypeNormalized;
[self addChild:_gameBall];
}
return self;
}
-(void)onEnter
{
[super onEnter];
}
-(void)onExit
{
[super onExit];
}
-(void)touchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchPoint = [touch locationInNode:self];
touchPoint = [self convertToNodeSpace:touchPoint];
[_gameBall setPosition:CGPointMake(touchPoint.x, self.gameBall.position.y)];
NSLog(@"%f , %f",_gameBall.position.x,_gameBall.position.y);
}
-(void)touchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
}
@end
那是.m文件
现在是.h文件
#import "cocos2d-ui.h"
#import "cocos2d.h"
@interface IntroScene : CCScene
+(CCScene*)scene;
@end
答案 0 :(得分:0)
CGPoint touchPoint = [touch locationInNode:self];
touchPoint = [self convertToNodeSpace:touchPoint];
可能是您的问题..尝试将其更改为:
CGPoint touchPoint = [touch locationInView:[touch view]];
touchPoint = [self convertToNodeSpace:touchPoint];
<强> -edit - 强>
好的,试试:
CGPoint touchPoint = [touch locationInView:[touch view]];
touchPoint = [[self parent] convertToNodeSpace:touchPoint];
<强> -edit2 - 强>
刚刚注意到cgpointmake
:
[_gameBall setPosition:CGPointMake(touchPoint.x, self.gameBall.position.y)];
可能没有做任何特别的事情,但您应该保持代码单调,就像使用_gameball.position
然后也使用_gameball.position.y
所以可能想把它改成:
_gameBall setPosition:CGPointMake(touchPoint.x, _gameBall.position.y)];
<强> -edit3 - 强>
这似乎对我有用:
CGPoint touchPoint = [touch locationInView:[touch view]];
touchPoint = [[_gameBall parent] convertToNodeSpace:touchPoint];
[_gameBall setPosition:ccp(touchPoint.x, _gameBall.position.y)];
- 最终修改
由于您使用的是cocos2d,还可以使用他们的ccTouchesBegan函数。将其更改为:
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSArray* touchArray = [touches allObjects];
for (UITouch* touch in touchArray)
{
CGPoint touchPoint = [touch locationInView:[touch view]];
touchPoint = [_gameBall convertToNodeSpace:touchPoint];
[_gameBall setPosition:ccp(touchPoint.x, _gameBall.position.y)];
break;
}
}
如果没有注册触摸,则将[self setTouchEnabled:YES];
添加到您的场景中。