Hey fellow Unity Developers, hope you’re having a nice day!
I’m currently developing a 2D Platformer and i have this issue with my player sinking into colliders and also hitting bumps when moving over an platform made up from a tileset.
So my question is, how is the best way to do a 2D Platformer Controller, and handle collisions - i’m still fairly new to Unity and C# so would love to learn about new ways to achieve this.
Here is my PlayerController:
using System.Collections;
using System.Collections.Generic;
using Com.LuisPedroFonseca.ProCamera2D;
using UnityEngine;
public class PlayerController : MonoBehaviour {
[Header("Player Movement")]
public LayerMask playerMask;
public float maxSpeed = 7f;
public float jumpTakeOffSpeed = 7f;
public bool canMoveInAir = true;
public Transform groundCheck;
public bool grounded;
private float playerInput;
private Vector2 velocity;
private Rigidbody2D rb2d;
private float groundCheckRadius = 0.2f;
void OnEnable()
{
rb2d = GetComponent<Rigidbody2D>();
ProCamera2D.Instance.AddCameraTarget(transform);
}
void Start () {
}
void FixedUpdate()
{
velocity = rb2d.velocity;
grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, playerMask);
Debug.DrawLine(transform.position, groundCheck.position, Color.red);
Move(Input.GetAxis("Horizontal"));
if (Input.GetButton("Jump"))
{
Jump();
}
}
public void Move(float horizontalInput)
{
if (!canMoveInAir && !grounded)
return;
velocity.x = horizontalInput * maxSpeed;
rb2d.velocity = velocity;
}
public void Jump()
{
if (grounded && velocity.y == 0)
{
rb2d.AddForce(Vector2.up * jumpTakeOffSpeed, ForceMode2D.Impulse);
}
}
public void Die()
{
Destroy(gameObject);
}
}