大家可以參考這篇文章:Augmented Reality Tutorial No. 15: Augmented Reality using Unity3D, Vuforia and Arduino (part 2)
解開後打開,在Unity工具上打開範例程式,在Assets目錄中點選Edgaras物件,畫面如下:
開啟fire.cs原如檔。程式列表如下:
// Unity code is available to download - link below the video!
using UnityEngine;
using System.Collections;
using System.IO.Ports;
public class fire : MonoBehaviour {
string value;
Vector3 rot;
SerialPort stream = new SerialPort("COM9", 9600); // for Arduino connection
// Use this for initialization
void Start () {
stream.Open();
gameObject.GetComponent().enableEmission = true;
gameObject.GetComponent().emit = true;
//gameObject.GetComponent().duration = 0.1;
gameObject.GetComponent().startDelay = 0.5f;
gameObject.GetComponent().startLifetime = 0.65f;
gameObject.GetComponent().startSpeed = 200;
gameObject.GetComponent().startSize = 10;
gameObject.GetComponent().startRotation = 1;
gameObject.GetComponent().maxParticles = 1000;
gameObject.GetComponent().emissionRate = 100;
}
// Update is called once per frame
void Update () {
value = stream.ReadLine(); // value from Arduino
float val = float.Parse(value);
float v = val / 1023;
gameObject.GetComponent().startSpeed = v*200;
gameObject.GetComponent().startSize = v*50;
Debug.Log(v);
}
}
這個範例是利用RS232讓電腦和Arduino可以進行資料的交換,利用SerialPort物件來進行,通訊速率選擇在9600 bps,對於通訊速率的說明,可以參考維基百科位元速率的說明。在Start()函式內呼叫Open()函式來打開通訊埠,接下來在Update()函式內,呼叫ReadLine()函式來讀取Arduino傳送過來的數值,經過計算後,設定ParticleSystem物件的startSpeed和startSize兩個屬性。
沒有留言:
張貼留言