- Home /
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?
Answer by skovacs1 · Oct 07, 2010 at 07:50 PM
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
- Always move towards the player, whatever their position. Easy
- 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.
- This would be stored in array of Vector3 or of a custom data structure of several points representing bezier curves.
- You would have to add points in some smart way and this is dependent upon your movement system.
- 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.
Thanks - parenting is what I wanted for the bullet, so it relatively sticks to the player until fire is released
Your answer
Follow this Question
Related Questions
Make a simple tree 1 Answer
How to flip my Bullet with my Sprite 1 Answer
Calling a function of another object's child? 1 Answer
Trouble accessing child 3 Answers
parenting problem 1 Answer