詳談Unity物理射線發射子物打中實體化物件_心智圖擴展_反彈功能單元測試

我們要結合前面幾張心智圖

要實踐用物理射線打中
牆壁,牆壁碎裂(牆壁用兩層for loop生成)
添加RigidBody在牆壁Cube上

Unity中的

輸入部分:

物件屬性/方法







第一階段 .  生成一堵牆


前置動作

腳本添加至   MainCamera

調整地面


針對 做好的  Brick 預置物添加  鋼體




Ver1.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RayHit : MonoBehaviour {
    //牆壁的  寬 、 高
    private int x=10;//寬  10 Cube
    private int y=5;//高  5  Cube

    public GameObject prefabBrick;

    // Use this for initialization
    void Start () {
        for (int i = 0; i < x; i++)
            for (int j = 0; j < y; j++) {
                GameObject.Instantiate(prefabBrick,new Vector3(i,j,0),Quaternion.identity);
            }
    }
    
    // Update is called once per frame
    void Update () {
        
    }
}


改至中央位置(牆壁至中)


第二階段 .  將 生成一堵牆  程式 從 start()生命週期方法中額外封裝提出成一個函數



第三階段.  增加輸入互動

創建子彈 prefab


針對攝影機畫面位置發射球體



Ver2.


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RayHit : MonoBehaviour {
    private int x = 10;  //宽度.
    private int y = 5;  //高度.

    private Ray ray;
    private RaycastHit hit;

    public GameObject prefabBrick;
    public GameObject prefabBullet;

    private Transform m_Transform;

    void Start () {
        m_Transform = gameObject.GetComponent<Transform>();
        CreateWall();
    }


    void Update () {
        SendBullet();
    }

    /// <summary>
    /// for循环生成墙壁.
    /// </summary>
    void CreateWall()
    {
        for (int i = 0; i < x; i++)
        {
            for (int j = 0; j < y; j++)
            {
                GameObject.Instantiate(prefabBrick, new Vector3(i - 5, j, 0), Quaternion.identity);
            }
        }
    }

    /// <summary>
    /// 发射子弹.
    /// </summary>
    void SendBullet()
    {
        if (Input.GetMouseButtonDown(0))
        {
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {
                //实例化子弹.
                GameObject go = GameObject.Instantiate(prefabBullet, m_Transform.position, Quaternion.identity) as GameObject;

                //计算方向.
                Vector3 dir = hit.point - m_Transform.position;

                //发射子弹.
                go.GetComponent<Rigidbody>().AddForce(dir * 300);
            }
        }
    }
}




效果











留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients