初始Unity 3D——小Demo打砖块

需求:鼠标点击墙壁,从观察者角度发射子弹,击中墙壁砖块。子弹在五秒钟后消失

从小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 () {

    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值