I’m new to unity, and I’ve been trying to make a player controller that makes the player able to move in the XZ plane with a maximum velocity, independently of their velocity in the Y axis. So far this is what I’ve got, partly through copying from examples and just trial and error:
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
[SerializeField]
private float _moveSpeed;
[SerializeField]
private float _moveAcceleration;
[SerializeField]
private Rigidbody _rb;
private void Update()
{
Gamepad gamepad = Gamepad.current;
if (gamepad == null)
return;
Vector2 leftStick = gamepad.leftStick.ReadValue();
Move(leftStick);
}
private void Move(Vector2 direction)
{
// The Quaternion.Euler(0, -45, 0) is used to correct for perspective,
// as my camera is pointed at 45° with respect to the player.
Vector3 _moveDirection = Quaternion.Euler(0, -45, 0) * new Vector3(direction.x, 0, direction.y);
float _scaledMoveAcceleration = _moveAcceleration * Time.deltaTime;
_rb.AddForce(_moveDirection.x * _scaledMoveAcceleration, 0, _moveDirection.z * _scaledMoveAcceleration, ForceMode.VelocityChange);
//This is what I'm using to limit the player's velocity
_rb.velocity = Vector3.ClampMagnitude(_rb.velocity, _moveSpeed);
}
}
As you can see, my player has a Rigidbody component I linked to the script in the inspector. I also have a jump method that simply adds a vertical velocity when a button is pressed, but I removed it for clarity.
My main problem is that the player’s movement on the Y axis isn’t independant of its movement on the XZ plane, so if I drop the player from a cliff, it ends up falling faster if I don’t move the player in mid-air, and it stops accelerating when it reaches a the max velocity I set. I know this is caused by my usage of Vector3.ClampMagnitude, but I haven’t found an alternative that fits my needs.