- Home /
Bullets follow the ship in 2D Space Shooter game
Hello, i have a bullet where when i shoot a bullet and move the ship the bullet shootsforwards but follows on the ship Position to left an right.
Here my scripts:
public class Bullet : MonoBehaviour { public Rigidbody2D Rigidbody; public float Speed; public int Damage; public GameObject ExplosionPrefab;
private void Start()
{
Rigidbody.GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
Rigidbody.AddRelativeForce(Vector2.up * Speed);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Enemy"))
{
var meteoroidController = collision.GetComponent<MeteoridController>();
meteoroidController.TakeDamage(Damage);
Instantiate(ExplosionPrefab, transform.position, Quaternion.identity);
Destroy(gameObject);
}
}
}
public class WeaponSystem : MonoBehaviour { public Transform[] Spawnpoints; public Bullet BulletPrefab; public float FireRate = 1; public AudioSource SoundEffect;
private float _fireRatecounter;
private void Update()
{
_fireRatecounter += Time.deltaTime;
}
public void Fire()
{
if (_fireRatecounter >= FireRate)
{
_fireRatecounter = 0;
SoundEffect.Play();
foreach (var spawnPoint in Spawnpoints)
{
Instantiate(BulletPrefab, spawnPoint);
}
}
}
} thanks for the help
Answer by UnityM0nk3y · Apr 14, 2021 at 11:09 AM
Perhaps try:
Rigidbody.AddForce(Vector2.up * Speed);
Answer by Ermiq · Apr 15, 2021 at 02:30 PM
So, what you do with the bullets is just this:
foreach (Transform spawnPoint in Spawnpoints)
{
Instantiate(BulletPrefab, spawnPoint);
}
In human language: take all the transform objects from the Spawnpoints
list (seems like you have two of them, to the left/right of the ship, and they are attached to the ship probably), create a bullet object and attach it to the spawnpoint object.
Basically it is the same as if you just drag&dropped a bullet onto the spawnpoint in the scene editor. Obviously the bullets will just hang at the given position as children/attachments of the spawnpoint objects and won't fly anywhere.
What you need is to instantiate the bullets without attaching them to anything so they would live on their own as independent objects and then move them to the desired direction.
Remove the parenting argument from the Instantiate (...)
method call. It should be just
Instantiate(BulletPrefab);
or some other overload of the method that doesn't set the newly created object as a child of another object.
To move the bullets you could either use physics engine and apply some force to the bullets rigidbody
component or manipulate the bullets positions directly by setting their transform.position
property in Update()
.
There're tons of tutorials and answers available on YouTube, UnityLearn, StackExchange, etc. on how to do that.