Unity3d游戏开发官方入门教程:飞机大战(七)——发射子弹

分类栏目:unity3d教程

230

Unity3d游戏开发官方入门教程:飞机大战(七)——发射子弹

本节要点

  1. Instantiate()用于实例化一个prefab
  2. Input.GetButton()用于接收按钮事件
  3. Time.time用于记录从游戏开始到现在的时间

创建子弹挂点

创建一个游戏对象,命名为Shot Spawn,作为子弹的挂点,并拖拽到Hierarchy的Player中作为child对象
将一个Bolt从prefabs里拖拽出来,拖动Shot Spawn的position的Z,子弹创建的初始位置大概为1.25:

设置完挂点的位置后,从Hierarchy中删除Bolt。

修改Player的PlayerController.cs脚本

增加Update()函数,并使用Instantiate()方法进行子弹对象实例化。
增加3个public对象:shot、shotSpawn和fireRate,分别用于指定子弹对象、子弹挂点和子弹发射间隔时间。
增加1个private对象nextFire,用于计算时间间隔

PlayerController.cs详细脚本如下:



using System.Collections; 

using System.Collections.Generic; 

using UnityEngine; 

[System.Serializable] 

public class Boundary { 

public float xMin, xMax, zMin, zMax; } 

public class PlayerController : MonoBehaviour { 

public float speed; 

public float tilt; 

public Boundary boundary; 

private Rigidbody rb; 

public GameObject shot; 

public Transform shotSpawn; 

public float fireRate; 

private float nextFire; 

void Update() { 

if (Input.GetButton("Fire1") && Time.time > nextFire) { nextFire = Time.time + fireRate; Instantiate(shot, shotSpawn.position, shotSpawn.rotation); } } 

void Start() { rb = GetComponent<Rigidbody>(); } 

void FixedUpdate() { float moveHorizontal = Input.GetAxis("Horizontal"); 

float moveVertical = Input.GetAxis("Vertical"); Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical); 

rb.velocity = movement * speed; rb.position = new Vector3 ( Mathf.Clamp(rb.position.x, boundary.xMin, boundary.xMax), 0.0f, Mathf.Clamp(rb.position.z, boundary.zMin, boundary.zMax) ); 

rb.rotation = Quaternion.Euler(0.0f, 0.0f, rb.velocity.x * -tilt); } }



在Inspector中指定脚本的public对象

将prafabs中的Bolt拖拽到Inspector中的Shot
将Hierarchy中的Shot Spawnt拖拽到Inspector中的Shot Spawnt
将Fire Rate设置为0.2

运行游戏,按下鼠标左键,效果如下: