My physics based player controller is slippery awkward and the player cant go faster than its max speed when affected by outside forces like and explosion is there any way to fix these problems?
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
// Movement Variables
private Vector3 movement;
public float speed;
public float groundSpeed = 50f;
public float airSpeed = 20f;
public float maxSpeed = 10f;
public float jumpForce = 5f;
public float groundDistance = 1.1f;
public Rigidbody rb;
// Camera Variables
public float sensitivity = 200;
public Transform player;
public Transform cam;
private float xRotation = 0f;
// Runs when the game starts
private void Start()
{
rb = GetComponent<Rigidbody>();
Cursor.lockState = CursorLockMode.Locked;
}
private void Update()
{
// Runs Camera Function
Look();
}
// Runs every physics update
private void FixedUpdate()
{
// Runs Movement Function
Movement();
}
// Does Movment Stuff
private void Movement()
{
// AddsForce to move the player using wasd or arrow keys
float x = Input.GetAxisRaw("Horizontal");
float z = Input.GetAxisRaw("Vertical");
rb.AddForce(transform.forward * z * speed);
rb.AddForce(transform.right * x * speed);
// Changes player's acceleration in the air
if (IsGrounded() == false)
{
speed = airSpeed;
}
if (IsGrounded() == true)
{
speed = groundSpeed;
}
// Uses rb.velocity to jump instead of addforce
if (Input.GetButton("Jump") && IsGrounded() == true)
{
rb.velocity = new Vector3(rb.velocity.x, jumpForce, rb.velocity.z);
}
// Limits Speed
if (rb.velocity.magnitude > maxSpeed)
{
rb.velocity = rb.velocity.normalized * maxSpeed;
}
}
// Checks If Player Is Grounded
private bool IsGrounded()
{
return Physics.Raycast(transform.position, Vector3.down, groundDistance);
}
// Does First Person Camera Stuff
private void Look()
{
float mouseX = Input.GetAxisRaw("Mouse X") * sensitivity * Time.deltaTime;
float mouseY = Input.GetAxisRaw("Mouse Y") * sensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
cam.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
player.Rotate(Vector3.up * mouseX);
}
}
Edit: I’m also looking for an effective coded gravity solution that works much like the default unity gravity