Why is does my player stick to the wall in my platforrmer?

Viewed 43

I'm working on a small 2D platformer (with the help of tutorials) on Unity to get better at the game engine. When I was testing the movement script, the player would stick to the wall and not fall down unless I stopped holding the A or D key. I'm really new, so forgive me if I made a stupid mistake. Here's the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    public float radius;

    public float speed;
    public float jumpForce;

    public Transform feet;

    Rigidbody2D rb;

    public LayerMask groundLayers;

    void Start ()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate ()
    {
        rb.velocity = new Vector2(Input.GetAxisRaw("Horizontal") * speed, rb.velocity.y);

        if (Input.GetKey(KeyCode.Space) && IsGrounded())
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
        }
        
    }

    public bool IsGrounded ()
    {
        Collider2D groundCheck = Physics2D.OverlapCircle(feet.position, radius, groundLayers);

        if (groundCheck != null)
        {
            return true;
        }
        return false;
    }
}
1 Answers

It is because of the friction between the wall and the player.

Imagine yourself pressing your phone on the wall with your finger. Your phone won't fall off, and that is because of the friction keeping it from falling.

A solution to this issue would be to create two extra box / cylinder colliders, put them on each side of the player sprite, and set their friction to 0. This should make them slide off walls, and the keep the normal collision for the ground working without having to code a weird solution that might cause bugs.

Related