move player
创建一个Sphere,命名为PlayerController,并把它设置为Rigidbody
添加script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
public float speed;//设置为public就可以在unity内改变speed的值
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update () {
}
//is called before performing any physics calculations
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(speed*movement);
}
}
move camera
让Camera随着Player的移动而移动
为Camera添加Script: CameraController.cs
offset的值为camera 位置与 player位置的差值
public class CameraController : MonoBehaviour {
public GameObject player;
private Vector3 offset;
// Use this for initialization
void Start () {
offset = transform.position - player.transform.position;
}
// Update is called once per frame
void LateUpdate () {//LateUpdate 在所有Update被执行完之后再执行,也是每帧都跟新。
transform.position = player.transform.position + offset;
}
}
把Unity中的Plyaer给到CameraCotroller.cs中的player变量
设置碰撞物
create cube(we call it 'pick up')
让cube自动旋转-->添加script:Rotator.cs
public class Rotator : MonoBehaviour {
// Update is called once per frame
void Update () {
transform.Rotate(new Vector3(15, 30, 45)*Time.deltaTime);//
}
}
要生成多个cube,所以设置为prefab.(prefabs包含一个或者多个游戏对象模板)
创建prefabs文件夹,并把Hierarchy里的pick up拉到prefabs文件夹里
粘贴多个pick ups
设置prefabs 的颜色-->新建Material
把pick up Material拉到一个pickup上,并点击apply
使用UI 显示文本,例如score
设置text的锚点,使其在左上角:
在PlayerController.cs设置Text变量用于显示count:
public class PlayerController : MonoBehaviour {
public float speed;//设置为public就可以在unity内改变speed的值
public Text countText;//关联到Unity里的 Count Text UI
private Rigidbody rb;
private int count;
void Start()
{
rb = GetComponent<Rigidbody>();
count = 0;
countText.text = "Count: " + count.ToString();
}
// Update is called once per frame
void Update () {
}
//is called before performing any physics calculations
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(speed*movement);
}
void SetCountText()
{
countText.text = "Count: " + count.ToString();
}
}
碰撞检测
我们可以在collier sphere右上角找到collider的使用方法
void OnTriggerEnter(Collider other)
{
// Destroy(other.gameObject);我们需要禁用而不是销毁碰撞对象
count = count + 1;
SetCountText();
}
我们需要查看GameObject API 看怎么禁用GameObject如果碰撞了
我们使用CompareTag和SetActive两个API:
先看看事例代码:
所以我们这样写代码:
void OnTriggerEnter(Collider other)
{
// Destroy(other.gameObject);我们需要禁用而不是销毁碰撞对象
if(other.gameObject.CompareTag("Pick up"))
{
other.gameObject.SetActive(false);
}
count = count + 1;
SetCountText();
}
然后我们在Unity中为所有的pick up设置Tag为“Pick up”
unity 中的Tag必须和代码中的保持一致:
必须把prefabs变成触发器!!
现在可以实现碰撞后pick up消失了!