using UnityEngine;
using System.Collections;

public class YoyoController : MonoBehaviour {
    public GameObject yoyo;
    private HingeJoint joint;
    private Rigidbody body;
    private Vector3 initialTransform;
    private float initialAnchorY;
    private AudioSource audioSource;

    void Start() {
        joint = GetComponent<HingeJoint>();
        body = GetComponent<Rigidbody>();
        audioSource = GetComponents<AudioSource>()[1];
        initialTransform = transform.localPosition;
        initialAnchorY = joint.anchor.y;
    }

    void FixedUpdate() {
        float vSpeed = Input.GetAxis("Vertical");
        if (vSpeed < 0) {
            if (!audioSource.isPlaying) {
                audioSource.Play();
            }
            initialTransform = transform.localPosition;
            transform.localPosition -= transform.TransformDirection(Vector3.down) * vSpeed * 2.6f;
            float distance = Vector3.Distance(transform.localPosition, initialTransform);
            joint.anchor = new Vector3(joint.anchor.x, initialAnchorY + distance, joint.anchor.z);
        } else {
            body.velocity = Vector3.zero;
            body.angularVelocity = Vector3.zero;
        }
        yoyo.SetActive(vSpeed < 0);
    }
}
