Navigation

    Fuze Arena Logo
    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Popular
    • Users
    • Groups
    • Help
    • Discord

    How to automatically rotate a sprite to make it face a certain point!

    Beginners
    3
    3
    241
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • vinicity
      vinicity F last edited by vinicity

      I noticed this question comes up a lot, and it has been answered in a few different places, but I thought I would make a separate topic to make it easy to find.

      A common scenario is that you have a sprite and you want to rotate it so that it faces another sprite. It could be that incoming enemies are flying towards you, and you want their ships to move with the front first. Or maybe you want your player sprite to face the direction where your target reticle is?

      This is how you do it (in three easy steps) if you have a playerSpr sprite that you want to face a targetSpr sprite:

      1. Calculate the vector that describes the difference between the two sprites.
      diff = getSpriteLocation(playerSpr) - getSpriteLocation(targetSpr)
      
      1. Calculate the angle in degrees using atan2. This is a mathematical formula that takes as input the y difference and the x difference and returns the angle.
      angle = atan2(diff.y, diff.x)
      
      1. Now that we have the angle, we can rotate the player sprite. Depending on the original orientation of the sprite you may need to add an offset (generally + or - 90 degrees).
      setSpriteRotation(playerSpr, angle - 90)
      

      It is all really simple. As a bonus, this is how you can get the distance between the sprites:

      dist = sqrt(diff.y * diff.y + diff.x * diff.x)
      

      Here is a small working example that you can download and try it out for yourself:

      ID: NXK76GP92C

      1 Reply Last reply Reply Quote 8
      • SteveZX81
        SteveZX81 F last edited by

        Awesome indeed. I'm sure I can find a use for this ;)
        Thanks.

        PickleCatStars 1 Reply Last reply Reply Quote 2
        • PickleCatStars
          PickleCatStars F @SteveZX81 last edited by

          Oh yeah, someone gave a TED talk on this a while back :)

          alt text

          1 Reply Last reply Reply Quote 3
          • First post
            Last post