Using raycasting to make a character NOT move off a platform

I’ve got this. The Debug.DrawLine() correctly draws the line, but the actual raycast appears to be behaving differently than the Line.

// This shoots a ray forward and down to make sure that the character is not going to fall down a level.
// Returns true if there is ground below in fron of the character
function testGround()
{
	var hit : RaycastHit;
	Debug.DrawRay(transform.position + Vector3.up, transform.forward - (Vector3.up * 1.5), Color.yellow);
	if(Physics.Raycast(transform.position + Vector3.up, transform.forward - (Vector3.up), 1.5))
	{
		grounded = true;
	}

}

Basically, my characters using this script are always setting themselves as grounded or not grounded, regardless of what terrain they are approaching.

I’m pretty sure it has something to do with my Physics.Raycast line, but hat has been one of the biggest stumbling blocks for me in learning.

Any help is appreciated!

edit used Vector3.up for both casts. Got rid of unsused hitInfo.

You draw a totally different ray than what you use for the actual raycasting,

First you use Vector3.up when drawing the ray and transform.up when you do the raycast. In most cases they should be the same (unless you tilt your character), however it makes no sense to use two different vectors.

Next thing is the drawray call draws the ray at an angle of around 56° while your raycast casts at 45° downwards.

Ok, just simplify the calculations by assuming our character isn’t rotated. So it’s forward vector points towards the world’s z-axis (0,0,1)

when you calculate this:

    transform.forward - (Vector3.up)  // or this transform.forward - (transform.up)

You end up with a vector like this:

    (0,0,1) - (0,1,0) = (0,-1,1)

since it’s a direction vector it would get normalized internally to a length of 1. So internally Unity will use:

    (0,-0.707,0.707)

this vector points at 45° downwards since the amount on the forward axis is equal to the amount on the y axis.
However when you calculate:

    transform.forward - (Vector3.up * 1.5)

You actually calculate this:

    (0,0,1) - ((0,1,0) * 1.5) == (0,0,1) - (0,1.5,0) == (0,-1.5,1)

This vector points more downwards than forward so the angle is greater. If you normalize the vector (length is ~1.8027) you get (0,0.8320,0.5547). The ASin of the y value will give you the angle:

    ASin(0.707) == 45°
    ASin(0.8320) == 56.309°

If you want the exact same vector for both, the drawing and the raycast, you should normalize the vector manually and then scale it with your desired length (in your case 1.5):

    var dir = transform.forward - Vector3.up;
    dir = dir.normalized;
    Debug.DrawRay(transform.position + Vector3.up, dir * 1.5, Color.yellow);
    if(Physics.Raycast(transform.position + Vector3.up, dir, 1.5))