Hi,
I’ve created a script which makes a capsule spawn in a random point and then moves to another random point and once that point is reached it recreates a new point in which to move to and it does.
Once I created this script I realised soon after running it that the rotation of the capsule needed to be in the direction of movement. I added a Quarternion which looks at the end point and then should rotate towards it but for some reason sometimes it works and sometimes it doesn’t and that’s where my problem lies. Hopefully someone can see what/where I’ve gone wrong and would be so helpful as to point this out to me and correct me.
(I understand that the Y axis also floats around and the capsule starts to spin because Y isn’t set to 0 - I haven’t looked into fixing this yet but if you notice anything that can be changed then please feel free to mention).
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour {
public Vector3 startMarker;
public Vector3 endMarker;
public Vector3 currentPos;
public float speed = 1.0f;
private float startTime;
private float journeyLength;
void Start()
{
startMarker = new Vector3(Random.Range(-10f, 10f), 0f, Random.Range(-10f, 10f));
endMarker = new Vector3(Random.Range(-10f, 10f), 0f, Random.Range(-10f, 10f));
startTime = Time.time;
journeyLength = Vector3.Distance(startMarker, endMarker);
}
void ResetMovement()
{
startMarker = transform.position;
startTime = Time.time;
endMarker = new Vector3(Random.Range(-10f, 10f), 0f, Random.Range(-10f, 10f));
}
void EnemyMovement()
{
float distCovered = (Time.time - startTime) * speed;
float fracJourney = distCovered / journeyLength;
transform.position = Vector3.Lerp(startMarker, endMarker, fracJourney);
Quaternion targetRotation = Quaternion.LookRotation(endMarker);
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, Time.deltaTime * 100);
currentPos = transform.position;
if (currentPos == endMarker)
{
ResetMovement();
}
}
void Update()
{
EnemyMovement();
}
}