【发布时间】:2018-12-09 03:31:46
【问题描述】:
故事是我有一个研究项目,我必须在其中模拟一个跟踪实验。
我在一个盒子里有一个球(我们希望将来可以将其实现为 VR 房间),并且球会移动到随机坐标。
我还计划添加另一个对象,用户可以单击(或者在 VR 的情况下,使用操纵杆)来移动和跟随球。
小球每次运动的坐标,物体每次运动的坐标都必须输出到文件中。
现在,我很难将球发送到随机坐标。
球名为“Player”,文件名为“PlayerController”。两个问题是,在使用 Random 的 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();
}
【问题讨论】:
-
每次运行我得到不同的坐标。球不会停止移动,因为您在协程结束时将
hasArrived设置为 false,因此它每 2 秒再次触发一次 -
所以,@ryeMoss 我删除了 hasArrived 的最后一行,它确实解决了持续路径问题。对此感激不尽。但是,我仍然面临两个问题: 1. 每次运行都显示相同的路径。这可能是因为我有一台Mac吗? 2. 我有一个包含 20 个向量的数组要移动到,但现在球只移动到一个点。我该如何解决这个问题?