/******************************
*PC用Kinect玩水果忍者核心代码*
******************************/
private const double ArmXStretchedThreshold = 0.3;//手臂X轴方向伸展阀值,单位米
private const double ArmZStretchedThreshold = 0.2;//手臂Z轴方向伸展阀值,单位米
private bool isMouseLeftButtonDown = false;
void kinect_SkeletonFrameReady(object sender,SkeletonFrameReadyEventArgs e)
{
if(isWindowsClosing)
{
return;
}
//获取距离Kinect距离最近的被骨骼跟踪的用户
Skeleton s = GetClosetSkeleton(e);
if(s == null)
{
return;
}
if(s.TrackingState == SkeletonTrackingState.Tracked)
{
var joints = s.Joints;
Joint rightHand = Joints[JointType.HandRight];
Joint leftHand = Joints[JointType.HandLeft];
Joint head = Joints[JointType.Head];
//根据Kinect距离判定是左手还是右手操作鼠标,兼容左右手
var hand = (rightHand.Position.Z < leftHand.Position.Z ? rightHand : leftHand);
//如果手没有伸出,则不做跟踪
if(head.Position.Z - hand.Position.Z <= ArmZStretchedThreshold)
{
return;
}
//模拟鼠标移动
TrackHand2SimulateMouseMove(hand);
bool isLeftHandStretched = ((head.Position.X-leftHand.Position.X)>=ArmXStretchedThreshold && (head.Position.Z-hand.Position.Z)<ArmZStretchedThreshold);
bool isRightHandStretched = ((rightHand.Position.X-leftHand.Position.X)>=ArmXStretchedThreshold) && (head.Position.Z-hand.Position.Z)<ArmZStretchedThreshold);
//无论左手或右手水平举起,模拟鼠标左键按下事件
if(isLeftHandStretched || isRightHandStretched)
{
MouseToolkit.mouse_event(MouseToolkit.MouseEventFlag.LeftDown,0,0,0,0);
isMouseLeftButtonDown = true;
}
else if(isMouseLeftButtonDown)
{
isMouseLeftButtonDown = false;
MouseToolkit.mouse_event(MouseToolkit.MouseEventFlag.LeftUp,0,0,0,0);
}
}
}
private void TrackHand2SimulateMouseMove(Joint hand)
{
if(hand.TrackingState != JointTrackingState.Tracked)
{
return;
}
//获得屏幕高度和宽度
int screenWidth = (int)SystemParameters.PrimaryScreenWidth;
int screenHeight = (int)SystemParameters.PrimaryScreenHeight;
//将骨骼坐标映射为屏幕坐标且手在有限范围内移动即可覆盖整个屏幕
float posX = hand.ScaleTo(screenWidth,screenHeight,0.2f,0.2f).Position.X;
float posY = hand.ScaleTo(screenWidth,screenHeight,0.2f,0.2f).Position.Y;
Joint scaledCursorJoint = new Joint
{
TrackingState = JointTrackingState.Tracked;
Position = new SkeletonPoint
{
X = posX;
Y = posY;
Z = hand.Position.Z;
}
};
int x = Convert.ToInt32(scaledCursorJoint.Position.X);
int y = Convert.ToInt32(scaledCursorJoint.Position.Y);
int mouseX = Convert.ToInt32(x*65536/screenWidth);
int mouseY = Convert.ToInt32(x*65536/screenHeight);
MouseToolkit.mouse_event(MouseToolkit.MouseEventFlag.Absolute|MouseToolkit.MouseEventFlag.Move,mouseX,mouseY,0,0);
}
PC用Kinect玩水果忍者核心代码
最新推荐文章于 2019-05-16 17:32:39 发布