private void StopCommandExecute() { var motor = new Motor(); motor.Activated = false; _eventAggregator.GetEvent<ActivateMotorEvent>().Publish(motor); }
// Use this for initialization public virtual void Start () { _myTransform = transform; myPhotonView = GetComponent<PhotonView>(); myAvatar = GetComponent<Avatar>(); myMotor = GetComponent<Motor>(); myStatus = GetComponent<CharacterStatus>(); }
private void Awake() { motor = GetComponent<Motor>(); if (motor == null) { Debug.Log("Provide a motor."); } }
dynamic MotorTest(dynamic a) { var m = new Motor (); m.Port = 'D'; m.Power = 50f; m.Direction = MotorDirection.Default; m.Time = TimeSpan.FromSeconds (3); return "OK"; }
public void SetSpeed(Motor m, int speed) { if (speed<0 || speed>255) throw new ArgumentException("Speed should be between 0 and 255"); string motor = m == Motor.Right ? "r" : "l"; string cmd="speed" + motor; Send(cmd, speed.ToString()); }
/// <summary> /// Initializes a new instance of the <see cref="Vibration"/> class. /// </summary> /// <param name="targetMotor">The target motor</param> /// <param name="frequency">The motor frequency.</param> /// <param name="duration">The duration of the vibration</param> /// <param name="modifier">Frequency modifier delegate</param> public Vibration(Motor targetMotor, float frequency, float duration, Func<Vibration, float> modifier) { _targetMotor = targetMotor; _computedFrequency = _initialFrequency = frequency; _initialDuration = duration; // duration input is specified in milliseconds - so convert it to ticks _timeRemaining = (long) duration*TimeSpan.TicksPerMillisecond; _modifier = modifier; }
public MainPage() { accelerometer = Accelerometer.GetDefault(); pid = new PidController.PidController(PROPORTIONAL_GAIN, INTEGRAL_GAIN, DERIVATIVE_GAIN, 100f, 0f); pid.SetPoint = 0; motor = new Motor(0, 36, 250); this.InitializeComponent(); }
public void SetMotor(Motor motor) { if (motor != null && steering != null && motor.IsKinematic != steering.IsKinematic) { Debug.LogError((steering.IsKinematic ? "Kinematic" : "Dynamic") + " steering cannot be used with " + (motor.IsKinematic ? "Kinematic" : "Dynamic") + " motor. Steering removed."); steering = null; } this.motor = motor; }
public int ReadEncoder(Motor motor) { var buffer = new[] { (byte)Commands.ReadEncoder, (byte)motor, Constants.Unused, Constants.Unused }; _goPiGo.DirectAccess.Write(buffer); _goPiGo.DirectAccess.Read(buffer); int encoder = buffer[1] * 256 + buffer[2]; return encoder; }
private void Awake() { // get the car controller reference m_CarController = GetComponent<Motor>(); // give the random perlin a random value m_RandomPerlin = Random.value * 100; m_Rigidbody = GetComponent<Rigidbody>(); tim = transform.root.GetComponentInChildren<timer>(); }
public void SetSpeed(Motor motor, double speed) { if (speed > 1 || speed < -1) new ArgumentOutOfRangeException(nameof(speed), "Must be between -1 and 1."); if (motor != Motor.Motor1 && motor != Motor.Motor2) throw new ArgumentException(nameof(motor), "You must specify a valid motor."); if (speed == 1.0) speed = 0.99; if (speed == -1.0) speed = -0.99; this.directions[(int)motor].Write(speed < 0); this.pwms[(int)motor].Set(this.Frequency, speed < 0 ? 1 + speed : speed); }
public MotorTestViewModel(MotorTestView view) { _view = view; Motores = new ObservableCollection<MotorDto>(); Motor motor1 = new Motor(); motor1.LadoMotor = LadoMotorEnum.Esquerda; motor1.LocalizacaoMotor = LocalizacaoMotorEnum.Frente; motor1.Potencia = 0; Motor motor2 = new Motor(); motor2.LadoMotor = LadoMotorEnum.Direita; motor2.LocalizacaoMotor = LocalizacaoMotorEnum.Frente; motor2.Potencia = 0; Motor motor3 = new Motor(); motor3.LadoMotor = LadoMotorEnum.Esquerda; motor3.LocalizacaoMotor = LocalizacaoMotorEnum.Traz; motor3.Potencia = 0; Motor motor4 = new Motor(); motor4.LadoMotor = LadoMotorEnum.Direita; motor4.LocalizacaoMotor = LocalizacaoMotorEnum.Traz; motor4.Potencia = 0; Carro = new CarroRobo(); Carro.TipoComunicacao = TipoComunicacaoEnum.Serial; ComunicacaoSerial comunicacaoSerial = new ComunicacaoSerial("COM7", 9600); comunicacaoSerial.AbrirPorta(); Carro.Comunicacao = comunicacaoSerial; Carro.Motores = new List<Motor>(); Carro.Motores.Add(motor1); Carro.Motores.Add(motor2); Carro.Motores.Add(motor3); Carro.Motores.Add(motor4); MotorDto motorDto1 = new MotorDto(motor1, Carro); MotorDto motorDto2 = new MotorDto(motor2, Carro); MotorDto motorDto3 = new MotorDto(motor3, Carro); MotorDto motorDto4 = new MotorDto(motor4, Carro); Motores.Add(motorDto1); Motores.Add(motorDto2); Motores.Add(motorDto3); Motores.Add(motorDto4); }
// After all objects are initialized, Awake is called when the script // is being loaded. This occurs before any Start calls. // Use Awake instead of the constructor for initialization. public void Awake() { motor = GetComponent<Motor>(); if (motor == null) { Debug.Log("No Motor"); } pathManager = GetComponent<PathManager>(); GameObject mainCamera = GameObject.Find("Main Camera"); if (mainCamera != null) { targetedCameras = mainCamera.GetComponents<TargetedCamera>(); } targetRowsPerColumn = Mathf.Max(3, targetRowsPerColumn); }
public DetalleMotor(int Id) { InitializeComponent(); try { //Motor = General.GetEntityById<Motor>("Motor", "MotorID", Id); Motor = Datos.GetEntity<Motor>(c => c.MotorID == Id && c.Estatus); if (Motor == null) throw new EntityNotFoundException(Id.ToString(), "Motor"); MotorView = Datos.GetEntity<MotoresView>(m => m.MotorID == Id); if (Motor == null) throw new EntityNotFoundException(Id.ToString(), "MotoresView"); EsNuevo = false; } catch (Exception ex) { Util.MensajeError(ex.Message, GlobalClass.NombreApp); } }
private void MainPage_Loaded(object sender, RoutedEventArgs e) { // GPIOの初期化 RPi.gpio = GpioController.GetDefault(); if (RPi.gpio != null) { motorLeft = new Motor(23, 24); motorRight = new Motor(27, 22); /// 停止状態 motorLeft.Direction = 0; motorRight.Direction = 0; // LED led = new Led(4); led.Off(); } this.KeyLFront.PointerPressed += Key_PointerPressed; this.KeyLBack.PointerPressed += Key_PointerPressed; this.KeyRFront.PointerPressed += Key_PointerPressed; this.KeyRBack.PointerPressed += Key_PointerPressed; this.sw1.Toggled += Sw1_Toggled; // バインド _model = new DataModel(); this.DataContext = _model; }
public static string SendData(Motor? motor, string command) { if (motor == null) return ""; command = (char)(32 + (int)motor) + command; byte[] writeBuffer = command.Select(x => (byte)x).ToArray(); MessageStream.Write(writeBuffer, 0, writeBuffer.Length); System.Threading.Thread.Sleep(100); byte[] readBuffer = Enumerable.Repeat((byte)0, 50).ToArray(); int NumberOfBytes = MessageStream.Read(readBuffer, 0, readBuffer.Length); return Encoding.Default.GetString(readBuffer, 0, NumberOfBytes); }
public static void Stop(Motor motor) { string Answer = SendCommand(motor, ((char)3).ToString()); if (Answer[0] != 255) { trace.Value.TraceEvent(TraceEventType.Warning, 0, "Error during 'Stop', Error code: " + GetErrorCode(Answer[0])); } }
// Use this for initialization void Start() { this.gameObject.renderer.material.color = new Color(0.1F, 0.75F, 1F, 1F); this.gameObject.collider.material.bounciness = 0F; int n = 0; //int triggerIndex = -1; int colliderIndex = -1; colliders = this.GetComponents<Collider>(); for (int j = 0; j < colliders.Length; j++) { if (colliders[j].isTrigger == true) { n++; //triggerIndex = j; } if (colliders[j].isTrigger == false) { colliderIndex = j; } } if (n > 1) { throw new Exception("You have too many colliders jackass"); } else if (n == 0) { throw new Exception("You have no colliders wtf"); } else { //triggerCollider = colliders[triggerIndex]; actualCollider = colliders[colliderIndex]; } playerObject = GameObject.Find("Player"); playerMotor = playerObject.GetComponent<Motor>(); playerCollider = playerObject.GetComponent<SphereCollider>(); }
public static void GoToStepPosition(Motor motor, int StepPosition) { int steps = StepPosition - GetStepPosition(motor); GoXSteps(motor, steps); }
public Plane(Motor motor) : base() { VehicleMotor = motor; }
/* * This method controls the movements of the robot to scan the facelets * of any single face of the cube. */ public static void BuildFace(Face face, Motor motorA, Motor motorB, EV3ColorSensor sensor) { RGBColor[] colors = null; RGBColor color = null; Thread count = new Thread(() => colors = CountFacelets(motorA, sensor)); MoveCube.Move(motorB, MoveCube.SensorMid, 15); color = sensor.ReadRGB(); MoveCube.Move(motorB, MoveCube.SensorSide, 15); count.Start(); while (!count.IsAlive) { ; } WaitHandle handle = motorA.SpeedProfile((sbyte)100, 0, (uint)360, 0, true); handle.WaitOne(); count.Join(); MoveCube.Move(motorB, MoveCube.SensorRest, 15); char colorvalue = ' '; for (int i = 0; i < 9; i++) { switch (i) { case 0: colorvalue = getColorValue(color); face.square[1, 1] = colorvalue; break; case 1: color = colors[0]; colorvalue = getColorValue(color); face.square[2, 1] = colorvalue; break; case 3: color = colors[2]; colorvalue = getColorValue(color); face.square[1, 2] = colorvalue; break; case 5: color = colors[4]; colorvalue = getColorValue(color); face.square[0, 1] = colorvalue; break; case 7: color = colors[6]; colorvalue = getColorValue(color); face.square[1, 0] = colorvalue; break; case 2: color = colors[1]; colorvalue = getColorValue(color); face.square[2, 2] = colorvalue; break; case 4: color = colors[3]; colorvalue = getColorValue(color); face.square[0, 2] = colorvalue; break; case 6: color = colors[5]; colorvalue = getColorValue(color); face.square[0, 0] = colorvalue; break; case 8: color = colors[7]; colorvalue = getColorValue(color); face.square[2, 0] = colorvalue; break; } Console.WriteLine("Line: {0} Color: {1} RGB code: {2}", i, colorvalue, color); } }
private void Awake() { motor = GetComponent <Motor>(); materialSetter = GetComponent <MaterialSetter>(); hitEffect = GetComponent <IHitable>(); }
public override string GetMD5String() { // return motor md5 because this analysis actually has no config return(Motor.GetMD5String()); }
public ActionResult Salvar(Motor obj) { new MotorDAO().Inserir(obj); return(RedirectToAction("Index", "Motor")); }
public override void Execute() { Motor.ShootBall(Force); }
static void WriteMotor(Motor motor) { Console.WriteLine($"1-){motor.Model}\n2-){motor.Color}\n3-){motor.Year}\n4-){motor.Price}"); Console.ReadKey(); }
void RandomMove() { _curDistanation = Quaternion.AngleAxis(Random.Range(0f, 360f), Vector3.up) * new Vector3(_moveRadius, 0, 0) + _startPosition; Motor.MoveToPoint(_curDistanation); }
/* * This method controls the movements of the robot to position * each face of the cube to be scanned by the color sensor. */ public static char[] BuildCube(Cube cube, Motor motorA, Motor motorB, Motor motorD, EV3ColorSensor sensor) { char[] faces = new char[6]; // Position face in cube for (int j = 0; j < 6; j++) { switch (j) { case 0: BuildFace(cube.face[3], motorA, motorB, sensor); cube.face [3].TurnCWCore(); cube.face [3].TurnCWCore(); MoveCube.Move(motorD, MoveCube.GrabArm); MoveCube.Move(motorD, MoveCube.PullArm); MoveCube.Move(motorD, MoveCube.RestArm); break; case 1: BuildFace(cube.face[2], motorA, motorB, sensor); cube.face [2].TurnCWCore(); MoveCube.Move(motorD, MoveCube.GrabArm); MoveCube.Move(motorD, MoveCube.PullArm); MoveCube.Move(motorD, MoveCube.RestArm); break; case 2: BuildFace(cube.face[1], motorA, motorB, sensor); MoveCube.MoveRel(motorA, MoveCube.CCW90); MoveCube.Move(motorD, MoveCube.GrabArm); MoveCube.Move(motorD, MoveCube.PullArm); MoveCube.Move(motorD, MoveCube.RestArm); break; case 3: BuildFace(cube.face[0], motorA, motorB, sensor); cube.face [0].TurnCCWCore(); MoveCube.MoveRel(motorA, MoveCube.CW90); MoveCube.Move(motorD, MoveCube.GrabArm); MoveCube.Move(motorD, MoveCube.PullArm); MoveCube.Move(motorD, MoveCube.RestArm); break; case 4: BuildFace(cube.face [4], motorA, motorB, sensor); MoveCube.Move(motorD, MoveCube.GrabArm); MoveCube.Move(motorD, MoveCube.PullArm); MoveCube.Move(motorD, MoveCube.RestArm); break; case 5: BuildFace(cube.face [5], motorA, motorB, sensor); break; } } for (int i = 0; i < 6; i++) { faces [i] = cube.face [i].square [1, 1]; } return(faces); }
// forcefully build fem file public void buildFEMM() { FEMM.CloseFemm(); Motor.BuildFEMModel(CurrentFEMMFile); FEMM.CloseFemm(); }
// load /// <summary>Loads a file into an instance of the Train class.</summary> /// <param name="FileName">The train.dat file to load.</param> /// <returns>An instance of the Train class.</returns> internal static Train Load(string FileName) { Train t = new Train(); t.Pressure.BrakePipeNormalPressure = 0.0; System.Globalization.CultureInfo Culture = System.Globalization.CultureInfo.InvariantCulture; string[] Lines = System.IO.File.ReadAllLines(FileName, new System.Text.UTF8Encoding()); for (int i = 0; i < Lines.Length; i++) { int j = Lines[i].IndexOf(';'); if (j >= 0) { Lines[i] = Lines[i].Substring(0, j).Trim(); } else { Lines[i] = Lines[i].Trim(); } } bool ver1220000 = false; for (int i = 0; i < Lines.Length; i++) { if (Lines[i].Length != 0) { string s = Lines[i].ToLowerInvariant(); if (s == "bve1220000") { ver1220000 = true; } else if (s != "bve2000000" & s != "openbve") { MessageBox.Show("The format of the train.dat is not recognized.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } break; } } for (int i = 0; i < Lines.Length; i++) { int n = 0; switch (Lines[i].ToLowerInvariant()) { case "#acceleration": i++; while (i < Lines.Length && !Lines[i].StartsWith("#", StringComparison.InvariantCultureIgnoreCase)) { if (n == t.Acceleration.Entries.Length) { Array.Resize<Acceleration.Entry>(ref t.Acceleration.Entries, t.Acceleration.Entries.Length << 1); } string u = Lines[i] + ","; int m = 0; while (true) { int j = u.IndexOf(','); if (j == -1) break; string s = u.Substring(0, j).Trim(); u = u.Substring(j + 1); double a; if (double.TryParse(s, System.Globalization.NumberStyles.Float, Culture, out a)) { switch (m) { case 0: t.Acceleration.Entries[n].a0 = Math.Max(a, 0.0); break; case 1: t.Acceleration.Entries[n].a1 = Math.Max(a, 0.0); break; case 2: t.Acceleration.Entries[n].v1 = Math.Max(a, 0.0); break; case 3: t.Acceleration.Entries[n].v2 = Math.Max(a, 0.0); if (t.Acceleration.Entries[n].v2 < t.Acceleration.Entries[n].v1) { double x = t.Acceleration.Entries[n].v1; t.Acceleration.Entries[n].v1 = t.Acceleration.Entries[n].v2; t.Acceleration.Entries[n].v2 = x; } break; case 4: if (ver1220000) { if (a <= 0.0) { t.Acceleration.Entries[n].e = 1.0; } else { const double c = 1.23315173118822; t.Acceleration.Entries[n].e = 1.0 - Math.Log(a) * t.Acceleration.Entries[n].v2 * c; if (t.Acceleration.Entries[n].e > 4.0) { t.Acceleration.Entries[n].e = 4.0; } } } else { t.Acceleration.Entries[n].e = a; } break; } } m++; } i++; n++; } Array.Resize<Acceleration.Entry>(ref t.Acceleration.Entries, n); i--; break; case "#performance": case "#deceleration": i++; while (i < Lines.Length && !Lines[i].StartsWith("#", StringComparison.InvariantCultureIgnoreCase)) { double a; if (double.TryParse(Lines[i], System.Globalization.NumberStyles.Float, Culture, out a)) { switch (n) { case 0: if (a >= 0.0) t.Performance.Deceleration = a; break; case 1: if (a >= 0.0) t.Performance.CoefficientOfStaticFriction = a; break; case 3: if (a >= 0.0) t.Performance.CoefficientOfRollingResistance = a; break; case 4: if (a >= 0.0) t.Performance.AerodynamicDragCoefficient = a; break; } } i++; n++; } i--; break; case "#delay": i++; while (i < Lines.Length && !Lines[i].StartsWith("#", StringComparison.InvariantCultureIgnoreCase)) { double a; if (double.TryParse(Lines[i], System.Globalization.NumberStyles.Float, Culture, out a)) { switch (n) { case 0: if(a >= 0.0) t.Delay.DelayPowerUp = a; break; case 1: if(a >= 0.0) t.Delay.DelayPowerDown = a; break; case 2: if(a >= 0.0) t.Delay.DelayBrakeUp = a; break; case 3: if(a >= 0.0) t.Delay.DelayBrakeDown = a; break; } } i++; n++; } i--; break; case "#move": i++; while (i < Lines.Length && !Lines[i].StartsWith("#", StringComparison.InvariantCultureIgnoreCase)) { double a; if (double.TryParse(Lines[i], System.Globalization.NumberStyles.Float, Culture, out a)) { switch (n) { case 0: if(a >= 0.0) t.Move.JerkPowerUp = a; break; case 1: if(a >= 0.0) t.Move.JerkPowerDown = a; break; case 2: if(a >= 0.0) t.Move.JerkBrakeUp = a; break; case 3: if(a >= 0.0) t.Move.JerkBrakeDown = a; break; case 4: if(a >= 0.0) t.Move.BrakeCylinderUp = a; break; case 5: if(a >= 0.0) t.Move.BrakeCylinderDown = a; break; } } i++; n++; } i--; break; case "#brake": i++; while (i < Lines.Length && !Lines[i].StartsWith("#", StringComparison.InvariantCultureIgnoreCase)) { double a; if (double.TryParse(Lines[i], System.Globalization.NumberStyles.Float, Culture, out a)) { int b = (int)Math.Round(a); switch (n) { case 0: if (b >= 0 & b <= 2) t.Brake.BrakeType = (Brake.BrakeTypes)b; break; case 1: if (b >= 0 & b <= 2) t.Brake.BrakeControlSystem = (Brake.BrakeControlSystems)b; break; case 2: if (a >= 0.0) t.Brake.BrakeControlSpeed = a; break; } } i++; n++; } i--; break; case "#pressure": i++; while (i < Lines.Length && !Lines[i].StartsWith("#", StringComparison.InvariantCultureIgnoreCase)) { double a; if (double.TryParse(Lines[i], System.Globalization.NumberStyles.Float, Culture, out a)) { switch (n) { case 0: if (a > 0.0) t.Pressure.BrakeCylinderServiceMaximumPressure = a; break; case 1: if (a > 0.0) t.Pressure.BrakeCylinderEmergencyMaximumPressure = a; break; case 2: if (a > 0.0) t.Pressure.MainReservoirMinimumPressure = a; break; case 3: if (a > 0.0) t.Pressure.MainReservoirMaximumPressure = a; break; case 4: if (a > 0.0) t.Pressure.BrakePipeNormalPressure = a; break; } } i++; n++; } i--; break; case "#handle": i++; while (i < Lines.Length && !Lines[i].StartsWith("#", StringComparison.InvariantCultureIgnoreCase)) { double a; if (double.TryParse(Lines[i], System.Globalization.NumberStyles.Float, Culture, out a)) { int b = (int)Math.Round(a); switch (n) { case 0: if (b == 0 | b == 1) t.Handle.HandleType = (Handle.HandleTypes)b; break; case 1: if (b > 0) t.Handle.PowerNotches = b; break; case 2: if (b > 0) t.Handle.BrakeNotches = b; break; case 3: if (b >= 0) t.Handle.PowerNotchReduceSteps = b; break; } } i++; n++; } i--; break; case "#cockpit": case "#cab": i++; while (i < Lines.Length && !Lines[i].StartsWith("#", StringComparison.InvariantCultureIgnoreCase)) { double a; if (double.TryParse(Lines[i], System.Globalization.NumberStyles.Float, Culture, out a)) { switch (n) { case 0: t.Cab.X = a; break; case 1: t.Cab.Y = a; break; case 2: t.Cab.Z = a; break; case 3: t.Cab.DriverCar = (int)Math.Round(a); break; } } i++; n++; } i--; break; case "#car": i++; while (i < Lines.Length && !Lines[i].StartsWith("#", StringComparison.InvariantCultureIgnoreCase)) { double a; if (double.TryParse(Lines[i], System.Globalization.NumberStyles.Float, Culture, out a)) { int b = (int)Math.Round(a); switch (n) { case 0: if (a > 0.0) t.Car.MotorCarMass = a; break; case 1: if (b >= 1) t.Car.NumberOfMotorCars = b; break; case 2: if (a > 0.0) t.Car.TrailerCarMass = a; break; case 3: if (b >= 0) t.Car.NumberOfTrailerCars = b; break; case 4: if (b > 0.0) t.Car.LengthOfACar = a; break; case 5: t.Car.FrontCarIsAMotorCar = a == 1.0; break; case 6: if (a > 0.0) t.Car.WidthOfACar = a; break; case 7: if (a > 0.0) t.Car.HeightOfACar = a; break; case 8: t.Car.CenterOfGravityHeight = a; break; case 9: if (a > 0.0) t.Car.ExposedFrontalArea = a; break; case 10: if (a > 0.0) t.Car.UnexposedFrontalArea = a; break; } } i++; n++; } i--; break; case "#device": i++; while (i < Lines.Length && !Lines[i].StartsWith("#", StringComparison.InvariantCultureIgnoreCase)) { double a; if (double.TryParse(Lines[i], System.Globalization.NumberStyles.Float, Culture, out a)) { int b = (int)Math.Round(a); switch (n) { case 0: if (b >= -1 & b <= 1) t.Device.Ats = (Device.AtsModes)b; break; case 1: if (b >= 0 & b <= 2) t.Device.Atc = (Device.AtcModes)b; break; case 2: t.Device.Eb = a == 1.0; break; case 3: t.Device.ConstSpeed = a == 1.0; break; case 4: t.Device.HoldBrake = a == 1.0; break; case 5: if (b >= -1 & b <= 3) t.Device.ReAdhesionDevice = (Device.ReAdhesionDevices)b; break; case 6: t.Device.LoadCompensatingDevice = a; break; case 7: if (b >= 0 & b <= 2) t.Device.PassAlarm = (Device.PassAlarmModes)b; break; case 8: if (b >= 0 & b <= 2) t.Device.DoorOpenMode = (Device.DoorModes)b; break; case 9: if (b >= 0 & b <= 2) t.Device.DoorCloseMode = (Device.DoorModes)b; break; } } i++; n++; } i--; break; case "#motor_p1": case "#motor_p2": case "#motor_b1": case "#motor_b2": { string section = Lines[i].ToLowerInvariant(); i++; Motor m = new Motor(); while (i < Lines.Length && !Lines[i].StartsWith("#", StringComparison.InvariantCultureIgnoreCase)) { if (n == m.Entries.Length) { Array.Resize<Motor.Entry>(ref m.Entries, m.Entries.Length << 1); } string u = Lines[i] + ","; int k = 0; while (true) { int j = u.IndexOf(','); if (j == -1) break; string s = u.Substring(0, j).Trim(); u = u.Substring(j + 1); double a; if (double.TryParse(s, System.Globalization.NumberStyles.Float, Culture, out a)) { int b = (int)Math.Round(a); switch (k) { case 0: m.Entries[n].SoundIndex = b >= 0 ? b : -1; break; case 1: m.Entries[n].Pitch = Math.Max(a, 0.0); break; case 2: m.Entries[n].Volume = Math.Max(a, 0.0); break; } } k++; } i++; n++; } Array.Resize<Motor.Entry>(ref m.Entries, n); i--; switch (section) { case "#motor_p1": t.MotorP1 = m; break; case "#motor_p2": t.MotorP2 = m; break; case "#motor_b1": t.MotorB1 = m; break; case "#motor_b2": t.MotorB2 = m; break; } } break; } } if (t.Pressure.BrakePipeNormalPressure <= 0.0) { if (t.Brake.BrakeType == Brake.BrakeTypes.AutomaticAirBrake) { t.Pressure.BrakePipeNormalPressure = t.Pressure.BrakeCylinderEmergencyMaximumPressure + 0.75 * (t.Pressure.MainReservoirMinimumPressure - t.Pressure.BrakeCylinderEmergencyMaximumPressure); if (t.Pressure.BrakePipeNormalPressure > t.Pressure.MainReservoirMinimumPressure) { t.Pressure.BrakePipeNormalPressure = t.Pressure.MainReservoirMinimumPressure; } } else { if (t.Pressure.BrakeCylinderEmergencyMaximumPressure < 480000.0 & t.Pressure.MainReservoirMinimumPressure > 500000.0) { t.Pressure.BrakePipeNormalPressure = 490000.0; } else { t.Pressure.BrakePipeNormalPressure = t.Pressure.BrakeCylinderEmergencyMaximumPressure + 0.75 * (t.Pressure.MainReservoirMinimumPressure - t.Pressure.BrakeCylinderEmergencyMaximumPressure); } } } if (t.Brake.BrakeType == Brake.BrakeTypes.AutomaticAirBrake) { t.Device.HoldBrake = false; } if (t.Device.HoldBrake & t.Handle.BrakeNotches <= 0) { t.Handle.BrakeNotches = 1; } if (t.Cab.DriverCar < 0 | t.Cab.DriverCar >= t.Car.NumberOfMotorCars + t.Car.NumberOfTrailerCars) { t.Cab.DriverCar = 0; } return t; }
//Where the damage is actually applied void DamageApplication(Vector3 damagePoint, Vector3 damageForce, float damageForceLimit, Vector3 surfaceNormal, ContactPoint colPoint, bool useContactPoint) { float colMag = Mathf.Min(damageForce.magnitude, maxCollisionMagnitude) * (1 - strength) * damageFactor; //Magnitude of collision float clampedColMag = Mathf.Pow(Mathf.Sqrt(colMag) * 0.5f, 1.5f); //Clamped magnitude of collision Vector3 clampedVel = Vector3.ClampMagnitude(damageForce, damageForceLimit); //Clamped velocity of collision Vector3 normalizedVel = damageForce.normalized; float surfaceDot; //Dot production of collision velocity and surface normal float massFactor = 1; //Multiplier for damage based on mass of other rigidbody Transform curDamagePart; float damagePartFactor; MeshFilter curDamageMesh; Transform curDisplacePart; Transform seamKeeper = null; //Transform for maintaining seams on shattered parts Vector3 seamLocalPoint; Vector3 vertProjection; Vector3 translation; Vector3 clampedTranslation; Vector3 localPos; float vertDist; float distClamp; DetachablePart detachedPart; Suspension damagedSus; //Get mass factor for multiplying damage if (useContactPoint) { damagePoint = colPoint.point; surfaceNormal = colPoint.normal; if (colPoint.otherCollider.attachedRigidbody) { massFactor = Mathf.Clamp01(colPoint.otherCollider.attachedRigidbody.mass / rb.mass); } } surfaceDot = Mathf.Clamp01(Vector3.Dot(surfaceNormal, normalizedVel)) * (Vector3.Dot((tr.position - damagePoint).normalized, normalizedVel) + 1) * 0.5f; //Damage damageable parts for (int i = 0; i < damageParts.Length; i++) { curDamagePart = damageParts[i]; damagePartFactor = colMag * surfaceDot * massFactor * Mathf.Min(clampedColMag * 0.01f, (clampedColMag * 0.001f) / Mathf.Pow(Vector3.Distance(curDamagePart.position, damagePoint), clampedColMag)); //Damage motors Motor damagedMotor = curDamagePart.GetComponent <Motor>(); if (damagedMotor) { damagedMotor.health -= damagePartFactor * (1 - damagedMotor.strength); } //Damage transmissions Transmission damagedTransmission = curDamagePart.GetComponent <Transmission>(); if (damagedTransmission) { damagedTransmission.health -= damagePartFactor * (1 - damagedTransmission.strength); } } //Deform meshes for (int i = 0; i < deformMeshes.Length; i++) { curDamageMesh = deformMeshes[i]; localPos = curDamageMesh.transform.InverseTransformPoint(damagePoint); translation = curDamageMesh.transform.InverseTransformDirection(clampedVel); clampedTranslation = Vector3.ClampMagnitude(translation, clampedColMag); //Shatter parts that can shatter ShatterPart shattered = curDamageMesh.GetComponent <ShatterPart>(); if (shattered) { seamKeeper = shattered.seamKeeper; if (Vector3.Distance(curDamageMesh.transform.position, damagePoint) < colMag * surfaceDot * 0.1f * massFactor && colMag * surfaceDot * massFactor > shattered.breakForce) { shattered.Shatter(); } } //Actual deformation if (translation.sqrMagnitude > 0 && strength < 1) { for (int j = 0; j < meshVertices[i].verts.Length; j++) { vertDist = Vector3.Distance(meshVertices[i].verts[j], localPos); distClamp = (clampedColMag * 0.001f) / Mathf.Pow(vertDist, clampedColMag); if (distClamp > 0.001f) { damagedMeshes[i] = true; if (seamKeeper == null || seamlessDeform) { vertProjection = seamlessDeform ? Vector3.zero : Vector3.Project(normalizedVel, meshVertices[i].verts[j]); meshVertices[i].verts[j] += (clampedTranslation - vertProjection * (usePerlinNoise ? 1 + Mathf.PerlinNoise(meshVertices[i].verts[j].x * 100, meshVertices[i].verts[j].y * 100) : 1)) * surfaceDot * Mathf.Min(clampedColMag * 0.01f, distClamp) * massFactor; } else { seamLocalPoint = seamKeeper.InverseTransformPoint(curDamageMesh.transform.TransformPoint(meshVertices[i].verts[j])); meshVertices[i].verts[j] += (clampedTranslation - Vector3.Project(normalizedVel, seamLocalPoint) * (usePerlinNoise ? 1 + Mathf.PerlinNoise(seamLocalPoint.x * 100, seamLocalPoint.y * 100) : 1)) * surfaceDot * Mathf.Min(clampedColMag * 0.01f, distClamp) * massFactor; } } } } } seamKeeper = null; //Deform mesh colliders for (int i = 0; i < deformColliders.Length; i++) { localPos = deformColliders[i].transform.InverseTransformPoint(damagePoint); translation = deformColliders[i].transform.InverseTransformDirection(clampedVel); clampedTranslation = Vector3.ClampMagnitude(translation, clampedColMag); if (translation.sqrMagnitude > 0 && strength < 1) { for (int j = 0; j < colVertices[i].verts.Length; j++) { vertDist = Vector3.Distance(colVertices[i].verts[j], localPos); distClamp = (clampedColMag * 0.001f) / Mathf.Pow(vertDist, clampedColMag); if (distClamp > 0.001f) { damagedCols[i] = true; colVertices[i].verts[j] += clampedTranslation * surfaceDot * Mathf.Min(clampedColMag * 0.01f, distClamp) * massFactor; } } } } //Displace parts for (int i = 0; i < displaceParts.Length; i++) { curDisplacePart = displaceParts[i]; translation = clampedVel; clampedTranslation = Vector3.ClampMagnitude(translation, clampedColMag); if (translation.sqrMagnitude > 0 && strength < 1) { vertDist = Vector3.Distance(curDisplacePart.position, damagePoint); distClamp = (clampedColMag * 0.001f) / Mathf.Pow(vertDist, clampedColMag); if (distClamp > 0.001f) { curDisplacePart.position += clampedTranslation * surfaceDot * Mathf.Min(clampedColMag * 0.01f, distClamp) * massFactor; //Detach detachable parts if (curDisplacePart.GetComponent <DetachablePart>()) { detachedPart = curDisplacePart.GetComponent <DetachablePart>(); if (colMag * surfaceDot * massFactor > detachedPart.looseForce && detachedPart.looseForce >= 0) { detachedPart.initialPos = curDisplacePart.localPosition; detachedPart.Detach(true); } else if (colMag * surfaceDot * massFactor > detachedPart.breakForce) { detachedPart.Detach(false); } } //Maybe the parent of this part is what actually detaches, useful for displacing compound colliders that represent single detachable objects else if (curDisplacePart.parent.GetComponent <DetachablePart>()) { detachedPart = curDisplacePart.parent.GetComponent <DetachablePart>(); if (!detachedPart.detached) { if (colMag * surfaceDot * massFactor > detachedPart.looseForce && detachedPart.looseForce >= 0) { detachedPart.initialPos = curDisplacePart.parent.localPosition; detachedPart.Detach(true); } else if (colMag * surfaceDot * massFactor > detachedPart.breakForce) { detachedPart.Detach(false); } } else if (detachedPart.hinge) { detachedPart.displacedAnchor += curDisplacePart.parent.InverseTransformDirection(clampedTranslation * surfaceDot * Mathf.Min(clampedColMag * 0.01f, distClamp) * massFactor); } } //Damage suspensions and wheels damagedSus = curDisplacePart.GetComponent <Suspension>(); if (damagedSus) { if ((!damagedSus.wheel.grounded && ignoreGroundedWheels) || !ignoreGroundedWheels) { curDisplacePart.RotateAround(damagedSus.tr.TransformPoint(damagedSus.damagePivot), Vector3.ProjectOnPlane(damagePoint - curDisplacePart.position, -translation.normalized), clampedColMag * surfaceDot * distClamp * 20 * massFactor); damagedSus.wheel.damage += clampedColMag * surfaceDot * distClamp * 10 * massFactor; if (clampedColMag * surfaceDot * distClamp * 10 * massFactor > damagedSus.jamForce) { damagedSus.jammed = true; } if (clampedColMag * surfaceDot * distClamp * 10 * massFactor > damagedSus.wheel.detachForce) { damagedSus.wheel.Detach(); } foreach (SuspensionPart curPart in damagedSus.movingParts) { if (curPart.connectObj && !curPart.isHub && !curPart.solidAxle) { if (!curPart.connectObj.GetComponent <SuspensionPart>()) { curPart.connectPoint += curPart.connectObj.InverseTransformDirection(clampedTranslation * surfaceDot * Mathf.Min(clampedColMag * 0.01f, distClamp) * massFactor); } } } } } //Damage hover wheels HoverWheel damagedHoverWheel = curDisplacePart.GetComponent <HoverWheel>(); if (damagedHoverWheel) { if ((!damagedHoverWheel.grounded && ignoreGroundedWheels) || !ignoreGroundedWheels) { if (clampedColMag * surfaceDot * distClamp * 10 * massFactor > damagedHoverWheel.detachForce) { damagedHoverWheel.Detach(); } } } } } } }
/// <summary> /// Reset motor's position. /// </summary> /// /// <param name="motor">Motor to reset.</param> /// <param name="relative">Specifies if relative (to last movement) or absolute motor's /// position should reset.</param> /// <param name="waitReply">Wait reply from NXT (safer option) or not (faster option).</param> /// /// <returns>Returns <b>true</b> if command was executed successfully or <b>false</b> otherwise.</returns> /// public bool ResetMotorPosition( Motor motor, bool relative, bool waitReply ) { byte[] command = new byte[4]; // prepare message command[0] = (byte) ( ( waitReply ) ? NXTCommandType.DirectCommand : NXTCommandType.DirectCommandWithoutReply ); command[1] = (byte) NXTDirectCommand.ResetMotorPosition; command[2] = (byte) motor; command[3] = (byte) ( ( relative ) ? 0xFF : 0x00 ); // reset relative or absolute position return SendCommand( command, new byte[3] ); }
protected override void DoMeasureData(TransientStepArgs args, FEMM femm) { // measure base data base.DoMeasureData(args, femm); // measure only one, not all those for skew angle if (args.skewAngleAdded != 0) { return; } // measure loss // other processes need to wait for the first to finish this block of code lock (lock_first) { if (allElements == null) { Stator3Phase stator = Motor.Stator as Stator3Phase; int rotor_steel_group = -1; int rotor_magnet_group = -1; double rotor_Keddy = 0; double rotor_Kh = 0; double rotor_ro = 0; if (Motor.Rotor is SPMRotor) { var rotor = Motor.Rotor as SPMRotor; rotor_steel_group = rotor.Group_BlockLabel_Steel; rotor_magnet_group = rotor.Group_BlockLabel_Magnet_Air; rotor_Keddy = rotor.P_eddy_10_50; rotor_Kh = rotor.P_hysteresis_10_50; rotor_ro = rotor.Steel_ro; } else if (Motor.Rotor is VPMRotor) { var rotor = Motor.Rotor as VPMRotor; rotor_steel_group = rotor.Group_BlockLabel_Steel; rotor_magnet_group = rotor.Group_BlockLabel_Magnet_Air; rotor_Keddy = rotor.P_eddy_10_50; rotor_Kh = rotor.P_hysteresis_10_50; rotor_ro = rotor.Steel_ro; } List <PointD> nodes = new List <PointD>(); int n = femm.mo_numnodes(); for (int i = 1; i <= n; i++) { var p = femm.mo_getnode(i); nodes.Add(p); } allElements = new List <FEMM.Element>(); n = femm.mo_numelements(); for (int i = 1; i <= n; i++) // start from 1 { var e = femm.mo_getelement(i); for (int j = 0; j < e.nodes.Length; j++) { e.nodes[j]--;//convert from 1-base index to 0-base index } allElements.Add(e); } var statorElements = allElements.Where(e => e.group == stator.Group_BlockLabel_Steel).ToList(); statorLoss = new CoreLoss(this, nodes, statorElements); statorLoss.name = "Stator_"; statorLoss.ro = stator.Steel_ro; statorLoss.Keddy = stator.P_eddy_10_50; statorLoss.Kh = stator.P_hysteresis_10_50; var rotorElements = allElements.Where(e => e.group == rotor_steel_group || e.group == rotor_magnet_group).ToList(); // convert coordinates of elements back to 0 degree rotor angle // hashset of node to mark rotated node HashSet <int> rotatedNodes = new HashSet <int>(); // angle to rotate back double a = Motor.GetNormalizedRotorAngle(args.RotorAngle) * Math.PI / 180; // for each element foreach (var e in rotorElements) { double xx = e.center.X; double yy = e.center.Y; e.center.X = xx * Math.Cos(-a) - yy * Math.Sin(-a); e.center.Y = xx * Math.Sin(-a) + yy * Math.Cos(-a); // rotate nodes of this element also for (int i = 0; i < e.nodes.Length; i++) { int node_index = e.nodes[i]; // if already rotated if (rotatedNodes.Contains(node_index)) { continue; } xx = nodes[node_index].X; yy = nodes[node_index].Y; nodes[node_index] = new PointD() { X = xx * Math.Cos(-a) - yy * Math.Sin(-a), Y = xx * Math.Sin(-a) + yy * Math.Cos(-a), }; // mark as rotated rotatedNodes.Add(node_index); } } rotorLoss = new CoreLoss(this, nodes, rotorElements); rotorLoss.name = "Rotor_"; rotorLoss.isRotor = true; rotorLoss.Keddy = rotor_Keddy; rotorLoss.Kh = rotor_Kh; rotorLoss.ro = rotor_ro; } }// lock(..) statorLoss.GatherData(args, femm); rotorLoss.GatherData(args, femm); }
/// <summary> /// Set motor state. /// </summary> /// /// <param name="motor">Motor to set state for.</param> /// <param name="state">Motor's state to set.</param> /// <param name="waitReply">Wait reply from NXT (safer option) or not (faster option).</param> /// /// <returns>Returns <b>true</b> if command was executed successfully or <b>false</b> otherwise.</returns> /// public bool SetMotorState( Motor motor, MotorState state, bool waitReply ) { byte[] command = new byte[12]; // prepare message command[0] = (byte) ( ( waitReply ) ? NXTCommandType.DirectCommand : NXTCommandType.DirectCommandWithoutReply ); command[1] = (byte) NXTDirectCommand.SetOutputState; command[2] = (byte) motor; command[3] = (byte) state.Power; command[4] = (byte) state.Mode; command[5] = (byte) state.Regulation; command[6] = (byte) state.TurnRatio; command[7] = (byte) state.RunState; // tacho limit command[8] = (byte) ( state.TachoLimit & 0xFF ); command[9] = (byte) ( ( state.TachoLimit >> 8 ) & 0xFF ); command[10] = (byte) ( ( state.TachoLimit >> 16 ) & 0xFF ); command[11] = (byte) ( ( state.TachoLimit >> 24 ) & 0xFF ); return SendCommand( command, new byte[3] ); }
private void Start() { motor = GetComponent <Motor>(); anim = GetComponent <ActorAnimation>(); }
/// <summary> /// Returns true if CarInfo instances are equal /// </summary> /// <param name="other">Instance of CarInfo to be compared</param> /// <returns>Boolean</returns> public bool Equals(CarInfo other) { if (ReferenceEquals(null, other)) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return (( Model == other.Model || Model != null && Model.Equals(other.Model) ) && ( Year == other.Year || Year != null && Year.Equals(other.Year) ) && ( Price == other.Price || Price != null && Price.Equals(other.Price) ) && ( SerialNumber == other.SerialNumber || SerialNumber != null && SerialNumber.Equals(other.SerialNumber) ) && ( SoldDateUtc == other.SoldDateUtc || SoldDateUtc != null && SoldDateUtc.Equals(other.SoldDateUtc) ) && ( Comment == other.Comment || Comment != null && Comment.Equals(other.Comment) ) && ( Transmission == other.Transmission || Transmission != null && Transmission.Equals(other.Transmission) ) && ( Motor == other.Motor || Motor != null && Motor.Equals(other.Motor) ) && ( GarageId == other.GarageId || GarageId != null && GarageId.Equals(other.GarageId) ) && ( SellerId == other.SellerId || SellerId != null && SellerId.Equals(other.SellerId) )); }
/// <summary> /// Constructor de un SUV /// </summary> /// <param name="modelo"></param> /// <param name="color"></param> /// <param name="cilindrada"></param> /// <param name="tipoAutomovil"></param> /// <param name="tipoModelo"></param> /// <param name="motor"></param> public Suv(string modelo, string color, int cilindrada, Tipo tipoAutomovil, TipoModelo tipoModelo, Motor motor) : base(modelo, color, cilindrada, tipoAutomovil, tipoModelo, motor) { }
void Start() { myMotor = GetComponent <Motor>(); myCollider = GetComponent <Collider2D>(); }
/// <summary> /// (Called by KinematicCharacterMotor during its update cycle) /// This is where you tell your character what its velocity should be right now. /// This is the ONLY place where you can set the character's velocity /// </summary> public override void UpdateVelocity(ref Vector3 currentVelocity, float deltaTime) { Vector3 targetMovementVelocity = Vector3.zero; if (Motor.GroundingStatus.IsStableOnGround) { // Reorient velocity on slope currentVelocity = Motor.GetDirectionTangentToSurface(currentVelocity, Motor.GroundingStatus.GroundNormal) * currentVelocity.magnitude; // Calculate target velocity Vector3 inputRight = Vector3.Cross(_moveInputVector, Motor.CharacterUp); Vector3 reorientedInput = Vector3.Cross(Motor.GroundingStatus.GroundNormal, inputRight).normalized *_moveInputVector.magnitude; targetMovementVelocity = reorientedInput * MaxStableMoveSpeed; // Smooth movement Velocity currentVelocity = Vector3.Lerp(currentVelocity, targetMovementVelocity, 1 - Mathf.Exp(-StableMovementSharpness * deltaTime)); } else { // Add move input if (_moveInputVector.sqrMagnitude > 0f) { targetMovementVelocity = _moveInputVector * MaxAirMoveSpeed; // Prevent climbing on un-stable slopes with air movement if (Motor.GroundingStatus.FoundAnyGround) { Vector3 perpenticularObstructionNormal = Vector3.Cross(Vector3.Cross(Motor.CharacterUp, Motor.GroundingStatus.GroundNormal), Motor.CharacterUp).normalized; targetMovementVelocity = Vector3.ProjectOnPlane(targetMovementVelocity, perpenticularObstructionNormal); } Vector3 velocityDiff = Vector3.ProjectOnPlane(targetMovementVelocity - currentVelocity, Gravity); currentVelocity += velocityDiff * AirAccelerationSpeed * deltaTime; } // Gravity currentVelocity += Gravity * deltaTime; // Drag currentVelocity *= (1f / (1f + (Drag * deltaTime))); } // Handle jumping { _jumpedThisFrame = false; _timeSinceJumpRequested += deltaTime; if (_jumpRequested) { // Handle double jump if (AllowDoubleJump) { if (_jumpConsumed && !_doubleJumpConsumed && (AllowJumpingWhenSliding ? !Motor.GroundingStatus.FoundAnyGround : !Motor.GroundingStatus.IsStableOnGround)) { Motor.ForceUnground(); // Add to the return velocity and reset jump state currentVelocity += (Motor.CharacterUp * JumpSpeed) - Vector3.Project(currentVelocity, Motor.CharacterUp); _jumpRequested = false; _doubleJumpConsumed = true; _jumpedThisFrame = true; } } // See if we actually are allowed to jump if (_canWallJump || (!_jumpConsumed && ((AllowJumpingWhenSliding ? Motor.GroundingStatus.FoundAnyGround : Motor.GroundingStatus.IsStableOnGround) || _timeSinceLastAbleToJump <= JumpPostGroundingGraceTime))) { // Calculate jump direction before ungrounding Vector3 jumpDirection = Motor.CharacterUp; if (_canWallJump) { jumpDirection = _wallJumpNormal; } else if (Motor.GroundingStatus.FoundAnyGround && !Motor.GroundingStatus.IsStableOnGround) { jumpDirection = Motor.GroundingStatus.GroundNormal; } // Makes the character skip ground probing/snapping on its next update. // If this line weren't here, the character would remain snapped to the ground when trying to jump. Try commenting this line out and see. Motor.ForceUnground(); // Add to the return velocity and reset jump state currentVelocity += (jumpDirection * JumpSpeed) - Vector3.Project(currentVelocity, Motor.CharacterUp); _jumpRequested = false; _jumpConsumed = true; _jumpedThisFrame = true; } } // Reset wall jump _canWallJump = false; } // Take into account additive velocity if (_internalVelocityAdd.sqrMagnitude > 0f) { currentVelocity += _internalVelocityAdd; _internalVelocityAdd = Vector3.zero; } }
public RobotController(RaspberryPi pi) { _drive = new Motor(pi.Pin11, pi.Pin13); _flag = new Motor(pi.Pin33, pi.Pin35); _buzzer = pi.Pin40; }
public void RowSelect(Motor selectedMotor) { var windowManager = IoC.Get <IWindowManager>(); windowManager.ShowWindow(new MotorBOMViewModel(selectedMotor, $"{selectedMotor.FullDescription}{Environment.NewLine}Bill Of Material."), null, null); }
/// <summary> /// Use this constructor when using multi transactional operations. /// </summary> /// <param name="closeConnectionWhenFinish">If true, close the connection after any CRUD operation</param> /// <param name="motor">Motor class from caller</param> public EmployeesBsn(bool closeConnectionWhenFinish, Motor motor) { this.motor = motor; this.EmployeesDAO = new EmployeesDAO(motor); this.closeConnectionWhenFinish = closeConnectionWhenFinish; }
/// <summary> /// Default constructor. /// </summary> /// <param name="motor">Database context class. Performs the database access operations.</param> public TagDAO(Motor motor) { this.motor = motor; GenericDAO d = new GenericDAO(motor); }
private int get_motormax() { var motormax = 8; var enable = MainV2.comPort.MAV.param.ContainsKey("FRAME") || MainV2.comPort.MAV.param.ContainsKey("Q_FRAME_TYPE"); if (!enable) { Enabled = false; return(motormax); } MAVLink.MAV_TYPE type = MAVLink.MAV_TYPE.QUADROTOR; int frame_type = 0; // + frame if (MainV2.comPort.MAV.param.ContainsKey("Q_FRAME_CLASS")) { var value = (int)MainV2.comPort.MAV.param["Q_FRAME_CLASS"].Value; switch (value) { case 0: type = MAVLink.MAV_TYPE.QUADROTOR; break; case 1: type = MAVLink.MAV_TYPE.HEXAROTOR; break; case 2: type = MAVLink.MAV_TYPE.OCTOROTOR; break; case 3: type = MAVLink.MAV_TYPE.OCTOROTOR; break; } frame_type = (int)MainV2.comPort.MAV.param["Q_FRAME_TYPE"].Value; } else { type = MainV2.comPort.MAV.aptype; frame_type = (int)MainV2.comPort.MAV.param["FRAME"].Value; } var motors = new Motor[0]; if (type == MAVLink.MAV_TYPE.TRICOPTER) { motormax = 4; motors = Motor.build_motors(MAVLink.MAV_TYPE.TRICOPTER, frame_type); } else if (type == MAVLink.MAV_TYPE.QUADROTOR) { motormax = 4; motors = Motor.build_motors(MAVLink.MAV_TYPE.QUADROTOR, frame_type); } else if (type == MAVLink.MAV_TYPE.HEXAROTOR) { motormax = 6; motors = Motor.build_motors(MAVLink.MAV_TYPE.HEXAROTOR, frame_type); } else if (type == MAVLink.MAV_TYPE.OCTOROTOR) { motormax = 8; motors = Motor.build_motors(MAVLink.MAV_TYPE.OCTOROTOR, frame_type); } else if (type == MAVLink.MAV_TYPE.HELICOPTER) { motormax = 0; } return(motormax); }
internal Train () { this.Acceleration = new Acceleration(); this.Performance = new Performance(); this.Delay = new Delay(); this.Move = new Move(); this.Brake = new Brake(); this.Pressure = new Pressure(); this.Handle = new Handle(); this.Cab = new Cab(); this.Car = new Car(); this.Device = new Device(); this.MotorP1 = new Motor(); this.MotorP2 = new Motor(); this.MotorB1 = new Motor(); this.MotorB2 = new Motor(); }
/// <summary> /// (Called by KinematicCharacterMotor during its update cycle) /// This is where you tell your character what its velocity should be right now. /// This is the ONLY place where you can set the character's velocity /// </summary> public override void UpdateVelocity(ref Vector3 currentVelocity, float deltaTime) { switch (CurrentCharacterState) { case CharacterState.Default: { Vector3 targetMovementVelocity = Vector3.zero; if (Motor.GroundingStatus.IsStableOnGround) { // Reorient velocity on slope currentVelocity = Motor.GetDirectionTangentToSurface(currentVelocity, Motor.GroundingStatus.GroundNormal) * currentVelocity.magnitude; // Calculate target velocity Vector3 inputRight = Vector3.Cross(_moveInputVector, Motor.CharacterUp); Vector3 reorientedInput = Vector3.Cross(Motor.GroundingStatus.GroundNormal, inputRight).normalized *_moveInputVector.magnitude; targetMovementVelocity = reorientedInput * MaxStableMoveSpeed; // Smooth movement Velocity currentVelocity = Vector3.Lerp(currentVelocity, targetMovementVelocity, 1 - Mathf.Exp(-StableMovementSharpness * deltaTime)); } else { // Add move input if (_moveInputVector.sqrMagnitude > 0f) { targetMovementVelocity = _moveInputVector * MaxAirMoveSpeed; // Prevent climbing on un-stable slopes with air movement if (Motor.GroundingStatus.FoundAnyGround) { Vector3 perpenticularObstructionNormal = Vector3.Cross(Vector3.Cross(Motor.CharacterUp, Motor.GroundingStatus.GroundNormal), Motor.CharacterUp).normalized; targetMovementVelocity = Vector3.ProjectOnPlane(targetMovementVelocity, perpenticularObstructionNormal); } Vector3 velocityDiff = Vector3.ProjectOnPlane(targetMovementVelocity - currentVelocity, Gravity); currentVelocity += velocityDiff * AirAccelerationSpeed * deltaTime; } // Gravity currentVelocity += Gravity * deltaTime; // Drag currentVelocity *= (1f / (1f + (Drag * deltaTime))); } // Handle jumping { _jumpedThisFrame = false; _timeSinceJumpRequested += deltaTime; if (_jumpRequested) { // Handle double jump if (AllowDoubleJump) { if (_jumpConsumed && !_doubleJumpConsumed && (AllowJumpingWhenSliding ? !Motor.GroundingStatus.FoundAnyGround : !Motor.GroundingStatus.IsStableOnGround)) { Motor.ForceUnground(); // Add to the return velocity and reset jump state currentVelocity += (Motor.CharacterUp * JumpSpeed) - Vector3.Project(currentVelocity, Motor.CharacterUp); _jumpRequested = false; _doubleJumpConsumed = true; _jumpedThisFrame = true; } } // See if we actually are allowed to jump if (_canWallJump || (!_jumpConsumed && ((AllowJumpingWhenSliding ? Motor.GroundingStatus.FoundAnyGround : Motor.GroundingStatus.IsStableOnGround) || _timeSinceLastAbleToJump <= JumpPostGroundingGraceTime))) { // Calculate jump direction before ungrounding Vector3 jumpDirection = Motor.CharacterUp; if (_canWallJump) { jumpDirection = _wallJumpNormal; } else if (Motor.GroundingStatus.FoundAnyGround && !Motor.GroundingStatus.IsStableOnGround) { jumpDirection = Motor.GroundingStatus.GroundNormal; } // Makes the character skip ground probing/snapping on its next update. // If this line weren't here, the character would remain snapped to the ground when trying to jump. Try commenting this line out and see. Motor.ForceUnground(); // Add to the return velocity and reset jump state currentVelocity += (jumpDirection * JumpSpeed) - Vector3.Project(currentVelocity, Motor.CharacterUp); _jumpRequested = false; _jumpConsumed = true; _jumpedThisFrame = true; } } // Reset wall jump _canWallJump = false; } // Take into account additive velocity if (_internalVelocityAdd.sqrMagnitude > 0f) { currentVelocity += _internalVelocityAdd; _internalVelocityAdd = Vector3.zero; } break; } case CharacterState.Swimming: { float verticalInput = 0f + (_jumpInputIsHeld ? 1f : 0f) + (_crouchInputIsHeld ? -1f : 0f); // Smoothly interpolate to target swimming velocity Vector3 targetMovementVelocity = (_moveInputVector + (Motor.CharacterUp * verticalInput)).normalized * SwimmingSpeed; Vector3 smoothedVelocity = Vector3.Lerp(currentVelocity, targetMovementVelocity, 1 - Mathf.Exp(-SwimmingMovementSharpness * deltaTime)); // See if our swimming reference point would be out of water after the movement from our velocity has been applied { Vector3 resultingSwimmingReferancePosition = Motor.TransientPosition + (smoothedVelocity * deltaTime) + (SwimmingReferencePoint.position - Motor.TransientPosition); Vector3 closestPointWaterSurface = Physics.ClosestPoint(resultingSwimmingReferancePosition, _waterZone, _waterZone.transform.position, _waterZone.transform.rotation); // if our position would be outside the water surface on next update, project the velocity on the surface normal so that it would not take us out of the water if (closestPointWaterSurface != resultingSwimmingReferancePosition) { Vector3 waterSurfaceNormal = (resultingSwimmingReferancePosition - closestPointWaterSurface).normalized; smoothedVelocity = Vector3.ProjectOnPlane(smoothedVelocity, waterSurfaceNormal); } } currentVelocity = smoothedVelocity; break; } } }
/// <summary> /// Reset motor's position. /// </summary> /// /// <param name="motor">Motor to reset.</param> /// <param name="relative">Specifies if relative (to last movement) or absolute motor's /// position should reset.</param> /// /// <returns>Returns <b>true</b> if command was executed successfully or <b>false</b> otherwise.</returns> /// public bool ResetMotorPosition( Motor motor, bool relative ) { return ResetMotorPosition( motor, relative, true ); }
/// <summary> /// Setup path base on motor output fem file, motor params and analysis name /// </summary> private void generateOutputPath() { // directory store data for current motor (using md5 as folder) D:\..\..\m1\md5string-motor\Transient\ OutDir0 = Path.GetDirectoryName(Motor.Path_FEMMFile) + "\\" + Path.GetFileNameWithoutExtension(Motor.Path_FEMMFile) + "\\" + Motor.GetMD5String() + "\\Transient"; //using hash md5 instead of actual name because femm cannot open the path in unicode //<outdir0>\md5-transient-variant\ OutDir = OutDir0 + "\\" + Utils.CalculateMD5Hash(AnalysisName); Path_TransResultsFile = OutDir + "\\results.txt"; }
/// <summary> /// Set motor state. /// </summary> /// /// <param name="motor">Motor to set state for.</param> /// <param name="state">Motor's state to set.</param> /// /// <returns>Returns <b>true</b> if command was executed successfully or <b>false</b> otherwise.</returns> /// public bool SetMotorState( Motor motor, MotorState state ) { return SetMotorState( motor, state, true ); }
/// <summary> /// This is called every frame by MyPlayer in order to tell the character what its inputs are /// </summary> public void SetInputs(ref PlayerCharacterInputs inputs) { // Handle state transition from input if (inputs.NoClipDown) { if (CurrentCharacterState == CharacterState.Default) { TransitionToState(CharacterState.NoClip); } else if (CurrentCharacterState == CharacterState.NoClip) { TransitionToState(CharacterState.Default); } } _jumpInputIsHeld = inputs.JumpHeld; _crouchInputIsHeld = inputs.CrouchHeld; // Clamp input Vector3 moveInputVector = Vector3.ClampMagnitude(new Vector3(inputs.MoveAxisRight, 0f, inputs.MoveAxisForward), 1f); // Calculate camera direction and rotation on the character plane Vector3 cameraPlanarDirection = Vector3.ProjectOnPlane(inputs.CameraRotation * Vector3.forward, Motor.CharacterUp).normalized; if (cameraPlanarDirection.sqrMagnitude == 0f) { cameraPlanarDirection = Vector3.ProjectOnPlane(inputs.CameraRotation * Vector3.up, Motor.CharacterUp).normalized; } Quaternion cameraPlanarRotation = Quaternion.LookRotation(cameraPlanarDirection, Motor.CharacterUp); switch (CurrentCharacterState) { case CharacterState.Default: { // Move and look inputs _moveInputVector = cameraPlanarRotation * moveInputVector; _lookInputVector = cameraPlanarDirection; // Jumping input if (inputs.JumpDown) { _timeSinceJumpRequested = 0f; _jumpRequested = true; } // Crouching input if (inputs.CrouchDown) { _shouldBeCrouching = true; if (!_isCrouching) { _isCrouching = true; Motor.SetCapsuleDimensions(0.5f, 1f, 0.5f); MeshRoot.localScale = new Vector3(1f, 0.5f, 1f); } } else if (inputs.CrouchUp) { _shouldBeCrouching = false; } break; } case CharacterState.NoClip: { _moveInputVector = inputs.CameraRotation * moveInputVector; _lookInputVector = cameraPlanarDirection; break; } } }
/// <summary> /// Get motor state. /// </summary> /// /// <param name="motor">Motor to get state for.</param> /// <param name="state">Motor's state.</param> /// /// <returns>Returns <b>true</b> if command was executed successfully or <b>false</b> otherwise.</returns> /// public bool GetMotorState( Motor motor, out MotorState state ) { state = new MotorState( ); // check motor port if ( motor == Motor.All ) { throw new ArgumentException( "Motor state can be retrieved for one motor only" ); } byte[] command = new byte[3]; byte[] reply = new byte[25]; // prepare message command[0] = (byte) NXTCommandType.DirectCommand; command[1] = (byte) NXTDirectCommand.GetOutputState; command[2] = (byte) motor; if ( SendCommand( command, reply ) ) { state.Power = (sbyte) reply[4]; state.Mode = (MotorMode) reply[5]; state.Regulation = (MotorRegulationMode) reply[6]; state.TurnRatio = (sbyte) reply[7]; state.RunState = (MotorRunState) reply[8]; // tacho limit state.TachoLimit = reply[9] | ( reply[10] << 8 ) | ( reply[11] << 16 ) | ( reply[12] << 24 ); // tacho count state.TachoCount = reply[13] | ( reply[14] << 8 ) | ( reply[15] << 16 ) | ( reply[16] << 24 ); // block tacho count state.BlockTachoCount = reply[17] | ( reply[18] << 8 ) | ( reply[19] << 16 ) | ( reply[20] << 24 ); // rotation count state.RotationCount = reply[21] | ( reply[22] << 8 ) | ( reply[23] << 16 ) | ( reply[24] << 24 ); return true; } return false; }
private void generateOutputPath() { OutDir0 = Path.GetDirectoryName(Motor.Path_FEMMFile) + "\\" + Path.GetFileNameWithoutExtension(Motor.Path_FEMMFile) + "\\" + Motor.GetMD5String(); OutDir = OutDir0 + "\\" + "MMAnalysis"; Path_resultsFile = OutDir + "\\results.txt"; }
public static void GoToPosition(Motor motor, double Position) { GoToStepPosition(motor, (int)((double)Position / MotorCalibration[motor])); }
/// <summary> /// Turn on/off specified motors. /// </summary> /// /// <param name="motors">Motors to turn on/off.</param> /// <param name="on">True to turn motors on, otherwise false.</param> /// /// <returns>Returns <b>true</b> if command was executed successfully or <b>false</b> otherwise.</returns> /// public bool SetMotorOn(Motor motors, bool on) { return(SendCommand(new byte[] { (byte)RCXCommand.SetMotorOnOff, (byte)((byte)motors | (on ? 0x80 : 0x40)) }, new byte[1], 1)); }
public static void GoXSteps(Motor motor, int Steps) { double absSteps = Math.Abs(Steps); if (absSteps < 1048575 & absSteps > 0) { string Command = ""; byte[] SWA = new byte[5]; SWA[4] = (byte)Math.Truncate(absSteps / 16 / 16 / 16 / 16); absSteps = absSteps - SWA[4] * 16 * 16 * 16 * 16; SWA[3] = (byte)Math.Truncate(absSteps / 16 / 16 / 16); absSteps = absSteps - SWA[3] * 16 * 16 * 16; SWA[2] = (byte)Math.Truncate(absSteps / 16 / 16); absSteps = absSteps - SWA[2] * 16 * 16; SWA[1] = (byte)Math.Truncate(absSteps / 16); SWA[0] = (byte)(absSteps - SWA[1] * 16); Command = Command + (char)SWA[0] + (char)SWA[1] + (char)SWA[2] + (char)SWA[3] + (char)SWA[4]; if (Steps < 0) { Command = Command + (char)16; } else { Command = Command + (char)17; } Command = Command + (char)0 + (char)0; string Answer = SendData(motor, Command); if (Answer[0] != 255) { trace.Value.TraceEvent(TraceEventType.Warning, 0, "Error during 'GoSteps', Error code: " + GetErrorCode(Answer[0])); } } }
/// <summary> /// Set power of specified motors. /// </summary> /// /// <param name="motors">Motors to set power of.</param> /// <param name="power">Power level to set, [0..7].</param> /// /// <returns>Returns <b>true</b> if command was executed successfully or <b>false</b> otherwise.</returns> /// public bool SetMotorPower(Motor motors, byte power) { return(SendCommand(new byte[] { (byte)RCXCommand.SetMotorPower, (byte)motors, 2, Math.Min(power, (byte)7) }, new byte[1], 1)); }
public static string Status(Motor motor) { string Answer = SendCommand(motor, ((char)7).ToString()); if (Answer.Length == 10) { return Answer; } else { trace.Value.TraceEvent(TraceEventType.Error, 0, "Gonio isn't in PC mode"); return ""; } }
/// <summary> /// Set direction of specified motors. /// </summary> /// /// <param name="motors">Motors to set direction of.</param> /// <param name="isForward">True to set forward direction, false to set backward.</param> /// /// <returns>Returns <b>true</b> if command was executed successfully or <b>false</b> otherwise.</returns> /// public bool SetMotorDirection(Motor motors, bool isForward) { return(SendCommand(new byte[] { (byte)RCXCommand.SetMotorDirection, (byte)((byte)motors | (isForward ? 0x80 : 0)) }, new byte[1], 1)); }
public static int GetStepPosition(Motor motor) { string Answer = SendCommand(motor, ((char)7).ToString()); if (Answer.Length == 10) { bool sign = GetBit((byte)Answer[7], 2); if (sign == true) return -1 * int.Parse(string.Concat((Answer.Take(7).Reverse()))); else return int.Parse(string.Concat((Answer.Take(7).Reverse()))); } else { trace.Value.TraceEvent(TraceEventType.Error, 0, "Can't get motor position"); return -1; } }
public MotorSettings1D(Motor motor) : base(motor) { servo = new ServoSettings1D(this); velocityMotor = new VelocityMotorSettings1D(this); }