The story is that I have this research project in which I have to simulate a tracking experiment.
I have a ball in a box (which we hope can be implemented as a VR room in the future), and the ball moves to random coordinates.
I also plan on adding another object that the user can click on (or in the case of VR, use a joystick) to move and follow the ball.
The coordinates of each movement of the ball, and the coordinates of each movement of the object must be outputted to a file.
Right now, I am having difficulty sending the ball to random coordinates.
The ball is named "Player" and the file is named "PlayerController." The two issues are that while utilizing the Unity version of Random, I consistently attain the same coordinates on each run and the ball does not stop moving.
My code is attached below. Also, if any of you readers have an idea on how to implement the rest of my project, suggestions are definitely appreciated!
Thank you so much!
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();
}
Aucun commentaire:
Enregistrer un commentaire