Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I have particles, with a velocity (x and y) per tick. I would like to to make my cursor a gravity force, so particles fly to the cursor's position.

How can I apply gravity (that is towards my cursor position) on my velocity (x and y)?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

Just subtract the particle position from the cursor position to make the acceleration vector. Then multiply the norm with the gravity constant.

//pseudocode
GRAVITY_NORM = 9.8;
accVector = normalize(cursor.pos - particle.pos);
//Apply acceleration: S = S0 + v0*dt + 0.5*g*dt*dt;
accNorm = particle.vel*dt + 0.5*GRAVITY_NORM*dt*dt; 
particle.pos = particle.pos + accVector*accNorm;

This computation actually doesn't calculates the gravity force, but the gravity acceleration (in Earth). If you want to get the real gravity force for a more general case you should attribute your cursor and particle with mass. However this system implies that you cursor should also be affected by the force and I'm assuming that it isn't your intention. Anyway, the equation for the force is

f = G * ( m1 * m2 ) * 1/r*r, where G is the gravity constant,
m1 and m2 are the masses and r is the distance between the bodies.
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.