Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

decreasing and increasing speed over time

Discussion in 'Scripting' started by WeirderChimp, Jan 7, 2014.

  1. WeirderChimp

    WeirderChimp

    Joined:
    Nov 21, 2012
    Posts:
    26
    hey

    im making a game with some AI and ive got my ai so when its with in 30 units of the player it runs and 10 units it walks and i change the speed from 5 when its in run distance to 2 when its in walk distance but i just use ---> speed = walkspeed; OR speed = runspeed; how would i make it more smooth because with my animation it looks bad when the animation suddenly gets slower

    for example

    if (AI is with in walkspeed which is 10)
    slowly decrease speed until it is = to walkspeed at a rate of (a variable)

    AND same for going to runspeed

    any help would be great
    i just cant get my head around how to animate my AI so it looks good

    thanks ~Scott
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    I'd use Mathf.SmoothDamp for this. Unfortunately the example in the docs for this one isn't as good as most of them... basically you just need to keep track of three things to use this: (1) the current speed; (2) the target speed (how fast you want to go), and (3) a "velocity" which is how fast the variable (speed) in this case is changing, and which you shouldn't worry about. Just keep it around and pass it in to SmoothDamp each time. Something like this:

    Code (csharp):
    1.  
    2.   public float targetSpeed;
    3.   float speed;
    4.   float speedDV;  // "damp velocity"
    5.  
    6.   void Update() {
    7.     speed = Mathf.SmoothDamp(speed, targetSpeed, ref speedDV, 0.5f);
    8.     // now, do whatever you're currently doing with speed!
    9.   }
    10.  
    That last parameter to SmoothDamp is the approximate time it should take to reach the new target speed. So, based on the distance, set targetSpeed (rather than speed), and then use the code above to get the actual speed.