Pico在Unity开发中点击事件及检测的功能实现
一、创建RayCtrl脚本并挂载在(射线检测参考主页中射线检测的文章,这边不做过多解释)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RayCtrl : MonoBehaviour
{
private LineRenderer line;
public GameObject NowGameObject;
private GameObject StartPos;
public static Vector3 hitPos;
public Transform dot;
private RaycastHit hit;
public static string name;
// Use this for initialization
void Start()
{
line = transform.Find("ray_LengthAdaptive").GetComponent<LineRenderer>();
line.gameObject.SetActive(true);
dot = transform.Find("dot");
dot.gameObject.SetActive(true);
StartPos = GameObject.Find("StartPos");
hitPos = Vector3.zero;
}
// Update is called once per frame
void Update()
{
Ray ray = new Ray { origin = StartPos.transform.position, direction = StartPos.transform.forward };
line.SetPosition(0, ray.origin);
if (Physics.Raycast(ray, out hit, 1000))
{
line.SetPosition(1, hit.point);
line.startColor = Color.green;
dot.position = hit.point;
hitPos = hit.point;
NowGameObject = hit.transform.gameObject;
name = NowGameObject.name;
}
else
{
line.SetPosition(1, ray.origin + ray.direction * 2);
line.startColor = Color.red;
dot.position = ray.origin + ray.direction * 2;
hitPos = ray.origin + ray.direction * 2;
name = null;
}
}
}
具体如下图:
二、创建代码GameObjectManager
为了方便检测,我这里写了一个鼠标左键点击的检测。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Pvr_UnitySDKAPI;
public class GameObjectManager : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (RayCtrl.name == this.gameObject.name)
{
if (Input.GetMouseButton(0) || Controller.UPvr_GetKey(1, Pvr_KeyCode.TRIGGER))
{
//这里写需要的功能
}
}
}
}
这里为了测试,我写了一个旋转事件。
将GameObjectManager脚本添加到需要进行交互的物体上(物体身上必须要有碰撞体)