I have been trying to use WSAD to control a character to rotate and move “forward” along the direction according to the input from the Keys. it works well during its movement period. but when I stop it, which means I release my control on the keys. it stops its movement, but sometimes ,it will rotate itself for a degree between 10-20.
Most important is , I mean to only use Rigidbody, and its MovePosition and MoveRotation methods.
I use GetAxisRaw on “Hztl” and “Vtcl” to get Input calls, and use the input as character’s target direction, then set a targetRotation variable to store the direction got from Quaternion.LookRotation.
then MoveRotation it with info from Quaternion.Lerp
I am stuck here for 2 days, please anyone can help me solve it.
below is my code, please copy it and add it to a object of your scene and have a look:
Rigidbody rb;
private float h_Input;
private float v_Input;
private Vector3 direction;
public float moveSpeed = 8;
public float rotateSpeed = 20;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
}
private void FixedUpdate()
{
Move();
}
private void Move()
{
h_Input = Input.GetAxisRaw("Horizontal");
v_Input = Input.GetAxisRaw("Vertical");
if (h_Input!=0|| v_Input !=0)
{
direction = new Vector3(h_Input, 0, v_Input);
Quaternion rotationTarget = Quaternion.LookRotation(direction, Vector3.up );
rb.MoveRotation(Quaternion.Lerp(rb.rotation,rotationTarget, rotateSpeed * Time.fixedDeltaTime));
rb.MovePosition(rb.position + transform.TransformDirection(Vector3.forward) * moveSpeed * Time.fixedDeltaTime);
}
},