- Home /
Rotation with multiple objects
I have the following snippet right now. I have a script that will control multiple objects with the same tag. The script is applied to an object moving around the game scene and I need the tagged objects to rotate to look at it. The rotation works, however all of them point the same direction relative to each other and not in the game space.
For example, if I have the tagged objects positioned in a circle around the script object they will all point in the same direction and not in fact the center of the game object that is moving around the map as I want them to.
//Objects tagged will look in the direction of the wind
if (taggedGameObjects != null) {
GameObject[] tagged;
tagged = GameObject.FindGameObjectsWithTag(taggedGameObjects);
foreach (GameObject obj in tagged) {
Vector3 targetPoint = new Vector3(0, transform.position.y, 0) - transform.position;
Quaternion targetRotation = Quaternion.LookRotation (targetPoint, Vector3.up);
obj.transform.rotation = Quaternion.Slerp(obj.transform.rotation, targetRotation, Time.deltaTime * 2.0f);
}
};
Any insight to help would be appreciated
Answer by Doireth · Oct 10, 2013 at 09:43 AM
The "targetPoint" looks to be the problem. Should be calculated like:
Vector3 targetPoint = transform.position - [Position of Tagged Object]
They currently all look the same way as target point is only working of the transform of the object that holds the script.
Solution:
foreach (GameObject obj in tagged) {
Vector3 relativePos = new Vector3(transform.position.x,obj.transform.position.y,transform.position.z) - obj.transform.position;
Quaternion rotation = Quaternion.LookRotation(relativePos);
obj.transform.rotation = rotation;
}