Search code examples
mit-scratch

How do I determine the direction of another sprite in Scratch


I'm programming a simple game for education in MIT Scratch and want to make a sprite turn towards another sprite (think an alien ship following our hero ship). I can easily make the alien ship point towards the hero:

point towards 'hero'

But what I really want to do is something more gradual like this:

if alien direction (in degrees) > direction of hero: turn -2 degrees
if alien direction (in degrees) < direction of hero: turn 2 degrees

So how do I determine 'direction of hero'?


Solution

  • Unfortunately there doesn't seem to be a built-in way to get this, so some trigonometry is needed. To calculate the direction from sprite 1 to sprite 2 you can calculate the displacement from 1 to 2 in x and y, then use the atan function to find the required angle:

    Script to calculate angle to another sprite

    Since you actually want the direction relative to the direction the alien ship is facing, it might be better to use the vector product (aka cross product):

    enter image description here

    The screenshots here are taken from this Scratch project.