VR射线拾取
程序员文章站
2022-05-23 15:18:53
...
射线拾取其实很简单,这个加多了个shader
脚本要挂载在里,
namespace VRTK {
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RayPick : MonoBehaviour
{
public bool IsUse = true;
//外发光的shader
public Shader outLine;
LineRenderer m_Renderer;GameObject oldObj;// Use this for initializationvoid Start(){}void Awake() {m_Renderer = GetComponent<LineRenderer>();}// Update is called once per framevoid Update(){if (IsUse){Ray camRay = new Ray(transform.position, transform.forward);RaycastHit Hit;if (m_Renderer == null)gameObject.AddComponent<LineRenderer>();m_Renderer.SetPosition(0, transform.position);if (m_Renderer.enabled == false)m_Renderer.enabled = true;if (Physics.Raycast(camRay, out Hit, Mathf.Infinity)) // 射线 捡取{m_Renderer.SetPosition(1, Hit.point);if (Hit.transform.CompareTag("PickItem")){ //射线进入oldObj = Hit.transform.gameObject; oldObj.GetComponent<MeshRenderer>().materials[1].shader = outLine;//视线捡取,当按下toupaid 左边建,视线对焦物品 按下griss就可以捡取if (GetComponentInChildren<VRTK_ControllerEvents>().gripPressed == true){oldObj.GetComponent<MeshRenderer>().materials[1].shader = null;float a = Mathf.Sign(Vector3.Dot(transform.forward, oldObj.transform.position));oldObj.transform.position = transform.position - new Vector3(-0.25f, 0, 0.25f) * a;m_Renderer.enabled = false;IsUse = false;}}else{if (oldObj != null)oldObj.GetComponent<MeshRenderer>().materials[1].shader = null;}}else{if (oldObj != null)oldObj.GetComponent<MeshRenderer>().materials[1].shader = null;}}else{if (oldObj != null) { oldObj.GetComponent<MeshRenderer>().materials[1].shader = null;oldObj = null;}}}public void m_use(){IsUse = true;}public void PickItem(){}void OnEnter(){}void OnExit(){}}}另外,如果射线没有碰到collider, 也需要做一些处理,解决方法一,在子物体上放个空物体,位置调位(0,0,0) Vector3.zero
然后把空物体的z位置调高,这个空物体就作为line的终点,就将lineRender的第二个position设置为这个空物体即可。
当然你也可以直接继承point类,但是我觉得point里面有些没必要的于是就写多了这个。新手起步,大神勿喷。谢谢宝贵意见。