Hi guys,
I’m trying to make a function that scans around an object using rays at a given number of rays per cycle, or granularity. If the ray does not return with a hit, I want to feed this into a list that refreshes every frame (Others have suggested I use lists for this purpose over arrays).
I then want to sort the list based on the dot product with the players position (the best match being the one with the largest dot product, i.e closest to one, ray with direction nearest to parallel to player position).
I then want to return the ray’s direction for the frame in question.
At the moment, the following code doesn’t seem to see anything in the list although the step seems to be updating correctly; I find this hard to believe as my Raycast distance is set very small. Can anyone see why this isn’t working?
Cheers,
Popuppirate
private System.Collections.Generic.List<Ray> free_rays;
private System.Collections.Generic.List<RaycastHit> free_rays_info;
private int granularity=100;
public float step;
public float safe_zone;
public Vector3 step_target;
// Use this for initialization
void Start () {
step = 0;
safe_zone = 0.1f;
free_rays = new System.Collections.Generic.List<Ray>();
}
// Update is called once per frame
void Update () {
GameObject player=GameObject.FindGameObjectWithTag ("Player");
if (step<=360){
for (int i=0; i<granularity; i++) {
Vector3 scan = Quaternion.AngleAxis (step, transform.forward) * transform.forward;//MAKE NEW VECTOR STEP DEGREES FROM TRANSFORM.FORWARDS
Ray ray = new Ray (transform.position, scan);//MAKE RAY IN THIS DIRECTION
RaycastHit hit;
if (Physics.Raycast(ray, out hit, safe_zone)){
continue;
} else {//IF DIDN'T HIT READ INTO FREE_RAYS
free_rays.Add(ray);
}
step+=(360f/(granularity*1.0f));
}
free_rays.Sort (delegate (Ray ray1, Ray ray2) {
return Vector3.Dot (ray1.direction, player.transform.position).CompareTo (Vector3.Dot(ray1.direction, player.transform.position));
});//SORT BASED ON DOT PRODUCT
Vector3 step_target= free_rays[free_rays.Count-1].direction; //RETURN LARGEST DOT PRODUCT (CLOSEST TO 1).
} else {
free_rays.Clear(); //ON END OF CYCLE, CLEAR LIST AND RESET STEP.
step=0;
}
}
}