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) { 
            ..............
        }
    }
  }

}