Search Unity

Detecting the ground with raycasting

Discussion in 'Scripting' started by Legit Tactical, Feb 1, 2015.

  1. Legit Tactical

    Legit Tactical

    Joined:
    Sep 22, 2013
    Posts:
    27
    Hi, I'm currently working on a platformer and I wanted to detect the ground using raycasts for jumping

    This is the code I wrote in order to do that.

    Code (CSharp):
    1.     private float distToGround;
    2.  
    3.     void Start()
    4.     {
    5.         distToGround = collider.bounds.extents.y;
    6.     }
    7.  
    8.     bool isGrounded ()
    9.     {
    10.         return Physics.Raycast(transform.position, -Vector3.up, distToGround + 0.1);
    11.     }
    12.  


    I thought that this would work but I get these errors.


    error CS1502: The best overloaded method match for `UnityEngine.Physics.Raycast(UnityEngine.Vector3, UnityEngine.Vector3, float)' has some invalid arguments


    error CS1503: Argument `#3' cannot convert `double' expression to type `float'


    These may have fairly simple solutions but I've been trying to fix the problem for 30 minutes and whenever Id o it always seems to add more errors.

    I would greatly appreciate some assistance.
     
  2. Yemachu

    Yemachu

    Joined:
    Feb 1, 2015
    Posts:
    13
    You are adding a double to "distToGround", resulting in a double as parameter. There however is no overload for physics.Raycast that accepts a double as one of its arguments.

    Solution:
    Code (CSharp):
    1. bool isGrounded()
    2. {
    3.         return Physics.Raycast(transform.position, -Vector3.up,  distToGround + 0.1f);
    4. }
    Notice the 'f' at the end of the line. This makes the double a float.
     
    Legit Tactical likes this.
  3. Legit Tactical

    Legit Tactical

    Joined:
    Sep 22, 2013
    Posts:
    27

    Oh wow, thank you. I can't believe I didn't notice something so simple. Then again, I suppose it happens to everyone.

    Thank you very much.
     
  4. Nubz

    Nubz

    Joined:
    Sep 22, 2012
    Posts:
    553
    More than a lot of us would like to admit.
     
    Legit Tactical likes this.
  5. Yemachu

    Yemachu

    Joined:
    Feb 1, 2015
    Posts:
    13
    These types of issues tend to be easy to overlook, and they occur far more often than I'd like (granted I rather don't have them occur at all). Fortunatly they are rather easy to solve when you spot them...

    In any case, glad I could be of help.
     
  6. Legit Tactical

    Legit Tactical

    Joined:
    Sep 22, 2013
    Posts:
    27
    Thanks again.