How would I instantiate three projectiles all at different directions relative to mouse position?

Hi, so I found a script that allows me to instantiate a projectile object that aims toward mouse position. However I want to modify it to instantiate three projectiles, one directly toward mouse position and two more from the same starting point but with one being at an increase of angle and one being at a decrease. You can think of it like this.

Normal Projectile: –
/
New Projectile —
\

I have the script that I’m currently using attached below.

using UnityEngine;

public class SwordShot : MonoBehaviour
{
    public GameObject bullet;
    public Transform firePoint;
    public float bulletSpeed = 50;
    Vector2 lookDirection;
    Vector2 lookDirection2;
    float lookAngle;
    public Camera cam;
    public float shootCD;
    public float timeSinceLastShot;
    void Update()
    {
        lookDirection = cam.ScreenToWorldPoint(Input.mousePosition);
        lookDirection2 = new Vector2(lookDirection.x - transform.position.x, lookDirection.y - transform.position.y);
        lookAngle = Mathf.Atan2(lookDirection2.y, lookDirection2.x) * Mathf.Rad2Deg;

        firePoint.rotation = Quaternion.Euler(0, 0, lookAngle);

        if (Input.GetKeyDown(KeyCode.F) && timeSinceLastShot <= 0)
        {
            timeSinceLastShot = shootCD;
            GameObject bulletClone = Instantiate(bullet);
            bulletClone.transform.position = firePoint.position;
            bulletClone.transform.rotation = Quaternion.Euler(0, 0, lookAngle - 90);
            bulletClone.GetComponent<Rigidbody2D>().velocity = firePoint.right * bulletSpeed;
            Destroy(bulletClone, .71f);
        }

        if (timeSinceLastShot > 0)
        {
            timeSinceLastShot -= Time.deltaTime;
        }
    }
}

Welcome! You will need to use some vector math to do it… but guess what? Unity’s API makes it SUPER simple to do.

If you have a vector velocity such as this term you are presently using:

firePoint.right * bulletSpeed

then you can rotate it by multiplying it by a Quaternion.

Let’s just put it in a temp var first:

Vector3 velocity = firePoint.right * bulletSpeed;

Then make one +10 and -25 degrees left / right:

Vector3 vel1 = Quaternion.Euler( 0, 0, +10) * velocity;
Vector3 vel2 = Quaternion.Euler( 0, 0, -25) * velocity;

The degrees goes in the third argument to the Quaternion.Euler() factory because you are in 2D, which means +Z (the third argument) is the axis around which you wish to rotate.

1 Like

First I want to thank you for the welcome! Also, you made this whole process the furthest from a headache that it could have been. Exactly as you said is as I did and it works flawlessly, I have attached my latest upload of the project if you’d like to give your handiwork a shot, and again, thank you.

https://thictony.itch.io/sidewaysdarksoulsbutworse

1 Like