user3277468
user3277468

Reputation: 141

Unity Setting Parent Objects position Equal to Their child position

I have two 3D objects eventually they will be 3D models of different sizes and shapes but I am trying to get the underlying functionality correct.

One is a regular Sphere with a child gameObject at position (0,-0.5,0) named s1.

One is a cylinder scaled (0.3,0.3,0.3) with child gameObject at position (0,0.5,0) named c1.

I am trying to move the objects so the two parents are aligned at the same child object position.

The code below moves the cyclinder position directly on the s1 position. Im just having trouble getting the vector math to work out so the c1 position is directly on the s1 position. I've tried multiple different addition,subtraction,division to get them to align but haven't had any luck. Any help understanding how to solve this would be much appreciated.

public GameObject sphere;
public GameObject cyclinder;

private GameObject s1;
private GameObject c1;

// Start is called before the first frame update
void Start()
{
    s1 = sphere.transform.Find("s1").gameObject;
    c1 = cyclinder.transform.Find("c1").gameObject;


    cyclinder.transform.position = s1.transform.position;
}

Upvotes: 0

Views: 3104

Answers (2)

kevernicus
kevernicus

Reputation: 364

While your question is not very clear, I think you mean you are trying to position your cylinder and sphere in such a way that their child objects (s1 and c1) share the exact same world position.

The steps I'd follow are:

  • Calculate the world-space offset between the child and its parent (normally this would just be the localPosition of your child object, but since you are also applying a localScale, this is taken into account by manually calculating an offset vector using world positions)
  • Set the parent position to the new position + the above offset

For example:

Vector3 finalPos = ... // Position I want both s1 and c1 to share

// Cylinder: world offset, moving from c1 to the parent object
Vector3 cylOffset = cylinder.transform.position - c1.transform.position;

// Position the cylinder, and apply the offset
cylinder.transform.position = finalPos + cylOffset;

// Sphere: world offset, moving from s1 to the parent object
Vector3 sphereOffset = sphere.transform.position - s1.transform.position;

// Position the sphere, and apply the offset
sphere.transform.position = finalPos + sphereOffset;

Upvotes: 1

user3277468
user3277468

Reputation: 141

The answer to this is to do

cyclinder.transform.position = s1.transform.position - (c1.transform.localposition/4);

Upvotes: 0

Related Questions