Beispiel #1
0
 static readonly Accum _friction = Accum.MakeAccum(0x00000000); //0x0000E800);
 public virtual Accum GetFriction()
 {
     return(FixedMath.Clamp(_friction, Accum.Zero, Accum.One));
 }
Beispiel #2
0
 public static bool GetClosestViableNode(Vector2d from, Vector2d dest, int pathingSize, out GridNode returnNode)
 {
     returnNode = GridManager.GetNode(dest.x, dest.y);
     if (returnNode.Unwalkable)
     {
         bool valid = false;
         PanLineAlgorithm.FractionalLineAlgorithm.Coordinate cacheCoord = new PanLineAlgorithm.FractionalLineAlgorithm.Coordinate();
         bool validTriggered = false;
         pathingSize = (pathingSize + 1) / 2;
         int minSqrMag = pathingSize * pathingSize;
         minSqrMag *= 2;
         foreach (var coordinate in PanLineAlgorithm.FractionalLineAlgorithm.Trace(dest.x.ToDouble(), dest.y.ToDouble(), from.x.ToDouble(), from.y.ToDouble()))
         {
             currentNode = GridManager.GetNode(FixedMath.Create(coordinate.X), FixedMath.Create(coordinate.Y));
             if (!validTriggered)
             {
                 if (currentNode != null && currentNode.Unwalkable == false)
                 {
                     validTriggered = true;
                 }
                 else
                 {
                     cacheCoord = coordinate;
                 }
             }
             if (validTriggered)
             {
                 if (currentNode == null || currentNode.Unwalkable)
                 {
                 }
                 else
                 {
                     //calculate sqrMag to last invalid node
                     int testMag = coordinate.X - cacheCoord.X;
                     testMag *= testMag;
                     int buffer = coordinate.Y - cacheCoord.Y;
                     buffer  *= buffer;
                     testMag += buffer;
                     if (testMag >= minSqrMag)
                     {
                         valid = true;
                         break;
                     }
                 }
             }
         }
         if (!valid)
         {
             return(false);
         }
         returnNode = currentNode;
     }
     return(true);
 }
    protected override void Execute(List <LogicEntity> entities)
    {
        foreach (LogicEntity e in entities)
        {
            LogicEntity owner = _context.GetEntityWithId(e.followPoint.targetID);
            targetPosition = owner.position.value + e.followPoint.offset;
            distance       = targetPosition - e.position.value;
            maxRotation    = e.followPoint.maxRotation;

            if (e.isAttached && distance.magnitude < e.followPoint.pickUpRadius)
            {
                if (e.isDangerous)
                {
                    e.isDangerous = false;
                }

                targetVelocity = distance * e.followPoint.followSpeed / GameController.FPS;

                if (distance.x.Abs() <= targetVelocity.x)
                {
                    targetVelocity.x = 0;
                }

                if (distance.y.Abs() <= targetVelocity.y)
                {
                    targetVelocity.y = 0;
                }

                if (e.position.value.y <= targetPosition.y)
                {
                    targetVelocity.y = targetPosition.y - e.position.value.y;
                }

//				if (e.hasCollisionInfo) {
//
//					if (e.collisionInfo.value.CollidesHorizontal ()) {
//
//						targetVelocity.y -= (e.collisionInfo.value.horizontalHit.y - e.position.value.y).Sign () * FixedMath.ONE;
//						UnityEngine.Debug.Log ("h: " + -(e.collisionInfo.value.horizontalHit.y - e.position.value.y).Sign () * FixedMath.ONE);
//
//					}
//
//					if (e.collisionInfo.value.CollidesVertical ()) {
//
//						targetVelocity.x -= (e.collisionInfo.value.verticalHit.x - e.position.value.x).Sign () * FixedMath.ONE;
//						UnityEngine.Debug.Log ("v: " + -(e.collisionInfo.value.verticalHit.x - e.position.value.x).Sign () * FixedMath.ONE);
//
//					}
//
//				}

                e.ReplaceLastVelocity(e.velocity.value);
                e.ReplaceVelocity(targetVelocity * 50);

                angle = FixedMath.Lerp01(

                    0,
                    distance.x.Sign() * maxRotation,
                    distance.x.Abs()

                    );

                e.ReplaceLastRotation(e.rotation.value);
                e.ReplaceRotation(angle);
            }

            else if (!owner.isStunned && !e.hasThrowTimer && !e.isDangerous && distance.magnitude < e.followPoint.pickUpRadius * OUTER_RADIUS_FACTOR)
            {
                bool bIsPressed = false;


                if (owner.hasPlayerID)
                {
                    foreach (InputEntity controller in Contexts.sharedInstance.input.GetEntitiesWithControllerID(owner.playerID.id))
                    {
                        if (controller.controllerInput.snapshot.GetButton(CommandInput.Buttons.B).pressed)
                        {
                            bIsPressed = true;
                        }
                    }
                }

                if (!bIsPressed)
                {
                    targetVelocity = distance * (FixedMath.ONE - distance.magnitude.Div(e.followPoint.pickUpRadius * OUTER_RADIUS_FACTOR)) * e.followPoint.followSpeed / (GameController.FPS * 2);

                    e.isAttached = true;
                    e.ReplaceLastVelocity(e.velocity.value);
                    e.ReplaceVelocity(targetVelocity * 50);
                }
            }

            else if (!owner.isStunned && !e.hasThrowTimer && !e.isAttached && distance.magnitude < e.followPoint.pickUpRadius)
            {
                bool bIsPressed = false;


                if (owner.hasPlayerID)
                {
                    foreach (InputEntity controller in Contexts.sharedInstance.input.GetEntitiesWithControllerID(owner.playerID.id))
                    {
                        if (controller.controllerInput.snapshot.GetButton(CommandInput.Buttons.B).pressed)
                        {
                            bIsPressed = true;
                        }
                    }
                }

                if (!bIsPressed)
                {
                    e.isAttached   = true;
                    e.isInvincible = true;
                    e.ReplaceInvincibilityTimer(PICKUP_INVINCIBILITY_TIME);
                }
            }
            else if (e.isAttached)
            {
                e.isAttached = false;
            }
        }
    }
    protected override void Execute(List <InputEntity> entities)
    {
        int numCommands = _context.commandList.commands.Count;

        foreach (InputEntity e in entities)
        {
            foreach (LogicEntity player in Contexts.sharedInstance.logic.GetEntitiesWithPlayerID(e.controllerID.id))
            {
                if (!player.isFastFalling && player.hasFastFallFactor && !player.isGrounded &&
                    e.controllerInput.snapshot.GetAxis(Axes.MoveVertical) < -FixedMath.Create(4, 10) &&
                    player.velocity.value.y < player.minJumpVelocity.value &&
                    !e.controllerInput.snapshot.GetButton(Buttons.A).pressed)
                {
                    _context.commandList.commands.Add(new FastFallCommand(

                                                          player.id.value,
                                                          true

                                                          ));
                }
                else if (player.isFastFalling && (player.isGrounded ||
                                                  e.controllerInput.snapshot.GetAxis(Axes.MoveVertical) >= -FixedMath.Create(4, 10) ||
                                                  player.velocity.value.y >= player.minJumpVelocity.value ||
                                                  e.controllerInput.snapshot.GetButton(Buttons.A).pressed
                                                  ))
                {
                    _context.commandList.commands.Add(new FastFallCommand(

                                                          player.id.value,
                                                          false

                                                          ));
                }

                if (e.controllerInput.snapshot.GetButton(Buttons.A).down)
                {
                    _context.commandList.commands.Add(new JumpCommand(
                                                          player.id.value,
                                                          player.maxJumpVelocity.value,
                                                          e.controllerInput.snapshot.GetAxis(Axes.MoveHorizontal)

                                                          ));
                }

                if (e.controllerInput.snapshot.GetButton(Buttons.A).up)
                {
                    _context.commandList.commands.Add(new ReleaseJumpCommand(
                                                          player.id.value,
                                                          player.minJumpVelocity.value,
                                                          player.maxJumpVelocity.value

                                                          ));
                }

                if (e.controllerInput.snapshot.GetButton(Buttons.B).down)
                {
                    _context.commandList.commands.Add(new ThrowCommand(
                                                          player.id.value,
                                                          new FixedVector2(
                                                              e.controllerInput.snapshot.GetAxis(Axes.MoveHorizontal),
                                                              e.controllerInput.snapshot.GetAxis(Axes.MoveVertical)
                                                              )

                                                          ));
                }

                if (e.controllerInput.snapshot.GetButton(Buttons.B).up)
                {
//					_context.commandList.commands.Add (new ChangeColorCommand (
//						player.id.value,
//						Color.white
//
//					));
                }

                _context.commandList.commands.Add(new RunCommand(
                                                      player.id.value,
                                                      new FixedVector2(
                                                          e.controllerInput.snapshot.GetAxis(Axes.MoveHorizontal),
                                                          e.controllerInput.snapshot.GetAxis(Axes.MoveVertical)
                                                          )
                                                      ));


                if (_context.commandList.commands.Count > numCommands)
                {
                    e.isValidInput = true;
                }
            }
        }
    }
Beispiel #5
0
 //f(x) that the table will cache
 public override long F(long x)
 {
     return(FixedMath.Sin(x));
 }
Beispiel #6
0
 /// <summary>
 /// 标准矩形的构造函数
 /// </summary>
 /// <param name="leftBound"></param>
 /// <param name="rightBound"></param>
 /// <param name="upBound"></param>
 /// <param name="downBound"></param>
 public Body(int leftBound, int rightBound, int downBound, int upBound) : this(FixedMath.Create(leftBound), FixedMath.Create(rightBound), FixedMath.Create(downBound), FixedMath.Create(upBound))
 {
 }
Beispiel #7
0
    public Body(long leftBound, long rightBound, long downBound, long upBound)
    {
        //Debug.Log(" " + leftBound.ToFloat() + " " + rightBound.ToFloat() + " " + downBound.ToFloat() + " " + upBound.ToFloat());

        bodyType   = BodyType.Rectangle;
        isStandard = true;

        direction = new Vector2d(1, 0);
        length    = rightBound - leftBound;
        width     = upBound - downBound;

        position = new Vector2d(leftBound + (length).Div(FixedMath.Create(2)), downBound + (width).Div(FixedMath.Create(2)));

        //Debug.Log(" pos " + position + " l " + length.ToFloat() + " w " + width.ToFloat());
    }
    public override void GetDesiredSteering(SteeringResult rst)
    {
        if (Finish)
        {
            return;
        }
        if (_firstStart)
        {
            _index = 0;
            if (Path != null && Path.Count > 0)
            {
                Target       = Path[_index];
                _finalTarget = Path[Path.Count - 1];
            }
            else
            {
                Finish = true;
                return;
            }
            _firstStart = false;
        }
        if (Arrive())
        {
            Self.Position = Target;
            GridService.Clear(Target, Self as SceneObject);
            _index++;
            if (_index == Path.Count)
            {
                GridService.TagAs(Target, Self as SceneObject, GridService.NodeType.BeTaken);
                Finish = true;
                return;
            }
            Target = Path[_index];
        }
        if (Vector3d.SqrDistance(Self.Position, _finalTarget) <= FixedMath.Create(Radius))
        {
            _index = Path.Count - 1;
        }
        if (_index == Path.Count - 1)
        {
            if (GridService.IsNotEmptyBy(Target) != Self) //|| (_caculatedIndex&(_index+1)) == 0)
            {
                //  _caculatedIndex += _index + 1;
                Vector3d t;
                if (Formation == Formation.Quad)
                {
                    GridService.SearchNearEmptyPoint(Path[_index], out t);
                }
                else
                {
                    GridService.SearchNearCircleEmptyPoint(Self.Position, Path[_index], Radius, out t);
                }
                Target = t;
                GridService.TagAs(Target, Self as SceneObject, GridService.NodeType.FlagAsTarget);
            }
        }
        Vector3d desiredVelocity = _so.Forward * Self.Speed;
        var      nextPosi        = Self.Position + desiredVelocity * LockFrameMgr.FixedFrameTime;

        if (!JPSAStar.active.IsWalkable(nextPosi))
        {
            List <PathFinderNode> list = new List <PathFinderNode>();
            JPSAStar.active.AStarFindPath(Self.Position, Target, list);
            for (int i = 0; i < list.Count - 1; i++)
            {
                Path.Insert(0, JPSAStar.active.P2V(list[i]));
            }
            Target = Path[0];
        }
        Self.Position += desiredVelocity * LockFrameMgr.FixedFrameTime;
        UnityEngine.Debug.DrawLine(Self.Position.ToVector3(), Target.ToVector3(), Color.red, 0.1f);
    }
Beispiel #9
0
    //获取一个顺时针夹角(需先标准化向量)
    public static long GetRotationAngle(this Vector2d dir, Vector2d aimDir)
    {
        //dir = dir.normalized;
        //aimDir = aimDir.normalized;

        long angle = FixedMath.Create(Math.Acos(dir.Dot(aimDir).ToFloat())).Mul(FixedMath.Create(180).Div(FixedMath.Create(Math.PI)));

        if (angle != FixedMath.Create(180) && FixedMath.Create(angle) != 0)
        {
            long cross = dir.x.Mul(aimDir.y) - aimDir.x.Mul(dir.y);
            if (cross < FixedMath.Create(0))
            {
                return(angle);
            }
            else
            {
                return(FixedMath.Create(360) - angle);
            }
        }

        return(angle);
    }
Beispiel #10
0
        public static void Run(string [] args)
        {
            long   ticDelta = 0, renderDelta = 0;
            double fpsTime;

            if (closing)
            {
                return;
            }

            if (!CommandLine.Parser.Default.ParseArguments(args, options))
            {
                GConsole.WriteLine("Fatal error: There was an error reading the argument list");
                Console.Read();
                return;
            }

            try {
                /*Data.UDMF.UDMFParser udmfParser = new Data.UDMF.UDMFParser ();
                 * udmfParser.Setup ();
                 *
                 * using (var reader = new StreamReader ("TEXTMAP.txt"))
                 *  udmfParser.Parse (reader);
                 *
                 * Console.ReadKey ();
                 * return;*/

                GConsole.WriteLine("Core: Loading engine.PK3");
                ZipLumpContainer container  = null;
                string           engPK3File = Path.GetFullPath(Path.Combine(Constants.ProgDir, @"engine.pk3"));

                if (File.Exists(engPK3File))
                {
                    if (ZipLumpContainer.CheckContainer(engPK3File))
                    {
                        container = new ZipLumpContainer(engPK3File);
                    }
                }

                if (container == null)
                {
                    throw new FatalError(String.Format("Could not load engine.PK3. Stopping execution."));
                }

                GConsole.WriteLine(" engine.PK3, {0} lumps", container.Count);
                LumpManager.AddContainer(container);

                GConsole.WriteLine("Core: Initializing patches");
                InitPatches();

                GConsole.WriteLine("Core: Generating fixed-point Sin/Cos/Atan LUTs");
                FixedMath.GenerateTables();

                GConsole.WriteLine("Core: Initializing video");
                RenderEngine = OpenTkRenderer.Default;
                RenderEngine.Initialize(800, 600, false);
                RenderEngine.OnFocusChange += Renderer_OnFocusChange;

                GConsole.WriteLine("Core: Initializing playsim");
                Ticker = new Ticker();
                Ticker.Initialize();

                GConsole.WriteLine("Core: Starting game loop");
                ticClock.Reset();
                ticClock.Start();
                renderClock.Reset();
                renderClock.Start();

                while (true)
                {
                    if (closing)
                    {
                        return;
                    }

                    if (ticClock.ElapsedMilliseconds >= Constants.MsecsPerTic)
                    {
                        ticDelta = ticClock.ElapsedMilliseconds;
                        ticClock.Restart();
                        Ticker.Update(ticDelta);
                        Input.ClearTotals();
                    }
                    Input.UpdateInput();

                    renderDelta = renderClock.ElapsedMilliseconds;
                    renderClock.Restart();

                    fpsClock.Restart();
                    RenderEngine.Render(renderDelta);
                    fpsTime = fpsClock.ElapsedMilliseconds;

                    if (RenderEngine.IsUsable())
                    {
                        RenderEngine.WindowTitle = String.Format("Frame time: {0} ms", fpsTime);
                    }
                }
            } catch (FatalError err) {
                DisposeResources();
                GConsole.WriteLine(err.Message);
                Console.ReadKey();
            } catch (VeryFatalError err) {
                DisposeResources();
                GConsole.WriteLine(err.Message);
                Console.ReadKey();
            }
        }
Beispiel #11
0
 public static Accum GetTicTimeFracAccum()
 {
     return(FixedMath.Clamp(new Accum(ticClock.ElapsedMilliseconds) / new Accum(Constants.MsecsPerTic), Accum.Zero, Accum.One));
 }
        public override void OnInspectorGUI()
        {
            if (Application.isPlaying)
            {
                EditorGUILayout.LabelField("Debug Information", EditorStyles.boldLabel);

                base.DrawDefaultInspector();
                return;
            }
            EditorGUI.BeginChangeCheck();

            if (leTarget == null)
            {
                leTarget = (LSBody)target;
            }

            if (leTarget.cachedTransform == null)
            {
                leTarget.cachedTransform = leTarget.GetComponent <Transform>();
            }
            if (leTarget.cachedGameObject == null)
            {
                leTarget.cachedGameObject = leTarget.GetComponent <GameObject>();
            }


            Vector3 transformPos = leTarget.cachedTransform.position;

            leTarget.Position.x = FixedMath.Create(transformPos.x);
            leTarget.Position.y = FixedMath.Create(transformPos.z);

            Vector3 transformRot = leTarget.cachedTransform.eulerAngles;

            leTarget.Rotation = Vector2d.up;
            leTarget.Rotation.Rotate(FixedMath.Create(Mathf.Sin(transformRot.y * Mathf.Deg2Rad)), FixedMath.Create(Mathf.Cos(transformRot.y * Mathf.Deg2Rad)));
            //leTarget.Interpolate = EditorGUILayout.Toggle ("Interpolate", leTarget.Interpolate);


            EditorGUILayout.Space();


            EditorGUILayout.LabelField("Collider Settings", EditorStyles.boldLabel);
            leTarget.Shape = (ColliderType)EditorGUILayout.EnumPopup("Shape", leTarget.Shape);
            if (leTarget.Shape == ColliderType.None)
            {
                return;
            }
            leTarget.IsTrigger = EditorGUILayout.Toggle("Is Trigger", leTarget.IsTrigger);


            if (!leTarget.IsTrigger && !leTarget.Immovable)
            {
                GUIContent PriorityContent = new GUIContent("Priority", "The priority of this object in collisions. Objects of lower priority yield to objects of higher priority.");
                leTarget.Priority = EditorGUILayout.IntField(PriorityContent, leTarget.Priority);
            }

            switch (leTarget.Shape)
            {
            case ColliderType.Circle:
                GUIContent ImmovableContent = new GUIContent("Immovable", "Is this object immovable, i.e. a wall. Note: non-immovable objects are not supported for any shape except circle.");
                leTarget.Immovable = EditorGUILayout.Toggle(ImmovableContent, leTarget.Immovable);
                EditorGUILayout.BeginHorizontal();
                LSEditorUtility.FixedNumberField("Radius", ref leTarget.Radius);
                EditorGUILayout.EndHorizontal();
                break;

            case ColliderType.AABox:
                leTarget.Immovable = true;
                EditorGUILayout.BeginHorizontal();
                LSEditorUtility.FixedNumberField("Half Width", ref leTarget.HalfWidth);
                EditorGUILayout.EndHorizontal();

                EditorGUILayout.BeginHorizontal();
                LSEditorUtility.FixedNumberField("Half Height", ref leTarget.HalfHeight);
                EditorGUILayout.EndHorizontal();
                break;

            case ColliderType.Polygon:
                leTarget.Immovable = true;
                if (leTarget.Vertices == null || leTarget.Vertices.Length == 0)
                {
                    leTarget.Vertices    = new Vector2d[4];
                    leTarget.Vertices[0] = new Vector2d(FixedMath.Half, FixedMath.Half);
                    leTarget.Vertices[1] = new Vector2d(FixedMath.Half, -FixedMath.Half);
                    leTarget.Vertices[2] = new Vector2d(-FixedMath.Half, -FixedMath.Half);
                    leTarget.Vertices[3] = new Vector2d(-FixedMath.Half, FixedMath.Half);
                }

                EditorGUILayout.BeginHorizontal();
                int VerticesCount = EditorGUILayout.IntField("Vertices count", leTarget.Vertices.Length);
                EditorGUILayout.EndHorizontal();
                if (VerticesCount > leTarget.Vertices.Length)
                {
                    Vector2d[] NewVertices = new Vector2d[VerticesCount];
                    leTarget.Vertices.CopyTo(NewVertices, 0);
                    for (int i = leTarget.Vertices.Length; i < VerticesCount; i++)
                    {
                        NewVertices[i] = new Vector2d(-FixedMath.One, 0);
                    }
                    leTarget.Vertices = NewVertices;
                }
                else if (VerticesCount < leTarget.Vertices.Length)
                {
                    Vector2d[] NewVertices = new Vector2d[VerticesCount];
                    for (int i = 0; i < VerticesCount; i++)
                    {
                        NewVertices[i] = leTarget.Vertices[i];
                    }
                    leTarget.Vertices = NewVertices;
                }
                for (int i = 0; i < leTarget.Vertices.Length; i++)
                {
                    EditorGUILayout.BeginHorizontal();
                    LSEditorUtility.Vector2dField("V" + i.ToString() + ":", ref leTarget.Vertices[i]);
                    EditorGUILayout.EndHorizontal();
                }
                break;
            }


            SceneView.RepaintAll();
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RegisterCompleteObjectUndo(leTarget, "LSBody Change");
                EditorUtility.SetDirty(leTarget);
            }
        }
Beispiel #13
0
 public static float ContrainAxisTo16Angles(this float axis)
 {
     return(ContrainAxisTo16Angles(FixedMath.Create(axis)).ToFloat());
 }
 public GridSettings()
 {
     Init(256, 256, FixedMath.Create(-128), FixedMath.Create(-128), true);
 }
Beispiel #15
0
    Vector2d linearPrograming(List <FixedLine> lines)
    {
        _fixedVecocity     = _self.Velocity.ToVector2d();
        _fixedPrefVelocity = _fixedVecocity.Normalize() * _self.Speed;
        Vector2d newV = _fixedPrefVelocity;

        // return curVelocity todo: 3D Linear Programming
        for (int i = 0; i < lines.Count; ++i)
        {
            var line1 = lines[i];
            var d     = line1.direction;
            var p     = line1.point;
            if (Vector2d.det(d, p - _fixedVecocity) > 0)
            {
                // ||d||^2 * t^2 + 2(dot(d, p)) * t + (||p||^2 - r^2) >= 0  available area in max speed
                // delta = b^2 - 4ac, ||d|| = 1
                var dp    = Vector2d.Dot(p, d);
                var delta = 4 * dp.Mul(dp) - 4 * (p.SqrMagnitude() - _self.Speed.Mul(_self.Speed));
                if (delta < 0)
                {
                    newV = _fixedVecocity;
                    break;
                }
                delta /= 4;

                // m1 = (-b - sqrt(delta)) / ||d||^2
                // m2 = (-b + sqrt(delta)) / ||d||^2
                // m1 <= m2
                var m1 = -dp - FixedMath.Sqrt(delta);
                var m2 = -dp + FixedMath.Sqrt(delta);
                // Cramer's rule
                // p = p1 + t1d1 = p2 + t2d2
                for (var j = 0; j < i; ++j)
                {
                    var line2 = lines[j];

                    // t1 = det(d2, p1 - p2) / det(d1, d2)
                    var t1y = Vector2d.det(line1.direction, line2.direction);
                    var t1x = Vector2d.det(line2.direction, p - line2.point);
                    // parallel
                    if (Math.Abs(t1y) < 100)
                    {
                        // on the other side of available area
                        if (t1x < 0)
                        {
                            newV = _fixedVecocity;
                            return(newV);
                        }
                        continue;
                    }

                    var t = t1y.Div(t1x);
                    // right side of line1, mod m1
                    if (t1y < 0)
                    {
                        m1 = Math.Max(m1, t);
                    }
                    else
                    {
                        m2 = Math.Min(m2, t);
                    }
                    //      Debug.LogError("fixed " + m1.ToFloat()+" "+m2.ToFloat());
                    if (m1 > m2)
                    {
                        newV = _fixedVecocity;
                        return(newV);
                    }
                }

                var tPref = Vector2d.Dot(d, _fixedPrefVelocity - p);
                if (tPref > m2)
                {
                    newV = p + m2 * d;
                }
                else if (tPref < m1)
                {
                    newV = p + m1 * d;
                }
                else
                {
                    newV = p + tPref * d;
                }
                _fixedVecocity = newV;
            }
        }

        return(newV);
    }
 public GridSettings()
 {
     Init(500, 500, FixedMath.Create(-100), FixedMath.Create(-100), true);
 }
Beispiel #17
0
    //弹走圆形
    Vector2d Offset_Rectangle_Circle(Body circle)
    {
        //Body rectangle = this;
        Vector2d newCirclePos = circle.position;

        long rot = FixedMath.Create(0);

        if (!isStandard)
        {
            //先把圆形归位
            rot          = direction.GetRotationAngle(new Vector2d(1, 0));
            newCirclePos = circle.position.PostionRotateInXZ(position, rot);
        }


        Vector2d oc = newCirclePos - position;

        long halfLength = length.Mul(FixedMath.Half);

        Vector2d offset = new Vector2d();

        if (oc.x > FixedMath.Create(0) && oc.x < halfLength + circle.radius)
        {
            offset.x = (halfLength - oc.x) + circle.radius;
        }
        else if (oc.x < FixedMath.Create(0) && oc.x > -halfLength - circle.radius)
        {
            offset.x = (-halfLength - oc.x) - circle.radius;
        }
        else
        {
            offset.x = 0;
        }

        long halfWidth = width.Mul(FixedMath.Half);

        if (oc.y > FixedMath.Create(0) && oc.y < halfWidth + circle.radius)
        {
            offset.y = (halfWidth - oc.y) + circle.radius;
        }
        else if (oc.y < FixedMath.Create(0) && oc.y > -halfWidth - circle.radius)
        {
            offset.y = (-halfWidth - oc.y) - circle.radius;
        }
        else
        {
            offset.y = 0;
        }

        if (Math.Abs(offset.x) > Math.Abs(offset.y))
        {
            offset.x = 0;
        }
        else
        {
            offset.y = 0;
        }

        offset = offset.Vector2dRotateInXZ(rot);
        return(offset);
    }
        internal override void Update()
        {
            if ((lastControls & MoveForwardMask) != 0)
            {
                if (moveVelocity >= 0)
                {
                    ApplyAcceleration(1, MoveAcceleration, MaxForwardSpeed, ref moveVelocity);
                }
                else
                {
                    ApplyBraking(-1, MoveDeceleration, ref moveVelocity);
                }
            }
            else if ((lastControls & MoveBackwardMask) != 0)
            {
                if (moveVelocity <= 0)
                {
                    ApplyAcceleration(-1, MoveAcceleration, MaxBackwardSpeed, ref moveVelocity);
                }
                else
                {
                    ApplyBraking(1, MoveDeceleration, ref moveVelocity);
                }
            }
            else
            {
                ApplyBraking(moveVelocity >= 0 ? 1 : -1, MoveDamping, ref moveVelocity);
            }

            if ((lastControls & RotateRightMask) != 0)
            {
                if (rotationVelocity <= 0)
                {
                    ApplyAcceleration(-1, RotationAcceleration, MaxRotationSpeed, ref rotationVelocity);
                }
                else
                {
                    ApplyBraking(1, RotationDeceleration, ref rotationVelocity);
                }
            }
            else if ((lastControls & RotateLeftMask) != 0)
            {
                if (rotationVelocity >= 0)
                {
                    ApplyAcceleration(1, RotationAcceleration, MaxRotationSpeed, ref rotationVelocity);
                }
                else
                {
                    ApplyBraking(-1, RotationDeceleration, ref rotationVelocity);
                }
            }
            else
            {
                ApplyBraking(rotationVelocity >= 0 ? 1 : -1, RotationDamping, ref rotationVelocity);
            }

            if ((lastControls & SimpleShotMask) != 0 && entity.entityManager.matchManager.CurrentTick - lastShotTick > SimpleShotCooldown)
            {
                lastShotTick = entity.entityManager.matchManager.CurrentTick;

                OnShot();
            }

            if ((lastControls & AdvancedShotMask) != 0 && entity.entityManager.matchManager.CurrentTick - lastAdvancedShotTick > AdvancedShotCooldown)
            {
                lastAdvancedShotTick = entity.entityManager.matchManager.CurrentTick;

                OnAdvancedShot();
            }

            transform.Position += new Vector2(FixedMath.Cos(transform.Rotation), FixedMath.Sin(transform.Rotation)) * moveVelocity;

            transform.Rotation += rotationVelocity;
        }
Beispiel #19
0
    private bool Circle_Rectangle(Body circle, Body rectangle)
    {
        Vector2d newCirclePos = circle.position;

        //标准矩形
        if (!rectangle.isStandard)
        {
            //先进行一次剪枝
            long x1 = circle.position.x - rectangle.position.x;
            long y1 = circle.position.y - rectangle.position.y;
            long d1 = x1.Mul(x1) + y1.Mul(y1);

            long r1 = circle.radius + FixedMath.Create(1.42f).Mul(rectangle.width + rectangle.length);
            long d2 = r1.Mul(r1);

            if (d1 > d2)
            {
                return(false);
            }

            //先把圆形归位
            long angle = rectangle.direction.GetRotationAngle(new Vector2d(1, 0));
            newCirclePos = circle.position.PostionRotateInXZ(rectangle.position, angle);
        }

        long cx, cy;

        if (newCirclePos.x < rectangle.position.x - rectangle.length.Mul(FixedMath.Half))
        {
            cx = rectangle.position.x - rectangle.length.Mul(FixedMath.Half);
        }
        else if (newCirclePos.x > rectangle.position.x + rectangle.length.Mul(FixedMath.Half))
        {
            cx = rectangle.position.x + rectangle.length.Mul(FixedMath.Half);
        }
        else
        {
            cx = newCirclePos.x;
        }

        if (newCirclePos.y < rectangle.position.y - rectangle.width.Mul(FixedMath.Half))
        {
            cy = rectangle.position.y - rectangle.width.Mul(FixedMath.Half);
        }
        else if (newCirclePos.y > rectangle.position.y + rectangle.width.Mul(FixedMath.Half))
        {
            cy = rectangle.position.y + rectangle.width.Mul(FixedMath.Half);
        }
        else
        {
            cy = newCirclePos.y;
        }

        long d = (cx - newCirclePos.x).Mul(cx - newCirclePos.x) + (cy - newCirclePos.y).Mul(cy - newCirclePos.y);

        if (d < (circle.radius.Mul(circle.radius)))
        {
            return(true);
        }

        return(false);
    }
Beispiel #20
0
    // Use this for initialization
    void Start()
    {
        return;

        func = callBack;
        //int count = 0;
        //for (int i = 0; i < 100; i++)
        //{
        //    var g = GameObject.CreatePrimitive(PrimitiveType.Cube);
        //    g.transform.position = new Vector3(Random.Range(0, 100), 0, Random.Range(0, 100));
        //}
        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
        //sw.Start();
        //for (int i = 0; i < 100; i++)
        //{
        //    Ray r = new Ray();
        //    r.origin = new Vector3(Random.Range(0, 50),0, Random.Range(0, 50));
        //    r.direction = new Vector3(Random.Range(0, 1f), 0, Random.Range(0, 1f));
        //    r.direction = r.direction.normalized;
        //    var hit = Physics.Raycast(r, 100, -1);
        //   // Debug.DrawLine(r.origin, r.direction*100+r.origin, Color.red, 10);
        //    if (hit) count++;
        //}
        //   Debug.Log(sw.ElapsedMilliseconds);
        //return;
        Vector2d[] vs = new Vector2d[4];
        for (int i = 0; i < 100; i++)
        {
            var          center = new Vector2d(Random.Range(0, 100), Random.Range(0, 100));
            var          aabb   = new AABB(center, FixedMath.One * 2, FixedMath.One * 2);
            FixtureProxy fp     = new FixtureProxy();
            long         angle  = FixedMath.One * (int)(Random.Range(0, 359));
            Vector2d     a      = -aabb.Extents;
            Vector2d     b      = a + new Vector2d(0, aabb.Height);
            Vector2d     c      = aabb.Extents;
            Vector2d     d      = a + new Vector2d(aabb.Width, 0);
            var          halfw  = aabb.Width / 2;
            var          halfh  = aabb.Height / 2;
            var          radius = FixedMath.Sqrt((halfw).Mul(halfw) + halfh.Mul(halfh));
            a     = RotatePosi(a, angle);
            b     = RotatePosi(b, angle);
            c     = RotatePosi(c, angle);
            d     = RotatePosi(d, angle);
            vs[0] = a;
            vs[1] = b;
            vs[2] = c;
            vs[3] = d;
            Vector2d min = Vector2d.Min(vs) + center;
            Vector2d max = Vector2d.Max(vs) + center;
            DLog.Log(radius.ToFloat().ToString());
            var outteraabb = new AABB(center, radius * 2, radius * 2);
            fp.AABB    = aabb;
            fp.Fixture = new Transform2d(ref center, ref angle);
            int id = tree.AddProxy(ref outteraabb, fp);
            tree.MoveProxy(id, ref outteraabb, Vector2d.zero);
            DrawFixtureProxy(fp);
            DrawAABB(outteraabb);
        }

        //var bcs = GameObject.FindObjectsOfType<BoxCollider>();
        //for (int i = 0; i < bcs.Length; i++)
        //{
        //    var bc = bcs[i];
        //    var aabb = new AABB(new Vector2d(bc.transform.position), FixedMath.One, FixedMath.One);
        //    FixtureProxy fp = new FixtureProxy();
        //    fp.AABB = aabb;
        //    long angle = FixedMath.One * (int)(bc.transform.eulerAngles.y);
        //    Vector2d p = new Vector2d(bc.transform.position);
        //    fp.Fixture = new Transform2d(ref p, ref angle);
        //    tree.AddProxy(ref aabb, fp);
        //    DrawFixtureProxy(fp);
        //}
        //   sw.Reset();
        sw.Start();
        for (int i = 0; i < 1; i++)
        {
            RayCastInput input = new RayCastInput();
            input.Point1 = new Vector2d(Random.Range(0, 50) * FixedMath.One, Random.Range(0, 50) * FixedMath.One);
            input.Point2 = new Vector2d(Random.Range(50, 100) * FixedMath.One, Random.Range(50, 100) * FixedMath.One);
            NewSphere(input.Point1.ToVector3(), "start");
            NewSphere(input.Point2.ToVector3(), "end");
            input.MaxFraction = FixedMath.One;
            DrawLine(input);
            tree.RayCast(callBack, ref input);
        }
        Debug.Log(sw.ElapsedMilliseconds);
    }
Beispiel #21
0
    //弹走圆形
    Vector2d Offset_Rectangle_Circle(Body circle)
    {
        //Body rectangle = this;
        Vector2d newCirclePos = circle.position;

        long rot = FixedMath.Create(0);

        if (!isStandard)
        {
            //先把圆形归位
            rot          = direction.GetRotationAngle(new Vector2d(1, 0));
            newCirclePos = circle.position.PostionRotateInXZ(position, rot);
        }


        //long cx, cy;

        //if (newCirclePos.x < rectangle.position.x - rectangle.length.Mul(FixedMath.Half))
        //{
        //    cx = rectangle.position.x - rectangle.length.Mul(FixedMath.Half);
        //}
        //else if (newCirclePos.x > rectangle.position.x + rectangle.length.Mul(FixedMath.Half))
        //{
        //    cx = rectangle.position.x + rectangle.length.Mul(FixedMath.Half);
        //}
        //else
        //{
        //    cx = newCirclePos.x;
        //}

        //if (newCirclePos.y < rectangle.position.y - rectangle.width.Mul(FixedMath.Half))
        //{
        //    cy = rectangle.position.y - rectangle.width.Mul(FixedMath.Half);
        //}
        //else if (newCirclePos.y > rectangle.position.y + rectangle.width.Mul(FixedMath.Half))
        //{
        //    cy = rectangle.position.y + rectangle.width.Mul(FixedMath.Half);
        //}
        //else
        //{
        //    cy = newCirclePos.y;
        //}

        Vector2d oc = newCirclePos - position;

        //Debug.DrawLine(position.ToVector3(), (position + oc.Vector2dRotateInXZ(rot)).ToVector3(),Color.yellow);

        Vector2d offset = new Vector2d();

        if (oc.x > FixedMath.Create(0) && oc.x < length.Mul(FixedMath.Half) + circle.radius)
        {
            offset.x = (length.Mul(FixedMath.Half) - oc.x) + circle.radius;
        }
        else if (oc.x < FixedMath.Create(0) && oc.x > -length.Mul(FixedMath.Half) - circle.radius)
        {
            offset.x = (-length.Mul(FixedMath.Half) - oc.x) - circle.radius;
        }
        else
        {
            offset.x = 0;
        }

        if (oc.y > FixedMath.Create(0) && oc.y < width.Mul(FixedMath.Half) + circle.radius)
        {
            offset.y = (width.Mul(FixedMath.Half) - oc.y) + circle.radius;
        }
        else if (oc.y < FixedMath.Create(0) && oc.y > -width.Mul(FixedMath.Half) - circle.radius)
        {
            offset.y = (-width.Mul(FixedMath.Half) - oc.y) - circle.radius;
        }
        else
        {
            offset.y = 0;
        }

        if (Math.Abs(offset.x) > Math.Abs(offset.y))
        {
            offset.x = 0;
        }
        else
        {
            offset.y = 0;
        }

        offset = offset.Vector2dRotateInXZ(rot);
        return(offset);
    }
Beispiel #22
0
    // Update is called once per frame
    void Update()
    {
        var aabb = new AABB(new Vector2d(FixedMath.Create(points[3].transform.position.x), FixedMath.Create(points[3].transform.position.y)), FixedMath.One, FixedMath.One);

        aabb.DrawAABB(0, 0.01f);
        bool rst = AABB.TestTriangle(new Vector2d(FixedMath.Create(points[0].transform.position.x), FixedMath.Create(points[0].transform.position.y)),
                                     new Vector2d(FixedMath.Create(points[1].transform.position.x), FixedMath.Create(points[1].transform.position.y)),
                                     new Vector2d(FixedMath.Create(points[2].transform.position.x), FixedMath.Create(points[2].transform.position.y)),
                                     aabb,
                                     0
                                     );

        DLog.Log(rst.ToString());
    }
        void OnSceneGUI()
        {
            if (MoreThanOne)
            {
                return;
            }

            //Have to reinitialize everything because can't apply modified properties on base.serializedObject
            SerializedObject so = new SerializedObject(target);

            so.Update();
            SerializedProperty Shape      = so.FindProperty("_internalBody").FindPropertyRelative("_shape");
            SerializedProperty HalfWidth  = so.FindProperty("_internalBody").FindPropertyRelative("_halfWidth");
            SerializedProperty HalfHeight = so.FindProperty("_internalBody").FindPropertyRelative("_halfHeight");
            SerializedProperty Radius     = so.FindProperty("_internalBody").FindPropertyRelative("_radius");
            SerializedProperty Height     = so.FindProperty("_internalBody").FindPropertyRelative("_height");

            /*
             * //Currently unused
             * SerializedProperty Layer = so.FindProperty("_internalBody").FindPropertyRelative("_layer");
             * SerializedProperty IsTrigger = so.FindProperty("_internalBody").FindPropertyRelative("_isTrigger");
             * SerializedProperty Immovable = so.FindProperty("_internalBody").FindPropertyRelative("_immovable");
             * SerializedProperty Vertices = so.FindProperty("_internalBody").FindPropertyRelative("_vertices");
             * SerializedProperty PositionalTransform = so.FindProperty("_internalBody").FindPropertyRelative("_positionalTransform");
             * SerializedProperty RotationalTransform = so.FindProperty("_internalBody").FindPropertyRelative("_rotationalTransform");
             */

            ColliderType shape = (ColliderType)Shape.intValue;

            if (shape == ColliderType.None)
            {
                return;
            }
            Handles.color = Color.blue;
            LSBody    Body             = ((UnityLSBody)target).InternalBody;
            Transform transform        = ((UnityLSBody)target).transform;
            Vector3   targetPos        = transform.position;
            const int ImprecisionLimit = 100000;

            if (Mathf.Abs(targetPos.x) >= ImprecisionLimit ||
                Mathf.Abs(targetPos.y) >= ImprecisionLimit ||
                Mathf.Abs(targetPos.z) >= ImprecisionLimit)
            {
                return;
            }
            const float spread    = .02f;
            int         spreadMin = -1;
            int         spreadMax = 1;

            Handles.CapFunction dragCap = Handles.SphereHandleCap;
            float height    = targetPos.y;
            float xModifier = 0f;

            if (shape == ColliderType.Circle)
            {
                //Minus so the move handle doesn't end up on the same axis as the transform.position move handle
                float oldRadius = Radius.longValue.ToFloat();
                float newRadius =
                    Mathf.Abs(
                        (Handles.FreeMoveHandle(
                             new Vector3(targetPos.x - Radius.longValue.ToFloat(), targetPos.y, targetPos.z)
                             , Quaternion.identity,
                             MoveHandleSize,
                             Vector3.zero,
                             Handles.SphereHandleCap))
                        .x - targetPos.x);
                if (Mathf.Abs(oldRadius - newRadius) >= .02f)
                {
                    Radius.longValue = FixedMath.Create(newRadius);
                }

                Handles.DrawLine(targetPos, new Vector3(targetPos.x + Radius.longValue.ToFloat(), targetPos.y, targetPos.z));
                float baseHeight = targetPos.y;
                for (int i = spreadMin; i <= spreadMax; i++)
                {
                    Handles.CircleHandleCap(
                        1,
                        new Vector3(targetPos.x, baseHeight + (float)i * spread, targetPos.z)
                        , Quaternion.Euler(90, 0, 0)
                        , Radius.longValue.ToFloat()
                        , EventType.Repaint);
                }
                baseHeight = targetPos.y + Height.longValue.ToFloat();
                for (int i = spreadMin; i <= spreadMax; i++)
                {
                    Handles.CircleHandleCap(
                        1,
                        new Vector3(targetPos.x, baseHeight + (float)i * spread, targetPos.z)
                        , Quaternion.Euler(90, 0, 0)
                        , Radius.longValue.ToFloat()
                        , EventType.Repaint);
                }
                xModifier = 0;//Radius.longValue.ToFloat();
            }
            else if (shape == ColliderType.AABox)
            {
                float oldWidth = HalfWidth.longValue.ToFloat();
                float newWidth =
                    Mathf.Abs(
                        Handles.FreeMoveHandle(
                            new Vector3(targetPos.x - (float)HalfWidth.longValue.ToFormattedDouble(), targetPos.y, targetPos.z),
                            Quaternion.identity,
                            MoveHandleSize,
                            Vector3.zero,
                            dragCap)
                        .x - targetPos.x);
                if (Mathf.Abs(newWidth - oldWidth) >= .02f)
                {
                    HalfWidth.longValue = FixedMath.Create(newWidth);
                }
                float oldHeight = HalfHeight.longValue.ToFloat();
                float newHeight =
                    System.Math.Abs(
                        Handles.FreeMoveHandle(
                            new Vector3(targetPos.x, targetPos.y, targetPos.z - (float)HalfHeight.longValue.ToFormattedDouble()),
                            Quaternion.identity,
                            MoveHandleSize,
                            Vector3.zero,
                            dragCap)
                        .z - targetPos.z);
                if (Mathf.Abs(newHeight - oldHeight) >= .02f)
                {
                    HalfHeight.longValue = FixedMath.Create(newHeight);
                }
                float halfWidth  = HalfWidth.longValue.ToFloat();
                float halfHeight = HalfHeight.longValue.ToFloat();
                for (int i = 0; i < 1; i++)
                {
                    height = targetPos.y + (float)i * spread;
                    Vector3[] lines = new Vector3[]
                    {
                        new Vector3(targetPos.x + halfWidth, height, targetPos.z + halfHeight),
                        new Vector3(targetPos.x + halfWidth, height, targetPos.z - halfHeight),

                        new Vector3(targetPos.x + halfWidth, height, targetPos.z - halfHeight),
                        new Vector3(targetPos.x - halfWidth, height, targetPos.z - halfHeight),

                        new Vector3(targetPos.x - halfWidth, height, targetPos.z - halfHeight),
                        new Vector3(targetPos.x - halfWidth, height, targetPos.z + halfHeight),

                        new Vector3(targetPos.x - halfWidth, height, targetPos.z + halfHeight),
                        new Vector3(targetPos.x + halfWidth, height, targetPos.z + halfHeight)
                    };
                    Handles.DrawPolyLine(lines);
                }
                for (int i = 0; i < 1; i++)
                {
                    height = targetPos.y + (float)i * spread + Height.longValue.ToFloat();
                    Vector3[] lines = new Vector3[]
                    {
                        new Vector3(targetPos.x + halfWidth, height, targetPos.z + halfHeight),
                        new Vector3(targetPos.x + halfWidth, height, targetPos.z - halfHeight),

                        new Vector3(targetPos.x + halfWidth, height, targetPos.z - halfHeight),
                        new Vector3(targetPos.x - halfWidth, height, targetPos.z - halfHeight),

                        new Vector3(targetPos.x - halfWidth, height, targetPos.z - halfHeight),
                        new Vector3(targetPos.x - halfWidth, height, targetPos.z + halfHeight),

                        new Vector3(targetPos.x - halfWidth, height, targetPos.z + halfHeight),
                        new Vector3(targetPos.x + halfWidth, height, targetPos.z + halfHeight)
                    };
                    Handles.DrawPolyLine(lines);
                }

                xModifier = 0;//halfWidth;
            }
            else if (shape == ColliderType.Polygon)
            {
                float yRot = transform.eulerAngles.y * Mathf.Deg2Rad;

                Vector2d rotation = Vector2d.CreateRotation(yRot);
                bool     changed  = false;


                Vector3[] draws = new Vector3[Body.Vertices.Length + 1];

                for (int i = 0; i < Body.Vertices.Length; i++)
                {
                    Vector2d vertex = Body.Vertices [i];
                    vertex.Rotate(rotation.x, rotation.y);
                    Vector3 drawPos    = vertex.ToVector3() + targetPos;
                    Vector3 newDrawPos = Handles.FreeMoveHandle(drawPos, Quaternion.identity, MoveHandleSize, new Vector3(0, float.PositiveInfinity, 0), Handles.SphereHandleCap);
                    if ((newDrawPos - (drawPos)).magnitude >= .01f)
                    {
                        newDrawPos -= targetPos;
                        vertex      = new Vector2d(newDrawPos);
                        vertex.RotateInverse(rotation.x, rotation.y);
                        Body.Vertices [i] = vertex;
                        changed           = true;
                    }
                    draws[i] = drawPos;
                    Handles.Label(drawPos, "V: " + i.ToString(), LabelStyle);
                }
                if (Body.Vertices.Length > 0)
                {
                    draws[draws.Length - 1] = draws[0];
                    Handles.DrawPolyLine(draws);
                    for (int i = 0; i < draws.Length; i++)
                    {
                        Vector3 highPos = draws[i];
                        highPos.y += Body.Height.ToFloat();
                        Handles.DrawLine(draws[i], highPos);
                        draws[i] = highPos;
                    }
                    Handles.DrawPolyLine(draws);
                }
                if (changed)
                {
                    so.Update();
                }
            }


            Handles.DrawLine(
                new Vector3(targetPos.x + xModifier, targetPos.y, targetPos.z),
                new Vector3(targetPos.x + xModifier, targetPos.y + Height.longValue.ToFloat(), targetPos.z));

            Vector3 movePos = targetPos;

            movePos.x += xModifier;
            movePos.y += (float)Height.longValue.ToFormattedDouble();
            Vector3 lastMovePos = movePos;

            movePos =
                Handles.FreeMoveHandle(
                    movePos,
                    Quaternion.identity,
                    MoveHandleSize,
                    Vector3.zero,
                    dragCap
                    );
            if ((lastMovePos - movePos).sqrMagnitude >= .1f)
            {
                Height.longValue = FixedMath.Create(Mathf.Max(Mathf.Abs(movePos.y - targetPos.y)));
            }
            so.ApplyModifiedProperties();
        }
 long FixedNumberField(Rect position, GUIContent label, long value)
 {
     return(FixedMath.Create(EditorGUI.DoubleField(position, label, value.ToDouble())));
 }
Beispiel #25
0
            public GridNode GetNode()
            {
                //Calculated closest side to raycast in first
                long xDif = OffsettedPos.x - XGrid;

                xDif = xDif.ClampOne();
                long yDif = OffsettedPos.y - YGrid;

                yDif = yDif.ClampOne();
                long nodeHalfWidth = FixedMath.One / 2;

                //Check to see if we should raycast towards corner first
                if ((xDif.Abs() >= nodeHalfWidth / 2) &&
                    (yDif.Abs() >= nodeHalfWidth / 2))
                {
                    dirX = FixedMath.RoundToInt(xDif);
                    dirY = FixedMath.RoundToInt(yDif);
                }
                else
                {
                    if (xDif.Abs() < yDif.Abs())
                    {
                        dirX = 0;
                        dirY = yDif.RoundToInt();
                    }
                    else
                    {
                        dirX = xDif.RoundToInt();
                        dirY = 0;
                    }
                }

                int layerStartX = dirX,
                    layerStartY = dirY;
                int iterations  = 0; // <- this is for debugging

                for (layer = 1; layer <= this.MaxTestDistance;)
                {
                    this.CheckPathNode(GridManager.GetNode(XGrid + dirX, YGrid + dirY));
                    if (this.castNodeFound)
                    {
                        return(this.closestNode);
                    }
                    AdvanceRotation();
                    //If we make a full loop
                    if (layerStartX == dirX && layerStartY == dirY)
                    {
                        layer++;
                        //Advance a layer instead of rotation
                        if (dirX > 0)
                        {
                            dirX = layer;
                        }
                        else if (dirX < 0)
                        {
                            dirX = -layer;
                        }
                        if (dirY > 0)
                        {
                            dirY = layer;
                        }
                        else if (dirY < 0)
                        {
                            dirY = -layer;
                        }
                        layerStartX = dirX;
                        layerStartY = dirY;
                    }
                    iterations++;
                    if (iterations > 500)
                    {
                        Debug.Log("tew many");
                        break;
                    }
                }

                //If the cast node is found or the side has been checked, do not raycast on that side

                if (!castNodeFound)
                {
                    return(null);
                }
                return(closestNode);
            }
        public void OnSceneGUI()
        {
            if (Application.isPlaying)
            {
                return;
            }
            LSBody    Body            = (LSBody)(target);
            Transform cachedTransform = Body.transform;
            Vector3   TargetPosition  = cachedTransform.position;

            TargetPosition.y += .55f;
            Vector3[] PolyLine;
            switch (Body.Shape)
            {
            case ColliderType.Circle:
                Handles.color = FrameColor;
                Handles.CircleCap(1, TargetPosition, CapRotation, FixedMath.ToFloat(Body.Radius));
                Handles.CircleCap(1, TargetPosition, CapRotation, FixedMath.ToFloat(Body.Radius) + -.005f);
                Handles.CircleCap(1, TargetPosition, CapRotation, FixedMath.ToFloat(Body.Radius) + .005f);

                Vector3 NewVec = TargetPosition;
                NewVec.x     -= (float)Math.Round(FixedMath.ToDouble(Body.Radius), 4, MidpointRounding.AwayFromZero);
                Handles.color = MoveColor;
                NewVec        = Handles.FreeMoveHandle(NewVec, Quaternion.identity, .35f, Vector3.zero, Handles.SphereCap);
                Body.Radius   = FixedMath.Create(NewVec.x - TargetPosition.x);
                if (Body.Radius < 0)
                {
                    Body.Radius = -Body.Radius;
                }
                break;

            case ColliderType.AABox:
                float halfWidth  = FixedMath.ToFloat(Body.HalfWidth);
                float halfHeight = FixedMath.ToFloat(Body.HalfHeight);
                PolyLine = new Vector3[5];
                for (int i = 0; i < 4; i++)
                {
                    PolyLine [i] = TargetPosition;
                }

                PolyLine [0].x += halfWidth;
                PolyLine [0].z += halfHeight;

                PolyLine [1].x += halfWidth;
                PolyLine [1].z -= halfHeight;

                PolyLine [2].x -= halfWidth;
                PolyLine [2].z -= halfHeight;

                PolyLine [3].x -= halfWidth;
                PolyLine [3].z += halfHeight;

                PolyLine [4]  = PolyLine [0];
                Handles.color = FrameColor;
                Handles.DrawAAPolyLine(5f, PolyLine);
                Handles.color = MoveColor;

                Vector3 WidthScaler = TargetPosition;
                WidthScaler.x -= (float)LSEditorUtility.Round(Body.HalfWidth);
                WidthScaler    = Handles.FreeMoveHandle(WidthScaler, Quaternion.identity, .35f, Vector3.zero, Handles.SphereCap);
                Body.HalfWidth = FixedMath.Create(WidthScaler.x - TargetPosition.x);

                Vector3 HeightScaler = TargetPosition;
                HeightScaler.z -= (float)LSEditorUtility.Round(Body.HalfHeight);
                HeightScaler    = Handles.FreeMoveHandle(HeightScaler, Quaternion.identity, .35f, Vector3.zero, Handles.SphereCap);
                Body.HalfHeight = FixedMath.Create(HeightScaler.z - TargetPosition.z);
                if (Body.HalfWidth <= 0)
                {
                    Body.HalfWidth = -Body.HalfWidth;
                }
                if (Body.HalfHeight < 0)
                {
                    Body.HalfHeight = -Body.HalfHeight;
                }

                break;

            case ColliderType.Polygon:
                if (Body.Vertices == null || Body.Vertices.Length == 0)
                {
                    break;
                }

                PolyLine      = new Vector3[Body.Vertices.Length + 1];
                Handles.color = MoveColor;
                for (int i = 0; i < Body.Vertices.Length; i++)
                {
                    //TODO: Handle world scaling
                    Vector3 vertPos     = Body.Vertices [i].ToVector3(0f) + TargetPosition;
                    Vector3 freemoveVec = Handles.FreeMoveHandle(vertPos, Quaternion.identity, .35f, Vector3.zero, Handles.SphereCap) - TargetPosition;
                    Body.Vertices [i] = new Vector2d(FixedMath.Create(freemoveVec.x), FixedMath.Create(freemoveVec.z));
                    Handles.Label(vertPos, "V" + i.ToString());
                    PolyLine [i] = vertPos;
                }

                PolyLine [Body.Vertices.Length] = PolyLine [0];
                Handles.color = FrameColor;
                Handles.DrawAAPolyLine(5f, PolyLine);
                break;
            }
        }
    void UpdateMove(EntityBase entity, int deltaTime)
    {
        MoveComponent    mc = (MoveComponent)entity.GetComp("MoveComponent");
        CommandComponent cc = (CommandComponent)entity.GetComp("CommandComponent");

        mc.dir        = cc.moveDir;
        mc.m_velocity = 4000;

        Vector2d newPos = mc.pos;

        newPos += mc.dir * FixedMath.Create(deltaTime).Div(FixedMath.Create(1000)).Mul(FixedMath.Create(mc.m_velocity).Div(FixedMath.Create(1000)));

        mc.pos = newPos;

        //Debug.Log("dir " + mc.dir + " ");
    }
Beispiel #28
0
    void computeNewFixedVelocity()
    {
        _fixedLines.Clear();

        for (var i = 0; i < neighborsList.Count; ++i)
        {
            var neighbor = neighborsList[i];

            var relativePos  = neighbor.Position.ToVector2d() - _self.Position.ToVector2d();
            var mRelativePos = relativePos.Magnitude();
            //flag
            var relativeVel = _self.Velocity.ToVector2d() - neighbor.Velocity.ToVector2d();
            var comRadius   = neighbor.Radius + _self.Radius;

            FixedLine line = new FixedLine();
            Vector2d  u    = Vector2d.zero;

            if (comRadius < mRelativePos)
            {
                Vector2d vec        = relativeVel - relativePos / FixedMath.Create(6);
                var      mVec       = vec.Magnitude();
                var      dotProduct = Vector2d.Dot(vec, relativePos);
                if (dotProduct < 0 && dotProduct.Mul(dotProduct) > comRadius.Mul(comRadius) * mVec.Mul(mVec))
                {
                    Vector2d normVec = vec.Normalize();
                    line.direction = new Vector2d(normVec.y, -normVec.x);
                    u = normVec * (comRadius.Div(FixedMath.Create(6)) - mVec);
                }
                else
                {
                    long     mEdge = FixedMath.Sqrt(mRelativePos.Mul(mRelativePos) - comRadius.Mul(comRadius));
                    Vector2d edge  = Vector2d.zero;
                    if (Vector2d.det(relativePos, vec) > 0)
                    {
                        edge = Vector2d.rotate(relativePos, mEdge.Div(mRelativePos), comRadius.Div(mRelativePos));
                    }
                    else
                    {
                        edge  = Vector2d.rotate(relativePos, mEdge.Div(mRelativePos), -comRadius.Div(mRelativePos));
                        edge *= -1;
                    }
                    line.direction = edge.Normalize();
                    // project   u' = v * dot(u, v) / v^2
                    // v = ||line.direction|| = 1
                    u = Vector2d.Dot(relativeVel, line.direction) * line.direction - relativeVel;
                }
            }
            // tricks
            else
            {
                Vector2d vec     = relativeVel - relativePos / LockFrameMgr.FixedFrameTime;
                Vector2d normVec = vec.Normalize();
                line.direction = new Vector2d(normVec.y, -normVec.x);
                u = (comRadius.Div(LockFrameMgr.FixedFrameTime) - vec.Magnitude()) * normVec;
            }

            line.point = _fixedVecocity + u / 2;
            _fixedLines.Add(line);
        }

        _fixedVecocity = linearPrograming(_fixedLines);
    }
Beispiel #29
0
 public void SetAxis(Axes i, float value)
 {
     axes [(int)i] = FixedMath.Create(value);
 }
Beispiel #30
0
 /// <summary>
 /// Changes the actor's pitch (In radians)
 /// </summary>
 /// <param name="x">The value to change the pitch by</param>
 /// <param name="interpolate">If true, the change will be interpolated</param>
 public virtual void ChangePitchRadians(Accum x, bool interpolate = false)
 {
     prevPitch = (interpolate ? pitch : prevPitch);
     pitch     = FixedMath.ClampInt((pitch + FixedMath.RadiansToDegrees(x)), -90, 90);
 }