I have a GameObject that rotates itself and has 4 guns that are children, I created the empty GameObject at the end of every gun and I would like to instantiate the bullet prefab the way the gun is rotated and give them force to go to that direction
Here is how the game looks: Imgur: The magic of the Internet
And this is my script to spawn, but don’t know how to give force:
public GameObject bullet;
public Transform gun;
public float time;
void Spawn()
{
Instantiate(bullet, transform.position, gun.transform.rotation);
}
void Start()
{
Invoke("Spawn", time);
}
You need to change bullet’s position in Update(). For example you could do this:
Change your instantiate code:
//Make an array to store all instantiated bullets.
// we'll need this to move each bullet in it's own direction later
private ArrayList bullets = new ArrayList ();
private void Spawn()
{
//Store instantiated bullet as local variable 'clone'
GameObject clone = Instantiate (bullet, transform.position, gun.transform.rotation);
//Add bullet to the list
bullets.Add (clone);
//Call delayed method to delete bullet which is first in the bullets array
// we need it to prevent performance issues when there's too much bullets in the scene
// so we're adding 1 new bullet and deleting 1 old bullet
Invoke ("DestroyBullet", 2f); //bullet will be destroyed in 2 seconds
}
private void DestroyBullet ()
{
GameObject bulletToDestroy = bullets[0] as GameObject; //very first bullet in the array
bullets.RemoveAt (0); //remove bullet from the array
Destroy (bulletToDestroy); //destroy bullet's gameObject itself
}
Now in Update() you’ll change each bullet’s position:
void Update ()
{
//Moving every bullet in the array relative to it's position and direction
for (int i = 0; i < bullets.Count; i++) {
GameObject bullet = bullets *as GameObject;*
bullet.transform.position =*
bullet.transform.position + bullet.transform.forward * Time.deltaTime; //Time.deltaTime here //is a multiplier for move speed. Now bullet will move for 1 meter per second. } }