Moving the camera
接下来我们来编写一个控制摄像机跟随球的脚本。这个流程其实非常简单。先创建一个脚本。内容如下:
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour {
public GameObject player;
private Vector3 offset;
void Start () {
offset = transform.position;
}
void LateUpdate () {
transform.position = player.transform.position + offset;
}
}
定义一个offset的向量,将自己的转换坐标复制过去。然后定义一个共有的player GameObject。然后在Inspactor就能在Script这一栏里面看到player变量,然后从Hierarchy里面把Player拖到变量后面,这样就建立了关联。在LastUpdate函数中将当前摄像机位置+player的位置向量,这样就实现了摄像机的跟随。
Creating pick-up objects
接下来创建一些拾取的cube。这个流程和创建Player的流程相同。我们为这个cube创建一个旋转的脚本
using UnityEngine;
using System.Collections;
public class Rotator : MonoBehaviour {
// Update is called once per frame
void Update () {
transform.Rotate (new Vector3(15,30,45)*Time.deltaTime);
}
}
重载Update函数,并且将其按照时间来做一个旋转。为了方便拾取的时候检测到cube,我们需要将cube的tag打成PickUp
Collecting and counting
接着就是将球体移动时候,加入碰撞检查。当球体碰到了cube,将会让cube不显示。这个流程也是通过脚本来做实现的。
void OnTriggerEnter (Collider other)
{
if (other.gameObject.tag == "PickUp")
{
other.gameObject.SetActive(false);
count ++;
countText.text = "Count: " + count.ToString ();
}
}
这个代码是写到PlayerController.cs文件中的。也是绑定在Player这个对象上。OnTriggerEnter是一个碰撞检测的回调函数,我们需要通过other.gameObject.tag这个属性读取出名字,如果为PickUp,那就说明是cube。接下来就将这个cube的Active设置成false。这样就会在游戏中隐藏到这些cube。