问题我已经有百度或者google过。可是得到的结果对新手来说并不是太友好。所以才能这里问一问大大们。
我想做一个简单的Arduino与Unity3D的游戏交互。
我希望通过arduino发送一个数值 并用Unity获取到。
如:Aduino 发送一个50的值,然后Unity接收到50并且能显示出来。(可以方便控制游戏物体移动)。
下面是我找到的一个比较简单的代码,可是会使Unity死机
[mw_shl_code=bash,true]
void setup()
{
Serial.begin(38400);
}
void loop()
{
float values[] = {analogRead(0),analogRead(1),analogRead(2)};
Serial.flush();
Serial.print(map(values[0],0,1023,0,359));
Serial.print(",");
Serial.print(map(values[1],0,1023,0,359));
Serial.print(",");
Serial.print(map(values[2],0,1023,0,359));
Serial.println();
delay(30);
}[/mw_shl_code]
[mw_shl_code=bash,true]
using UnityEngine;
using System.Collections;
using System.IO.Ports;
public class serialRotation : MonoBehaviour {
SerialPort stream = new SerialPort("COM4", 38400); //Set the port (com4) and the baud rate (9600, is standard on most devices)
float[] lastRot = {0,0,0}; //Need the last rotation to tell how far to spin the camera
Vector3 rot;
Vector3 offset;
void Start () {
stream.Open(); //Open the Serial Stream.
}
// Update is called once per frame
void Update () {
string value = stream.ReadLine(); //Read the information
string[] vec3 = value.Split(','); //My arduino script returns a 3 part value (IE: 12,30,18)
if(vec3[0] != "" && vec3[1] != "" && vec3[2] != "") //Check if all values are recieved
{
rot = new Vector3(float.Parse(vec3[0]),float.Parse(vec3[1]),float.Parse(vec3[2]));
//Read the information and put it in a vector3
transform.rotation = Quaternion.Slerp(transform.rotation,
Quaternion.Euler(0,rot.x,rot.y),
Time.deltaTime*3);
//Take the vector3 and apply it to the object this script is applied.
stream.BaseStream.Flush(); //Clear the serial information so we assure we get new information.
}
}
void OnGUI()
{
string newString = "Connected: " + transform.eulerAngles;
GUI.Label(new Rect(10,10,300,100), newString); //Display new values
GUI.Label(new Rect(10,30,300,100), "\t" + rot);
}
}[/mw_shl_code]
希望大大们 能够解答 如果能给简单的代码示例最好了..
谢谢!!