Solved problem with multiple leveled scenario

I wanted to share this with whoever has/had this issue.

My scenario has several parts. There is a “cliff”, things pass over it and stuff. So while doing this part of the series I found a problem with that. The thing is, when you raycast through several objects of the same kind, it sometimes decided to prioritize parts of the level that were occluded.

image

Let’s suppose that red box to the left is my camera and the arrow is my raycast. When I raycasted, probably due to how RaycastAll stores the elements hit, it was picking the last element corresponding to my layer. It should ended picking up the hit where the arrow ends. But instead, it picked something else towards the end of the raycast.

So yeah, I went and did some tinkering with the CameraRaycast, and this seemed to work. Specifically at the FindTopPriorityHit method.

	RaycastHit? FindTopPriorityHit (RaycastHit[] raycastHits) {
		// Form list of layer numbers hit
		List<int> layersOfHitColliders = new List<int> ();
		foreach (RaycastHit hit in raycastHits) {
			layersOfHitColliders.Add (hit.collider.gameObject.layer);
		}
// Edit starts here.
		// Step through layers in order of priority looking for a gameobject with that layer
		foreach (int layer in layerPriorities) {
            RaycastHit? selectedHit = null;
			foreach (RaycastHit hit in raycastHits) {
				if (hit.collider.gameObject.layer == layer) {
                    //return hit; // stop looking
                    // 
                    if (!selectedHit.HasValue || hit.distance < selectedHit.Value.distance) selectedHit = hit;
				}
			}
            if (selectedHit.HasValue) return selectedHit;
		}
// And ends here.
		return null; // because cannot use GameObject? nullable
	}

Basically all I did was to cycle through the rest of elements, just checking which hit element is the closest to the raycasting object (i.e. the camera). That ensures it gets what the player clicked, not the first whatever thing it gets since it seems to not be ordered by what we need. It might work just walk through the array in reverse. But just to be sure… did it like this.

Hopefully this helps someone.

Privacy & Terms