基于Unity3D实现3D迷宫小游戏的示例代码

目录
  • 一、前言
  • 二、构思
  • 三、正式开发
    • 3-1、搭建场景
    • 3-2、设置出入口
    • 3-3、添加角色
    • 3-4、实现角色移动
    • 3-5、出入口逻辑
  • 四、总结

一、前言

闲来无事,从零开始整个《3D迷宫》小游戏。

本篇文章会详细介绍构思、实现思路,希望可以帮助到有缘人。

二、构思

首先,要实现一个小游戏,心里肯定要有一个大概的想法,然后就是将想法完善起来。

我的想法就是一个用立体的墙搭建的迷宫,然后控制人物在迷宫中移动,最后找到出口,就这么简单。

当然,这是一个雏形,比如可以加点音效、背景、关卡、解密等。

那么整理一下实现思路就是:

  • 构建3D迷宫
  • 实现人物移动
  • 实现出入口逻辑

OK,下面就正式开发。

三、正式开发

3-1、搭建场景

首先,新建个项目,我用了Unity 2019.4.7f1版本,项目名称跟位置按照自己的喜好设置即可:

接下来构建迷宫,先新建一个Plane,让它最够大,扩大10倍:

新建Cube,调整大小缩放,让它看起来像是一堵墙,然后构建迷宫:

3-2、设置出入口

放两个Cube,设置缩放,将出口名字改成Exit,这样就行了,到时候通过碰撞检测检测小球是否到达出口即可。

3-3、添加角色

在Hierarchy视图,右击选择3D Objcet→Capsule,新建一个球体,添加Rigibody组件:

设置Drag抓地力为1。

就这样设置就行了,在实际运行中如果参数不合适还可以再调整。

将小球移动到入口的位置。

3-4、实现角色移动

这里直接使用官方的第一人称移动代码RigidbodyFirstPersonController .cs:

public class RigidbodyFirstPersonController : MonoBehaviour
    {
        [Serializable]
        public class MovementSettings
        {
            public float ForwardSpeed = 8.0f;   // Speed when walking forward
            public float BackwardSpeed = 4.0f;  // Speed when walking backwards
            public float StrafeSpeed = 4.0f;    // Speed when walking sideways
            public float RunMultiplier = 2.0f;   // Speed when sprinting
	        public KeyCode RunKey = KeyCode.LeftShift;
            public float JumpForce = 30f;
            public AnimationCurve SlopeCurveModifier = new AnimationCurve(new Keyframe(-90.0f, 1.0f), new Keyframe(0.0f, 1.0f), new Keyframe(90.0f, 0.0f));
            [HideInInspector] public float CurrentTargetSpeed = 8f;

#if !MOBILE_INPUT
            private bool m_Running;
#endif

            public void UpdateDesiredTargetSpeed(Vector2 input)
            {
	            if (input == Vector2.zero) return;
				if (input.x > 0 || input.x < 0)
				{
					//strafe
					CurrentTargetSpeed = StrafeSpeed;
				}
				if (input.y < 0)
				{
					//backwards
					CurrentTargetSpeed = BackwardSpeed;
				}
				if (input.y > 0)
				{
					//forwards
					//handled last as if strafing and moving forward at the same time forwards speed should take precedence
					CurrentTargetSpeed = ForwardSpeed;
				}
#if !MOBILE_INPUT
	            if (Input.GetKey(RunKey))
	            {
		            CurrentTargetSpeed *= RunMultiplier;
		            m_Running = true;
	            }
	            else
	            {
		            m_Running = false;
	            }
#endif
            }

#if !MOBILE_INPUT
            public bool Running
            {
                get { return m_Running; }
            }
#endif
        }

        [Serializable]
        public class AdvancedSettings
        {
            public float groundCheckDistance = 0.01f; // distance for checking if the controller is grounded ( 0.01f seems to work best for this )
            public float stickToGroundHelperDistance = 0.5f; // stops the character
            public float slowDownRate = 20f; // rate at which the controller comes to a stop when there is no input
            public bool airControl; // can the user control the direction that is being moved in the air
            [Tooltip("set it to 0.1 or more if you get stuck in wall")]
            public float shellOffset; //reduce the radius by that ratio to avoid getting stuck in wall (a value of 0.1f is nice)
        }

        public Camera cam;
        public MovementSettings movementSettings = new MovementSettings();
        public MouseLook mouseLook = new MouseLook();
        public AdvancedSettings advancedSettings = new AdvancedSettings();

        private Rigidbody m_RigidBody;
        private CapsuleCollider m_Capsule;
        private float m_YRotation;
        private Vector3 m_GroundContactNormal;
        private bool m_Jump, m_PreviouslyGrounded, m_Jumping, m_IsGrounded;

        public Vector3 Velocity
        {
            get { return m_RigidBody.velocity; }
        }

        public bool Grounded
        {
            get { return m_IsGrounded; }
        }

        public bool Jumping
        {
            get { return m_Jumping; }
        }

        public bool Running
        {
            get
            {
 #if !MOBILE_INPUT
				return movementSettings.Running;
#else
	            return false;
#endif
            }
        }

        private void Start()
        {
            m_RigidBody = GetComponent<Rigidbody>();
            m_Capsule = GetComponent<CapsuleCollider>();
            mouseLook.Init (transform, cam.transform);
        }

        private void Update()
        {
            RotateView();

            if (CrossPlatformInputManager.GetButtonDown("Jump") && !m_Jump)
            {
                m_Jump = true;
            }
        }

        private void FixedUpdate()
        {
            GroundCheck();
            Vector2 input = GetInput();

            if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (advancedSettings.airControl || m_IsGrounded))
            {
                // always move along the camera forward as it is the direction that it being aimed at
                Vector3 desiredMove = cam.transform.forward*input.y + cam.transform.right*input.x;
                desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized;

                desiredMove.x = desiredMove.x*movementSettings.CurrentTargetSpeed;
                desiredMove.z = desiredMove.z*movementSettings.CurrentTargetSpeed;
                desiredMove.y = desiredMove.y*movementSettings.CurrentTargetSpeed;
                if (m_RigidBody.velocity.sqrMagnitude <
                    (movementSettings.CurrentTargetSpeed*movementSettings.CurrentTargetSpeed))
                {
                    m_RigidBody.AddForce(desiredMove*SlopeMultiplier(), ForceMode.Impulse);
                }
            }

            if (m_IsGrounded)
            {
                m_RigidBody.drag = 5f;

                if (m_Jump)
                {
                    m_RigidBody.drag = 0f;
                    m_RigidBody.velocity = new Vector3(m_RigidBody.velocity.x, 0f, m_RigidBody.velocity.z);
                    m_RigidBody.AddForce(new Vector3(0f, movementSettings.JumpForce, 0f), ForceMode.Impulse);
                    m_Jumping = true;
                }

                if (!m_Jumping && Mathf.Abs(input.x) < float.Epsilon && Mathf.Abs(input.y) < float.Epsilon && m_RigidBody.velocity.magnitude < 1f)
                {
                    m_RigidBody.Sleep();
                }
            }
            else
            {
                m_RigidBody.drag = 0f;
                if (m_PreviouslyGrounded && !m_Jumping)
                {
                    StickToGroundHelper();
                }
            }
            m_Jump = false;
        }

        private float SlopeMultiplier()
        {
            float angle = Vector3.Angle(m_GroundContactNormal, Vector3.up);
            return movementSettings.SlopeCurveModifier.Evaluate(angle);
        }

        private void StickToGroundHelper()
        {
            RaycastHit hitInfo;
            if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
                                   ((m_Capsule.height/2f) - m_Capsule.radius) +
                                   advancedSettings.stickToGroundHelperDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
            {
                if (Mathf.Abs(Vector3.Angle(hitInfo.normal, Vector3.up)) < 85f)
                {
                    m_RigidBody.velocity = Vector3.ProjectOnPlane(m_RigidBody.velocity, hitInfo.normal);
                }
            }
        }

        private Vector2 GetInput()
        {

            Vector2 input = new Vector2
                {
                    x = CrossPlatformInputManager.GetAxis("Horizontal"),
                    y = CrossPlatformInputManager.GetAxis("Vertical")
                };
			movementSettings.UpdateDesiredTargetSpeed(input);
            return input;
        }

        private void RotateView()
        {
            //avoids the mouse looking if the game is effectively paused
            if (Mathf.Abs(Time.timeScale) < float.Epsilon) return;

            // get the rotation before it's changed
            float oldYRotation = transform.eulerAngles.y;

            mouseLook.LookRotation (transform, cam.transform);

            if (m_IsGrounded || advancedSettings.airControl)
            {
                // Rotate the rigidbody velocity to match the new direction that the character is looking
                Quaternion velRotation = Quaternion.AngleAxis(transform.eulerAngles.y - oldYRotation, Vector3.up);
                m_RigidBody.velocity = velRotation*m_RigidBody.velocity;
            }
        }

        /// sphere cast down just beyond the bottom of the capsule to see if the capsule is colliding round the bottom
        private void GroundCheck()
        {
            m_PreviouslyGrounded = m_IsGrounded;
            RaycastHit hitInfo;
            if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo,
                                   ((m_Capsule.height/2f) - m_Capsule.radius) + advancedSettings.groundCheckDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore))
            {
                m_IsGrounded = true;
                m_GroundContactNormal = hitInfo.normal;
            }
            else
            {
                m_IsGrounded = false;
                m_GroundContactNormal = Vector3.up;
            }
            if (!m_PreviouslyGrounded && m_IsGrounded && m_Jumping)
            {
                m_Jumping = false;
            }
        }
    }

MouseLook.cs:

public class MouseLook
    {
        public float XSensitivity = 2f;
        public float YSensitivity = 2f;
        public bool clampVerticalRotation = true;
        public float MinimumX = -90F;
        public float MaximumX = 90F;
        public bool smooth;
        public float smoothTime = 5f;
        public bool lockCursor = true;

        private Quaternion m_CharacterTargetRot;
        private Quaternion m_CameraTargetRot;
        private bool m_cursorIsLocked = true;

        public void Init(Transform character, Transform camera)
        {
            m_CharacterTargetRot = character.localRotation;
            m_CameraTargetRot = camera.localRotation;
        }

        public void LookRotation(Transform character, Transform camera)
        {
            float yRot = CrossPlatformInputManager.GetAxis("Mouse X") * XSensitivity;
            float xRot = CrossPlatformInputManager.GetAxis("Mouse Y") * YSensitivity;

            m_CharacterTargetRot *= Quaternion.Euler (0f, yRot, 0f);
            m_CameraTargetRot *= Quaternion.Euler (-xRot, 0f, 0f);

            if(clampVerticalRotation)
                m_CameraTargetRot = ClampRotationAroundXAxis (m_CameraTargetRot);

            if(smooth)
            {
                character.localRotation = Quaternion.Slerp (character.localRotation, m_CharacterTargetRot,
                    smoothTime * Time.deltaTime);
                camera.localRotation = Quaternion.Slerp (camera.localRotation, m_CameraTargetRot,
                    smoothTime * Time.deltaTime);
            }
            else
            {
                character.localRotation = m_CharacterTargetRot;
                camera.localRotation = m_CameraTargetRot;
            }

            UpdateCursorLock();
        }

        public void SetCursorLock(bool value)
        {
            lockCursor = value;
            if(!lockCursor)
            {//we force unlock the cursor if the user disable the cursor locking helper
                Cursor.lockState = CursorLockMode.None;
                Cursor.visible = true;
            }
        }

        public void UpdateCursorLock()
        {
            //if the user set "lockCursor" we check & properly lock the cursos
            if (lockCursor)
                InternalLockUpdate();
        }

        private void InternalLockUpdate()
        {
            if(Input.GetKeyUp(KeyCode.Escape))
            {
                m_cursorIsLocked = false;
            }
            else if(Input.GetMouseButtonUp(0))
            {
                m_cursorIsLocked = true;
            }

            if (m_cursorIsLocked)
            {
                Cursor.lockState = CursorLockMode.Locked;
                Cursor.visible = false;
            }
            else if (!m_cursorIsLocked)
            {
                Cursor.lockState = CursorLockMode.None;
                Cursor.visible = true;
            }
        }

        Quaternion ClampRotationAroundXAxis(Quaternion q)
        {
            q.x /= q.w;
            q.y /= q.w;
            q.z /= q.w;
            q.w = 1.0f;

            float angleX = 2.0f * Mathf.Rad2Deg * Mathf.Atan (q.x);

            angleX = Mathf.Clamp (angleX, MinimumX, MaximumX);

            q.x = Mathf.Tan (0.5f * Mathf.Deg2Rad * angleX);

            return q;
        }

    }

将所有的墙的父物体设置为地板。

设置摄像机的位置和父物体:

运行程序:

3-5、出入口逻辑

出口用碰撞检测,新建脚本ExitControl.cs,编辑代码:

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

public class ExitControl : MonoBehaviour
{
    void OnCollisionEnter(Collider col)
    {
        if (col.gameObject.name == "Capsule")
        {
            SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        }
    }
}

将代码附给Exit对象。

结束了。

四、总结

本文实现了一个《3D迷宫》小游戏。

首先,搭建场景,然后实现角色移动,出入口逻辑。

整天代码比较简单,官方的移动代码也可以学习一下。

以上就是基于Unity3D实现3D迷宫小游戏的示例代码的详细内容,更多关于Unity3D迷宫游戏的资料请关注我们其它相关文章!

(0)

相关推荐

  • Unity3D实现飞机大战游戏(1)

    本文为大家分享了Unity3D飞机大战游戏第一部分的实现代码,供大家参考,具体内容如下 实现背景轮播 1.首先找两个背景图片,让两张图片竖直摆放且没有间隔 2.两个图片的下降的播放速度应当同步 public float moveSpeed = 3f;//指的是在unity里的移动速度 // Update is called once per frame void Update() { this.transform.Translate(Vector3.down * moveSpeed *Time.

  • Unity3D实现飞机大战游戏(2)

    本文为大家分享了Unity3D飞机大战游戏第一部分的实现代码,供大家参考,具体内容如下 让飞机可以发射子弹 准备工作: 1.将子弹设置成预制体 2.在飞机下新建一个子物体Gun 3.调整好位置以后,将子弹设置成预制体 //发射子弹的速率 public float rate = 0.2f; public GameObject bullet;//子弹的类型 //发射子弹的方法 public void fire() { //初始化一个子弹预制体 GameObject.Instantiate(bulle

  • Unity3D实现甜品消消乐游戏

    目录 前言 项目效果展示 项目概况 素材展示 场景展示 场景元素 玩法介绍 版本说明 项目源码 前言 解释: 之前用的ScreenToGif录屏,因为上传的.gif最大不超过5MB,所以做了不少删帧和色彩弱化等处理,这才导致色彩看上去不是很舒服,不要盯着它看太久,不然会有点难受... 由于使用的素材是现成的,没有花时间精力去扒,所以细节方面可能不是做的很好. 说明: 这次的甜品消消乐虽然看上去好像挺简单普通的,但是相对于之前的坦克大战,某种程度上已然提升难度了,归类到了算法类层的游戏. 拉到最后

  • Java实现的迷宫游戏

    完整项目地址: https://github.com/richenyunqi/Maze-game 软件总体框架 该软件主要分为如下三个模块: 参数设置模块 按钮功能模块按钮功能模块 迷宫主界面模块迷宫主界面模块 软件各模块介绍 参数设置模块 1.迷宫大小相关参数: ROWS(即迷宫行数,默认设置为奇数,最小值为11,最大值为99,默认值为11): COLS(即迷宫列数,默认设置为奇数,最小值为11,最大值为99,默认值为11): Lattice's width(即组成迷宫的格子的宽度,迷宫格子默

  • 如何用 Python 制作一个迷宫游戏

    相信大家都玩过迷宫的游戏,对于简单的迷宫,我们可以一眼就看出通路,但是对于复杂的迷宫,可能要仔细寻找好久,甚至耗费数天,然后可能还要分别从入口和出口两头寻找才能找的到通路,甚至也可能找不到通路. 虽然走迷宫问题对于我们人类来讲比较复杂,但对于计算机来说却是很简单的问题.为什么这样说呢,因为看似复杂实则是有规可循的. 我们可以这么做,携带一根很长的绳子,从入口出发一直走,如果有岔路口就走最左边的岔口,直到走到死胡同或者找到出路.如果是死胡同则退回上一个岔路口,我们称之为岔口 A, 这时进入左边第二

  • 使用C++实现迷宫游戏

    迷宫游戏就是玩家在地图中移动,移动至终点则游戏结束. 自己用文本文档手打了个小地图,0表示空白,1表示墙,文件名随意,我改成了map.MapData.然后程序里定义一个全局变量char Map[MapLenX][MapLenY];(长宽自定义)行为X,列为Y.定义char型常量RoadSymbol = '0', WallSymbol = '1', PlayerSymbol = '+'. 本游戏为面向对象编写的,所以就要设计一个类.数据需要一个坐标和一个bool型储存是否到达终点.所以自定义了个结

  • Unity3D实现经典小游戏Pacman

    目录 项目概况 整体布局 地图介绍 玩法介绍 相关知识 版本说明 项目源码 项目概况 整体布局 地图介绍 除了音效,游戏地图上的元素有: 普通糖豆(玩家通过移动,经过的普通糖豆会被吃掉,获得积分)  特殊糖豆(玩家吃到后,可以让所有敌方停止移动,产生幻影效果) 隔离墙(相当于迷宫的墙,在两堵墙之间的间隙才能移动)  剩余游戏时间Remain(共设300s,时间一到,游戏结束) 截止到现在花费的游戏时间Now(设在0~300之间) 截止到目前为止的游戏得分Score(越高越好) 敌方人机(分为四种

  • 基于Unity3D实现3D迷宫小游戏的示例代码

    目录 一.前言 二.构思 三.正式开发 3-1.搭建场景 3-2.设置出入口 3-3.添加角色 3-4.实现角色移动 3-5.出入口逻辑 四.总结 一.前言 闲来无事,从零开始整个<3D迷宫>小游戏. 本篇文章会详细介绍构思.实现思路,希望可以帮助到有缘人. 二.构思 首先,要实现一个小游戏,心里肯定要有一个大概的想法,然后就是将想法完善起来. 我的想法就是一个用立体的墙搭建的迷宫,然后控制人物在迷宫中移动,最后找到出口,就这么简单. 当然,这是一个雏形,比如可以加点音效.背景.关卡.解密等.

  • Java实现可视化走迷宫小游戏的示例代码

    目录 效果图 数据层 视图层 控制层 效果图 数据层 本实例需要从 .txt 文件中读取迷宫并绘制,所以先来实现文件读取IO类 MazeData.java,该程序在构造函数运行时将外部文件读入,并完成迷宫各种参数的初始化,注意规定了外部 .txt 文件的第一行两个数字分别代表迷宫的行数和列数.此外还提供了各类接口来读取或操作私有数据. import java.io.BufferedInputStream; import java.io.File; import java.io.FileInput

  • 基于JS实现接粽子小游戏的示例代码

    目录 游戏设计 游戏实现 添加粽子元素 粽子掉落 难度选择 开始游戏 总结 端午节马上就到了,听说你们公司没发粽子大礼包?没关系,这里用 JS 实现了一个简单的接粽子小游戏,能接到多少粽子,完全看你手速,不用担心端午没粽子了. 游戏设计 在游戏屏幕内,会随机的从顶部掉落粽子,通过鼠标移动到粽子上并点击,成功接住粽子,得到积分.在设置面板中,可以设置游戏难度,分为简单.很难.超级难三种等级,不同等级的积分也是不同的,玩家可根据自己的手速进行设置.游戏结束后,可看到自己的成绩.实现出来的效果如下(可

  • 基于C语言实现关机小游戏的示例代码

    目录 关机会写吧 猜数字会写吧 那么合起来 实际效果 关机会写吧 #include <stdlib.h> #include <string.h> #include <stdio.h> int main() { char input[10] = { 0 }; system("shutdown -s -t 60"); again: printf("电脑将于1分钟后关机,输入:我是猪,取消关机!\n"); scanf("%s&

  • 基于Python实现开心消消乐小游戏的示例代码

    目录 前言 一.准备 1.1 图片素材 1.2 音频素材 二.代码 2.1 导入模块 2.2 游戏音乐设置 2.3 制作树类 2.4 制作鼠标点击效果 2.5 制作出现元素 2.6 数组 2.7 制作人物画板 三.效果展示(仅部分) 3.1 初始页面 3.2 第一关画面 3.3 失败画面 3.4 第十关画面 穿过云朵升一级是要花6个金币的,有的时候金币真的很重要 前言 嗨喽,大家好呀!这里是魔王~ 一天晚上,天空中掉下一颗神奇的豌豆种子,正好落在了梦之森林的村长屋附近. 种子落地后吸收了池塘的水

  • Java实现接月饼小游戏的示例代码

    目录 前言 主要设计 功能截图 代码实现 游戏启动类 核心类 画面绘制 总结 前言 <接月饼小游戏>是一个基于java的自制游戏,不要被月亮砸到,尽可能地多接月饼. 此小项目可用来巩固JAVA基础语法,swing的技巧用法. 主要设计 设计游戏界面,用swing实现 设计背景 设计得分物体-月饼,碰到加一分 设计障碍物-月亮,碰到会死亡 监听鼠标的左右键,用来控制篮子左右移动 设计积分系统 将resource文件夹设为resource(Project Manage中可以设置),因为要用里面的图

  • Java实现贪吃蛇大作战小游戏的示例代码

    目录 效果展示 项目介绍 项目背景 总体需求 实现过程 代码展示 项目结构 总结 大家好,今天尝试用swing技术写一个贪吃蛇大作战小游戏,供大家参考. 效果展示 效果展示 一.游戏界面 二.得分情况 项目介绍 项目背景 “贪吃蛇大作战”游戏是一个经典的游戏,它因操作简单.娱乐性强,自从计算机实现以来,深受广大电脑玩家的喜爱,本项目基于Java技术,开发了一个 操作简单.界面美观.功能较齐全 的“贪吃蛇”游戏.通过本游戏的开发,达到学习Java技术和熟悉软件开发流程的目的. 总体需求  本系统主

  • C语言实现猜数字小游戏的示例代码

    目录 一.猜数字小游戏的要求 二.猜数字小游戏实现的过程 2.1项目创建 2.2头文件内容 2.3源文件内容 三.猜数字小游戏调试结果如下 四.基于猜数字小游戏的总结 五.完整代码 一.猜数字小游戏的要求 猜数字小游戏是我们小时候喜欢我们一个经典小游戏,在本文中,猜数字小游戏主要的功能如下所示 1.登入猜数字小游戏系统,显示小时欢迎界面. 2.用户猜的数字有系统随机在1-20之间生成. 3.用户可以有5次机会猜这个随机生成的数字. 4.若用户猜大了,则系统会显示猜大了,并提示还有多少猜数字的机会

  • Python快速实现简易贪吃蛇小游戏的示例代码

    贪吃蛇(也叫做贪食蛇)游戏是一款休闲益智类游戏,有PC和手机等多平台版本.既简单又耐玩.该游戏通过控制蛇头方向吃蛋,从而使得蛇变得越来越长. 贪吃蛇游戏最初为单机模式,后续又陆续推出团战模式.赏金模式.挑战模式等多种玩法. 另外还有一种名为“贪吃蛇”钻井测井技术,是运用旋转导向系统.随钻测井系统等的油气田定向钻井.随钻测井技术,可完成海上“丛式井”和复杂油气层的开采需求,大幅降低油气田开发综合成本. 依然是基于pygame库,pip install pygame安装即可 完整代码如下: # 导入

  • Matlab实现别踩白块小游戏的示例代码

    目录 游戏效果 游戏说明 完整代码 pianoKeys.m(主函数) getMusic.m(用于获取音乐数据) 游戏效果 游戏说明 ‘A’,‘S’,‘D’,F’按键代表四条通路(点击S开始),按错按钮或黑块接触底限均为失败. 完整代码 分两个m文件,应放在同一文件夹 pianoKeys.m(主函数) function pianoKeys %======================%======== [v1,notes,fs]=getMusic;%读取音乐 %=================

随机推荐