Home > Net >  Adding forward raycast and find angle between two raycast of different gameobjects?
Adding forward raycast and find angle between two raycast of different gameobjects?

Time:06-21

I want to add forward Raycast to my game objects (g1,g2,g3) in order to print navigation directions (left, right, front, back) based on the angle between them at runtime. Example, if angle between camera and g1 is 0-90 (right), 90-180 (left). I don't know the proper coding skills to write this code so it would be much appreciated. Thanks, below is what I have my written code so far.

public GameObject target;
public GameObject start; 
public GameObject checkpoint1; 
public GameObject checkpoint2; 
public GameObject checkpoint3; 
int raylength = 10;

 void Update()
 {
     ObjectRays();
     DrawRays();
 }
 public void ObjectRays()
 {
     var ray1 = new Ray(target.transform.position, target.transform.forward);
     var ray2 = new Ray(checkpoint1.transform.position, checkpoint1.transform.forward);
     var ray3 = new Ray(checkpoint2.transform.position, checkpoint2.transform.forward);
     var ray4 = new Ray(checkpoint3.transform.position, checkpoint3.transform.forward);
     Physics.Raycast(target.transform.position, Vector3.forward, 25.0f);
     RaycastHit hit;
     
 }
 public void DrawRays()
 {
     Debug.DrawRay(target.transform.position, target.transform.forward * raylength, Color.green, 0.5f);
 }

CodePudding user response:

To solve the problem, first set all your sensors in an array to access and control them systematically. In the code below, after defining a dictionary with the key: RayObject and Value: RaycastHit, you can even access RaycastHits separately by input their game-objects.

public GameObject[] rayObjects; // setup all sensors here

public LayerMask layer; // ray detection layer
public float rayLength; // ray length

public void ObjectRays()
{
    var HitDictionary = new Dictionary<GameObject, RaycastHit>();
    
    foreach (var rayObject in rayObjects)
    {
        var ray = new Ray(rayObject.transform.position, rayObject.transform.forward);
        
        Physics.Raycast(ray, out var hit, rayLength, layer.value);
        
        Debug.DrawRay(ray.origin, ray.direction*rayLength);
        
        HitDictionary.Add(rayObject, hit);
    }

    Debug.Log(HitDictionary[rayObjects[0]].transform.name); // this is a way to find the hits
}

CodePudding user response:

Use Vector3.Angle:

Vector3 targetDir = checkpoint1.position - transform.position;
float angle = Vector3.Angle(targetDir, transform.forward);
  • Related