1.创建场景
1.打开Unity并创建一个新场景。
2.添加一个Cube作为门。
3.添加一个Ul Button用于触发开门效果
2.设置旋转点
1.创建一个空的GameObject,命名为"DoorPivot”,将其放置在门的旋转点位置
2.将门作为“DoorPivot”的子对象
3.创建c#脚本
创建C#脚本,例如“DoorController.cs”,并附加到门上或"DoorPivot"上,脚本如下:
using UnityEngine;
public class DoorController : MonoBehaviour
{
public Transform doorPivot;
public float openAngle = 90f;
public float openSpeed = 2f;
private bool isOpen = false;
private Quaternion closedRotation;
private Quaternion openRotation;
void Start()
{
closedRotation = doorPivot.rotation;
openRotation = Quaternion.Euler(doorPivot.eulerAngles + Vector3.up * openAngle);
}
void Update()
{
if (isOpen)
{
doorPivot.rotation = Quaternion.Slerp(doorPivot.rotation, openRotation, Time.deltaTime * openSpeed);
}
else
{
doorPivot.rotation = Quaternion.Slerp(doorPivot.rotation, closedRotation, Time.deltaTime * openSpeed);
}
}
public void ToggleDoor()
{
isOpen = !isOpen;
}
}
4.连接按钮和脚本
1.选择Ul Button,在Inspector窗囗中找到Button组件。
2.在Button组件的OnClick事件中,点击”+“号添加一个新的事件。
3.将门的GameObject拖到事件的对象槽中。
4.从下拉菜单中选择DoorController ->ToggleDoor0()方法