So I want to make a dynamic AI enemy using ray casting in a two dimensional platformer game. The objective is to have it detect whether it is at the edge of a platform so that it can turn around. If it worked I could just plop down the enemy anywhere on a platform and would not have to set up a bunch of triggers which can be slow. The only thing is that the physics.raycast is returning falsely. When there is no platform it still returns true, as if it is hitting the platform. I even made a debug.drawray to check that the numbers were right. Here is the code.
function DropCheck () {
drop.start = transform.position + drop.offset;
var forwards = transform.TransformDirection(drop.angleForward);
var back = transform.TransformDirection(drop.angleBackward);
Debug.DrawRay (drop.start,forwards*drop.lenght,Color.blue);
if(!Physics.Raycast(drop.start,forwards,drop.lenght)){
Debug.Log("No ground");
}
Debug.DrawRay (drop.start,back*drop.lenght,Color.blue);
if(Physics.Raycast(drop.start,back,drop.lenght)){
Debug.Log("Ground");
}
else{
Debug.Log("no ground");
}
}
The drop.angleForward is a Vector3(1, -1, 0),
and drop.angleBackward is a Vector3(-1,-1,0).
For my tests a length of 2 intersects the platform and returns as true, which is what I want.
The drop.offset was to test in playmode whether changing the origin would work.
Perhaps I just not understanding how ray casting really works. I’m imagining it as a single line through the 3D space, though here it is acting, well not quite sure, more like a plane?