In games such as RPG games, when we click on the map, the character goes to the clicked location. This process can also be that we click on the screen, and a ray is emitted from the plane of the camera, pointing to the clicked location.
For example: we click a certain place, the sphere will go to a certain place
Create a script to mount on the sphere
Screenplay:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RayTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//方式一
//Ray ray = new Ray(Vector3.zero, Vector3.up);
//方式二
//通过摄像机获得射线,ScreenPointToRay 从屏幕点开始发射射线 Input.mousePosition 鼠标按到的点
//Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
}
// Update is called once per frame
void Update()
{
//按住鼠标左键发射射线
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//声明一个碰撞信息类
RaycastHit hit;
//碰撞检测
//Physics.Raycast物理类里面一个射线检测方法,out hit 注意out+空格是C#里面的语法,我们声明了信息类,而out会帮助我们填写内容
bool res = Physics.Raycast(ray, out hit);
//如果碰撞到的情况下,hit就有内容了,反之就没有内容了
if (res)
{
Debug.Log(hit.point);
transform.position = hit.point;
}
//多检测
//100:检测距离, 1<<10:只检测第十个图层
RaycastHit[] hit = Physics.RaycastAll(ray, 100, 1<<10);
}
}
}