Coding the Character
With the character setup, it is now time to code it.
This tutorial will look at coding the character to achieve the following:
- Left and Right Movement of a character.
- A jumping mechanic
- An internal cooldown to stop “jump spam”
- Compatibility for both Keyboard and Controllers
Example Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float moveSpeed = 5f;
public float jumpForce = 10f;
public float jumpDelay;
private Rigidbody2D rb;
bool canJump;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
canJump = true;
}
private void Update()
{
// Handle player input
float horizontalInput = Input.GetAxis("Horizontal");
HandleMovement(horizontalInput);
if (Input.GetButtonDown("Jump") && canJump)
{
StartCoroutine(Jump());
}
}
private void HandleMovement(float horizontalInput)
{
// Move the player horizontally
Vector2 movement = new Vector2(horizontalInput * moveSpeed, rb.velocity.y);
rb.velocity = movement;
}
IEnumerator Jump()
{
canJump = false;
// Make the player jump if grounded
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
yield return new WaitForSeconds(jumpDelay);
canJump = true;
}
}