I made a plane that can shoot bullets, but they always shoot in one direction. By that I mean when I rotate the plane it keeps shooting the bullets in the same direction. Here is my code for the bullet scripts.
This script spawns the bullet
using UnityEngine;
using System.Collections;
public class BulletProjectile : MonoBehaviour {
public GameObject spawnPosObj;
public GameObject Bullet;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(Bullet, spawnPosObj.transform.position, Quaternion.identity);
}
}
}
This script tells the bullet what to do when it spawns
using UnityEngine;
using System.Collections;
public class BulletScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.Translate(transform.forward * 50 * Time.deltaTime);
}
}
1 Answer
1
First off, try formatting your question better so it’s easier to understand. With the code snippets out of place it can be confusing.
The fact you use Quaternion.identity when instantiating means each instantiated bullet’s rotation is set to (0, 0, 0). Therefore, all bullets you instantiate face the same direction. Since you are having each bullet move by it’s transform.forward direction, and each bullet is facing the same direction, each bullet will move in the same direction. Make sense?
One way to make the bullet’s travel direction more realistic would be to tell each individual bullet which direction the plane is facing at the moment of instantiation.
Here’s how it could be done:
First, the BulletScript:
public Vector3 travelDirection;
void Update()
{
transform.Translate(travelDirection * 50 * Time.deltaTime);
}
See how the bullet translates by a travel direction instead of it’s transform.forward? The travel direction variable is empty but it will be assigned when the bullet is instantiated.
Now, the BulletProjectile:
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
GameObject bullet = (GameObject)Instantiate(Bullet, spawnPosObj.transform.position, Quaternion.identity);
bullet.GetComponent<BulletScript>().travelDirection = PlaneObject.transform.forward;
}
}
This may not be the best solution in your case, or the most efficient. But hopefully it will give you an understanding of how to accomplish things like this on your own in the future. Bye.
Thank you for your feedback but in this line of code: bullet.GetComponent().travelDirection = PlaneObject.transform.forward; plane object does not exist. Do you want me to create another gameObject with that name?
– Philosophbot