indiegamedev

Unity3D – OnMouseDown – Set Color-Speed-Size-Gravity – Shuriken Particle System – Javascript

Unity3D – OnMouseDown – Set Color-Speed-Size-Gravity – Shuriken Particle System – Javascript

Unity’s Shuriken Particle System is easy to drive via code!

Create a scene with:

– Particle System

– Cube, attach the script:


#pragma strict

var myParticles : GameObject; // Assign in Inspector

function Start () {
} // END Start

function Update () {	
}// END Update

function OnMouseDown ()
{
        // When you click over the object
        Debug.Log('Particle Activaction!');
        myParticles.particleSystem.startColor = Color.red; // change Start Color
        myParticles.particleSystem.startSpeed = 30;        // change Start Speed
        myParticles.particleSystem.startSize = 30;         // change Start Size
        myParticles.particleSystem.gravityModifier = 1;    // use gravity
       
  
}// END OnMouseDown()

Inspector> DRAG AND DROP your Particle System over var myParticles

Play and click over the Cube.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – OnMouseDown – Set Color-Speed-Size-Gravity – Shuriken Particle System – Javascript

Unity3D – Character Controller – Move – Basic – JS

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 -

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Character Controller – Move – Basic – JS

Unity3D – Character Controller – isGrounded – JavaScript

Unity3D – Character Controller – isGrounded – JavaScript

Was the CharacterController touching the ground during the last move?


function Update () {
		var controller : CharacterController = GetComponent(CharacterController);
		if (controller.isGrounded)
			print("We are grounded");
	}

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Character Controller – isGrounded – JavaScript

Unity3D – Character Controller – Velocity – JavaScript

Unity3D – Character Controller – Velocity – JavaScript

This allows you to track how fast the character is actually walking for example when he is stuck at a wall this value will be the zero vector, or if vertical speed is <0 the character is falling down. The current relative velocity of the Character. The velocity is relative because it won't track movements to the transform that happen outside of the CharacterController (e.g. character parented under another moving Transform, such as a moving vehicle). [js] function Update () { // Get relative velocity of Character Controller component GetVelocity(); }//END UPDATE function GetVelocity() { // Get the component var controller : CharacterController = GetComponent(CharacterController); var horizontalVelocity : Vector3 = controller.velocity; horizontalVelocity = Vector3(controller.velocity.x, 0, controller.velocity.z); // The speed on the x-z plane ignoring any speed var horizontalSpeed : float = horizontalVelocity.magnitude; // The speed from gravity or jumping var verticalSpeed : float = controller.velocity.y; // The overall speed var overallSpeed : float = controller.velocity.magnitude; Debug.Log(horizontalSpeed + " " + verticalSpeed + " " + overallSpeed ); }// END GetVelocity() [/js]

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Character Controller – Velocity – JavaScript

Unity3D – Character Controller – Detect Collision

Unity3D – Character Controller – Detect Collision

Determines whether other rigidbodies or character controllers collide with this character controller (by default this is always enabled).
This property is useful to disable the character controller temporarily. For example, you might want to mount a character into a car and disable collision detection until it exits the car again.

        var c : CharacterController;
	c = GetComponent(CharacterController);
	c.detectCollisions = false;
By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Character Controller – Detect Collision