Jump to content
Search Community

Random x,y values on refresh of timeline

nkc524 test
Moderator Tag

Go to solution Solved by GreenSock,

Recommended Posts

Hi there,

I can't seem to get this working. I have a bunch of bubbles that I want to yoyo, and once that yoyo is complete I want it to go towards a new, random direction (both x and y). I want the initial x,y starting values to remain the same, but the bubbles to move towards a new directed for each timeline refresh.

Is this possible? Below is everything I have tried

PS I would submit a codepen, but the code is complicated since it deals with JSX. I can't seem to get it working on codepen
 
useLayoutEffect(() => {
   
    bubArray.forEach(x => {
      gsap.set((`.bubble-${x}`), {
        position: 'absolute',
        x: gsap.utils.random(0, 500),
        y: gsap.utils.random(0, 500)
      })
 
      let btl = gsap.timeline()
      btl.to(`.bubble-${x}`, {
        y: gsap.utils.random(0, 500),
        x: gsap.utils.random(0, 500),
        duration: 3,
        yoyo: true,
        repeat: 1,
        repeatRefresh: true,
        onComplete: () => {btl.invalidate(); btl.restart(true)}
      })
  })
Link to comment
Share on other sites

  • Solution

I see several problems: 

  1. You're using gsap.utils.random() which does indeed return a random value, but you're plugging that one specific value into the tween, thus when you invalidate() and it looks at those again, it just sees the same number. You're not actually using a function-based value or a dynamic string which would get evaluated each time fresh. 
  2. I'm not sure why you're using a timeline at all. Seems wasteful. Not "wrong", just a bit odd. 
  3. Why use an onComplete that invalidates and restarts rather than just using repeat: -1 (infinite)? You've already got the repeatRefresh doing the invalidation for you, so it just seems redundant. 

There are MANY ways to accomplish what you're after - here's one: 

See the Pen jOKBxKG?editors=1010 by GreenSock (@GreenSock) on CodePen

 

Does that help? 

  • Like 2
Link to comment
Share on other sites

Hi there!

This is exactly what I was looking for. I was unsure of how to use the "random" function, as I am still settling in with using GSAP.  I only used the timeline because I thought it was necessary in order to use the invalidate() and reset() functions, but your solution is exactly what I want. 

Thanks so much for the quick reply and help!

  • Like 1
Link to comment
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.
×
×
  • Create New...