故事是我有这个研究项目,我必须模拟跟踪实验 .
我在一个盒子里有一个球(我们希望将来可以将它作为一个VR室实施),然后球移动到随机坐标 .
我还计划添加另一个用户可以点击的对象(或者在VR的情况下,使用操纵杆)移动并跟随球 .
必须将球的每个运动的坐标和对象的每个运动的坐标输出到文件 .
现在,我很难将球发送到随机坐标 .
球被命名为“Player”,文件名为“PlayerController” . 这两个问题是,在使用随机的Unity版本时,我在每次运行中始终获得相同的坐标,并且球不会停止移动 .
我的代码附在下面 . 此外,如果您的任何读者都知道如何实施我的项目的其余部分,建议肯定赞赏!
非常感谢!
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class PlayerController : MonoBehaviour {
private float movementDuration = 2.0f;
private float waitBeforeMoving = 2.0f;
private bool hasArrived = false;
private Coroutine moveCoroutine = null;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (!hasArrived)
{
hasArrived = true;
Vector3[] v = new Vector3[20];
for (int i=0; i<v.Length; i++)
{
Random.InitState(System.DateTime.Now.Millisecond);
v[i] = new Vector3(Random.Range(-10.0f, 10.0f),
Random.Range(-10.0f, 10.0f),
Random.Range(-10.0f, 10.0f));
moveCoroutine = StartCoroutine(MoveToPoint(v[i]));
}
}
if (Input.GetMouseButtonDown(0))
StopMovement();
}
private IEnumerator MoveToPoint(Vector3 targetPos)
{
float timer = 0.0f;
Vector3 startPos = transform.position;
while (timer < movementDuration)
{
timer += Time.deltaTime;
float t = timer / movementDuration;
t = t * t * t * (t * (6f * t - 15f) + 10f);
transform.position = Vector3.Lerp(startPos, targetPos, t);
yield return null;
}
yield return new WaitForSeconds(waitBeforeMoving);
hasArrived = false;
}
private void StopMovement()
{
if (moveCoroutine != null)
StopCoroutine(moveCoroutine);
}
public void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("sphereTag"))
StopMovement();
}
1 回答
球不会停止移动,因为你在你的协程结束时将hasArrived设置为false,所以它每2秒再次发射一次 .
我每次坐标都不一样 - 不确定你面临的问题 . 可能是Random.InitState()的东西
你设置循环的方式,数组中的每个向量都被输入到自己的协程中,但这一切都是瞬间发生的,因为在进入你的for循环的下一次迭代之前没有延迟 . 如果你试图遍历所有20个点,你应该调用一个单独的协同程序,其中包含for循环和嵌入式延迟: