# Accelerate object with slider problem

**URL:** https://discussions.unity.com/t/accelerate-object-with-slider-problem/648619
**Category:** Scripting
**Tags:** Scripting
**Created:** [December 10, 2016, 7:56pm UTC](https://discussions.unity.com/t/accelerate-object-with-slider-problem/648619 "2016-12-10T19:56:13Z")
**Posts on this page:** 14
**Page:** 1

<div class="post-metadata">

### Author: ![cruising](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/cruising/32/321126_2.png) [@cruising](https://discussions.unity.com/u/cruising)
#### Post date: [December 10, 2016, 7:56pm UTC](https://discussions.unity.com/t/accelerate-object-with-slider-problem/648619/1 "2016-12-10T19:56:13Z")

</div>

Hello!

Im working on a slider movement for objects, the slider and movement works for the object, but when you drag the slider to 100% or what ever value, the object also instantly accelerate with the slider value.

I have AccelRate in the FixedUpdate, but it is ignored of some reason, the thing is when you move the slider,  
the object shall accelerate slowly untill it reach the value of the slider + with the rate AccelRate ofc, not instantly.

Just like a car when you put the pedal to the metall, the car gain speed to the “rate” of your pedal level after some time.

CODE:

```csharp
public Slider Impulseslider;

    public void ImpulseSlider(string sliderID)
    {
        CurSpeed = Impulseslider.value;
    }

    void FixedUpdate ()
    {
        Slidervalue = CurSpeed;

        if (Impulseslider.value > 0)
        {
            Slidervalue = Mathf.Min(Slidervalue + AccelRate * Time.deltaTime, MaxSpeed);
            GetComponent<Rigidbody>().velocity = transform.forward * CurSpeed;
            impulse_active = true;
        } else {        
            Slidervalue = Mathf.Max(Slidervalue - DeAccel * Time.deltaTime * 1.5f, 0);
            GetComponent<Rigidbody>().velocity = transform.forward * CurSpeed;
            impulse_active = false;
        }
    }
}

```

---

<div class="post-metadata">

### Author: ![steego](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/steego/32/924633_2.png) [@steego](https://discussions.unity.com/u/steego)
#### Post date: [December 10, 2016, 10:56pm UTC](https://discussions.unity.com/t/accelerate-object-with-slider-problem/648619/2 "2016-12-10T22:56:57Z")

</div>

First, you should get in the habit of caching the rigidbody, as GetComponent is a somewhat expensive call.

The reason it doesn’t accelerate is that you are setting the speed to CurSpeed, which I assume is set by the slider in the ImpulseSlider method. All the math you use to update Slidervalue doesn’t seem to affect CurSpeed, and so is not used to set the speed at all.

Finally, I’d recommend you rather use AddForce instead of doing this calculation yourself, should be easier and probably more performant.

---

<div class="post-metadata">

### Author: ![cruising](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/cruising/32/321126_2.png) [@cruising](https://discussions.unity.com/u/cruising)
#### Post date: [December 10, 2016, 11:22pm UTC](https://discussions.unity.com/t/accelerate-object-with-slider-problem/648619/3 "2016-12-10T23:22:56Z")

</div>

> [@steego](#):
>
> First, you should get in the habit of caching the rigidbody, as GetComponent is a somewhat expensive call.
> 
> The reason it doesn’t accelerate is that you are setting the speed to CurSpeed, which I assume is set by the slider in the ImpulseSlider method. All the math you use to update Slidervalue doesn’t seem to affect CurSpeed, and so is not used to set the speed at all.
> 
> Finally, I’d recommend you rather use AddForce instead of doing this calculation yourself, should be easier and probably more performant.

I forgot to post this

```csharp
public Component Ship;
void Start()
    {
        Ship = GetComponent<Rigidbody>();
    }

```

The ship do accelerate from 0-100, its just that if you instantly drag the slider up to 50, the object also accelerate to 50 instead of accelerate slowly.  
Could you please post a example for AddForce?

---

<div class="post-metadata">

### Author: ![steego](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/steego/32/924633_2.png) [@steego](https://discussions.unity.com/u/steego)
#### Post date: [December 10, 2016, 11:41pm UTC](https://discussions.unity.com/t/accelerate-object-with-slider-problem/648619/4 "2016-12-10T23:41:56Z")

</div>

In your FixedUpdate, you’d do something like this

```auto
Ship.AddForce(transform.forward * AccelRate, ForceMode.Acceleration);

```

You then also want to limit the speed, as you have in your code.

```auto
if (Ship.velocity.sqrMagnitude > maxSpeedSqr) 
{
    Ship.velocity = Ship.velocity.normalized * maxSpeed;
}

```

maxSpeedSqr should here be the square of your wanted max speed. We use it together with sqrMagnitude in the if check, because computing square roots is a slow operation.

---

<div class="post-metadata">

### Author: ![steego](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/steego/32/924633_2.png) [@steego](https://discussions.unity.com/u/steego)
#### Post date: [December 10, 2016, 11:58pm UTC](https://discussions.unity.com/t/accelerate-object-with-slider-problem/648619/5 "2016-12-10T23:58:02Z")

</div>

To elaborate, I hope I’m not over-complicating things here, but while this task seems deceivingly simple it is actually part of a separate field of study in engineering called [control systems engineering](https://en.wikipedia.org/wiki/Control_engineering). To do this properly, what you need is something called a [PID controller](https://en.wikipedia.org/wiki/PID_controller).

Take a look at [this forum thread](https://forum.unity3d.com/threads/use-a-pid-loop-to-control-unity-game-objects.395831/) for an implementation you could try to use.

---

<div class="post-metadata">

### Author: ![cruising](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/cruising/32/321126_2.png) [@cruising](https://discussions.unity.com/u/cruising)
#### Post date: [December 11, 2016, 12:08am UTC](https://discussions.unity.com/t/accelerate-object-with-slider-problem/648619/6 "2016-12-11T00:08:21Z")

</div>

> [@steego](#):
>
> In your FixedUpdate, you’d do something like this
> 
> ```auto
> Ship.AddForce(transform.forward * AccelRate, ForceMode.Acceleration);
> 
> ```
> 
> You then also want to limit the speed, as you have in your code.
> 
> ```auto
> if (Ship.velocity.sqrMagnitude > maxSpeedSqr)
> {
> Ship.velocity = Ship.velocity.normalized * maxSpeed;
> }
> 
> ```
> 
> maxSpeedSqr should here be the square of your wanted max speed. We use it together with sqrMagnitude in the if check, because computing square roots is a slow operation.

Ok this works as it should do, but having problem to slow down the ship, i know its the else that isnt correct. But im not sure about how i should do it

```csharp
    void FixedUpdate ()
    {
        Slidervalue = CurentSpeed;

        if (CurentSpeed > MaxSpeed)
            CurentSpeed = MaxSpeed;
       

        if (Impulseslider.value > 0)
        {
            Ship.AddForce(transform.forward * CurentSpeed * AccelerateRate, ForceMode.Acceleration);
            impulse_active = true;

        } else {        

            Ship.AddForce(transform.forward * CurentSpeed * Deccelerate, ForceMode.Acceleration);
            impulse_active = false;
        }

        if (Input.GetAxis("Turn") > 0)
        {
            //GetComponent<Rigidbody>().MoveRotation = transform.forward * turnspeed;
        }
    }
}

```

---

<div class="post-metadata">

### Author: ![steego](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/steego/32/924633_2.png) [@steego](https://discussions.unity.com/u/steego)
#### Post date: [December 11, 2016, 12:20am UTC](https://discussions.unity.com/t/accelerate-object-with-slider-problem/648619/7 "2016-12-11T00:20:03Z")

</div>

Deccelerate needs to be a negative value in this case, or you can just put -Deccelerate.

---

<div class="post-metadata">

### Author: ![cruising](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/cruising/32/321126_2.png) [@cruising](https://discussions.unity.com/u/cruising)
#### Post date: [December 11, 2016, 12:26am UTC](https://discussions.unity.com/t/accelerate-object-with-slider-problem/648619/8 "2016-12-11T00:26:30Z")

</div>

> [@steego](#):
>
> Deccelerate needs to be a negative value in this case, or you can just put -Deccelerate.

That didnt work, i tried both ways and it keeps the speed it had when i turn the slider to a lower level

```csharp
Ship.AddForce(transform.forward * CurentSpeed - Decacelerate, ForceMode.Acceleration);

Ship.AddForce(transform.forward * CurentSpeed * -Decacelerate, ForceMode.Acceleration);

```

---

<div class="post-metadata">

### Author: ![steego](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/steego/32/924633_2.png) [@steego](https://discussions.unity.com/u/steego)
#### Post date: [December 11, 2016, 1:08am UTC](https://discussions.unity.com/t/accelerate-object-with-slider-problem/648619/9 "2016-12-11T01:08:34Z")

</div>

You probably need a much larger decelerate value then, as you need to overcome the forward momentum.

---

<div class="post-metadata">

### Author: ![cruising](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/cruising/32/321126_2.png) [@cruising](https://discussions.unity.com/u/cruising)
#### Post date: [December 11, 2016, 1:44am UTC](https://discussions.unity.com/t/accelerate-object-with-slider-problem/648619/10 "2016-12-11T01:44:33Z")

</div>

> [@steego](#):
>
> You probably need a much larger decelerate value then, as you need to overcome the forward momentum.

Doesnt matter if i have value 10000, it still dont slow down or stop of some reason

---

<div class="post-metadata">

### Author: ![Zaflis](https://avatars.discourse-cdn.com/v4/letter/z/85e7bf/32.png) [@Zaflis](https://discussions.unity.com/u/Zaflis)
#### Post date: [December 11, 2016, 4:53am UTC](https://discussions.unity.com/t/accelerate-object-with-slider-problem/648619/11 "2016-12-11T04:53:55Z")

</div>

Are you sure the slider actually goes negative?

```csharp
Debug.Log(Impulseslider.value);

```

---

<div class="post-metadata">

### Author: ![cruising](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/cruising/32/321126_2.png) [@cruising](https://discussions.unity.com/u/cruising)
#### Post date: [December 11, 2016, 3:16pm UTC](https://discussions.unity.com/t/accelerate-object-with-slider-problem/648619/12 "2016-12-11T15:16:01Z")

</div>

> [@Zaflis](#):
>
> Are you sure the slider actually goes negative?
> 
> ```csharp
> Debug.Log(Impulseslider.value);
> 
> ```

Yes i have the value of the slider shown in the inspector, it goes up and down with the on-screen slider + impulse\_active =true; bool is also working.

![](http://i65.tinypic.com/zyejrl.png)

---

<div class="post-metadata">

### Author: ![steego](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/steego/32/924633_2.png) [@steego](https://discussions.unity.com/u/steego)
#### Post date: [December 11, 2016, 9:11pm UTC](https://discussions.unity.com/t/accelerate-object-with-slider-problem/648619/13 "2016-12-11T21:11:03Z")

</div>

Take a look at the attached example that I threw together. It uses a simple PD controller to smooth out the forces, adjust the pk and pd variables to tune the controller.

Hope this helps?

[2882411–211662–sliderspeed.unitypackage](https://discussions.unity.com/uploads/short-url/nfdSS3xNcd3vWEZkEzmJUber7KE.unitypacka) (42.2 KB)

---

<div class="post-metadata">

### Author: ![cruising](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/cruising/32/321126_2.png) [@cruising](https://discussions.unity.com/u/cruising)
#### Post date: [December 12, 2016, 11:02am UTC](https://discussions.unity.com/t/accelerate-object-with-slider-problem/648619/14 "2016-12-12T11:02:19Z")

</div>

> [@steego](#):
>
> Take a look at the attached example that I threw together. It uses a simple PD controller to smooth out the forces, adjust the pk and pd variables to tune the controller.
> 
> Hope this helps?

Idk if im doing something wrong or if it is the script, if i change the max speed to 60 as i use as standard, the object goes instantly to the end of the universe and unity getting a error and pausing, also the slider goes from the left side screen all the way to the right side.  
ERROR

```csharp
rigidbody.force assign attempt for 'Romulan_BOP' is not valid. Input force is { -0.000000, -0.000000, -Infinity }.
UnityEngine.Rigidbody:AddForce(Vector3, ForceMode)

```

But i did this earlier today and this works as i want it to do, my next step is to make it turn in a curve with banking, and so far i have failed to do so.

```csharp
    void FixedUpdate ()
    {
        CurrentAccelerate = Ship.velocity.magnitude;
        ImpulsSlidervalue = CurentSpeed;

        if (CurentSpeed > MaxSpeed)
            CurentSpeed = MaxSpeed;   

        if (Impulseslider.value > 0)
        {
            targetPosition += transform.forward * CurentSpeed * Time.deltaTime;
            impulse_active = true;

        } else {
            targetPosition += transform.forward * CurentSpeed * Time.deltaTime;
            impulse_active = false;
        }

        if (Input.GetAxis("Turn") != 0)
        {
            //targetPosition += transform.right * Input.GetAxisRaw("Horizontal") * CurentSpeed * Time.deltaTime;
        }

        var currentPosition = SgtHelper.Dampen3(transform.position, targetPosition, AccelerateRate, Time.deltaTime, 0.1f);
        SgtHelper.SetPosition(transform, currentPosition);
        }
    }

```
