Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Move : MonoBehaviour {
- public float speed = 4;
- public float pathResolution = .05f;
- public float turnSpeed = 6;
- Path v;
- Vector2[] points;
- int iOld;
- int i;
- bool reverseDirection;
- void Start () {
- v = FindObjectOfType<PathCreator>().path;
- points = v.CalculateEvenlySpacedPoints(pathResolution);
- transform.position = points[i];
- i = 1;
- }
- void Update () {
- MoveStep(Time.deltaTime * speed);
- if (Input.GetKeyDown(KeyCode.Space))
- {
- ReverseDirection();
- }
- }
- void ReverseDirection()
- {
- reverseDirection = !reverseDirection;
- int t = i;
- i = iOld;
- iOld = t;
- }
- void MoveStep(float dst)
- {
- Vector2 targetPos = points[i];
- Vector2 offset =points[i] - (Vector2)transform.position;
- float dstToTarget = offset.magnitude;
- Vector2 dirToTarget = offset.normalized;
- Quaternion currentRot = transform.rotation;
- transform.right = dirToTarget;
- Quaternion targetRot = transform.rotation;
- transform.rotation = Quaternion.Slerp(currentRot, targetRot, Time.deltaTime * turnSpeed);
- float dstToMove = Mathf.Min(dst, dstToTarget);
- transform.Translate(dirToTarget * dstToMove, Space.World);
- if (dstToMove == dstToTarget)
- {
- iOld = i;
- i = (points.Length + i + ((reverseDirection) ? -1 : 1)) % points.Length;
- }
- float dstRemaining = dst - dstToMove;
- if (dstRemaining > .001)
- {
- MoveStep(dstRemaining);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment