I’m gathering the Vector2.Distance from ObjectA to ObjectB, then casting a ray2d from ObjectA to ObjectB using that distance to determine if anything is in the way. What’s unusual is that not only is the ray hitting an object(which does not exist) but it’s hitting an object prior to the actual distance between ObjectA and ObjectB.
Below is the code I’m using to better show the situation.
Getting the location to move/cast to
//manually set the mouse position to a vector3
Vector3 mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
//set world destination)
Vector3 worldPosition = Camera.main.ScreenToWorldPoint(mousePosition);
Vector2 flatWorldPosition = new Vector2(worldPosition.x, worldPosition.y);
RoundVector2ToGrid(ref flatWorldPosition);
//after rounding to nearest tile set move destination.
_move.Destination = flatWorldPosition;
//find the best way to reach this destination
FindPath(flatWorldPosition);
Checking for collision using raycast
private void FindPath(Vector2 destination)
{
//this is a test object without a collider that is moved to my Vector2 destination.
//it appears to be placed properly. used for testing
GameObject testObj = GameObject.FindGameObjectWithTag("Finish");
testObj.transform.position = destination;
RaycastHit2D hit;
//get current position of object
Vector2 objectPosition = new Vector2(transform.position.x, transform.position.y);
//starting position of ray and max cast distance
Vector2 rayStart;
float castDistance;
float quickestPath = -1f;
//first check if the object can reach its destination without any way points
rayStart = objectPosition;
//distance between obj and final dest
castDistance = Vector2.Distance(rayStart, destination);
//fire ray
hit = Physics2D.Raycast(rayStart, destination, castDistance);
//if we dont hit anything then its a clean shot to the final destination.
//set move location and get out of method
if (hit.distance == 0)
{
//for some reason hit.distance is always > 0 even with no obstacles in the way.
//hit.distance is < than castDistance
Don’t suppose I’m missing something here?