效果如下图
link
在 Unity 中使用射线移动物体的原理主要基于射线检测和物体位置的更新,下面为你详细阐述相关原理及实现步骤。
射线检测原理
射线检测是一种在三维空间中从一个点沿着特定方向发射一条无限长的射线,并检测该射线与场景中的物体是否相交的技术。在 Unity 里,射线由 Ray 结构体表示,它包含一个起点(origin)和一个方向(direction)。射线检测通过 Physics.Raycast 或 Physics.RaycastAll 等方法实现。
精准点击物体拖拽的效果 点击选中需要移动的物体,拖动物体,
物体是3D物体,摄像机是正交摄像机,
移动物体代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraRayObj : MonoBehaviour
{
public Vector3 offects;
private Transform cube;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
//给拖拽的物体一个tag值 JQR 方便区分
//鼠标按下 记录鼠标点击物体的点到物体坐标位置的插值
if (Physics.Raycast(ray, out hit) && hit.collider.tag == "JQR")
{
cube = hit.collider.transform;
offects = hit.collider.transform.position - hit.point;
}
}
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
//射线打到后面板子,相当于物体的位置, 板子设置一个层级
if (Physics.Raycast(ray, out hit, 1000, 1 << 8) && cube != null)
{
//第一种方式
//cube.position = v3-Vector3.forward*v3.z + hit.point-Vector3.forward*hit.point.z;
//第二种方式
cube.position = new Vector3(hit.point.x + offects.x, hit.point.y + offects.y, cube.transform.position.z);
}
}
if (Input.GetMouseButtonUp (0))
{
cube = null;
}
}
}
在加一个上下拖动的代码
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShengGaoCube : MonoBehaviour {
Ray ray,ray1,ray2;
RaycastHit hit,hit1,hit2;
public Camera cameraa;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKey (KeyCode .V))
{
this.GetComponent<ShuiYiTuoDong>().enabled = false;
if (Input.GetMouseButton(0))
{
Debug.DrawLine(transform.position, hit.point);
ray = cameraa.ScreenPointToRay(this.transform.position);
LayerMask lm = 1 << 9;
if (Physics.Raycast(ray, out hit, lm))
{
}
ray1 = cameraa.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray1, out hit1))
{
if (hit1.transform.name == "Cube")
{
this.transform.position = new Vector3(this.transform.position.x, hit1.point.y, this.transform.position.z);
}
}
}
}
else
{
this.GetComponent<ShuiYiTuoDong>().enabled = true;
}
}
}
最后自行测试即可