Raycasting 3D and 2D

In this example we will print a name of the object that was clicked.

// 3D raycasting    
void Update()
    {
        if(Input.GetMouseButtonUp(0)){
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if(Physics.Raycast(ray, out hit, 100)){
                Debug.Log(hit.transform.name);
            }
        }
    }
// 2D raycasting that works with colliders

        if(Input.GetMouseButtonUp(0)){
            RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
            
            if(hit.collider != null)
            {
                Debug.Log (hit.transform.name);
            }
        }

Dodaj komentarz

Twój adres email nie zostanie opublikowany.