Child Object position relative to direction of Parent

Hey, new Unity user here…

I’m making a 2D game and have a FaceMarker child object for the player which sits in front of the direction he’s facing. This is for checking whats in front of the player that he can interact with etc.

The player isn’t rotating, it’s more of an isometric RPG style view. So if he’s looking right, it’ll sit a tile to his right, if left, tile to his left and so on.

I’m, struggling to get code working for it. Tried this (for left/right) but it’s kicking out errors. Not sure of the correct way to handle it;

if(rbody.velocity.x > 0) {
    GameObject.Find("FaceMarker").transform.position.x = new Vector2 (transform.position.x + 1, transform.position.y);
    }

if(rbody.velocity.x < 0) {
    GameObject.Find("FaceMarker").transform.position.x = new Vector2 (transform.position.x - 1, transform.position.y);
    }

Any tips?

A little more information would be great, but lets try to help anyway :slight_smile:

First of all, I suppose you are using a rigidbody2D which you declared and got as component with GetComponent<> and called it rbody.

Second, you shouldn’t use GameObject.Find like that, it consumes lot of resources and should be referenced as soon as you find it. One simple solution should be declaring a GameObject variable in the parent’s script and drag the child into it in the editor. With this you will have access to it just by calling the variable.

After that, if the object is a child, you dont need to set it’s position whenever you detect the velocity of the parent, as it will move locally everytime it moves. What you should do is use GetKeyDown to detect the key pressed and set it locally only once, something like this:

// The variable for the child object
public GameObject child;

if (Input.GetKeyDown(KeyCode.RightArrow))
  child.transform.position = new Vector2(transform.position.x + 1, transform.position.y);

if (Input.GetKeyDown(KeyCode.LeftArrow))
  child.transform.position = new Vector2(transform.position.x + -1, transform.position.y);

Try it like that and tell us the results :slight_smile:

Good Luck