How to check against another position?

So what I’m looking for is something along the lines of:
If transform.position x-1 is colliding with “Ground” layer, then Grounded = true;

I don’t want it to be an actual collision, just to check if the space next to an object is of a specific layer. C# please.

Have a look at the Unity standard asset first person controller, I believe there’s a grounded check in there.

1 Like

Raycasting from the object in question straight down (against a specific layer) and measuring the distance feels like the most appropriate way to do what you want given your aversion to collisions.

However, it’s still far better to use a collider for the ground and then use OnCollisionEnter to check the impact point for having a “normal” y value that’s positive (facing at least slightly upwards) and then setting isGrounded to true until OnCollisionExit is called. There should be no need to check it every frame when the physics engine already does it for you.

1 Like
  if ((transform.position.y < 1) && (transform.position.y > transform.lossyScale.y/2f ))
        { 
            //if it is, send ray down in world space and at Grounded layer mask for distance 1  
            //if ray meets up something at Ground layer returns true
            if (Physics.Raycast(gameObject.transform.position, gameObject.transform.up * -1, 1f, groundLayer)) 
            {
                grounded = true;
            }
            else
            {
                grounded = false;
            }
        }

Here’s my solution, if you prefer to raycast. With

(transform.position.y > transform.lossyScale.y/2f )

you will check if your object is actually touching the ground already. lossyScale is object’s scale in world and by halving it we get the bottom (assuming the pivot point is in middle of object). If your object falls on side, code won’t return true, since it’s bottom sticks to the side. Also it rotates a bit and sticks up from a corner, code might start spamming between true and false like mad.

1 Like

Alright I finally broke down and used the Raycast. Yet another step towards completion of my game. Thanks everybody :slight_smile: