2
votes

I have two nodes. Player and Enemy. I want Enemy node to follow Player node once it's close enough and Enemy node would stop when it collides with Player node. And what I get is Enemy node goes on top of Player and both nodes gets pushed. I thought about somehow stopping Enemy node from moving on collision with Player but it seems to me like it should be a cleaner way.

(I move Enemy node by changing it possition on Update).

Here's my GameScene.sks:

character and enemy options from GameScene

-(void)didMoveToView:(SKView *)view {

    player = [self childNodeWithName:@"character"];
    enemy  = [self childNodeWithName:@"enemy"];
    self.physicsWorld.contactDelegate = self;
}

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

    for (UITouch *touch in touches) {
        moveToTouch = [touch locationInNode:self];
        SKNode *tile = [self nodeAtPoint:moveToTouch];
        if([tile.name isEqualToString:@"tile"])
        {
            moveToTouch = tile.position;
        }
    }
}

-(void)update:(CFTimeInterval)currentTime {

    [self walk:player to:moveToTouch];

    if((SDistanceBetweenPoints(enemy.position, player.position) < 200))
    {
        [self walk:enemy to:player.position];
    }


}

-(void)walk:(SKNode*)node to:(CGPoint)moveTo
{
    if (CGPointEqualToPoint(moveTo, CGPointZero))
    {
        return;
    }


    if(round(moveTo.y) != round(node.position.y))
    {

        if(moveTo.y > node.position.y)
        {
            node.position = CGPointMake(node.position.x,node.position.y+2);
        }
        else if (moveTo.y < node.position.y)
        {
            node.position = CGPointMake(node.position.x,node.position.y-2);
        }

    }else if(round(moveTo.x) != round(node.position.x))
    {

        if(moveTo.x > node.position.x)
        {
            node.position = CGPointMake(node.position.x+2,node.position.y);
        }
        else if (moveTo.x < node.position.x)
        {
            node.position = CGPointMake(node.position.x-2,node.position.y);
        }

    }

    float distance = SDistanceBetweenPoints(node.position, moveTo);
    if (distance < 1.0){
        moveToTouch = CGPointZero;
    }

}
1
I have never used the Visual component to make sprite kit games, but it sounds like your issue is you do not want to be registering collision, so set those masks to 0 (Or so that they have a mask that they can't collide with). You then want to focus on using your contact masks, and at the point they contact, stop the enemy - Knight0fDragon
@Knight0fDragon Thanks, I will try that! - HelloimDarius
should be using a contact delegate in your scene with a dedbegincontact function call - Knight0fDragon

1 Answers

1
votes

I don't know how you have it set up that your enemy follows the player. But you could try to

  • set the enemy dynamic to false
  • or put velocity to 0

Use collision detection to know when the collided.