How do you calculate diagonal velocity?
I'm writing a game of sorts to practice some programming, and i've come across this problem. In my game, there are circles on the screen. And when the user clicks on the screen, the circles should move away from the click. I've got the x and y position of the point where the mouse button was pressed, and i have the x and y position of each cicle ob开发者_如何学Cject.
I found the center of the circles with the following code
float cx = circle.getX()+circle.getRadius();
float cy = circle.getY()+circle.getRadius();
And to find the distance from the edge of the circle to the mouse click I did this
float distance = (float) Math.sqrt( ((cx-x)*(cx-x)) + ((cy-y)*(cy-y)) ) - circle.getRadius();
Now after I check if the circle is close enough to the click, how can I split a velocity of 1f, for example, to the circle's variables vx and vy?
EDIT: Well actually I wanted acceleration, but I guess it's all the same.
This sounds like a job for sin
and cos
in java.lang.Math
: http://download.oracle.com/javase/6/docs/api/java/lang/Math.html .
Once you know the total velocity (1f
in your example above) and the angle (in radians), the horizontal component of the velocity is v * cos(angle)
, and the vertical component is v * sin(angle)
.
You probably need to negate the angle if you want to move it away.
To calculate an angle from horizontal and vertical distances, use atan2
.
Btw, if you don't want to take unnecessary square roots, and want to avoid the cost of computing series the way trigenometric functions do, take a look at http://www.youtube.com/user/njwildberger#p/u/368/9wd0i44vK04 .
Find the line from the mouse to the center of the circle and that should be the "force" vector. This vector will give you the direction, now you just need to figure out how distance affects the magnitude.
You could first find angle as Mike suggested and use cos and sin functions.
Or use:
velHoriz = velocity * (cx-x) / distance
velVert = velocity * (cy-y) / distance
精彩评论