You should sit down and get to grips with vector math first. It's faster than doing it all in trigonometry and once you get your head around it you can do some really cool stuff.
Most of what I've learned recently has come from
this page on vectors for Flash and from picking apart
Flade, a Flash physics engine that uses verlet integration.
Verlet integration simply means that you do away with velocity and store where you were and where you are now. The beauty of doing this is that you have the data to calculate your trajectory on hand at all times. Plus you can wind back the clock when you collide with an object because you know where you were last frame.
I've put together a simple verlet integration demo below with a bit of vector math as well. There is no need for cos, sin or atan2 unless you are rotating something.
Code:
float damping = 0.96;
float gravityX = 0.0;
float gravityY = 0.0;
Particle p;
void setup(){
size(400, 400);
p = new Particle(200, 200);
smooth();
}
void draw(){
background(255);
p.verlet();
p.collision();
p.draw();
if(mousePressed){
p.getVector(mouseX, mouseY);
p.xPrev -= p.dx;
p.yPrev -= p.dy;
}
}
class Particle{
// Verlet stuff
float xNow, yNow, xPrev, yPrev;
// Vector math stuff
float dx, dy, vx, vy, len;
// Constructor
Particle(float x, float y){
xNow = xPrev = x;
yNow = yPrev = y;
}
void draw(){
ellipse(xNow, yNow, 20, 20);
}
// velocity free movement calculation - plus you can calculate your direction of motion
void verlet(){
float tempX = xNow;
float tempY = yNow;
xNow += damping * (xNow - xPrev) + gravityX;
yNow += damping * (yNow - yPrev) + gravityY;
xPrev = tempX;
yPrev = tempY;
}
void collision(){
// more research for you sonny
}
// Work out some simple vector math
void getVector(float x, float y){
vx = x - xNow;
vy = y - yNow;
len = dist(x, y, xNow, yNow);
// dx is equal to cos(atan2(vy, vx));
// dy is equal to sin(atan2(vy, vx));
// the arc trigonometry function against the trigonometry function cancel each other out
dx = vx / len;
dy = vy / len;
}
}