I have attempted to create a movement system that only uses player input (no physics or rigidbodies), and I want the player to interact dynamically with barriers and walls, sliding across them if the player tries to run against them. I have created a basic flowchart showing how I want to pull this off:
However, the way I have implemented this so far has resulted in strange and glitchy behavior, most notably when trying to rotate the movement vector so the player will travel perpendicular to a wall they are running against.
Here is the script I have (sorry if it’s a mess, it’s a Frankenstein’s monster of forum posts, previous assets, and novel code that I haven’t gotten to clean up yet):
public class PlayerMovement : MonoBehaviour
{
public Vector3 dir;
public Vector3 move;
public Vector3 normal;
public float speedC;
public float angle;
public RaycastHit ray;
public bool collision;
public Quaternion rotation = Quaternion.identity;
// Use this for initialization
void Start()
{
angle = 90f;
}
void Update()
{
move = transform.position;
//Get input
var inputV = Input.GetAxis("Vertical");
var inputH = Input.GetAxis("Horizontal");
//Test for collision with wall
if (Physics.SphereCast(move, 0.25f, move, out ray, 0.25f))
{
Debug.Log("Collision");
collision = true;
}
else
{
collision = false;
}
//placeholder vector for input direction
dir.x = inputH;
dir.z = inputV;
//determine angle between wall and move vector
if (collision)
{
angle = Vector3.Angle(dir, ray.normal);
Vector3 cross = Vector3.Cross(dir, ray.normal);
if (cross.y < 0) angle = -angle;
}
else
{
angle = 90;
}
//debugging variables
normal = ray.normal;
rotation.eulerAngles = new Vector3(0, angle, 0);
//slow player down based on the angle of the wall
float speed = speedC * (angle/90);
Vector3 up = new Vector3(0, angle, 0);
move.x += inputH * Time.deltaTime * speed;
move.z += inputV * Time.deltaTime * speed;
//rotate the move vector
if (collision)
{
move = move - transform.position;
move = Quaternion.Euler(0, angle, 0) * move;
move = move + transform.position;
}
//move the player
transform.position = move;
}
}
This is currently very glitch as it is, phasing through walls and vibrating intensely when up against a wall, as if it’s only sometimes rotating properly. If anyone has any insight on how to properly do any of this, please let me know.