Hello,
I would like to fire some random rays from a spot light (inside its cone) based on “Spot Angle” and “Range” parameters of the light.
The following code brings me almost there, but when I rotate the spotlight, the rays don’t!
var rndPoint = Random.insideUnitCircle * light.spotAngle;
direction = transform.position + transform.forward + new Vector3(rndPoint.x, rndPoint.y, 0f);
ray = new Ray(transform.position, direction);
Debug.DrawRay(ray.origin, ray.direction * light.range);
Thank you for your precious help!
Here ya go…
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class RandomRays : MonoBehaviour {
void Update () {
for(int i = 0; i<500; i++)
{
Vector3 target = RandomSpotLightCirclePoint(light);
Debug.DrawLine(target, target+Vector3.one*0.01f, Color.red, 0.5f);
}
}
Vector3 RandomSpotLightCirclePoint(Light spot)
{
float radius = Mathf.Tan(Mathf.Deg2Rad*spot.spotAngle/2) * spot.range;
Vector2 circle = Random.insideUnitCircle * radius;
Vector3 target = spot.transform.position + spot.transform.forward*spot.range + spot.transform.rotation*new Vector3(circle.x, circle.y);
return target;
}
}
ok so
spotlight.position + spotlight.forward + random.unitcircle
that gives you a position 1 unit in front and if you just use random.unitcircle it gives you a 30 degree cone basically. This has to do with it being an angle whos max value is the angle of a right triangle whose x and y are both one because .forward is one unit ahead and unit circle is a max radius of one and the angle of a 1 by 1 right angle triangle is 30
if you’d like an angle other than 30 you can modify the random.unitcircle or .forward and multiply it by a determined number
(which would be using sin or cos or whatever and saying ok i have a lenght of 1 an angle of 20 or 30 or 40 or wathever you want and plugging that in to find the length of the other side and multiplying by that number since 1 * any number is itself your all good)
so in that way you can define a max angle for the spotlight and find a point 1 unit ahead of the light within that angle. Now that you’ve done that all thats left is to cast a ray from the spotlight towards the point. you can again because we are using the number 1 you can multiply by 10 for example to get a unit 10 meters away on the line if you want to know the end or you can just cast to infinity by casting towards it.