Tập lệnh cửa cho sự thống nhất

Trong hướng dẫn này, tôi sẽ hướng dẫn cách tạo một cánh cửa trượt và cổ điển trong Unity.

Cửa cổ điển

Cửa cổ điển là cửa thông thường được mở bằng cách xoay quanh bản lề.

bước

Để tạo một cánh cửa thông thường trong Unity, hãy làm theo các bước dưới đây:

  • Tạo một tập lệnh mới, gọi nó là 'SC_DoorScript', xóa mọi thứ khỏi tập lệnh rồi dán mã bên dưới:

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;
        }
    }
}
  • Kéo và thả mô hình cửa của bạn vào chế độ xem Cảnh (hoặc tạo Khối mới và chia tỷ lệ cho giống với một cánh cửa)
  • Tạo một GameObject mới (GameObject -> Create Empty) và đặt tên cho nó "Door"
  • Di chuyển đối tượng "Door" đến vị trí cần đặt bản lề cửa

Vị trí đối tượng bản lề cửa Unity

  • Đính kèm thành phần SphereCollider vào đối tượng "Door" và thay đổi bán kính của nó sao cho nó lớn hơn một cánh cửa (đây sẽ là khu vực mà người chơi có thể mở cửa)
  • Di chuyển mô hình cửa của bạn vào trong đối tượng "Door"
  • Đảm bảo trình phát của bạn được gắn thẻ là "Player"
  • Khi bước vào khu vực kích hoạt, bạn có thể mở/đóng cửa bằng cách nhấn 'F'.

Cửa trượt

Cửa trượt là cửa mở bằng cách trượt theo một hướng cụ thể (ví dụ: lên, xuống, trái hoặc phải) và thường được sử dụng trong Cấp độ khoa học viễn tưởng.

bước

Để tạo cửa trượt trong Unity, hãy làm theo các bước dưới đây:

  • Tạo một tập lệnh mới, đặt tên là 'SC_SlidingDoor', xóa mọi thứ khỏi tập lệnh rồi dán mã bên dưới:

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;
        }
    }
}
  • Kéo và thả mô hình cửa của bạn vào chế độ xem Cảnh (hoặc tạo Khối mới và chia tỷ lệ cho giống với một cánh cửa)
  • Tạo một GameObject mới (GameObject -> Create Empty) và đặt tên cho nó "SlidingDoor"
  • Di chuyển đối tượng "SlidingDoor" đến vị trí chính giữa của mẫu cửa của bạn
  • Đính kèm thành phần SphereCollider vào đối tượng "SlidingDoor" và thay đổi bán kính của nó sao cho nó lớn hơn một cánh cửa (đây sẽ là khu vực sẽ kích hoạt sự kiện mở)
  • Di chuyển mô hình cửa của bạn vào trong đối tượng "SlidingDoor"
  • Đảm bảo trình phát của bạn được gắn thẻ là "Player"
  • Khi đi vào khu vực kích hoạt, cửa sẽ tự động mở và sau đó đóng lại khi người chơi rời khỏi khu vực kích hoạt.

Sharp Coder Trình phát video

Bài viết được đề xuất
Tài sản thống nhất hàng đầu từ Cửa hàng tài sản
Tập lệnh nhìn chuột cho Unity
Lựa chọn đơn vị kiểu RTS cho sự thống nhất
FPC Swimmer - Tài sản thống nhất toàn diện cho môi trường nước đắm chìm
Cách sử dụng Bộ điều khiển Xbox trong Unity
Cách sử dụng hệ thống nước HDRP mới trong Unity
Weather Maker - Nâng môi trường thống nhất lên tầm cao mới