using System; using UnityEngine; using System.Collections; using System.IO.Ports; using System.Linq; public class Serial2 : MonoBehaviour{ public float x; public float y; public RotationControl bot; ~Serial2() { serialPort.Close(); } public bool enabled = false; SerialPort serialPort; public void Update() { if (serialPort == null) { serialPort = new SerialPort(@"\\.\" + "COM7", 115200); try { serialPort.NewLine = "\n"; serialPort.Open(); serialPort.DiscardOutBuffer(); serialPort.DiscardInBuffer(); enabled = true; } catch { enabled = false; } } if (enabled) { if (serialPort is SerialPort) { string received = serialPort.ReadLine(); string[] data = received.Split(','); x = ConvertRadiansToDegrees(float.Parse(data.First())); y = ConvertRadiansToDegrees(float.Parse(data.Last())); bot.rotation = new Quaternion(-1* limit(y, -30, 30), 0, -1* limit(x, -30, 30), 1); } } } public float limit(float input, float min, float max) { return (input < max & input > min) ? input : input < min ? min : max; } public float ConvertRadiansToDegrees(float radians) { float degrees = (float) ((180 / Math.PI) * radians); return (degrees); } }