Search code examples
iossprite-kittouchesmoved

move Sprite with touches moved


i am moving a sprite using the touches moved method. currently the sprite jumps to the point on which the screen is touched but I want the sprite only to move when it is touched directly.

my code:

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

    for (UITouch *touch in touches) {

        CGPoint location = [touch locationInNode:self];
        CGPoint newPosition = CGPointMake(location.x, self.size.height/2);

        self.sprite.position = newPosition;
     }
 }

Solution

  • check if the touch location is inside the sprite, like this:

    -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *touch = [touches anyObject];
        CGPoint positionInScene = [touch locationInNode:self];
        if(CGRectContainsPoint(self.sprite.boundingBox,positionInScene)) {
    
            CGPoint newPosition = CGPointMake(positionInScene.x, self.size.height/2);
    
            self.sprite.position = newPosition;
        }
    }