Example #1
0
    public static TwistSwing Decompose(CartesianAxis twistAxis, Quaternion q)
    {
        DebugUtilities.AssertIsUnit(q);

        float w = q.W;
        float x = q[(int)twistAxis];
        float y = q[((int)twistAxis + 1) % 3];
        float z = q[((int)twistAxis + 2) % 3];

        float swingW = (float)Sqrt(Sqr(w) + Sqr(x));

        float twistW, twistZ;

        if (swingW != 0)
        {
            twistW = w / swingW;
            twistZ = x / swingW;
        }
        else
        {
            //if swingW is 0, then there isn't a unique decomposition, so I'll arbitrarily assume no twist
            twistW = 1;
            twistZ = 0;
        }

        float swingY = twistW * y - twistZ * z;
        float swingZ = twistW * z + twistZ * y;

        var twist = new Twist(Sign(twistW) * twistZ);
        var swing = new Swing(swingY, swingZ);

        return(new TwistSwing(twist, swing));
    }
Example #2
0
    public void TestAsQuaternion()
    {
        var twist      = new Twist(0.4f);
        var swing      = new Swing(0.2f, 0.3f);
        var twistSwing = new TwistSwing(twist, swing);

        MathAssert.AreEqual(
            twist.AsQuaternion(CartesianAxis.X).Chain(swing.AsQuaternion(CartesianAxis.X)),
            twistSwing.AsQuaternion(CartesianAxis.X),
            Acc);

        MathAssert.AreEqual(
            twist.AsQuaternion(CartesianAxis.X).Chain(swing.AsQuaternion(CartesianAxis.X)),
            twistSwing.AsQuaternion(CartesianAxis.X),
            Acc);

        MathAssert.AreEqual(
            twist.AsQuaternion(CartesianAxis.X).Chain(swing.AsQuaternion(CartesianAxis.X)),
            twistSwing.AsQuaternion(CartesianAxis.X),
            Acc);

        MathAssert.AreEqual(
            twist.AsQuaternion(CartesianAxis.X).Chain(swing.AsQuaternion(CartesianAxis.X)),
            twistSwing.AsQuaternion(CartesianAxis.X),
            Acc);
    }
Example #3
0
 protected override void OnStateChange()                 //Runs when strategy is initialized
 {
     if (State == State.SetDefaults)
     {
         Description                  = @"Trading using an estimation value of the CCI indictor, which secure more profits and entering trades before the current price bar formed allow the best entry";
         Name                         = "CCIWithPreditionEntry";
         Calculate                    = Calculate.OnBarClose;
         EntriesPerDirection          = 1;
         EntryHandling                = EntryHandling.AllEntries;
         IsExitOnSessionCloseStrategy = true;
         ExitOnSessionCloseSeconds    = 30;
         IsFillLimitOnTouch           = false;
         MaximumBarsLookBack          = MaximumBarsLookBack.TwoHundredFiftySix;
         OrderFillResolution          = OrderFillResolution.Standard;
         Slippage                     = 0;
         StartBehavior                = StartBehavior.WaitUntilFlat;
         TimeInForce                  = TimeInForce.Gtc;
         TraceOrders                  = false;
         RealtimeErrorHandling        = RealtimeErrorHandling.StopCancelClose;
         StopTargetHandling           = StopTargetHandling.PerEntryExecution;
         BarsRequiredToTrade          = 5;
         IsInstantiatedOnEachOptimizationIteration = true;
     }
     else if (State == State.Configure)                          //Runes when strategy is added onto the chart
     {
         AddDataSeries(Data.BarsPeriodType.Tick, 1);
         AddDataSeries("ES 09-20", Data.BarsPeriodType.Tick, 2000);                      //Using 2000 tick charts -> each price bar
         SetStopLoss(CalculationMode.Ticks, 12);
     }
     else if (State == State.DataLoaded)                 //Called after data has been loaded
     {
         AddChartIndicator(CCI(14));
         swing = Swing(Input, 2);
     }
 }
Example #4
0
    /**
     *  Returns a Swing final such that:
     *		delta.Transform(initial.TransformTwistAxis()) == final.TransformTwistAxis()
     */
    public static Swing ApplyDelta(Swing initial, Swing delta)
    {
        float iw = initial.W;
        float iy = initial.Y;
        float iz = initial.Z;

        float dw = delta.W;
        float dy = delta.Y;
        float dz = delta.Z;

        float c   = 2 * iw * (dw * iw - dz * iz - dy * iy) - dw;
        float fww = dw * c - iw * iw + 1;
        float fwy = dy * c + iw * iy;
        float fwz = dz * c + iw * iz;

        if (fww < MathUtil.ZeroTolerance)
        {
            // This happens when initial and delta sum to a half rotation (W = 0) in which case it's not
            // possible to return the angle from fwy and fwz. Instead I combine the axis of initial+delta
            // with a 180 angle:
            return(MakeUnitized(0, iy + dy, iz + dz));
        }
        else
        {
            // I could calculate {fy, fz} = {fwy,fwz}/Sqrt[fww] but this has higher precision:
            return(MakeUnitized(fww, fwy, fwz));
        }
    }
Example #5
0
    public static Swing FromTo(CartesianAxis twistAxis, Vector3 from, Vector3 to)
    {
        /*
         * This function is not optimized.
         * I should write an optimized version if I need to use FromTo in production.
         */

        DebugUtilities.AssertIsUnit(from);
        DebugUtilities.AssertIsUnit(to);

        float fromX = from[((int)twistAxis + 0) % 3];
        float fromY = from[((int)twistAxis + 1) % 3];
        float fromZ = from[((int)twistAxis + 2) % 3];

        float toX = to[((int)twistAxis + 0) % 3];
        float toY = to[((int)twistAxis + 1) % 3];
        float toZ = to[((int)twistAxis + 2) % 3];

        Vector2 axis = Vector2.Normalize(new Vector2(fromZ - toZ, toY - fromY));

        float   projectionLength = axis.X * fromY + axis.Y * fromZ;
        Vector2 projection       = axis * projectionLength;   //by construction, projection onto axis is same for from and to
        Vector3 fromRejection    = new Vector3(fromY - projection.X, fromZ - projection.Y, fromX);
        Vector3 toRejection      = new Vector3(toY - projection.X, toZ - projection.Y, toX);
        Vector3 rejectionCross   = Vector3.Cross(fromRejection, toRejection);
        float   rejectionDot     = Vector3.Dot(fromRejection, toRejection);

        float angle = (float)Atan2(axis.X * rejectionCross.X + axis.Y * rejectionCross.Y, rejectionDot);

        return(Swing.AxisAngle(axis.X, axis.Y, angle));
    }
Example #6
0
    private void Solve(RigidBoneSystem boneSystem, InverseKinematicsGoal goal, RigidBoneSystemInputs inputs)
    {
        var bone = boneSystem.BonesByName[boneName];

        //get bone transforms with the current bone rotation zeroed out
        inputs.Rotations[bone.Index] = TwistSwing.Zero;
        var boneTransforms = boneSystem.GetBoneTransforms(inputs);
        var boneTransform  = boneTransforms[bone.Index];

        var worldSourcePosition  = boneTransforms[goal.SourceBone.Index].Transform(goal.SourceBone.CenterPoint + goal.UnposedSourcePosition);
        var worldTargetPosition  = goal.TargetPosition;
        var worldCenterPosition  = boneTransform.Transform(bone.CenterPoint);
        var worldSourceDirection = Vector3.Normalize(worldSourcePosition - worldCenterPosition);
        var worldTargetDirection = Vector3.Normalize(worldTargetPosition - worldCenterPosition);

        //transform source and target to bone's oriented space
        var parentTotalRotation             = bone.Parent != null ? boneTransforms[bone.Parent.Index].Rotation : Quaternion.Identity;
        var orientedSpaceToWorldTransform   = bone.OrientationSpace.Orientation.Chain(parentTotalRotation);
        var worldToOrientatedSpaceTransform = Quaternion.Invert(orientedSpaceToWorldTransform);
        var orientedSourceDirection         = Vector3.Transform(worldSourceDirection, worldToOrientatedSpaceTransform);
        var orientedTargetDirection         = Vector3.Transform(worldTargetDirection, worldToOrientatedSpaceTransform);

        CartesianAxis twistAxis           = (CartesianAxis)bone.RotationOrder.primaryAxis;
        var           newOrientedRotation = Swing.FromTo(twistAxis, orientedSourceDirection, orientedTargetDirection);

        bone.SetOrientedSpaceRotation(inputs, new TwistSwing(Twist.Zero, newOrientedRotation), true);
    }
Example #7
0
 protected override void OnStateChange()                 //Runs when strategy is initialized
 {
     if (State == State.SetDefaults)
     {
         Description                  = @"Algorithm that automatically plots trend channel";
         Name                         = "AutoTrendChannel";
         Calculate                    = Calculate.OnBarClose;
         Strength                     = 5;
         NumberOfTrendChannel         = 5;
         EntriesPerDirection          = 1;
         EntryHandling                = EntryHandling.AllEntries;
         IsExitOnSessionCloseStrategy = true;
         ExitOnSessionCloseSeconds    = 30;
         IsFillLimitOnTouch           = false;
         MaximumBarsLookBack          = MaximumBarsLookBack.TwoHundredFiftySix;
         OrderFillResolution          = OrderFillResolution.Standard;
         Slippage                     = 0;
         StartBehavior                = StartBehavior.WaitUntilFlat;
         TimeInForce                  = TimeInForce.Gtc;
         TraceOrders                  = false;
         RealtimeErrorHandling        = RealtimeErrorHandling.StopCancelClose;
         StopTargetHandling           = StopTargetHandling.PerEntryExecution;
         BarsRequiredToTrade          = 4;
         IsInstantiatedOnEachOptimizationIteration = true;
     }
     else if (State == State.Configure)                          //Runes when strategy is added onto the chart
     {
         AddDataSeries("ES 09-20", Data.BarsPeriodType.Tick, 2000);
     }
     else if (State == State.DataLoaded)                 //Called after data has been loaded
     {
         swing        = Swing(Input, Strength);
         trendChannel = new TrendQueue(this, NumberOfTrendChannel);
     }
 }
Example #8
0
    public bool Test(Swing swing)
    {
        float limitY = swing.Y < 0 ? MinY : MaxY;
        float limitZ = swing.Z < 0 ? MinZ : MaxZ;
        float rSqr   = Sqr(swing.Y / limitY) + Sqr(swing.Z / limitZ);

        return(rSqr <= 1);
    }
Example #9
0
    public Swing Clamp(Swing swing)
    {
        float y = swing.Y;
        float z = swing.Z;

        EllipseClamp.ClampToEllipse(ref y, ref z, MinY, MaxY, MinZ, MaxZ);
        return(new Swing(y, z));
    }
    private void TestClampRotation(Vector3 input, Vector3 expected)
    {
        var inputTS    = new TwistSwing(Twist.MakeFromAngle(input.X), Swing.MakeFromAxisAngleProduct(input.Y, input.Z));
        var clampedTS  = constraint.Clamp(inputTS);
        var expectedTS = new TwistSwing(Twist.MakeFromAngle(expected.X), Swing.MakeFromAxisAngleProduct(expected.Y, expected.Z));

        MathAssert.AreEqual(expectedTS, clampedTS, 1e-4f);
    }
Example #11
0
 protected override void OnStateChange()
 {
     if (State == State.SetDefaults)
     {
         Description                  = @"A strategy that focuses on trending markets (rather than ranging),
                                                         1D to confirm, ignore ranging by watching for 4HR MA cross tangles,
                                                         trade direction of trend when price retests sup/res. SL trails behind.";
         Name                         = "TrendRider 0.2";
         Calculate                    = Calculate.OnBarClose;
         EntriesPerDirection          = 1;
         EntryHandling                = EntryHandling.UniqueEntries;
         IsExitOnSessionCloseStrategy = false;
         ExitOnSessionCloseSeconds    = 30;
         IsFillLimitOnTouch           = false;
         MaximumBarsLookBack          = MaximumBarsLookBack.TwoHundredFiftySix;
         OrderFillResolution          = OrderFillResolution.Standard;
         Slippage                     = 0;
         StartBehavior                = StartBehavior.WaitUntilFlat;
         TimeInForce                  = TimeInForce.Gtc;
         TraceOrders                  = false;
         RealtimeErrorHandling        = RealtimeErrorHandling.StopCancelClose;
         StopTargetHandling           = StopTargetHandling.PerEntryExecution;
         BarsRequiredToTrade          = 20;
         // Disable this property for performance gains in Strategy Analyzer optimizations
         // See the Help Guide for additional information
         IsInstantiatedOnEachOptimizationIteration = true;
         AutoTrading     = false;
         FastMA          = 10;
         SlowMA          = 20;
         OrderQuantity   = 10000;
         StopLossPercent = 1;
         LTF             = 2;
         MTF             = 3;
         HTF             = 4;
         RFStrength      = 0.05;
         SwingStrength   = 12;
     }
     else if (State == State.Configure)
     {
         AddDataSeries(Data.BarsPeriodType.Minute, 15);
         AddDataSeries(Data.BarsPeriodType.Minute, 60);
         AddDataSeries(Data.BarsPeriodType.Minute, 240);
         AddDataSeries(Data.BarsPeriodType.Day, 1);
         AddDataSeries(Data.BarsPeriodType.Week, 1);
     }
     else if (State == State.DataLoaded)
     {
         SMA1 = SMA(Closes[MTF], Convert.ToInt32(FastMA));                            // 4 hour
         SMA2 = SMA(Closes[MTF], Convert.ToInt32(SlowMA));                            // 4 hour
         SMA3 = SMA(Closes[HTF], Convert.ToInt32(FastMA));                            // 1 day
         SMA4 = SMA(Closes[HTF], Convert.ToInt32(SlowMA));                            // 1 day
         SMA5 = SMA(Closes[4], Convert.ToInt32(FastMA));                              // 1 week
         SMA6 = SMA(Closes[4], Convert.ToInt32(SlowMA));                              // 1 week
         SetStopLoss("", CalculationMode.Percent, 3, false);
         Swing1 = Swing(Closes[MTF], SwingStrength);
         MACD1  = MACD(Close, 12, 26, 9);
     }
 }
    public void TestToEdgeCase()
    {
        Vector3 to    = -Vector3.UnitZ;
        var     swing = Swing.To(CartesianAxis.Z, to);

        var swungTwistAxisV = swing.TransformTwistAxis(CartesianAxis.Z);

        MathAssert.AreEqual(to, swungTwistAxisV, Acc);
    }
    // Start is called before the first frame update
    void Start()
    {
        _enemyHealth = GetComponent <EnemyHealth>();
        _swing       = GetComponent <Swing>();

        _enemyHealth.OnDie += OnDestroySwinger;

        _swing.StartSwing();
    }
Example #14
0
 void Reset()
 {
     //s.SetActive(true);
     //Instantiate(Shine, pos, transform.rotation); //產生揮擊圖案
     start_mode = true;
     Debug.Log("play_mode in Reset" + play_mode);
     chock      = Swing.Reset;
     reset_mode = false;
 }
    public TwistSwing FromTwistSwingAngles(Vector3 angles /* in radians */)
    {
        Twist twist = Twist.MakeFromAngle(angles[primaryAxis]);

        Swing swing = Swing.MakeFromAxisAngleProduct(
            angles[(primaryAxis + 1) % 3],
            angles[(primaryAxis + 2) % 3]);

        return(new TwistSwing(twist, swing));
    }
    public void TestCalculateApplyDeltaRoundtrip()
    {
        var initial = new Swing(0.2f, 0.1f);
        var final   = new Swing(-0.3f, 0.4f);

        var delta          = Swing.CalculateDelta(initial, final);
        var roundtripFinal = Swing.ApplyDelta(initial, delta);

        MathAssert.AreEqual(final, roundtripFinal, Acc);
    }
    public static Swing Swing(Random rnd)
    {
        var swingTheta     = ContinuousUniform.Sample(rnd, -PI, PI);
        var swingMagnitude = ContinuousUniform.Sample(rnd, 0, 1);
        var swingY         = swingMagnitude * Cos(swingTheta);
        var swingZ         = swingMagnitude * Sin(swingTheta);
        var swing          = new Swing((float)swingY, (float)swingZ);

        return(swing);
    }
Example #18
0
    void Start()
    {
        FileStream fileStream = new FileStream(@"D:\TextReader.txt", FileMode.Open, FileAccess.Read);

        try
        {
            // read from file or write to file
            //FileStream fileStream = new FileStream(@"c:\test1.txt", FileMode.Open, FileAccess.Read);
            //while(line = fileStream.Readline() != -1)
        }
        finally
        {
            fileStream.Close();
        }
        System.IO.StreamReader file = new System.IO.StreamReader(@"D:\TextReader.txt");
        string line;
        int    counter = 0;

        while ((line = file.ReadLine()) != null)
        {
            //System.Console.WriteLine(line);
            counter++;
            //System.Console.WriteLine("Hello world");
            Debug.Log("counter = " + counter);
            Debug.Log(line);
        }

        file.Close();
        Debug.Log("There were " + counter + " lines.");

        chock = (Swing)(0);

        chock = (Swing)(int.Parse("5"));
        Debug.Log(chock + " chock in hit");

        sp = new SerialPort("COM4", 115200);
        Debug.Log("sp is new");
        if (!sp.IsOpen)
        {
            print("Opening COM4, baud 115200");
            sp.Open();
            print("open success");
            sp.ReadTimeout = 5000;
            sp.Handshake   = Handshake.None;
            if (sp.IsOpen)
            {
                print("Open");
            }
            pos = new Vector3(0, 0, -1.5f); //start的座標


            thread2 = new Thread(new ThreadStart(ProcessData));
            thread2.Start();
        }
    }
    public void TestOffClamp_OffAxis()
    {
        var constraint     = new SwingConstraint(-0.1f, +0.2f, -0.3f, +0.4f);
        var unclampedSwing = new Swing(0.3f, 0.5f);
        var clampedSwing   = constraint.Clamp(unclampedSwing);

        // NArgMin[{EuclideanDistance[{0.3, 0.5}, {x, y}], (x/0.2)^2 + (y/0.4)^2 <= 1}, {x, y}]
        var expectedClampedSwing = new Swing(0.10463055104437786f, 0.34089557289708267f);

        MathAssert.AreEqual(expectedClampedSwing, clampedSwing, 1e-4f);
    }
Example #20
0
    public static Swing To(CartesianAxis twistAxis, Vector3 to)
    {
        DebugUtilities.AssertIsUnit(to);

        float toX = to[((int)twistAxis + 0) % 3];
        float toY = to[((int)twistAxis + 1) % 3];
        float toZ = to[((int)twistAxis + 2) % 3];

        /*
         * To reconstruct the swing quaternion, we need to calculate:
         *     <y, z> = Sin[angle / 2] * rotation-axis
         *     w = Cos[angle / 2]
         *
         * We know:
         *     Cos[angle]
         *       = Dot[twist-axis, to]
         *       = toX
         *
         *     rotation-axis
         *       = Normalize[Cross[twist-axis, to]]
         *       = Normalize[<-toZ, toX>]
         *       = <-toZ, toX> / Sqrt[toX^2 + toZ^2]
         *       = <-toZ, toX> / Sqrt[1 - toX^2]
         *
         * So:
         *     w = Cos[angle / 2]
         *       = Sqrt[(1 + Cos[angle]) / 2]    (half-angle trig identity)
         *       = Sqrt[(1 + toX) / 2]
         *
         *    <y,z>
         *      = Sin[angle / 2] * rotation-axis
         *      = Sqrt[(1 - Cos[angle]) / 2] * rotation-axis    (half-angle trig identity)
         *      = Sqrt[(1 - toX) / 2] * rotation-axis
         *      = Sqrt[(1 - toX) / 2] / Sqrt[1 - toX^2] * <-toZ, toY>
         *      = Sqrt[(1 - toX) / (2 * (1 - toX^2))] * <-toZ, toY>
         *      = Sqrt[(1 - toX) / (2 * (1 - toX) * (1 + toX))] * <-toZ, toY>
         *      = Sqrt[1 / (2 * (1 + toX))] * <-toZ, toY>
         *      = 1 / (2 * w) * <-toZ, toY>
         */
        float ww = (1 + toX);
        float wy = -toZ;
        float wz = +toY;

        if (ww < MathUtil.ZeroTolerance)
        {
            // This is a 180 degree swing (W = 0) so X and Y don't have a unique value
            // I'll arbitrarily use:
            return(new Swing(1, 0));
        }

        return(Swing.MakeUnitized(ww, wy, wz));
    }
Example #21
0
        public Swing Activate(Stats stats, Target target)
        {
            var swing = new Swing
            {
                Outcome = HitTable.Roll(stats.MainHand.Table),
                Damage  = 600 + (15 * stats.Resource)
            };

            stats.Resource = 0;

            swing.Damage = Damage.ReduceArmor(swing.Damage, stats, target);
            return(swing);
        }
Example #22
0
 void Start()
 {
     _extend        = GetComponent <Extend>();
     _controller    = GetComponent <ControllerInput>();
     _swing         = GetComponent <Swing>();
     _particleQueue = new GameObject[ParticleQueueSize];
     _particles     = new ParticleSystem.Particle[InnerDecalParticleSystem.main.maxParticles];
     _hits          = new RaycastHit[8];
     _adjacentHits  = new RaycastHit[1];
     _layerMask     = 1 | (1 << 9);
     ResetSliceCooldown();
     ResetCrackleCooldown();
 }
        private void TestSwingDistributionFunction()
        {
            var name = "Качели";
            var obj  = new Swing();

            chart4.Series[0].IsVisibleInLegend = false;
            chart4.Series.Add(name);
            chart4.Series[name].ChartType = SeriesChartType.Line;
            chart4.Series[name].Color     = Color.Red;
            for (double i = 1; i < 17; i += 0.001)
            {
                chart4.Series[name].Points.AddXY(i, obj.DistributionFunction(i));
            }
        }
Example #24
0
        public void TestSwing()
        {
            Serial attacker = 0x1000;
            Serial defender = 0x2000;

            var expected = new Swing(attacker, defender).Compile();

            using var ns = PacketTestUtilities.CreateTestNetState();
            ns.SendSwing(attacker, defender);

            var result = ns.SendPipe.Reader.TryRead();

            AssertThat.Equal(result.Buffer[0].AsSpan(0), expected);
        }
Example #25
0
 protected override void OnStateChange()
 {
     if (State == State.SetDefaults)
     {
         Description                  = @"A strategy that focuses on multi-timeframe MA crosses (4HR to confirm), daily and weekly to filter. Goes for big swing moves.";
         Name                         = "TrendRider 0.1";
         Calculate                    = Calculate.OnBarClose;
         EntriesPerDirection          = 1;
         EntryHandling                = EntryHandling.UniqueEntries;
         IsExitOnSessionCloseStrategy = false;
         ExitOnSessionCloseSeconds    = 30;
         IsFillLimitOnTouch           = false;
         MaximumBarsLookBack          = MaximumBarsLookBack.TwoHundredFiftySix;
         OrderFillResolution          = OrderFillResolution.Standard;
         Slippage                     = 0;
         StartBehavior                = StartBehavior.WaitUntilFlat;
         TimeInForce                  = TimeInForce.Gtc;
         TraceOrders                  = false;
         RealtimeErrorHandling        = RealtimeErrorHandling.StopCancelClose;
         StopTargetHandling           = StopTargetHandling.PerEntryExecution;
         BarsRequiredToTrade          = 20;
         // Disable this property for performance gains in Strategy Analyzer optimizations
         // See the Help Guide for additional information
         IsInstantiatedOnEachOptimizationIteration = true;
         AutoTrading     = false;
         FastMA          = 10;
         SlowMA          = 20;
         OrderQuantity   = 10000;
         StopLossPercent = 1;
     }
     else if (State == State.Configure)
     {
         AddDataSeries(Data.BarsPeriodType.Minute, 60);
         AddDataSeries(Data.BarsPeriodType.Minute, 240);
         AddDataSeries(Data.BarsPeriodType.Day, 1);
         AddDataSeries(Data.BarsPeriodType.Week, 1);
     }
     else if (State == State.DataLoaded)
     {
         SMA1 = SMA(Closes[2], Convert.ToInt32(FastMA));                            // 4 hour
         SMA2 = SMA(Closes[2], Convert.ToInt32(SlowMA));                            // 4 hour
         SMA3 = SMA(Closes[3], Convert.ToInt32(FastMA));                            // 1 day
         SMA4 = SMA(Closes[3], Convert.ToInt32(SlowMA));                            // 1 day
         SMA5 = SMA(Closes[4], Convert.ToInt32(FastMA));                            // 1 week
         SMA6 = SMA(Closes[4], Convert.ToInt32(SlowMA));                            // 1 week
         SetStopLoss("", CalculationMode.Percent, 3, false);
         Swing1 = Swing(Closes[1], 12);
     }
 }
Example #26
0
        static void Main(string[] args)
        {
            Console.WriteLine("  Welcome to your game GOLF\n\nPress any key to get started");
            Console.ReadKey(true);

            do
            {
                double angle    = AngleM();
                double velocity = VelocityM();
                double distance = CalculateDistance(angle, velocity);
                setNewLocation(distance);
                swing           = swing + 1;
                distanceBetween = Math.Abs(goalLocation - ballLocation);
                Console.WriteLine("ballLocation:" + ballLocation);
                Console.WriteLine(distanceBetween + " between the cup and the ball");
                Console.WriteLine(maxSwings - swing + " swings left");

                Swing SW = new Swing(angle, velocity, distance);
                swings.Add(SW);

                if (ballLocation == goalLocation)
                {
                    Console.WriteLine(" You win \nPress any key to show your score and double press to close the game"); // ballLocation = 0
                    Console.ReadKey();
                    break;
                }
                else if (distanceBetween > goalLocation)                                                                                                             //the is after the goal > 640
                {
                    Console.WriteLine("You'r atfer the line of the cup, Game Over, try later\nPress any key to show your score and double press to close the game"); //max 640, more = lose
                    Console.ReadKey(true);
                    break;
                }
                else if (swing >= maxSwings)
                {
                    Console.WriteLine(" You lose! bad luck, no more swings left\nPress any key to show your score and double press to close the game "); // 0 swings  game over
                    Console.ReadKey(true);
                    break;
                }
            } while (true);
            Console.Clear();
            foreach (var swing in swings)
            {
                Console.WriteLine("The historic ");
                Console.WriteLine("The angle: " + swing.Angle);
                Console.WriteLine("The velocity: " + swing.Velocity);
                Console.WriteLine("The distance: " + swing.Distance);
            }
            Console.ReadKey(true);
        }
    public void TestAxisAngleProduct()
    {
        Vector2 axis             = Vector2.Normalize(new Vector2(-1, 3));
        float   angle            = 0.8f;
        Vector2 axisAngleProduct = axis * angle;

        var swing = Swing.MakeFromAxisAngleProduct(axisAngleProduct.X, axisAngleProduct.Y);

        MathAssert.AreEqual(axisAngleProduct, swing.AxisAngleProduct, Acc);

        var expectedQ = Quaternion.RotationAxis(new Vector3(axis.X, axis.Y, 0), angle);
        var q         = swing.AsQuaternion(CartesianAxis.Z);

        MathAssert.AreEqual(expectedQ, q, Acc);
    }
    public void TestFromTo()
    {
        var     rnd = new Random(0);
        Vector3 a   = MakeRandomUnitVector(rnd);
        Vector3 b   = MakeRandomUnitVector(rnd);

        foreach (CartesianAxis twistAxis in CartesianAxes.Values)
        {
            Swing fromAToB = Swing.FromTo(twistAxis, a, b);
            MathAssert.AreEqual(b, Vector3.Transform(a, fromAToB.AsQuaternion(twistAxis)), Acc);

            Swing fromBToA = Swing.FromTo(twistAxis, b, a);
            MathAssert.AreEqual(a, Vector3.Transform(b, fromBToA.AsQuaternion(twistAxis)), Acc);
        }
    }
    public void TestAxisAngle()
    {
        Vector2 axis  = Vector2.Normalize(new Vector2(-1, 3));
        float   angle = 0.8f;

        var swing = Swing.AxisAngle(axis.X, axis.Y, angle);

        MathAssert.AreEqual(axis, swing.Axis, Acc);
        Assert.AreEqual(angle, swing.Angle, Acc);

        var expectedQ = Quaternion.RotationAxis(new Vector3(axis.X, axis.Y, 0), angle);
        var q         = swing.AsQuaternion(CartesianAxis.Z);

        MathAssert.AreEqual(expectedQ, q, Acc);
    }
Example #30
0
 private void OnTriggerEnter(Collider other)
 {
     if (!stopGrowing)
     {
         stopGrowing = true;
         swingParent.transform.position = new Vector3(swingParent.transform.position.x, other.transform.position.y, swingParent.transform.position.z);
         transform.parent      = swingParent.transform;
         lamp.transform.parent = swingParent.transform;
         if (addSwing)
         {
             Swing swing = swingParent.AddComponent <Swing>();
             swing.randomRotation = true;
             swing.rotation       = swingAmount;
         }
     }
 }