public StickState(XBoxController controller, StickType type) { _controller = controller; _stickType = type; _previosValue = new Point(0, 0); _controller.StateChanged += _controller_StateChanged; }
private void TestAndDiagnostics_Load(object sender, EventArgs e) { MainForm mainForm = Parent.Parent as MainForm; xboxController = mainForm.SharedXBoxController(); gamepadController = mainForm.SharedGamepadController(); }
private void TestMotorControl(XBoxController controller, bool simulate = false) { OnIsRunngingChanged(true); try { Motor.Instance.Start(simulate); Tuple <int, int> speedValues = new Tuple <int, int>(0, 0); while (!_shouldStop && !controller.Buttons.Equals(GamepadButtonFlags.A)) { Tuple <int, int> nextSpeedValues = CalculateSpeedValues(controller); // only update if values changed { speedValues = nextSpeedValues; Motor.Instance.LeftSpeedValue = (speedValues.Item1); Motor.Instance.RightSpeedValue = (speedValues.Item2); if (simulate) { log.Info(String.Format("Leftspeed: {0}, Rightspeed: {1}", speedValues.Item1, speedValues.Item2)); } } } Motor.Instance.PullUp(); Stop(); } catch (Exception pnve) { log.Error("A motor problem occured: " + pnve.Message + "\n " + pnve.StackTrace); } finally { OnIsRunngingChanged(false); } }
/// <summary> /// Transforms the input values from controller to left and right speed /// values for the motors /// </summary> /// <param name="controller"></param> /// <returns>A Tuple(int, int) with left and right speed values</int></returns> private Tuple <int, int> CalculateSpeedValues(XBoxController controller) { controller.Update(); float rightTrigger = controller.RightTrigger; float leftTrigger = controller.LeftTrigger; double rightThumbX = controller.RightThumb.X; int leftspeed = 0; int rightspeed = 0; // calculate speed based on left and right triggers (right trigger forward, left trigger backward) int tempSpeed = (int)((rightTrigger - leftTrigger));// / 255 * 100); if (rightThumbX > 0) { double multiplier = rightThumbX / 100; leftspeed = (int)(tempSpeed + multiplier * 255); rightspeed = (int)(tempSpeed - multiplier * 255); } else if (rightThumbX < 0) { double multiplier = rightThumbX / -100; leftspeed = (int)(tempSpeed - multiplier * 255); rightspeed = (int)(tempSpeed + multiplier * 255); } else { rightspeed = leftspeed = tempSpeed; } return(Tuple.Create(leftspeed, rightspeed)); }
public static void Open(bool luma = false) { _luma = luma; oldbuttons = 0xff0f0000; oldtouch = 0x00000002; oldcircle = 0x00088000; oldcstick = 0x81008080; //oldspecial = 0x00000000; XBoxControllerWatcher watcher = new BrandonPotter.XBox.XBoxControllerWatcher(); watcher.ControllerConnected += (c) => { controller = c; }; watcher.ControllerDisconnected += (c) => { c = null; }; threadXbox = new Thread(() => { Running = true; while (Running) { CheckState(); } }); threadXbox.Start(); }
private void GraphAnalogControl_Load(object sender, EventArgs e) { MainForm mainForm = Parent.Parent as MainForm; xboxController = mainForm.SharedXBoxController(); gamepadController = mainForm.SharedGamepadController(); }
public ButtonState(XBoxController controller, ButtonFlags button) { _button = button; _controller = controller; controller.StateChanged += Controller_StateChanged; controller.ButtonDown += Controller_ButtonDown; controller.ButtonUp += Controller_ButtonUp; }
/// <summary> /// Initializes a new instance of the XBoxControllerComponent class. /// </summary> public XBoxControllerComponent() : base("XBox Controller", "XBoxCont", "Outputs Data from a connected XBox Controller", "Firefly", "Arduino & I/O Boards") { var connectedControllers = XBoxController.GetConnectedControllers(); XBoxControllerWatcher watcher = new XBoxControllerWatcher(); watcher.ControllerConnected += (c) => Connected(c); }
public static int Connect() { try { _xBoxController = XBoxController.GetConnectedControllers().ToList(); } catch { } return(_xBoxController.Count); }
static void Main(string[] args) { /// Enregistrement de la license SciChart en début de code SciChartSurface.SetRuntimeLicenseKey("RJWA77RbaJDdCRJpg4Iunl5Or6/FPX1xT+Gzu495Eaa0ZahxWi3jkNFDjUb/w70cHXyv7viRTjiNRrYqnqGA+Dc/yzIIzTJlf1s4DJvmQc8TCSrH7MBeQ2ON5lMs/vO0p6rBlkaG+wwnJk7cp4PbOKCfEQ4NsMb8cT9nckfdcWmaKdOQNhHsrw+y1oMR7rIH+rGes0jGGttRDhTOBxwUJK2rBA9Z9PDz2pGOkPjy9fwQ4YY2V4WPeeqM+6eYxnDZ068mnSCPbEnBxpwAldwXTyeWdXv8sn3Dikkwt3yqphQxvs0h6a8Dd6K/9UYni3o8pRkTed6SWodQwICcewfHTyGKQowz3afARj07et2h+becxowq3cRHL+76RyukbIXMfAqLYoT2UzDJNsZqcPPq/kxeXujuhT4SrNF3444MU1GaZZ205KYEMFlz7x/aEnjM6p3BuM6ZuO3Fjf0A0Ki/NBfS6n20E07CTGRtI6AsM2m59orPpI8+24GFlJ9xGTjoRA=="); /// Initialisation des modules utilisés dans le robot int robotId = 10; /// Ne pas changer cette variable ! int teamId = 0; /// Ne pas changer cette variable ! usbDriver = new USBVendor(); msgDecoder = new MsgDecoder(); msgEncoder = new MsgEncoder(); robotMsgGenerator = new MsgGenerator(); robotMsgProcessor = new MsgProcessor(robotId, competition); xBoxManette = new XBoxControllerNS.XBoxController(robotId); strategyManager = new StrategyEurobot(robotId, teamId, "224.16.32.79"); localWorldMapManager = new LocalWorldMapManager(robotId, teamId, bypassMulticast: false); positioning2Wheels = new Positioning2Wheels(robotId); trajectoryGenerator = new TrajectoryGeneratorNonHolonome(robotId); /// Création des liens entre module, sauf depuis et vers l'interface graphique usbDriver.OnUSBDataReceivedEvent += msgDecoder.DecodeMsgReceived; // Transmission des messages reçus par l'USB au Message Decoder msgDecoder.OnMessageDecodedEvent += robotMsgProcessor.ProcessRobotDecodedMessage; // Transmission les messages décodés par le Message Decoder au Message Processor //Events d'activation et configuration de l'asservissement en vitesse depuis le Strategy Manager strategyManager.On2WheelsToPolarMatrixSetupEvent += robotMsgGenerator.GenerateMessage2WheelsToPolarMatrixSet; //Transmission des messages de set-up de la matrice de transformation moteurindepeandt -> polaire en embarqué strategyManager.On2WheelsAngleSetupEvent += robotMsgGenerator.GenerateMessage2WheelsAngleSet; //Transmission des messages de set-up de la config angulaire des roues en embarqué strategyManager.OnOdometryPointToMeterSetupEvent += robotMsgGenerator.GenerateMessageOdometryPointToMeter; //Transmission des messages de set-up du coeff pointToMeter en embarqué strategyManager.On2WheelsIndependantSpeedPIDSetupEvent += robotMsgGenerator.GenerateMessage2WheelsIndependantSpeedPIDSetup; //Setup du PID independant strategyManager.OnSetAsservissementModeEvent += robotMsgGenerator.GenerateMessageSetAsservissementMode; robotMsgGenerator.OnMessageToRobotGeneratedEvent += msgEncoder.EncodeMessageToRobot; // Envoi des messages du générateur de message à l'encoder msgEncoder.OnMessageEncodedEvent += usbDriver.SendUSBMessage; // Envoi des messages en USB depuis le message encoder robotMsgProcessor.OnPolarOdometrySpeedFromRobotEvent += positioning2Wheels.OnOdometryRobotSpeedReceived; //Envoi des vitesses reçues de l'embarqué au module de calcul de positionnement positioning2Wheels.OnCalculatedLocationEvent += trajectoryGenerator.OnPhysicalPositionReceived; //Envoi du positionnement calculé au module de génération de trajectoire trajectoryGenerator.OnGhostLocationEvent += localWorldMapManager.OnGhostLocationReceived; trajectoryGenerator.OnSpeedConsigneEvent += robotMsgGenerator.GenerateMessageSetSpeedConsigneToRobot; //Transmission des commande de vitesse aux moteurs de déplacement strategyManager.OnSetSpeedConsigneToMotorEvent += robotMsgGenerator.GenerateMessageSetSpeedConsigneToMotor; //Transmission des commande de vitesse (aux moteurs annexes) positioning2Wheels.OnCalculatedLocationEvent += localWorldMapManager.OnPhysicalPositionReceived; strategyManager.InitStrategy(); //à faire après avoir abonné les events ! StartRobotInterface(); while (!exitSystem) { Thread.Sleep(500); } }
public void BikeBridge() { var bike = new Bike(); var xboxController = new XBoxController(bike); var psController = new PSController(bike); Assert.AreEqual("Run", xboxController.ButtonA()); Assert.AreEqual("Stop", xboxController.ButtonB()); Assert.AreEqual("Stop", psController.ButtonA()); Assert.AreEqual("Run", psController.ButtonB()); }
public void DragonBridge() { var dragon = new Dragon(); var xboxController = new XBoxController(dragon); var psController = new PSController(dragon); Assert.AreEqual("Run", xboxController.ButtonA()); Assert.AreEqual("Fly", xboxController.ButtonB()); Assert.AreEqual("Fly", psController.ButtonA()); Assert.AreEqual("Run", psController.ButtonB()); }
public CarHuman(bool captureState, int frequencyMs) { this.captureState = captureState; this.frequencyMs = frequencyMs / 1000.0f; StateInputMeasurements = new List <float[]>(); StateOutputMeasurements = new List <float[]>(); var controllerManager = new ControllerManager(); gameController = controllerManager.GetController(); // Default the car configuration. Rarely ever changed, not even sure this needs to be exposed. Configuration = new CarConfiguration(); }
static void Main(string[] args) { XBoxControllerWatcher xbcw = new XBoxControllerWatcher(); xbcw.ControllerConnected += OnControllerConnected; xbcw.ControllerDisconnected += OnControllerDisconnected; Console.WriteLine("Press any key to exit."); while (!Console.KeyAvailable) { System.Threading.Thread.Sleep(1000); foreach (var c in XBoxController.GetConnectedControllers()) { Console.WriteLine("Controller " + c.PlayerIndex.ToString() + " Thumb Left X = " + c.ThumbLeftX.ToString() + ", Y = " + c.ThumbLeftY.ToString() + ", A = " + c.ButtonAPressed.ToString()); } } }
static void Main(string[] args) { try { var controller = XBoxController.RetrieveController(0); controller.ButtonClick += Controller_ButtonClick; controller.LeftStickMotion += Controller_LeftStickMotion; controller.RightStickMotion += Controller_RightStickMotion; _mainController = new MainController(); XBoxController.StartPolling(); _mainController.Run(); XBoxController.StopPolling(); } catch (Exception ex) { Debug.WriteLine(ex); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex.ToString()); } }
private async void ControllerListenerLoopAsync() { CancellationToken cancellationTokenSource = m_CancellationTokenSource.Token; XBoxController connectedController = XBoxController.GetConnectedControllers().FirstOrDefault(); while (!cancellationTokenSource.IsCancellationRequested) { await Task.Delay(20); if (connectedController.IsConnected) { StickValues newValues = new StickValues(connectedController.ThumbLeftX, connectedController.ThumbLeftY, connectedController.ThumbRightX, connectedController.ThumbRightY); if (m_LastUpdate < Environment.TickCount) { m_LastUpdate = Environment.TickCount + UpdateFrequency; ControllerUpdate?.Invoke(this, newValues); } if (newValues != m_LastValues) { m_LastValues = newValues; ControllerChanged?.Invoke(this, newValues); } CheckButton("A", connectedController.ButtonAPressed); CheckButton("B", connectedController.ButtonBPressed); CheckButton("X", connectedController.ButtonXPressed); CheckButton("Y", connectedController.ButtonYPressed); CheckButton("Back", connectedController.ButtonBackPressed); CheckButton("Start", connectedController.ButtonStartPressed); CheckButton("Up", connectedController.ButtonUpPressed); CheckButton("Down", connectedController.ButtonDownPressed); CheckButton("Left", connectedController.ButtonLeftPressed); CheckButton("Right", connectedController.ButtonRightPressed); CheckButton("LB", connectedController.ButtonShoulderLeftPressed); CheckButton("RB", connectedController.ButtonShoulderRightPressed); CheckButton("LT", connectedController.TriggerLeftPressed); CheckButton("RT", connectedController.TriggerRightPressed); CheckButton("LS", connectedController.ThumbpadLeftPressed); CheckButton("RS", connectedController.ThumbpadRightPressed); } } }
/// <summary> /// Log the Contorller values. /// </summary> /// <param name="controller"></param> /// <returns></returns> private bool TestConrollerOutputs(XBoxController controller) { OnIsRunngingChanged(true); while (!_shouldStop) { Thread.Sleep(200); // give console some time after each iteration controller.Update(); Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => { log.Info("\nLeft Thumb X: " + controller.LeftThumb.X + " " + "\nLeft Thumb Y: " + controller.LeftThumb.Y + "\n" + "A?: " + controller.Buttons.Equals(GamepadButtonFlags.A) + "\n" + "Rigth Thumb X: " + controller.RightThumb.X + "\n" + "Rigth Thumb Y: " + controller.RightThumb.Y + "\n" + "Left Trigger: " + controller.LeftTrigger + "\n" + "Right Trigger: " + controller.RightTrigger); })); //Console.WriteLine(controller.leftThumb + " " + controller.rightThumb + " " + controller.leftTrigger + " " + controller.rightTrigger); } log.Info("Controller test ended"); OnIsRunngingChanged(false); return(true); }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } LagoVista.Core.UWP.Services.UWPDeviceServices.Init(rootFrame.Dispatcher); _joystick = new XBoxController(); _joystick.StartListening(rootFrame.Dispatcher); // Place the frame in the current Window Window.Current.Content = rootFrame; } if (e.PrelaunchActivated == false) { if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); } }
void InitController() { xBoxController = GetComponent <XBoxController> (); }
private static void OnControllerConnected(XBoxController controller) { Console.WriteLine("Controller Connected: Player " + controller.PlayerIndex.ToString()); }
/// <summary> /// Make Vector drive around based on an Xbox controller /// </summary> /// <returns></returns> public static async Task Main() { // Create a new connection to the first configured Vector using var robot = await Robot.NewConnection(); Console.WriteLine("Requesting control of Vector..."); await robot.Control.RequestControl(); // If Vector is on the charger, drive him off the charger if (robot.Status.IsOnCharger) { Console.WriteLine("Drive Vector off charger..."); await robot.Behavior.DriveOffCharger(); } // Create a task that will receive input from the game controller taskXboxController = new Task(() => { // Enable the game controller XBoxController.XInputEnable(true); // a structure to hold the state of the game controller XBoxController.XInputState state = new XBoxController.XInputState(); int prevPacketNumber = 0; for (; ;) { // try to get input; if no game controller, it will error out var err = XBoxController.XInputGetState(0, ref state); if (0 != err) { Thread.Sleep(500); continue; } // skip if the packet number has not changed // (this is unlikely to be needed code) if (prevPacketNumber == state.PacketNumber) { Thread.Sleep(100); continue; } // Save the packet number prevPacketNumber = state.PacketNumber; // Get the left-right percentage and use that for an angle var turnAngle = state.Gamepad.sThumbRX * -90.0 / 32768.0; var turnAngle2 = turnAngle * turnAngle; if (turnAngle2 > 10.0) { // Send a command to turn by that amount robot.Behavior.TurnInPlace(((float)turnAngle).Degrees()); } // Get the forward/back amount var fwd = state.Gamepad.sThumbRY * 200.0 / 32768.0; var fwd2 = fwd * fwd; if (fwd2 > 10.0) { robot.Behavior.DriveStraight((float)fwd, 50); } } }); // Start communicating taskXboxController.Start(); Console.WriteLine("Press any key to exit..."); await Task.Run(() => Console.ReadKey(true)); }
static void Main(string[] args) { ConsoleFormat.InitMainConsole(); /// Enregistrement de la license SciChart en début de code SciChartSurface.SetRuntimeLicenseKey(ConstVar.SCICHART_RUNTIME_KEY); ConsoleFormat.SetupScichartLicenceKey(); /// Initialisation des modules utilisés dans le robot int robotId = (int)RobotId.Robot1; int teamId = (int)TeamId.Team1; usbDriver = new USBVendor(); msgDecoder = new MsgDecoder(); msgEncoder = new MsgEncoder(); msgGenerator = new MsgGenerator(); msgProcessor = new MsgProcessor(robotId, competition); ConsoleFormat.SetupAllCommunication(); xBoxManette = new XBoxController(robotId); ConsoleFormat.SetupXboxController(); logRecorder = new LogRecorder(); logReplay = new LogReplay(); strategyManager = new StrategyEurobot(robotId, teamId, "224.16.32.79"); #region Communication to Low Lvl /// Création des liens entre module, sauf depuis et vers l'interface graphique usbDriver.OnUSBuffReceivedEvent += msgDecoder.BuffReceived; // Transmission des messages reçus par l'USB au Message Decoder msgDecoder.OnCorrectMessageReceivedEvent += msgProcessor.ProcessRobotDecodedMessage; // Transmission les messages décodés par le Message Decoder au Message Processor msgGenerator.OnMessageToRobotGeneratedEvent += msgEncoder.EncodeAndSendMessage; // Envoi des messages du générateur de message à l'encoder msgEncoder.OnSendMessageEvent += usbDriver.SendUSBMessage; // Envoi des messages en USB depuis le message encoder #endregion #region Console // Control: bool hex_viewer = false; bool hex_sender = false; bool hex_viewer_error = true; bool hex_sender_error = true; bool hex_processor = false; bool hex_generator = false; #region USB Vendor usbDriver.OnDeviceAddedEvent += ConsoleFormat.PrintNewDeviceAdded; usbDriver.OnDeviceRemovedEvent += ConsoleFormat.PrintDeviceRemoved; usbDriver.OnUsbVendorExeptionEvent += ConsoleFormat.PrintUsbErrorExeption; #endregion #region Hex Viewer if (hex_viewer) { msgDecoder.OnUnknowByteEvent += ConsoleFormat.PrintUnknowByte; msgDecoder.OnSOFByteReceivedEvent += ConsoleFormat.PrintSOF; msgDecoder.OnFunctionMSBByteReceivedEvent += ConsoleFormat.PrintFunctionMSB; msgDecoder.OnFunctionLSBByteReceivedEvent += ConsoleFormat.PrintFunctionLSB; msgDecoder.OnPayloadLenghtMSBByteReceivedEvent += ConsoleFormat.PrintLenghtMSB; msgDecoder.OnPayloadLenghtLSBByteReceivedEvent += ConsoleFormat.PrintLenghtLSB; msgDecoder.OnPayloadByteReceivedEvent += ConsoleFormat.PrintPayloadByte; msgDecoder.OnCorrectMessageReceivedEvent += ConsoleFormat.PrintCorrectChecksum; msgDecoder.OnErrorMessageReceivedEvent += ConsoleFormat.PrintWrongChecksum; } #endregion #region Hex Viewer Error if (hex_viewer_error) { msgDecoder.OnOverLenghtMessageEvent += ConsoleFormat.PrintOverLenghtWarning; msgDecoder.OnUnknowFunctionEvent += ConsoleFormat.PrintUnknowFunctionReceived; msgDecoder.OnWrongLenghtFunctionEvent += ConsoleFormat.PrintWrongFonctionLenghtReceived; } #endregion #region Hex Sender if (hex_sender) { msgEncoder.OnSendMessageByteEvent += ConsoleFormat.PrintSendMsg; } #endregion #region Hex Sender Error if (hex_sender_error) { msgEncoder.OnSerialDisconnectedEvent += ConsoleFormat.PrintOnSerialDisconnectedError; msgEncoder.OnUnknownFunctionSentEvent += ConsoleFormat.PrintUnknowFunctionSent; msgEncoder.OnWrongPayloadSentEvent += ConsoleFormat.PrintWrongFunctionLenghtSent; } #endregion #endregion #region Lidar lidar = new SickLidar(17422959); // 18110177 lidarProcess = new LidarProcess(robotId, teamId); lidar.OnLidarDeviceConnectedEvent += lidarProcess.OnNewLidarConnected; lidar.OnLidarDeviceConnectedEvent += ConsoleFormat.NewLidarDeviceConnected; lidar.PointsAvailable += lidarProcess.OnRawPointAvailable; lidar.Start(); #endregion lidarProcess.OnRawLidarDataEvent += logRecorder.OnRawLidarDataReceived; msgProcessor.OnSpeedPolarOdometryFromRobotEvent += logRecorder.OnPolarSpeedDataReceived; #region Local World Map localWorldMap = new LocalWorldMap(robotId, teamId); localWorldMap.OnUpdateRobotLocationEvent += lidarProcess.OnRobotLocation; lidarProcess.OnRawLidarPointPolarEvent += localWorldMap.OnLidarRawPointReceived; lidarProcess.OnProcessLidarPolarDataEvent += localWorldMap.OnLidarProcessedPointReceived; lidarProcess.OnProcessLidarLineDataEvent += localWorldMap.OnLidarProcessedLineReceived; lidarProcess.OnProcessLidarCupDataEvent += localWorldMap.OnLidarProcessedCupReceived; lidarProcess.OnLidarSetupRobotLocationEvent += localWorldMap.OnRobotLocation; //lidarProcess.OnProcessLidarObjectsDataEvent += localWorldMap.OnLidarProcesObjectsReceived; localWorldMap.OnLocalWorldMapEvent += strategyManager.OnLocalWorldMapReceived; localWorldMap.Init(); #endregion #region Position2Wheels positioning2Wheels = new Positioning2Wheels(robotId); msgProcessor.OnSpeedPolarOdometryFromRobotEvent += positioning2Wheels.OnOdometryRobotSpeedReceived; positioning2Wheels.OnCalculatedLocationEvent += localWorldMap.OnRobotLocationArgs; #endregion #region TrajectoryPlanner trajectoryPlanner = new TrajectoryPlanner(robotId); trajectoryPlanner.OnNewGhostLocationEvent += localWorldMap.OnGhostLocation; trajectoryPlanner.OnNewRobotLocationEvent += localWorldMap.OnRobotLocation; trajectoryPlanner.OnDestinationReachedEvent += strategyManager.OnGhostLocationReached; #endregion #region Strategy /!\Need to be Last /! \ strategyManager.On2WheelsToPolarMatrixSetupEvent += msgGenerator.GenerateMessage2WheelsToPolarMatrixSet; //Transmission des messages de set-up de la matrice de transformation moteurindepeandt -> polaire en embarqué strategyManager.On2WheelsAngleSetupEvent += msgGenerator.GenerateMessage2WheelsAngleSet; //Transmission des messages de set-up de la config angulaire des roues en embarqué strategyManager.OnOdometryPointToMeterSetupEvent += msgGenerator.GenerateMessageOdometryPointToMeter; //Transmission des messages de set-up du coeff pointToMeter en embarqué strategyManager.OnSetAsservissementModeEvent += msgGenerator.GenerateMessageSetAsservissementMode; strategyManager.OnDestinationReachedEvent += localWorldMap.OnDestinationReached; strategyManager.OnWaypointsReachedEvent += localWorldMap.OnWaypointReached; strategyManager.OnSetActualLocationEvent += trajectoryPlanner.OnUpdateActualLocation; strategyManager.OnSetWantedLocationEvent += trajectoryPlanner.OnUpdateWantedDestination; strategyManager.OnGhostCalculationBeginEvent += trajectoryPlanner.OnLaunchCalculation; strategyManager.OnSetNewWaypointEvent += localWorldMap.AddNewWaypointsEvent; strategyManager.OnSetNewDestinationEvent += localWorldMap.SetDestinationLocationEvent; strategyManager.OnUpdateGhostCalculationOrderEvent += trajectoryPlanner.OnCalculateGhostMovement; ConsoleFormat.PrintStrategyBoot(); strategyManager.InitStrategy(); //à faire après avoir abonné les events ! #endregion if (usingMatchDisplay) { StartMatchInterface(); } else { StartRobotInterface(); } ConsoleFormat.EndMainBootSequence(); while (!exitSystem) { Thread.Sleep(500); } }
private static void OnControllerDisconnected(XBoxController controller) { Console.WriteLine("Controller Disconnected: Player " + controller.PlayerIndex.ToString()); }
protected override void Initialize() { Game1.game = this; // initialize screen this.Screen.Initialize(); // initialize players Avatars for (int i = 0; i < GameConfig.NumPlayers; ++i) { var pos = (i % 4) switch { 0 => new Vector2(300, 300), 1 => new Vector2(300, 800), 2 => new Vector2(1400, 300), 3 => new Vector2(1400, 800), _ => throw new NotImplementedException() }; var robot = new Robot((PlayerColor)(i % 4)) { Position = pos, Visible = false }; sprites.Add(robot); } // init Controler Players for (int i = 0; i < XBoxController.SupportedNumber; ++i) { var xBoxController = new XBoxController(i); controllers.Add(xBoxController); var player = new Player(xBoxController); playersGroup.Add(player); } // init Keybord Players for (int i = 0; i < KeyboardController.SupportedNumber; ++i) { var keyboardControler = new KeyboardController(i); controllers.Add(keyboardControler); var player = new Player(keyboardControler); playersGroup.Add(player); } // add bodypartdispensers var bpdHeart = new BodyPartDispenser(DispenserType.Herzgerät, 2) { Position = new Vector2(945, 1035) }; conveyerBelt.Add(bpdHeart); var bpdLungs = new BodyPartDispenser(DispenserType.Lungengerät, 2) { Position = new Vector2(1350, 80) }; conveyerBelt.Add(bpdLungs); var bpdKidneys = new BodyPartDispenser(DispenserType.Nierengerät, 2) { Position = new Vector2(535, 80) }; conveyerBelt.Add(bpdKidneys); // add scanner var scanner = new Scanner() { Position = new Vector2(1800, Game1.conveyerBelt.YPos) }; conveyerBelt.Add(scanner.Lower); TopLayer.Add(scanner.RightWall); TopLayer.Add(scanner.Upper); TopLayer.Add(scanner); // prepare FinishScreen this.FinishScreen = new FinishScreen(); TopLayer.Add(FinishScreen); // prepare StartScreen this.StartScreen = new StartScreen(sprites.OfType <Robot>()) { Visible = true }; TopLayer.Add(this.StartScreen); // add recycler var recycler = new Recycler() { Position = new Vector2(1810, 900) }; recycler.AddDispenser(bpdHeart); recycler.AddDispenser(bpdLungs); recycler.AddDispenser(bpdKidneys); conveyerBelt.Add(recycler); // add Textboxes TextBoxLeft = new TextBox() { Position = new Vector2(30, 30), Width = 100, Height = 100 }; TextBoxLeft.Text = ""; TextBoxLeft.FontScale = 0.5f; TopLayer.Add(TextBoxLeft); base.Initialize(); }
private void Awake() { controler = new XBoxController(); MovementSetUp(); }
private void mainForm_Load(object sender, EventArgs e) { try { evaDataSet.BeginInit(); evaDataSet.EnforceConstraints = true; evaDataSet.ReadXml("EventAction.xml", XmlReadMode.IgnoreSchema); evaDataSet.EndInit(); } catch { updateApplicationStatus(ApplicationState.Alert, @"Unable to read EventAction XML database."); } try { configDataSet = new DataSet(); configDataSet.BeginInit(); configDataSet.ReadXml("Configuration.xml"); configDataSet.EndInit(); } catch { updateApplicationStatus(ApplicationState.Alert, @"Unable to read Configuration XML database."); } try { DataTable dataTable = configDataSet.Tables["GamepadController"]; DataRow dataRow = dataTable.Rows[0]; int playerIndex = Convert.ToInt32(dataRow["player"]); gamepadController = new PG3B.Interface.GamepadController(playerIndex); } catch { updateApplicationStatus(ApplicationState.Warning, @"Unable to initialize GamePad."); } try { DataTable dataTable = configDataSet.Tables["XBoxController"]; DataRow dataRow = dataTable.Rows[0]; string portName = Convert.ToString(dataRow["port"]); xboxController = new PG3B.Interface.XBoxController(portName); switch (Convert.ToString(dataRow["model"])) { case "WiredCommonLine": xboxController.IsWireless = false; break; case "WirelessCommonGround": xboxController.IsWireless = true; break; } } catch { updateApplicationStatus(ApplicationState.Alert, @"Unable to initialize PG3B using Config.xml file."); } UpdateControllerStatus(); InitializeSubForms(); }
private void Connected(XBoxController c) { Console.WriteLine("Controller " + c.PlayerIndex.ToString() + " Connected."); Controller = c; }
static void Main(string[] args) { XBoxControllerWatcher xbcw = new XBoxControllerWatcher(); xbcw.ControllerConnected += OnControllerConnected; xbcw.ControllerDisconnected += OnControllerDisconnected; Point defPnt = new Point(); GetCursorPos(ref defPnt); InputSimulator input = new InputSimulator(); _x = defPnt.X; _y = defPnt.Y; int clickBuffer = 0; int rightClickBuffer = 0; int pageNavBuffer = 0; while (!Console.KeyAvailable) { System.Threading.Thread.Sleep(10); foreach (var c in XBoxController.GetConnectedControllers()) { //handle cursor position _x += trueSpeed(c.ThumbLeftX); _y -= trueSpeed(c.ThumbLeftY); SetCursorPos(_x, _y); //handle single left clicks if (c.ButtonAPressed && clickBuffer == 0) { clickBuffer += 1; //DoMouseClickLeft(); input.Mouse.LeftButtonClick(); } else if (clickBuffer != 0 && clickBuffer < 12) { clickBuffer += 1; } else //if (clickBuffer > 12) { clickBuffer = 0; } //hold left click if (c.ButtonShoulderLeftPressed) { input.Mouse.LeftButtonDown(); } //handle right clicks if (c.ButtonBPressed && rightClickBuffer == 0) { rightClickBuffer += 1; //DoMouseClickRight(); input.Mouse.RightButtonClick(); } else if (rightClickBuffer != 0 && rightClickBuffer < 21) { rightClickBuffer += 1; } else //if (clickBuffer > 21) { rightClickBuffer = 0; } //handle page scrolling if (trueSpeed(c.ThumbRightY) > 2) { MouseWheelUp(); } if (trueSpeed(c.ThumbRightY) < -2) { MouseWheelDown(); } if (trueSpeed(c.ThumbRightX) > 2) { MouseWheelRight(); } if (trueSpeed(c.ThumbRightX) < -2) { MouseWheelLeft(); } //handle page navigation if (c.ButtonLeftPressed && pageNavBuffer == 0) { pageNavBuffer += 1; input.Keyboard.KeyPress(VirtualKeyCode.BROWSER_BACK); } else if (pageNavBuffer != 0 && pageNavBuffer < 12) { pageNavBuffer += 1; } else //if (clickBuffer > 12) { pageNavBuffer = 0; } if (c.ButtonRightPressed && pageNavBuffer == 0) { pageNavBuffer += 1; input.Keyboard.KeyPress(VirtualKeyCode.BROWSER_FORWARD); } else if (pageNavBuffer != 0 && pageNavBuffer < 12) { pageNavBuffer += 1; } else //if (clickBuffer > 12) { pageNavBuffer = 0; } } } }
private void Start() { XBoxController.StartPolling(); }
static void Main(string[] args) { XBoxController controller = new XBoxController(); Console.WriteLine("XBox 360 Controller (Press ENTER to exit...)"); //Connection controller.Connection.ValueChanged += (s, e) => Console.WriteLine($"Connection state: {e.Value}"); //Battery controller.Battery.ValueChanged += (s, e) => Console.WriteLine($"Battery level: {e.Value}"); //Buttons A, B, X, Y controller.A.ValueChanged += (s, e) => Console.WriteLine($"A state: {e.Value}"); controller.B.ValueChanged += (s, e) => Console.WriteLine($"B state: {e.Value}"); controller.X.ValueChanged += (s, e) => Console.WriteLine($"X state: {e.Value}"); controller.Y.ValueChanged += (s, e) => Console.WriteLine($"Y state: {e.Value}"); //Buttons Start, Back controller.Start.ValueChanged += (s, e) => Console.WriteLine($"Start state: {e.Value}"); controller.Back.ValueChanged += (s, e) => Console.WriteLine($"Back state: {e.Value}"); //Buttons D-Pad Up, Down, Left, Right controller.Up.ValueChanged += (s, e) => Console.WriteLine($"Up state: {e.Value}"); controller.Down.ValueChanged += (s, e) => Console.WriteLine($"Down state: {e.Value}"); controller.Left.ValueChanged += (s, e) => Console.WriteLine($"Left state: {e.Value}"); controller.Right.ValueChanged += (s, e) => Console.WriteLine($"Right state: {e.Value}"); //Buttons Shoulder Left, Right controller.LeftShoulder.ValueChanged += (s, e) => Console.WriteLine($"Left shoulder state: {e.Value}"); controller.RightShoulder.ValueChanged += (s, e) => Console.WriteLine($"Right shoulder state: {e.Value}"); //Buttons Thumb Left, Right controller.LeftThumbclick.ValueChanged += (s, e) => Console.WriteLine($"Left thumb state: {e.Value}"); controller.RightThumbclick.ValueChanged += (s, e) => Console.WriteLine($"Right thumb state: {e.Value}"); //Trigger Position Left, Right controller.LeftTrigger.ValueChanged += (s, e) => Console.WriteLine($"Left trigger position: {e.Value}"); controller.RightTrigger.ValueChanged += (s, e) => Console.WriteLine($"Right trigger position: {e.Value}"); //Thumb Positions Left, Right controller.LeftThumbstick.ValueChanged += (s, e) => Console.WriteLine($"Left thumb X: {e.Value.X}, Y: {e.Value.Y}"); controller.RightThumbstick.ValueChanged += (s, e) => Console.WriteLine($"Right thumb X: {e.Value.X}, Y: {e.Value.Y}"); //Rumble Left, Right controller.LeftRumble.ValueChanged += (s, e) => Console.WriteLine($"Left rumble speed: {e.Value}"); controller.RightRumble.ValueChanged += (s, e) => Console.WriteLine($"Right rumble speed: {e.Value}"); //Rumble 0.25f speed for 500 milliseconds when the A or B button is pushed controller.A.ValueChanged += (s, e) => controller.LeftRumble.Rumble(0.25f, 500); controller.B.ValueChanged += (s, e) => controller.RightRumble.Rumble(0.25f, 500); //Rumble at 1.0f speed for 1000 milliseconds when the X or Y button is pushed controller.X.ValueChanged += (s, e) => controller.LeftRumble.Rumble(1.0f, 1000); controller.Y.ValueChanged += (s, e) => controller.RightRumble.Rumble(1.0f, 1000); //Rumble at the speed of the trigger position controller.LeftTrigger.ValueChanged += (s, e) => controller.LeftRumble.Rumble(e.Value); controller.RightTrigger.ValueChanged += (s, e) => controller.RightRumble.Rumble(e.Value); //Wait on ENTER to exit... Console.ReadLine(); }
private void Pause() { XBoxController.StopPolling(); }