using UnityEngine;
using System.Collections;

public class ClickRepulseObjects : MonoBehaviour
{
    public float MinForce;    // Força da distância maxima
    public float MaxForce;    // Força da distância minima
    public float MinDistance; // distancia até a qual a força é max
    public float MaxDistance; // distancia a partir da qual a força é min
    public float XForcePercentage;
    public AudioClip[] startSounds;

    private AudioSource audioSource;
    private Rigidbody2D rb;
    // Use this for initialization
    void Start()
    {
        audioSource = GetComponent<AudioSource>();
        rb = GetComponent<Rigidbody2D>();
    }
    public void useForce()
    {
        rb.AddForce(calculateForce());
    }

    Vector2 calculateForce()
    {
        Vector2 mouse = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        float distance = Vector2.Distance(rb.position, mouse);
        if (distance < MaxDistance)
        {
            if (distance < MaxDistance / 2)
            {
                rb.velocity = new Vector3(0, 0, 0);
            }
            else
            {
                rb.velocity = new Vector3(rb.velocity.x / 2, rb.velocity.y / 2, 0);
            }
        }
        float angle = Mathf.Atan2(rb.position.y - mouse.y, rb.position.x - mouse.x);//Mathf.Deg2Rad * Vector2.Angle(mousepos, rb.position);
        float percentage = (Mathf.Max(MinDistance, Mathf.Min(MaxDistance, distance)) / MaxDistance);
        return new Vector2((MaxForce - percentage * (MaxForce - MinForce)) * Mathf.Cos(angle) * XForcePercentage, (MaxForce - percentage * (MaxForce - MinForce)) * Mathf.Sin(angle));
    }
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.name == "SoundTrigger")
        {
            audioSource.PlayOneShot(startSounds[Random.Range((int)0, startSounds.Length)]);
        }
        else
        {
            //audioSource.PlayOneShot(deathSound);
            Destroy(gameObject);
        }
    }
};