Advertisement
salahzar

MuoviPiattaforma.cs

Aug 17th, 2019
439
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5.  
  6. public class MuoviPiattaforma : MonoBehaviour
  7. {
  8.  
  9.     // destinations / targets
  10.     public Transform[] targets;
  11.  
  12.     // speed
  13.     public float speed = 1;
  14.  
  15.     // flag that sets whether we are moving or not
  16.     bool isMoving = false;
  17.  
  18.     // next destination index
  19.     int nextIndex;
  20.  
  21.     // Use this for initialization
  22.     void Start()
  23.     {
  24.         // set the player to the first target
  25.         transform.position = targets[0].position;
  26.  
  27.         // next destination is 1
  28.         nextIndex = 1;
  29.     }
  30.  
  31.     // Update is called once per frame
  32.     void Update()
  33.     {
  34.         // Check for input
  35.         HandleInput();
  36.  
  37.         // Move our platform
  38.         HandleMovement();
  39.  
  40.     }
  41.  
  42.     void HandleInput()
  43.     {
  44.         //check for Fire1 axis
  45.         if (Input.GetButtonDown("Fire1"))
  46.         {
  47.             // negate isMoving
  48.             isMoving = !isMoving;
  49.         }
  50.     }
  51.  
  52.     // take care of movement
  53.     void HandleMovement()
  54.     {
  55.         // if we are not moving, exit
  56.         if (!isMoving) return;
  57.  
  58.         // calculate the distance from target
  59.         float distance = Vector3.Distance(transform.position, targets[nextIndex].position);
  60.  
  61.         // have we arrived?
  62.         if (distance > 0)
  63.         {
  64.  
  65.             // calculate how much we need to move (step) d = v * t
  66.             float step = speed * Time.deltaTime;
  67.  
  68.             // move by that step
  69.             transform.position = Vector3.MoveTowards(transform.position, targets[nextIndex].position, step);
  70.         }
  71.         // if we have arrived we should update nextIndex
  72.         else
  73.         {
  74.             // next index is increased by 1
  75.             nextIndex++;
  76.  
  77.             // array element index starts at 0 and goes all the way to length-1
  78.             if (nextIndex == targets.Length)
  79.             {
  80.                 nextIndex = 0;
  81.             }
  82.  
  83.  
  84.             //stop moving
  85.             isMoving = false;
  86.         }
  87.     }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement