Search code examples
c#visual-studiounity-game-enginepositionmirror

How can I mirror a gameobject movement in Unity?


I have two gameobjects and I want them to be placed butt on butt just like in the picture, but I want them to move and rotate together so that they will always be placed like that. I am controlling the black object so I just usedtransform.rotation = Quaternion.Euler(0, 0, player.transform.eulerAngles.z + 180); in order to get the right rotation, but I just can't get the position right. Here is a sketch of how I want them to be placed.Visual explanation of the positions

When moving my black object in a direction, the two gameobjects do not remain attached. Here is a representation of the problem.Problem

Here you have my exact script and photo: Script that I use for moving the ai:

transform.position = player.transform.position + new Vector3(0, player.transform.localScale.y + transform.localScale.y - 1, 0); transform.rotation = Quaternion.Euler(0, 0, player.transform.eulerAngles.z + 180); transform.parent = player.transform;

And the exact photo in the Inspector:enter image description here

And this is how I want them to be placed at all the time:https://bugguide.net/images/cache/SL2/ZZL/SL2ZZLPZMLOH6HHRUHRREHVH7HVHZLWZLL6Z7H6Z8H5Z7HEZ5LEZ5H8ZSLAHRL2Z4LBZ7LAZILAZXLGZKL2ZMHAHMH.jpg

[UPDATE] I used @Ali Kanat 's answer and I'm halfway there:Update As you can see in the picture the two bugs are now one over the other but they are moving together as they should.


Solution

  • You can just make red object(or any other objects you have) a child of black object and rotate black object. This way you can preserve the geometry and you do not have to modify transformcomponent of the other objects.

    After the comments i am assuming the big lady bug is the Player. To achieve what you want programmatically can be like this:

    //forward, up or right depends on which direction is the front of your player
    transform.position = player.transform.position + ((-player.transform.forward) * (player.transform.localScale.y
            + transform.localScale.y)/2);
    transform.forward = (-player.transform.forward);
    

    Because what you want to achieve is to find the position which is (PlayersizeY + enemySizeY) away in direction of back of the Player. This will work no matter what your Player`s orientation is.