A characters in a 2D game normally moves freely within a NavMesh / collision boundary. This script causes them to instead snap vertically to the top edge of a collider. If that collider's shape is that of the ground, they will appear to move along the ground without moving vertically inappropriately.
To use it:
- Create a new GameObject and attach a 2D Collider (e.g. Polygon Collider 2D) to it, and reshape it to match the ground's shape and position.
- Create a new C# script named StickToGroundY.cs and attach it to your character
- Configure the Stick To Ground Y's Inspector, assigning its Ground Layer field to match that of the ground GameObject created in step 1.
- Set the character's starting position to be above the ground, at a distance no more than the length of the component's "Raycast Distance" field.
StickToGroundY.cs:
using UnityEngine;
public class StickToGroundY : MonoBehaviour
{
public LayerMask groundLayer;
public float raycastDistance = 1f;
private RaycastHit2D hitInfo = new RaycastHit2D ();
private void LateUpdate ()
{
hitInfo = Physics2D.Raycast (transform.position + Vector3.up * 0.1f, -Vector3.up, raycastDistance, groundLayer);
if (hitInfo.collider)
{
transform.position = hitInfo.point;
}
}
}