Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. // Author: CoffeeStraw
  2.  
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6.  
  7. public class TrainMovement : MonoBehaviour
  8. {
  9. [SerializeField]
  10. Vector3[] path;
  11.  
  12. [SerializeField]
  13. float percentsPerSecond = 0.2f; // Una sorta di velocità: l'oggetto percorrerà 2% del path ogni secondo
  14.  
  15. [SerializeField]
  16. float currentPathPercent = 0.0f; // Posizione iniziale
  17.  
  18. // Costanti calcolate all'avvio del gioco
  19. float pathVelocity;
  20. float pathLength = 0;
  21.  
  22. // Abilitazione della preview del percorso nell'editor
  23. private void OnDrawGizmos()
  24. {
  25. iTween.DrawPath(path);
  26. }
  27.  
  28. // Calcolo delle costanti
  29. private void Start()
  30. {
  31. pathLength = iTween.PathLength(path);
  32. pathVelocity = pathLength * percentsPerSecond;
  33. }
  34.  
  35. // Calcolo della posizione ad ogni frame
  36. private void Update()
  37. {
  38. // Calcolo del movimento in maniera che si muova a velocità lineare anche sulle curve
  39. float deltaPercent = percentsPerSecond * Time.deltaTime;
  40. Vector3 nextPoint = iTween.PointOnPath(path, currentPathPercent + deltaPercent);
  41. float calcDist = Vector3.Magnitude(nextPoint - transform.position);
  42. float calcVelocity = calcDist / Time.deltaTime;
  43. float velocityScale = pathVelocity / calcVelocity;
  44.  
  45. currentPathPercent += (deltaPercent * velocityScale);
  46.  
  47. // Appena ha finito il percorso, ricomincia da capo
  48. if (currentPathPercent > 1.0f)
  49. currentPathPercent -= 1.0f;
  50. else if (currentPathPercent < 0)
  51. currentPathPercent += 1.0f;
  52.  
  53. // Posizionamento dell'oggetto nel punto calcolato, lasciando calcolare l'orientamento alla libreria iTween
  54. Vector3 pos = iTween.PointOnPath(path, currentPathPercent);
  55. Hashtable hash = iTween.Hash(
  56. "position", pos,
  57. "orienttopath", true);
  58. iTween.MoveUpdate(this.gameObject, hash);
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement