Unity 另外一个方法Camera.main.ScreenPointToRay(Input.mousePosition)
射线起始点:相机Camera;射线终点:鼠标的位置。
这个方法把屏幕的像素点转换为了3d 世界的坐标,跟3d 世界的Camera间形成了一个射线。
用该方法写了一个例子,鼠标点击屏幕上的物体,物体旋转45度
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using UnityEngine;
using Random = UnityEngine.Random;
public class RayCamera : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
private RaycastHit hit;
// Update is called once per frame
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Input.GetMouseButton(0))
{
if (Physics.Raycast(ray, out hit, 1000))
{
hit.transform.Rotate(Vector3.up,45);
}
}
Debug.DrawLine(transform.position,hit.point,Color.green);
}
}