Advertisement
Guest User

Smooth movement

a guest
Oct 18th, 2020
1,467
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.26 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. // @kurtdekker
  6.  
  7. public class SmoothMovement : MonoBehaviour
  8. {
  9.     float currentQuantity;
  10.     float desiredQuantity;
  11.  
  12.     const float MovementPerSecond = 2.0f;
  13.  
  14.     void Start ()
  15.     {
  16.         // TODO: set up your initial values, if any
  17.         currentQuantity = 1;
  18.  
  19.         // match desired
  20.         desiredQuantity = currentQuantity;
  21.     }
  22.  
  23.     void AcceptUserInput()
  24.     {
  25.         if (Input.GetKeyDown( KeyCode.Alpha1))
  26.         {
  27.             desiredQuantity = 1;
  28.         }
  29.         if (Input.GetKeyDown( KeyCode.Alpha2))
  30.         {
  31.             desiredQuantity = 2;
  32.         }
  33.         if (Input.GetKeyDown( KeyCode.Alpha3))
  34.         {
  35.             desiredQuantity = 3;
  36.         }
  37.     }
  38.  
  39.     void ProcessMovement()
  40.     {
  41.         // Every frame without exception move the currentQuantity
  42.         // towards the desiredQuantity, by the movement rate:
  43.         currentQuantity = Mathf.MoveTowards(
  44.             currentQuantity,
  45.             desiredQuantity,
  46.             MovementPerSecond * Time.deltaTime);
  47.     }
  48.  
  49.     public UnityEngine.UI.Text TextOutput;
  50.     void DisplayResults()
  51.     {
  52.         TextOutput.text = "Press 1, 2 or 3 to select desiredQuantity.\n\n" +
  53.             "desiredQuantity = " + desiredQuantity + "\n" +
  54.             "currentQuantity = " + currentQuantity + "\n";
  55.     }
  56.  
  57.     void Update ()
  58.     {
  59.         AcceptUserInput();
  60.  
  61.         ProcessMovement();
  62.  
  63.         DisplayResults();
  64.     }
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement