Reputation: 51
I have an object and a player. How do I make it so that the object is always in front of the player, no matter what position the player is at?
Hey guys thanks for your replies! Just to add that the object spawns at a random position, then I have made it move towards the player (this is why I haven't made it a child of the player). From then it will always stay in front of the player.
Upvotes: 2
Views: 1395
Reputation: 7605
You can set that object to be a child of the player
GameObject childPlacehoderObj; // Set this to the child you want to give a home
GameObject playerObj; // This will be the parent
childPlacehoderObj.transform.parent = playerObj.transform;
Now the child will move along with the parent.
Update: object spawns at a random position, then I have made it move towards the player
What you can do then, is to create an empty object which will be the final position of that object. And this empty object you make it a child of the player.
Then what you do is to make the object, one it is spawned, to move to the position of that empty object. You can add something like this in the object which should be in front of the player
void Update()
{
// Move our position a step closer to the target.
float step = speed * Time.deltaTime; // calculate distance to move
transform.position = Vector3.MoveTowards(transform.position, childPlacehoderObj.position, step);
}
Finally once the object reaches the target point, you can make it child of the player.
Upvotes: 3
Reputation: 136
Maybe you could just set the player as parent of the Object. Like this the Object would define it's Position after the Position of the Player and after it is once infront of the Player it would always stay there no matter his postition.
Upvotes: 1