Vector3.Angle Help

Hello, So I have a tank “3D”, and I want it to “Shoot” only when the Cannon is Facing the target. Now I am using Vectir3.Angle, and it seems to work but its not perfect. because I am only Interested in the Horizontal Angle Not the Vertical, nor an average of the two. Please help me solve this. I am a total noob here. Thank you in advance!


Vector3 dir = target.position - transform.position;
float angle = Vector3.Angle(dir, transform.forward);

if (angle < angleValueToStartFire)
{
if (fireCountdown <= 0f)
{
Shoot();
fireCountdown = 1f / fireRate;
}
fireCountdown -= Time.deltaTime;
}

You can make a new Vector3, set it to transform.forward, and then set the Y of both that and “dir” to 0.

thank you,

How would I go about doing this part " and then set the Y of both that and “dir” to 0."

Sorry, tottal noob here

on another note, I use “transform.forward”, doesnt that automatically make y=0?

No, though Y will be 0 if your object isn’t tilted up or down.

It would look like:

Vector3 dir = target.position - transform.position;
dir.y = 0f;
Vector3 fwd = transform.forward;
fwd.y = 0f;
float angle = Vector3.Angle(dir, fwd);
1 Like

Love you! it worked