android unity hid,Unity5.X与Arduino交互

问题我已经有百度或者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]

希望大大们 能够解答 如果能给简单的代码示例最好了..

谢谢!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值