Hi,
When landing from a jump and then moving immediately, my player’s character model will rotate the wrong way for exactly one frame.
The transform of the player GameObject does not change at all.
Any ideas what could be causing this?
I’ll put the code below, sorry if it’s long. But I’m not exactly sure what part is causing this.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterMovement : MonoBehaviour
{
private Camera cam;
public float moveSpeed = 10f;
public float thrust = 4000f;
Rigidbody rb;
[HideInInspector] public Vector3 desiredMoveDirection;
public bool grounded;
public float fallMultiplier = 4f;
Quaternion InAirRotation;
public float downForce = 100f;
public bool canMove;
// Start is called before the first frame update
void Start()
{
cam = Camera.main;
rb = GetComponent<Rigidbody>();
grounded = true;
canMove = true;
}
// Update is called once per frame
void Update()
{
}
void FixedUpdate()
{
if(canMove)//Movement Enabled
{
float horizontalAxis = Input.GetAxis("Horizontal");
float verticalAxis = Input.GetAxis("Vertical");
var forward = cam.transform.forward;
var right = cam.transform.right;
forward.y = 0f;
right.y = 0f;
forward.Normalize();
right.Normalize();
desiredMoveDirection = forward * verticalAxis + right * horizontalAxis;
//Add force to Rigidbody depending on the input.
rb.AddForce(desiredMoveDirection.normalized * moveSpeed * Time.deltaTime);
if(grounded)
{
//Always set the Y axis to 0. - This stops the character trying to look at itself.
Vector3 vel = rb.velocity;
vel.y = 0f;
rb.velocity = vel;
//Rotate to movement only when moving. When Idle, facing wherever player was walking.
if(desiredMoveDirection != Vector3.zero)
{
//Make player look at the direction they're moving.
transform.rotation = Quaternion.Lerp(transform.rotation,Quaternion.LookRotation(rb.velocity),10f);
}
} else
{
//If not grounded but input is detected.
if(desiredMoveDirection != Vector3.zero)
{
//Moving but not Grounded
//Look at direction of movement.
var newRotation = Quaternion.LookRotation(rb.velocity);
//Ignore the movement of the X and Z axis.
newRotation.x = 0;
newRotation.z = 0;
transform.rotation = Quaternion.Lerp(transform.rotation, newRotation, 10f);
}
}
}
//Actions - jumping, attacking, etc.
if(Input.GetButton("Jump"))
{
//Jump
if(grounded)
{
rb.AddForce(transform.up * thrust);
changeSpeed();
grounded = false;
}
}
if(rb.velocity.y <= 0)
{
//If the player is is the air - fall faster.
//rb.velocity += Vector3.up * Physics.gravity.y * (fallMultiplier -1) * Time.deltaTime;
}
if(rb.velocity.y < 0)
{
rb.AddForce(-Vector3.up * (downForce));
}
}
private void OnCollisionEnter(Collision other)
{
if(other.gameObject.tag == "Ground")
{
grounded = true;
moveSpeed = 6000f;
} else { grounded = false; }
}
void changeSpeed()
{
moveSpeed = moveSpeed / 2;
}
}