Home > Software design >  Get new child object postion based on parent transform
Get new child object postion based on parent transform

Time:09-10

I need a function that calculates new OffSet position that takes 2 arguments old offset and rotation value (the rotation is only a float because the rotation is only happening around 1 axis always. I managed to find how to calculate facing direction based on rotation but I am having problem with offset. Found same topics like this but no answer except making child objects, which is not a good way. So a code like this

var offset = new Vector3(0f,5f,10f);
var rotationY = 90f;
var newOffset = NeededFunction(offset, rotationY);

The newOffset should be a Vector3 (10f,5f,0f). This is the funtion to calculate the facing direction

 private Vector3 GetFacingDirection()
{
    var rotY = transform.eulerAngles.y;
    var vector = Quaternion.AngleAxis(rotY, Vector3.up)
        * Vector3.forward;
    return vector;
}

CodePudding user response:

  1. Get Quaternion.LookRotation of the local position of the child game object. This is childStartRot. (Calculate in start, or only when you change it)
  2. Get the magnitude (or distance from 0) of the local position of the child game object. You can calculate this by getting the .magnitude property of the child's local position. This is childMag (Calculate in start, or only when you change it)
  3. Get total rotation of the parent times child this link explains how to add Quaternions (non-commutative) rotation. This is combinedRot. (This updates every frame)
  4. The point this rotation is "looking at" is equal to Vector3.forward * combinedRot. This is pointOnRot
  5. Normalize pointOnRot. Then multiply pointOnRot by childMag to get the offset position.
  6. The position of the child is equal to pointOnRot the parent object's position.

Example script:

public Quaternion parentRot; //change whenever in play mode
public Vector3 parentPos; //change whenever in play mode
public Vector3 childPos;

Quaternion childStartRot;
float childMag;

void Start()
{
   Vector3 local = parentPos - childPos;
   childStartRot = Quaternion.LookRotation(local);

   childMag = local.magnitude;
}
void Update()
{
   Quaternion combinedRot = parentRot * childStartRot;
   Vector3 pointOnRot = Vector3.forward * combinedRot;

   pointOnRot = pointOnRot.normalized * childMag;

   Vector3 output = pointOnRot   parentPos;
   //set child object position to output.
}
  • Related