Home > Blockchain >  How to make a small gun animation in unity without the gun slowly moving
How to make a small gun animation in unity without the gun slowly moving

Time:08-24

I'm new to unity and I'm experiencing something I am trying to make a gun animation making it go up and down but the problem is that after enough time the gun start moving from is original position.

Here is my code:

if (Input.GetMouseButton(0))
{
    StartCoroutine(bouncing());
    gun.GetComponent<Renderer>().material.color = Color.blue;
    range = 80f;
}

if (Input.GetMouseButtonDown(1))
{
    StartCoroutine(big_bouncing());
    gun.GetComponent<Renderer>().material.color = Color.red;
    range = 10f;
}

IEnumerator bouncing()
{
    gun.transform.position = new Vector3(gun.transform.position.x, gun.transform.position.y   bounce, gun.transform.position.z);
    yield return new WaitForSeconds(0.1f);
    gun.transform.position = new Vector3(gun.transform.position.x, gun.transform.position.y -  bounce, gun.transform.position.z);
}

IEnumerator big_bouncing()
{
    gun.transform.position = new Vector3(gun.transform.position.x, gun.transform.position.y   big_bounce, gun.transform.position.z);
    yield return new WaitForSeconds(0.1f);
    gun.transform.position = new Vector3(gun.transform.position.x, gun.transform.position.y - big_bounce, gun.transform.position.z);
}

Start:

start

End:

end

CodePudding user response:

I think this can have multiple causes

  • Concurrent Coroutines

    If someone smashes the mouse buttons it might happen that you are running multiple Coroutines at the same time leading to strange behavior

  • Global vs Local position

    You are using the transform.position which is the global Unity world space coordinates. In case this object is a child of anything that moves (your player) then it is wrong to use the world space position since during the 0.1 seconds of waiting your parent object might keep moving.

    You might rather want to use gun.transform.localPosition instead!

    gun.transform.localPosition  = Vector3.up * bounce;
    yield return new WaitForSeconds(0.1f);
    gun.transform.localPosition -= Vector3.up * bounce;
    
  • And finally (unlikely) there might be rounding errors for always adding and substracting float values (these should probably not be too notable though)

    But anyway to be sure you could cashe the original position and rather reset to that one instead of re-substracting the same distance

  • Related