A responsive character controller is essential for fun gameplay.
Create a Rigidbody2D
component for physics-based movement.
Use a script to capture player input and move the character:
public class PlayerController : MonoBehaviour {
public float speed = 5f;
private Rigidbody2D rb;
void Start() {
rb = GetComponent<Rigidbody2D>();
}
void Update() {
float moveX = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveX * speed, rb.velocity.y);
}
}
Add a Collider2D
to detect ground contact.
Modify the script to allow jumping when the player is grounded:
public float jumpForce = 10f;
private bool isGrounded;
void OnCollisionEnter2D(Collision2D collision) {
if (collision.contacts[0].normal.y > 0.5f) {
isGrounded = true;
}
}
void OnCollisionExit2D(Collision2D collision) {
isGrounded = false;
}
void Update() {
if (Input.GetButtonDown("Jump") && isGrounded) {
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
}
Use the Animator Controller to create Idle, Walk, and Jump animations.
Write a script to trigger animations based on movement:
animator.SetFloat("Speed", Mathf.Abs(rb.velocity.x));
animator.SetBool("IsGrounded", isGrounded);
Activity: Create a 2D character that can run, jump, and idle, with animations for each state.