using UnityEngine;
using System.Collections;

[RequireComponent (typeof(MeshFilter))]
public class Bend : MonoBehaviour {
	
	private Vector3[] original;
	private Mesh mesh;
	
	public float force = 0.0f;

	void Start() {		
		MeshFilter mfilter = GetComponent(typeof(MeshFilter)) as MeshFilter;
		mesh = mfilter.mesh;
		original = mesh.vertices;
	}

	void Update() {	
		if(force == 0.0f) {
			mesh.vertices = original;
			mesh.RecalculateNormals();
			return;
		}
		
		Vector3[] vs = mesh.vertices;
		int vc = vs.Length;
			
		float radius = 1 / force;

		for (int i = 0; i < vc; i++) {
			Vector3 v = copy(original[i]);
			
			float l = v.z;
			float d = v.x;

			float fa = (Mathf.PI / 2) + (force * l);
			
			float op = Mathf.Sin(fa) * (radius + d);
			float ow = Mathf.Cos(fa) * (radius + d);

			vs[i].z = -ow;
			vs[i].x = op - radius; 
		}
		
		mesh.vertices = vs;
		mesh.RecalculateNormals();
	}
	
	private Vector3 copy(Vector3 orig) {
		return new Vector3(orig.x, orig.y, orig.z);
	}
}