首页 > 其他分享 >Unity2D 快速入门 赛车小游戏教程 项目式教学

Unity2D 快速入门 赛车小游戏教程 项目式教学

时间:2024-09-06 23:22:11浏览次数:7  
标签:Unity2D void called Start 小游戏 赛车 frame using public

Unity2D 快速入门 赛车小游戏教程 项目式教学icon-default.png?t=O83Ahttps://www.bilibili.com/video/BV1a3H9eDEpo/?share_source=copy_web&vd_source=f7debfaee600750d60e895f62aeac43f

本教程涉及到Unity常用组件、常用方法等核心知识点,掌握本教程相关知识后你基本就算入门Unity了

1.需求分析

  1. 玩家通过点击屏幕上的向左、向右移动按钮控制红色小车左右移动避让黄色小车
  2. 黄色小车在屏幕最上方随机生成后向下移动
  3. 屏幕右上方分数跟随时间变化而变化
  4. 红色小车与某一辆黄色小车碰撞则游戏结束,弹出游戏结束界面
  5. 游戏结束界面上有本局游戏分数以及重新开始的按钮

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(Collider2D collision)
    {
        GameManager.insta.overPanel.ShowPanel();
    }
}

主界面挂载脚本MainPanel.cs,拖拽相应物体

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MainPanel : MonoBehaviour
{
    /// <summary>
    /// 红色小车物体
    /// </summary>
    public RedCar redCar;

    /// <summary>
    /// 分数文本
    /// </summary>
    public Text scoreText;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    /// <summary>
    /// 点击按钮向左移动
    /// </summary>
    public void OnLeftMoveClick()
    {
        redCar.moveDirection = -1;
    }
    
    /// <summary>
    /// 点击按钮向右移动
    /// </summary>
    public void OnRightMoveClick()
    {
        redCar.moveDirection = 1;
    }
}

2.4 黄色小车自动向下移动

黄色小车挂载脚本YellowCar.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class YellowCar : MonoBehaviour
{
    /// <summary>
    /// 移动速度
    /// </summary>
    private int moveSpeed = 100;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        transform.localPosition -= new Vector3(0, moveSpeed * Time.deltaTime, 0);//向下移动
        if(transform.localPosition.y <= -1060) Destroy(gameObject);//如果移动到屏幕最底端则自动销毁
    }
}

2.5 红色小车与黄色小车碰撞则游戏结束

红色小车挂载组件Box Collider 2D和Rigidbody 2D

黄色小车挂载组件Box Collider 2D

结束界面挂载脚本OverPanel.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class OverPanel : MonoBehaviour
{
    /// <summary>
    /// 分数文本
    /// </summary>
    public Text scoreText;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    /// <summary>
    /// 显示面板
    /// </summary>
    public void ShowPanel()
    {
        Time.timeScale = 0f;//游戏暂停
        gameObject.SetActive(true);
    }

    /// <summary>
    /// 点击按钮重新开始游戏
    /// </summary>
    public void OnRestartClick()
    {
        Time.timeScale = 1f;//游戏恢复
        gameObject.SetActive(false);
        SceneManager.LoadScene(0);
    }
}

GameManager.cs新增结束界面变量

public class GameManager : MonoBehaviour
{
    /// <summary>
    /// 游戏管理器实例
    /// </summary>
    public static GameManager insta;

    /// <summary>
    /// 主界面
    /// </summary>
    public MainPanel mainPanel;

    /// <summary>
    /// 结束界面
    /// </summary>
    public OverPanel overPanel;

    ...

2.6 更新界面分数

主界面

...
    
public class MainPanel : MonoBehaviour
{
    /// <summary>
    /// 红色小车物体
    /// </summary>
    public RedCar redCar;

    /// <summary>
    /// 分数文本
    /// </summary>
    public Text scoreText;

    /// <summary>
    /// 分数数值
    /// </summary>
    public int score;

    /// <summary>
    /// 开始时间
    /// </summary>
    private float startTime;

    // Start is called before the first frame update
    void Start()
    {
        startTime = Time.time;
    }

    // Update is called once per frame
    void Update()
    {
        //更新分数
        score = (int)(Time.time - startTime);
        scoreText.text = "分数:" + score;
    }

    ...

结束界面

...

public class OverPanel : MonoBehaviour
{
    /// <summary>
    /// 分数文本
    /// </summary>
    public Text scoreText;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        scoreText.text = "分数:" + GameManager.insta.mainPanel.score;
    }

...

2.7 通过预设随机生成黄色小车

创建黄色小车根目录

...

    /// <summary>
    /// 创建黄色小车上一次时间
    /// </summary>
    private float lastTime;

    /// <summary>
    /// 黄色小车物体预设
    /// </summary>
    public GameObject preYellowCarGo;

    /// <summary>
    /// 黄色小车根目录
    /// </summary>
    public GameObject yellowCarRootGo;

    // Start is called before the first frame update
    void Start()
    {
        startTime = Time.time;
        lastTime = Time.time;
    }

    // Update is called once per frame
    void Update()
    {
        //更新分数
        score = (int)(Time.time - startTime);
        scoreText.text = "分数:" + score;
        
        //每过3秒生成一辆黄色小车
        if(Time.time - lastTime >= 3f)
        {
            CreateYellowCar();
            lastTime = Time.time;
        }
    }

    /// <summary>
    /// 点击按钮向左移动
    /// </summary>
    public void OnLeftMoveClick()
    {
        redCar.moveDirection = -1;
    }
    
    /// <summary>
    /// 点击按钮向右移动
    /// </summary>
    public void OnRightMoveClick()
    {
        redCar.moveDirection = 1;
    }

    /// <summary>
    /// 创建黄色小车
    /// </summary>
    private void CreateYellowCar()
    {
        //在x坐标为-490到490之间随机生成黄色小车
        GameObject yellowCarGo = Instantiate(preYellowCarGo, yellowCarRootGo.transform);
        int randomInt = Random.Range(-490, 490);
        yellowCarGo.transform.localPosition = new Vector3(randomInt, 1060, 0);
    }
}

2.8 添加音频

创建游戏中音频物体

...

    /// <summary>
    /// 黄色小车根目录
    /// </summary>
    public GameObject yellowCarRootGo;

    /// <summary>
    /// 游戏进行中音频
    /// </summary>
    public AudioSource gameInAudioSource;

    // Start is called before the first frame update
    void Start()
    {
        startTime = Time.time;// 开始时间赋值
        lastTime = Time.time;// 创建黄色小车上一次时间赋值

        gameInAudioSource.Play();//播放游戏进行音乐
    }

...

创建游戏结束音频物体

...

    /// <summary>
    /// 游戏技术音频
    /// </summary>
    public AudioSource gameOverAudioSource;

...

    /// <summary>
    /// 显示面板
    /// </summary>
    public void ShowPanel()
    {
        Time.timeScale = 0f;//游戏暂停
        gameObject.SetActive(true);

        //停止游戏进行音频,播放游戏结束音频
        if (GameManager.insta.mainPanel.gameInAudioSource.isPlaying)
        {
            GameManager.insta.mainPanel.gameInAudioSource.Stop();
        }
        gameOverAudioSource.Play();
    }

...

2.9 物体换皮

3.完整代码

GameManager

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour
{
    /// <summary>
    /// 游戏管理器实例
    /// </summary>
    public static GameManager insta;

    /// <summary>
    /// 主界面
    /// </summary>
    public MainPanel mainPanel;

    /// <summary>
    /// 结束界面
    /// </summary>
    public OverPanel overPanel;

    private void Awake()
    {
        insta = this;
    }

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

MainPanel

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MainPanel : MonoBehaviour
{
    /// <summary>
    /// 红色小车物体
    /// </summary>
    public RedCar redCar;

    /// <summary>
    /// 分数文本
    /// </summary>
    public Text scoreText;

    /// <summary>
    /// 分数数值
    /// </summary>
    public int score;

    /// <summary>
    /// 开始时间
    /// </summary>
    private float startTime;

    /// <summary>
    /// 创建黄色小车上一次时间
    /// </summary>
    private float lastTime;

    /// <summary>
    /// 黄色小车物体预设
    /// </summary>
    public GameObject preYellowCarGo;

    /// <summary>
    /// 黄色小车根目录
    /// </summary>
    public GameObject yellowCarRootGo;

    /// <summary>
    /// 游戏进行中音频
    /// </summary>
    public AudioSource gameInAudioSource;

    // Start is called before the first frame update
    void Start()
    {
        startTime = Time.time;// 开始时间赋值
        lastTime = Time.time;// 创建黄色小车上一次时间赋值

        gameInAudioSource.Play();//播放游戏进行音乐
    }

    // Update is called once per frame
    void Update()
    {
        //更新分数
        score = (int)(Time.time - startTime);
        scoreText.text = "分数:" + score;
        
        //每过3秒生成一辆黄色小车
        if(Time.time - lastTime >= 3f)
        {
            CreateYellowCar();
            lastTime = Time.time;
        }
    }

    /// <summary>
    /// 点击按钮向左移动
    /// </summary>
    public void OnLeftMoveClick()
    {
        redCar.moveDirection = -1;
    }
    
    /// <summary>
    /// 点击按钮向右移动
    /// </summary>
    public void OnRightMoveClick()
    {
        redCar.moveDirection = 1;
    }

    /// <summary>
    /// 创建黄色小车
    /// </summary>
    private void CreateYellowCar()
    {
        //在x坐标为-490到490之间随机生成黄色小车
        GameObject yellowCarGo = Instantiate(preYellowCarGo, yellowCarRootGo.transform);
        int randomInt = Random.Range(-490, 490);
        yellowCarGo.transform.localPosition = new Vector3(randomInt, 1060, 0);
    }
}

OverPanel

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class OverPanel : MonoBehaviour
{
    /// <summary>
    /// 分数文本
    /// </summary>
    public Text scoreText;

    /// <summary>
    /// 游戏技术音频
    /// </summary>
    public AudioSource gameOverAudioSource;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        scoreText.text = "分数:" + GameManager.insta.mainPanel.score;
    }

    /// <summary>
    /// 显示面板
    /// </summary>
    public void ShowPanel()
    {
        Time.timeScale = 0f;//游戏暂停
        gameObject.SetActive(true);

        //停止游戏进行音频,播放游戏结束音频
        if (GameManager.insta.mainPanel.gameInAudioSource.isPlaying)
        {
            GameManager.insta.mainPanel.gameInAudioSource.Stop();
        }
        gameOverAudioSource.Play();
    }

    /// <summary>
    /// 点击按钮重新开始游戏
    /// </summary>
    public void OnRestartClick()
    {
        Time.timeScale = 1f;//游戏恢复
        gameObject.SetActive(false);
        SceneManager.LoadScene(0);
    }
}

RedCar

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(Collider2D collision)
    {
        GameManager.insta.overPanel.ShowPanel();
    }
}

YellowCar

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class YellowCar : MonoBehaviour
{
    /// <summary>
    /// 移动速度
    /// </summary>
    private int moveSpeed = 100;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        transform.localPosition -= new Vector3(0, moveSpeed * Time.deltaTime, 0);//向下移动
        if(transform.localPosition.y <= -1060) Destroy(gameObject);//如果移动到屏幕最底端则自动销毁
    }
}

标签:Unity2D,void,called,Start,小游戏,赛车,frame,using,public
From: https://blog.csdn.net/teacherchen90/article/details/141967215

相关文章

  • 基于python的贪吃蛇小游戏
    游戏规则1.玩家控制蛇在屏幕上移动(上下左右方向键),目标是吃到随机出现的食物。2.每次吃到食物后,蛇的长度会增加。3.游戏难度逐渐增加,蛇的移动速度会随着长度的增加而加快。4.如果蛇撞到自己或碰到墙壁,游戏结束。代码importtkinterastkimportrandomfromtkinter......
  • 基于java语言的点击方块小游戏
    游戏玩法目标:玩家需要在限时内点击尽可能多的方块。规则:游戏启动后,屏幕上会随机出现一个移动的方块;玩家点击方块得分,方块会重新随机出现在另一个位置;游戏限时为30秒,时间结束时显示总分。代码importjavax.swing.*;importjava.awt.*;importjava.awt.event.*;import......
  • C语言猜数小游戏
    问题:用C语言写一个猜数小游戏,要求数字是整数小于1000且随即生成,玩家需要输入数字,程序给出提示,直至最终猜到最终正确的数字,游戏结束。小游戏实现代码如下:#include<stdio.h>#include<stdlib.h>//lib头文件调用随机函数#include<time.h>//time头文件调用时间......
  • uniapp js 数独小游戏 写死的简单数独demo(优化完成) 数独 4.0
    <template> <viewclass="wrap">  <viewclass="timeGame">   <textclass="time">时间{{gameTime}}</text>  </view>  <viewclass="listWrap">   <view    ......
  • C++实现 || 敲桌子小游戏
    这是一个在聚会和酒桌上常玩的一个小游戏。游戏规则所有人围着桌子一个大圈,从“1”开始喊,遇到7、7的倍数或是带7的数字,就敲一下桌子(酒桌上用筷子敲下杯子),以此类推。一旦有人做错了就要接受惩罚。实现思路我们建立一个for循环,让变量在其中不断递增。在循环体内部,我们对变量进行判断,......
  • Unity实战案例 2D小游戏HappyGlass(模拟水珠)
    本案例素材和教程都来自Siki学院,十分感谢教程中的老师本文仅作学习笔记分享交流,不作任何商业用途预制体  在这个小案例中,水可以做成圆形但是带碰撞体,碰撞体比图形小一圈,顺便加上Trailrenderer组件 材质将碰撞材质的friction为0,bonciness可以按照需要修改脚本 ......
  • uniapp js 划消小游戏 1.0 去控制台看打印(仅作参考)
    <template> <viewclass="wrap">  划消:{{sdNum}}*{{sdNum}}  <viewclass="btn"style="padding:32rpx;background:pink"@click="clickBtn">点击划消按钮</view>  <viewclass="btn&q......
  • uniapp js 数独小游戏 写死的简单数独 数独 3.0
    <template> <viewclass="wrap">  数独:{{sdNum}}*{{sdNum}}  <viewclass="btn"style="padding:32rpx;background:pink"@click="startFun">点击开始计时</view>  <viewclass="btn&q......
  • uniapp js 数独小游戏 9*9 数独 2.0
    效果图: game.vue<template> <view> <viewclass="main"> <viewclass="foot"> <viewv-if="!isTip"class="sudoku_area"> <viewv-for="(row,index)ofrowList":key=&quo......
  • uniapp js 数独小游戏 n*n 看控制台的打印 数独 1.0
    uniappjs 数独小游戏n*n 看控制台的打印game.vue<template> <view>4567</view></template><scriptsetuplang="ts">import{ref}from'vue'import{onShow}from'@dcloudio/uni-app'constsdNum=ref(......