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

15 篇文章 6 订阅

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

教程目录:
Unity游戏开发官方入门教程:飞机大战(一)——创建新项目、导入资源、设置场景
Unity游戏开发官方入门教程:飞机大战(二)——创建飞船对象
Unity游戏开发官方入门教程:飞机大战(三)——设置相机和光照
Unity游戏开发官方入门教程:飞机大战(四)——使用Quad加入背景
Unity游戏开发官方入门教程:飞机大战(五)——实现飞船控制脚本
Unity游戏开发官方入门教程:飞机大战(六)——创建子弹
Unity游戏开发官方入门教程:飞机大战(七)——发射子弹
Unity游戏开发官方入门教程:飞机大战(八)——创建销毁边界
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

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值