I am trying to create a character controller for a 2d platformer (I mean without a rigidbody). I have looked online but could not find any good tutorials. Does anyone know where a good tutorial for this is? Or is it better to just try to find things that are related to it, and piece information together? And if so, can I get some pointers on where to start? Thanks.
I have exactly such a thing here: 2D Animation Methods in Unity. Be sure to download the demo project, since Gamasutra mangles the code a bit.
Code (CSharp): using UnityEngine; public class Player : MonoBehaviour { Rigidbody2D Rig2D; public float Speed = 5f; public float JumpForce; void Start() { Rig2D = GetComponent<Rigidbody2D>(); } void FixedUpdate() { if (Input.GetKey(KeyCode.A)) { transform.position -= transform.right * Speed * Time.deltaTime; } if (Input.GetKey(KeyCode.D)) { transform.position += transform.right * Speed * Time.deltaTime; } } private void OnCollisionStay2D(Collision2D Collision2D) { if (Input.GetKeyDown(KeyCode.W)) { Rig2D.AddForce(new Vector2(0, JumpForce * 50)); } } } sorry, still quite Buggy...
A controller that doesnt use rigidbody mainly because it has difficulty handling slopes and isnt quite as easy to fine tune as a character controller
Because, if there is a slope then the rigidbody may slide down/get stuck when moving up it which is not ideal for some platformers
using UnityEngine; public class CharacterController2D : MonoBehaviour { public float WalkSpeed = 10; public float JumpForce = 5; void Update() { var Move = Input.GetAxis("Horizontal"); transform.position += new Vector3(Move, 0, 0) * Time.deltaTime * WalkSpeed; if (Input.GetButtonDown("Jump") && GetComponent<Rigidbody2D>().velocity.y == 0) { GetComponent<Rigidbody2D>().AddForce(new Vector2(0, JumpForce), ForceMode2D.Impulse); } } } here is my 2d characterController. If you want to copy this make shore that you have a rigidbody on your player and freeze position x and freeze rotation z on contraints in your rigidbody component and change your scripts name to CharacterController2D or else its not gonna work.
Code (CSharp): using UnityEngine; public class CharacterController2D : MonoBehaviour { public float WalkSpeed = 10; public float JumpForce = 5; void Update() { var Move = Input.GetAxis("Horizontal"); transform.position += new Vector3(Move, 0, 0) * Time.deltaTime * WalkSpeed; if (Input.GetButtonDown("Jump") && GetComponent<Rigidbody2D>().velocity.y == 0) { GetComponent<Rigidbody2D>().AddForce(new Vector2(0, JumpForce), ForceMode2D.Impulse); } } }