Here is my movement code. I narrowed down the problem and realized that in my movement, it is constantly adding force trying to get the player to the target velocity. So the real problem was that this force was stopping any recoil in the x and z axis from achieving their desired effect, while the y axis functioned normally, causing the player to have too much recoil in the y-axis.
I do not know how I can fix it while keeping the movement similar, and I would appreciate if anyone has any ideas.
using UnityEngine;
public class PlayerMotor : MonoBehaviour
{
public PlayerInput input;
public PlayerState state;
public float groundSpeed = 6f;
public float airSpeed = 4f;
public float acceleration = 10f;
public float jumpForce = 5f;
public float sprintMultiplier = 1.5f;
float currentSprintMult = 1f;
Rigidbody rb;
void Awake()
{
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
}
void FixedUpdate()
{
HandleMovement();
HandleJump();
}
void HandleMovement()
{
Vector2 moveInput = input.Move;
Vector3 moveDir =
transform.right * moveInput.x +
transform.forward * moveInput.y;
float speed = (state.GroundedState == GroundedState.Grounded)
? groundSpeed
: airSpeed;
if (state.MovementState == MovementState.Sprinting)
{
currentSprintMult = sprintMultiplier;
}
else
{
currentSprintMult = 1.0f;
}
speed *= currentSprintMult;
Vector3 targetVelocity = moveDir * speed;
Vector3 currentVelocity = rb.linearVelocity;
Vector3 velocityChange = targetVelocity - new Vector3(currentVelocity.x, 0f, currentVelocity.z);
rb.AddForce(velocityChange * acceleration, ForceMode.Acceleration);
}
void HandleJump()
{
if (state.GroundedState != GroundedState.Grounded)
return;
if (input.JumpPressed)
{
Vector3 vel = rb.linearVelocity;
vel.y = 0f;
rb.linearVelocity = vel;
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
input.ConsumeJump();
}
}
public void FullRecoil(Quaternion dir, float strength)
{
Vector3 recoilDir = -(dir * Vector3.forward).normalized;
rb.AddForce(recoilDir * strength, ForceMode.Impulse);
}
}