Unity-Uniduinoの値を計算

ワークショップで作ったスクリプトその4くらい


using UnityEngine;
using System.Collections;
using Uniduino; //aruduino tukau nara hitsu you

public class analog_test : MonoBehaviour {// haifun wa tsukae nai no?


	public Arduino arduino;//
	
	public int pin = 0;//?
	public int pinValue;//pin level get
	public int yValue;
	public int zValue;

	public int pinValueX;
	public int pinValueY;
	public int pinValueZ;
	

	public float spinSpeed;//kaiten sokudo
	public GameObject rotBone;//add my bone here

	public double rotZ = 0;

//ここあらネットで拾ったスクリプト組み合わせ大会
	ArrayList pinValueListX = new ArrayList();
	ArrayList pinValueListY = new ArrayList();
	ArrayList pinValueListZ = new ArrayList();
	// smoothing回数 多いほど滑らか
	int SMOOTHING_LENGTH = 20; 
	

	void Start () {//初期化など
		
		arduino = Arduino.global;
		arduino.Log = (s) => Debug.Log("Arduino: " +s);//log dakara huyou?
		arduino.Setup(ConfigurePins); //call ConfigurePins function
		
		//cube = GameObject.Find("Cube");

	}
	
	void ConfigurePins( )
	{
		//arduino.pinMode(pin, PinMode.ANALOG); //
		//arduino.reportAnalog(pin, 1); //pin number 1 is enable(1)
		arduino.pinMode(0, PinMode.ANALOG); 
		arduino.reportAnalog(0, 1);
		arduino.pinMode(1, PinMode.ANALOG); 
		arduino.reportAnalog(1, 1);
		arduino.pinMode(2, PinMode.ANALOG); 
		arduino.reportAnalog(2, 1);
	//	spinSpeed = 0.1;
	}



	
	void Update () {

		//以下も追加

		updatePinValueList (
			arduino.analogRead (0),
			arduino.analogRead (1),
			arduino.analogRead (2)
			);


		pinValueX = getSmoothedValue (pinValueListX);
		pinValueY = getSmoothedValue (pinValueListY);
		pinValueZ = getSmoothedValue (pinValueListZ);
		///追加

		double degX = Mathf.Atan2(pinValueX - 536, pinValueZ - 500) / 3.14159 * 180.0 ;//角度を加速度から
		double degY = Mathf.Atan2(pinValueY - 530, pinValueZ - 500) / 3.14159 * 180.0 ;//climb
		//double degZ = Mathf.Atan2(pinValueZ - 500, pinValueX - 533) / 3.14159 * 180.0 ;//角度を加速度から
		double degZ = Mathf.Atan2(pinValueZ - 500, pinValueY - 530) / 3.14159 * 180.0 ;//角度を加速度から

		if(degX > 1)
		{
			rotZ = rotZ - (degX * 0.01);
		}if(degX < -1){
			rotZ = rotZ - (degX * 0.01);
		};
	}


	void updatePinValueList(int x, int y, int z){
		if (pinValueListX.Count > SMOOTHING_LENGTH) {
			pinValueListX.RemoveAt(0);	
		}
		if (pinValueListY.Count > SMOOTHING_LENGTH) {
			pinValueListY.RemoveAt(0);	
		}
		if (pinValueListZ.Count > SMOOTHING_LENGTH) {
			pinValueListZ.RemoveAt(0);	
		}
		// smoothingしたの値
		pinValueListX.Add (x);
		pinValueListY.Add (y);
		pinValueListZ.Add (z);
	}
	
	int getSmoothedValue(ArrayList list){
		if (list.Count < SMOOTHING_LENGTH) {
			return 0;
		}
		
		int sum = 0;
		for (int i=0; i<list.Count; i++){
			sum += (int)list[i];
		}
		return (int)(sum / SMOOTHING_LENGTH);
	}

}