简体   繁体   中英

Unity/C# - Set position and rotation manually of object based on another object

I have 3 objects in 3D Space, but they are only 2D representations of the 3D object. Object A (Obj-A) is the parent object, and 2 different objects (Obj-B, Obj-C) that are not attached to Obj-A as a child, but I have to move along as if they were its child. I am moving and rotating Obj-A, and I am setting Obj-B and Obj-C's positions based on Obj-A with an offset sort of like this:

objB.transform.position = objA.transform.position + offset;
objC.transform.position = objA.transform.position - offset;

But of course, when Obj-A rotates, I want Obj-B and Obj-C's position to be affected by its rotation as well. When I rotate Obj-B and Obj-C based on the same logic as Obj-A, they only rotate on their local axis. Basically it should look like this:

预期结果

I am working on Unity, but this part of the project is computed on a C# script independent from Unity. With this, I only have access to the objects' transform positions and the rotation angle, and simply adding Obj-B and Obj-C as children to Obj-A is off the table.

Please help! Thank you!

First you should copy the rotation like

objB.transform.rotation = objA.transform.rotation;
objC.transform.rotation = objA.transform.rotation;

then you should use the offset componentwise with the local coordinate system of objA :

objB.transform.position = objA.transform.position 
                          + offset.x * objA.transform.right
                          + offset.y * objA.transform.up
                          + offset.z * objA.transform.forward;

objB.transform.position = objA.transform.position 
                          - offset.x * objA.transform.right
                          - offset.y * objA.transform.up
                          - offset.z * objA.transform.forward;

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