Home > OS >  Defining a relative point with rotations
Defining a relative point with rotations

Time:02-19

I want to get a relative point (so it's current pos a vector3 of directions)

so that when I rotate the gameObject it's still in the same relative point

Example: (say if it was 1 unit away from the gameObject in the x axis when rotation is 0, it should be 1 unit away form the gameObject in the z axis when rotation is -90)

here's what I tried: (center is a vector3 of the distance relative to the gameObject)

boxPos = new Vector3(
    center.x   transform.position.x   (transform.rotation.eulerAngles.y * (1 / 360) * center.x),
    center.y   transform.position.y,
    center.z   transform.position.z   (0.5f - (transform.rotation.eulerAngles.y * (1 / 360) * center.z))
    );

any way how to do so?

CodePudding user response:

There is a math equation to solve this. Assuming you have Quaternion rotation; for the objects rotation, Vector3 objectPosition; for the game object and Vector3 point; for the point in local space, the equation is (rotation * (point-objectPosition)) objectPosition

Vector3 objectPosition = transform.position;
Quaternion rotation = transform.rotation;
Vector3 point = Vector3(1, 0, 0);
Vector3 worldSpacePoint = (rotation * (point-objectPosition))   objectPosition;
// if rotation is -90 degrees on the Y axis and objectPosition is zero, worldSpacePoint will be Vector3(0, 0, 1)

CodePudding user response:

You're already using a transform so just use InverseTransformPoint to calculate the local position of the object and if you want to convert back to a world position you can use TransformPoint:

Transform target;
Vector3 relativePos;

// ...

Vector3 relativePos = transform.InverseTransformPoint(target.position);

// ...

Vector3 worldPos = transform.TransformPoint(relativePos);
  • Related