transform.Translate changing object position by incorrect amount
I'm trying to make the camera revolve around the game object while keeping its lens pointed at the object (think of a geostationary satellite), but the object's position is being changed by an incorrect value, which throws off the revolution.
Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraRotator : MonoBehaviour {
public float speed;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
//var x = Input.GetAxis("Horizontal2") * Time.deltaTime * speed; //the input-driven rotation
var x = 1f; //driver value to speed testing
float currentX = transform.position.x;
float currentZ = transform.position.z;
Debug.Log ("currentX = " + currentX);
Debug.Log ("currentZ = " + currentZ); //these return the x and z positions of the object before translation
transform.Translate (-x, 0, x); //change the object's x position by -1, and the object's z position by +1
float rotX = (float) (x * 1.8);
transform.Rotate (0, rotX, 0); //geostationary stuff that seems to be working but may be contributing to the problem (I don't know)
}
}
It works for the first update (x is decreased by 1 and z is increased by 1), but after that it reduces x by slightly less than 1 (0.968096) and increases z by slightly more than 1 (1.03092). The difference continues to increase after that, with x being decreased by 0.935236 and z being increased by 1.06082 for the third update and so on.
I'm very new to Unity (and C# for that matter), so it's likely a case of me not understanding something in how .Translate works, but right now I have absolutely no idea.
Answer by UnityCoach · Apr 25, 2017 at 07:44 AM
By default, Transform.Translate uses Space.Self for reference coordinates. As you rotate the object about Y , it'll start balancing your X translation on X and Z.
Transform.position always returns the position in World space.
You can use transform.Translate (-x, 0, x, Space.World);
to fix this.
The Transform component offers many interesting transformation features like TransformPoint, etc..
I believe you could possibly do it all with Transform.RotateAround