- Home /
My character occasionally gets stuck in random places as if there was a barrier, but when I jump those "barriers" disappear.
I'm quite new to C# and Unity so I have no idea how to solve this. I recently made a sprite that looks like this:
and I made a simple script that looks like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb;
private bool canJump;
private float jumpingcd = 2f;
private Vector2 jumpforce = new Vector2(0, 100);
public float currenttimetillcddone = 0f;
float xaxis;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
canJump = false;
xaxis = Input.GetAxis("Horizontal");
}
// Update is called once per frame
void Update()
{
xaxis = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(xaxis*7f, rb.velocity.y);
if (currenttimetillcddone >= jumpingcd)
{
canJump = true;
}
else
{
currenttimetillcddone += Time.deltaTime;
canJump = false;
}
if (Input.GetButton("Jump") && canJump)
{
currenttimetillcddone = 0f;
rb.AddForce(jumpforce); //Doesn't work rn
}
}
}
but, as the title says, my character sometimes stops at what seems to be an invisible barrier which sometimes disappears when I click my spacebar. Can somebody help me?
Answer by wehttam359 · May 22 at 06:04 PM
Are you using a tilemap? Your character may be getting stuck on the borders between the tiles. If that's the case, put a Composide Collider 2D on the tilemap. This will combine the individual tiles into on smooth collider. That will automatically put a Rigidbody2D onto the object, so make sure the enable all of its constraints! Also, check "Used By Composite" on your TilemapCollider2D.