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();
}
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!
Answer
After trying to write a code that merges the squares effectively (especially for large Tilemaps) both horizontally and vertically I decided to look if there is a better suited collider than the PolygonCollider2D which I've been using. Then I stumbled across a certain component and now I feel really stupid...
The trick to avoid the problem I mentioned in my question involves absolutely 0 lines of code.
- For the TilemapCollider2D check the box "Used by Composite".
- Then add the Component CompositeCollider2D (Found under Physics2D). This will automatically add a Rigidbody2D to your object if it doesn't have one already.
- Change the "Body Type" of the Rigidbody2D to Kinematic unless you want physical interaction with the tilemap.
- Profit.
I did some testing and it seems like my problem is solved now. If I should run across another error with this method, I'll update this answer accordingly.
No comments:
Post a Comment