Unity3d

Ray

scarecrow1992 2022. 2. 21. 00:37

 

https://docs.unity3d.com/kr/2018.4/Manual/CameraRays.html

 

화면상에 마우스가 존재하는 위치로 캐릭터를 돌아보게 만들기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public Crosshairs crosshairs;
 
public void LookAt(Vector3 lookPoint) {
    Vector3 heightCorrectedPoint = new Vector3 (lookPoint.x, transform.position.y, lookPoint.z);
    transform.LookAt (heightCorrectedPoint);
}
 
void Update () {
    // Look input
    Ray ray = viewCamera.ScreenPointToRay (Input.mousePosition);
    Plane groundPlane = new Plane (Vector3.up, Vector3.up * gunController.GunHeight);
    float rayDistance;
 
    if (groundPlane.Raycast(ray,out rayDistance)) {
        Vector3 point = ray.GetPoint(rayDistance);
        //Debug.DrawLine(ray.origin,point,Color.red);
        LookAt(point);
    }
}
cs

 

 

마우스를 클릭한 위치에 있는 오브젝트 얻기

1
2
3
4
5
6
7
8
RaycastHit hit;
 
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),
    out hit, 200.0f, LayerMask.GetMask("TileObject"))) {
 
    //Debug.Log(hit.point);
    GameObject object = hit.transform.gameObject;
}
cs