Question

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'?

Was it helpful?

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.

OTHER TIPS

Use point towards as a way of finding out:

set temp to direction
point towards hero
if temp > direction
   set direction to temp-2
else if temp < direction
   set direction to temp-2
else
   set direction to temp
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top