游戏界面:
游戏实现思路:
游戏开始随机生成5个Box
键盘输入控制Player移动 当Player碰撞到物体 检测物体身上标签
如果Tag为Box则Box销毁 在其位置生成一个Gold
如果Tag为Gold则Gold销毁 得分+1
游戏实现过程:
所需物体: Box Gold(Prefabs)用于实例化、Player、Text(计算得分)CreatBOx(空物体,控制Box生成)
所需脚本:
Gold 挂载在预制体Gold上,实现金币自动旋转
using UnityEngine;
using System.Collections;
public class Gold : MonoBehaviour {
private Transform transform;
void Start () {
transform = gameObject.GetComponent<Transform>();
}
void Update () {
//使物体旋转
transform.Rotate(Vector3.left,5);
}
}
Box 挂载在预制体Box上 实现物体生成后3-5s内销毁
using UnityEngine;
using System.Collections;
public class Box : MonoBehaviour {
// Use this for initialization
void Start () {
//销毁物体 随机3-5s
GameObject.Destroy(gameObject, Random.Range(3, 5));
}
}
CreatBox 挂载在物体CreatBox上 实现Box的生成
using UnityEngine;
using System.Collections;
public class CreatBox : MonoBehaviour {
public GameObject prefabs;
void Start () {
//调用函数 开始3s后调用 每隔3s执行一次
InvokeRepeating("Creatbox", 3, 3);
}
void Creatbox() {
for (int i = 0; i < 5; i++)
{
//实例化对象(预制体,随机位置,不旋转)
GameObject.Instantiate(prefabs,new Vector3(Random.Range(-4.5f,4.5f),5, Random.Range(-4.5f, 4.5f)),Quaternion.identity);
}
}
}
Play 挂载在物体Palyer上 控制物体移动 及碰撞检测及得分
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Play: MonoBehaviour
{
private Rigidbody rigidbody;
public GameObject gold;
public Text text;
int Score = 0;
void Start()
{
rigidbody = gameObject.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
//输入检测 给Rigidbody添加力 实现物体移动
if (Input.GetKey(KeyCode.W))
{
rigidbody.AddForce(Vector3.forward * 10, ForceMode.Force);
}
if (Input.GetKey(KeyCode.S))
{
rigidbody.AddForce(Vector3.back * 10, ForceMode.Force);
}
if (Input.GetKey(KeyCode.A))
{
rigidbody.AddForce(Vector3.left * 10, ForceMode.Force);
}
if (Input.GetKey(KeyCode.D))
{
rigidbody.AddForce(Vector3.right * 10, ForceMode.Force);
}
}
private void OnCollisionEnter(Collision collision)
{
//碰撞检测
/*Box就销毁盒子 然后实例化金币
* Gold就得分+1
*/
if (collision.gameObject.tag == "Box")
{
print("1");
Vector3 vector = collision.transform.position;
print("2");
GameObject.Destroy(collision.gameObject);
GameObject.Instantiate(gold, vector + Vector3.forward, Quaternion.identity);
}
if (collision.gameObject.tag == "Gold")
{
GameObject.Destroy(collision.gameObject);
Score++;
text.text = "得分:" + Score;
}
}
}