Having issue with conflicting lerps through angleaxis… or something. (C#)

Updated on May 11, 2017 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
0 on May 11, 2017

Hey everyone! I’m trying to rotate a 2d object on the Z axis when you left click, and rotate it back to it’s start position when you release left mouse. I’m using Quaternion.AngleAxis to lerp the rotation, and I have a series of variables set up for each one.

  1. public bool rotateIt = false;
  2. private float rotateTimer = 0f;
  3. private float rotatePercentage = 0f;
  4. public bool unRotateIt = false;
  5. private float unRotateTimer = 0f;
  6. private float unRotatePercentage = 0f;

The code below is in the update:

  1. if (Input.GetKeyDown(KeyCode.Mouse0))
  2. {
  3. isClicking = true;
  4. waterParticles.GetComponent<ParticleSystem>().Play();
  5. rotateIt = true;
  6. unRotateIt = false;
  7. rotateTimer = 0f;
  8. }
  9. if (Input.GetKeyUp(KeyCode.Mouse0))
  10. {
  11. isClicking = false;
  12. rotateIt = false;
  13. if (transform.rotation.z >= 0f)
  14. {
  15. unRotateIt = true;
  16. unRotateTimer = 0f;
  17. }
  18. }
  19. if (rotateIt == true)
  20. {
  21. float startRotation = transform.rotation.z;
  22. float endRotation = 20f;
  23. rotateTimer += 40f * Time.deltaTime;
  24. float rotatePercentage = Mathf.Clamp(rotateTimer, 0f, 20f) / 20f;
  25. transform.rotation = Quaternion.AngleAxis(Mathf.Lerp(startRotation, endRotation, rotatePercentage), Vector3.forward);
  26. }
  27. if (unRotateIt == true)
  28. {
  29. float startUnRotation = transform.rotation.z;
  30. float unEndRotation = 0f;
  31. unRotateTimer += 40f * Time.deltaTime;
  32. float unRotatePercentage = Mathf.Clamp(unRotateTimer, 0f, 20f) / 20f;
  33. Debug.Log("unrotatepercentage: " + unRotatePercentage);
  34. transform.rotation = Quaternion.AngleAxis(Mathf.Lerp(startUnRotation, unEndRotation, unRotatePercentage), Vector3.forward);
  35. }

My expectation / hope is that this would cause the object to rotate over time in one direction when you click, and start rotating back the other direction when you release. This isn’t doing quite that though- when you hold left mouse the obj rotates in the first direction like expected, but when left mouse is released it instantly goes back to the start position instead of lerping. I’ve tried quite a few fixes for this but I can’t tell what’s causing it. Anyone know how to solve this issue? Much appreciated!

  • Liked by
Reply