Hi, I am implementing a player movement with rb.AddForce so that if I want to apply forces later i can
I created a basic script that handles that but i dont know how to apply a force for jumping correctly
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Header("Movement Data")] [SerializeField]
private float maxSpeed = 5f;
[SerializeField] private float acceleration = 5f;
[SerializeField] private float deceleration = 5f;
[SerializeField] private float jumpForce = 5f;
private PlayerInputHandler playerInput;
private Rigidbody2D rb;
void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
void Start()
{
playerInput = PlayerInputHandler.Instance;
}
void FixedUpdate()
{
HandleMove();
HandleJump();
}
private void HandleMove()
{
if (playerInput.IsMoving)
{
rb.AddForce(new Vector2(playerInput.MoveInput * acceleration, 0f), ForceMode2D.Force);
if (rb.linearVelocity.magnitude > maxSpeed)
{
rb.linearVelocity = rb.linearVelocity.normalized * maxSpeed;
}
}
else
{
rb.linearVelocity = new Vector2(Mathf.MoveTowards(rb.linearVelocity.x, 0, deceleration * Time.fixedDeltaTime), rb.linearVelocity.y);
}
}
private void HandleJump()
{
if (playerInput.JumpInput)
{
rb.AddForce(new Vector2(rb.linearVelocity.x, jumpForce), ForceMode2D.Impulse);
}
}
}
When jumping, the jump force is just weird and is being applied only for a certain period of time so that you see the player going fast up, then slow up, then go down
Also if jumpForce is too strong it just ignore the direction and just go almost up.