Unity3D – Character Controller – Move – Basic – JS

Character Controller is a special Unity3D component for characters. You can use this to control first person or third person characters.

Rotate around Y, move forward/backward

We are going to create a script to:
– Rotate around y axis -> using right/left arrow
– Move forward/backward -> using up/down arrow

Let’s go on!

Create a scene with:

– Main Camera
– (parent)Empty Object
– (child) Character Geometry, your .fbx
– (child) Props of the Character, your .fbx
– PlayerController.js

PlayerController.js:

#pragma strict

// Attach this script to the player
// Rotate around y axis - using right/left arrow 
// Move forward - using up/down arrow

// It request CharacterController component
@script RequireComponent(CharacterController)

	var speed : float = 3.0; // move speed
	var rotateSpeed : float = 3.0; // rotate speed
	
	function Update () {

	        // Get the component
		var controller : CharacterController = GetComponent(CharacterController);

		// Rotate around y axis - using right/left arrow START -----------
		transform.Rotate(0, Input.GetAxis ("Horizontal") * rotateSpeed, 0);
		// Rotate around y axis - using right/left arrow END -------------
		
		// Move forward / backward START ---------------------------------
		var forward : Vector3 = transform.TransformDirection(Vector3.forward);
		var curSpeed : float = speed * Input.GetAxis ("Vertical");
		// .SimpleMove forward - using up/down arrow
		controller.SimpleMove(forward * curSpeed);
		// Move forward / backward END -----------------------------------
	
        }// END Update()

Move forward/sideways, jump

Change the script to:
– Move the character controller forward and sideways based on the arrow keys.
– Jump when pressing space.

#pragma strict

/// Attach this script to your player
    
/// This script moves the character controller forward 
/// and sideways based on the arrow keys.
/// It also jumps when pressing space.
	
/// Make sure to attach a character controller to the same game object.
/// It is recommended that you make only one call to Move or SimpleMove per frame.	

// It request CharacterController component
@script RequireComponent(CharacterController)

	var speed : float = 6.0;       // the speed of the character
	var jumpSpeed : float = 8.0;   // the jump speed
	var gravity : float = 20.0;    // the gravity

	private var moveDirection : Vector3 = Vector3.zero; // shorthand for writing Vector3(0, 0, 0).

	function Update() {
	
		// Get the component CharacterController
		var controller : CharacterController = GetComponent(CharacterController);
		// if touching the ground during the last move
		if (controller.isGrounded) {
			// We are grounded, so recalculate
			// move direction directly from axes START -----------------------
			moveDirection = Vector3(Input.GetAxis("Horizontal"), 0,
			                        Input.GetAxis("Vertical"));
			moveDirection = transform.TransformDirection(moveDirection);
			moveDirection *= speed;
			// move direction directly from axes END -------------------------
			// jump START ----------------------------------------------------
			if (Input.GetButton ("Jump")) {
				moveDirection.y = jumpSpeed;
			}
			// jump END ------------------------------------------------------
		}// END if .isGrounded

		// Apply gravity
		moveDirection.y -= gravity * Time.deltaTime;
		
		// Move the controller
		controller.Move(moveDirection * Time.deltaTime);
		
	}// END Update()

	

Move as 2.5D Platform – single jump

Change the script to:
– Move the character controller sideways XY plane, based on the left/right arrow keys.
– Jump when pressing space.

#pragma strict

        /// 2.5D platform Character Controller - single jump
    
        /// Attach this script to your player
    
        /// This script moves the character controller  
	/// sideways based on the left/right arrow keys.
	/// It also jumps when pressing space.
	
	/// Make sure to attach a character controller to the same game object.
	/// It is recommended that you make only one call to Move or SimpleMove per frame.	

// It request CharacterController component
@script RequireComponent(CharacterController)

	var speed : float = 6.0;       // the speed of the character
	var jumpSpeed : float = 8.0;   // the jump speed
	var gravity : float = 20.0;    // the gravity

	private var moveDirection : Vector3 = Vector3.zero; // shorthand for writing Vector3(0, 0, 0).

	function Update() {
	
		// Get the component CharacterController
		var controller : CharacterController = GetComponent(CharacterController);
		// if touching the ground during the last move
		if (controller.isGrounded) {
			// We are grounded, so recalculate
			// move direction directly from axes START -----------------------
			moveDirection = Vector3(Input.GetAxis("Horizontal"), 0,
			                        0);
			moveDirection = transform.TransformDirection(moveDirection);
			moveDirection *= speed;
			// move direction directly from axes END -------------------------
			// jump START ----------------------------------------------------
			if (Input.GetButton ("Jump")) {
				moveDirection.y = jumpSpeed;
			}
			// jump END ------------------------------------------------------
		}// END if .isGrounded

		// Apply gravity
		moveDirection.y -= gravity * Time.deltaTime;
		
		// Move the controller
		controller.Move(moveDirection * Time.deltaTime);
		
	}// END Update()
	

Inspector> setup Speed, Jump Speed, Gravity vars

Notice:

moveDirection = Vector3(Input.GetAxis("Horizontal"), 0, 0); 

I have removed GetAxis(“Vertical”)

Move as 2.5D Platform – double jump (Air Jump)

Change the script to:
– Move the character controller sideways XY plane, based on the left/right arrow keys.
– Ground jump and Air jump


#pragma strict

    /// 3D and 2.5D platform Character Controller
    /// http://blog.lucedigitale.com 
    /// Author: Andrea Tonin
    
    /// Attach this script to your player
    
    /// This script moves the character controller  
    /// sideways based on the left/right arrow keys.
    /// It also jumps when pressing space.
	
    /// Make sure to attach a character controller to the same game object.
    /// It is recommended that you make only one call to Move or SimpleMove per frame.	

// It request CharacterController component
@script RequireComponent(CharacterController)

	var speed : float = 6.0;         // the speed of the character
	var jumpSpeed : float = 8.0;     // the jump speed
	var gravity : float = 20.0;      // the gravity
	
	var canJump : boolean = true;    // the player can jump, uncheck to disable jump
	var disableZMov : boolean = true;// disable Z movement
	
	var falling : boolean = false;   // the player is falling down
	
	var apex : float;                // max relative height to perform an Air Jump -> Assign in Inspector
	                                 // (apice) la massima altezza relativa all'interno della quale può innestare l'Air Jump
	var MaxJumpHeight : float;       // max absolute height to perform an Air Jump -> calculate into Update()

	private var moveDirection : Vector3 = Vector3.zero; // shorthand for writing Vector3(0, 0, 0).

	function Update() {
	
		// Get the component CharacterController
		var controller : CharacterController = GetComponent(CharacterController);
		
		
		// Move direction directly from axes START ########################################
		// if touching the ground during the last move
		if (controller.isGrounded) {// We are grounded
			
			if (disableZMov)
			// use it to move in 2.5D space
			moveDirection = Vector3(Input.GetAxis("Horizontal"), 0, 0);
			
			if (!disableZMov)
			// use it to move in 3D space
			moveDirection = Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
			
			moveDirection = transform.TransformDirection(moveDirection);
			moveDirection *= speed;
		}// END if .isGrounded
		// Move direction directly from axes END ############################################
		
	
               // Jump START #######################################################################
			// GROUND Jump START -------------------------------------------------------
			// salta se -----------     --------------> è a terra AND è abilitato a saltare
			if (Input.GetButton ("Jump") && controller.isGrounded && canJump) {
			    // record Y position...
			    var RecPositionY : float = transform.position.y;
			    // calculate the absolute height in the world space to be able Air Jump
			    MaxJumpHeight = RecPositionY + apex;
			    // perform your best jump
				moveDirection.y = jumpSpeed;			
			} //  END if
			
			// AIR Jump START ----------------------------------------------------------
			// salta se -------------------------------> è in aria AND è abilitato a saltare AND non sta cadendo AND non ha superato l'altezza del primo salto
			if (Input.GetButton ("Jump") && !controller.isGrounded && canJump && !falling && transform.position.y <= MaxJumpHeight) {
				moveDirection.y = jumpSpeed;			
			} //  END if
		// Jump END ###########################################################################
		

		// Apply gravity
		moveDirection.y -= gravity * Time.deltaTime;
		
		// Move the controller
		controller.Move(moveDirection * Time.deltaTime);
		
		// others useful datas --------------------------------------------
		// The speed from gravity or jumping
		var verticalSpeed : float = controller.velocity.y;
		// Non ho bisogno di altri controlli perchè .velocity è relativa e non tiene conto del movimento indotto da altri oggetti, ad esempio una piattaforma mobile
		if (verticalSpeed < 0)   
		falling = true; // the Character Controller is falling
		if (verticalSpeed >= 0) 
		falling = false;
		
		// debug code
		Debug.Log("Posizione Y" + transform.position.y + "Altezza Max" + MaxJumpHeight);
		
	}// END Update()	

Inspector> setup all vars

Notice:


...
var apex : float;                // max relative height to perform an Air Jump -> Assign in Inspector
	                              
var MaxJumpHeight : float;       // max absolute height to perform an Air Jump -> calculate into Update()
...

               // Jump START #######################################################################
			// GROUND Jump START -------------------------------------------------------
			// salta se -----------     --------------> è a terra AND è abilitato a saltare
			if (Input.GetButton ("Jump") && controller.isGrounded && canJump) {
			    // record Y position...
			    var RecPositionY : float = transform.position.y;
			    // calculate the absolute height in the world space to be able Air Jump
			    MaxJumpHeight = RecPositionY + apex;
			    // perform your best jump
				moveDirection.y = jumpSpeed;			
			} //  END if
			
			// AIR Jump START ----------------------------------------------------------
			// salta se -------------------------------> è in aria AND è abilitato a saltare AND non sta cadendo AND non ha superato l'altezza del primo salto
			if (Input.GetButton ("Jump") && !controller.isGrounded && canJump && !falling && transform.position.y <= MaxJumpHeight) {
				moveDirection.y = jumpSpeed;			
			} //  END if
		// Jump END ###########################################################################

For italian people, come funziona?

1. – Input.GetButton (“Jump”) && controller.isGrounded – dal salto da terra, registro la Y assoluta di partenza – RecPositionY

2. – Input.GetButton (“Jump”) && !controller.isGrounded – dal salto in aria, controllo che l’altezza max del primo salto non venga superata – transform.position.y <= MaxJumpHeight -