- Home /
player can stick to wall
If the player jumps into a wall and keeps holding the d or a key(depending what side of the game the wall is on) they will just stick to the wall.
Is there any code that could prevent this?
my code for the player:
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float speed;
public float jumpSpeed;
bool grounded = false;
public Transform groundcheck;
float groundRadius = 0.2f;
public LayerMask whatIsGround;
void FixedUpdate()
{
grounded = Physics2D.OverlapCircle (groundcheck.position, groundRadius, whatIsGround);
if(Input.GetKey(KeyCode.D))
{
rigidbody2D.velocity = new Vector2 (speed, rigidbody2D.velocity.y);
}
else if(Input.GetKey(KeyCode.A))
{
rigidbody2D.velocity = new Vector2 (speed*-1, rigidbody2D.velocity.y);
}
else
{
rigidbody2D.velocity = new Vector2 (0, rigidbody2D.velocity.y);
}
}
void Update()
{
if(grounded && Input.GetKeyDown(KeyCode.W))
{
rigidbody2D.AddForce (new Vector2 (0, jumpSpeed));
}
}
}
Thanks in advance.
Answer by AKWolf · Aug 29, 2014 at 01:55 AM
I had the same problem, but in a 3D platformer.
Try reading up on Physics Materials. What was happening in my case was that the velocity vector I was applying to my character kept pushing him into the wall, and the friction between the wall collider and my character collider made him "stick".
What I ended up doing is creating custom physics materials for my wall colliders and my character collider, which solved the problem (essentially I turned friction to be super low for those surfaces). Once you create a new physics material, you can add it on the actual collider component on your GameObject.
Hope that helps!
Answer by stulleman · Aug 20, 2014 at 05:55 PM
I think you could prevent this with using rigidBody2D.AddForce().
Alternatively, because I know why you dont't want to use AddForce :P, you can just check, like you check if you are grounded, if you touch a wall. If so don't apply any velocity.
I tried but failed for some reason it wouldn't work, is there something else i can try
@stulleman, I'm not sure if anyone gets notified when I comment, but I hope so.
I check for "IsGrounded" via a linecast centered directly below my character. I find that there is a problem that your movement gets disabled if you move off an edge where the linecast won't touch anything anymore. Having 2-3 different linecast instances with the exact same purpose seems inefficient to me. Is there any other way?
I use Rigidbody2D.addForce() to move my player horizontally and I am currently using Unity 5.1.
Thanks.
Your answer
Follow this Question
Related Questions
Why do I double jump? This isn't supposed to happen... 2 Answers
Change gravity on button 1 Answer
move, destroy self, instantiate again, repeat. 2 Answers
2D - Detect Slopes x Walls 1 Answer