Script for a gentle 'bobbing' motion, similar to thrusters trying to remain at stationary position in mid-air

Hi,

I was wondering if anyone can recommend any scripts that achieve this kind of motion?

Thanks

Try creating two positions on the Y axis, and then moving between them smoothly. Here is a simple example I can give you, experiment around and modify it how you wish. Just to test, attach this script to a sphere in your scene, and it should “hover”.

var pos1 : Vector3;

var pos2 : Vector3;

var offset : Vector3;

var moveSpeed : float = 0.05;

var moveTo;

function Start()

{

offset = Vector3.down;

pos1 = transform.position;

pos2 = transform.position + offset; 

}

function Update()

{

if(transform.position == pos1)

{

	moveTo = pos2;

}

if(transform.position == pos2)

{

	moveTo = pos1;

}



transform.position = Vector3.MoveTowards(transform.position, moveTo, moveSpeed);

}

That worked beautifully thank you! I needed it for my hover board script haha. Now my question is, how do I change the distance it “bobs” at? I only want it to happen slightly.

Here is Clunk’s (the top answer to this question) script converted to C#. And Yes, it works great.


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ShipBobbing : MonoBehaviour
{
    Vector3 bobFrom;
    Vector3 bobTo;
    Vector3 offset = new Vector3(0,1.5f);
    float moveSpeed = 0.0008f;
    Vector3 bobbingDestination;

    // Start is called before the first frame update
    void Start()
    {
        offset = Vector3.down;
        bobFrom = transform.position;
        bobTo = transform.position + offset;
    }

    // Update is called once per frame
    void Update()
    {
        if (transform.position == bobFrom)
        {
            bobbingDestination = bobTo;
        }
        if (transform.position == bobTo)
        {
            bobbingDestination = bobFrom;
        }

        transform.position = Vector3.MoveTowards(transform.position, bobbingDestination, moveSpeed);
    }
}