Search code examples
rotationsprite-kitdirection

Spritekit is a SKSpriteNode facing another SKSpriteNode


I'd like to find out if a sprite is facing another sprite? For instance I would like to make a player have the ability to shoot a monster if he is pointing his gun anywhere between the length of the monster. Please help!


Solution

  • To determine if the player node is facing the enemy node, you will need to calculate the angle between the nodes (see angle theta in Figure 1).

    enter image description here

    Figure 1 Diagram showing the angles between the nodes in the scene

    Calculate theta by taking the inverse tangent of the difference in y divided by the difference in x:

        CGFloat dx = enemy.position.x - player.position.x;
        CGFloat dy = enemy.position.y - player.position.y;
    
        theta = atan2f(dy, dx);
    

    If the difference between theta and the player's zRotation is small, the player is facing the enemy.

       if (fabs(theta-player.zRotation) < maxDifference) {
            // Do something here
       }