Make the ball on canvas, move slowly towards the mouse

im trying to make the ball move slowly towards my mouse.

Im using paper.js, which is a simple animation library. Using this, I have a ball moving around the screen. Here are some of the properties of the ball:

balls [0] .vector.angle - its direction. 0 = right, 90 = down, 180 = left, etc. And all between

balls [0] .point.x - its position x and y for position y.

balls [0] .vector.length - its speed.

I put a mouse move event, and I think ive got the angle between them below:

    canvas.addEventListener("mousemove", function(e){

    var a = balls[0].point.y - e.clientY;
    var b = balls[0].point.x - e.clientX;
    var angleDeg = Math.atan2(a, b) * 180 / Math.PI;
});

So, I made the ball motionless to test this, and moved the mouse around it. To the left of the ball gives me 0 degrees. Above gives me 90. On the right gives me 180. And under the ball gives me -90, etc. And everything in between.

, , :

var distance = Math.sqrt( a*a + b*b );

var maxSpeed = 20; 
balls[0].vector.length = (distance/30 > maxSpeed) ? maxSpeed : distance/30;

, , . , . , , , .

+4
2

, . , , .

var MAX_SPEED = 20;
var MIN_SPEED = 0.25; // Very slow if close but not frozen.
var ATTRACTION = 0.5; 
var diff_y = e.clientY - balls[0].point.y;
var diff_x = e.clientX - balls[0].point.x;
var distance = Math.sqrt(diff_x * diff_x + diff_y * diff_y)
var speed = distance * ATTRACTION;
if (speed > MAX_SPEED) speed = MAX_SPEED;
if (speed < MIN_SPEED) speed = MIN_SPEED;
// The rates along axes are proportional to speed;
// we use ratios instead of sine / cosine.
balls[0].point.x += (diff_x / distance) * speed;
balls[0].point.y += (diff_y / distance) * speed;

, .

+1

deltas

var deltaX = e.clientX - balls[0].point.x;
var deltaY = e.clientY - balls[0].point.y;
var distance = Math.sqrt(deltaX*deltaX+deltaY*deltaY);
var maxSpeed = 20; 
balls[0].vector.length = (distance/30 > maxSpeed ) ? maxSpeed  : distance / 30;
balls[0].point.x = balls[0].point.x + (balls[0].vector.length * deltaX / distance);
balls[0].point.y = balls[0].point.y + (balls[0].vector.length * deltaY / distance);

,

+1

Source: https://habr.com/ru/post/1696131/


All Articles