How do I make a sprite rotate to face another sprite?

I’m working on a tower defense game but I am unable to find a way for my towers to rotate to look at the current enemy they’re targeting. Any solutions?

Have you tried using the atan2() function?

I looked at it but uh, I don’t understand it.

You use the atan2() function to find the angle of rotation for the tower. In the sample code below, in the atan2() line, the arguments ex-height/2 and ey-width/2 represent the position of the enemy relative to the tower:

function setup() {
  createCanvas(400, 400);

// position variables for enemy
ex = 150; ey = 0;

function draw() {
  // fill & stroke properties for enemy and tower
  // enemy
  circle(ex, ey, 20);
  ex ++; ey ++;
  // tower
  translate(width/2, height/2);
  a = atan2(ex-width/2, ey-height/2);
  triangle(-10,0, 0,20, 10,0);
  // draw green beam
  rect(0, 0, 1, 500);

You’ll need to adapt this code to work with your program.

1 Like