- Home /
Rigidbody Player Controller sticking to walls
My player controller is a rigidbody so whenever I'm running at a wall my player would get stuck instead of sliding down. Another thing I tried was using a physics material, but that just makes it so my player feels as if it's sliding on ice and is pretty uncontrollable. I'm also pretty new at programming so let me know if there are any improvements I could do to tweak my code, it would be greatly appreciated!
The Code: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField]
private float accelSpeed = 1000;
[SerializeField]
private float maxSpeed = 8;
Rigidbody rb;
bool grounded = false;
float xV = 0, yV = 0;
public void Awake()
{
rb = GetComponent<Rigidbody>();
}
public void Update()
{
if (rb.velocity.magnitude > maxSpeed) {
rb.velocity = rb.velocity.normalized;
rb.velocity *= maxSpeed;
}
if (Input.GetAxisRaw("Vertical") == 0 && Input.GetAxisRaw("Horizontal") == 0)
{
float xVelocity = rb.velocity.x;
float yVelocity = rb.velocity.z;
xVelocity = Mathf.SmoothDamp(xVelocity, 0, ref xV, 5);
yVelocity = Mathf.SmoothDamp(yVelocity, 0, ref yV, 5);
rb.velocity = new Vector3(xVelocity,rb.velocity.y,yVelocity);
}
rb.AddForce(transform.forward*Input.GetAxisRaw("Vertical")* accelSpeed * Time.deltaTime + transform.right * Input.GetAxisRaw("Horizontal") * accelSpeed * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.Space) && grounded) {
grounded = false;
rb.AddForce(Vector3.up*500);
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.contacts.Length > 0)
{
ContactPoint contact = collision.contacts[0];
if (Vector3.Dot(contact.normal, Vector3.up) > 0.5)
{
grounded = true;
}
}
}
}
You could add a directional force away from the wall if you collide with it. This should stop you from sticking to it
Yea I tried that but it's more like the player bounces off walls instead of just sliding down, but thanks anyway!
Your answer
Follow this Question
Related Questions
Question about movement with Rigidbody | Diagnol movement going faster 2 Answers
Creating a platform game on 2 axis. Should I use a rigid body, or a character controller. 1 Answer
Make character move according to camera position. 1 Answer
character(ball) rolls with less speed when I build it 2 Answers