Unity HTC Vive通过手柄控制模型的手臂运动旋转

在物理实验室模拟kinect模块中的拓展功能,手柄控制模型手臂的移动。

由于找不到合适的骨骼绑定的模型,项目中采用了一个手臂悬空的模型。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using VRTK;
using VRTK.Highlighters;

public class moveByLeft : MonoBehaviour {

	private Vector3 rePos;

	private GameObject LeftController;

	private Vector3 tarPos;

	private Vector3 reConPos;
	private Vector3 ConPos;

	private float transX;
	private float transY;
	private float transZ;

	// Use this for initialization
	void Start () {
		rePos = this.transform.position;

		LeftController = VRTK_DeviceFinder.GetControllerLeftHand();
		reConPos = LeftController.transform.position;
	}

	// Update is called once per frame
	void Update () {
		ConPos = LeftController.transform.position;

		transX = ConPos.x - reConPos.x;
		transY = ConPos.y - reConPos.y;
		transZ = ConPos.z - reConPos.z;

		tarPos.x = rePos.x + transX;
		tarPos.y = rePos.y + transY;
		tarPos.z = rePos.z + transZ;

		this.transform.position = tarPos;
		this.transform.rotation = LeftController.transform.rotation;
	}
}

左臂右臂分别通过不同的脚本控制。首先记录手臂的位置,初始的坐标,记录为repos。通过VRTK_DeviceFinder获取手柄的位置,记录坐标。在update函数中,执行过程中不断监听记录手柄的位置变换,分别计算x轴y轴z轴的位移量偏差,定义新的三维数组,将位移量偏差与手臂的初始位置叠加,使手臂根据手柄位置进行实时运动。

旋转同理。左臂右臂同理。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using VRTK;
using VRTK.Highlighters;


public class moveByControl : MonoBehaviour {

	private Vector3 rePos;

	private GameObject RightController;

	private Vector3 tarPos;

	private Vector3 reConPos;
	private Vector3 ConPos;

	private float transX;
	private float transY;
	private float transZ;

	// Use this for initialization
	void Start () {
		rePos = this.transform.position;

		RightController = VRTK_DeviceFinder.GetControllerRightHand ();
		reConPos = RightController.transform.position;
	}
	
	// Update is called once per frame
	void Update () {
		ConPos = RightController.transform.position;

		transX = ConPos.x - reConPos.x;
		transY = ConPos.y - reConPos.y;
		transZ = ConPos.z - reConPos.z;

		tarPos.x = rePos.x + transX;
		tarPos.y = rePos.y + transY;
		tarPos.z = rePos.z + transZ;

		this.transform.position = tarPos;
		this.transform.rotation = RightController.transform.rotation;
	}
}

你可能感兴趣的:(HTCVive,Unity3D,C#)