之前完成一个体感接钻石的小游戏,大体过程就是天上掉钻石,用一个物体接住,这个物体是通过kinect来控制的他的前后左右。接到不同的钻石就可以获得不同的得分。
这段代码是下落的位置,下落的游戏物体,还定义了ScoreHit()得分。主要解决海上下落问题,此脚本具有通用性。
using UnityEngine;
using System.Collections.Generic;
public class BallCreator : MonoBehaviour
{
// the ball prefab. @note MUST be attached
public GameObject prefab;
// the object we create the balls near @note MUST be attached.
public Transform where;
// holds the player mapper (used to find out if we have a target player).
public NIPlayerManager m_playerManager;
// the time to create the next ball
//private float m_timeToCreateNextBall;
public float m_timeToCreateNextBall;
// The number of balls the user hit (used for scoring)
private int m_numBallsHit = 0;
// The number of balls created (used for scoring)
// private int m_numBallsCreated;
public int m_numBallsCreated;
// Marks that the user has scored a hit (used for scoring).
//
public void ScoreHit()
{
m_numBallsHit++;
}
// mono-behavior initialization
public void Start () {
m_numBallsHit = 0;
m_numBallsCreated = 0;
m_timeToCreateNextBall = 0;
if(m_playerManager==null)
m_playerManager = FindObjectOfType(typeof(NIPlayerManager)) as NIPlayerManager;
}
// mono-behavior Update is called once per frame
public void Update ()
{
if (Time.time < m_timeToCreateNextBall)
return; // we created a ball very recently, wait.
if (m_playerManager == null)
return; // this means we don't even have a plyer manager.
NISelectedPlayer player = m_playerManager.GetPlayer(0);
if (player == null || player.Valid == false || player.Tracking == false)
return; // this means we don't have a calibrated user
if (SkeletonGuiControl.m_mode == SkeletonGuiControl.SkeletonGUIModes.GUIMode)
return; // we don't throw balls while in GUI mode.
// now we know we should throw a ball. We first figure out where (a random around the
// x axis of the "where" transform and a constant modifier on the y and z).
Vector3 pos = where.position;
pos.x += Random.Range(- 2.0f, 2.0f);
pos.y += 8.0f;
pos.z += 2.1f;
// create the ball
Instantiate(prefab, pos, Quaternion.identity);
m_numBallsCreated++;
// we set the time for the next ball. The time itself depends on how many balls were created
// (the more balls, the less time on average).
float maxTime = 5.0f;
float minTime = 1.0f;
if (m_numBallsCreated > 15)
maxTime = 4.0f;
if (m_numBallsCreated > 30)
maxTime = 3.0f;
if (m_numBallsCreated > 45)
minTime = 0.5f;
if (m_numBallsCreated > 85)
maxTime = 2.0f;
m_timeToCreateNextBall = Time.time + Random.Range(minTime,maxTime);
}
// mono-behavior OnGUI shows the scoring
void OnGUI()
{
if (SkeletonGuiControl.m_mode == SkeletonGuiControl.SkeletonGUIModes.GUIMode)
return; // we don't draw score while in GUI mode.
GUI.Box(new Rect(Screen.width/2 -100, 10, 200, 20), "You Hit " + m_numBallsHit + " balls of " + m_numBallsCreated);
}
}