简体   繁体   中英

How to map 3D coordinates to 2D plane

I'm writing a OpenGL application in which there is a rectangle placed on a 3D object. The 3D object can move around and rotate and the rectangle follows these movements.

What I would like to do is to point with the mouse towards the rectangle so that a dot would appear in that point on the rectangle, and I want the point to follow it as the 3D object that "holds" the rectangle moves around.

I know how to find the intersection on a plane, and I know how to find the world coordinates of the contact point. What I need is a way to convert the world coordinates to the 2D local coordinate system of the rectangle.

For example, suppose I have the plane positioned like this in the 3D world, with a given orientation (sorry, I can't really draw properly):

在此处输入图片说明

The black point in the center is the origin of the plane, while the blue point is the one I would like to find. The numbers near the points are their world coordinates; in this example the Z axis "comes out" of the screen.

I would like to map the coordinates of the blue point in the local coordinate system of the plane, like this: 在此处输入图片说明

I know that somehow this shouldn't be hard, but I can't find a way at all. Any hints would be appreciated!

You probably already use a transformation matrix to render the rectangle. If you have the 3D position of the point, just transform it with the inverse transformation matrix and you get a 3D position in the rectangle's space. If the local system is aligned with the rectangle, one of the coordinates should always be zero and you can drop it.

I found what I needed in this post here .

Basically the solution for me is to project the point onto the x and y axis of the local coordinate system of the rectangle.

In pseudo code it's like this:

// I compute the direction that go from the origin of the rectangle to its x axis, in world coordinates, and take the norm; same thing for the y axis
var xDir = Norm(mRectangle.LocalToWorld([1, 0, 0]) - mRectangle.LocalToWorld([0, 0, 0]));
var yDir = Norm(mRectangle.LocalToWorld([0, 1, 0]) - mRectangle.LocalToWorld([0, 0, 0]));

// I compute the dot product
mLocalPosition.x = Dot(xDir, (contactPoint - mRectangle.LocalToWorld([0, 0, 0])));
mLocalPosition.y = Dot(yDir, (contactPoint - mRectangle.LocalToWorld([0, 0, 0])));

// I can now set the position of the point converting the local coordinates found to world coordinates
mPoint.SetPosition(mRectangle.LocalToWorld([mLocalPosition.x, mLocalPosition.y, 0]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM