Unity3D Game Engine – Get Mouse Button – Physic.Raycast – Hit GameObject

Unity3D Game Engine – Get Mouse Button – Physic.Raycast – Hit GameObject

Physic.Raycast is useful if you need to know the exact point where the mouse pointer is.

Create a scene with:

– Main Camera
– Cube
– Empty Object, assign GetMouseClick.js:


#pragma strict

function Update(){
    // if you press Left Mouse Button -> GetMouseButtonDown(0) 
    if (Input.GetMouseButtonDown(0)){
        var hit: RaycastHit;
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition); // it sends a ray from Camera.main
        if (Physics.Raycast(ray, hit)){ // if it hits something        

            var object = hit.transform.gameObject; // if the ray hits a GameObject
 
            Debug.Log("Clicked!");
            // Do something...
        }
    }
 
}

Play and click over the Cube

NOTICE: You can assign the script at every object in the scene

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D Game Engine – Get Mouse Button – Physic.Raycast – Hit GameObject

Unity3D – GetMouseButton – PhysicRaycast – Get GameObject name

Unity3D – GetMouseButton – PhysicRaycast – Get GameObject name

Once you have determined that your raycast actually hit something, you can query the name of your ‘hit’ object.

Create a scene with:

– Cube, remame myCube

– Main Camera, attach the script:


#pragma strict


function Update(){
    // if you press Mouse Button
    if (Input.GetMouseButtonDown(0)){ // if you press Left Mouse Button -> GetMouseButtonDown(0) 
        var hit: RaycastHit;
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition); // it sends a ray from Camera.main
        if (Physics.Raycast(ray, hit)){ // if it hits something        
           
            var MyObjectName = hit.collider.gameObject.name; // get the name of the 'hit' object
            
            Debug.Log(MyObjectName); // show the name of the clicked object
            // Do something...
        }
    }
 
}

Play, if you click the Cube you will see inside console ‘myCube’.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – GetMouseButton – PhysicRaycast – Get GameObject name

Unity3D – OnMouseDown – SetActive – Shuriken Particle System – Javascript

Unity3D – OnMouseDown – SetActive – Shuriken Particle System – Javascript

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

We will create a simple Asteroid object taht will explode OnMouseDown

Create a scene with:

– Main Camera

– (parent) EmptyObject -> name it Asteroid -> ADD a Box Collider (or OnMouseDown will not work!)
-> Transform Reset

– (child) Mesh -> your mesh -> Transform Reset

– (child) Particle System (MAIN TOP MENU> GameObject> Create Other> Particle System)
-> Inspector> Play On Awake active
-> Transform Reset

Attach to Asteroid (EmptyObject) the script:


#pragma strict

var myParticles : GameObject; // Assign in Inspector

function Start () {
   // Prefab Esplosione, disattivo altrimenti esplode subito alla creazione 
    myParticles.SetActive(false); 
} // END Start

function Update () {	
}// END Update

function OnMouseDown ()
{
        // When you click over the object
        Debug.Log('Particle Activaction!');
        myParticles.SetActive(true); 
}// END OnMouseDown()

Inspector> DRAG AND DROP Particle System over var myParticles

Play and click over the Box Collider of Asteroid (EmptyObject).

For italian peolple: come funziona?

1. Creo un oggetto padre con all’interno la geometria e il sistema particellare
2. Resetto la posizione dei tre game object perchè coincidano
3. Creo un box collider nell’oggetto padre e assegno lo script
4. Lo script ottiene il sistema particellare come GameObject e lo attiva al click. Il sistema particellare parte di sicuro perchè ha attivo ‘Play On Awake’ in Inspector.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – OnMouseDown – SetActive – Shuriken Particle System – Javascript

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