2
\$\begingroup\$

I want to

  1. gradually stop the car animation as it collides with another car
  2. gradually speed up the car animation as it exits the collider

I have two ways to achieve this.

  1. Update
  2. Co-routine

For co-routine I used this piece of code:

IEnumerator IncreaseSpeedGradually1(AnimationControlSpeed lastGOHitScript)
{
    //stop if decrease speed in progress
    StopCoroutine("DecreaseSpeedGradually");
    float decrementValue = ((lastHitVehicleSpeed / 2) * 2);
    while (lastGOHitScript.Speed <= lastHitVehicleSpeed)
    {
        lastGOHitScript.Speed += decrementValue * Time.deltaTime;
        yield return 0;
    }
    //setting speed to the last speed
    lastGOHitScript.Speed = lastGOHitScript.iniSpeeed;
}

and for the update-based approach I just added this criteria to the method:

if (carAnimState == carAnimationState.starting)
{
    carAnimState = carAnimationState.running;
}

if (carAnimState == carAnimationState.stoping)
{

    carAnimState = carAnimationState.running;
}

These are the two ways I thought about using. I wanted to ask which is right way to do this job? To slow down animation speed and hence get my objective? I guess co-routines can be problematic later in my game. Are there performance concerns for using one of the approaches?

\$\endgroup\$
1
  • \$\begingroup\$ float decrementValue = ((lastHitVehicleSpeed / 2) * 2); // are you sure about this? \$\endgroup\$
    – zcabjro
    Commented Jun 25, 2016 at 14:28

1 Answer 1

1
\$\begingroup\$

Why just slow down the animation? If you want a slow-mo effect, just slowing the animation means everything else is still going to move at normal speed around you. For that, I would recommend lowering Time.timeScale, which slows down time for everything, including the physics engine.

And to answer your question, neither. The best way is to use OnCollisionEnter() and OnCollisionExit(). These are events built into Unity for collision detection. So you would say:

void OnCollisionEnter(Collider other)
{
    if(// other collider is a car)
    {
        Time.timeScale = 0.1f; // One tenth the speed of realtime.
    }
}

void OnCollisionExit(Collider other)
{
    if(// other collider was a car)
    {
        Time.timeScale = 1.0f; // Back to realtime.
    }
}

So you attach that script to your player's car, and then whenever they collide with another car, time will slow down until they stop colliding with that other car, at which point time will speed up again back to normal. There would of course be occasions in which the player's car won't stop colliding with the other car, so you'd probably want to speed time up again after a set amount of time anyway.

\$\endgroup\$
1
  • \$\begingroup\$ it will slow down everywhere but i want to mess with only collided cars \$\endgroup\$ Commented Aug 3, 2016 at 10:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .