Hey Everyone,
I’ve tried countless times to get movement that is realistic and snappy on ground and reacts normally in air. The type of movement I’m looking for is similar to the likes of Slope as I’m trying to recreate it. I’ve gone through so many different versions of code and have come up with this, its just a mess, it reacts decently enough on ground but has zero realism in the air, leading to my player slowly gliding up ramps and slowly gliding down.
Please if anyone can help either with the code, point me towards a tutorial or explain a different way to me it would be much appreciated. I’ve spent far too long on what seems to maybe be an easy fix right under my nose. Thanks in advance.
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class MovePlayer : MonoBehaviour
{
[Header("Movement")]
public float strafeSpeed;
public float forwardSpeed;
public float maxSpeed;
public float fasterForce = 2;
private bool isGrounded;
public float gravity = 9.8f; // Adjust the gravity force as needed
public float airDrag = 0.1f; // Adjust the air drag to control air resistance
[SerializeField] private Rigidbody rb;
public float moveForce = 10f;
public float rotationSpeed = 10f;
public float jumpForce = 5f;
// Start is called before the first frame update
void Start()
{
rb.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
// Check if the player is on the ground
isGrounded = Physics.Raycast(transform.position, Vector3.down, 0.1f);
// Handle input for movement
float horizontalInput = Input.GetAxis("Horizontal") * strafeSpeed;
Vector3 moveDirection = new Vector3(horizontalInput, 0, forwardSpeed).normalized;
// Apply force for movement
if (Mathf.Abs(rb.velocity.magnitude) < maxSpeed)
{
rb.AddForce(moveDirection * moveForce, ForceMode.Acceleration);
}
// Jumping (you can modify this based on your requirements)
if (isGrounded && Input.GetButtonDown("Jump"))
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.VelocityChange);
}
// Apply a downward force for more natural gravity
if (!isGrounded)
{
rb.AddForce(Vector3.down * (Mathf.Abs(Physics.gravity.y)* 0.5f), ForceMode.Acceleration);
}
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.down, out hit, 0.5f))
{
Vector3 slopeNormal = hit.normal;
Vector3.OrthoNormalize(ref slopeNormal, ref moveDirection);
Vector3 slopeForce = slopeNormal * (Vector3.Dot(Vector3.up, slopeNormal) * moveForce * 0.5f);
rb.AddForce(slopeForce, ForceMode.Acceleration);
}
}
}