Question by
AlexT_IH · Aug 22, 2016 at 06:47 PM ·
unity 5bugmovement script
Movement script flips character upside down
I made the following script, which applies forward movement, while rotating the character, to simulate WSAD movement.
void ApplyRotation(float h, float v)
{
//We need to be able to turn around the Y axis using the arrow/WASD keys,
//so we'll make a rotation that enables this.
float turnVal = (h == 0f) ? v : h;
tiltZ = Utilities.ClampAngle(tiltZ, 0f, 360f) + turnVal;
Vector3 lv = new Vector3(h, 0, v);
var nrot = Quaternion.LookRotation(lv,transform.up);
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(transform.rotation.eulerAngles + nrot.eulerAngles), Time.deltaTime * turningSpeed);
}
It works just fine at first, but as the player keeps moving, they are slowly flipped upside down. I have tracked the bug to this script, but am unable to find what is wrong with it. Anyone have any ideas?
PS: The code for Utilities.ClampAngle()
is below.
public static float ClampAngle(float angle, float minAngle, float maxAngle)
{
int full_rotations = (angle > 360f || angle < -360f) ? Math.Abs(Convert.ToInt32(angle)) % 360 : 0;
//We need to either subtract (in case angle is positive) or
//add (in case angle is negative) any full rotations (360 degrees)
//before we clamp.
//This is equivalent to:
//do
//{
// if(angle < -360)
// angle += 360f;
// if(angle > 360)
// angle -= 360f;
//} while (angle < -360f || angle > 360f);
if (full_rotations > 0)
angle += Mathf.Sign(angle) * (-1) * full_rotations * 360f;
return Mathf.Clamp(angle, minAngle, maxAngle);
}
Comment
Your answer
