Skip to content

Instantly share code, notes, and snippets.

@leestuartx
Created April 2, 2015 22:10
Show Gist options
  • Save leestuartx/b2565ad679e71306a830 to your computer and use it in GitHub Desktop.
Save leestuartx/b2565ad679e71306a830 to your computer and use it in GitHub Desktop.
Use IOS or Android as a mobile controller in Unity (Send)
using UnityEngine;
using System.Collections;
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class UDP_GyroSend : MonoBehaviour {
private static int localPort;
// prefs
private string IP; // define in init
public int port; // define in init
// "connection" things
IPEndPoint remoteEndPoint;
UdpClient client;
// gui
string strMessage="";
string newIPAddr="127.0.0.1";
string newPortNum="2067";
public bool isActive;
private float initialDelay = 0f;
private float repeatTime = 0.01f;
public UILabel IPAddressLbl;
public UILabel PortLbl;
public UILabel playerNumLbl;
public UILabel statusLbl;
public UILabel sendingLabel;
private float touchSpeed = 0.1f;
private Vector2 touchPos = Vector2.zero;
private bool hasInitialized = false;
private bool accelerometerActive = true;
private bool gpsActive = true;
private bool gyroscopeActive = true;
private bool compassActive = true;
private string bk = "\n"; //Line Break for labels
private bool startedSendingUpdates = false;
private Vector3 accelerometerData;
// private Vector3 GPSCoord;
private float compassHeading;
void Awake()
{
//Load the ip and port from the player prefs
string tempIP = PlayerPrefs.GetString("IPAddr");
if (tempIP != "")
IPAddressLbl.text = tempIP;
string tempPort = PlayerPrefs.GetString("PortNum");
if (tempPort != "")
PortLbl.text = tempPort;
string tempPlayerNum = PlayerPrefs.GetString("PlayerN");
if (tempPlayerNum != "")
playerNumLbl.text = tempPlayerNum;
}
IEnumerator InitializeAllFeatures()
{
// First, check if user has location service enabled
if (Input.location.isEnabledByUser)
{
// Start service before querying location
Input.location.Start(1, 1); //Desired accuracy and update by distance in meters
// Wait until service initializes
int maxWait = 20;
while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
{
yield return new WaitForSeconds(1);
maxWait--;
}
// Service didn't initialize in 20 seconds
if (maxWait < 1)
{
SetStatus("Timed out");
}
else // Not a timeout
{
// Connection has failed
if (Input.location.status == LocationServiceStatus.Failed)
{
SetStatus("Unable to determine device location");
}
}
Input.compass.enabled = true;
InvokeRepeating("UpdateGPS", 0, 1f);
InvokeRepeating("UpdateAccelerometer", 0, 0.01f);
}
}
// call it from shell (as program)
private static void SetupClient()
{
UDP_GyroSend sendObj=new UDP_GyroSend();
sendObj.init();
// testing via console
// sendObj.inputFromConsole();
Debug.Log("Does this shit get called");
// as server sending endless
sendObj.sendEndless(" endless infos \n");
}
public void SetStatus(string newStatus)
{
statusLbl.text = "Status: " + newStatus;
}
public void SetSendingText()
{
string startingText = "Sending: " + bk;
if (accelerometerActive)
{
startingText += "Accelerometer:" + accelerometerData + bk;
}
if (gpsActive)
{
startingText += "GPS On" + bk;
}
if (gyroscopeActive)
{
startingText += "Gyroscope On" + bk;
}
if (compassActive)
{
startingText += "Compass:" + compassHeading + bk;
}
sendingLabel.text = startingText;
}
public void EnableAccelerometer(){
accelerometerActive = !accelerometerActive;
if (accelerometerActive)
{
InvokeRepeating("UpdateAccelerometer", 0, 0.01f);
}
else
{
CancelInvoke("UpdateAccelerometer");
}
}
public void EnableGPS()
{
gpsActive = !gpsActive;
if (gpsActive)
{
Input.location.Start(0.1f, 0.1f);
InvokeRepeating("UpdateGPS", 0, 0.5f);
}
else
{
CancelInvoke("UpdateGPS");
Input.location.Stop();
}
}
public void EnableGyroscope()
{
gyroscopeActive = !gyroscopeActive;
Camera.main.gameObject.GetComponent<IOSGyro_Update>().enabled = gyroscopeActive;
}
public void EnableCompass()
{
compassActive = !compassActive;
Input.compass.enabled = compassActive;
if (compassActive)
{
InvokeRepeating("Orientate", 1, 0.05f);
}
else
{
CancelInvoke("Orientate");
}
}
void UpdateAccelerometer()
{
accelerometerData = Input.acceleration;
sendString("accel:" + accelerometerData);
}
void UpdateGPS()
{
//Get the Latitude and Longitude values
LocationInfo li = Input.location.lastData;
sendString("gps: " + li.latitude + "," + li.longitude + "," + li.altitude);
//sendString("gps:" + GPSCoord );
}
void Orientate()
{
//Compass heading will determine y rotation
compassHeading = Input.compass.trueHeading;
sendString("compa:" + compassHeading );
}
// start from unity3d
public void DoSendUpdates()
{
//Save the connection info to the playerprefs
PlayerPrefs.SetString("IPAddr", IPAddressLbl.text);
PlayerPrefs.SetString("PortNum", PortLbl.text);
PlayerPrefs.SetString("PlayerN", playerNumLbl.text);
StartCoroutine(InitializeAllFeatures());
SetStatus("Connecting...");
if (hasInitialized)
{
//Reconnect to new IP Addr
hasInitialized = false;
CancelInvoke("SendUpdates");
if (client != null)
client.Close();
}
//Update the status on screen of the type of data we are currently sending
if (!startedSendingUpdates)
{
startedSendingUpdates = true;
InvokeRepeating("SetSendingText", 0, 0.1f);
}
hasInitialized = true;
Debug.Log("Do the send updates");
init();
InvokeRepeating("SendUpdates", initialDelay, repeatTime);
// Main();
}
void Update()
{
if (hasInitialized)
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
touchPos = touchDeltaPosition;
SetStatus("touch pos: " + touchPos);
//Send the touc position over to the client
sendString("tPos:" + touchPos);
}
else if (Input.GetButtonDown("Fire1"))
{
touchPos = Input.mousePosition;
Vector3 screenPos = new Vector3(touchPos.x, touchPos.y, 0);
//Send the touc position over to the client
sendString("tPos:" + screenPos);
}
}
}
public void DoPlayerNumberChange(){
if (client != null)
sendString("playN:" + playerNumLbl.text);
}
public void DoPressSpecialButton()
{
if (client != null)
sendString("useS:");
}
// init
public void init()
{
print("UDPSend.init()");
// define
IP=IPAddressLbl.text;
port = int.Parse(PortLbl.text);
// ----------------------------
// Send
// ----------------------------
remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);
client = new UdpClient();
// status
print("Sending to "+IP+" : "+port);
print("Testing: nc -lu "+IP+" : "+port);
}
// inputFromConsole
private void inputFromConsole()
{
try
{
string text;
do
{
text = Console.ReadLine();
if (text != "")
{
byte[] data = Encoding.UTF8.GetBytes(text);
client.Send(data, data.Length, remoteEndPoint);
}
} while (text != "");
}
catch (Exception err)
{
print(err.ToString());
}
}
// sendData
private void sendString(string message)
{
if (!hasInitialized)
return;
try
{
byte[] data = Encoding.UTF8.GetBytes(message);
client.Send(data, data.Length, remoteEndPoint);
}
catch (Exception err)
{
print(err.ToString());
}
}
IEnumerator WaitTime(float waitDelay) {
yield return new WaitForSeconds(waitDelay);
}
private void SendUpdates(){
/** Send the latest accelerometer info to the client, the client will then use that for lerping camera position */
Vector3 cameraPos = Camera.main.transform.position;
Vector3 cameraRot = Camera.main.transform.rotation.eulerAngles;
sendString("camR:"+cameraRot.ToString());
}
// endless test
private void sendEndless(string testStr)
{
do
{
sendString(testStr);
}
while(true);
}
void OnApplicationQuit()
{
if (client != null)
client.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment