Example #1
0
        public void Init(Telemetry tel)
        {
            // Do not move N computation below, N is used by LLAtoECEF method!
            gpsLLA = tel.uavPosition;
            gpsLLA.Press_Altitude = gpsLLA.Altitude - localGeoidHeight;

            N      = a / Math.Sqrt(1 - e2 * Math.Pow(Math.Sin(gpsLLA.Latitude), 2));
            cosLat = Math.Cos(gpsLLA.Latitude);
            sinLat = Math.Sin(gpsLLA.Latitude);
            cosLon = Math.Cos(gpsLLA.Longitude);
            sinLon = Math.Sin(gpsLLA.Longitude);

            gpsECEF = LLAtoECEF(gpsLLA);

            uavAngles = tel.uavAngles;
            cosYaw    = Math.Cos(uavAngles.Yaw);
            sinYaw    = Math.Sin(uavAngles.Yaw);
            if (zeroUavPitchRoll)
            {
                cosPitch = cosRoll = 1;
                sinPitch = sinRoll = 0;
            }
            else
            {
                cosPitch = Math.Cos(uavAngles.Pitch);
                sinPitch = Math.Sin(uavAngles.Pitch);
                cosRoll  = Math.Cos(uavAngles.Roll);
                sinRoll  = Math.Sin(uavAngles.Roll);
            }

            R_ECEF_LNED = null;
            R_LNED_ECEF = null;
            R_LNED_BODY = null;
            R_BODY_LNED = null;
        }
Example #2
0
        /// <summary>
        /// Writes the transformation matrix to a mat file.
        /// </summary>
        /// <param name="matFile">The MAT file to write.</param>
        /// <param name="rotationMatrix">The rotation matrix.</param>
        /// <param name="translation">The translation matrix.</param>
        private void WriteRotationMatrixAndTranslationToMatFile(File matFile, double[,] rotationMatrix, double[] translation)
        {
            // Delete the file if a previous one exists
            if (System.IO.File.Exists(matFile.Path))
            {
                System.IO.File.Delete(matFile.Path);
            }

            string xLine = null;
            string yLine = null;
            var    zLine = "";

            // PowerInspect writes the MAT files using Invariant culture.
            string transLine = "   T   " + Convert.ToString(translation[0], CultureInfo.InvariantCulture) + " " +
                               Convert.ToString(translation[1], CultureInfo.InvariantCulture) + " " +
                               Convert.ToString(translation[2], CultureInfo.InvariantCulture);

            var rotations = Angles.GetRotationsFromMatrixXYZ(rotationMatrix);

            zLine = "   R Z " + Convert.ToString(rotations[0].Value, CultureInfo.InvariantCulture);
            yLine = "   R Y " + Convert.ToString(rotations[1].Value, CultureInfo.InvariantCulture);
            xLine = "   R X " + Convert.ToString(rotations[2].Value, CultureInfo.InvariantCulture);
            var lines = new List <string>();

            lines.Add(xLine);
            lines.Add(yLine);
            lines.Add(zLine);
            lines.Add(transLine);
            lines.Add("*");
            lines.Add("");

            // create a new text document
            System.IO.File.WriteAllLines(matFile.Path, lines);
        }
Example #3
0
 public Telemetry()
 {
     uavAngles       = new Angles();
     uavPosition     = new Position();
     uavAcceleration = new Acceleration();
     uavSpeed        = new Speed();
 }
Example #4
0
        //-----------------------------------------------------------------------------
        // Seed Bouncing
        //-----------------------------------------------------------------------------

        // Try to bounce off of a seed bouncer tile, returning true if the bounce was successful.
        private bool AttemptBounce(TileSeedBouncer seedBouncer)
        {
            // Determine the angle the we are moving in.
            angle = Angles.NearestFromVector(physics.Velocity);

            // Determine the angle to bounce off at.
            int newAngle            = -1;
            int bouncerAngle        = seedBouncer.Angle;
            int bouncerAngleReverse = Angles.Reverse(seedBouncer.Angle);
            int plus1  = Angles.Add(angle, 1, WindingOrder.Clockwise);
            int plus2  = Angles.Add(angle, 2, WindingOrder.Clockwise);
            int minus1 = Angles.Add(angle, 1, WindingOrder.CounterClockwise);

            if (plus2 == bouncerAngle || plus2 == bouncerAngleReverse)
            {
                newAngle = Angles.Reverse(angle);
            }
            else if (plus1 == bouncerAngle || plus1 == bouncerAngleReverse)
            {
                newAngle = Angles.Add(angle, 2, WindingOrder.Clockwise);
            }
            else if (minus1 == bouncerAngle || minus1 == bouncerAngleReverse)
            {
                newAngle = Angles.Add(angle, 2, WindingOrder.CounterClockwise);
            }

            // Start moving in the new angle.
            if (newAngle >= 0)
            {
                angle            = newAngle;
                physics.Velocity = Angles.ToVector(angle) * physics.Velocity.Length;
                return(true);
            }
            return(false);
        }
Example #5
0
        protected override void OnGetCameraTransform(out Vec3 position, out Vec3 forward, out Vec3 up, ref Degree cameraFov)
        {
            //To use data about orientation the camera if the cut scene is switched on
            if (IsCutSceneEnabled())
            {
                if (CutSceneManager.Instance.GetCamera(out position, out forward, out up, out cameraFov))
                {
                    return;
                }
            }

            Vec3 offset;
            {
                Quat rot = new Angles(0, 0, MathFunctions.RadToDeg(cameraDirection.Horizontal)).ToQuat();
                rot    *= new Angles(0, MathFunctions.RadToDeg(cameraDirection.Vertical), 0).ToQuat();
                offset  = rot * new Vec3(1, 0, 0);
                offset *= cameraDistance;
            }

            Vec3 lookAt = new Vec3(cameraPosition.X, cameraPosition.Y, 0);

            forward   = -offset;
            position  = lookAt + offset;
            up        = new Vec3(0, 0, 1);
            cameraFov = 80f;
        }
Example #6
0
        void MomentaryTurnToPositionUpdate(Vec3 turnToPosition)
        {
            if (turretBody == null || baseBody == null || mainGunAttachedObject == null)
            {
                return;
            }

            Vec3 diff = turnToPosition - Position;

            Radian horizontalAngle = MathFunctions.ATan(diff.Y, diff.X);
            Radian verticalAngle   = MathFunctions.ATan(diff.Z, diff.ToVec2().Length());

            turretBody.Rotation = new Angles(0, 0, -horizontalAngle.InDegrees()).ToQuat();

            Quat rot = baseBody.Rotation.GetInverse() * turretBody.Rotation;

            Quat verticalRot = new Angles(0, verticalAngle.InDegrees(), 0).ToQuat();

            mainGunAttachedObject.PositionOffset = rot * mainGunOffsetPosition;
            mainGunAttachedObject.RotationOffset = rot * verticalRot;
            RecalculateMapBounds();

            if (EntitySystemWorld.Instance.IsServer())
            {
                server_shouldSendTurnToPosition = turnToPosition;
            }
        }
Example #7
0
        void ReadSpectatorMessage(PacketReader stream)
        {
            Vec3f  pos = stream.ReadVec3f();
            Angles ang = stream.ReadAngles();

            this.ScriptObject.SetToSpectator(World.Current, pos, ang);
        }
Example #8
0
        static void SpawnPlayer(ArenaClient client)
        {
            var     charInfo = client.CharInfo;
            NPCInst npc      = new NPCInst(NPCDef.Get(charInfo.BodyMesh == HumBodyMeshs.HUM_BODY_NAKED0 ? "maleplayer" : "femaleplayer"))
            {
                UseCustoms     = true,
                CustomBodyTex  = charInfo.BodyTex,
                CustomHeadMesh = charInfo.HeadMesh,
                CustomHeadTex  = charInfo.HeadTex,
                CustomVoice    = charInfo.Voice,
                CustomFatness  = charInfo.Fatness,
                CustomScale    = new Vec3f(charInfo.BodyWidth, 1.0f, charInfo.BodyWidth),
                CustomName     = charInfo.Name
            };

            foreach (string e in client.HordeClass.Equipment)
            {
                ItemInst item = new ItemInst(ItemDef.Get(e));
                npc.Inventory.AddItem(item);
                npc.EffectHandler.TryEquipItem(item);
            }

            if (client.HordeClass.NeedsBolts)
            {
            }

            npc.Inventory.AddItem(new ItemInst(ItemDef.Get("hptrank")));

            Vec3f  spawnPos = Randomizer.GetVec3fRad(activeDef.SpawnPos, activeDef.SpawnRange);
            Angles spawnAng = Randomizer.GetYaw();

            //npc.TeamID = 0;
            npc.Spawn(activeWorld, spawnPos, spawnAng);
            client.SetControl(npc);
        }
Example #9
0
        protected virtual void UpdateGuidePos(long now)
        {
            if (now < guidedNextUpdate)
            {
                return;
            }

            Vec3f          pos = this.Position;
            Angles         ang = this.Angles;
            VobEnvironment env = this.Environment;

            if (now - guidedNextUpdate < TimeSpan.TicksPerSecond)
            {
                // nothing really changed, only update every second
                if (pos.GetDistance(guidedLastPos) < MinPositionDistance &&
                    !ang.DifferenceIsBigger(guidedLastAng, MinAnglesDifference) &&
                    env == guidedLastEnv)
                {
                    return;
                }
            }

            guidedLastPos = pos;
            guidedLastAng = ang;
            guidedLastEnv = env;

            Messages.WritePosDirMessage(this, pos, ang, env);

            guidedNextUpdate = now + PosUpdateInterval;

            //this.ScriptObject.OnPosChanged();
        }
Example #10
0
        static NPCInst SpawnEnemy(HordeEnemy enemy, Vec3f spawnPoint, float spawnRange = 100)
        {
            NPCInst npc = new NPCInst(NPCDef.Get(enemy.NPCDef));

            if (enemy.WeaponDef != null)
            {
                ItemInst item = new ItemInst(ItemDef.Get(enemy.WeaponDef));
                npc.Inventory.AddItem(item);
                npc.EffectHandler.TryEquipItem(item);
            }

            if (enemy.ArmorDef != null)
            {
                ItemInst item = new ItemInst(ItemDef.Get(enemy.ArmorDef));
                npc.Inventory.AddItem(item);
                npc.EffectHandler.TryEquipItem(item);
            }

            npc.SetHealth(enemy.Health, enemy.Health);

            Vec3f  spawnPos = Randomizer.GetVec3fRad(spawnPoint, spawnRange);
            Angles spawnAng = Randomizer.GetYaw();

            //npc.TeamID = 1;
            npc.BaseInst.SetNeedsClientGuide(true);
            npc.Spawn(activeWorld, spawnPos, spawnAng);
            return(npc);
        }
Example #11
0
    private static int ShortestAngleDegrees(int from, int to)
    {
        var fromRadians = Angles.ToRadians(from);
        var toRadians   = Angles.ToRadians(to);

        return((int)Math.Round(Angles.ToDegrees(Angles.ShortestAngleBetween(fromRadians, toRadians))));
    }
Example #12
0
    public override void BuildInput(InputBuilder input)
    {
        base.BuildInput(input);

        var pawn = Local.Pawn;

        if (pawn == null)
        {
            return;
        }

        if ((Math.Abs(input.AnalogLook.pitch) + Math.Abs(input.AnalogLook.yaw)) > 0.0f)
        {
            if (!orbitEnabled)
            {
                orbitAngles = (orbitYawRot * orbitPitchRot).Angles();
                orbitAngles = orbitAngles.Normal;

                orbitYawRot   = Rotation.From(0.0f, orbitAngles.yaw, 0.0f);
                orbitPitchRot = Rotation.From(orbitAngles.pitch, 0.0f, 0.0f);
            }

            orbitEnabled   = true;
            timeSinceOrbit = 0.0f;

            orbitAngles.yaw   += input.AnalogLook.yaw;
            orbitAngles.pitch += input.AnalogLook.pitch;
            orbitAngles        = orbitAngles.Normal;
            orbitAngles.pitch  = orbitAngles.pitch.Clamp(MinOrbitPitch, MaxOrbitPitch);
        }

        input.ViewAngles = orbitEnabled ? orbitAngles : Entity.Rotation.Angles();
        input.ViewAngles = input.ViewAngles.Normal;
    }
        public override void BuildInput(InputBuilder input)
        {
            _lookAngles     += input.AnalogLook;
            _lookAngles.roll = 0;

            base.BuildInput(input);
        }
Example #14
0
        protected void Shoot()
        {
            Projectile projectile     = (Projectile)projectileType.GetConstructor(Type.EmptyTypes).Invoke(null);
            Vector2F   vectorToPlayer = (RoomControl.Player.Center - Center).Normalized * shootSpeed;

            if (aimType == AimType.SeekPlayer)
            {
                ShootProjectile(projectile, vectorToPlayer.Normalized * shootSpeed);
            }
            else if (aimType == AimType.SeekPlayerByDirection)
            {
                int shootDirection = Directions.NearestFromVector(vectorToPlayer);
                ShootFromDirection(projectile, shootDirection, shootSpeed);
            }
            else if (aimType == AimType.SeekPlayerByAngle)
            {
                int shootAngle = Angles.NearestFromVector(vectorToPlayer);
                ShootFromAngle(projectile, shootAngle, shootSpeed);
            }
            else
            {
                ShootFromDirection(projectile, direction, shootSpeed);
            }

            //Pause(shootPauseDuration);
        }
Example #15
0
    public override void BuildInput(ClientInput input)
    {
        base.BuildInput(input);

        var player = Player.Local;

        if (player == null)
        {
            return;
        }

        if ((Math.Abs(input.AnalogLook.pitch) + Math.Abs(input.AnalogLook.yaw)) > 0.0f)
        {
            if (!orbitEnabled)
            {
                orbitAngles = Rot.Angles();
                orbitAngles = orbitAngles.Normal;

                orbitYawRot   = Rotation.From(0.0f, orbitAngles.yaw, 0.0f);
                orbitPitchRot = Rotation.From(orbitAngles.pitch, 0.0f, 0.0f);
            }

            orbitEnabled = true;
            orbitTimer   = Time.Now + OrbitCooldown;

            orbitAngles.yaw   += input.AnalogLook.yaw;
            orbitAngles.pitch += input.AnalogLook.pitch;
            orbitAngles        = orbitAngles.Normal;
            orbitAngles.pitch  = orbitAngles.pitch.Clamp(MinOrbitPitch, MaxOrbitPitch);
        }

        input.ViewAngles = orbitAngles.WithYaw(orbitAngles.yaw - player.WorldRot.Yaw());
        input.ViewAngles = input.ViewAngles.Normal;
    }
Example #16
0
        void UpdateTaskControlKeys()
        {
            if (task_enabled)
            {
                Vec3   unit_pos = ControlledObject.Position;
                Vec3   unit_dir = ControlledObject.Rotation.GetForward();
                Vec3   need_dir = task_position - unit_pos;
                Angles angle    =
                    new Angles(ControlledObject.Rotation.ToAngles().Roll, ControlledObject.Rotation.ToAngles().Pitch,
                               Quat.FromDirectionZAxisUp(need_dir).ToAngles().Yaw);
                ControlledObject.Rotation = Quat.Slerp(ControlledObject.Rotation, angle.ToQuat(), 6.0f * TickDelta);

                ControlKeyPress(GameControlKeys.Forward, 1);

                if (ControlledObject.Rotation.GetUp().Z < .4f)
                {
                    ControlKeyPress(GameControlKeys.Reload, 1);
                }
                else
                {
                    ControlKeyRelease(GameControlKeys.Reload);
                }
            }
            else
            {
                ControlKeyRelease(GameControlKeys.Forward);
            }
        }
Example #17
0
    public override void UpdateCamera(Camera camera)
    {
        if (!Player.Local.IsValid())
        {
            return;
        }

        WorldPos = camera.Pos;
        WorldRot = camera.Rot;

        camera.ViewModelFieldOfView = FieldOfView;

        var newPitch = WorldRot.Pitch();
        var newYaw   = WorldRot.Yaw();

        var pitchDelta = Angles.NormalizeAngle(newPitch - lastPitch);
        var yawDelta   = Angles.NormalizeAngle(lastYaw - newYaw);

        var playerVelocity = Player.Local.Velocity;
        var verticalDelta  = playerVelocity.z * Time.Delta;
        var viewDown       = Rotation.FromPitch(newPitch).Up * -1.0f;

        verticalDelta *= (1.0f - System.MathF.Abs(viewDown.Cross(Vector3.Down).y));
        pitchDelta    -= verticalDelta * 1;

        var offset = CalcSwingOffset(pitchDelta, yawDelta);

        offset += CalcBobbingOffset(playerVelocity);

        WorldPos += WorldRot * offset;

        lastPitch = newPitch;
        lastYaw   = newYaw;
    }
Example #18
0
        public override void Update()
        {
            base.Update();

            // Find the start time for the current swing angle.
            int swingAngleStartTime = 0;

            for (int i = 0; i < swingAngleIndex; i++)
            {
                swingAngleStartTime += swingAngleDurations[i];
            }

            // Check for changing swing angles.
            bool changedAngles = false;
            int  t             = 0;
            int  time          = (int)playerTool.AnimationPlayer.PlaybackTime;

            for (int i = 0; i < swingAngleDurations.Length; i++)
            {
                if (time == t && swingAngleIndex != i)
                {
                    swingAngleIndex = i;
                    swingAngle      = Angles.Add(swingAngle, 1, swingAngleDirection);
                    changedAngles   = true;
                    break;
                }
                t += swingAngleDurations[i];
            }

            // Check for a swing tile peak (tile peaks happen just as the angle is changed).
            if (changedAngles)
            {
                Vector2F hitPoint        = player.Center + (Angles.ToVector(swingAngle, false) * 13);
                Point2I  hitTileLocation = player.RoomControl.GetTileLocation(hitPoint);
                OnSwingTilePeak(swingAngle, hitPoint);
            }

            Rectangle2I toolBox = swingCollisionBoxes[swingDirection, Math.Min(swingCollisionBoxes.Length - 1, swingAngleIndex)];

            toolBox.Point          += (Point2I)player.CenterOffset;
            playerTool.CollisionBox = toolBox;

            // Invoke any occuring timed actions.
            if (timedActions.ContainsKey(time))
            {
                timedActions[time].Invoke();
            }

            // Reset the swing when the button is pressed again.
            if (isReswingable && weapon.IsEquipped && weapon.IsButtonPressed())
            {
                Swing(player.UseDirection);
            }

            // End the swing.
            if (playerTool.AnimationPlayer.IsDone && player.Graphics.IsAnimationDone)
            {
                OnSwingEnd();
            }
        }
Example #19
0
        public static void CreateItemCmd(string item)
        {
            var owner = ConsoleSystem.Caller.Pawn;

            if (owner == null)
            {
                return;
            }

            BaseItem itemClass = ItemUtils.GetItemById(item);

            // Check to make sure we've actually returned an item.
            if (itemClass == null)
            {
                Log.Info($"Error: {item} could not be found.");
                return;
            }

            Log.Info($"{itemClass}");

            Vector3 pos = Vector3.Zero;
            Angles  ang = new Angles(0, owner.EyeRot.Angles().yaw, 0);

            var tr = Trace.Ray(owner.EyePos, owner.EyePos + owner.EyeRot.Forward * 200)
                     .UseHitboxes()
                     .Ignore(owner)
                     .Size(2)
                     .Run();

            pos = tr.EndPos;

            CreatePhysicalItem(itemClass, pos, ang);
        }
Example #20
0
        static void NPCInst_sOnNPCInstMove(NPCInst npc, Vec3f oldPos, Angles oldAng, NPCMovement oldMovement)
        {
            if (npc.IsDead || !npc.IsPlayer || npc.IsUnconscious)
            {
                return;
            }

            ArenaClient client = (ArenaClient)npc.Client;

            if (client.HordeClass == null)
            {
                return;
            }

            if (ActiveStandInst != null)
            {
                return;
            }

            foreach (var s in ActiveStands)
            {
                if (npc.GetPosition().GetDistance(s.Stand.Position) < s.Stand.Range)
                {
                    StartStand(s);
                    break;
                }
            }
        }
Example #21
0
 partial void pSpawn(World world, Vec3f position, Angles angles)
 {
     if (this.needsClientGuide)
     {
         SetGuide(FindNewGuide());
     }
 }
Example #22
0
 public virtual void BuildInput(ClientInput owner)
 {
     if (Zoomed)
     {
         owner.ViewAngles = Angles.Lerp(owner.LastViewAngles, owner.ViewAngles, 0.2f);
     }
 }
Example #23
0
        private void PropertyValueChanged(object sender, string propertyname, string propertyvalue)
        {
            var val = _values.FirstOrDefault(x => x.OriginalKey == propertyname);
            var li  = KeyValuesList.Items.OfType <ListViewItem>().FirstOrDefault(x => ((string)x.Tag) == propertyname);

            if (val == null)
            {
                if (li != null)
                {
                    KeyValuesList.Items.Remove(li);
                }
                return;
            }
            val.IsModified = true;
            val.Value      = propertyvalue;
            if (li == null)
            {
                var dt = SmartEditButton.Checked ? val.DisplayText(Document.GameData) : val.OriginalKey;
                var dv = SmartEditButton.Checked ? val.DisplayValue(Document.GameData) : val.Value;
                li = new ListViewItem(dt)
                {
                    Tag = val.OriginalKey, BackColor = val.GetColour()
                };
                KeyValuesList.Items.Add(li).SubItems.Add(dv);
            }
            else
            {
                li.BackColor        = val.GetColour();
                li.SubItems[1].Text = SmartEditButton.Checked ? val.DisplayValue(Document.GameData) : val.Value;
            }
            if (propertyname == "angles" && propertyvalue != Angles.GetAnglePropertyString())
            {
                Angles.SetAnglePropertyString(propertyvalue);
            }
        }
Example #24
0
        public static bool RotateTowards(WoWPlayer PlayerUnit, Vector2 TargetUnitPos, double RotationThreshhold, bool DisableForward)
        {
            double mydiff = Angles.AngleDiff(Angles.Calculateangle(TargetUnitPos, PlayerUnit.Position), PlayerUnit.Rotation);

            if ((Math.Abs(mydiff) < RotationThreshhold))
            {
                SendKey.KeyUp(ConstController.WindowsVirtualKey.VK_LEFT, PlayerUnit.MovingInfo.IsTurningLeft, ref PlayerUnit.MovingInfo.myleft, PlayerUnit.WindowTitle);
                SendKey.KeyUp(ConstController.WindowsVirtualKey.VK_RIGHT, PlayerUnit.MovingInfo.IsTurningRight, ref PlayerUnit.MovingInfo.myright, PlayerUnit.WindowTitle);
                return(true);
            }
            else if (mydiff < 0)
            {
                if (DisableForward)
                {
                    SendKey.KeyUp(ConstController.WindowsVirtualKey.VK_UP, PlayerUnit.MovingInfo.IsMovingForward, ref PlayerUnit.MovingInfo.myforward, PlayerUnit.WindowTitle);
                }
                SendKey.KeyDown(ConstController.WindowsVirtualKey.VK_LEFT, !PlayerUnit.MovingInfo.IsTurningLeft, ref PlayerUnit.MovingInfo.myleft, PlayerUnit.WindowTitle);
                SendKey.KeyUp(ConstController.WindowsVirtualKey.VK_RIGHT, PlayerUnit.MovingInfo.IsTurningRight, ref PlayerUnit.MovingInfo.myright, PlayerUnit.WindowTitle);
            }
            else if (mydiff > 0)
            {
                if (DisableForward)
                {
                    SendKey.KeyUp(ConstController.WindowsVirtualKey.VK_UP, PlayerUnit.MovingInfo.IsMovingForward, ref PlayerUnit.MovingInfo.myforward, PlayerUnit.WindowTitle);
                }
                SendKey.KeyDown(ConstController.WindowsVirtualKey.VK_RIGHT, !PlayerUnit.MovingInfo.IsTurningRight, ref PlayerUnit.MovingInfo.myright, PlayerUnit.WindowTitle);
                SendKey.KeyUp(ConstController.WindowsVirtualKey.VK_LEFT, PlayerUnit.MovingInfo.IsTurningLeft, ref PlayerUnit.MovingInfo.myleft, PlayerUnit.WindowTitle);
            }
            return(false);
        }
Example #25
0
        protected override NPCInst SpawnNPC(NPCClass classDef, Vec3f pos, Angles ang, float posOffset = 100, int teamID = 1, bool giveAI = true)
        {
            NPCInst npc = base.SpawnNPC(classDef, pos, ang, posOffset, teamID, giveAI);

            npc.AllowHitTarget.Add(OnAllowHit);
            return(npc);
        }
Example #26
0
        // Constructor. CameraProperties remain constant during the mission
        public CAMFrame(CAMProperties camera)
        {
            zeroCamDistance = RTDPSettings.geolocationSettings.zeroCamDistance;
            zeroCamPanRoll  = RTDPSettings.geolocationSettings.zeroCamPanRoll;

            camPosition = camera.camPosition;

            scaleFactor = camera.pixelPitch;
            offsetX     = (camera.imageHeight - 1) * scaleFactor / 2;
            offsetY     = (camera.imageWidth - 1) * scaleFactor / 2;
            focalLength = camera.focalLength;

            camAngles = camera.camAngles;
            cosPitch  = Math.Cos(camAngles.Pitch);
            sinPitch  = Math.Sin(camAngles.Pitch);
            if (zeroCamPanRoll)
            {
                cosYaw = cosRoll = 1;
                sinYaw = sinRoll = 0;
            }
            else
            {
                cosYaw  = Math.Cos(camAngles.Yaw);
                sinYaw  = Math.Sin(camAngles.Yaw);
                cosRoll = Math.Cos(camAngles.Roll);
                sinRoll = Math.Sin(camAngles.Roll);
            }

            R_BODY_CAM = null;
            R_CAM_BODY = null;
        }
Example #27
0
        public override void OnReadProperties(PacketReader stream)
        {
            base.OnReadProperties(stream);
            this.ItemType     = (ItemTypes)stream.ReadByte();
            this.name         = stream.ReadString();
            this.visualChange = stream.ReadString();
            this.Material     = (ItemMaterials)stream.ReadByte();

            if (stream.ReadBit())
            {
                this.Range = stream.ReadUShort();
            }
            if (stream.ReadBit())
            {
                this.Damage = stream.ReadUShort();
            }
            if (stream.ReadBit())
            {
                this.Protection = stream.ReadUShort();
            }
            if (stream.ReadBit())
            {
                this.InvOffset = stream.ReadVec3f();
            }
            if (stream.ReadBit())
            {
                this.InvRotation = stream.ReadCompressedAngles();
            }
        }
Example #28
0
 public override void BuildInput(InputBuilder owner)
 {
     if (Zoomed)
     {
         owner.ViewAngles = Angles.Lerp(owner.OriginalViewAngles, owner.ViewAngles, 0.2f);
     }
 }
Example #29
0
        public override void BuildInput(ClientInput input)
        {
            if (thirdperson_orbit && input.Down(InputButton.Walk))
            {
                if (input.Down(InputButton.Attack1))
                {
                    orbitDistance += input.AnalogLook.pitch;
                    orbitDistance  = orbitDistance.Clamp(0, 1000);
                }
                else
                {
                    orbitAngles.yaw   += input.AnalogLook.yaw;
                    orbitAngles.pitch += input.AnalogLook.pitch;
                    orbitAngles        = orbitAngles.Normal;
                    orbitAngles.pitch  = orbitAngles.pitch.Clamp(-89, 89);
                }

                input.AnalogLook = Angles.Zero;

                input.Clear();
                input.StopProcessing = true;
            }

            base.BuildInput(input);
        }
Example #30
0
        /// <summary>
        /// Turns Euler angles into a rotation matrix. The angles are assumed to be in degrees.
        /// </summary>
        public static Matrix3x3 ToMatrix(this Angles eulerAngles, bool invertedPitch = false)
        {
            var x = eulerAngles.Roll.ToRadians();
            var y = eulerAngles.Pitch.ToRadians();
            var z = eulerAngles.Yaw.ToRadians();

            if (invertedPitch)
            {
                y = -y;
            }

            return(new Matrix3x3(
                       (float)(Math.Cos(y) * Math.Cos(z)),
                       (float)(Math.Sin(x) * Math.Sin(y) * Math.Cos(z) - Math.Cos(x) * Math.Sin(z)),
                       (float)(Math.Cos(x) * Math.Sin(y) * Math.Cos(z) + Math.Sin(x) * Math.Sin(z)),

                       (float)(Math.Cos(y) * Math.Sin(z)),
                       (float)(Math.Sin(x) * Math.Sin(y) * Math.Sin(z) + Math.Cos(x) * Math.Cos(z)),
                       (float)(Math.Cos(x) * Math.Sin(y) * Math.Sin(z) - Math.Sin(x) * Math.Cos(z)),

                       (float)(-Math.Sin(y)),
                       (float)(Math.Sin(x) * Math.Cos(y)),
                       (float)(Math.Cos(x) * Math.Cos(y))
                       ));
        }
Example #31
0
        void Fire()
        {
            if( !Visible )
                return;

            if( fireworkBulletType == null )
                return;

            Bullet bullet = (Bullet)Entities.Instance.Create( fireworkBulletType, Map.Instance );

            bullet.Position = GetInterpolatedPosition() + new Vec3( 0, 0, .1f );

            EngineRandom random = World.Instance.Random;
            Quat rot = new Angles( random.NextFloatCenter() * 25, 90 + random.NextFloatCenter() * 25, 0 ).ToQuat();

            bullet.Rotation = rot;

            bullet.PostCreate();

            foreach( MapObjectAttachedObject attachedObject in bullet.AttachedObjects )
            {
                MapObjectAttachedRibbonTrail attachedRibbonTrail = attachedObject as MapObjectAttachedRibbonTrail;
                if( attachedRibbonTrail == null )
                    continue;

                ColorValue color;
                switch( random.Next( 4 ) )
                {
                case 0: color = new ColorValue( 1, 0, 0 ); break;
                case 1: color = new ColorValue( 0, 1, 0 ); break;
                case 2: color = new ColorValue( 0, 0, 1 ); break;
                case 3: color = new ColorValue( 1, 1, 0 ); break;
                default: color = new ColorValue( 0, 0, 0 ); break;
                }

                if( attachedRibbonTrail.RibbonTrail != null )
                    attachedRibbonTrail.RibbonTrail.Chains[ 0 ].InitialColor = color;
            }
        }
Example #32
0
File: Tank.cs Project: whztt07/SDK
        void UpdateTowerTransform()
        {
            if( towerBody == null || chassisBody == null || mainGunAttachedObject == null )
                return;

            Radian horizontalAngle = towerLocalDirection.Horizontal;
            Radian verticalAngle = towerLocalDirection.Vertical;

            Range gunRotationRange = Type.GunRotationAngleRange * MathFunctions.PI / 180.0f;
            if( verticalAngle < gunRotationRange.Minimum )
                verticalAngle = gunRotationRange.Minimum;
            if( verticalAngle > gunRotationRange.Maximum )
                verticalAngle = gunRotationRange.Maximum;

            //update tower body
            towerBody.Position = GetInterpolatedPosition() + GetInterpolatedRotation() * towerBodyLocalPosition;
            towerBody.Rotation = GetInterpolatedRotation() * new Angles( 0, 0, -horizontalAngle.InDegrees() ).ToQuat();
            towerBody.Sleeping = true;

            //update gun vertical rotation
            Quat verticalRotation = new Angles( 0, verticalAngle.InDegrees(), 0 ).ToQuat();
            mainGunAttachedObject.RotationOffset = verticalRotation;
            RecalculateMapBounds();
        }
 public double Angle(Angles angle)
 {
     return featureAngles[(int)angle];
 }
        private Vec2 GetMovementByControlKeys()
        {
            Vec2 localVector = Vec2.Zero;

            if (EntitySystemWorld.Instance.IsServer() || EntitySystemWorld.Instance.IsDedicatedServer())
            {
                PlayerManager.ServerOrSingle_Player player = null;
                player = PlayerManager.Instance.ServerOrSingle_GetPlayer(Intellect);
                if (GameMap.Instance != null && player.Intellect == Intellect) //PlayerIntellect.Instance == Intellect)
                {
                    localVector.X -= Intellect.GetControlKeyStrength(GameControlKeys.Forward);// +this.Type.SpeedForward;
                    localVector.X += Intellect.GetControlKeyStrength(GameControlKeys.Backward);// +this.Type.SpeedBackward;
                    localVector.Y -= Intellect.GetControlKeyStrength(GameControlKeys.Left);// +this.Type.SpeedLeft;
                    localVector.Y += Intellect.GetControlKeyStrength(GameControlKeys.Right);// +this.Type.SpeedRight;

                    if (localVector != Vec2.Zero)
                    {
                        Vec2 diff = Position.ToVec2() - TurnToPosition.ToVec2(); ;// *Rotation.GetForward().ToVec2();//RendererWorld.Instance.DefaultCamera.Position.ToVec2();
                        Degree angle = new Radian(MathFunctions.ATan(diff.Y, diff.X));
                        Degree vecAngle = new Radian(MathFunctions.ATan(-localVector.Y, localVector.X));
                        Quat rot = new Angles(0, 0, vecAngle - angle).ToQuat();
                        Vec2 vector = (rot * new Vec3(1, 0, 0)).ToVec2();
                        return vector;
                    }
                    else
                        return Vec2.Zero;
                }
                return Vec2.Zero;
            }
            else if (EntitySystemWorld.Instance.IsSingle())
            {
                if (GameMap.Instance != null && PlayerIntellect.Instance == Intellect)
                {
                    localVector.X -= Intellect.GetControlKeyStrength(GameControlKeys.Forward);// +this.Type.SpeedForward;
                    localVector.X += Intellect.GetControlKeyStrength(GameControlKeys.Backward);// +this.Type.SpeedBackward;
                    localVector.Y -= Intellect.GetControlKeyStrength(GameControlKeys.Left);// +this.Type.SpeedLeft;
                    localVector.Y += Intellect.GetControlKeyStrength(GameControlKeys.Right);// +this.Type.SpeedRight;

                    if (localVector != Vec2.Zero)
                    {
                        Vec2 diff = Position.ToVec2() - TurnToPosition.ToVec2(); ;// *Rotation.GetForward().ToVec2();//RendererWorld.Instance.DefaultCamera.Position.ToVec2();
                        Degree angle = new Radian(MathFunctions.ATan(diff.Y, diff.X));
                        Degree vecAngle = new Radian(MathFunctions.ATan(-localVector.Y, localVector.X));
                        Quat rot = new Angles(0, 0, vecAngle - angle).ToQuat();
                        Vec2 vector = (rot * new Vec3(1, 0, 0)).ToVec2();
                        return vector;
                    }
                    else
                        return Vec2.Zero;
                }
                return Vec2.Zero;
            }
            return Vec2.Zero;
            ////    if (localVector != Vec2.Zero)
            ////    {
            ////        localVector.Normalize();

            ////        //calculate force vector with considering camera orientation
            ////        Vec2 diff = Position.ToVec2() - RendererWorld.Instance.DefaultCamera.Position.ToVec2();
            ////        //new Vec3( RendererWorld.Instance.DefaultCamera.Position.X,RendererWorld.Instance.DefaultCamera.Position.Y, Damager_Ball_Player.Position.Z);
            ////        //diff.Z += this.Type.BallRadius;

            ////        Degree angle = new Radian(MathFunctions.ATan(diff.Y, diff.X));
            ////        Degree vecAngle = new Radian(MathFunctions.ATan(-vec.Y, vec.X));
            ////        Quat rot = new Angles(0, 0, vecAngle - angle).ToQuat();

            ////        Vec2 forceVector2 = (rot * new Vec3(1, 0, 0)).ToVec2();

            ////        Vec2 forceVector = new Vec2(forceVector2.X, forceVector2.Y);

            ////        return forceVector;
            ////    }
            ////    else return vec;
            ////}
            ////else
            ////    return vec;
        }
Example #35
0
        void TickUserForceToBall( float delta )
        {
            const float forceMultiplier = 10;

            Vec2 vec = Vec2.Zero;
            if( EngineApp.Instance.IsKeyPressed( EKeys.Left ) || EngineApp.Instance.IsKeyPressed( EKeys.A ) )
                vec.Y++;
            if( EngineApp.Instance.IsKeyPressed( EKeys.Right ) || EngineApp.Instance.IsKeyPressed( EKeys.D ) )
                vec.Y--;
            if( EngineApp.Instance.IsKeyPressed( EKeys.Up ) || EngineApp.Instance.IsKeyPressed( EKeys.W ) )
                vec.X++;
            if( EngineApp.Instance.IsKeyPressed( EKeys.Down ) || EngineApp.Instance.IsKeyPressed( EKeys.S ) )
                vec.X--;

            if( vec != Vec2.Zero )
            {
                vec.Normalize();

                //calculate force vector with considering camera orientation
                Vec2 diff = ball.Position.ToVec2() - RendererWorld.Instance.DefaultCamera.Position.ToVec2();
                Degree angle = new Radian( MathFunctions.ATan( diff.Y, diff.X ) );
                Degree vecAngle = new Radian( MathFunctions.ATan( -vec.Y, vec.X ) );
                Quat rot = new Angles( 0, 0, vecAngle - angle ).ToQuat();
                Vec2 forceVector2 = ( rot * new Vec3( 1, 0, 0 ) ).ToVec2();
                Vec3 forceVector = new Vec3( forceVector2.X, forceVector2.Y, 0 );

                Body body = ball.PhysicsModel.Bodies[ 0 ];
                body.AddForce( ForceType.GlobalAtLocalPos, delta, forceVector * forceMultiplier, Vec3.Zero );
            }
        }
Example #36
0
		Vec2 GetMovementVectorByControlKeys()
		{
			//use specified force move vector
			if( forceMoveVectorTimer != 0 )
				return forceMoveVector;

			//TPS arcade specific
			//vector is depending on camera orientation
			if( GameMap.Instance != null && GameMap.Instance.GameType == GameMap.GameTypes.TPSArcade &&
				PlayerIntellect.Instance == Intellect )
			{
				//this is not adapted for networking.
				//using RendererWorld.Instance.DefaultCamera is bad.

				Vec2 localVector = Vec2.Zero;
				localVector.X += Intellect.GetControlKeyStrength( GameControlKeys.Forward );
				localVector.X -= Intellect.GetControlKeyStrength( GameControlKeys.Backward );
				localVector.Y += Intellect.GetControlKeyStrength( GameControlKeys.Left );
				localVector.Y -= Intellect.GetControlKeyStrength( GameControlKeys.Right );

				if( localVector != Vec2.Zero )
				{
					Vec2 diff = Position.ToVec2() - RendererWorld.Instance.DefaultCamera.Position.ToVec2();
					Degree angle = new Radian( MathFunctions.ATan( diff.Y, diff.X ) );
					Degree vecAngle = new Radian( MathFunctions.ATan( -localVector.Y, localVector.X ) );
					Quat rot = new Angles( 0, 0, vecAngle - angle ).ToQuat();
					Vec2 vector = ( rot * new Vec3( 1, 0, 0 ) ).ToVec2();
					return vector;
				}
				else
					return Vec2.Zero;
			}

			//PlatformerDemo specific
			if( GameMap.Instance != null && GameMap.Instance.GameType == GameMap.GameTypes.PlatformerDemo &&
				PlayerIntellect.Instance == Intellect )
			{
				Vec2 vector = Vec2.Zero;
				vector.X -= Intellect.GetControlKeyStrength( GameControlKeys.Left );
				vector.X += Intellect.GetControlKeyStrength( GameControlKeys.Right );
				return vector;
			}

			//default behaviour
			{
				Vec2 localVector = Vec2.Zero;
				localVector.X += Intellect.GetControlKeyStrength( GameControlKeys.Forward );
				localVector.X -= Intellect.GetControlKeyStrength( GameControlKeys.Backward );
				localVector.Y += Intellect.GetControlKeyStrength( GameControlKeys.Left );
				localVector.Y -= Intellect.GetControlKeyStrength( GameControlKeys.Right );

				Vec2 vector = ( new Vec3( localVector.X, localVector.Y, 0 ) * Rotation ).ToVec2();
				if( vector != Vec2.Zero )
				{
					float length = vector.Length();
					if( length > 1 )
						vector /= length;
				}
				return vector;
			}
		}
Example #37
0
		protected override void OnRenderFrame()
		{
			base.OnRenderFrame();

			//update position, rotation of attached meshes of wheels
			if( wheelAttachedObjects != null )
			{
				Radian[] wheelsRotationAngle = null;
				Radian[] wheelsSteer = null;
				float[] wheelsSuspensionJounce = null;
				if( EntitySystemWorld.Instance.IsClientOnly() && networkingClient_wheelsRotationAngle != null )
				{
					wheelsRotationAngle = networkingClient_wheelsRotationAngle;
					wheelsSteer = networkingClient_wheelsSteer;
					wheelsSuspensionJounce = networkingClient_wheelsSuspensionJounce;
				}
				else if( physicsVehicle != null )
				{
					wheelsRotationAngle = physicsVehicle.GetWheelsRotationAngle();
					wheelsSteer = physicsVehicle.GetWheelsSteer();
					wheelsSuspensionJounce = physicsVehicle.GetWheelsSuspensionJounce();
				}

				if( wheelsRotationAngle != null )
				{
					for( int wheelIndex = 0; wheelIndex < 4; wheelIndex++ )
					{
						MapObjectAttachedObject attachedObject = wheelAttachedObjects[ wheelIndex ];
						if( attachedObject != null )
						{
							attachedObject.PositionOffset = attachedObject.TypeObject.Position +
								new Vec3( 0, 0, wheelsSuspensionJounce[ wheelIndex ] );
							Quat rotationAngle = new Angles( 0, -wheelsRotationAngle[ wheelIndex ].InDegrees(), 0 ).ToQuat();
							Quat rotationSteer = new Angles( 0, 0, -wheelsSteer[ wheelIndex ].InDegrees() ).ToQuat();
							attachedObject.RotationOffset = attachedObject.TypeObject.Rotation * rotationSteer * rotationAngle;
						}
					}
				}
			}
		}
Example #38
0
        protected override void OnGetCameraTransform( out Vec3 position, out Vec3 forward,
            out Vec3 up, ref Degree cameraFov)
        {
            Vec3 offset;
            {
                Quat rot = new Angles( 0, 0, MathFunctions.RadToDeg(
                    cameraDirection.Horizontal ) ).ToQuat();
                rot *= new Angles( 0, MathFunctions.RadToDeg( cameraDirection.Vertical ), 0 ).ToQuat();
                offset = rot * new Vec3( 1, 0, 0 );
                offset *= cameraDistance;
            }
            Vec3 lookAt = new Vec3( cameraPosition.X, cameraPosition.Y, 0 );

            position = lookAt + offset;
            forward = -offset;
            up = new Vec3( 0, 0, 1 );
        }
Example #39
0
	public static Matrix vm_angles_2_matrix(ref Angles a)
	{
		float sinp = Mathf.Sin(a.pitch);
		float cosp = Mathf.Cos(a.pitch);

		float sinb = Mathf.Sin(a.bank);
		float cosb = Mathf.Cos(a.bank);

		float sinh = Mathf.Sin(a.heading);
		float cosh = Mathf.Cos(a.heading);
		
		return sincos_2_matrix(sinp, cosp, sinb, cosb, sinh, cosh);
	}
Example #40
0
        void MomentaryTurnToPositionUpdate(Vec3 turnToPosition)
        {

            if ((turnToPosition - Position).Length() < 4.0f)
            {
                Vec3 dir = (turnToPosition - Position).GetNormalize();
                turnToPosition += dir * 10f;
            }

            Vec3 diff = (turnToPosition - Position);
            Quat collisionRotation;
            float distance = diff.LengthFast();

            Radian horizontalAngle = MathFunctions.ATan(diff.Y, diff.X);
            Radian verticalAngle = MathFunctions.ATan(diff.Z, diff.ToVec2().Length());

            collisionRotation = new Angles(0, 0, -horizontalAngle.InDegrees()).ToQuat();

            collisionRotation *= new Angles(0, verticalAngle.InDegrees(), 0).ToQuat();

            Rotation = Quat.Slerp(Rotation, collisionRotation, Type.HomingCorrection);

        }
Example #41
0
        void TickIntellect( Intellect intellect )
        {
            Vec2 forceVec = Vec2.Zero;

            if( forceMoveVectorTimer != 0 )
            {
                forceVec = forceMoveVector;
            }
            else
            {
                Vec2 vec = Vec2.Zero;

                vec.X += intellect.GetControlKeyStrength( GameControlKeys.Forward );
                vec.X -= intellect.GetControlKeyStrength( GameControlKeys.Backward );
                vec.Y += intellect.GetControlKeyStrength( GameControlKeys.Left );
                vec.Y -= intellect.GetControlKeyStrength( GameControlKeys.Right );

                forceVec = ( new Vec3( vec.X, vec.Y, 0 ) * Rotation ).ToVec2();

                //TPS arcade specific (camera observe)
                //set forceVec depending on camera orientation
                if( GameMap.Instance.GameType == GameMap.GameTypes.TPSArcade && forceVec != Vec2.Zero )
                {
                    if( Intellect != null && PlayerIntellect.Instance == Intellect )
                    {
                        //this is not adapted for networking.
                        //using RendererWorld.Instance.DefaultCamera is bad.

                        Vec2 diff = Position.ToVec2() - RendererWorld.Instance.DefaultCamera.
                            Position.ToVec2();
                        Degree angle = new Radian( MathFunctions.ATan( diff.Y, diff.X ) );
                        Degree vecAngle = new Radian( MathFunctions.ATan( -vec.Y, vec.X ) );
                        Quat rot = new Angles( 0, 0, vecAngle - angle ).ToQuat();
                        forceVec = ( rot * new Vec3( 1, 0, 0 ) ).ToVec2();
                    }
                }

                if( forceVec != Vec2.Zero )
                {
                    float length = forceVec.Length();
                    if( length > 1 )
                        forceVec /= length;
                }
            }

            if( forceVec != Vec2.Zero )
            {
                float speedCoefficient = 1;
                if( FastMoveInfluence != null )
                    speedCoefficient = FastMoveInfluence.Type.Coefficient;

                float maxSpeed;
                float force;

                if( IsOnGround() )
                {
                    //calcualate maxSpeed and force on ground.

                    Vec2 localVec = ( new Vec3( forceVec.X, forceVec.Y, 0 ) * Rotation.GetInverse() ).ToVec2();

                    float absSum = Math.Abs( localVec.X ) + Math.Abs( localVec.Y );
                    if( absSum > 1 )
                        localVec /= absSum;

                    bool running = IsNeedRun();

                    maxSpeed = 0;
                    force = 0;

                    if( Math.Abs( localVec.X ) >= .001f )
                    {
                        //forward and backward
                        float speedX;
                        if( localVec.X > 0 )
                            speedX = running ? Type.RunForwardMaxSpeed : Type.WalkForwardMaxSpeed;
                        else
                            speedX = running ? Type.RunBackwardMaxSpeed : Type.WalkBackwardMaxSpeed;
                        maxSpeed += speedX * Math.Abs( localVec.X );
                        force += ( running ? Type.RunForce : Type.WalkForce ) * Math.Abs( localVec.X );
                    }

                    if( Math.Abs( localVec.Y ) >= .001f )
                    {
                        //left and right
                        maxSpeed += ( running ? Type.RunSideMaxSpeed : Type.WalkSideMaxSpeed ) *
                            Math.Abs( localVec.Y );
                        force += ( running ? Type.RunForce : Type.WalkForce ) * Math.Abs( localVec.Y );
                    }
                }
                else
                {
                    //calcualate maxSpeed and force when flying.
                    maxSpeed = Type.FlyControlMaxSpeed;
                    force = Type.FlyControlForce;
                }

                //speedCoefficient
                maxSpeed *= speedCoefficient;
                force *= speedCoefficient;

                if( mainBody.LinearVelocity.LengthFast() < maxSpeed )
                {
                    mainBody.AddForce( ForceType.Global, 0, new Vec3( forceVec.X, forceVec.Y, 0 ) *
                        force * TickDelta, Vec3.Zero );
                }
            }

            lastTickForceVector = forceVec;
        }
Example #42
0
        // NH & KEEN - reworked the homing function for better accuracy
        private void MomentaryTurnToPositionUpdate(Vec3 turnToPosition)
        {
            if (targetBody != null)
            {
                turnToPosition = targetBody.Position;

                if (targetShape != null)
                {
                    turnToPosition += (targetShape.Position * targetBody.Rotation);
                }

                if (Type.HomingPrediction > 0.0f)
                {
                    float flyTime = (turnToPosition - Position).Length() / Type.Velocity;

                    turnToPosition += targetBody.LinearVelocity * flyTime * Type.HomingPrediction;
                }
            }

            Vec3 diff = (turnToPosition - Position);

            Degree horizontalAngle = new Radian(-MathFunctions.ATan(diff.Y, diff.X)).InDegrees();
            Degree verticalAngle = new Radian(MathFunctions.ATan(diff.Z, diff.ToVec2().Length())).InDegrees();

            Quat collisionRotation = new Angles(0, 0, horizontalAngle).ToQuat();
            collisionRotation *= new Angles(0, verticalAngle, 0).ToQuat();

            Radian targetAngle = Quat.GetAngle(Rotation, collisionRotation);

            float PI = (float)Math.PI;

            if (targetAngle > PI)
            {
                targetAngle = (2 * PI) - targetAngle;
            }

            Radian maxTurnAbility = Type.HomingCorrection.InRadians() * TickDelta;

            if (targetAngle > maxTurnAbility)
            {
                float relativeCorrection = maxTurnAbility / targetAngle;

                Rotation = Quat.Slerp(Rotation, collisionRotation, relativeCorrection);
            }
            else
            {
                Rotation = collisionRotation;
            }
        }
Example #43
0
	void physics_sim_rot(float sim_time)
	{
		float shock_fraction_time_left = 0.0f;
		float shock_amplitude = 0.0f;
		float rotdamp = 0.0f;

		if ((p_flags & PF_IN_SHOCKWAVE) > 0) 
		{
			if (timestamp_elapsed(shockwave_decay)) 
			{
				p_flags &= ~PF_IN_SHOCKWAVE;
				rotdamp = this.rotdamp;
			} 
			else 
			{
				shock_fraction_time_left = timestamp_until(shockwave_decay) / (float)SW_BLAST_DURATION;
				rotdamp = this.rotdamp + this.rotdamp * (SW_ROT_FACTOR - 1) * shock_fraction_time_left;
				shock_amplitude = shockwave_shake_amp * shock_fraction_time_left;
			}
		} 
		else 
		{
			rotdamp = this.rotdamp;
		}

		Vector3 new_vel = Vector3.zero;
		Vector3 delta_pos = Vector3.zero;
		
		apply_physics(rotdamp, desired_rotvel.x, rotvel.x, sim_time, ref new_vel.x, ref delta_pos.x);
		apply_physics(rotdamp, desired_rotvel.y, rotvel.y, sim_time, ref new_vel.y, ref delta_pos.y);
		apply_physics(rotdamp, desired_rotvel.z, rotvel.z, sim_time, ref new_vel.z, ref delta_pos.z);
		
		rotvel = new_vel;

		Angles tangles = new Angles();
		tangles.pitch = rotvel.x * sim_time;
		tangles.heading = rotvel.y * sim_time;
		tangles.bank = rotvel.z * sim_time;

		if ((p_flags & PF_IN_SHOCKWAVE) > 0) 
		{
			tangles.pitch += UnityEngine.Random.Range(-0.5f, 0.5f) * shock_amplitude;
			tangles.heading += UnityEngine.Random.Range(-0.5f, 0.5f) * shock_amplitude;
		}

		last_rotmat = MathUtils.vm_angles_2_matrix(ref tangles);
		Matrix tmp = MathUtils.vm_matrix_x_matrix(ref orient, ref last_rotmat);
		orient.Copy(ref tmp);
		
		MathUtils.vm_orthogonalize_matrix(ref orient);
	}
Example #44
0
        void MomentaryTurnToPositionUpdate( Vec3 turnToPosition )
        {
            if( turretBody == null || baseBody == null || mainGunAttachedObject == null )
                return;

            Vec3 diff = turnToPosition - Position;

            Radian horizontalAngle = MathFunctions.ATan( diff.Y, diff.X );
            Radian verticalAngle = MathFunctions.ATan( diff.Z, diff.ToVec2().Length() );

            turretBody.Rotation = new Angles( 0, 0, -horizontalAngle.InDegrees() ).ToQuat();

            Quat rot = baseBody.Rotation.GetInverse() * turretBody.Rotation;

            Quat verticalRot = new Angles( 0, verticalAngle.InDegrees(), 0 ).ToQuat();

            mainGunAttachedObject.PositionOffset = rot * mainGunOffsetPosition;
            mainGunAttachedObject.RotationOffset = rot * verticalRot;

            if( EntitySystemWorld.Instance.IsServer() )
               server_shouldSendTurnToPosition = turnToPosition;
        }
        void sensor_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
        {
            using (SkeletonFrame skeletonFrame=e.OpenSkeletonFrame())
            {
               if (skeletonFrame == null)
                {
                    return;
                }

                inputmethod = W.inputmethod;
                skeletonFrame.CopySkeletonDataTo(allSkeletons);

                //get the first tracked skeleton
                Skeleton first = (from s in allSkeletons
                                         where s.TrackingState == SkeletonTrackingState.Tracked
                                         select s).FirstOrDefault();

                // skeleton data may not be available
                if (first == null)
                {
                    return;
                }

                // display skeleton on window
                displaySkeleton(first);

                // Selecting the input method
                switch (inputmethod)
                {
                    case 0: // input version 1
                        Angles angles1 = new Angles(first);
                        AxisAngles = angles1.getFinalAngles();
                        break;

                    case 2: // input version 2
                        HandPosition angles2 = new HandPosition(first);
                        AxisAngles = angles2.getFinalAngles();
                        break;

                    case 1: // input version 3
                        HandPositionLower angles3 = new HandPositionLower(first);
                        AxisAngles = angles3.getFinalAngles();
                        break;

                    default:
                        MessageBox.Show("Error !!!");
                        break;

                }

                AxisAngles = medians.getNextMedian(AxisAngles);

                // Displaying on GUI
                W.axis1.Content = AxisAngles[1].ToString();
                W.axis2.Content = AxisAngles[2].ToString();
                W.axis3.Content = AxisAngles[3].ToString();
                W.axis4.Content = AxisAngles[4].ToString();
                W.axis5.Content = AxisAngles[5].ToString();
                W.axis6.Content = AxisAngles[6].ToString();

                if (W.RoboticArmMovement)
                    MoveRoboticArm(AxisAngles);
            }
        }
Example #46
0
 void UpdateRotation()
 {
     Rotation = new Angles( 0, 0, -rotationAngle.InDegrees() ).ToQuat();
 }
Example #47
0
        void TickIntellect( Intellect intellect )
        {
            Vec2 forceVec = Vec2.Zero;

            if( forceMoveVectorTimer != 0 )
            {
                forceVec = forceMoveVector;
            }
            else
            {
                Vec2 vec = Vec2.Zero;

                vec.X += intellect.GetControlKeyStrength( GameControlKeys.Forward );
                vec.X -= intellect.GetControlKeyStrength( GameControlKeys.Backward );
                vec.Y += intellect.GetControlKeyStrength( GameControlKeys.Left );
                vec.Y -= intellect.GetControlKeyStrength( GameControlKeys.Right );

                forceVec = ( new Vec3( vec.X, vec.Y, 0 ) * Rotation ).ToVec2();

                //TPS arcade specific (camera observe)
                //set forceVec depending on camera orientation
                if( GameMap.Instance.GameType == GameMap.GameTypes.TPSArcade && forceVec != Vec2.Zero )
                {
                    if( Intellect != null && PlayerIntellect.Instance == Intellect )
                    {
                        //!!!!!!not adapted for networking
                        //using RendererWorld.Instance.DefaultCamera is bad

                        Vec2 diff = Position.ToVec2() - RendererWorld.Instance.DefaultCamera.
                            Position.ToVec2();
                        Degree angle = new Radian( MathFunctions.ATan( diff.Y, diff.X ) );
                        Degree vecAngle = new Radian( MathFunctions.ATan( -vec.Y, vec.X ) );
                        Quat rot = new Angles( 0, 0, vecAngle - angle ).ToQuat();
                        forceVec = ( rot * new Vec3( 1, 0, 0 ) ).ToVec2();
                    }
                }

                if( forceVec != Vec2.Zero )
                {
                    float length = forceVec.Length();
                    if( length > 1 )
                        forceVec /= length;
                }
            }

            if( forceVec != Vec2.Zero )
            {
                float velocityCoefficient = 1;
                if( FastMoveInfluence != null )
                    velocityCoefficient = FastMoveInfluence.Type.Coefficient;

                float maxVelocity;
                float force;

                if( IsOnGround() )
                {
                    maxVelocity = Type.WalkMaxVelocity;
                    force = Type.WalkForce;
                }
                else
                {
                    maxVelocity = Type.FlyControlMaxVelocity;
                    force = Type.FlyControlForce;
                }

                maxVelocity *= forceVec.LengthFast();

                //velocityCoefficient
                maxVelocity *= velocityCoefficient;
                force *= velocityCoefficient;

                if( mainBody.LinearVelocity.LengthFast() < maxVelocity )
                    mainBody.AddForce( ForceType.Global, 0, new Vec3( forceVec.X, forceVec.Y, 0 ) *
                        force * TickDelta, Vec3.Zero );
            }

            lastTickForceVector = forceVec;
        }