Skip to content

Instantly share code, notes, and snippets.

@alvaropinot
Last active May 30, 2025 22:05
Show Gist options
  • Select an option

  • Save alvaropinot/dd592fbfe5921d7fdb751329a609cb0a to your computer and use it in GitHub Desktop.

Select an option

Save alvaropinot/dd592fbfe5921d7fdb751329a609cb0a to your computer and use it in GitHub Desktop.
Making Objects Float Up & Down in Unity

From http://www.donovankeith.com/2016/05/making-objects-float-up-down-in-unity/

Making Objects Float Up & Down in Unity

by admin · May 6, 2016 Ever wanted to make an object float up and down while spinning in Unity? Well, I’ve written a script for that.

End Result of Script

FloatingAndSpinningCubeinUnity

Usage

  1. Select an object in your Unity project.
  2. Add Component > New Script
  • Name: Floater
  • Language: C-Sharp
  1. Edit the script
  2. Copy & Paste the code below into your script editor.
  3. Save the script.
  4. Tweak settings to your heart’s content

image

// Floater v0.0.2
// by Donovan Keith
//
// [MIT License](https://opensource.org/licenses/MIT)
using UnityEngine;
using System.Collections;
// Makes objects float up & down while gently spinning.
public class Floater : MonoBehaviour {
// User Inputs
public float degreesPerSecond = 15.0f;
public float amplitude = 0.5f;
public float frequency = 1f;
// Position Storage Variables
Vector3 posOffset = new Vector3 ();
Vector3 tempPos = new Vector3 ();
// Use this for initialization
void Start () {
// Store the starting position & rotation of the object
posOffset = transform.position;
}
// Update is called once per frame
void Update () {
// Spin object around Y-Axis
transform.Rotate(new Vector3(0f, Time.deltaTime * degreesPerSecond, 0f), Space.World);
// Float up/down with a Sin()
tempPos = posOffset;
tempPos.y += Mathf.Sin (Time.fixedTime * Mathf.PI * frequency) * amplitude;
transform.position = tempPos;
}
}
@alvaropinot
Copy link
Copy Markdown
Author

alvaropinot commented Sep 6, 2020

FloatingAndSpinningCubeinUnity

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment