Hello Unity users, I’m making an FPS so I would like to achieve the best FPS controller that handles smooth slopes limit, anti-slope sliding, ect… So I wrote this script : (see gifs below)
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (Rigidbody))]
public class Player_Movement: MonoBehaviour {
[Header("Components")]
public Rigidbody rb;
[Header("Stats")]
public float speed;
public float runFactor;
public bool grounded;
[Header("Offsets")]
public LayerMask layers;
public float speedScale;
[Header("Run-Time values")]
public Vector2 rawAxis;
public Vector3 normalizedAxis;
public Vector3 smoothedAxis;
public Vector3 localAxis;
RaycastHit hit;
public Vector3 force;
void Start (){
}
void Update (){
rawAxis = new Vector2 (Input.GetAxisRaw ("Horizontal"), Input.GetAxisRaw ("Vertical"));
normalizedAxis = new Vector3 (rawAxis.x, 0f, rawAxis.y).normalized;
smoothedAxis = new Vector3 (Mathf.SmoothStep (smoothedAxis.x, normalizedAxis.x, Time.deltaTime * 15f), 0f, Mathf.SmoothStep (smoothedAxis.z, normalizedAxis.z, Time.deltaTime * 15f));
localAxis = transform.TransformDirection (smoothedAxis);
}
void FixedUpdate () {
float totalSpeed = speed * speedScale;
var draggedVel = Vector3.zero;
draggedVel.x = rb.velocity.x * 0.75f;
draggedVel.y = rb.velocity.y;
draggedVel.z = rb.velocity.z * 0.75f;
rb.velocity = draggedVel;
Debug.DrawRay (transform.position, Vector3.down * 1f);
if(Physics.Raycast(transform.position, Vector3.down, out hit, 100f, layers)){
Debug.DrawRay (hit.point, hit.normal * 0.5f, Color.magenta, 2f);
}
force = Vector3.Cross (Vector3.Cross (hit.normal, localAxis), hit.normal) * totalSpeed;
rb.AddForce (force, ForceMode.VelocityChange);
}
void OnDrawGizmos(){
Gizmos.color = Color.green;
Gizmos.DrawSphere (hit.point + force, 0.3f);
}
}
When I’m walking down slopes, it’s working like a charm, but I go up a slope it’s doing a weird thing, and I don’t know why.
The green sphere is the result of “hit.point + force”.
If someone could help me it would be appreciable,
yours sincerely,
Tom.