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游戏开发官方入门教程:飞机大战(十一)——游戏控制
本节要点
Instantiate()
用于实例化一个prefabInput.GetButton()
用于接收按钮事件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
- 运行游戏,按下鼠标左键,效果如下:
参考资料:https://unity3d.com/cn/learn/tutorials/s/space-shooter-tutorial
最后
以上就是畅快饼干最近收集整理的关于Unity游戏开发官方入门教程:飞机大战(七)——发射子弹的全部内容,更多相关Unity游戏开发官方入门教程内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复