Camera常用方法就是ScreenPointToRay,以下代码是通过检测鼠标指向来进行射线检测。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraTest : MonoBehaviour
{
private Camera camera;
// Start is called before the first frame update
void Start()
{
camera = Camera.main;
}
// Update is called once per frame
void Update()
{
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
//Debug.DrawRay(ray.origin, ray.direction);
//Debug.DrawLine(ray.origin,ray.direction * 100);
bool isCollider = Physics.Raycast(ray,out RaycastHit hitInfo);
Debug.Log(isCollider+"\n"+hitInfo.collider);
//不能打印hitInfo.collider.gameObject,避免射线指向空时,出现空指针,空指针的GameObject会报错
}
}