UnityJohn_Lemon escape room

What’s unity?

Unity3D is a multi-platform comprehensive game development tool developed by Unity Technologies that allows players to easily create many types of interactive content such as 3D games, virtual reality, real-time movies and animations, architectural visualization, digital education, automobiles/transportation and manufacturing. , is a powerful professional game engine. Unity is similar to software such as Director, Blender, Virtools or Torque Game Builder that use an interactive graphical development environment as the primary method.
—————
Copyright statement: This article is the original article of CSDN blogger “Want to eat roasted sweet potatoes.” It follows the CC 4.0 BY-SA copyright agreement. For reprinting, please attach the original source link and this statement.
Original link: https://blog.csdn.net/qq_46093832/article/details/120306980

Unity development learning route

Demo production process:

  1. Install and configure, get familiar with editor tools
  2. To import the resource file, you can go to Window->Asset Store to download the desired scene, download the Tutorial Resources here, add it to my resource and open it in unity, import it into unity
  3. Drag in the character and adjust the viewing angle through GameObject->Align with view
  4. Make prefabs (expand in detail below)
  5. Create an animation, create a folder MyAnimators->Animator Controller-> double-click to enter, set the corresponding animation relationship
  6. Create scripts to program people/things that need to be implemented
  7. Complete the creation and package the game

About prefabs

Why create a prefab

In Unity, the role of prefabs is to reuse resources, such as flowers, trees, and house buildings in the game world. These resources are recurring, and we can make them into prefabs to facilitate reuse.

Create scope

Anything that can be dragged into the Hierarchy panel can be made into a prefab, including but not limited to models, UI, empty objects for mounting scripts, etc.

Create method

Drag the objects in the Scene to Prefabs, the icon will turn into a blue block

Writing scripts

PlayerMovement

Control the movement of game characters through keyboard input, the grammar is relatively easy to understand, see the notes for detailed functions.

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

public class PlayerMovement : MonoBehaviour
{<!-- -->
    public float turnspeed = 20f; //Define the rotation speed
 
    Animator m_Animator;
    Rigidbody m_Rigidbody; //Define the components on the game character

    Vector3 m_Movement;//The vector of the game character movement
    Quaternion m_Quaternion=Quaternion.identity;//Define the angle of character rotation

    // Start is called before the first frame update
    void Start()
    {<!-- -->
        m_Animator = GetComponent<Animator>();
        m_Rigidbody = GetComponent<Rigidbody>();
        //Get the rigid body and animation control mechanism components on the character
    }

    // Update is called once per frame
    private void FixedUpdate()
    {<!-- -->
        float horizontal = Input.GetAxis("Horizontal");//Keyboard input moves horizontally
        float vertical = Input.GetAxis("Vertical");//keyboard input value movement
        m_Movement.Set(horizontal, 0f, vertical);//Set the movement direction of the game character
        m_Movement.Normalize();//speed normalization

        bool hasHorizontalInput = !Mathf.Approximately(horizontal,0f); //Define the bool value of movement
        bool hasverticalInput = !Mathf.Approximately(vertical, 0f);

        //control animation playback
        bool iswalking = hasHorizontalInput || hasverticalInput;
        m_Animator.SetBool("isWalking", iswalking);

        //rotation transition
        Vector3 desireForwad = Vector3.RotateTowards(transform.forward, m_Movement, turnspeed * Time.deltaTime, 0f);
        m_Quaternion = Quaternion.LookRotation(desirForwad);
    }

    //Rotation and transition of game characters
    private void OnAnimatorMove()
    {<!-- -->
        m_Rigidbody.MovePosition(m_Rigidbody.position + m_Movement * m_Animator.deltaPosition.magnitude);
        m_Rigidbody.MoveRotation(m_Quaternion);
    }
   
}

CameraFollow

The camera moves with the characters, and it can also be realized by setting a virtual camera.

Idea: Find and record the relative position between the camera and the player in the Start function. In the update of each frame (implemented by the Update function), the keyboard input controls the movement of the character, but the relative position does not change.

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

public class CameraFollow1 : MonoBehaviour
{<!-- -->
    //Follow the game character
    private Transform Player;

    //The distance between the camera and the character
    Vector3 offset;
   
    // Start is called before the first frame update
    void Start()
    {<!-- -->
        Player = GameObject. Find("JohnLemon"). transform;
        offset = transform.position - Player.position;
    }
    // Update is called once per frame
    void Update()
    {<!-- -->
        transform.position = offset + Player.position;
    }
}

GameEnding

Effects when the game ends, including showing the canvas and playing audio, restarting on failure and exiting on success.

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

public class GameEnding : MonoBehaviour
{<!-- -->

    public float fadeDuration = 1f; //Fade in and fade out time
    public float displayDuration = 1f; //Duration of game victory display
    public GameObject Player; //Game character
    public CanvasGroup ExitBK;//Canvas background when the game wins
    public CanvasGroup FailBK;//Canvas background when the game fails
    bool IsExit = false;//The bool value when the game wins
    bool IsFail = false;//The bool value when the game fails

    //Define the timer for the gradient of the picture
    public float timer=0f;

    //Audio component
    public AudioSource winaudio;
    public AudioSource failaudio;

    //bool controls the sound effect to play only once
    bool IsPlay=false;
    // Update is called once per frame
    private void OnTriggerEnter(Collider other)
    {<!-- -->
        if (other. gameObject == Player)
        {<!-- -->
            // detect the player
            IsExit = true;
        }
    }

    //Control function when the game fails
    public void Caught()
    {<!-- -->
        IsFail = true;
    }

    void Update()
    {<!-- -->
        if (IsExit)
        {<!-- -->
             EndLevel(ExitBK, false, winaudio);
        }
        else if (IsFail)
        {<!-- -->
            EndLevel(FailBK, true, failaudio);
        }
    }
    //The method when the game wins/loses
    void EndLevel(CanvasGroup igCanvasGroup, bool doRestart, AudioSource playaudio)
    {<!-- -->
        //Sound effect playback
        if (!IsPlay)
        {<!-- -->
            playaudio.Play();
            IsPlay = true;
        }

        //When the player touches the timer, the timer starts to count
        timer + = Time.deltaTime;//Control the display of CanvasGroup opacity
        igCanvasGroup.alpha = timer / fadeDuration;
        //Game victory/failure picture gradient for 1s, display for 1s
        if (timer > fadeDuration + displayDuration)
        {<!-- -->
        // Debug. Log("Fail");
            
            if (doRestart)//The game fails, restart the game
            {<!-- -->
                SceneManager. LoadScene("Main");
            }
            else
            {<!-- -->
                Application. Quit();
            }
        }
    }
}

Observer

Ray detection, to determine whether the player has entered the death zone.

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

public class Observer : MonoBehaviour
{<!-- -->
    //game character
    public Transform Player;
    public GameEnding gameEnding;

    //Whether the game player has entered the line of sight of the scanning rod
    bool IsInRange = false;

    private void OnTriggerEnter(Collider other)
    {<!-- -->
        //The scanning stick scans to the player
        if (other. gameObject == Player. gameObject)
        {<!-- -->
            IsInRange = true;
        }
    }

    // Update is called once per frame
    void Update()
    {<!-- -->
        if (IsInRange == true)
        {<!-- -->
            //Ray detection
            Vector3 dir = Player.position - transform.position + Vector3.up;//Consider the offset of the center of gravity
            Ray ray = new Ray(transform. position, dir);
            RaycastHit raycastHit;
            if(Physics. Raycast(ray, out raycastHit))
            {<!-- -->
                if (raycastHit.collider.transform == Player)
                {<!-- -->
                    //The game fails, call the caught method of gameending
                    gameEnding. Caught();
                }
            }
        }
    }
}

WayPointsPatrol

Generate moving points and use arrays to store target points. The specific location can be set in the array waypoints[]

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

public class WayPointsPatrol : MonoBehaviour
{<!-- -->
    //navigation component
    public NavMeshAgent navMeshAgent;
    //Array of navigation points
    public Transform[] waypoints;
    //The target point of the current patrol
    int m_currentpointIndex;


    // Start is called before the first frame update
    void Start()
    {<!-- -->
        navMeshAgent = GetComponent<NavMeshAgent>();
        //From the starting point to the first patrol point
        navMeshAgent.SetDestination(waypoints[0].position);
    }

    // Update is called once per frame
    void Update()
    {<!-- -->
        // reach the target point, go to the next target point
        if (navMeshAgent. remainingDistance<navMeshAgent.stoppingDistance)
        {<!-- -->
            m_currentpointIndex=(m_currentpointIndex + 1) % waypoints.Length;
            navMeshAgent.SetDestination(waypoints[m_currentpointIndex].position);
        }
    }
}

Several statements worth recording:

void Start()
//Initial state function, run at the beginning of the game
void Update()
//A function that runs every frame, dynamically acquired
public void FixedUpdate()
//Fixed frame update, generally used for physical update
public void OnAnimatorMove()
//You can make the object change the space coordinates of the object according to the space displacement of the animation itself
public void OnTriggerEnter()
// detect object collision
Time.deltaTime
//The next frame time minus the previous frame time
//The meaning of its existence: It can make moving objects move at the same average speed at the same time.
navMeshAgent. SetDestination()
//The position of the next target point
GameObject. GetComponent<Type>()
//GameObject is the variable name of the current game object
//Type is the component name, the type is string
//Get the current game object component method, you can directly call it to access the game object components and adjust parameters.
Animator //Define animation
Rigidbody //Define the rigid body component
Vector3 //Define the moving vector
Quaternion //Define the rotation angle
AudioSource //define audio

Final effect

Overall interface
Interface after running