寫一個(gè)發(fā)射子彈打方塊的demo

2019-01-19

今天寫了一個(gè)發(fā)射子彈打方塊的Unity demo

學(xué)習(xí)地址
Unity零基礎(chǔ)入門 - 打磚塊 http://www.sikiedu.com/course/77

項(xiàng)目

game界面

可以實(shí)現(xiàn)的功能:鏡頭的上下左右移動,以及建立一個(gè)球體,發(fā)射球 體

建立模型

在Unity界面創(chuàng)建一個(gè)Plane作為地面,創(chuàng)建一些cube疊成一堵墻

tip:Ctrl+d快捷復(fù)制,Ctrl+移動可以完成模型按照整數(shù)單位移動,旋轉(zhuǎn),將cube放入新建的Prefabs文件夾中
image.png

并且為cube添加剛體組件,使其有剛體屬性
在Prefabs中添加球體,來當(dāng)做子彈

代碼

移動代碼

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
    public float speed = 5;
    // Start is called before the first frame update
    void Start()
    {
    }
    // Update is called once per frame
    void Update()
    {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        //Debug.Log(h);
        transform.Translate(new Vector3(h,v,0) * Time.deltaTime * speed);
    }
}

發(fā)射代碼

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

public class shoot : MonoBehaviour{
    // Start is called before the first frame update
    public GameObject bullet;//子彈
    public float speed = 20;//速度
    void Start(){
    }

    // Update is called once per frame
    void Update(){
        if (Input.GetMouseButtonDown(0))
        {
            GameObject b = GameObject.Instantiate(bullet, transform.position, transform.rotation);//新建一個(gè)子彈,位置為攝像頭位置
            Rigidbody rgb = b.GetComponent<Rigidbody>();//獲取子彈的剛體屬性
            rgb.velocity = transform.forward * speed;//賦予子彈初速度
        }

    }
}

tip:拖拽可賦予游戲物體屬性

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容