Parabola shooting

How to instantiate a bullet and shoot it so that it makes an arc?

Making a prefab

First, we need to make a prefab. My prefab will be made out of pumpkin graphic downloaded from pixabay.com.

This is a 2D example, so when I dragged and dropped a graphic file on the scene, sprite renderer component has been attached automatically.

I added Circle Collider 2D and Rigidbody 2D on top of it. In the Rigidbody 2D component I changed the mass to 4 and gravity scale to 2. It’s not obligatory but affects the way the prefab is shot and I liked it more.

Creating the script

I created a script named Shoot and added the code as seen below:

public class Shoot : MonoBehaviour
{
    Rigidbody2D rb;
    float speed;
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        speed = 20f;
        Shooter();
        Destroy(gameObject, 2.0f);
    }

    void Shooter()
    {
        rb.AddForce(new Vector2(2.4f * speed, 1.6f * speed), ForceMode2D.Impulse);
    }
}

I added the script to the pumpkin object and made a prefab out of it by dragging it to the Project tab.

In the code above I added the reference to the Rigidbody 2D component so that we can use it in the Shooter() method. I created speed variable to quickly adapt the speed of the bullet.

Just after that I called Shooter() method to add the force to the object. Destroy() method is added to destroy the object after 2 seconds. We don’t want to keep unnecessary objects in the scene, those pumpkin bullets once shot will drop out of the screen so we won’t need them anymore.

Shooting a pumpkin

Once the prefab is ready it’s time to start shooting. I added a ghost to the scene and added some code so that I can instantiate the prefab, like so:

    [SerializeField] GameObject prefabBullet;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Shoot();
        }
    }

    void Shoot()
    {
        GameObject bullet = Instantiate(prefabBullet, transform.position, transform.rotation);
    }

In the Update() method we check if the spacebar key is pressed. If it is then void Shoot() function is called. In Shoot() function we instantiate the prefab in the same location and rotation as the gameObject to which the script is attached to.

At the very end prefab reference should be attached to the script where the prefab is instantiated.

Some devs uses public variables for that but some use SerializedField to keep the variable private but still visible in the inspector.

It’s up to you which way you choose but probably SerializedField is a better way of doing it.

Dodaj komentarz

Twój adres email nie zostanie opublikowany.