今回は↓の動画のように、現実での直方体とUnity上の直方体の動きをリンクさせました。

 動作環境
  • Windows10
  • Unity 2018.4.31f1 Personal
  • Visual Studio Community 2019 16.8.4
  • Arduino1.8.10

手順
①前回の状態を再現する
 今回は、前回(http://blog.livedoor.jp/chisato_tofu/archives/26199124.html)の発展形なので前回の状態を再現できていることを前提とします。

②センサーを作る
 今回用いたセンサーは可変抵抗を直方体のxyz軸に配置し、その値を角度(°)に変換しUnityに送っています。そのため今回は、三軸に可変抵抗を配置する構造をFusion360で設計し3Dプリンタで制作しています。↓の図のようなモデルをFusion360で作り、赤円の場所に可変抵抗を配置します。
a
 これを3Dプリンターで印刷し組み立て配線を行い下のような状態にしました。
IMG_3008

②Arduinoのコードを書く
 前回のコードを発展させる形で3つのデータを送れるようにします。Unity側で","区切りで読み取ることができるため、データの切れ目に","を挿入して送ります。
  1. int val1;
  2. int val2;
  3. int val3;

  4. void setup() {
  5.   Serial.begin(115200) ;
  6. }

  7. void loop() {
  8.   val1 = analogRead(0);
  9.   val2 = analogRead(1);
  10.   val3 = analogRead(2);

  11.   val1 = map(val1, 880, 160, -90, 90);
  12.   val2 = map(val2, 840, 145, 0, -180);
  13.   val3 = map(val3, 873, 176, -90, 90);

  14.   Serial.print(val1);
  15.   Serial.print(",");
  16.   Serial.print(val2);
  17.   Serial.print(",");
  18.   Serial.println(val3);
  19.   delay(50) ;
  20. }
③C#のコードを書く
 シリアル入力を","で区切りそれぞれをcubeの角度に対応させるようなプログラムを書きました。これを"SerialCube"というC#のファイルに格納しています。
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;

  5. public class SerialCube : MonoBehaviour{

  6. public SerialHandler serialHandler;
  7. public Text text;
  8. public GameObject Cube1;

  9. void Start(){
  10. serialHandler.OnDataReceived += OnDataReceived;
  11. }

  12. void Update(){
  13. }

  14. void OnDataReceived(string message){
  15. try{
  16. string[] angles = message.Split(',');
  17. text.text = "x:" + angles[0] + "\n" + "y:" + angles[1] + "\n" + "z:" + angles[2] + "\n"; 

  18. Vector3 angle = new Vector3(float.Parse(angles[1]), float.Parse(angles[0]), float.Parse(angles[2]));
  19. Cube1.transform.rotation = Quaternion.Euler(angle);
  20. }
  21. catch (System.Exception e){
  22. Debug.LogWarning(e.Message);
  23. }
  24. }
  25. }
④C#とCubeの対応
 ③で書いたコードをCubeに対応させていきます。
 まず、前回と同じように"Hierarchy"->"Creare"->"Create Empty"を行い、"SerialCube"という空オブジェクトを作成し、③で書いたコードをドラッグ&ドロップし対応させておきます。
 "Hierarchy"->"Create"->"3D Object"->"Cube"で直方体を作成し、↓の画像のように"inspector"で調整します。今回は上から二項目目の"Rotation"をシリアル通信で変えていきます。
スクリーンショット 2021-02-05 141526
 作成したCubeに③で作ったファイルをドラッグアンドドロップして関連付けを行います。そうしたら↓の画像のように"Inspector"->Serial Cube (Script)の項目を設定します。
スクリーンショット 2021-02-05 142023

④実行する
 Arduinoにプログラムを書き込み実行させると動作します。
スクリーンショット 2021-02-05 142218