Search Unity

Float over the ground

Discussion in 'Physics' started by mohsenz, Jul 10, 2019.

  1. mohsenz

    mohsenz

    Joined:
    Aug 10, 2016
    Posts:
    29
    I try to float a rigidbody object in a distance of ground, with Raycast + "AddForce" or "MovePosition" but It's not working well,

    Code (CSharp):
    1.  
    2.     public float Distancevalue;
    3.     public LayerMask Mymask;
    4.  
    5.     void FixedUpdate()
    6.     {
    7.         if (Physics.Raycast(transform.position, Vector3.down, Distancevalue))
    8.         {
    9.             RaycastHit hitInfo;
    10.             Physics.Raycast(transform.position, Vector3.down, out hitInfo, Distancevalue, Mymask.value);
    11.             float correction = Distancevalue - hitInfo.distance;
    12.  
    13.          //   transform.position = new Vector3(transform.position.x, transform.position.y + correction, transform.position.z);
    14.          //   GetComponent<Rigidbody>().AddForce(transform.position.x, transform.position.y + correction, transform.position.z);
    15.             GetComponent<Rigidbody>().MovePosition(new Vector3(transform.position.x, transform.position.y + correction, transform.position.z));
    16.  
    17.         }
    18.     }
    is there something wrong ?

    thanks
     
  2. Deleted User

    Deleted User

    Guest

    You might need to set the rigidbody "Is kinematic" when the object needs to hover and put it back once it no longer needs to hover.
    Code (CSharp):
    1.     private Rigidbody rigidBody;
    2.  
    3.     private void Start()
    4.     {
    5.         rigidBody = GetComponent<Rigidbody>();
    6.     }
    7.  
    8.     private void FixedUpdate()
    9.     {
    10.         rigidBody.isKinematic = true;
    11.     }
    Code (CSharp):
    1.     private Rigidbody rigidBody;
    2.  
    3.     private void Start()
    4.     {
    5.         rigidBody = GetComponent<Rigidbody>();
    6.     }
    7.  
    8.     private void FixedUpdate()
    9.     {
    10.         rigidBody.isKinematic = false;
    11.     }
     
  3. mohsenz

    mohsenz

    Joined:
    Aug 10, 2016
    Posts:
    29
    I need the rigidbody object to float all the time with a specific distance to the ground, but I need to mask some objects on the ground to just fly over them and keep the object distance to the ground.
    did you mean, I should make "isKinematic = false" once the rigidbody detect an object on the bottom?