Follow another object direction problem


I have two objects in my 2d game.
One (pet) need to follow another object(player) position.
Here is my code

    void Update()
        direction = (player.position - transform.position).normalized;
        transform.Translate(direction * Time.deltaTime * petSpeed);

My problem is pet object direction ( rotation) . When pet is child of player, pet direction works fine(rotate as player rotate), but when pet is outside player object pet, pet not rotating as player .

I don’t want pet to be child object of Player.

Can some one tell me why direction don’t work when pet is not child of player?


When GameObject is child to an other GameoObject its Transform will use the parent Transform as a reference. It means it will “follow” the changes in the parent Transform (position, rotation, scale).
When object don’t have that relationship then their Transforms are unassosiated unless you influence them via script. Your script only changes the position not rotation.

If you want the pet to face it’s owner then add

Vector3 target2D = player.position; //add if 2D creates issues
target2D.z = 0; //add if 2D creates issues
transform.LookAt(target2D); //you can use player if 2D don't create a problem..

if you want the pet to look the same direction as the owner looks then just set the transform.rotation = player.rotation

Hope you get it working