Hello,我是KitStar。
以下文章整理的不对。还请见谅。
using UnityEngine;
using System.Collections;
using MPVR.Device; //这个命名空间是我们自己写的,主要封装着手柄的一个操作
using System;
public class VRTeleporter : MonoBehaviour {
public LayerMask groundMask;
[Serializable]
public class ColorCycle
{
public Color pressDown;
public Color triggering;
}
public ColorCycle colorCycle;
public Transform target; //移动的目标
public Transform rayModel; //射线物体
public Transform hitModel; //射线触碰时生成的物体
bool m_updating = false; //是否开始Update
bool m_hitted = false; //是否检测到物体
Ray m_ray;
RaycastHit m_hit;
void Start() {
ViveManager.Instance.R.onTouchpadPressDown = OnTouchpadPressDown; //这两个主要时我们自己封装的对于手柄按下Touchpad键时触发。你可以用VIVE内置的接口
ViveManager.Instance.R.onTouchpadPressUp = OnTouchpadPressUp;
rayModel.gameObject.GetComponent<MeshRenderer>().enabled = false;
hitModel.gameObject.GetComponent<MeshRenderer>().enabled = false;
Material newMaterial = new Material(Shader.Find("Unlit/Color"));
rayModel.gameObject.GetComponent<MeshRenderer>().material = newMaterial;
}
void OnTouchpadPressDown(ViveController.HandSide handSide) {
m_updating = true;
rayModel.gameObject.GetComponent<MeshRenderer>().enabled = m_updating;
}
void OnTouchpadPressUp(ViveController.HandSide handSide) {
m_updating = false;
rayModel.gameObject.GetComponent<MeshRenderer>().enabled = m_updating;
if (m_hitted) {
target.position = new Vector3(m_hit.point.x - this.transform.localPosition.x, 0, m_hit.point.z - this.transform.localPosition.z);
}
}
GameObject TeleportPlane;
void Update() {
if (m_updating) {
m_ray = new Ray(this.transform.position, this.transform.forward);
m_hitted = Physics.Raycast(m_ray, out m_hit, groundMask);
if(m_hitted)
{
TeleportPlane = m_hit.collider.gameObject;
rayModel.gameObject.GetComponent<MeshRenderer>().material.SetColor("_Color", colorCycle.triggering);
TeleportPlane.GetComponent<MeshRenderer>().material.SetColor("_Color", new Color(0.6f,1,1,0.2f));
rayModel.transform.localScale = new Vector3(0.004f, 0.004f, 10f);
hitModel.gameObject.GetComponent<MeshRenderer>().enabled = m_hitted;
}
else
{
rayModel.gameObject.GetComponent<MeshRenderer>().material.SetColor("_Color", colorCycle.pressDown);
rayModel.transform.localScale = new Vector3(0.001f, 0.001f, 10f);
TeleportPlane.GetComponent<MeshRenderer>().material.SetColor("_Color", new Color(0,0,0,0));
hitModel.gameObject.GetComponent<MeshRenderer>().enabled = false;
}
hitModel.position = m_hit.point;
}
}
}