Question by
AlexT_IH · Aug 14, 2016 at 02:18 PM ·
scripting problemmovementflippingunity 5.1.1
WSAD Movement performs unwanted flipping of character
I am making a 3rd person shooter game, and the following script part is supposed to handle the character's movement and animation (I have a rather old type of model available for my game's purposes), using the Arrow Buttons or the WSAD keys. It is supposed to simply apply rotation (left/right) to the character while moving it forward.
void AnimMovement()
{
//We receive the raw values for the Horizontal and Vertical input axes (-1, 0 or 1)...
var movementV = GetInputValues();
float h = movementV.first;
float v = movementV.second;
//And the current state of the player's animator.
var curState = playerAnimator.GetCurrentAnimatorStateInfo(0);
//For optimization purposes, if there is no input (h = v = 0), then we return here.
if (h == 0f && v == 0f)
{
//We are not moving.
playerAnimator.SetFloat("Speed", 0f);
return;
}
//if (h != PrevH)
playerAnimator.SetFloat("Speed", 1f);
//We will move our player, only if the current state of their Animator is the LocomotionState.
//This is to prevent our player from moving when dead.
if (curState.shortNameHash == Hashes.LocomotionHash)
{
cc.SimpleMove(transform.forward * speed);
}
if(tag != Tags.AIPlayerController)
ApplyRotation(h, v);
PrevH = h;
PrevV = v;
}
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);
}
Pair<float, float> GetInputValues()
{
float h, v;
if (gameObject.tag == Tags.PlayerController)
{
//PlayerController input.
h = Input.GetAxisRaw("Horizontal");
v = Input.GetAxisRaw("Vertical");
}
else
{
//AIPlayerController input.
h = nav.nextPosition.x;
v = nav.nextPosition.z;
}
return new Pair<float, float>(h, v);
}
The problem is that, while at first the character moves well, after a while it simply goes upside down. I suspect it has something to do with the rotation being applied to the character, but I am stumped.
Does anybody have any idea why this is happening?
Comment