How to get a projectile to go in a specific direction

Hi! I want to know how to make a prefab fire in a certain direction that I can specify!
my line of code looks like this

UnityEngine.Object.Instantiate<GameObject>(
    this.projectile ,
    this.enemy.position ,
    angle_I_want_to_specify
);

I’m also using Unity-2019-4-LTS
Any help would be really appreciated, I’ve been looking for this for a while now

thanks again!

image_2024-01-12_175820050

edit: unity 3D, sorry my bad

fire in directions like so:
image_2024-01-12_194855124
but I want to specify the angles so that I can do others like 45 degrees etc.

4 Answers

4

Now that i’ve seen the update , you can just create an array where you store the rotations and just use them on the spot.

Note : if the reason why you don’t want to create the Quaternions everytime is for “performance” then my advice is to not worry about it and and create your quaternions every time

you can do something like this

private Quaternion GetRotationFromAngle(float angle)
{
     return Quaternion.AngleAxis(angle , Vector3.up);
}

// example of use
{
    Quaternion rot = GetRotationFromAngle(180);

    UnityEngine.Object.Instantiate<GameObject>(
    this.projectile ,
    from.position,
    rot
    );
}

Does this answer your question ?

This should do it (assuming your game is 2D)

Vector3 dir = to.transform.position - from.transform.position;
Quaternion rot = Quaternion.LookDirection(dir , Vector3.up);

UnityEngine.Object.Instantiate<GameObject>(
    this.projectile ,
    from.position,
    rot
);

that’s my bad, i should’ve specified it to be 3d!

another thing is that is there any way to make it so i wont have to create tons of quanternions for other angles?

This should work is 3D as well (well for 90% of the cases). As for the creating thing , you can just "pre-create" the quaterions and cache them somewhere. Maybe i missed what you really was so maybe post more context/examples

–

just updated it with a screenshot that should make things more clear, let me know if i need to make any changes