- Home /
Rotating an object so that the direction between it's children matches the forward of rotating object
Hello, I have been really struggling to solve this issue.
I have an object - "ParentObject" with a child that rotates into an appropriate position - "Rotator". The "Rotator" object has several children which we will call Grip1, Grip2, Grip3, Grip4. They are all in different locations that cannot be moved or rotated. The only object that can be moved or rotated in this scenario is the "Rotator".
I want to be able to programmatically rotate the "Rotator" object so that the direction between two selected Grips matches the forward direction of the ParentObject.
So I need to find the direction between the two Grips being used and then rotate their parent so that both the grips fall along a perfect line created by the forward direction of the parent.
I have tried so many things and I am lost. I was hoping something like this would work but it does not:
float angleDifferenceY = Mathf.Atan2(directionToObject.x, directionToObject.z) Mathf.Rad2Deg; float angleDifferenceX = Mathf.Atan2(directionToObject.y, directionToObject.z) Mathf.Rad2Deg; rotator.transform.Rotate(angleDifferenceX, angleDifferenceY, 0); execute = false;
Any help would be appreciated
please use the code block feature. That is really hard to read.
Answer by Astrydax · Jul 07, 2021 at 06:57 AM
You should be able to average the differences of the two grips from their target and set that as the direction of the rotator.
Answer by BastianUrbach · Jul 07, 2021 at 01:35 PM
You can use Quaternion.FromToRotation for this. It calculates the shortest rotation that rotates one vector to another. All you need to do is figure out the current direction of the grips and then FromToRotation can give you the rotation that you need to apply:
var currentDirection = grip1.position - grip2.position;
var targetDirection = parent.forward;
var rotation = Quaternion.FromToRotation(currentDirection, targetDirection);
rotator.rotation = rotation * rotator.rotation;
If you're interested in the math behind that function: the cross product of the two directions is the axis of the rotation and the acos of their dot product is its angle.
Your answer
Follow this Question
Related Questions
How to get angular difference? 2 Answers
Align GameObject to Terrain angle 2 Answers
Creating a multiple part turret what locks onto certain axis. 4 Answers
How to properly do Twin Stick shooter controls with an XBOX controller? 1 Answer
Error of angle 0 Answers