Jump to content
GreenSock

Search In
  • More options...
Find results that contain...
Find results in...
Tee

Prevent animation speed spikes when animating to cursor

Recommended Posts

I have a circle which is supposed to be transformed in the direction of the cursor all time. 

 

node.addEventListener("mousemove", e => {
    const {x, y, width, height} = blob.current.getBoundingClientRect();
    
    gsap.timeline()
        .to(blob.current, {
            duration: 10,
            x: e.clientX - (x + width / 2),
            y: e.clientY - (y + height / 2),
            force3D: true,
            overwrite: "auto",
            ease: Linear.easeNone
        }, 0)
})

This is fine, but includes unwanted behavior: when being further away from the circle and rapidly changing direction and distance from the circle, there obviously will be a change in speed since the distance for the circle to travel in this 10 seconds gets shorter/longer. How can I ensure the same travel speed all the time, no matter where the cursor is?

Link to post
Share on other sites

For a consistent velocity you could pass a calculated value to duration something like this:

distance: https://www.purplemath.com/modules/distform.htm

distance equation simplified by @OSUblake : Math.hypot(x2 - x1, y2 - y1)

speed:  whatever you want

duration = distance/speed

 

EDIT: Pen has been updated to utilize Jack's function with Blakes equation (see following posts):

 

See the Pen gOrVEmE by Visual-Q (@Visual-Q) on CodePen

  • Like 3
Link to post
Share on other sites

Yep, @Visual-Q is exactly right. 

 

Minor note: you don't need to Math.abs() in there because you're squaring the numbers anyway. I'm pretty sure this simplified version would work: 

Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)

And here's a helper function that'd let you pass in individual values or you could even just pass in two points (objects that have x and y properties): 

function distance(x1, y1, x2, y2) {
  if (typeof(x1) === "object") {
    y1 = x1.y;
    x1 = x1.x;
    x2 = y1.x;
    y2 = y1.y;
  }
  return Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
}

 

  • Like 3
Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

×