public Rotator IntVectorToRotator(Vector3 v) { Rotator r = new Rotator(); r.Yaw = (int)(v.X); r.Pitch = (int)(v.Y); r.Roll = (int)(v.Z); return r; }
public Rotator PropToRotator(byte[] buff) { Rotator r = new Rotator(); r.Pitch = -BitConverter.ToInt32(buff, 8); r.Roll = BitConverter.ToInt32(buff, 12); r.Yaw = -BitConverter.ToInt32(buff, 16); return r; }
public Vector3 RotatorToVector(Rotator r) { Vector3 v = new Vector3(); float f = (3.1415f * 2f) / 65536f; v.X = r.Yaw * f; v.Y = r.Pitch * f; v.Z = r.Roll * f; return v; }
public Rotator VectorToRotator(Vector3 v) { Rotator r = new Rotator(); float f2 = 65536f / 360f; r.Yaw = (int)(v.Y * f2); r.Pitch = (int)(v.X * f2); r.Roll = (int)(v.Z * f2); r.Yaw = r.Yaw % (65536 / 2); r.Pitch = r.Pitch % (65536 / 2); r.Roll = r.Roll % (65536 / 2); return r; }
public void SetWinState() { GameData.DRAW_CHAT = false; GameData.DRAW_STATS = false; if (Network.isClient) { myPlayerRotator = PlayerManager.instance.myPlayer.GetComponent<Rotator>(); myPlayerRotator.enabled = false; Screen.lockCursor = false; } DrawUI.instance.drawUI = DrawWinState; }
public BackgroundRectanglesLayer(SpriteBatch spriteBatch, Texture2D[] images, Rotator roation, float velocity, Vector2 startOffset, Rectangle ViewPort) { this.spriteBatch = spriteBatch; this.images = images; frameDimensions = images.Length > 0 ? new Dimensions(images[0].Width, images[0].Height) : Dimensions.Zero; this.currentRotation = roation; this._velocity = velocity; // Where we start in relation to our frames. so 0,0 means the top left of the first texture is at 0,0on the screen, // 50,50 would be: display background from position 50,50 at screen co-ords 0,0. // ie whats' the starting co-ordinate for the top-left of the screen. this._currentPosition = startOffset; // not perfect, ensures it DOES update. this._previousPosition = _currentPosition.AddX(-1); _destination = new Rectangle(Point.Zero, new Point(ViewPort.Width, ViewPort.Height)); this.totalWidth = frameDimensions.Width * images.Length; this.totalHeight = frameDimensions.Height; }
private void SetMovementProps(Transform knife) { Mover mover = knife.GetComponent <Mover>(); Rotator rotator = knife.GetComponent <Rotator>(); if (mover) { Vector2 velocity = new Vector2(UnityEngine.Random.Range(-3f, 3f), UnityEngine.Random.Range(1f, 6f)); mover.SetVelocity(velocity); mover.SwitchRigidbodyType(RigidbodyType2D.Dynamic); } if (rotator) { float rotationSpeed = UnityEngine.Random.Range(200f, 350f); rotator.SetRotationSpeed(rotationSpeed); rotator.SetRotationSide(UnityEngine.Random.Range(0, 2) == 1); } }
/// <summary> /// Spawns an instance of an item /// </summary> /// <param name="id">Id of the npc id</param> /// <param name="position">Position of the npc</param> /// <param name="yaw">Yaw of the npc</param> /// <param name="zone">Zone where to register the npc</param> /// <param name="regionObject">returned object</param> /// <returns>Returns true if the object doesn't fail</returns> public bool SpawnItemInstance(uint id, Point position, Rotator yaw, Zone zone, out MapObject regionObject) { if (CreateInstance(id, 1, out regionObject)) { regionObject.Position = position; regionObject.Yaw = yaw; regionObject.currentzone = zone; regionObject.OnInitialize(position); regionObject.OnLoad(); regionObject.OnSpawn(); regionObject.OnRegister(); if (regionObject.id > 0) { Regiontree tree = regionObject.currentzone.Regiontree; foreach (Character regionCharacter in tree.SearchActors(regionObject, Saga.Enumarations.SearchFlags.Characters)) { try { if (regionCharacter.client.isloaded == false) { continue; } if (Point.IsInSightRangeByRadius(regionCharacter.Position, regionObject.Position)) { regionObject.ShowObject(regionCharacter); } } catch (SocketException) { //Do nothing } } return(true); } else { return(false); } } return(false); }
public static void EvaluateTarget(AActor actor) { // if (!IsVisiable(actor)) // return; if (actor.Health < 1f) { return; } Vector2 centerScreen = new Vector2(screensize.X / 2, screensize.Y / 2); Vector3 vecLocalPlayer = Main.cameraManager.CameraCache.POV.Location; Vector3 vecTargetPlayer = actor.GetBoneLocation((int)aimPos); Vector2 vecTargetPlayer2d = Main.cameraManager.WorldToScreen(vecTargetPlayer, screensize); float BulletSpeed = Main.localPawn.EquipWeapon().ShootWeaponEntityComp().BulletFireSpeed / 100; Vector3 TargetVelocity = GetPlayerVelocity(actor); float curDist = (vecTargetPlayer - vecLocalPlayer).Length(); float timeToTravel = (curDist / 100) / BulletSpeed; if (timeToTravel > 1f && !float.IsInfinity(timeToTravel)) { vecTargetPlayer += TargetVelocity * timeToTravel; vecTargetPlayer.Z += TargetVelocity.Z * timeToTravel + 0.5f * 588.6f * timeToTravel * timeToTravel; } Vector2 head = Main.cameraManager.WorldToScreen(actor.GetBoneLocation((int)aimPos), screensize); Vector2 prediction = Main.cameraManager.WorldToScreen(vecTargetPlayer, screensize); DrawFactory.DrawLine(head.X, head.Y, prediction.X, prediction.Y, 3, Color.Yellow); if (isInside(centerScreen.X, centerScreen.Y, 200, vecTargetPlayer2d)) { if (curDist < distance) { Rotator angDelta = ToRotator(vecLocalPlayer, vecTargetPlayer); idealAngDelta = angDelta; bestActor = actor; distance = curDist; } } }
public override Controller GetOutput(GameTickPacket gameTickPacket) { // This controller object will be returned at the end of the method. // This controller will contain all the inputs that we want the bot to perform. Controller controller = new Controller(); _gameDataMgr.PreProcess(gameTickPacket); // Store the required data from the gameTickPacket. // The GameTickPacket's attributes are nullables, so you must use .Value. // It is recommended to create your own internal data structure to avoid the displeasing .Value syntax. Vector3 ballLocation = gameTickPacket.Ball.Value.Physics.Value.Location.Value; Vector3 carLocation = gameTickPacket.Players(this.index).Value.Physics.Value.Location.Value; Rotator carRotation = gameTickPacket.Players(this.index).Value.Physics.Value.Rotation.Value; // Calculate to get the angle from the front of the bot's car to the ball. double botToTargetAngle = Math.Atan2(ballLocation.Y - carLocation.Y, ballLocation.X - carLocation.X); double botFrontToTargetAngle = botToTargetAngle - carRotation.Yaw; // Correct the angle if (botFrontToTargetAngle < -Math.PI) { botFrontToTargetAngle += 2 * Math.PI; } if (botFrontToTargetAngle > Math.PI) { botFrontToTargetAngle -= 2 * Math.PI; } // Decide which way to steer in order to get to the ball. if (botFrontToTargetAngle > 0) { controller.Steer = 1; } else { controller.Steer = -1; } // Set the throttle to 1 so the bot can move. controller.Throttle = 1; return(controller); }
public CarDemo() { int alpha = 255; int colA = Color.FromArgb(alpha, 51, 58, 51).ToArgb(); int colB = Color.FromArgb(alpha, 51, 102, 170).ToArgb(); int colC = Color.FromArgb(alpha, 170, 187, 187).ToArgb(); int colD = Color.FromArgb(alpha, 102, 153, 170).ToArgb(); int colE = Color.FromArgb(alpha, 119, 136, 119).ToArgb(); int colPad = Color.FromArgb(alpha, 153, 102, 51).ToArgb(); APEngine.init((float) 1 / 4); Vector massLessForces = new Vector(0, 3); APEngine.addMasslessForce(massLessForces); Surfaces surfaces = new Surfaces(colA, colB, colC, colD, colE, colPad); APEngine.addGroup(surfaces); Bridge bridge = new Bridge(colB, colC, colD); APEngine.addGroup(bridge); Capsule capsule = new Capsule(colC); APEngine.addGroup(capsule); rotator = new Rotator(colB, colE); APEngine.addGroup(rotator); SwingDoor swingDoor = new SwingDoor(colC); APEngine.addGroup(swingDoor); car = new Car(colC, colE); APEngine.addGroup(car); car.addCollidable(surfaces); car.addCollidable(bridge); car.addCollidable(rotator); car.addCollidable(swingDoor); car.addCollidable(capsule); capsule.addCollidable(surfaces); capsule.addCollidable(bridge); capsule.addCollidable(rotator); capsule.addCollidable(swingDoor); }
private FBXNode CreateFbxBone(int boneIndex, List <MESkeletalMesh.BoneStruct> Skeleton, FBXScene pScene, FBXNode parent) { MESkeletalMesh.BoneStruct bone = Skeleton[boneIndex]; string boneName = bone.BoneName; FBXSkeleton lSkeletonLimbNodeAttribute1 = FBXSkeleton.Create(pScene, boneName); lSkeletonLimbNodeAttribute1.SetSkeletonType(FBXWrapper.SkelType.eLimbNode); lSkeletonLimbNodeAttribute1.SetSize(1.0); FBXNode lSkeletonLimbNode1 = FBXNode.Create(pScene, boneName); lSkeletonLimbNode1.SetNodeAttribute(lSkeletonLimbNodeAttribute1); lSkeletonLimbNode1.LclTranslation = new List <double> { bone.Position.X, -bone.Position.Y, bone.Position.Z }; ME3Explorer.Unreal.Classes.SkeletalMeshOld.Quad boneQuad; boneQuad.x = -bone.Orientation.X; boneQuad.y = bone.Orientation.Y; boneQuad.z = bone.Orientation.Z; boneQuad.w = -bone.Orientation.W; if (boneIndex == 0) { boneQuad.w = boneQuad.w * -1; } Rotator rot = QuatToRotator(boneQuad); lSkeletonLimbNode1.LclRotation = new List <double> { rot.Roll, rot.Pitch, rot.Yaw }; var children = Skeleton.Where(b => b.Parent == boneIndex).ToList(); foreach (var childBone in children) { int childIndexInSkeleton = Skeleton.FindIndex(b => b.Name == childBone.Name); if (childIndexInSkeleton != boneIndex) { FBXNode fbxChildBone = CreateFbxBone(childIndexInSkeleton, Skeleton, pScene, lSkeletonLimbNode1); lSkeletonLimbNode1.AddChild(fbxChildBone); } } return(lSkeletonLimbNode1); }
//actor must be an Actor public static Matrix GetLocalToWorld(ExportEntry actor) { PropertyCollection props = actor.GetProperties(); var rotationProp = props.GetProp <StructProperty>("Rotation"); var locationsProp = props.GetProp <StructProperty>("location"); var drawScale3DProp = props.GetProp <StructProperty>("DrawScale3D"); var prePivotProp = props.GetProp <StructProperty>("PrePivot"); float drawScale = props.GetProp <FloatProperty>("DrawScale")?.Value ?? 1; Vector3 location = locationsProp != null?CommonStructs.GetVector3(locationsProp) : Vector3.Zero; Vector3 scale = drawScale * (drawScale3DProp != null ? CommonStructs.GetVector3(drawScale3DProp) : Vector3.One); Vector3 pivot = prePivotProp != null?CommonStructs.GetVector3(prePivotProp) : Vector3.Zero; Rotator rotator = rotationProp != null?CommonStructs.GetRotator(rotationProp) : new Rotator(0, 0, 0); return(ComposeLocalToWorld(location, rotator, scale, pivot)); }
private void CameraSwap() { if (_cam1 == false) { "Starting to swap cameras".AddLog(); _cam1 = true; _swapCam = new Camera(false); _swapCam.Position = new Vector3(_meCar.AbovePosition.X, _meCar.AbovePosition.Y, _meCar.AbovePosition.Z + 7); _swapCam.PointAtEntity(_meCar, Vector3.Zero, false); _gameCam = new Camera(false); _gameCam.FOV = NativeFunction.Natives.GET_GAMEPLAY_CAM_FOV <float>(); _gameCam.Position = NativeFunction.Natives.GET_GAMEPLAY_CAM_COORD <Vector3>(); Vector3 rot = NativeFunction.Natives.GET_GAMEPLAY_CAM_ROT <Vector3>(0); var rot1 = new Rotator(rot.X, rot.Y, rot.Z); _gameCam.Rotation = rot1; "Swapping camera".AddLog(); _swapCam.Active = true; NativeFunction.Natives.DO_SCREEN_FADE_OUT(7500); Stopwatch sw = new Stopwatch(); sw.Start(); while (true) { _swapCam.PointAtEntity(_meCar, Vector3.Zero, false); if (NativeFunction.Natives.IS_SCREEN_FADED_OUT <bool>() == true) { "Screen faded, swapping stages".AddLog(); _swapCam.Active = false; break; } GameFiber.Yield(); } if (_transport) { SwapStages(CameraSwap, Ending); } else { SwapStages(CameraSwap, Transport); } } }
public static Rotator ToRotator(Vector3 local, Vector3 target) { Vector3 rotation = local - target; Rotator newViewAngle = new Rotator(); float hyp = (float)Math.Sqrt(rotation.X * rotation.X + rotation.Y * rotation.Y); newViewAngle.Pitch = (float)(-Math.Atan(rotation.Z / hyp) * (180f / Math.PI)); newViewAngle.Yaw = (float)(Math.Atan(rotation.Y / rotation.X) * (180f / Math.PI)); newViewAngle.Roll = (float)0f; if (rotation.X >= 0f) { newViewAngle.Yaw += 180.0f; } return(newViewAngle.Clamp()); }
//private static bool BarriersListSelected = false; public static void Process(object sender, GraphicsEventArgs e) { _menuPool.ProcessMenus(); if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownRightNowComputerCheck(TrafficPolicerHandler.RoadManagementModifierKey) || TrafficPolicerHandler.RoadManagementModifierKey == System.Windows.Forms.Keys.None) { if (Albo1125.Common.CommonLibrary.ExtensionMethods.IsKeyDownComputerCheck(TrafficPolicerHandler.roadManagementMenuKey)) { roadManagementMenu.Visible = !roadManagementMenu.Visible; } } if (PlaceSignMenu.Visible) { if (UpdateSignPositionItem.Checked) { PositionToPlaceAt = Game.LocalPlayer.Character.Position; RotationToPlaceAt = Game.LocalPlayer.Character.Rotation; } } }
internal static unsafe CameraAnimInst Invoke(IntPtr obj, CameraAnim Anim, float Rate, float Scale, float BlendInTime, float BlendOutTime, bool bLoop, bool bRandomStartTime, float Duration, byte PlaySpace, Rotator UserPlaySpaceRot) { long *p = stackalloc long[] { 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L }; byte *b = (byte *)p; *((IntPtr *)(b + 0)) = Anim; *((float *)(b + 8)) = Rate; *((float *)(b + 12)) = Scale; *((float *)(b + 16)) = BlendInTime; *((float *)(b + 20)) = BlendOutTime; *((bool *)(b + 24)) = bLoop; *((bool *)(b + 25)) = bRandomStartTime; *((float *)(b + 28)) = Duration; *(b + 32) = PlaySpace; *((Rotator *)(b + 36)) = UserPlaySpaceRot; Main.GetProcessEvent(obj, PlayCameraAnim_ptr, new IntPtr(p));; return(*((IntPtr *)(b + 48))); } }
public void Generatematerials(Vector2 hitpoint) { if (available_item_count > 0) { available_item_count -= 1; GameObject item = items[Random.Range(0, items.Count - 1)]; GameObject material = Instantiate(item, hitpoint, Quaternion.identity) as GameObject; Rotator R = material.GetComponent <Rotator>(); if (R != null) { R.Set_rotation_Speed(Random.Range(-item_rotate_speed_min, item_rotate_speed_max)); } UnityFunctions.Move_RB_Random(material.GetComponent <Rigidbody2D>(), item_move_speed_min, item_move_speed_max); if (time_to_live > 0) { Destroy(material, time_to_live); } } }
public void Rotate(Vector3 spin) { if (hasMoved) { return; } hasMoved = true; Vector2 target = Rotator.RotateVector(this.xy, spin); // Crates.Remove(xy); Vector2 direction = target - xy; xy = target; Crates.Add(this); // try {Crates.Add(this);} // catch (ArgumentException) { // Debug.Log("gridofCrates doesn't register this move correctly"); // } StartCoroutine(AnimateRotation(target, spin)); }
protected override void ReceiveTick(float DeltaSeconds) { float yawDelta = RotationRate * DeltaSeconds; if (!RotateClockwise) { yawDelta *= -1; } Rotator rotation = GetActorRotation(); rotation.Yaw += yawDelta; OpenTK.Vector3 forwardVec = GetActorForwardVector(); OpenTK.Vector3 location = GetActorLocation(); location += DeltaSeconds * Velocity * forwardVec; SetActorLocationAndRotation(location, rotation, true); }
internal static unsafe bool Invoke(IntPtr obj, Rotator Actual, Rotator Expected, string What, float Tolerance, UObject ContextObject) { long *p = stackalloc long[] { 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L }; byte *b = (byte *)p; *((Rotator *)(b + 0)) = Actual; *((Rotator *)(b + 12)) = Expected; var What_handle = GCHandle.Alloc(What, GCHandleType.Pinned); *(IntPtr *)(b + 24) = What_handle.AddrOfPinnedObject(); *(int *)(b + IntPtr.Size + 24) = What.Length; *(int *)(b + IntPtr.Size + 4 + 24) = What.Length; *((float *)(b + 40)) = Tolerance; *((IntPtr *)(b + 48)) = ContextObject; Main.GetProcessEvent(obj, AssertEqual_Rotator_ptr, new IntPtr(p));; What_handle.Free(); return(*((bool *)(b + 56))); } }
public Program() { // The constructor, called only once every session and // always before any other method is called. Use it to // initialize your script. // // The constructor is optional and can be removed if not // needed. // // It's recommended to set RuntimeInfo.UpdateFrequency // here, which will allow your script to run itself without a // timer block. Runtime.UpdateFrequency = UpdateFrequency.Update1; engine = new GravEngine(this); _rotator = new Rotator(this); }
public async Task IsMovingAsync_SendValidRequest() { //Arrange string commandName = "ismoving"; IRestRequest sentRequest = null; var commandSenderMock = new Mock <ICommandSender>(); commandSenderMock .Setup(x => x.ExecuteRequestAsync <BoolResponse>(It.IsAny <string>(), It.IsAny <RestRequest>())) .Callback((string baseUrl, IRestRequest request) => sentRequest = request) .Returns(Task.FromResult(new BoolResponse(false))); var rotator = new Rotator(_deviceConfiguration, commandSenderMock.Object); //Act await rotator.IsMovingAsync(); //Assert Assert.Equal(Method.GET, sentRequest.Method); AssertCommonParameters(sentRequest.Parameters, _deviceConfiguration, commandName); }
public void Halt_SendValidRequest() { //Arrange string commandName = "halt"; IRestRequest sentRequest = null; var commandSenderMock = new Mock <ICommandSender>(); commandSenderMock .Setup(x => x.ExecuteRequest <CommandResponse>(It.IsAny <string>(), It.IsAny <RestRequest>())) .Callback((string baseUrl, IRestRequest request) => sentRequest = request) .Returns(new CommandResponse()); var rotator = new Rotator(_deviceConfiguration, commandSenderMock.Object); //Act rotator.Halt(); //Assert Assert.Equal(Method.PUT, sentRequest.Method); AssertCommonParameters(sentRequest.Parameters, _deviceConfiguration, commandName); }
private float CollectBoost(int boostId, Vector3 carPosition, Rotator carRotation) { Vector3f pos = new Vector3f(carPosition.X, carPosition.Y, carPosition.Z); Vector3f target = BoostLocations[boostId]; double targetAngle = Math.Atan2(target.y - pos.y, target.x - pos.x); double botAngle = targetAngle - carRotation.Yaw; if (botAngle < -Math.PI) { botAngle += Math.PI * 2; } if (botAngle > Math.PI) { botAngle -= Math.PI * 2; } double angleToGo = botAngle / Math.PI; return(Math.Min(1, (Math.Max(-1, (float)angleToGo)))); }
/// <summary> /// Display all proterties of one rotator /// </summary> /// <param name="rotator"></param> void DrawData(Rotator rotator) { EditorUtility.SetDirty(rotator); SerializedObject serializedObject = new SerializedObject(rotator); EditorGUILayout.BeginFadeGroup(_togleDisplayedRotator[rotator].faded); EditorGUI.indentLevel++; EditorGUILayout.PropertyField(serializedObject.FindProperty("_identifier")); EditorGUILayout.PropertyField(serializedObject.FindProperty("_timeBeforeStoppingInSeconds")); EditorGUILayout.PropertyField(serializedObject.FindProperty("_shouldReverseRotation")); EditorGUILayout.PropertyField(serializedObject.FindProperty("_rotationsSettings"), true); serializedObject.ApplyModifiedProperties(); EditorGUI.indentLevel--; EditorGUILayout.EndFadeGroup(); }
/// <summary> /// Initializes a new instance of the <see cref="Warcraft.ADT.Chunks.WorldModelObjectPlacementEntry"/> class. /// </summary> /// <param name="data">Data.</param> public WorldModelObjectPlacementEntry(byte[] data) { using (MemoryStream ms = new MemoryStream(data)) { using (BinaryReader br = new BinaryReader(ms)) { this.WorldModelObjectEntryIndex = br.ReadUInt32(); this.UniqueID = br.ReadInt32(); this.Position = br.ReadVector3f(); this.Rotation = br.ReadRotator(); this.BoundingBox = br.ReadBox(); this.Flags = (WorldModelObjectFlags)br.ReadUInt16(); this.DoodadSet = br.ReadUInt16(); this.NameSet = br.ReadUInt16(); this.Unused = br.ReadUInt16(); } } }
protected void Page_Load(object sender, EventArgs e) { Response.Cookies["loginreferrer"].Value = "/admin/rotator_header.aspx"; Response.Cookies["loginreferrer"].Expires = DateTime.Now.AddDays(30); if (Request.Cookies["adminid"] != null && Request.Cookies["adminid"].Value != "") { intProfile = Int32.Parse(Request.Cookies["adminid"].Value); } else { Response.Redirect("/admin/login.aspx"); } oRotator = new Rotator(intProfile, dsn); if (!IsPostBack) { LoopRepeater(); btnImage.Attributes.Add("onclick", "return OpenWindow('IMAGEPATH','','" + txtImage.ClientID + "',false,500,550);"); btnDelete.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this item?');"); btnCancel.Attributes.Add("onclick", "return Cancel();"); } }
override public void update(float dt) { Unit cu = caster.GetComponentInParent <Unit>(); Rotator rotator = caster.GetComponent <Rotator>(); rotator.turn(target.transform.position); if (Time.time - sightCheckAt > SIGHT_CHECK_PERIOD) { sightCheckAt = Time.time; if (cu.canSee(target)) { brain.memory.write("enemyPos", target.transform.position); } else { complete(); return; } } }
protected virtual bool Visit(Puzzle puzzle, Algorithm algorithm, ImmutableArray <NotationMoveType> moves) { if (this.WalkerStates.Count > this.MaximumDepth) { this.AtMaximumDepth(); return(false); } this.WalkerStates.Add(new SolveWalkerState(puzzle, algorithm, moves)); try { this.AlgorithmsTried++; this.TotalMoves += moves.Length; return(this.Visit(Rotator.ApplyMoves(puzzle, moves))); } finally { this.WalkerStates.RemoveAt(this.WalkerStates.Count - 1); this.TotalMoves -= moves.Length; } }
public override Controller GetOutput(GameTickPacket gameTickPacket) { // This controller object will be returned at the end of the method. // This controller will contain all the inputs that we want the bot to perform. Controller controller = new Controller(); // Wrap gameTickPacket retrieving in a try-catch so that the bot doesn't crash whenever a value isn't present. // A value may not be present if it was not sent. // These are nullables so trying to get them when they're null will cause errors, therefore we wrap in try-catch. try { // Store the required data from the gameTickPacket. Vector3 ballLocation = gameTickPacket.Ball.Value.Physics.Value.Location.Value; Vector3 carLocation = gameTickPacket.Players(this.index).Value.Physics.Value.Location.Value; Rotator carRotation = gameTickPacket.Players(this.index).Value.Physics.Value.Rotation.Value; // Calculate to get the angle from the front of the bot's car to the ball. double botToTargetAngle = GetHorizontalAngle(carLocation, ballLocation); double botFrontToTargetAngle = botToTargetAngle - carRotation.Yaw; // Correct the angle botFrontToTargetAngle = CorrectAngle(botFrontToTargetAngle); // Decide which way to steer in order to get to the ball. controller.Steer = (float)(botFrontToTargetAngle / Math.PI); /* Throttle between 0.5 and 1 depending on the steering angle * 0 Steer = 1 Throttle * +-1 Steer = 0.5 Throttle * A simply y = -2x+1 equation */ controller.Throttle = (float)(-2 * Math.Abs(controller.Steer)) + 1; } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } return(controller); }
override public void update(float dt) { Unit cu = caster.GetComponentInParent <Unit> (); Rotator rotator = caster.GetComponent <Rotator>(); // Try to aim if (!rotator.turn(target.transform.position)) { weapon.shooting = false; return; } // Stop shooting on empty clip, exceed recoil or burst size if (weapon.justShot && (weapon.clip == 0 || weapon.recoil > accuracy || weapon.burst > shots)) { complete(); return; } // Spotting check if (Time.time - sightCheckAt > SIGHT_CHECK_PERIOD) { sightCheckAt = Time.time; if (cu.canSee(target)) { brain.memory.write("enemyPos", target.transform.position); } else { complete(); return; } } if (!weapon.shooting) { weapon.shooting = true; } }
private void insetCoin(Vector3 coinPos) { GameObject coin = GameGlobals.Instance.trackGenerator.getRandomTrackObjectByType(TrackObject.ObjectType.PointsSingle); GameObject coinMesh = coin.transform.Find("coinMesh").gameObject; if (coin != null) { coin.GetComponent <TrackObject>().positioned = true; coin.transform.parent = transform; coin.transform.localPosition = coinPos; if (coinMesh != null) { coinMesh.transform.rotation = new Quaternion(0, 0, 0, 0); coinMesh.transform.Rotate(0, coins.Count * 35f, 0); Rotator rotator = coinMesh.GetComponent <Rotator>(); if (rotator != null) { rotator.enabled = true; } } if (coinLineRefraction == CoinLineRefraction.None) { coin.GetComponent <Coin>().audioPitch = 0; } else { float pitch = 1.0f + (0.4f / coinCount * lastAddedIndex); coin.GetComponent <Coin>().audioPitch = pitch; } coin.gameObject.SetActive(true); coins.Insert(lastAddedIndex, coin.transform); lastAddedIndex++; } }
private void DetachFromRotator() { if (connectedRotator == null) { return; } isDrifting = false; line.gameObject.SetActive(false); driftSign = Mathf.Sign(connectedRotator.ClockwiseValue); skidTimer.Duration = driftDuration + 0.5f; driftRotation = carTransform.rotation; if (connectedRotator) { connectedRotator = null; } }
public Program() { // The constructor, called only once every session and // always before any other method is called. Use it to // initialize your script. // // The constructor is optional and can be removed if not // needed. // // It's recommended to set RuntimeInfo.UpdateFrequency // here, which will allow your script to run itself without a // timer block. // Configure this program to run the Main method every 100 update ticks Runtime.UpdateFrequency = UpdateFrequency.Update100; rotator = new Rotator(this); GridTerminalSystem.GetBlocks(list); //get at start }
public void Equip(Item item) { if (occupied) { return; } occupied = true; this.item = item; // spawn item GameObject itemGO = Instantiate(item.prefab, transform); itemGO.transform.position += new Vector3(0, 0, itemOffsetZ); itemGO.transform.localScale *= scaleMultiplier; GameObjectUtil.IterateChildren(gameObject, SetUILayer, true); Rotator rotator = itemGO.AddComponent <Rotator>(); rotator.rotation = new Vector3(0, itemYRotation, 0); }
void CreateScene () { var cache = ResourceCache; scene = new Scene (); // Create the Octree component to the scene so that drawable objects can be rendered. Use default volume // (-1000, -1000, -1000) to (1000, 1000, 1000) scene.CreateComponent<Octree> (); // Create a Zone component into a child scene node. The Zone controls ambient lighting and fog settings. Like the Octree, // it also defines its volume with a bounding box, but can be rotated (so it does not need to be aligned to the world X, Y // and Z axes.) Drawable objects "pick up" the zone they belong to and use it when rendering; several zones can exist var zoneNode = scene.CreateChild("Zone"); var zone = zoneNode.CreateComponent<Zone>(); // Set same volume as the Octree, set a close bluish fog and some ambient light zone.SetBoundingBox (new BoundingBox(-1000.0f, 1000.0f)); zone.AmbientColor = new Color (0.05f, 0.1f, 0.15f); zone.FogColor = new Color (0.1f, 0.2f, 0.3f); zone.FogStart = 10; zone.FogEnd = 100; var boxesNode = scene.CreateChild("Boxes"); const int numObjects = 2000; for (var i = 0; i < numObjects; ++i) { Node boxNode = new Node(); boxesNode.AddChild(boxNode, 0); boxNode.Position = new Vector3(NextRandom (200f) - 100f, NextRandom (200f) - 100f, NextRandom (200f) - 100f); // Orient using random pitch, yaw and roll Euler angles boxNode.Rotation = new Quaternion(NextRandom(360.0f), NextRandom(360.0f), NextRandom(360.0f)); using (var boxObject = boxNode.CreateComponent<StaticModel>()) { boxObject.Model = cache.GetModel("Models/Box.mdl"); boxObject.SetMaterial(cache.GetMaterial("Materials/Stone.xml")); //we don't need this component in C# anymore so let's just delete a MCW for it (howerver, we can access it anytime if we need via GetComponent<>) //it's just an optimization to reduce cached objects count } // Add our custom Rotator component which will rotate the scene node each frame, when the scene sends its update event. // The Rotator component derives from the base class LogicComponent, which has convenience functionality to subscribe // to the various update events, and forward them to virtual functions that can be implemented by subclasses. This way // writing logic/update components in C++ becomes similar to scripting. // Now we simply set same rotation speed for all objects var rotationSpeed = new Vector3(10.0f, 20.0f, 30.0f); // First style: use a Rotator instance, which is a component subclass, and // add it to the boxNode. var rotator = new Rotator () { RotationSpeed = rotationSpeed }; boxNode.AddComponent (rotator); } // Create the camera. Let the starting position be at the world origin. As the fog limits maximum visible distance, we can // bring the far clip plane closer for more effective culling of distant objects CameraNode = scene.CreateChild("Camera"); var camera = CameraNode.CreateComponent<Camera>(); camera.FarClip = 100.0f; // Create a point light to the camera scene node var light = CameraNode.CreateComponent<Light>(); light.LightType = LightType.Point; light.Range = 30.0f; }
/// <summary> /// Initializes a new instance of the <see cref="Warcraft.ADT.Chunks.ModelPlacementEntry"/> class. /// </summary> /// <param name="data">Data.</param> public ModelPlacementEntry(byte[] data) { using (MemoryStream ms = new MemoryStream(data)) { using (BinaryReader br = new BinaryReader(ms)) { this.ModelEntryIndex = br.ReadUInt32(); this.UniqueID = br.ReadUInt32(); this.Position = br.ReadVector3f(); this.Rotation = br.ReadRotator(); this.ScalingFactor = br.ReadUInt16(); this.Flags = (ModelPlacementFlags)br.ReadUInt16(); } } }
public void WriteRotator(MemoryStream m, Rotator r) { m.Write(BitConverter.GetBytes(r.yaw), 0, 4); m.Write(BitConverter.GetBytes(r.pitch), 0, 4); m.Write(BitConverter.GetBytes(r.roll), 0, 4); }
public Rotator ReadRotator(int pos) { Rotator r = new Rotator(); r.yaw = BitConverter.ToInt32(memory, pos); r.pitch = BitConverter.ToInt32(memory, pos + 4); r.roll = BitConverter.ToInt32(memory, pos + 8); return r; }
void ReplyCrystalEating() { if(myPlayerRotator == null) myPlayerRotator = PlayerManager.instance.myPlayer.GetComponent<Rotator>(); eatingInProgress = true; crystalBarUI.eatingInProgress = true; }
public SerializableObject CreateObject(Model model, Vector3 pos, Rotator rot) { var tmpObject = new Object(model, pos); tmpObject.Rotation = rot; tmpObject.Position = pos; var tmpObj = new SerializableObject(); tmpObj.SetEntity(tmpObject); tmpObj.SpawnAfter = 0; tmpObj.RemoveAfter = 0; CurrentMission.Objects.Add(tmpObj); return tmpObj; }
void CreateScene() { var cache = GetSubsystem<ResourceCache>(); { rttScene = new Scene(); // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000) rttScene.CreateComponent<Octree>(); // Create a Zone for ambient light & fog control Node zoneNode = rttScene.CreateChild("Zone"); Zone zone = zoneNode.CreateComponent<Zone>(); // Set same volume as the Octree, set a close bluish fog and some ambient light zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f)); zone.AmbientColor = new Color(0.05f, 0.1f, 0.15f); zone.FogColor = new Color(0.1f, 0.2f, 0.3f); zone.FogStart = 10.0f; zone.FogEnd = 100.0f; // Create randomly positioned and oriented box StaticModels in the scene const uint numObjects = 2000; for (uint i = 0; i < numObjects; ++i) { Node boxNode = rttScene.CreateChild("Box"); boxNode.Position = new Vector3(NextRandom(200.0f) - 100.0f, NextRandom(200.0f) - 100.0f, NextRandom(200.0f) - 100.0f); // Orient using random pitch, yaw and roll Euler angles boxNode.Rotation = new Quaternion(NextRandom(360.0f), NextRandom(360.0f), NextRandom(360.0f)); StaticModel boxObject = boxNode.CreateComponent<StaticModel>(); boxObject.Model = cache.Get<Model>("Models/Box.mdl"); boxObject.SetMaterial(cache.Get<Material>("Materials/Stone.xml")); // Add our custom Rotator component which will rotate the scene node each frame, when the scene sends its update event. // Simply set same rotation speed for all objects Rotator rotator = new Rotator(); boxNode.AddComponent(rotator); rotator.SetRotationSpeed(new Vector3(10.0f, 20.0f, 30.0f)); } // Create a camera for the render-to-texture scene. Simply leave it at the world origin and let it observe the scene rttCameraNode = rttScene.CreateChild("Camera"); Camera camera = rttCameraNode.CreateComponent<Camera>(); camera.FarClip = 100.0f; // Create a point light to the camera scene node Light light = rttCameraNode.CreateComponent<Light>(); light.LightType = LightType.LIGHT_POINT; light.Range = 30.0f; } { // Create the scene in which we move around scene = new Scene(); // Create octree, use also default volume (-1000, -1000, -1000) to (1000, 1000, 1000) scene.CreateComponent<Octree>(); // Create a Zone component for ambient lighting & fog control Node zoneNode = scene.CreateChild("Zone"); Zone zone = zoneNode.CreateComponent<Zone>(); zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f)); zone.AmbientColor = new Color(0.1f, 0.1f, 0.1f); zone.FogStart = 100.0f; zone.FogEnd = 300.0f; // Create a directional light without shadows Node lightNode = scene.CreateChild("DirectionalLight"); lightNode.SetDirection(new Vector3(0.5f, -1.0f, 0.5f)); Light light = lightNode.CreateComponent<Light>(); light.LightType = LightType.LIGHT_DIRECTIONAL; light.Color = new Color(0.2f, 0.2f, 0.2f); light.SpecularIntensity = 1.0f; // Create a "floor" consisting of several tiles for (int y = -5; y <= 5; ++y) { for (int x = -5; x <= 5; ++x) { Node floorNode = scene.CreateChild("FloorTile"); floorNode.Position = new Vector3(x*20.5f, -0.5f, y*20.5f); floorNode.Scale = new Vector3(20.0f, 1.0f, 20.0f); StaticModel floorObject = floorNode.CreateComponent<StaticModel>(); floorObject.Model = cache.Get<Model>("Models/Box.mdl"); floorObject.SetMaterial(cache.Get<Material>("Materials/Stone.xml")); } } // Create a "screen" like object for viewing the second scene. Construct it from two StaticModels, a box for the frame // and a plane for the actual view { Node boxNode = scene.CreateChild("ScreenBox"); boxNode.Position = new Vector3(0.0f, 10.0f, 0.0f); boxNode.Scale = new Vector3(21.0f, 16.0f, 0.5f); StaticModel boxObject = boxNode.CreateComponent<StaticModel>(); boxObject.Model = cache.Get<Model>("Models/Box.mdl"); boxObject.SetMaterial(cache.Get<Material>("Materials/Stone.xml")); Node screenNode = scene.CreateChild("Screen"); screenNode.Position = new Vector3(0.0f, 10.0f, -0.27f); screenNode.Rotation = new Quaternion(-90.0f, 0.0f, 0.0f); screenNode.Scale = new Vector3(20.0f, 0.0f, 15.0f); StaticModel screenObject = screenNode.CreateComponent<StaticModel>(); screenObject.Model = cache.Get<Model>("Models/Plane.mdl"); // Create a renderable texture (1024x768, RGB format), enable bilinear filtering on it Texture2D renderTexture = new Texture2D(); renderTexture.SetSize(1024, 768, Graphics.GetRGBFormat(), TextureUsage.TEXTURE_RENDERTARGET); renderTexture.FilterMode = TextureFilterMode.FILTER_BILINEAR; // Create a new material from scratch, use the diffuse unlit technique, assign the render texture // as its diffuse texture, then assign the material to the screen plane object Material renderMaterial = new Material(); renderMaterial.SetTechnique(0, cache.Get<Technique>("Techniques/DiffUnlit.xml"), 0, 0); renderMaterial.SetTexture(TextureUnit.TU_DIFFUSE, renderTexture); screenObject.SetMaterial(renderMaterial); // Get the texture's RenderSurface object (exists when the texture has been created in rendertarget mode) // and define the viewport for rendering the second scene, similarly as how backbuffer viewports are defined // to the Renderer subsystem. By default the texture viewport will be updated when the texture is visible // in the main view RenderSurface surface = renderTexture.RenderSurface; Viewport rttViewport = new Viewport(rttScene, rttCameraNode.GetComponent<Camera>()); surface.SetViewport(0, rttViewport); } // Create the camera. Limit far clip distance to match the fog CameraNode = scene.CreateChild("Camera"); var camera = CameraNode.CreateComponent<Camera>(); camera.FarClip = 300.0f; // Set an initial position for the camera scene node above the plane CameraNode.Position = new Vector3(0.0f, 7.0f, -30.0f); } }
public Issue1914 () { Content = new Rotator (); }
static void Main(string[] args) { var progId = Rotator.Choose(string.Empty); var driver = new Rotator(progId); driver.Connected = true; Console.WriteLine("Connected to Rotator Driver"); driver.Move(5); while (driver.IsMoving) { Console.WriteLine("Moving..."); } Console.WriteLine("Moved 5 degrees Relative"); //driver.Move(5); //while (driver.IsMoving) //{ // Console.WriteLine("Moving..."); //} //Console.WriteLine("Moved 5 degrees relative"); //driver.Move(5); //while (driver.IsMoving) //{ // Console.WriteLine("Moving..."); //} //Console.WriteLine("Moved 5 degrees Relative"); //Console.WriteLine("Moving to Absolute Pos 5"); //while (driver.IsMoving) //{ // Console.WriteLine("Moving..."); //} Console.WriteLine("Moving to Absolute Pos 5"); driver.MoveAbsolute(5.9F); while (driver.IsMoving) { Console.WriteLine("Moving... Current Position = " + driver.Position.ToString()); Console.WriteLine("Moving... Target Position = " + driver.TargetPosition.ToString()); } Console.WriteLine("Moving to Absolute Pos 15"); driver.MoveAbsolute(75.125F); while (driver.IsMoving) { Console.WriteLine("Moving... Current Position = " + driver.Position.ToString() ); Console.WriteLine("Moving... Target Position = " + driver.TargetPosition.ToString()); } Console.WriteLine("Finished Move! Current Position = " + driver.Position.ToString()); Console.WriteLine("Moving to Absolute Pos 5"); driver.MoveAbsolute(5.9F); while (driver.IsMoving) { Console.WriteLine("Moving... Current Position = " + driver.Position.ToString()); Console.WriteLine("Moving... Target Position = " + driver.TargetPosition.ToString()); } Console.WriteLine("Moving... Current Position = " + driver.Position.ToString()); Console.WriteLine("Moving... Target Position = " + driver.TargetPosition.ToString()); driver.Connected = false; Console.WriteLine("Disconnected to Rotator Driver"); Console.ReadLine(); }
public static Rotator GetRotation(this GridDirection direction) { Vector3 offset = direction.AsOffset(); offset.Normalize(); Rotator rotation = new Rotator((int)((Angle)Math.Atan2(offset.Y, offset.X)).InDegrees, (int)((Angle)Math.Atan2(offset.Z, offset.Y)).InDegrees, 0); return rotation; }
public SerializableVehicle CreateVehicle(Model model, Vector3 pos, Rotator rotation, Color primColor, Color seconColor) { var tmpVeh = new Vehicle(model, pos) { PrimaryColor = primColor, SecondaryColor = seconColor, }; var blip = tmpVeh.AttachBlip(); blip.Color = Color.Orange; blip.Scale = 0.7f; _blips.Add(blip); tmpVeh.IsPositionFrozen = false; tmpVeh.Rotation = rotation; var tmpObj = new SerializableVehicle(); tmpObj.SetEntity(tmpVeh); tmpObj.SpawnAfter = 0; tmpObj.RemoveAfter = 0; tmpObj.FailMissionOnDeath = false; tmpObj.Health = 1000; CurrentMission.Vehicles.Add(tmpObj); return tmpObj; }
private void Form1_Load(object sender, EventArgs e) { try { // Set the view menu checked states positionAndTemperatureToolStripMenuItem.Checked = Properties.Settings.Default.DisplayPositionAndTemperature; relativeFocusAdjustToolStripMenuItem.Checked = Properties.Settings.Default.DisplayRelativeFocusAdjust; temperatureCompensationToolStripMenuItem.Checked = Properties.Settings.Default.DisplayTempComp; absoluteFocusAdjustToolStripMenuItem.Checked = Properties.Settings.Default.DisplayAbsoluteFocusAdjust; relativeFocusOffsetsToolStripMenuItem.Checked = Properties.Settings.Default.DisplayRelativeFocusOffsets; absoluteFocusPresetsToolStripMenuItem.Checked = Properties.Settings.Default.DisplayAbsoluteFocusPresets; rotatorGraphic1.NewPositionRequested += new EventHandler(rotatorGraphic1_NewPositionRequested); if (Properties.Settings.Default.Focuser2Disabled) { //Only Focuser 1 is disabled if (Properties.Settings.Default.SwitchF1F2) Foc1_CHK.Checked = !Properties.Settings.Default.Focuser2Disabled; //Only Focuser 2 is disabled else Foc2_CHK.Checked = !Properties.Settings.Default.Focuser2Disabled; } //Both are enabled else { Foc1_CHK.Checked = !Properties.Settings.Default.Focuser2Disabled; Foc2_CHK.Checked = !Properties.Settings.Default.Focuser2Disabled; } // hook up the view item checked_changed events positionAndTemperatureToolStripMenuItem.CheckedChanged += new EventHandler(this.viewItemToolStripMenuItem_CheckStateChanged); relativeFocusAdjustToolStripMenuItem.CheckedChanged += new EventHandler(this.viewItemToolStripMenuItem_CheckStateChanged); temperatureCompensationToolStripMenuItem.CheckedChanged += new EventHandler(this.viewItemToolStripMenuItem_CheckStateChanged); absoluteFocusAdjustToolStripMenuItem.CheckedChanged += new EventHandler(this.viewItemToolStripMenuItem_CheckStateChanged); relativeFocusOffsetsToolStripMenuItem.CheckedChanged += new EventHandler(this.viewItemToolStripMenuItem_CheckStateChanged); absoluteFocusPresetsToolStripMenuItem.CheckedChanged += new EventHandler(this.viewItemToolStripMenuItem_CheckStateChanged); Foc1_CHK.CheckedChanged += new EventHandler(this.viewItemToolStripMenuItem_CheckStateChanged); Foc2_CHK.CheckedChanged += new EventHandler(this.viewItemToolStripMenuItem_CheckStateChanged); alwaysOnTopToolStripMenuItem.CheckedChanged += new EventHandler(alwaysOnTopToolStripMenuItem_CheckedChanged); alwaysOnTopToolStripMenuItem.Checked = Properties.Settings.Default.AlwaysOnTop; // We do this after so the change takes affect now... // adjust form height for user preferences setFormHeight(); EventLogger.LogMessage("Creating Gemini Focuser Driver", TraceLevel.Info); myFoc = new ASCOM.DriverAccess.Focuser("ASCOM.Gemini.Focuser"); EventLogger.LogMessage("Creating Gemini Rotator Driver", TraceLevel.Info); myRot = new ASCOM.DriverAccess.Rotator("ASCOM.Gemini.Rotator"); FocLastConnectedState = !myFoc.Connected; // Set these to the opposite so that controls are immediatly refreshed. RotLastConnectedState = !myRot.Connected; } catch (Exception ex) { EventLogger.LogMessage("An error occurred while creating instances of Gemini ASCOM Drivers. " + ex.Message, TraceLevel.Error); CustomErrorBox error = new CustomErrorBox("An error occurred while creating the initial instances of the Gemini ASCOM Driver. " + "The program cannot continue. Please contact technical support.", ex.Message); error.ShowDialog(); Application.Exit(); } LoadFocusOffsets_F1(); LoadFocusPresets_F1(); //LoadFocusOffsets_F2(); //LoadFocusPresets_F2(); setFormWidth(); //setFormHeight(); Automatically occurs. }
public void BuildFor(SerializableData.Objectives.SerializableActorObjective actor) { Clear(); #region SpawnAfter { var item = new MenuListItem("Spawn After Objective", StaticData.StaticLists.NumberMenu, actor.SpawnAfter); item.OnListChanged += (sender, index) => { actor.SpawnAfter = index; }; AddItem(item); } #endregion #region ObjectiveIndex { var item = new MenuListItem("Objective Index", StaticData.StaticLists.ObjectiveIndexList, actor.ActivateAfter); item.OnListChanged += (sender, index) => { actor.ActivateAfter = index; if (string.IsNullOrEmpty(Editor.CurrentMission.ObjectiveNames[actor.ActivateAfter])) { MenuItems[4].SetRightBadge(NativeMenuItem.BadgeStyle.Alert); MenuItems[4].SetRightLabel(""); } else { var title = Editor.CurrentMission.ObjectiveNames[actor.ActivateAfter]; MenuItems[4].SetRightLabel(title.Length > 20 ? title.Substring(0, 20) + "..." : title); MenuItems[4].SetRightBadge(NativeMenuItem.BadgeStyle.None); } }; AddItem(item); } #endregion // TODO: Change NumberMenu to max num of objectives in mission // Note: if adding items before weapons, change item order in VehiclePropertiesMenu #region Weapons { var item = new NativeMenuItem("Weapon"); var dict = StaticData.WeaponsData.Database.ToDictionary(k => k.Key, k => k.Value.Select(x => x.Item1).ToArray()); var menu = new CategorySelectionMenu(dict, "Weapon", true, "SELECT WEAPON"); menu.Build("Melee"); Children.Add(menu); AddItem(item); BindMenuToItem(menu, item); menu.SelectionChanged += (sender, eventargs) => { GameFiber.StartNew(delegate { var hash = StaticData.WeaponsData.Database[menu.CurrentSelectedCategory].First( tuple => tuple.Item1 == menu.CurrentSelectedItem).Item2; NativeFunction.CallByName<uint>("REMOVE_ALL_PED_WEAPONS", actor.GetPed().Handle.Value, true); actor.GetPed().GiveNewWeapon(hash, actor.WeaponAmmo == 0 ? 9999 : actor.WeaponAmmo, true); actor.WeaponHash = hash; }); }; } { var listIndex = actor.WeaponAmmo == 0 ? StaticData.StaticLists.AmmoChoses.FindIndex(n => n == (dynamic) 9999) : StaticData.StaticLists.AmmoChoses.FindIndex(n => n == (dynamic) actor.WeaponAmmo); var item = new MenuListItem("Ammo Count", StaticData.StaticLists.AmmoChoses, listIndex); item.OnListChanged += (sender, index) => { int newAmmo = int.Parse(((MenuListItem) sender).IndexToItem(index).ToString(), CultureInfo.InvariantCulture); actor.WeaponAmmo = newAmmo; if(actor.WeaponHash == 0) return; NativeFunction.CallByName<uint>("REMOVE_ALL_PED_WEAPONS", actor.GetPed().Handle.Value, true); ((Ped)actor.GetPed()).GiveNewWeapon(actor.WeaponHash, newAmmo, true); }; AddItem(item); } #endregion #region Objective Name { var item = new NativeMenuItem("Objective Name"); if (string.IsNullOrEmpty(Editor.CurrentMission.ObjectiveNames[actor.ActivateAfter])) item.SetRightBadge(NativeMenuItem.BadgeStyle.Alert); else { var title = Editor.CurrentMission.ObjectiveNames[actor.ActivateAfter]; item.SetRightLabel(title.Length > 20 ? title.Substring(0, 20) + "..." : title); } item.Activated += (sender, selectedItem) => { GameFiber.StartNew(delegate { ResetKey(Common.MenuControls.Back); Editor.DisableControlEnabling = true; string title = Util.GetUserInput(); if (string.IsNullOrEmpty(title)) { item.SetRightBadge(NativeMenuItem.BadgeStyle.Alert); Editor.CurrentMission.ObjectiveNames[actor.ActivateAfter] = ""; SetKey(Common.MenuControls.Back, GameControl.CellphoneCancel, 0); Editor.DisableControlEnabling = false; return; } item.SetRightBadge(NativeMenuItem.BadgeStyle.None); title = Regex.Replace(title, "-=", "~"); Editor.CurrentMission.ObjectiveNames[actor.ActivateAfter] = title; selectedItem.SetRightLabel(title.Length > 20 ? title.Substring(0, 20) + "..." : title); SetKey(Common.MenuControls.Back, GameControl.CellphoneCancel, 0); }); }; AddItem(item); } #endregion #region Health { var listIndex = actor.Health == 0 ? StaticData.StaticLists.HealthArmorChoses.FindIndex(n => n == (dynamic)200) : StaticData.StaticLists.HealthArmorChoses.FindIndex(n => n == (dynamic)actor.Health); var item = new MenuListItem("Health", StaticData.StaticLists.HealthArmorChoses, listIndex); item.OnListChanged += (sender, index) => { int newAmmo = int.Parse(((MenuListItem)sender).IndexToItem(index).ToString(), CultureInfo.InvariantCulture); actor.Health = newAmmo; }; AddItem(item); } #endregion #region Armor { var listIndex = StaticData.StaticLists.HealthArmorChoses.FindIndex(n => n == (dynamic)actor.Armor); var item = new MenuListItem("Armor", StaticData.StaticLists.HealthArmorChoses, listIndex); item.OnListChanged += (sender, index) => { int newAmmo = int.Parse(((MenuListItem)sender).IndexToItem(index).ToString(), CultureInfo.InvariantCulture); actor.Armor = newAmmo; }; AddItem(item); } #endregion #region Accuracy { var listIndex = StaticData.StaticLists.AccuracyList.FindIndex(n => n == (dynamic)actor.Accuracy); var item = new MenuListItem("Accuracy", StaticData.StaticLists.AccuracyList, listIndex); item.OnListChanged += (sender, index) => { int newAmmo = int.Parse(((MenuListItem)sender).IndexToItem(index).ToString(), CultureInfo.InvariantCulture); actor.Accuracy = newAmmo; }; AddItem(item); } #endregion #region Relationship { var item = new MenuListItem("Relationship", StaticData.StaticLists.RelationshipGroups, actor.RelationshipGroup); item.OnListChanged += (sender, index) => { actor.RelationshipGroup = index; }; AddItem(item); } #endregion #region Behaviour { var wpyItem = new NativeMenuItem("Waypoints"); { var waypMenu = new WaypointEditor(actor); BindMenuToItem(waypMenu.CreateWaypointMenu, wpyItem); Vector3 camPos = new Vector3(); Rotator camRot = new Rotator(); wpyItem.Activated += (sender, selectedItem) => { camPos = Editor.MainCamera.Position; camRot = Editor.MainCamera.Rotation; waypMenu.Enter(); Editor.WaypointEditor = waypMenu; }; waypMenu.OnEditorExit += (sender, args) => { Editor.WaypointEditor = null; Editor.DisableControlEnabling = true; if (camPos != new Vector3()) { Editor.MainCamera.Position = camPos; Editor.MainCamera.Rotation = camRot; } }; } if (actor.Behaviour != 4) // Follow Waypoints wpyItem.Enabled = false; var item = new MenuListItem("Behaviour", StaticData.StaticLists.Behaviour, actor.Behaviour); item.OnListChanged += (sender, index) => { actor.Behaviour = index; wpyItem.Enabled = index == 4; }; AddItem(item); AddItem(wpyItem); } #endregion #region Show Health Bar { var item = new MenuCheckboxItem("Show Healthbar", actor.ShowHealthBar); AddItem(item); item.CheckboxEvent += (sender, @checked) => { actor.ShowHealthBar = @checked; MenuItems[12].Enabled = @checked; }; } #endregion #region Bar Name { var item = new NativeMenuItem("Healthbar Label"); AddItem(item); if (!actor.ShowHealthBar) item.Enabled = false; if (string.IsNullOrEmpty(actor.Name) && actor.ShowHealthBar) actor.Name = "HEALTH"; if(actor.ShowHealthBar) item.SetRightLabel(actor.Name.Length > 20 ? actor.Name.Substring(0, 20) : actor.Name); item.Activated += (sender, selectedItem) => { GameFiber.StartNew(delegate { ResetKey(Common.MenuControls.Back); Editor.DisableControlEnabling = true; string title = Util.GetUserInput(); if (string.IsNullOrEmpty(title)) { actor.Name = "HEALTH"; item.SetRightLabel(actor.Name.Length > 20 ? actor.Name.Substring(0, 20) : actor.Name); SetKey(Common.MenuControls.Back, GameControl.CellphoneCancel, 0); Editor.DisableControlEnabling = false; return; } title = Regex.Replace(title, "-=", "~"); actor.Name = title; item.SetRightLabel(actor.Name.Length > 20 ? actor.Name.Substring(0, 20) : actor.Name); SetKey(Common.MenuControls.Back, GameControl.CellphoneCancel, 0); }); }; } #endregion RefreshIndex(); }
public void BuildFor(SerializableData.SerializablePed actor) { Clear(); #region SpawnAfter { var item = new MenuListItem("Spawn After Objective", StaticData.StaticLists.NumberMenu, actor.SpawnAfter); item.OnListChanged += (sender, index) => { actor.SpawnAfter = index; }; AddItem(item); } #endregion #region RemoveAfter { var item = new MenuListItem("Remove After Objective", StaticData.StaticLists.RemoveAfterList, actor.RemoveAfter); item.OnListChanged += (sender, index) => { actor.RemoveAfter = index; }; AddItem(item); } #endregion // TODO: Change NumberMenu to max num of objectives in mission // Note: if adding items before weapons, change item order in VehiclePropertiesMenu #region Weapons { var item = new NativeMenuItem("Weapon"); var dict = StaticData.WeaponsData.Database.ToDictionary(k => k.Key, k => k.Value.Select(x => x.Item1).ToArray()); var menu = new CategorySelectionMenu(dict, "Weapon", true, "SELECT WEAPON"); menu.Build("Melee"); Children.Add(menu); AddItem(item); BindMenuToItem(menu, item); menu.SelectionChanged += (sender, eventargs) => { GameFiber.StartNew(delegate { var hash = StaticData.WeaponsData.Database[menu.CurrentSelectedCategory].First( tuple => tuple.Item1 == menu.CurrentSelectedItem).Item2; NativeFunction.CallByName<uint>("REMOVE_ALL_PED_WEAPONS", actor.GetEntity().Handle.Value, true); ((Ped) actor.GetEntity()).GiveNewWeapon(hash, actor.WeaponAmmo == 0 ? 9999 : actor.WeaponAmmo, true); actor.WeaponHash = hash; }); }; } { var listIndex = actor.WeaponAmmo == 0 ? StaticData.StaticLists.AmmoChoses.FindIndex(n => n == (dynamic) 9999) : StaticData.StaticLists.AmmoChoses.FindIndex(n => n == (dynamic) actor.WeaponAmmo); var item = new MenuListItem("Ammo Count", StaticData.StaticLists.AmmoChoses, listIndex); item.OnListChanged += (sender, index) => { int newAmmo = int.Parse(((MenuListItem) sender).IndexToItem(index).ToString(), CultureInfo.InvariantCulture); actor.WeaponAmmo = newAmmo; if(actor.WeaponHash == 0) return; NativeFunction.CallByName<uint>("REMOVE_ALL_PED_WEAPONS", actor.GetEntity().Handle.Value, true); ((Ped)actor.GetEntity()).GiveNewWeapon(actor.WeaponHash, newAmmo, true); }; AddItem(item); } #endregion #region Health { var listIndex = actor.Health == 0 ? StaticData.StaticLists.HealthArmorChoses.FindIndex(n => n == (dynamic)200) : StaticData.StaticLists.HealthArmorChoses.FindIndex(n => n == (dynamic)actor.Health); var item = new MenuListItem("Health", StaticData.StaticLists.HealthArmorChoses, listIndex); item.OnListChanged += (sender, index) => { int newAmmo = int.Parse(((MenuListItem)sender).IndexToItem(index).ToString(), CultureInfo.InvariantCulture); actor.Health = newAmmo; }; AddItem(item); } #endregion #region Armor { var listIndex = StaticData.StaticLists.HealthArmorChoses.FindIndex(n => n == (dynamic)actor.Armor); var item = new MenuListItem("Armor", StaticData.StaticLists.HealthArmorChoses, listIndex); item.OnListChanged += (sender, index) => { int newAmmo = int.Parse(((MenuListItem)sender).IndexToItem(index).ToString(), CultureInfo.InvariantCulture); actor.Armor = newAmmo; }; AddItem(item); } #endregion #region Accuracy { var listIndex = StaticData.StaticLists.AccuracyList.FindIndex(n => n == (dynamic)actor.Accuracy); var item = new MenuListItem("Accuracy", StaticData.StaticLists.AccuracyList, listIndex); item.OnListChanged += (sender, index) => { int newAmmo = int.Parse(((MenuListItem)sender).IndexToItem(index).ToString(), CultureInfo.InvariantCulture); actor.Accuracy = newAmmo; }; AddItem(item); } #endregion #region Relationship { var item = new MenuListItem("Relationship", StaticData.StaticLists.RelationshipGroups, actor.RelationshipGroup); item.OnListChanged += (sender, index) => { actor.RelationshipGroup = index; }; AddItem(item); } #endregion #region Behaviour { var wpyItem = new NativeMenuItem("Waypoints"); { var waypMenu = new WaypointEditor(actor); BindMenuToItem(waypMenu.CreateWaypointMenu, wpyItem); Vector3 camPos = new Vector3(); Rotator camRot = new Rotator(); wpyItem.Activated += (sender, selectedItem) => { camPos = Editor.MainCamera.Position; camRot = Editor.MainCamera.Rotation; waypMenu.Enter(); Editor.WaypointEditor = waypMenu; }; waypMenu.OnEditorExit += (sender, args) => { Editor.WaypointEditor = null; Editor.DisableControlEnabling = true; if (camPos != new Vector3()) { Editor.MainCamera.Position = camPos; Editor.MainCamera.Rotation = camRot; } }; } if (actor.Behaviour != 4) // Follow Waypoints wpyItem.Enabled = false; var item = new MenuListItem("Behaviour", StaticData.StaticLists.Behaviour, actor.Behaviour); item.OnListChanged += (sender, index) => { actor.Behaviour = index; wpyItem.Enabled = index == 4; }; AddItem(item); AddItem(wpyItem); } #endregion #region FailOnDeath { var item = new MenuCheckboxItem("Mission Fail On Death", actor.FailMissionOnDeath); item.CheckboxEvent += (sender, @checked) => { actor.FailMissionOnDeath = @checked; }; AddItem(item); } #endregion RefreshIndex(); }
public SerializablePickupObjective CreatePickupObjective(int weaponHash, Vector3 pos, Rotator rot) { var tmpObject = new Rage.Object(new Model("prop_mp_repair"), pos); tmpObject.Rotation = rot; tmpObject.Position = pos; tmpObject.IsPositionFrozen = true; var tmpObj = new SerializablePickupObjective(); tmpObj.SetObject(tmpObject); tmpObj.SpawnAfter = 0; tmpObj.ActivateAfter = 0; tmpObj.Respawn = false; tmpObj.Ammo = 9999; tmpObj.PickupHash = weaponHash; CurrentMission.Objectives.Add(tmpObj); return tmpObj; }