Unity용 도어 스크립트
이 튜토리얼에서는 Unity에서 클래식 문과 미닫이 문을 만드는 방법을 보여 드리겠습니다.
클래식 도어
클래식 문은 경첩을 중심으로 회전하여 열리는 일반 문입니다.
단계
Unity에 일반 문을 만들려면 다음 단계를 따르세요.
- 새 스크립트를 만들고 이름을 'SC_DoorScript'으로 지정하고 모든 내용을 제거한 후 아래 코드를 붙여넣습니다.
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;
}
}
}
- 문 모델을 씬 뷰로 드래그 앤 드롭하세요. (또는 새 큐브를 만들고 문과 비슷하게 크기를 조정하세요.)
- 새 GameObject를 생성하고(GameObject -> Create Blank) 이름을 지정합니다. "Door"
- 문 경첩이 있어야 할 위치로 "Door" 개체를 이동합니다.
- SphereCollider 구성 요소를 "Door" 개체에 연결하고 반경을 변경하여 문보다 크게 만듭니다(플레이어가 문을 열 수 있는 영역이 됨).
- 문 모델을 "Door" 개체 내부로 이동하세요.
- 플레이어가 다음과 같이 태그되어 있는지 확인하세요. "Player"
- 트리거 영역에 들어가면 'F'을 눌러 문을 열고 닫을 수 있습니다.
미닫이 문
미닫이문은 특정 방향(예: 위, 아래, 왼쪽, 오른쪽)으로 밀어서 열리는 문으로 SF 레벨에서 자주 사용됩니다.
단계
Unity에서 미닫이문을 만들려면 다음 단계를 따르세요.
- 새 스크립트를 만들고 이름을 'SC_SlidingDoor'로 지정하고 모든 내용을 제거한 후 아래 코드를 붙여넣습니다.
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;
}
}
}
- 문 모델을 씬 뷰로 드래그 앤 드롭하세요. (또는 새 큐브를 만들고 문과 비슷하게 크기를 조정하세요.)
- 새 GameObject를 생성하고(GameObject -> Create Blank) 이름을 지정합니다. "SlidingDoor"
- "SlidingDoor" 개체를 문 모델의 중앙 위치로 이동합니다.
- SphereCollider 구성 요소를 "SlidingDoor" 개체에 연결하고 반경을 변경하여 문보다 크게 만듭니다(이 부분이 열기 이벤트를 트리거하는 영역이 됩니다).
- 문 모델을 "SlidingDoor" 개체 내부로 이동하세요.
- 플레이어가 다음과 같이 태그되어 있는지 확인하세요. "Player"
- 트리거 영역에 들어가면 문이 자동으로 열리고 플레이어가 트리거 영역을 벗어나면 닫혀야 합니다.