Search Unity

How to check against another position?

Discussion in 'Scripting' started by Gerald Tyler, Jul 31, 2015.

  1. Gerald Tyler

    Gerald Tyler

    Joined:
    Jul 10, 2015
    Posts:
    80
    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.
     
  2. Fantastic Worlds Studio

    Fantastic Worlds Studio

    Joined:
    Apr 26, 2015
    Posts:
    48
    Have a look at the Unity standard asset first person controller, I believe there's a grounded check in there.
     
    Gerald Tyler likes this.
  3. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    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.
     
    Gerald Tyler likes this.
  4. Rokkimies

    Rokkimies

    Joined:
    May 18, 2015
    Posts:
    12
    Code (CSharp):
    1.  
    2.   if ((transform.position.y < 1) && (transform.position.y > transform.lossyScale.y/2f ))
    3.         {
    4.             //if it is, send ray down in world space and at Grounded layer mask for distance 1  
    5.             //if ray meets up something at Ground layer returns true
    6.             if (Physics.Raycast(gameObject.transform.position, gameObject.transform.up * -1, 1f, groundLayer))
    7.             {
    8.                 grounded = true;
    9.             }
    10.             else
    11.             {
    12.                 grounded = false;
    13.             }
    14.         }
    15.  
    16.  
    Here's my solution, if you prefer to raycast. With
    Code (CSharp):
    1.  
    2. (transform.position.y > transform.lossyScale.y/2f )
    3.  
    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.
     
    Gerald Tyler likes this.
  5. Gerald Tyler

    Gerald Tyler

    Joined:
    Jul 10, 2015
    Posts:
    80
    Alright I finally broke down and used the Raycast. Yet another step towards completion of my game. Thanks everybody :)