- Home /
Spawn an object?
Hello, this is a simple question, but how would I spawn an object at a certain velocity and position (relative to another object). Like a bullet firing from ship for a 2D shooter? Thanks.
Your bullet (or whatever you want to 'instantiate') should be a 'Child' or 'Sub-Object' of your GameObject 'Ship' (or w/e na$$anonymous$$g convention you chose).
This would make it very easy to get the bullet firing "FRO$$anonymous$$" the ship. A little fiddling around and you should have it in the position that you desire.
what if he moves the ship? wouldnt the bullet move with the ship? thats bad I think.
Answer by zannghast · Nov 05, 2010 at 06:53 AM
Further to lampshade's answer, here is an example of how you can use instantiate and the sort of firing mechanism you may want to look into:
// make sure that the ammo is where it's supposed to be GameObject ammoClone = (GameObject)Instantiate(ammo, startPointTransform.position);
// "firing" effect. The last parameter, ForceMode.VelocityChnage, is crucial in mimicking the initial velocity of a 'fired' object such as a cannonball or bullet. ammoClone.rigidbody.AddRelativeForce(startPointTransform.forward * BlastForce, ForceMode.VelocityChange);
The above code, is a snippet. It assumes the following conditions:
- ammo is a reference to the object acting as the ammo.
- The ammo object has a rigidbody component attached to it.
- startPointTransform is a reference to the Transform of the object acting as the origin or start point of the ammo object
- BlastForce is a float which you could control to adjust the initial force applied to the ammo
Note that this is in C#, not JS. It also doesn't add a velocity relative to the other object. To do that you'd have to first set the velocity to equal the other object and then add the force.
Answer by lampshade · Nov 05, 2010 at 06:23 AM
To Bring something into existance? Instantiate! http://unity3d.com/support/documentation/ScriptReference/Object.Instantiate.html
Your answer
Follow this Question
Related Questions
dragging out an object from mouse click? 1 Answer
Help! Can't destroy my bullet object because is a rigidbody 1 Answer
cube damage 2 Answers
Updating prefab information live 2 Answers
Spawn object with different material. 0 Answers