Reputation: 375
The following is a Processing sketch.
Dead centre coordinates are 0,0.
This means the far-left x coord is -250 and the far right x coord is 250. Similar dimension for y.
I want to move the mouse around the centre of the screen and have the relative coordinate appear on the radius, (i.e. mouse at coordinates 45,0 should mark point at 90,0).
The below code works but only for the right side of the screen, in short, angles up to 180. What is missing for this to work for the right hand side?
void draw(){
background(0);
fill(255);
stroke(255);
strokeWeight(5);
translate(width/2,height/2);
// mark center
point(0,0);
strokeWeight(12);
// mark mouse position (follow with point)
float x = mouseX - width/2;
float y = mouseY - height/2;
point(x,y);
// trace point on radius of circle same radius as width
float radius = width/2;
float sinAng = y/radius;
float cosAng = x/radius;
float m = sinAng/cosAng;
float angle = atan(m);
float boundaryX = cos(angle)*width/2;
float boundaryY = sin(angle)*height/2;
stroke(255,0,0);
point(boundaryX,boundaryY);
}
Upvotes: 0
Views: 212
Reputation: 42176
You can do this in fewer steps by using the atan2()
function.
The atan2()
function takes two parameters: the y distance between two points, and the x distance between two points, and it returns the angle between those points:
angle = atan2(y1-y0, x1-x0);
You can get rid of a few lines in your program by just doing this:
float x = mouseX - width/2;
float y = mouseY - height/2;
float angle = atan2(y, x);
float boundaryX = cos(angle)*width/2;
float boundaryY = sin(angle)*height/2;
No need to calculate the sinAng
, cosAng
, or m
variables.
Upvotes: 0
Reputation: 4855
You're loosing the quadrant when calculating m...
-x/-y = x/y
Just correct the angle to the right quadrant by using the sign of x and y.
Upvotes: 2