Raycast not taking full length
Hello Unity Community,
yep that was a bad rhyme... anyways. I am currently working on some type of FOV for detecting if something is inside the "View Cone". Firstly I tried to use Triggers with Colliders, but that did not work how I wanted it to be.
Now I am working with Raycasts. I am using a SphereOverlap to detect if anything is inside the possible viewrange, after that I check if the Object is in an specific Angle if so a Message will be sent out, however that is not working as I thought. Because the check if an Object is inside the specific Angle just... takes half or less of the Sight.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ViewScript : MonoBehaviour
{
public float radius; // Distance of Sight
public LayerMask mask; // A Layermask for Raycasting
public float curAngle; // Current Field of View Angle
// Update which gets called every Frame
private void Update()
{
// Creates a Sphere at the Position of the Object, with an radius and a specific Layermask
Collider[] hits = Physics.OverlapSphere(transform.position, radius, mask);
// If there are any Objects in Sphere
if(hits.Length != 0)
{
// For every Object
for(int i = 0; i < hits.Length; i++)
{
// [DEBUGGING]
Debug.Log($"Object in Sphere: {hits[i].gameObject}");
// Draws a Line from Object to Colliding Obj
Debug.DrawLine(transform.position, hits[i].transform.localPosition, Color.red, 1f);
RaycastHit hit;
if(Physics.Raycast(transform.position, hits[i].transform.localPosition, out hit, radius * 2, mask))
{
float temp_rotation = Vector3.Angle(transform.forward * (radius * 2), hit.transform.localPosition);
Debug.Log(temp_rotation);
Debug.DrawRay(hit.transform.localPosition, transform.right, Color.green, 2f);
if(temp_rotation >= 360 - curAngle & temp_rotation <= curAngle)
{
Debug.Log("Just withing the Sight! :) ");
}
}
}
}
}
private void OnDrawGizmos()
{
Gizmos.DrawWireSphere(transform.position, radius);
var line = transform.position + (transform.forward * radius);
var pos_rotatedLine = Quaternion.AngleAxis(curAngle, transform.up) * line;
var neg_rotatedLine = Quaternion.AngleAxis(360 - curAngle, transform.up) * line;
Gizmos.DrawRay(transform.position, pos_rotatedLine);
Gizmos.DrawRay(transform.position, neg_rotatedLine);
}
}
Any Help would be appreciated, cuz I can FEEL I did just some dumb Maths or thoughts. Kind Regards :)
EDIT: Also I just noticed that the smaller the Obj, the smaller the Length of the check gets.
Your answer
Follow this Question
Related Questions
Why is It not casting any Ray? [Scripting Problem] 0 Answers
RayCast issues 0 Answers
RayCasting from a Empty GameObject 1 Answer
Can not get my raycast to detect an object 0 Answers
How to acces rayhit location from a different script 2 Answers