So can someone tell me why this is causing my character not really to move but sorta shake instead of moving SMOOTHLY towards the direction the camera is pointing in?
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public Rigidbody rb;
public float movementSpeed = 100.0f;
void Start ( ) {
rb = GetComponent <Rigidbody> ( );
}
void Update ( ) {
Vector3 forward = transform.forward;
forward.y = 0;
rb.velocity = forward.normalized * movementSpeed * Time.deltaTime;
}
}
Rigidbody.velocity is already attenuated by Time.fixedDeltaTime, and physics is updated automatically in FixedUpdate.
By updating your velocity in Update and multiplying it by Time.deltaTime, you’re interfering with the fixed update and causing the velocity to jitter with the framerate.
Drop the Time.deltaTime and move this code into FixedUpdate.
So I upgraded my script a bit & I’ve now got the player moving in the direction the camera is facing, but is there any reason why my character floats a bit upward with this code when colliding against something & trying to continue moving forward?
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public Transform cam;
public Rigidbody target;
public float movementSpeed = 10.0f;
public float rotationSpeed = 1.0f;
void FixedUpdate ( ) {
Vector3 moveDirection = Vector3.zero;
if ( Input.GetKey ( KeyCode.W ) ) { moveDirection += cam.forward; }
if ( Input.GetKey ( KeyCode.S ) ) { moveDirection += -cam.forward; }
if ( Input.GetKey ( KeyCode.A ) ) { moveDirection += -cam.right; }
if ( Input.GetKey ( KeyCode.D ) ) { moveDirection += cam.right; }
moveDirection.y = 0.0f;
transform.position += moveDirection.normalized * movementSpeed * Time.deltaTime;
}
}