以下就是脚本代码,直接使用就行了
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GetPlayerIcon : MonoBehaviour
{
private KinectManager _kinectManager;
private int _headIndex = (int)KinectInterop.JointType.Head;
public GameObject objPlayerIcon;
private Texture2D destTex;
// Use this for initialization
void Start()
{
_kinectManager = KinectManager.Instance;
destTex = new Texture2D(200, 200);
}
// Update is called once per frame
void Update()
{
if (_kinectManager.GetUsersCount() >= 1)
{
if (GameControl._playerId != 0)
{
objPlayerIcon.GetComponent<RawImage>().texture = GetIcon(GameControl._playerId);
}
//objPlayerIcon.GetComponent<GUITexture>().texture = GetIcon(DragonDanceS._playerId);
}
}
/// <summary>
/// 获取玩家图像
/// </summary>
/// <param name="userId">玩家的kinect playerId</param>
/// <returns></returns>
private Texture2D GetIcon(long userId)
{
if (!JointTracked(userId, _headIndex))
{
return null;
}
else
{
Vector2 posDepth = _kinectManager.MapSpacePointToDepthCoords(JointPosition(userId, _headIndex));
ushort depthValue = _kinectManager.GetDepthForPixel((int)posDepth.x, (int)posDepth.y);
Vector2 posColor = _kinectManager.MapDepthPointToColorCoords(posDepth, depthValue);
Texture2D sourceTex = _kinectManager.GetUsersClrTex();
//Texture2D destTex = new Texture2D(200, 200);
Color[] pix = sourceTex.GetPixels((int)Mathf.Clamp((int)posColor.x - 100, 0, (sourceTex.width - 200)), (int)Mathf.Clamp((int)(posColor.y - 100), 0, (sourceTex.height - 200)), 200, 200);
for (int i = 0; i < destTex.height; i++)
{
for (int j = 0; j < destTex.width; j++)
{
destTex.SetPixel(j, i, pix[(destTex.height - i - 1) * destTex.width + j]);
}
}
destTex.Apply();
return destTex;
}
}
/// <summary>
/// 获取骨骼点相对Kinect的坐标
/// </summary>
/// <param name="userId">玩家Id</param>
/// <param name="joint">骨骼点</param>
/// <returns></returns>
private Vector3 JointPosition(long userId, int joint)
{
return _kinectManager.GetJointKinectPosition(userId, joint);
}
/// <summary>
/// 判断骨骼点是否被检测到
/// </summary>
/// <param name="userId"></param>
/// <param name="joint"></param>
/// <returns></returns>
private bool JointTracked(long userId, int joint)
{
return _kinectManager.IsJointTracked(userId, joint);
}
}
注意:
1.新建一个RawImage(必须是RawImage),然后将这个脚本挂载到RawImage节点上
2.必须要勾选KinectManger中的Compute Color Map选项!!!