I'm currently working on a simple 2D Physics-Based Platformer Project. However, I ran into the following issue:
I'm using a Tilemap and a TilemapCollider2D to display the world. When I move the player object, it sometimes gets stuck on the edges between the different squares of the TilemapCollider2D.
Here is a little gif showcasing my problem. Please note that I'm continually pressing A/D to move over the surface. The stopping is the bug I mentioned:
Here is my player code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
Rigidbody2D rb2d;
[Header("Background Variables")]
public float speed = 5.0f;
public float maxSpeed = 10.0f;
public float jumpStrength = 10.0f;
public float friction = 2.5f;
public bool isGrounded = false;
public int walling = 0; // 0 = no wall collision; 1 = left side collision; 2 = right side collision
private void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}
private void LateUpdate()
{
if(rb2d.velocity.x > maxSpeed)
{
rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
}
else if(rb2d.velocity.x < -maxSpeed)
{
rb2d.velocity = new Vector2(-maxSpeed, rb2d.velocity.y);
}
if(Input.GetAxisRaw("Horizontal") != 0.0f)
{
rb2d.AddForce(speed * Vector2.right * Input.GetAxisRaw("Horizontal"), ForceMode2D.Impulse);
}
else
{
rb2d.velocity = Vector2.Lerp(rb2d.velocity, new Vector2(0.0f, rb2d.velocity.y), friction);
}
if(Input.GetButtonDown("Jump"))
{
rb2d.velocity = new Vector2(rb2d.velocity.x, jumpStrength);
}
}
// These two methods currently have no effect, but I plan on extending them later
public void SetGrounded(bool isGrounded)
{
this.isGrounded = isGrounded;
}
public void SetWalling(int walling)
{
this.walling = walling;
}
}
My player uses a Rigidbody2D and BoxCollider2D.
Is there any good way to prevent this from happening or at least a workaround?
Thank you in advance!