Unity教学如何制作的2D赛车小游戏?
摘要:视频链接: https:www.bilibili.comvideoBV1wT9rYZEKe?spm_id_from=333.788.videopod.sections&vd_source=25b783f5f9
视频链接:
https://www.bilibili.com/video/BV1wT9rYZEKe?spm_id_from=333.788.videopod.sections&vd_source=25b783f5f945c4507229e9dec657b5bb
本教程涉及到 Unity 常用组件、常用方法等核心知识点,掌握本教程相关知识后你就就可以快速掌握一些 Unity2D 常用组件了
1.需求分析
玩家通过点击屏幕上的向左、向右移动按钮控制红色小车左右移动避让黄色小车
黄色小车在屏幕最上方随机生成后向下移动
屏幕右上方分数跟随时间变化而变化
红色小车与某一辆黄色小车碰撞则游戏结束,弹出游戏结束界面
游戏结束界面上有本局游戏分数以及重新开始的按钮
2.代码实现
2.1 创建项目目录
Imags:静态图片
Prefabs:预设物体
Resources:动态资源
Audio:音频
Scenes:场景
Scripts:脚本
2.2 创建面板、小车、按钮等
2.3 按钮控制红色小车左右移动
创建游戏管理脚本 GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
/// <summary>
/// 游戏管理器实例
/// </summary>
public static GameManager insta;
/// <summary>
/// 主界面
/// </summary>
public MainPanel mainPanel;
private void Awake()
{
insta = this;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
红色小车挂载脚本 RedCar.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RedCar : MonoBehaviour
{
/// <summary>
/// 移动速度
/// </summary>
private int moveSpeed = 100;
/// <summary>
/// 移动方向
/// </summary>
public int moveDirection = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//屏幕范围内左右移动
if (moveDirection == -1 && transform.localPosition.x <= -490) return;
if (moveDirection == 1 && transform.localPosition.x >= 490) return;
transform.localPosition += new Vector3(moveDirection * moveSpeed * Time.deltaTime, 0, 0);
}
/// <summary>
/// 碰撞显示结束界面
/// </summary>
/// <param name="collision"></param>
private void OnTriggerEnter2D
