1
\$\begingroup\$

I have a set of 2D points (defining a flat 2D 'connect the dots' shape). I want to calculate the 3D positions for these 2D points at a specific 3D position and rotation.

For example, say I have five 2D points forming the shape of a 2D hexagon. I want to place this hexagon shape at a specific location in my 3D world, at a specific rotation. I need to calculate new 3D coordinates for each of the 2D points.

If it matters, the 2D points will center around (0,0).

What magic formula do I need to do to accomplish this translation? Is there a built in method (in Unity) to do this?

Each point will be perpendicular to the rotation angle/direction, so will I need to calculate the cross product? Then somehow use this to remap each 2D point?

I should have paid more attention to this in school, all those years ago (I can't even remember if I actually learned this before!).

Any help will be appreciated. Thanks.

Here's some basic code to illustrate:

Vector3 position;     // Where in 3D to place the 2D shape
Quaternion rotation;  // What 3D rotation to apply to the 2D shape.  Should be a Vector3?
Vector2[] shapeIn;    // List of 2D points defining shape
Vector3[] shapeOut;   // List of updated 3D points at its new position and rotation

shapeOut = new Vector3[shapeIn.Length];

for (int p=0; p<shapeIn.Length; p++) {
    shapeOut[p] = MagicFormula(shapeIn[p]);
}
\$\endgroup\$
1
\$\begingroup\$

You don't need anything special to do this. You can "up-convert" a Vector2 to a Vector3 with z = 0 by writing:

(Vector3)shapeIn[p];

This will give you your shape in 3D, oriented in the XY plane (vertically, facing the default camera position you'd get for a new scene). (0, 0) in the source shape will map to (0, 0, 0) in the scene.

You can now use all the regular tricks you'd use to orient a 3D object.

To rotate it, you just need to multiply each point by a Quaternion representing the orientation you want. You could copy this from another object whose orientation you've manipulated in the scene to the angle you want:

shapeRotation = myReferenceObject.transform.rotation;

Or you could construct it using convenience functions like Quaternion.AngleAxis(angle, axis) or Quaternion.Euler(x, y, z)

To translate it, just add an offset Vector3 (which represents the coordinates of the worldspace point you want to map the source shape's (0, 0) to)

Putting it all together:

 shapeOut[p] = (shapeRotation * (Vector3)shapeIn[p]) + shapeOffset;
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.