R
R
Roman Rakzin2016-01-30 18:40:34
css
Roman Rakzin, 2016-01-30 18:40:34

The calculation of the speed of the ball, depending on the distance from it?

There is a ball in the center - I move the mouse to a certain distance from it, and if this distance is large, it moves faster on the coordinate grid. If the cursor is on the ball, it is standing. There is an example in the game agar.io.
How to implement this calculation?
Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twobomb, 2016-01-31
@twobomb

Distance formula between two points
ball - ball, mouse - mouse
dist = Math.sqrt(Math.pow(ball.x - mouse.x, 2) + Math.pow(ball.y - mouse.y, 2));/ /ball.x,ball.y - the center of the ball, if the ball is positioned from the upper left corner, then the center will be ball.x + ball.width/2, ball.y + ball.y + ball.height/2
// then randomly we set the dependence of speed and distance to our own, for example,
speed = 0;
maxSpeed ​​= 50;
if(dist > 10)//If the distance is less than 10px to the ball, then the speed will be 0
speed = dist/5;
if(speed > maxSpeed)
speed = maxSpeed;
//also don't forget to calculate the angle between the ball and the mouse and move the ball like this
ball.x += speed * Math.cos(ball.angle);//Angle must be in radians!!
ball.y += speed * Math.sin(ball.angle);//Angle must be in radians!!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question