Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment