Skip to content

Instantly share code, notes, and snippets.

@rsaenzi
Last active April 16, 2021 23:49
Show Gist options
  • Select an option

  • Save rsaenzi/af58dbcd423a2ee92819ee9acdf0bfe1 to your computer and use it in GitHub Desktop.

Select an option

Save rsaenzi/af58dbcd423a2ee92819ee9acdf0bfe1 to your computer and use it in GitHub Desktop.
Script for Unity to control the main character in an 2D platformer game
//
// CharacterController2D.cs
//
// Created by Rigoberto Sáenz Imbacuán (https://linkedin.com/in/rsaenzi/)
// Copyright © 2021. All rights reserved.
//
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(SpriteRenderer))]
[RequireComponent(typeof(Collider2D))]
[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(Animator))]
public class CharacterController2D : MonoBehaviour {
[Tooltip("Horizontal motion speed in meters/seconds")]
public float motionSpeed;
[Tooltip("Jump force in newtons")]
public float jumpForce;
[Tooltip("Amount of coins the character has collected")]
public int coins;
[Tooltip("Key to move the character left")]
public KeyCode keyLeft;
[Tooltip("Key to move the character right")]
public KeyCode keyRight;
[Tooltip("Key to make the character jump")]
public KeyCode keyJump;
// This variable is used to prevent jump while in the air
bool characterIsJumping = false;
// Use this for initialization
void Awake() {
coins = 0;
}
// Update is called once per frame
void Update() {
// If 'keyRight' key is pressed, move the character left
if (Input.GetKey(keyRight)) {
// Move character to the right
this.transform.Translate(Vector3.right * motionSpeed * Time.deltaTime, Space.Self);
// Set IsRunning variable inside Animator to true, to enter to Running animation state
this.gameObject.GetComponent<Animator>().SetBool("IsRunning", true);
// Flip the gameobject to make the character look to the right
this.gameObject.GetComponent<SpriteRenderer>().flipX = true;
}
// If 'keyLeft' key is pressed, move the character left
if (Input.GetKey(keyLeft)) {
// Move character to the left
this.transform.Translate(Vector3.left * motionSpeed * Time.deltaTime, Space.Self);
// Set IsRunning variable inside Animator to true, to enter to Running animation state
this.gameObject.GetComponent<Animator>().SetBool("IsRunning", true);
// Unflip the gameobject to make the character look to the left
this.gameObject.GetComponent<SpriteRenderer>().flipX = false;
}
// If player release either 'keyLeft' or 'keyRight' keys...
if (Input.GetKeyUp(keyLeft) || Input.GetKeyUp(keyRight)) {
// Set IsRunning variable inside Animator to false, to exit from Running animation state
this.gameObject.GetComponent<Animator>().SetBool("IsRunning", false);
}
// If 'keyJump' key is pressed, makes the character jump
if (Input.GetKeyDown(keyJump) && characterIsJumping == false) {
// Set this to true so we do not allow jumping while in the air
characterIsJumping = true;
// Applies a force to make the collider jump up
this.gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
// Set IsRunning variable inside Animator to true, to enter to Jumping animation state
this.gameObject.GetComponent<Animator>().SetBool("IsJumping", true);
}
}
// When character's collider touches another collider
void OnCollisionEnter2D(Collision2D col) {
// If character touches a platform...
if (col.gameObject.tag == "Platform") {
// Set this to false so the character can jump again
characterIsJumping = false;
// Set IsJumping variable inside Animator to false, to exit from Jumping animation state
this.gameObject.GetComponent<Animator>().SetBool("IsJumping", false);
}
// If character touches a coin...
if (col.gameObject.tag == "Coin") {
// Drop the coin gameobject
Destroy(col.gameObject);
// Increase the amount of collected coins
coins = coins + 1;
// Display the amount of coins in a UI Text component
GameObject.Find("Canvas/CoinCount").GetComponent<Text>().text = coins.ToString();
// Play the audio fx for action "catch coin"
// AudioPlayer.playSoundFX("AudioCoin");
}
}
}
/*
*
* Related:
*
* AudioPlayer: Script for Unity to play/stop sound fx and music
* https://gist.github.com/rsaenzi/119357d38d9c7255adfa8e465d486d0c
*
* UINavigation: Script for Unity to load/unload UI screens
* https://gist.github.com/rsaenzi/95df01c056d352651a9143b13ce305fa
*
* LevelLoader: Script for Unity to load/unload levels
* https://gist.github.com/rsaenzi/33cfff7d20e62c6f229442f7c6a7aa90
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment