嗨,所以我在Unity3d中使用C#,我的门代码出了问题。基本上我有一个检测立方体,它是实际门的子,这个代码附加到检测立方体。我的问题是门正在水平翻转并向上移动,这只是吓坏了。我的错误可能是显而易见的,但我是团结的新手,所以请耐心等待。任何帮助表示赞赏,提前谢谢。(也不知道这是否有用,但由于造型问题(AKA,我不知道为什么),门通常面朝下水平,因为它被撞倒了所以它被旋转90度,所以它是正直的)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Door : MonoBehaviour
{
public float doorOpenAngle = 90.0f;
public float doorCloseAngle = 0.0f;
public float doorAnimSpeed = 2.0f;
private Quaternion doorOpen = Quaternion.identity;
private Quaternion doorClose = Quaternion.identity;
public bool doorStatus = false;
private bool doorMoving = false;
public GameObject door;
void Start()
{
doorStatus = false;
doorOpen = Quaternion.Euler(-90, doorOpenAngle, 0);
doorClose = Quaternion.Euler(-90, doorCloseAngle, 0);
}
void Update()
{
}
public IEnumerator moveDoor(Quaternion destination)
{
doorMoving = true;
while (Quaternion.Angle(transform.localRotation, destination) > 4.0f)
{
door.transform.localRotation = Quaternion.Slerp(transform.localRotation, destination, Time.deltaTime * doorAnimSpeed);
yield return null;
}
doorStatus = !doorStatus;
doorMoving = false;
yield return null;
}
private void OnTriggerStay(Collider other)
{
other = GameObject.Find("FPSController").GetComponent<Collider>();
if (Input.GetKeyDown(KeyCode.E))
{
if (doorMoving == false)
{
if (doorStatus)
StartCoroutine(this.moveDoor(doorOpen));
else
StartCoroutine(this.moveDoor(doorClose));
}
}
}
}
这里的最终目标是让门旋转90度。
答案 0 :(得分:0)
将此添加到“开始”功能的末尾,以便您知道可以验证您的角度是否符合您的想法:
door.transform.localRotation = doorClose;
将起始角度设置在slerp之外应该可以解决部分问题。我还将while循环的条件更改为基于时间。
float elapsed = 0f;
Quaternion startRotation = door.transform.localRotation;
while (elapsed <= 1f/doorAnimSpeed){
elapsed += Time.deltaTime;
door.transform.localRotation = Quaternion.Slerp(startRotation, destination, elapsed * doorAnimSpeed);
yield return null;
}
您可能还想将空游戏对象添加为孩子,并将门模型添加到该对象中。然后,您可以根据需要旋转该空白,并且只在需要打开和关闭它时在一个轴上旋转父级。