Making an object follow another object (bullets following a player)

I want to have it so initially a bullet created by pressing/holding fire follows the player, by making it a child of the player parent, then this child/parent is broken when fire is released. How can i do this?

Parenting

Keep in mind that if the player rotates, the child object (your bullet) will rotate in space about the center point of the player.

You can achieve this by creating the object, parenting it and unparenting on release.

The script that fires your bullet

function Fire() {
    //do stuff....like create a bullet and get the player
    bullet.parent = player;
    //...
}

Somewhere else

function Update() {
    if(Input.GetButtonUp("Fire"))
        bullet.parent = null; //if on the bullet, use transform.parent
    if(parent) Something();
    else SomethingElse();
    //do stuff..
}

Other kinds of following

  1. Always move towards the player, whatever their position. Easy
  2. Follow the path that the player went along. Hard

If you're using physics to drive your bullet, that's potentially more complicated and I'd want to see some of your code to offer the best solution to your use case.

Moving towards the player

This is like a magic bullet that turns towards its target. If you want it to avoid walls and go around corners, you will have to add some ray casting and a few extras.

The script that fires your bullet

function Fire() {
    //do stuff....like create a bullet and get the player
    var script : BulletScript = bullet.GetComponent(BulletScript);
    if(script) script.target = player;
    //...
}

BulletScript.js

var target : Transform;
var speed : float = 50.0;

function Update() {
    if(Input.GetButtonUp("Fire")) target = null;
    if(target) transform.LookAt(target.position, transform.up);
    transform.position += speed * Time.deltaTime * transform.forward;
}

Following the player's path

This is like a ghost which will follow along the path the player followed. This requires you store the path the player has followed.

  1. This would be stored in array of Vector3 or of a custom data structure of several points representing bezier curves.
  2. You would have to add points in some smart way and this is dependent upon your movement system.
  3. Make the bullet move along the path by an amount related to its velocity.

Because this is highly dependent upon your movement system both for the player and the bullet, I would need to see your implementation in order to provide a solution.