Hi. I'm moving an object around the screen by using an angle and a speed. I'd like it to seek the mouse, by changing it's heading to face my cursor.
I'm having a real tough time calculating the angle it needs to point, and an equal problem having it figure out how to turn towards the target angle!
My code is messy and half baked, but the fundamentals (I hope) are there. The black triangle represents the current heading (angle) and the grey one points to where it thinks my mouse is (doesn't work).
Right now it just turns in circles, meaning that I cannot find a condition that has different outcomes.
HALP
Code:
/* this is messy as crap and half finished
I can't figure out how to calculate the angle the ball should face in order to move towards the mouse
and I can't figure out how to make it turn the shortest way to face said angle!
*/
ball frank;
float fatness=50;
void setup() {
size(350,700);
frank = new ball();
ellipseMode(CENTER);
}
void draw() {
background(255);
frank.move();
}
class ball {
float x;
float y;
float angle;
float speed;
float targetangle;
float anglerate=.02*PI;
ball(){
x=width/2;
y=height/3;
speed=random(3)+2;
angle=random(PI)+.5*PI;
}
void move() {
//move towards current heading
x=x + speed*cos(angle);
y=y + speed*sin(angle);
//draw ellipse
fill(255);
ellipse(x,y,fatness,fatness);
//draw vector line
line( x,y, x + 5*speed*cos(angle), y + 5*speed*sin(angle));
//draw current angle triangle
fill(0);
triangle( x + 5*speed*cos(angle), y + 5*speed*sin(angle), x + 2*speed*cos(angle+.5*PI), y + 2*speed*sin(angle+.5*PI),x + 2*speed*cos(angle-.5*PI), y + 2*speed*sin(angle-.5*PI));
//draw target angle triangle
fill(100,100,100,100);
triangle( x + 5*speed*cos(targetangle), y + 5*speed*sin(targetangle), x + 2*speed*cos(targetangle+.5*PI), y + 2*speed*sin(targetangle+.5*PI),x + 2*speed*cos(targetangle-.5*PI), y + 2*speed*sin(targetangle-.5*PI));
// bounces off left/ right walls, still need to do top and bottom
if((x+speed*cos(angle)>width) || (x<0)) {
angle=angle+2*(.5*PI-angle);
}
//define our target angle DOESNT WORK?!?!
targetangle=PI+atan(1/((mouseX-x)/(mouseY-y)));
//try to make it gradually turn to face the target angle DOESNT WORK!
if (angle>PI) {
angle -=anglerate;
} else {
angle += anglerate;
}
}
void reset() {
x=mouseX;
y=mouseY;
speed=random(2)+3;
angle=random(2*PI);
}
}
void mousePressed(){
frank.reset();
}