- Home /
Lobbing a Bomb with Instantiate.
It seems like this would be a common task in unity, but I can't seem to find an answer.
I would like to instantiate a Bomb (A prefab with its own properties), from my player, lobbing it forward like tossing a ball.
It has to take in to account the players speed too, though the first thing I feel I need to get down is the fact that it will not instantiate relative to its instantiate point, it is instantiating forward along the world Z axis not the relative z of its spawn point.
Here is the basic code that I cant quite get to work
if(Input.GetButtonDown("Powerup") && hasBomb == true)
{
var spawnBomb = GameObject.Find("shootPoint1").transform.position;
var bomb = Instantiate (bombPrefab,spawnBomb,Quaternion.identity);
bomb.transform.position = spawnBomb;
bomb.rigidbody.AddForce (0, 60, 600);
hasBomb = false;
}
And then, I would need to add the velocity of the player.
Any help is much, much appreciated.
well you could just pretend to be the world axes with an invisible fake object and treat it like some bomb spawning machine.
Epic title/question btw, really sparked my interest :)
Thanks, thats what the spawnBomb variable is for, it finds "shootPoint1" which is an empty game object, of which my player1 is its parent :)
Answer by Jayde · Dec 02, 2010 at 09:57 PM
The problem here is that you're adding a force using a vector in global space rather than in local space of your spawn poin.t You can simply use Transform.TransformDirection to convert a vector from local to global space.
if(Input.GetButtonDown("Powerup") && hasBomb == true)
{
var spawnBomb = GameObject.Find("shootPoint1").transform;
var bomb = Instantiate (bombPrefab,spawnBomb.position,Quaternion.identity);
//It's not necessary to set the position here since you already did in Instantiate
bomb.rigidbody.AddForce (spawnBomb.TransformDirection(0, 60, 600));
hasBomb = false;
}
The only thing I'd add to this is in the line of "var bomb = Instantiate(blah blah); whenever you spawn the bomb, it'd be at it's default rotation, no matter where your character's facing. If you don't want that, change the Quaternion.identity to transform.rotation
Excellent, thank you this has worked well. Can I ask two more things? Would it be easy to add rotation to the bomb? and how do I add the players current velocity to the direction of the bomb? If I am turbo boosting, the bomb will run into my player.
Your answer
Follow this Question
Related Questions
Instantiate a prefab with a key press to a relative location? 1 Answer
instantiating vertically 2 Answers
Brain freeze: declaring a prefab inside the same prefab 1 Answer
How to Add Y Axis Offset to transform.localPosition on an Instantiated Prefab? 2 Answers
Instantiating one prefab with different materials in one frame 0 Answers