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

版权声明:本文为博主原创文章,如需转载,请注明出处: https://blog.csdn.net/MASILEJFOAISEGJIAE/article/details/84452962

Unity版本:Unity 2018.2.14f1
原视频链接:https://unity3d.com/cn/learn/tutorials/s/space-shooter-tutorial

教程目录(持续更新中):
Unity游戏开发官方入门教程:飞机大战(一)——创建新项目、导入资源、设置场景
Unity游戏开发官方入门教程:飞机大战(二)——创建飞船对象
Unity游戏开发官方入门教程:飞机大战(三)——设置相机和光照
Unity游戏开发官方入门教程:飞机大战(四)——使用Quad加入背景
Unity游戏开发官方入门教程:飞机大战(五)——实现飞船控制脚本
Unity游戏开发官方入门教程:飞机大战(六)——创建子弹
Unity游戏开发官方入门教程:飞机大战(七)——发射子弹


本节要点

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

创建子弹挂点

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

修改Player的PlayerController.cs脚本

  1. 增加Update()函数,并使用Instantiate()方法进行子弹对象实例化。
  2. 增加3个public对象:shot、shotSpawn和fireRate,分别用于指定子弹对象、子弹挂点和子弹发射间隔时间。
  3. 增加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对象

  1. 将prafabs中的Bolt拖拽到Inspector中的Shot
  2. 将Hierarchy中的Shot Spawnt拖拽到Inspector中的Shot Spawnt
  3. 将Fire Rate设置为0.2
  4. 运行游戏,按下鼠标左键,效果如下:

参考资料:https://unity3d.com/cn/learn/tutorials/s/space-shooter-tutorial

猜你喜欢

转载自blog.csdn.net/MASILEJFOAISEGJIAE/article/details/84452962