﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class MovingPlatform : MonoBehaviour
{
    public Vector3 goal;
    public float speed = 5;
    public float smoothTime = 0.2f;
    [Range(0,1)]
    public float startingPoint;

    Vector3 velocity;
    Vector3 startPosition;
    Vector3 endPosition;
    Rigidbody rb;
    bool flip = false;
    

    private void Start()
    {
        rb = GetComponent<Rigidbody>();
        startPosition = transform.position;
        endPosition = transform.position + goal;

        transform.position = Vector3.Lerp(startPosition, endPosition, startingPoint);
    }
    
    void FixedUpdate()
    {
        //perform movements only in the Physics update loop
        Move(Time.fixedDeltaTime);
    }

    void Move(float deltaTime)
    {
        //breaking these out into a and b for legibility
        Vector3 a = rb.position;
        Vector3 b = flip ? startPosition : endPosition;

        //more readability
        Vector3 pos = Vector3.SmoothDamp(a, b, ref velocity, smoothTime, speed, deltaTime);

        //this is incredibly important for Kinematic Rigidbodies.  If you dont use this, the RB wont have velocity.
        rb.MovePosition(pos);


        //Go the other way.
        if (pos == endPosition || pos == startPosition)
        {
            flip = !flip;
        }
    }

    
    private void OnDrawGizmos()
    {
        if(Application.isPlaying)
            Gizmos.DrawLine(startPosition, endPosition);
        else
        {
            Gizmos.DrawLine(transform.position, transform.position + goal);
            Gizmos.DrawWireSphere(Vector3.Lerp(transform.position, transform.position + goal, startingPoint), 0.1f);
        }
            
    }
}
