How to Bind a gameobject Rotation to another gameobject Position?

Hi,

I want to control the rotation of a gameobject B using the translation of another gameobject A like in the image bellow.


To be exact:

  • When Object A transform.position.x = +x, Object B transform.rotation.z = +180
  • The same for the other axes.

Any ideas how to do that?

Thank you.

Psuedo code -

Get object A pos x and pos Y relative to the center.
Use in Atan2.
Use result of atan as rotation for object B.
Eventually adjust that rotation with whatever degree (±0 to 180) to make it appear at the desired angle.

Thank you for your reply,

I attached the following script to Object A,

public class move : MonoBehaviour {

	public GameObject objectB;

	void Update () {
		Vector3 relative = transform.InverseTransformPoint(transform.position);
		float angle = Mathf.Atan2(relative.x, relative.y) * Mathf.Rad2Deg;
		print (angle);
		objectB.transform.Rotate(0, angle, 0);
	}
}

But the value of “angle” is always 0, I think I missed something in the solution you proposed.
Any ideas what’s wrong with my script??!!

Vector3 relative = transform.InverseTransformPoint(transform.position);

should be

Vector3 relative = transform.InverseTransformPoint(objectB.transform.position);

You’re telling Unity, “Okay, take your own world-space position (transform.position), and tell me what that position is in your own local space (transform.InverseTransformPoint)”. Note that these two are the same - “relative” is always going to come out to 0,0,0. (Or within a rounding error of that, anyway)

One of those “transform.” in your code should be “objectB.transform.”, I think.

Thank you all for your help,

I changed the code as you suggested:

Vector3 relative = transform.InverseTransformPoint(objectB.transform.position);
		float angle = Mathf.Atan2(relative.x, relative.y) * Mathf.Rad2Deg;
		objectB.transform.rotation = Quaternion.Euler(0, 0, angle);

But, it’s not behaving the way I expected, when I move Object A along the X axes with Y=0, Object B rotation around Z axes just snaps between +180° and -180°.
I want a smooth transition between these two values when I move Object A along the X axes with Y=0.

Thank you very much for your time.

You could do something like this:

// Smooth
objectB.transform.rotation = Quaternion.Slerp(objectB.transform.rotation, Quaternion.Euler(0, 0, angle), Time.deltaTime * 2);

You might be hitting a “corner case” with y=0. Do the other values of y behave correctly? If so, you need to test for the y=0 case and create a workaround. This can happen with trig functions…or really, any function with a division, because you might divide by 0 inadvertently.