Hi guys,
In a game set in space I’m working on, I can’t seem to get an object to face the camera, as well as end up level to the camera, using LookRotation(). I believe it’s because the camera could be at any arbitrary angle. I have been able to get the rotation to work on two axis, x & y, but the object is not rotated correctly on the z axis so it’s not level with respect to the camera.
Setup: An object is parented to an empty GameObject which in turn is parented to my camera. The empty GameObject is 15 units down the Z-axis, and the object is parented to the empty GameObject’s origin.
The camera flies around space before stopping, and the object appears in front of the camera rotating using a rigid body . So when the tractor beam is activated by the user, the position / rotation of the camera is arbitrary and the Slerp rotates the object. The script below works fine until the camera is rotated.
using UnityEngine;
using System.Collections;
public class test_rotate : MonoBehaviour {
public Transform target;
Vector3 targetV3; // Vector3 of camera (for LookRotation)
Quaternion rotateTo; //used to store LookAt angle
bool beamOn;
public Rigidbody rb;
int counter = 0; //counter for frames
float tracterBeamSpeed = 5f; //modifies the speed of rotating the object to face camera
void Start () {
rb.AddRelativeTorque (new Vector3 (50f, 500f, 150f)); //sets the object rotating
}
void Update () {
if (beamOn)
{
counter++;
if (counter <= 40) {
transform.rotation = Quaternion.Slerp (transform.rotation, rotateTo, Time.deltaTime * tracterBeamSpeed);
Debug.Log("rotating" +counter);
} else {
beamOn = false;
counter = 0;
Debug.Log("done rotating");
}
}
}
//button triggers this method
public void RotateStart()
{
rb.freezeRotation = true; //turn of rigidbody forces for rotation
//tried this, works if rotate camera x and / or y but not if rotate camera.z
targetV3 = target.forward;
//******** tried this, doesn't work if camera has been rotated, and since object is
// parented relative position may not be necessary
//targetV3 = (transform.position - target.position);
rotateTo = Quaternion.LookRotation(targetV3);
//******** also tried this, same result, doesn't work when camera is rotated
//rotateTo = Quaternion.identity;
beamOn = true; //turns on the Slerp function in Update
}
}
Thanks for any advice!
By the way, if I pause the game and type 0,0,0 as the eular angle for rotation in the the editor for the object, it faces the camera perfectly, which is why I tried using Quaternion.identity