unity射擊小游戲,第一人稱攝像機實作
今天開始寫一些unity的小教程,就以剛剛寫的第一人稱的射擊小游戲作為案例,
先上效果圖:


首先游戲物品也沒有多少東西,就是地板,平行光,主攝像機,然后我們需要做一個子彈,這個子彈里面添加剛體,然后把它作為預設體保存,
生成fire.cs檔案,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fire : MonoBehaviour
{
public int speed =5;
public GameObject newObject;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float z= Input.GetAxis("Vertical") * speed*Time.deltaTime;
float x= Input.GetAxis("Horizontal") * speed *Time.deltaTime;
transform.Translate(x, 0, z);
if(Input.GetButtonDown("Fire1"))
{
GameObject n = Instantiate(newObject,transform.position,transform.rotation);
Vector3 fwd;
fwd = transform.TransformDirection(Vector3.forward);
n.GetComponent<Rigidbody>().AddForce(fwd*6000);
Destroy(n, 5);
}
if (Input.GetKey(KeyCode.Q))
{
transform.Rotate(0, -50 * Time.deltaTime, 0);
}
if (Input.GetKey(KeyCode.E))
{
transform.Rotate(0, 50 * Time.deltaTime, 0);
}
if (Input.GetKey(KeyCode.Z))
{
transform.Rotate(-50 * Time.deltaTime, 0, 0);
}
if (Input.GetKey(KeyCode.C))
{
transform.Rotate(50 * Time.deltaTime, 0, 0);
}
}
}
這份代碼直接掛在攝像機上面,newObject就是放入剛剛保存的預設體子彈就行了,
代碼決議:
float z= Input.GetAxis("Vertical") * speed*Time.deltaTime;
float x= Input.GetAxis("Horizontal") * speed *Time.deltaTime;
這里是管攝像頭,也就是第一人稱上下左右移動的,
if(Input.GetButtonDown("Fire1"))
{
GameObject n = Instantiate(newObject,transform.position,transform.rotation);
Vector3 fwd;
fwd = transform.TransformDirection(Vector3.forward);
n.GetComponent<Rigidbody>().AddForce(fwd*6000);
Destroy(n, 5);
}
這里管開火鍵,也就是滑鼠左鍵,
仔細看這里的代碼,這是預設體生成,也就是你們想要用代碼動態生成物品,就要學習這部分代碼,并且生成的子彈添加了一個向前的力,讓它飛出去,
if (Input.GetKey(KeyCode.Q))
{
transform.Rotate(0, -50 * Time.deltaTime, 0);
}
剩下這部分代碼也就是管鍵盤事件,鍵盤按鍵輸入,然后控制攝像機旋轉,達到鏡頭左右上下轉動的效果,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/266294.html
標籤:其他
