//模拟打地鼠游戏脚本
using UnityEngine;
using System.Collections.Generic;
public class SctrptTow : MonoBehaviour
{
public Transform[] cubes;
public GameObject mousePrefab;
float _time;
int score = 0;
public TextMesh _textMesh;//暴露出3D文字
//实现如下功能:
//1、实现3D打地鼠游戏,每个方块为出现地
//2、每隔0.5秒,从三个方块里蹦出三个角色,等待0.5秒后回去
//3、玩家用鼠标点击到角色,角色播放一个动画之后消失,每打到一次加一分
//4、倒计时30秒(3D文字显示),结束后以3D文字提示总分数
// 用来做初始化
// 每帧都会调用一次
void Update()
{
_time += Time.deltaTime;//计时器
if (_time > 1f)
{
_time = 0;
Spawn();//两秒后掉用创建方法;
}
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;//创建射线
if (Physics.Raycast(ray,out hit))//判断射线是否发出
{
if (hit.collider.CompareTag("Teddy"))//如果射线指向Tag为"Teddy"的标签
{
hit.collider.enabled = false;//将目标的碰撞器取消
//播放死亡动画
score++;
_textMesh.text = "分数:" + score;
}
}
}
}
void OnGUI()
{
//GUIStyle style = new GUIStyle();//修改GUI的样式
//style.normal.textColor = Color.red;//修改颜色
//style.fontSize = 50;//修改大小
//绘制标签
//GUI.Label(new Rect(0,0,200,50),"分数:" + score ,style);
//绘制buttonm
//if (GUI.Button(new Rect(0, 100, 200, 50), "分数:" + score)) ;
//{}
}
void Spawn()
{
//随机创建三个目标物体
int[] result = Get3RandomInt();
foreach (var num in result)
{
GameObject go = Instantiate(mousePrefab);//克隆目标物体
go.transform.position = cubes[num].position + Vector3.up * 0.5f;//将克隆目标的位置赋为出生地的位置
Destroy(go, 0.5f);
}
}
int[] Get3RandomInt() //随机两个目标的数组
{
List<int> result = new List<int>();
while (result.Count < 2)
{
int num = Random.Range(0, cubes.Length);//随机两个不重复的数字
if (!result.Contains(num))//如果result集合中不包含随机出的数
{
result.Add(num);//则添加这两个数字
}
}
return result.ToArray();//返回数组
}
}