- Home /
The question is answered, right answer was accepted
LookRotation Between 2 Points
Basically I am trying to get an object to look at one object or a specific rotation, then smoothly switch to another rotation or object, and to continuously loop.
I have written a small script that i think is on the right track for working using Co-routines.
public Transform pointB;
public Transform pointC;
public IEnumerator TurretLook (Transform thisTransform, Quaternion startAngle, Quaternion endAngle, float time)
{
float i = 0.0f;
float rate = 1.0f / time;
while (i < 1.0) {
i += Time.deltaTime * rate;
thisTransform.rotation = Quaternion.Lerp (startAngle, endAngle, i);
yield return new WaitForSeconds(0);
}
}
IEnumerator Start ()
{
Quaternion pointA = transform.rotation;
while (true) {
yield return TurretLook(transform, pointA, Quaternion.LookRotation (pointB.position - transform.position), 3.0f);
yield return TurretLook(transform, pointA, Quaternion.LookRotation (pointC.position - transform.position), 3.0f);
}
}
Answer by Sooper1337 · Oct 21, 2012 at 10:19 PM
Ended up Rewriting the Script. Posting Here in case anyone else might want this solution as well.
Uses 2 Empty Gameobjects with colliders attached to detect when the ray-cast intersects with one, then switched states to target the opposite.
using UnityEngine;
using System.Collections;
public class MainMenuTurret : MonoBehaviour
{
private float aimSpeed;
public float dampening;
public Transform[] points;
public enum Target{
point1,
point2
};
public Target tState;
public void MenuIdle ()
{
Ray idle = new Ray (transform.position, transform.forward);
RaycastHit hit;
Debug.DrawRay(idle.origin, idle.direction * 5, Color.blue);
if (Physics.Raycast (idle, out hit, 5)) {
GameObject hitObj = hit.collider.gameObject;
if (hitObj.tag == "P1")
tState = Target.point2;
if (hitObj.tag == "P2")
tState = Target.point1;
}
}
void Update ()
{
aimSpeed = dampening * Time.deltaTime;
MenuIdle ();
switch (tState) {
case Target.point1:
transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation (points [0].position - transform.position), aimSpeed);
break;
case Target.point2:
transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation (points [1].position - transform.position), aimSpeed);
break;
}
}
}
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
Quaternion.Slerp with Quaternion.LookRotation causes unexpected results 1 Answer
i want to get my to cube to rotate 90 degrees on the x-axis as it jumps 0 Answers
Quaternion.LookRotation and Vector3.SmoothDamp Problems 1 Answer
Rotate object without storing facing 1 Answer