How to get a CCSprite to follow users touch with ccTouchMoved
I want to be able to move certain sprite images with the users touch. Something along these lines:
- (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);
}
}
}
Of co开发者_JAVA技巧urse, this doesnt work for me, as there is no tick method running for this method to continually move the CCSprite. I know of the method ccTouchMoved, but I'm unsure how to implement it, any examples would be greatly appreciated.
Only CClayer is able to detect a touches, its automatic. So you are going to need to handle the per tick thing. And it should be ccTouchesMove.. Something like:
-(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");
}
Of course, in your init, you must set self.isTouchEnabled = YES;
You can drag sprite images with the following method in your scene:
-(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint location = [self convertTouchToNodeSpace: touch];
sprite.position = location;
}
Please modify your code as per below code, it is working for me.
UITouch * touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
if (CGRectContainsPoint(sprite.boundingBox,location)){
[sprite setPosition:location];
}
精彩评论