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疊成一堵墻

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:拖拽可賦予游戲物體屬性