using UnityEngine;
using System.Collections;
public class Brick : MonoBehaviour {
public GameObject brickPrefab;
public GameObject bulletPrefab;
void Start () {
//6*10
//行距
float row =1;
//列距
float column=1;
//6行
for (int i = 0; i < 6; i++) {
//10列
for (int j = 0; j < 10; j++) {
Vector3 brickPs = new Vector3 (-4.5f + j * row, 0.5f + i * column, 3);
Instantiate(brickPrefab,brickPs,Quaternion.identity);
}
}
}
// Update is called once per frame
void Update ()
{
//发射子弹
if(Input.GetMouseButtonDown(0))
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),out hit))
{
if (hit.collider.tag=="brick")
{
GameObject bullet = Instantiate (bulletPrefab, Camera.main.transform.position, Quaternion.identity)as GameObject;
Vector3 dir = hit.point - Camera.main.transform.position;
dir.Normalize();
bullet.GetComponent<Rigidbody>().velocity = dir * 200;
Destroy (bullet, 3);
}
}
}
}
}
操作步骤:
*************在场景中新建Plane,Cube,Sphere;
*************把brick和bullet设置为预制体,并分别为其添加Rigidbody(默认值);
*************把上述代码赋给Plane(也可新建一空物体,赋到空物体上),把两个预制体放置到对应的位置。
如果想让墙体在被打落之后消失,只需要将以下代码赋给brick(预制体)上即可。代码如下:
using UnityEngine;
using System.Collections;
public class xiaoshiSript : MonoBehaviour {
public bool isOver = false;
void Start () {
}
// Update is called once per frame
void Update () {
if (transform.position.y < 0 ) {
Destroy (gameObject,1);//一秒后消失
}
}
}
*************注意:把bullet(子弹)的碰撞检测类型改为Continuous Dynamic,否则会射穿墙体。