Hi, so, I am trying to make a 3D character controller, where if I press down (using the new input system) the player runs backwards, but with the current code I wrote, the player just completely flips around and faces the opposite direction? How do I fix this? Do I need to re-write everything?
https://youtu.be/FgVX2jotywE Here is a video of how it looks.
Here is the current code I wrote:
public class ThirdPersonController : MonoBehaviour
{
//Input Fields
private ThirdPersonActionsAsset playerActionAsset;
private InputAction move;
//Movement Fields
//Physics
private Rigidbody rigbod;
//
//Floats
[SerializeField] private float movementForce;
[SerializeField] private float jumpForce;
[SerializeField]private float maxSpeed;
//
//Other
private Vector3 forceDirection = Vector3.zero;
//Camera
[SerializeField] private Camera playerCamera;
//Animation
private Animator animator;
private void Awake()
{
rigbod = this.GetComponent<Rigidbody>();
playerActionAsset = new ThirdPersonActionsAsset();
animator = this.GetComponent<Animator>();
}
private void OnEnable()
{
playerActionAsset.Player.Attack.started += DoAttack;
move = playerActionAsset.Player.Move;
playerActionAsset.Player.Enable();
}
private void OnDisable()
{
playerActionAsset.Player.Attack.started -= DoAttack;
playerActionAsset.Player.Disable();
}
private void FixedUpdate()
{
forceDirection += move.ReadValue<Vector2>().x * GetCameraRight(playerCamera) * movementForce;
forceDirection += move.ReadValue<Vector2>().y * GetCameraForward(playerCamera) * movementForce;
rigbod.AddForce(forceDirection, ForceMode.Impulse);
forceDirection = Vector3.zero;
LookAt();
}
private void LookAt()
{
Vector3 direction = rigbod.velocity;
direction.y = 0f;
if (move.ReadValue<Vector2>().sqrMagnitude > 0.1f && direction.sqrMagnitude > 0.1f)
{
this.rigbod.rotation = Quaternion.LookRotation(direction, Vector3.up);
}
else
{
rigbod.angularVelocity = Vector3.zero;
}
}
private Vector3 GetCameraForward(Camera playerCamera)
{
Vector3 forward = playerCamera.transform.forward;
forward.y = 0;
return forward.normalized;
}
private Vector3 GetCameraRight(Camera playerCamera)
{
Vector3 right = playerCamera.transform.right;
right.y = 0;
return right.normalized;
}
private void DoAttack(InputAction.CallbackContext context)
{
animator.SetTrigger("Attack");
}
private bool IsGrounded()
{
Ray ray = new Ray(this.transform.position + Vector3.up * 0.25f, Vector3.down);
if (Physics.Raycast(ray, out RaycastHit hit, 0.3f))
return true;
else
return false;
}
}