Tuesday, January 20, 2015

Cast a ray to select 2D sprite in Unity

At beginning, I hope my grandfather could get better and move out of ICU  as soon as possible.

In Unity, we usually cast a ray from main camera to select a sprite. The sprite need to be added a collider2D component to realize the function.

void Update () {
  ClickItem ();
}

void ClickItem(){
  //check if the left button of mouse has been clicked
  if (Input.GetMouseButtonDown (0))
  {

    //transfer the position values to that in world axis    Vector3 v3 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Vector2 v2 = new Vector2 (v3.xv3.y);
    //cast a ray from zero point which is also the position of camera to v2    RaycastHit2D hit = Physics2D.Raycast (v2Vector2.zero);

    if (hit.collider != null//if the ray hit something
    {
        //Debug.Log(hit.collider.tag);
        //if the collision happens on an object itself
        if (hit.collider.gameObject == this.gameObject) { 
            ..............
        }
    }
  }

}

Wednesday, September 24, 2014

Set Depth Camera to show DigitDisplay

The Depth Camera can be used to show the bottom panel when the MainCamera is following the character.

At first, the scene consists of a background and a bottom panel which shows the digits.


Step 1: Choose "bottom" object, add a Layer named "Bottom", and modify the Layer as "Bottom".



Step 2: Create a Camera and Set as the image shows:
Change "Clear Flags" to "Depth only" and "Culling Mask" to "Bottom"

Step 3: Modify the MainCamera:
Change the "Culling Mask" value without Bottom and assign "Depth" value as "-1".

Step 4: Remove "Audio Listener" of "Camera" object:

Step 5: Write a script to "Camera" in order to show the game digit.

Is Trigger and OnTriggerEnter(), Destroy()

1. Trigger:

  • If two objects are both added Collider component and at least one of them is checked the "Is Trigger" attribute, then OnTriggerEnter() can be used in anyone.


  • Trigger can go into the object.
2. Destroy():

Destroy(gameObject);
Destroy(gameObject, 2.0f); //delay 2 seconds

Camera Follow Target

using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour {
    public GameObject target;
    public GameObject enemy;
    
    TargetController myTargetController;
    float velocity=0.0f;
    float newPositionX;
    
    // Update is called once per frame
    void Update () {
        //Camera Move
        if(target.transform.position.x>0 &&
           target.transform.position.x<33.5)
        {
            newPositionX=Mathf.SmoothDamp(transform.position.x,target.transform.position.xref velocity1.0f);
            transform.position=new Vector3(newPositionXtransform.position.ytransform.position.z);
        }
        //Active object when reach to a position
        if (transform.position.x > 2.8f) {
            if(enemy!=null){
                enemy.SetActive(true);
            }
        }
    }
}




AnimationController for the frames not in one texture

using System.Collections;

public class NewBehaviourScript : MonoBehaviour {
    public Texture [] frames;
    public bool direction=true;//head direction
    public bool destroy=false;//Destroy the animation after finish playing
    public int lastFrameNo=0//stop at a certain frame
    public bool oneTime=false;//do not repeat animation

    private int frameNumber=0;
    private int index=0;
    private float myTime=0;//time counter
    private int myIndex=0;

    // Update is called once per frame
    void Update () {
        frameNumber = frames.Length;

        if(!oneTime){
            myTime+=Time.deltaTime;
            myIndex=(int)(myTime*(frameNumber-1));//(frameNumber-1makes all animations played in 1s
            index=myIndex%frameNumber;
        }
        renderer.material.mainTexture=frames[index];//assign the frame to object

        if (direction) {
            renderer.material.mainTextureScale=new Vector2(1.0f,1);//set the heading direction
        }else{
            renderer.material.mainTextureScale=new Vector2(1.0f,1);
        }

        if (index == frameNumber - 1 && destroy) {
            //Destroy the animation
            Destroy(gameObject);
        }

        if (lastFrameNo != 0) {
            //stay on the certain frame
            if(index==lastFrameNo-1){
                oneTime=true;
            }
        }
    }
}

Customize GUI Button of Unity3D

First, I will give an example about how to implement a customized button, and then I would like to discuss how GUIs work under the function OnGUI().

Initially, there is a scene with a background:


Step 1: Create a GUISkin
Right click your mouse under project tab, choose "Create" -> "GUI Skin"
Drag the material pictures into the proper position
Then pull down the scroller bar and find "Custom Styles", put the other material into Element0 and assign the name as "easy"
Step 2: Write a script to show GUI and Drag it onto "MainCamera"

Step 3: Assign the startGUISkin with GUISkin in assets which we have already created in step 1

Step 4: Run and See



NOTE:
  • All the GUIs should be written in the OnGUI() function, which is called every frame.
  • GUI.Button(Rect,"label") use the default button skin. However, we also can use "Custom Styles" by writing GUI.Button(Rect,"label",GUI.skin.GetStyle("name")) .
  • If you want to hide GUI, then just set a boolean variable to controller it. Once the function doesn't run the GUI.Button(), the button will not show on the screen.
  • If(GUI.Button()) is a most widely used way to judge whether a button is clicked or not.
  • BTW, you can also modify the GUI.skin without assign a new GUISkin to it.

Character Player Controller

enum GameState
{
idle,
runLeft,
runRight,
jumpLeft,
jumpRight,
idleLeftJump,
idleRightJump,
celebrate,
die
}

var gameState:GameState;
private var moveDirection=true;
private var exit:boolean=false;
private var youWin:boolean=false;
private var youDie:boolean=false;
function Update(){
//Define GameState
if(Input.getAxis("Horizontal")>0){
moveDirection=true;
if(Input.GetButton("Jump")){
gameState=GameState.jumpRight;
}else{
gameState=GameState.runRight;
}
}else if(Input.getAxis("Horizontal")<0){
moveDirection=false;
if(Input.GetButton("Jump")){
gameState=GameState.jumpLeft;
}else{
gameState=GameState.runLeft;
}
}else{
if(Input.GetButton("Jump")){
if(moveDirection){
gameState=GameState.idleRightJump;
}else{
gameState=GameState.idleLeftJump;
}
}else{
gameState=GameState.idle;
}
}
if(youWin){
gameState=GameState.celebrate;
}
if(youDie){
gameState=GameState.die();
}
//Assign every state with a Vector3(x,y,x) variable
if(controller.isGrounded){
switch(gameState){
case GameState.runRight:
velocity=speed*Vector3(1,0,0);
break;
case GameState.runLeft:
velocity=speed*Vector3(-1,0,0);
break;
case GameState.jumpRight:
velocity=speed*Vector3(1,jumpSpeed,0);
break;
case GameState.jumpLeft:
velocity=speed*Vector3(-1,jumpSpeed,0);
break;
case GameState.idleLeftJump:
case GameState.idleRightJump:
velocity=speed*Vector3(0,jumpSpeed,0);
default:
velocity=Vector3.zero;
break;
}
}else{
velocity.y-=gravity*Time.deltaTime;
}
//Implement movement
controller.Move(velocity*Time.deltaTime);
}