Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Help rotating along a GameObject

Discussion in 'Scripting' started by Jeanseb05, Oct 11, 2020.

  1. Jeanseb05

    Jeanseb05

    Joined:
    Feb 29, 2020
    Posts:
    9
    Hi guys, I'm trying to figure out a simple algorithm but I can't find any solution, so any help will be appreciated :)

    So here is my problem. I have a GameObject that follows my player but I want the GameObject to always be on the right side of my player no matter the rotation of it. So I want my GameObject to follow the orientation of my GameObject not word relative.

    So for example here is what my current script is achieving Element.png


    And here is a picture of what is happening with my script element2.png

    And here's what I need Inkedelement2_LI.jpg

    When I rotate the player I need the GameObject to go to the new _destination and face the same place as the player. Ps : the 10f means the distance between the player and the GameObject.



    I have a current script which is part of my Mobs AI.


    Code (CSharp):
    1.  transform.rotation = playerTarget.transform.rotation;
    2.                 _destination = new Vector3(transform.position.x, transform.position.y, playerTarget.transform.position.z); // this give me the rotation along the world orientation
    3.                 transform.position = Vector3.MoveTowards(transform.position, _destination,0.3f);

    Thanks you very much :)
     
    Last edited: Oct 11, 2020
  2. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    How about a emptyObject child on your player,
    and then just tell your following object, to head towards the emptyObject,

    if your player turns right, the object will do exactly what you do (be carefull becouse of collision)
     
    Jeanseb05 likes this.
  3. Jeanseb05

    Jeanseb05

    Joined:
    Feb 29, 2020
    Posts:
    9
    Not a bad idea ! If I can't find a way to do this without an emptyObject I will do this Thanks :)
     
    Terraya likes this.
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,336
    Terraya's idea scales the best, for in the future you might want two minions to follow you, so you want them to take up kind of a "formation" around you.

    But if you desperately want to just NOT use the empty object, you can always use the transform shortcuts for your character and compute the offset in realtime from there. For example:

    Code (csharp):
    1. Vector3 OnMyLeftOneStepBehind = transform.position +
    2.     transform.right * -3.0f + transform.forward * -2.0f;
    Regardless of which way you face, that will always be 3 units to your left and 2 units behind you... handy!
     
    Terraya and Jeanseb05 like this.