I have tried to figure out how to use AddForce instead of what I currently use because everyone I ask says that it is better and also more what i’m going for, but I don’t know how to change it because every time I try I just keep accelerating instead of stopping at the desired speed (i’m also not quite sure how it works). Please help!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public float speed = 12f;
public float sprintSpeed = 9f;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
void Update()
{
// Check if the player is grounded
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
// Reset the downward velocity when grounded
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
// Jumping
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * Physics.gravity.y);
}
}
void FixedUpdate()
{
// Handle horizontal movement with Rigidbody physics
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
// Apply horizontal movement
if (Input.GetKey(KeyCode.LeftShift))
{
rb.MovePosition(rb.position + move * sprintSpeed * Time.fixedDeltaTime);
}
else
{
rb.MovePosition(rb.position + move * speed * Time.fixedDeltaTime);
}
// Apply vertical jump velocity
if (velocity.y != 0)
{
rb.velocity = new Vector3(rb.velocity.x, velocity.y, rb.velocity.z);
velocity.y = 0;
}
}
}