Search Unity

Keeping a transform position 5 units above ground at all times

Discussion in 'Getting Started' started by CyberInteractiveLLC, Apr 3, 2019.

  1. CyberInteractiveLLC

    CyberInteractiveLLC

    Joined:
    May 23, 2017
    Posts:
    307
    Hi, question as the title says, I'm not exactly looking for a physics hover script with a pid, as I didn't like the result of that especially when the object is moving very fast and the slope of the ground quickly changes or loops (goes upside down).. I want the object to stay "glued" at that height using a simple transform position functions, like:
    Code (CSharp):
    1. transform.position.y = groundPoint(transform.position) + 5.0f;
    suggestions?
     
    Last edited: Apr 3, 2019
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Looks to me like you've pretty much got it; you just need to fill in the groundPoint method. You'd do that by casting a ray down, to intersect with whatever you consider to be "ground".

    Also, you can't just assign to transform.position.y like that. You'd need to do something like:

    Code (csharp):
    1.    Vector3 pos = transform.position;
    2.    pos.y = GroundPoint(pos) + 5;
    3.    transform.position = pos;