主旨:
使用PC跟Arduino版製作互動小遊戲,玩法是利用麥克風聲控來關閉遊戲內物件,請看影片https://www.youtube.com/watch?v=aFHmrqDpOZ0
作法:
硬體方面將組裝好的麥克風硬體透過USB 與PC 連結
原理:
筆者這裡用的port是COM4,下面列出Arduino與unity互相溝通的API
再來附上
Arduino內所需要的程式
int micVal = 0; // 麥克風音量值
void setup() {
Serial.begin(57600);
}
void loop() {
micVal = analogRead(micPin);
if (micVal > 500) { // 如果音量大於 500 ...
Serial.println(micVal);//如果使用Serial.print, Unity會收不到
delay(1000);
}
}
在來是Unity內唯一腳本作用是收到Arduino訊號後立刻關閉CUDE
using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System;
public class Unity_Arduino : MonoBehaviour
{
public GameObject mSmoke;//就是cube
SerialPort sp = new SerialPort("COM4", 57600);
float m;
void Start()
{
sp.Open();
sp.ReadTimeout =1;
}
void FixedUpdate()
{
if (sp.IsOpen)
{
try //要是unity沒有跟上Arduino的Println 的話,ReadLine會LAG
{
string value = sp.ReadLine();
if (value != "")
{
//float.TryParse(sp.ReadLine(), out m); //將資料轉成float
Debug.Log("value="+ value);
mSmoke.SetActive(false);
}
}
catch (TimeoutException)
{
//Debug.Log("error="+ errorpiece);
}
}
}
}
留言列表