Processing: Mouse Rotation

Hello everybody :D

I have a question about Processing, which uses code similar to C++. I hope I came to the right place to ask this question.

I was making a 2d game and I need a picture to face where the mouse is pointing. So for example the picture is the top down view of a man's head and his head should rotate depending on where the mouse is located (i.e. his eyes face the mouse).

I tried using tan to calculate the angle, but I got a weird result.

Here is my code (NOTE: only top right quarter of the screen can calculate the angle):


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
PImage muha;
float rot;
float a;
float b;

void setup(){
  size(500, 500);
  muha = loadImage ("muha.png");
  
}

void draw(){
  background(200, 200, 200);
  
  if (mouseX > 250 && mouseY < 250){
    rot =  radians(90-atan((250 - mouseY)/(mouseX - 250)));
  
  }
  pushMatrix();
 translate(250,250);
  rotate(rot);
  image(muha, 0, 0);
  popMatrix(); 
 
}


I would appreciate any help!

Thanks,
Muhasaresa
I can give an idea for how I might start this problem. The lengths of a right angle triangle are described by the relation c^2 = a^2 + b^2

You first need a reference point (in terms of mouse coordinates) for your picture. Then, with your cursor coordinates you can make a simple subtraction to find the distance between the two. Then (for example), you can use a point along the x-axis from the 'picture's position to form a right angle. Then it is another simple subtraction to determine the length of another side. From there it should be trivial to find the angle you desire.

A pic is worth a 1000 words,


1
2
3
4
5
6
7
                    *cursor
                     |
                   / |
                 /   |  b
                /    |
            pic/_____|
                  a


Ahh u get the idea :p
Last edited on
Thanks :D

Good old Pythagoras always comes in handy!

Muhasaresa

Last edited on
Haha yeh I wonder if he could have imagined we would be using his triangles like this today :p

Good luck with ur project !

*mark as SOLVED?
Last edited on
Topic archived. No new replies allowed.