- Home /
How would I rotate an object relative to another without parenting?
The code below does the job, but as soon as I change the offsets to position the text it ends up rotating incrementally horrible until it's back to the original rotation. For example, if I set the offset to -0.9 it would move the text to the left of the object, when I've rotated said object 180 degrees the text is to the right of the object (or still left if you haven't changed the camera angle)
private void AlignWithPlane(GameObject textObj, GameObject planeObj, float zOffset,
float xOffset = 0.0f, float yOffset = -0.0f)
//float xOffset = 0.05f, float yOffset = -0.9f)
{
textObj.transform.position = new Vector3(planeObj.transform.position.x + xOffset, // Away/towards plane
planeObj.transform.position.y + yOffset, // Left/right plane
planeObj.transform.position.z + zOffset); // Up/down plane
textObj.transform.rotation = planeObj.transform.rotation;
}
Can you provide a drawing or picture of the alignment you are trying to achieve with these two object. There are multiple ways to solve this problem.
I'll do you one better! Here's a video: http://youtu.be/L$$anonymous$$F7eNCPVa$$anonymous$$
Answer by robertbu · Jun 19, 2013 at 05:02 PM
The video is helpful, but I'm still not completely sure what you want the correct behavior to be. The issue I see is more about your offset than your rotation. It looks to me that you want a local offset relative to the plane, but you are calculating everything as world coordinates. You can handle this by:
Vector3 v3Offset = new Vector3(xOffset, yOffset, zOffset);
textObject.transform.position = planeObj.transform.TransformPoint(v3Offset);
Another way would be to use Transform.forward to set your position:
textObj.transform.position = planeObj.transform.forward * offset;
Where 'offset' is some small float. Note for either solution you'll still have to assign the rotation as you do in the code above.
Your first code snippet was exactly what I was after! Thank you very much. :) -hands e-beer-
Answer by bubzy · Jun 19, 2013 at 04:42 PM
you might want to check Vector3.RotateAround()
Would you be able to provide an example please? :) I'm assu$$anonymous$$g you meant Transform.RotateAround(). Every time I try to use that I get lost. :\
I need to be able to rotate with relativity to all three axis while maintaining the constraint (without parenting).
Your answer
Follow this Question
Related Questions
Instantiate GameObject towards player 0 Answers
Transform a Vector by a Quaternion 1 Answer
How do I align my player transform to waypoints and without restricting Z Axis rotation? 2 Answers
Multiple Fire on different launcher GameObjects 1 Answer
Smooth 90 degrees rotation on input . (infinite number of times) 1 Answer