Skip to content

Instantly share code, notes, and snippets.

@kurtdekker
Last active September 11, 2023 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurtdekker/fb3c33ec6911a1d9bfcb23e9f62adac4 to your computer and use it in GitHub Desktop.
Save kurtdekker/fb3c33ec6911a1d9bfcb23e9f62adac4 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// @kurtdekker
//
// This is to take any continuous quantity and change it from one value
// to another over time. This code is for floats. It can be adapted to work for:
//
// Vector2, Vector3, Vector3
// Quaternion
// double
// Color
//
// ... pretty much any quantity that you want to gradually change over time.
//
// All you do is set the desiredQuantity, nothing else.
//
// The currentQuantity will be moved to the desiredQuantity.
//
// You would use the currentQuantity as the smoothly-moving value.
//
// See here for a full example runnable Unity3D package:
// https://forum.unity.com/threads/beginner-need-help-with-smoothdamp.988959/#post-6430100
public class SmoothMovement : MonoBehaviour
{
float currentQuantity;
float desiredQuantity;
const float MovementPerSecond = 2.0f;
void Start ()
{
// TODO: set up your initial values, if any
currentQuantity = 1;
// match desired
desiredQuantity = currentQuantity;
}
void AcceptUserInput()
{
if (Input.GetKeyDown( KeyCode.Alpha1))
{
desiredQuantity = 1;
}
if (Input.GetKeyDown( KeyCode.Alpha2))
{
desiredQuantity = 2;
}
if (Input.GetKeyDown( KeyCode.Alpha3))
{
desiredQuantity = 3;
}
}
// THIS IS THE MAGIC SAUCE: smoothly move currentQuantity to desiredQuantity:
void ProcessMovement()
{
// Every frame without exception move the currentQuantity
// towards the desiredQuantity, by the movement rate:
currentQuantity = Mathf.MoveTowards(
currentQuantity,
desiredQuantity,
MovementPerSecond * Time.deltaTime);
// Note: use Mathf.MoveTowardsAngle() if the quantity is in degrees
}
public UnityEngine.UI.Text TextOutput;
void DisplayResults()
{
TextOutput.text = "Press 1, 2 or 3 to select desiredQuantity.\n\n" +
"desiredQuantity = " + desiredQuantity + "\n" +
"currentQuantity = " + currentQuantity + "\n";
}
void Update ()
{
AcceptUserInput();
ProcessMovement();
DisplayResults();
}
}
@heinzer456
Copy link

me gusto

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