- Home /
Question by
Lost_Syndicate · Feb 12, 2018 at 08:55 PM ·
arrayvector3lookatrotatetowards
Rotating object towards transform array
Ok, so im trying to rotate my object towards these points i made. I have a transform array, but i cant use it in Vector3.RotateTowards. I dont know much about rotating an object towards one. Here is my script so far,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PathFollower : MonoBehaviour
{
public Transform[] path;
public float speed = 1.0f;
public float reachDistance = 1.0f;
public int currentPoint = 0;
private void Start()
{
}
private void Update()
{
float step = speed * Time.deltaTime;
Vector3 newDir = Vector3.RotateTowards(transform.forward,//How do i put Path[] here? , step, 0.0f);
Vector3 dir = path[currentPoint].position - transform.position;
transform.position += dir * Time.deltaTime * speed;
if (dir.magnitude <= reachDistance)
{
currentPoint++;
}
if (currentPoint >= path.Length)
{
currentPoint = 0;
}
}
private void OnDrawGizmos()
{
if (path.Length > 0)
for (int i = 0; i < path.Length; i++)
{
if (path[0] != null)
{
Gizmos.DrawSphere(path[i].position, reachDistance);
}
}
}
}
Anyone know how this is done or how to do it?
Comment
Answer by premium123 · Feb 13, 2018 at 12:49 AM
I had this code example. here you rotate only in Y direction against a targetPosition.
public static void RotateToTargetInY(Transform t, Vector3 targetPosition, float speed)
{
Quaternion rotation = Quaternion.LookRotation(targetPosition - t.position);
rotation.x = 0;
rotation.z = 0;
t.rotation = Quaternion.Slerp(t.rotation, rotation, Time.deltaTime * speed);
}
Answer by yummy81 · Feb 13, 2018 at 08:48 AM
So, in order to rotate your object towards those points, you can use Quaternion.LookRotation. Supply it with direction as a parameter, and assign it to transform.rotation in Update method. I made a few modifications to your code. Here it is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PathFollower : MonoBehaviour
{
public Transform[] path;
public float speed = 1.0f;
public float reachDistance = 1.0f;
public int currentPoint = 0;
private void Update()
{
Vector3 direction = path[currentPoint].position - transform.position;
transform.position += direction * Time.deltaTime * speed;
transform.rotation = Quaternion.LookRotation(direction);
if ( Vector3.Distance(transform.position, path[currentPoint].position) <= reachDistance )
{
currentPoint++;
}
currentPoint%=path.Length;
}
private void OnDrawGizmos()
{
if (path.Length > 0)
{
for (int i = 0; i < path.Length; i++)
{
if (path[i] != null) Gizmos.DrawSphere(path[i].position, reachDistance);
}
}
}
}