Firing rays in a cone shape from the player

Although some of my code seems to work, I am getting some unexpected results.

I have a for loop in which I create a new ray each time in a specific direction - which is where the problem lies. I want to trace a cone shape from the player in its forward direction. However, while the rays are cast in a circle or cone shape, the width or angle of this cone changes as the object moves rather than being set to a specific angle.

If I want to trace a cone shape with an angle of 30d from the center, it traces a cone shape centered around 30d, on the x axis in my case, instead. The angle changes as it moves.

How can I make it trace the cone shape specified by my angle around the forward direction?

		//search in circle around center
		float stepAngleDeg = 360 / subdivisions; //angle between two sampled rays
		for (int i = 0; i < subdivisions; i++)
		{
			Vector3 localRotation = new Vector3(angleFromCenter, 0, i * stepAngleDeg); //direction of Ray to cast in Euler XYZ form
			Vector3 direction = (Quaternion.Euler(localRotation) * transform.up).normalized; //turn rotation into direction
			
			Ray ray = new Ray (bulletSpawnPoint.position, direction);
			Debug.DrawLine(ray.origin, ray.origin + (direction * asteroidAvoidDistance), Color.red);
		}

If you want to trace a cone, I would suggest to “construct” your cone as follow :

You know the main axis of your cone, thanks to the transform.forward of your spawn point.

Then, you also have two vectors belonging to the base of your cone : transform.up and transform.right.

48169-cone.png

You have the radius of your cone (I guess) and your step angles (in radians). Thus, you can draw a circle like the Unit Circle Trigonometry : transform.right * cos(angle) * r + transform.up * sin(angle) * r. You now have a set of points, you have the apex of your cone, you can have a vector ! This vector is the direction + length of your ray.

EDIT : If you want your radius, you will have to use the following formula :

You know that tan α = opposite / adjacent where α is you angle. You want opposite (you already know adjacent, which is the height of your cone).

Thus, opposite = tan α x adjacent

48170-triangle.png

alt text

Though, I would recommend to use a solid mesh as a trigger to detect a collision from your bullet. (Just make it on a 3D software like blender, it takes 2 minutes, export it in fbx, remove mesh renderer, add mesh collider)

Here’s Unity’s own tutor’s code https://unity3d.com/learn/tutorials/projects/stealth-tutorial-4x-only/enemy-sight

You could have cone shaped collider and check if it’s not behind something with raycast towards target while onCollision with the collider. Unity - Scripting API: Collider.OnCollisionStay(Collision)

I saw several people looking for a ConeCast, so I made one. It’s an extension method to use as Physics.ConeCastAll: