Skip to content

Instantly share code, notes, and snippets.

@boaheck
Created January 24, 2018 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boaheck/252a4a48b4b6aea9ff1e11a3cc764e42 to your computer and use it in GitHub Desktop.
Save boaheck/252a4a48b4b6aea9ff1e11a3cc764e42 to your computer and use it in GitHub Desktop.
This is a simple unity script that is similar to what the built in unity character controller does in 3D but in 2D. To use this put it on an object with a box collider 2D and a rigidbody2D. Then you can simply call the move function and check the booleans to see if you're grounded etc... Very rough right now but it helps work on a 2d character w…
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterController2D : MonoBehaviour {
Rigidbody2D rigb;
BoxCollider2D col;
Vector2 pos, boxSize, boxOffset;
public LayerMask groundLayers;
public bool grounded, head, left, right;
void Start () {
rigb = GetComponent<Rigidbody2D> ();
col = GetComponent<BoxCollider2D> ();
boxSize = (col.size + (Vector2.one * 2 * col.edgeRadius)) * 0.9f;
boxOffset = col.offset;
pos = transform.position;
}
public void setPos(Vector3 nPos){
transform.position = new Vector3 (nPos.x, nPos.y);
pos = nPos;
}
public void Move (Vector2 move) {
rigb.MovePosition (pos + move);
}
void Update () {
pos = new Vector2 (transform.position.x, transform.position.y);
grounded = Physics2D.OverlapBox (pos + boxOffset + (Vector2.down * 0.07f), boxSize,0,groundLayers.value);
head = Physics2D.OverlapBox (pos + boxOffset + (Vector2.up * 0.07f), boxSize,0,groundLayers.value);
left = Physics2D.OverlapBox (pos + boxOffset + (Vector2.left * 0.07f), boxSize,0,groundLayers.value);
right = Physics2D.OverlapBox (pos + boxOffset + (Vector2.right * 0.07f), boxSize,0,groundLayers.value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment