using UnityEngine;
using System.Collections;

public class Attractor : MonoBehaviour 
{
    float speed = 10f;
    int mode = 1;

	void Update () 
    {
        if (Input.GetKey(KeyCode.A))
        {
            gameObject.transform.position += new Vector3(-speed * Time.deltaTime, 0f, 0f);
        }
        if (Input.GetKey(KeyCode.D))
        {
            gameObject.transform.position += new Vector3(speed * Time.deltaTime, 0f, 0f);
        }
        if (Input.GetKey(KeyCode.W))
        {
            gameObject.transform.position += new Vector3(0, speed * Time.deltaTime, 0f);
        }
        if (Input.GetKey(KeyCode.S))
        {
            gameObject.transform.position += new Vector3(0f, -speed * Time.deltaTime, 0f);
        }

        if (Input.GetKey(KeyCode.Alpha1)) mode = 0;
        if (Input.GetKey(KeyCode.Alpha2)) mode = 1;
	}

    void OnTriggerStay(Collider other)
    {
        if (other == null) return;

        Particle obj = other.gameObject.GetComponent<Particle>();

        if (obj == null) return;
       
        // attract
        if(mode == 0)
        {
            Vector3 attractPt = gameObject.transform.localPosition;
            obj.frc = attractPt - other.gameObject.transform.localPosition;
		    obj.frc.Normalize(); 

            other.rigidbody.velocity *= obj.drag; //apply drag
            other.rigidbody.velocity += obj.frc * 1.1f; //apply force
        }
        else
        {
             // repel
            Vector3 attractPt = gameObject.transform.localPosition;
		    obj.frc = attractPt - other.gameObject.transform.localPosition;
            obj.frc.Normalize(); 
		    
            float dist = Vector3.Distance(attractPt, other.gameObject.transform.localPosition);

            other.rigidbody.velocity *= obj.drag; 
		    if( dist < 150 ){
                other.rigidbody.velocity += -obj.frc * 1.6f;
		    }else{		
                obj.frc.x = Mathf.PerlinNoise(obj.uniqueVal, other.gameObject.transform.position.y * 0.01f);
			    obj.frc.y = Mathf.PerlinNoise(obj.uniqueVal, other.gameObject.transform.position.x * 0.01f);
			    other.rigidbody.velocity += obj.frc * 0.04f;
		    }
        }
    } 
}
