Search Unity

[SOLVED] Move up gameobject from ground ?

Discussion in 'Scripting' started by Quast, Dec 26, 2017.

  1. Quast

    Quast

    Joined:
    Jul 5, 2015
    Posts:
    504
    Hi
    I'm trying to make an object stay on air and keep his distance from ground. but with my script it just keep going up. for example, I want gameobject to stay up away from ground 20 meter. it should be away from ground 20 meter. How to do that.
    Code (CSharp):
    1.     public Transform target;
    2.     public Rigidbody rb;
    3.     public float up_from_hero;
    4.  
    5.     void Update() {
    6.         up_from_hero = gameObject.transform.position.y - target.transform.position.y;
    7.         rb.velocity = transform.up * 15 * Time.deltaTime;
    8.  
    9.     } // end update
    10.  
    11.     void FixedUpdate() {
    12.             RaycastHit hit;
    13.         if (Physics.Raycast(transform.position, -Vector3.up, out hit, 200.0f)) {
    14.                 print(" distance: " + hit.distance);
    15.         }
    16.  
    17.     }
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    You could turn off gravity in the rigidbody using the editor.
     
  3. Quast

    Quast

    Joined:
    Jul 5, 2015
    Posts:
    504
    Yes, I know, but how to stop it at 20 meter ?
     
  4. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    Well, you are doing a distance check, so just stop the velocity when the distance equals 20.
     
  5. Quast

    Quast

    Joined:
    Jul 5, 2015
    Posts:
    504
    OK, I do what you said. but it doesn't stop !! I don't know why ?
    Code (CSharp):
    1.         if (distance <= 5) {
    2.             rb.velocity = transform.up * 30 * Time.deltaTime;
    3.         }
    4.         else {
    5.             // stop or do nothing
    6.         }
    7. //  on fixedupdate distance =  hit.distance
    8.  
     
  6. Hikiko66

    Hikiko66

    Joined:
    May 5, 2013
    Posts:
    1,021
    You have to set the velocity back to nothing if you want it to stop.

    Code (csharp):
    1.         else {           rb.velocity = transform.up * 0 * Time.deltaTime;        }
    2.  
     
    Last edited: Dec 26, 2017
  7. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    a simpler way is
    Code (csharp):
    1.  
    2. rb.velocity = transform.zero;
    3.  
     
  8. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,713
    Vector3.zero
    :)
     
  9. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    Yeah, that's it. I'm hopeless without Visual Studio. :eek:
     
    TaleOf4Gamers likes this.
  10. Quast

    Quast

    Joined:
    Jul 5, 2015
    Posts:
    504
    Great. thank you guys :)
     
unityunity