How to make a ball float / hover

I have created a floor and a sphere and am trying to get the ball to hover (about 1.6meters) above the ground. The ball will need to have a rigidbody though and be subjected to gravity (in certain cases). I cant seem to replicate the slight “hover” effect for the ball where it goes up and down slightly.

I have seen a few other examples but either cant get them to work as they were in javascript and as much as i have tried i cant get them to work, or they are unpredictable and don’t give the results i desired.

C# examples only please. Many thanks.

Hi Somarl

It sounds like you want the ball to Oscillate

You can achieve this motion in Unity by doing something like this:

using UnityEngine;
using System.Collections;

public class Example : MonoBehaviour
    void Update()
        this.transform.position = Vector3.up * Mathf.Cos(Time.time);

I believe capitalizing the “c” in Mathf.cos would solve the recognition issue.

However, then you’ll probably run into the issue I did: operator “+” cannot be appluied to operands of type Vector3 and float. Alas, no solution to this at the moment, but someone on here must know a way around this!

Take a look at this video tutorial. It is for floating on water, but remember that the water does not really exist and therefore it is exactly the same as floating on air(with the water plane render disabled) :

His code is short and works perfectly. You can adjust the water height value to make your sphere float at various heights. You can add a coroutine to add a regular slight adjustment to this for an extra bobbing effect.