我应该使用StartCoroutine吗?
using UnityEngine;
using System.Collections;
using System.Reflection;
public class DetectPlayer : MonoBehaviour {
GameObject target;
int counter = 0;
public static bool touched = false;
public float moveSpeed = 3.0f;
public float smooth = 1f;
private float distanceTravelled;
private Vector3 startPositon;
public float distanceToTravel = 50;
private void Start()
{
startPositon = new Vector3(target.transform.position.x, target.transform.position.y, target.transform.position.z);
}
private void Update()
{
if (RaiseWalls.raised == true && touched == true)
{
MoveElevator();
//touched = false;
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.name == "ThirdPersonController") // "Platform"
{
Debug.Log("Touching Platform");
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.name == "ThirdPersonController") // "OnTop Detector"
{
counter = 0;
Debug.Log("On Top of Platform");
target = GameObject.Find("Elevator");
GameObject findGo = GameObject.Find("ThirdPersonController");
GameObject findGo1 = GameObject.Find("Elevator");
findGo.transform.parent = findGo1.transform;
GameObject go = GameObject.Find("CubeToRaise");
go.GetComponent<RaiseWalls>();
Debug.Log("The button clicked, raising the wall");
touched = true;
}
}
void OnTriggerExit(Collider other)
{
GameObject findGo = GameObject.Find("ThirdPersonController");
findGo.transform.parent = null;
}
void MoveElevator()
{
if (distanceTravelled == distanceToTravel)
{
}
else
{
target.transform.localPosition += target.transform.up * Time.deltaTime * moveSpeed;
distanceTravelled += Vector3.Distance(target.transform.position, startPositon);
}
}
}
在这种情况下,MoveElvator功能中的电梯正在向上移动。 现在我想在达到高度50时开始向后移动并在检测到地面时停止。
所以我添加了
if (distanceTravelled == distanceToTravel)
{
}
但不确定如何让它向下移动并在到达地面时停止。
答案 0 :(得分:0)
无论电梯是向上,向下还是保持静止,您都需要保持某种状态。您可以使用枚举:
enum State{
Idle,
MovingUp,
MovingDown
}
现在你只需要在顶部或底部向下移动并翻转方向。
答案 1 :(得分:0)
这是我使用的脚本:
float distance = 50;
float oneWayDuration;
void Start () {
StartCoroutine(Mover(oneWayDuration, distance));
}
IEnumerator Mover(float oneWayDuration, float yDifference)
{
Vector3 startPos = transform.position;
Vector3 desirePos = new Vector3(startPos.x, startPos.y + 50 , startPos.z);
float timeElapsed = 0f;
while (timeElapsed < oneWayDuration)
{
timeElapsed += Time.deltaTime;
transform.position = Vector3.Lerp(startPos, desirePos, timeElapsed / oneWayDuration);
yield return new WaitForEndOfFrame();
}
while (timeElapsed < oneWayDuration)
{
timeElapsed += Time.deltaTime;
transform.position = Vector3.Lerp(desirePos, startPos, timeElapsed / oneWayDuration);
yield return new WaitForEndOfFrame();
}
//Just in case
transform.position = startPos;
}