打墙砖(射线)

问题.png
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);
                }
            }
        }

    }
}
整体界面.png
碰撞检测.png

操作步骤:
*************在场景中新建Plane,Cube,Sphere;
*************把brick和bullet设置为预制体,并分别为其添加Rigidbody(默认值);
*************把上述代码赋给Plane(也可新建一空物体,赋到空物体上),把两个预制体放置到对应的位置。

代码赋值.png

如果想让墙体在被打落之后消失,只需要将以下代码赋给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,否则会射穿墙体。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容