Rotate and translate

Hi,

I am working on learning how to rotate an image to follow the mouse using a formula from Keith Peters HTML5 Animation.

I am curious why the following code does not rotate the image completely. It seems to only swing down and to the left instead of a full 360.

Here is my code:

ArrowImage arrow= new ArrowImage();

void setup(){
 size(640, 480);
 arrow.arrow = loadImage("arrow.png");
}

void draw() {
  background(0);
  //translate(width/2, height /2);
  float dx = mouseX - arrow.x;
  float dy = mouseY - arrow.y;
  double rotation = Math.atan2(dy, dx);
  rotate((float)rotation);
  arrow.draw();
  
}
class ArrowImage {
  
  int x = 0;
  int y = 0;
 PImage arrow;
  
  public ArrowImage() {
   
  }
  
  void draw() {
   image(arrow, width/2, height/2);
  }
}

Any thoughts would be appreciated.

Also, why does the screen go black when I uncomment translate line?
Thanks,
Marc

1 Like

atan2 is this way

Check if it’s negative and make it between 180 and 360 iirc

You mean like:

if((Math.atan2(dy,dx)) <0) {
  // make it between 180 and 360
}

By it you mean the results of atan2? How do I make the rotation angle between 0 and 180?

Thanks,
Marc

I don’t remember

eg

angle=map(atan2, 0,-PI, PI, TWO_PI);

The atan2 method works fine as you have used it in your code, there is no need to try and compensate for negative values or anything like that. The problem is in the angle is calculated using arrow.x and arrow.y but the actual arrow is drawn in position width/2 and height/2 as per class draw method change it to

  void draw() {
    pushStyle();
    imageMode(CENTER);
    image(arrow, x, y);
    popStyle();
  }

There are lots of improvements that could and should be made to your code, especially the class design.

2 Likes

To use the translate so the arrow appears in the centre of the display, modify your draw method to

  background(255);
  translate(width/2, height /2);
  float dx = mouseX - arrow.x - width/2;
  float dy = mouseY - arrow.y - height/2;
  double rotation = Math.atan2(dy, dx);
  rotate((float)rotation);
  arrow.draw();
}
2 Likes

Hi Peter,

Thank you for your reply. You guys are great on this forum.

I took your advice and got it working!

Thanks again,

Marc