需求:鼠标点击墙壁,从观察者角度发射子弹,击中墙壁砖块。子弹在五秒钟后消失
从小Demo中学习解决问题的逻辑思路:
1:使用prafab循环创建一堵墙
2:监听鼠标与墙壁的“碰撞“事件
3:发射子弹
1、循环创建墙壁
声明public变量,将砖块brick拖进去
void CreateWall(){
for(int i=0;i< width;i++){
for(int j=0;j< height;j++){
GameObject.Instantiate(brick,newVector3(i.j.0),Quaternion.identity)
}
}
}
2、发射射线,检测两个碰撞
//从主摄像机发射射线到鼠标左键点击的位置
ray=Camera.main.ScreenPointToRay(Input.position);
if(Physics.Raycast(ray,out hit)){
...
}
3、发射子弹
//创建子弹:
GameObject b=GameObject.Instantiate(bullet,camera位置);
//获取子弹发射路线,也就是一个向量
v=hit.position-camera位置;
//沿着路径发射子弹
b.GetComponent<Rigidbody>().AddForce(v*100);
还是感觉没得写,因为步骤简单,想要记住代码的话需要多去实践。下面贴出完整代码。
using UnityEngine;
using System.Collections;
public class RayTest2 : MonoBehaviour {
public GameObject brick;
public GameObject bullet;
private int width=10;
private int height = 6;
private Ray ray;
private RaycastHit hit;
private Transform m_Transform;
void Start () {
m_Transform = gameObject.GetComponent<Transform>();
CreateWall();
}
void Update () {
Fire(); //发射子弹
}
/// <summary>
/// 发射子弹
/// </summary>
void Fire()
{
if (Input.GetMouseButtonDown(0))
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit))
{
//GameObject.Destroy(hit.collider.gameObject); //让砖块消失
//获取子弹发射的路线 Vector3向量
Vector3 v = hit.point - m_Transform.position;
GameObject tempBullet = GameObject.Instantiate(bullet, m_Transform.position, Quaternion.identity) as GameObject;
tempBullet.GetComponent<Rigidbody>().AddForce(v*100);
}
}
}
/// <summary>
/// for循环创建墙壁
/// </summary>
void CreateWall()
{
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
GameObject.Instantiate(brick, new Vector3(i-5, j, 0), Quaternion.identity);
}
}
}
}
下面是子弹的脚本
using UnityEngine;
using System.Collections;
public class Bullet : MonoBehaviour {
void Start () {
GameObject.Destroy(gameObject, 5);
}
void Update () {
}
}