1
votes

I'm trying to make an SKAction so that my player is slowly pulled towards an enemy who is going to kill him. The problem, actually, is that the player and the enemy are in different nodes, following this hierarchy:

Scene (SKScene) -PARENT-> Player (SKNode)

Scene (SKScene) -PARENT-> EnemiesNode (SKNode) -PARENT-> Enemy (SKNode)

So what I'm trying to do is convert the enemy position into the scene's coordinate system and then converting this position to the player's coordinate system.

let enemyToScene = enemy.node?.convert(other.enemy!.position, to: self)
let sceneToPlayer = self.convert(enemyToScene!, to: self.player.position)
self.player.position.run(SKAction.move(to: enemyToPlayer!, duration: 2.0))

When this code is executed, what happens is that my player goes to a totally different position, but, what I've noticed is that he always goes to the same position, so I guess the conversion is working, but not as expected.

These are the positions before the conversion:

Enemy Position: Optional((-1440.0, -96.0))

Player Position: (347.970458984375, 339.2470703125)

And the enemy's position after the conversion:

EnemyToScene: Optional((-2880.0, -192.0))

SceneToPlayer: (-2038.263427734375, -27.4952392578125)

If anyone can help me, I'll be very pleased.

1

1 Answers

1
votes

A node's position is in its parent's geometry, so you need to convert enemy.position from the geometry of enemy.parent to the geometry of player.parent.

if
    let enemyNode = enemy.node,
    let enemyParent = enemy.parent,
    case let playerNode = player.position,
    let playerParent = playerNode.parent
{
    let targetPosition = enemyParent.convert(enemyNode.position, to: playerParent)
    playerNode.run(SKAction.move(to: targetPosition, duration: 2)
}