Rotating an image in the direction of the mouse

Hi,
I would greatly appreciate it if somebody could correct my code. I want to maintain object orientation. The program is intended simply to rotate a car image in the direction of the mouse.

class Car {
   PVector location;
   PImage img;
   double rotation;
   
   Car(PVector location) {
     this.location = location;
     img = loadImage("player1car.png");
   }
   
   void display() {
     pushMatrix();
     translate(location.x, location.y);
     rotate((float)rotation);
     imageMode(CENTER);
     image(img, location.x, location.y);
     popMatrix();
   }
   
   void update() {
     double distanceX = mouseX - location.x;
     double distanceY = mouseY - location.y;
     
     this.rotation = Math.atan2(distanceY, distanceX);
   }
}

I think the problem lies in my use of translate but im not sure.
Thank you for your help,
Marc

1 Like
     translate(location.x, location.y);
     rotate((float)rotation);
     imageMode(CENTER);
     image(img, location.x, location.y);

Looks good! Let’s go line by line to make sure we understand what all is going on.

     translate(location.x, location.y);

This moves (0,0) to where the Car’s center is supposed to be. This means that (0,0) is now the center of the car, and the origin of the coordinate system.

     rotate((float)rotation);

This rotates the coordinate system some amount around (0,0). Since that is the center of the car, we’re rotating about the center of the car, which is what we want.

     imageMode(CENTER);

This makes sense. Since we want the center of the car to be at the new origin, we can just draw our image at the new (0,0) position in the translated and rotate coordinate system to put the car where we need it to be.

     image(img, location.x, location.y);

And this draws the car at (0,0). Wait, no it doesn’t. This draws the car somewhere other than (0,0)! We don’t need to draw the car at it’s position - we’ve already moved the origin to where the car needs to be! This line is WRONG! it should just be:

    image( img, 0, 0 );

Try making this change in your code and see if it helps…

2 Likes

Wow! works perfectly! Thank you so much - I’d been banging my head against the wall over that for some time!

I really appreciate your help and the way you took the time to break down the code that I had already written for me. It was extremely helpful.
Thanks again,
Marc

1 Like