今天和同学开语音时间有点长,得抓紧在凌晨之前写完博客。
本篇博客完成的功能是实现飞盘的设计。思路:
创建一个飞盘物体,设置tag,设置材质,创建预制体。创建一个空物体用来管理飞盘创建,挂在一个脚本,在start方法中使用Invoke函数来定时调用飞盘批量创建方法(最好在创建时使用transform的setParent方法将创建的飞盘都放FeiPanParent之下)。当摄像机发出的射线射到了飞盘之上,同时又点击到了飞盘,满足条件时,通过飞盘的碎片查找到碎片的父物体transform.parent,再通过父物体的tansform来获取父物体之下的所有飞盘碎片trnaform.GetComponent(),返回一个Transform类型的数组,循环数组,给数组对应的物体添加刚体组件使其坠落。同时,获取到碎片的父物体时,使用GameObject.Destroy方法定时销毁整个飞盘
上代码:
武器脚本:
using UnityEngine;
using System.Collections;
public class Weapon : MonoBehaviour {
private Transform m_Transform; //武器trans
private Transform m_Point; //枪口
private Ray ray; //Camera发出的射线
private RaycastHit hit; //射线碰撞物体的信息
public AudioSource m_AudioSource; //声音元
private LineRenderer line;
void Start () {
m_AudioSource = gameObject.GetComponent<AudioSource>();
m_Transform = gameObject.GetComponent<Transform>();
m_Point = m_Transform.FindChild("Point");
line = m_Point.gameObject.GetComponent<LineRenderer>();
}
void Update () {
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray,out hit))
{
//控制手臂朝向鼠标位置
m_Transform.LookAt(hit.point);
//绘制测试线
Debug.DrawLine(m_Point.position, hit.point, Color.red);
//通过设置LineRender的位置来绘制瞄准线
line.SetPosition(0, m_Point.position);
line.SetPosition(1, hit.point);
//鼠标点击到了飞盘
if (Input.GetMouseButtonDown(0)&&hit.collider.tag=="FeiPan")
{
Fire(hit);
}
}
}
//射击飞盘
void Fire(RaycastHit hit)
{
m_AudioSource.Play();
//获取与射线碰撞点的字飞盘的父物体
Transform parent = hit.collider.gameObject.GetComponent<Transform>().parent;
//通过父物体获取其下所有子物体
Transform[] feiPans = parent.gameObject.GetComponentsInChildren<Transform>();
//循环遍历所有子物体,给其添加刚体使其坠落
for (int i=0;i<feiPans.Length;i++)
{
feiPans[i].gameObject.AddComponent<Rigidbody>(); //添加刚体使其坠落
}
//射击飞盘之后使其定时销毁
GameObject.Destroy(parent.gameObject, 1.0f);
}
}
飞盘管理脚本:
using UnityEngine;
using System.Collections;
public class FeiPanManager : MonoBehaviour {
public GameObject prefab_FeiPan;
private Transform m_Transform;
void Start () {
InvokeRepeating("CreateFeiPan", 2, 1);
m_Transform = gameObject.GetComponent<Transform>();
}
void Update () {
}
/// <summary>
/// 随机创建飞盘
/// </summary>
void CreateFeiPan()
{
for (int i=0;i<3;i++)
{
//飞盘随机生成的位置
Vector3 pos = new Vector3(Random.Range(-6.0f,6.0f),Random.Range(1,5), Random.Range(52,58));
GameObject go = GameObject.Instantiate(prefab_FeiPan, pos, Quaternion.identity) as GameObject;
//将创建的物体放在父物体之下,便于管理
go.GetComponent<Transform>().SetParent(m_Transform);
}
}
}