Scripts de porta para Unity

Neste tutorial mostrarei como fazer uma porta clássica e uma porta de correr em Unity.

Porta Clássica

Uma porta clássica é uma porta normal que se abre girando em torno das dobradiças.

Passos

Para fazer uma porta normal em Unity, siga os passos abaixo:

  • Crie um novo script, chame-o de 'SC_DoorScript', remova tudo dele e cole o código abaixo:

SC_DoorScript.cs

//Make an empty GameObject and call it "Door"
//Drag and drop your Door model into Scene and rename it to "Body"
//Make sure that the "Door" Object is at the side of the "Body" object (The place where a Door Hinge should be)
//Move the "Body" Object inside "Door"
//Add a Collider (preferably SphereCollider) to "Door" object and make it bigger then the "Body" model
//Assign this script to a "Door" Object (the one with a Trigger Collider)
//Make sure the main Character is tagged "Player"
//Upon walking into trigger area press "F" to open / close the door

using UnityEngine;

public class SC_DoorScript : MonoBehaviour
{
    // Smoothly open a door
    public AnimationCurve openSpeedCurve = new AnimationCurve(new Keyframe[] { new Keyframe(0, 1, 0, 0), new Keyframe(0.8f, 1, 0, 0), new Keyframe(1, 0, 0, 0) }); //Contols the open speed at a specific time (ex. the door opens fast at the start then slows down at the end)
    public float openSpeedMultiplier = 2.0f; //Increasing this value will make the door open faster
    public float doorOpenAngle = 90.0f; //Global door open speed that will multiply the openSpeedCurve

    bool open = false;
    bool enter = false;

    float defaultRotationAngle;
    float currentRotationAngle;
    float openTime = 0;

    void Start()
    {
        defaultRotationAngle = transform.localEulerAngles.y;
        currentRotationAngle = transform.localEulerAngles.y;

        //Set Collider as trigger
        GetComponent<Collider>().isTrigger = true;
    }

    // Main function
    void Update()
    {
        if (openTime < 1)
        {
            openTime += Time.deltaTime * openSpeedMultiplier * openSpeedCurve.Evaluate(openTime);
        }
        transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, Mathf.LerpAngle(currentRotationAngle, defaultRotationAngle + (open ? doorOpenAngle : 0), openTime), transform.localEulerAngles.z);

        if (Input.GetKeyDown(KeyCode.F) && enter)
        {
            open = !open;
            currentRotationAngle = transform.localEulerAngles.y;
            openTime = 0;
        }
    }

    // Display a simple info message when player is inside the trigger area (This is for testing purposes only so you can remove it)
    void OnGUI()
    {
        if (enter)
        {
            GUI.Label(new Rect(Screen.width / 2 - 75, Screen.height - 100, 155, 30), "Press 'F' to " + (open ? "close" : "open") + " the door");
        }
    }
    //

    // Activate the Main function when Player enter the trigger area
    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            enter = true;
        }
    }

    // Deactivate the Main function when Player exit the trigger area
    void OnTriggerExit(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            enter = false;
        }
    }
}
  • Arraste e solte seu modelo de porta na vista Cena (ou crie um novo Cubo e dimensione-o para se parecer com uma porta)
  • Crie um novo GameObject (GameObject -> Criar Vazio) e nomeie-o "Door"
  • Mova o objeto "Door" para a posição onde a dobradiça da porta deveria estar

Posição do objeto da dobradiça da porta da unidade

  • Anexe um componente SphereCollider ao objeto "Door" e altere seu raio para que seja maior que uma porta (esta será a área de onde o jogador poderá abrir a porta)
  • Mova seu modelo de porta dentro do objeto "Door"
  • Certifique-se de que seu player esteja marcado como "Player"
  • Ao entrar na área do gatilho, você poderá abrir/fechar a porta pressionando 'F'.

Porta deslizante

Uma porta deslizante é uma porta que se abre deslizando em uma direção específica (por exemplo, para cima, para baixo, para a esquerda ou para a direita) e é frequentemente usada em Níveis de ficção científica.

Passos

Para fazer uma porta deslizante em Unity, siga os passos abaixo:

  • Crie um novo script, chame-o de 'SC_SlidingDoor', remova tudo dele e cole o código abaixo:

SC_SlidingDoor.cs

//Make an empty GameObject and call it "SlidingDoor"
//Drag and drop your Door model into Scene and rename it to "Body"
//Move the "Body" Object inside "SlidingDoor"
//Add a Collider (preferably SphereCollider) to "SlidingDoor" Object and make it bigger then the "Body" model
//Assign this script to a "SlidingDoor" Object (the one with a Trigger Collider)
//Make sure the main Character is tagged "Player"
//Upon walking into trigger area the door should Open automatically

using UnityEngine;

public class SC_SlidingDoor : MonoBehaviour
{
    // Sliding door
    public AnimationCurve openSpeedCurve = new AnimationCurve(new Keyframe[] { new Keyframe(0, 1, 0, 0), new Keyframe(0.8f, 1, 0, 0), new Keyframe(1, 0, 0, 0) }); //Contols the open speed at a specific time (ex. the door opens fast at the start then slows down at the end)
    public enum OpenDirection { x, y, z }
    public OpenDirection direction = OpenDirection.y;
    public float openDistance = 3f; //How far should door slide (change direction by entering either a positive or a negative value)
    public float openSpeedMultiplier = 2.0f; //Increasing this value will make the door open faster
    public Transform doorBody; //Door body Transform

    bool open = false;

    Vector3 defaultDoorPosition;
    Vector3 currentDoorPosition;
    float openTime = 0;

    void Start()
    {
        if (doorBody)
        {
            defaultDoorPosition = doorBody.localPosition;
        }

        //Set Collider as trigger
        GetComponent<Collider>().isTrigger = true;
    }

    // Main function
    void Update()
    {
        if (!doorBody)
            return;

        if (openTime < 1)
        {
            openTime += Time.deltaTime * openSpeedMultiplier * openSpeedCurve.Evaluate(openTime);
        }

        if (direction == OpenDirection.x)
        {
            doorBody.localPosition = new Vector3(Mathf.Lerp(currentDoorPosition.x, defaultDoorPosition.x + (open ? openDistance : 0), openTime), doorBody.localPosition.y, doorBody.localPosition.z);
        }
        else if (direction == OpenDirection.y)
        {
            doorBody.localPosition = new Vector3(doorBody.localPosition.x, Mathf.Lerp(currentDoorPosition.y, defaultDoorPosition.y + (open ? openDistance : 0), openTime), doorBody.localPosition.z);
        }
        else if (direction == OpenDirection.z)
        {
            doorBody.localPosition = new Vector3(doorBody.localPosition.x, doorBody.localPosition.y, Mathf.Lerp(currentDoorPosition.z, defaultDoorPosition.z + (open ? openDistance : 0), openTime));
        }
    }

    // Activate the Main function when Player enter the trigger area
    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            open = true;
            currentDoorPosition = doorBody.localPosition;
            openTime = 0;
        }
    }

    // Deactivate the Main function when Player exit the trigger area
    void OnTriggerExit(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            open = false;
            currentDoorPosition = doorBody.localPosition;
            openTime = 0;
        }
    }
}
  • Arraste e solte seu modelo de porta na vista Cena (ou crie um novo Cubo e dimensione-o para se parecer com uma porta)
  • Crie um novo GameObject (GameObject -> Criar Vazio) e nomeie-o "SlidingDoor"
  • Mova o objeto "SlidingDoor" para a posição central do seu modelo de porta
  • Anexe um componente SphereCollider ao objeto "SlidingDoor" e altere seu raio para que seja maior que uma porta (esta será a área que acionará o evento open)
  • Mova seu modelo de porta dentro do objeto "SlidingDoor"
  • Certifique-se de que seu player esteja marcado como "Player"
  • Ao entrar na área do gatilho, a porta deve abrir automaticamente e fechar assim que o jogador sair da área do gatilho.

Sharp Coder Reprodutor de vídeo

Artigos sugeridos
FPC Swimmer - Um ativo de unidade abrangente para ambientes aquáticos imersivos
Script para criar um interruptor de luz no Unity
Seleção de unidade estilo RTS para Unity
Editor de mapa de altura de terreno no jogo para Unity
Script de aparência do mouse para Unity
Como usar o controlador Xbox no Unity
Script de tiro com arma baseado em Raycast e projéteis para Unity