Tuesday, July 25, 2017

unity - How to get the closest "visible" object from my "player"?


I'm using Unity 3d and i have to accomplish the following task: get the closest "visible" object to my player in forward direction.



It is a sort of radar.


I don't know where to start. Any advice is welcomed.


Thanks



Answer



Assuming that you're making a 3D game, you can use Physics.OverlapSphere to get a an array of Colliders that are within a certain range of the player. To check if the object is "visible" to the player, you could simply call Physics.Raycast in the direction of the object(s) returned by OverlapSphere and check if nothing that isn't the object you're checking for blocks the raycast. Here's a code example:


public class RadarController : MonoBehaviour
{
public int RadarRadius;
public string DetectableObjectTag;


public void CheckForVisibleObjects()
{
Collider[] objectColliders = Physics.SphereOverlap(this.transform.position, this.RadarRadius);
for(int index = 0; index <= objectColliders.Length - 1; index++)
{
GameObject colliderObject = objectColliders[index].gameObject;
if(colliderObject.tag == this.DetectableObjectTag)
{
RaycastHit hit;
bool hitOccurred = Physics.Raycast(this.transform.position, colliderObject.transform.position.normalized, out hit);

if(hitOccurred && hit.gameObject.tag == this.DetectableObjectTag)
{
// Do whatever you need to do with the resulting information
// here if the condition succeeds.
}
}
}
}

public void Update()

{
this.CheckForVisibleObjects();
}
}

Disclaimer: I am not able to check and see if this code works properly, or if it performs at an ideal rate. If there is an issue, just mention it and I'll see what I can do.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...