RoboidControl-csharp/Unity/Participant.cs

84 lines
3.5 KiB
C#

using UnityEngine;
using System.Linq;
namespace RoboidControl.Unity {
public class Participant : MonoBehaviour {
public string ipAddress;
public int port;
public RoboidControl.Participant coreParticipant;
protected virtual void Update() {
if (coreParticipant == null)
return;
if (coreParticipant.updateQueue.TryDequeue(out RoboidControl.Participant.UpdateEvent e))
HandleUpdateEvent(e);
}
private void HandleUpdateEvent(RoboidControl.Participant.UpdateEvent e) {
switch (e.messageId) {
case ParticipantMsg.Id:
GameObject remoteParticipant = new GameObject("RemoteParticipant");
Participant participant = remoteParticipant.AddComponent<Participant>();
participant.coreParticipant = e.participant;
participant.coreParticipant.component = participant;
if (participant.coreParticipant is ParticipantUDP participantUDP) {
participant.ipAddress = participantUDP.ipAddress;
participant.port = participantUDP.port;
}
break;
case ThingMsg.id:
HandleThingEvent(e);
break;
default:
Debug.Log($"Unhandled event: {e.messageId}");
break;
}
}
protected virtual void HandleThingEvent(RoboidControl.Participant.UpdateEvent e) {
switch (e.thing) {
case RoboidControl.DistanceSensor coreDistanceSensor:
coreDistanceSensor.component = DistanceSensor.Create(coreDistanceSensor);
break;
case RoboidControl.TouchSensor coreTouchSensor:
coreTouchSensor.component = TouchSensor.Create(coreTouchSensor);
break;
case RoboidControl.DifferentialDrive coreDrive:
coreDrive.component = DifferentialDrive.Create(coreDrive);
break;
case RoboidControl.Motor coreMotor:
if (coreMotor.component == null) {
Motor wheel = Motor.Create(coreMotor);
coreMotor.component = wheel;
// We need to know the details (though a binary msg)
// before we can create the wheel reliably
}
else // Update the component from the core
coreMotor.component.Init(coreMotor);
break;
case RoboidControl.Thing coreThing:
if (coreThing.component == null) {
Thing[] things = FindObjectsByType<Thing>(FindObjectsSortMode.None);
// Debug.Log(things.Length);
Thing thing = things.FirstOrDefault(t =>
t != null &&
t.core != null &&
t.core.owner.networkId == coreThing.owner.networkId &&
t.core.id == coreThing.id
);
if (thing == null)
thing = Thing.Create(coreThing);
coreThing.component = thing;
}
else // Update the component from the core
coreThing.component.Init(coreThing);
break;
}
}
}
}