예제 #1
0
    ///

    private void Init()
    {
        movementMode    = MovementMode.FREE;
        currentAccel    = accelFree;
        currentMaxSpd   = maxWalkingSpeed;
        desiredRotation = transform.rotation;
    }
예제 #2
0
 /* Change character to BattleMode
  * Should be called when something changes the character state
  * EX: Attacking or receiving damage
  */
 public void InputSetInBattleMode()
 {
     movementMode      = MovementMode.BATTLE;
     isDirectionLocked = false;
     stepState         = 0;
     currentAccel      = accelFree;
 }
예제 #3
0
 private void Update()
 {
     if (skeleton.health <= 0)
     {
         movementMode = MovementMode.Disabled;
     }
 }
예제 #4
0
 public void SetMovementAir()
 {
     PlayerMode    = MovementMode.OnAir;
     canSecondJump = true;
     //input.Crouch(true);
     //Debug.Log(PlayerMode);
 }
        private async Task <bool> GambleItems(Client client, MovementMode movementMode)
        {
            bool shouldGamble = client.Game.Me.Attributes[D2NG.Core.D2GS.Players.Attribute.GoldInStash] > 7_000_000;

            if (shouldGamble && System.Threading.Interlocked.Exchange(ref isAnyClientGambling, 1) == 0)
            {
                var gambleNPC = NPCHelpers.GetGambleNPC(client.Game.Act);
                Log.Information($"Gambling items at {gambleNPC}");
                var pathToGamble = await _pathingService.GetPathToNPC(client.Game, gambleNPC, movementMode);

                if (!await MovementHelpers.TakePathOfLocations(client.Game, pathToGamble, movementMode))
                {
                    Log.Warning($"{movementMode} to {gambleNPC} failed at {client.Game.Me.Location}");
                    return(false);
                }

                var uniqueNPC = NPCHelpers.GetUniqueNPC(client.Game, gambleNPC);
                if (uniqueNPC == null)
                {
                    Log.Warning($"{gambleNPC} not found at {client.Game.Me.Location}");
                    return(false);
                }

                NPCHelpers.GambleItems(client.Game, uniqueNPC);
                System.Threading.Interlocked.Exchange(ref isAnyClientGambling, 0);
            }

            return(true);
        }
        private async Task <bool> RepairItems(Game game, MovementMode movementMode)
        {
            if (NPCHelpers.ShouldGoToRepairNPC(game))
            {
                var repairNPC = NPCHelpers.GetRepairNPC(game.Act);
                Log.Information($"Client {game.Me.Name} moving to {repairNPC} for repair/arrows");
                var pathRepairNPC = repairNPC == NPCCode.Hratli ? await _pathingService.GetPathToObject(game, EntityCode.Hratli, movementMode)
                 : await _pathingService.GetPathToNPC(game.MapId, Difficulty.Normal, WayPointHelpers.MapTownArea(game.Act), game.Me.Location, repairNPC, movementMode);

                if (pathRepairNPC.Count > 0 && await MovementHelpers.TakePathOfLocations(game, pathRepairNPC, movementMode))
                {
                    var uniqueNPC = NPCHelpers.GetUniqueNPC(game, repairNPC);
                    if (uniqueNPC == null)
                    {
                        Log.Warning($"Client {game.Me.Name} Did not find {repairNPC} at {game.Me.Location}");
                        return(false);
                    }

                    if (!NPCHelpers.RepairItemsAndBuyArrows(game, uniqueNPC))
                    {
                        Log.Warning($"Client {game.Me.Name} Selling items and refreshing potions to {repairNPC} failed at {game.Me.Location}");
                    }
                }
                else
                {
                    Log.Warning($"Client {game.Me.Name} {movementMode} to {repairNPC} failed at {game.Me.Location}");
                }
            }

            return(true);
        }
예제 #7
0
 public void StartIdle()
 {
     _guardPosition     = transform.position;
     this._movementMode = MovementMode.Guard;
     this._stance       = Stance.DefensiveStance;
     AnimatorStopMoving();
 }
        private async Task <bool> RefreshAndSellItems(Game game, MovementMode movementMode, TownManagementOptions options)
        {
            var sellItemCount = game.Inventory.Items.Count(i => !Pickit.Pickit.ShouldKeepItem(game, i)) + game.Cube.Items.Count(i => !Pickit.Pickit.ShouldKeepItem(game, i));

            if (NPCHelpers.ShouldRefreshCharacterAtNPC(game) || sellItemCount > 5 || options.ItemsToBuy?.Count > 0)
            {
                var sellNpc = NPCHelpers.GetSellNPC(game.Act);
                Log.Information($"Client {game.Me.Name} moving to {sellNpc} for refresh and selling {sellItemCount} items");
                var pathSellNPC = await _pathingService.GetPathToNPC(game.MapId, Difficulty.Normal, WayPointHelpers.MapTownArea(game.Act), game.Me.Location, sellNpc, movementMode);

                if (pathSellNPC.Count > 0 && await MovementHelpers.TakePathOfLocations(game, pathSellNPC, movementMode))
                {
                    var uniqueNPC = NPCHelpers.GetUniqueNPC(game, sellNpc);
                    if (uniqueNPC == null)
                    {
                        Log.Warning($"Client {game.Me.Name} Did not find {sellNpc} at {game.Me.Location}");
                        return(false);
                    }

                    if (!NPCHelpers.SellItemsAndRefreshPotionsAtNPC(game, uniqueNPC, options.ItemsToBuy))
                    {
                        Log.Warning($"Client {game.Me.Name} Selling items and refreshing potions failed at {game.Me.Location}");
                        return(false);
                    }
                }
                else
                {
                    Log.Warning($"Client {game.Me.Name} {movementMode} to {sellNpc} failed at {game.Me.Location}");
                    return(false);
                }
            }

            return(true);
        }
예제 #9
0
 void CmdChangePos(Vector3 pos)
 {
     movePos = pos;
     mode    = MovementMode.move;
     print(gameObject.name + " - moving to " + pos.ToString());
     attackTarget = null;
 }
예제 #10
0
파일: Ghost.cs 프로젝트: chaitae/Ten
 void Update()
 {
     distanceFromPlayer = Vector3.Distance(this.transform.position, player.transform.position);
     if (moveMode == MovementMode.Flee)
     {
         if (!agent.hasPath)
         {
             RunAway();
         }
         if (distanceFromPlayer > sightDistance)
         {
             moveMode        = MovementMode.Wander;
             agent.isStopped = true;
             agent.ResetPath();
         }
     }
     else if (moveMode == MovementMode.Wander)
     {
         if (!agent.hasPath)
         {
             ChooseRandomLocation();
         }
         if (distanceFromPlayer <= sightDistance)
         {
             moveMode        = MovementMode.Flee;
             agent.isStopped = true;
             agent.ResetPath();
         }
     }
     else if (moveMode == MovementMode.Stop)
     {
         agent.isStopped = true;
         agent.ResetPath();
     }
 }
예제 #11
0
    public int ShiftMove(RaycastHit hit, MovementMode mode)
    {
        _attacking = false;
        AnimatorStopFiring();
        _guardPosition = new Vector3(float.PositiveInfinity, 0, 0);
        Unit temp = hit.transform.GetComponentInParent <Unit>();

        // if raycast hit ground instead of unit
        if (temp == null)
        {
            ShiftMove(hit.point, mode);
            return(mode == MovementMode.AMove ? 1 : 0);
        }

        // follow target
        if (temp.Alignment == Alignment.Friendly)
        {
            ShiftFollow(temp);
            return(3);
        }
        else     // attack target
        {
            ShiftAttack(temp);
            return(2);
        }
    }
예제 #12
0
 // Use this for initialization
 void Start()
 {
     m_mmMovement      = MovementMode.Hopping;
     m_fTime           = 0f;
     m_bIsGrounded     = false;
     m_bForceIsApplied = false;
 }
        private async Task <bool> IdentifyItems(Game game, MovementMode movementMode)
        {
            var unidentifiedItemCount = game.Inventory.Items.Count(i => !i.IsIdentified) +
                                        game.Cube.Items.Count(i => !i.IsIdentified);

            if (unidentifiedItemCount > 6)
            {
                Log.Information($"Visiting Deckard Cain with {unidentifiedItemCount} unidentified items");
                var deckhardCainCode = NPCHelpers.GetDeckardCainForAct(game.Act);

                var deckardCain     = NPCHelpers.GetUniqueNPC(game, deckhardCainCode);
                var pathDeckardCain = new List <Point>();
                if (deckardCain != null)
                {
                    pathDeckardCain = await _pathingService.GetPathToLocation(game.MapId, Difficulty.Normal, WayPointHelpers.MapTownArea(game.Act), game.Me.Location, deckardCain.Location, movementMode);
                }
                else
                {
                    pathDeckardCain = await _pathingService.GetPathToNPC(game.MapId, Difficulty.Normal, WayPointHelpers.MapTownArea(game.Act), game.Me.Location, deckhardCainCode, movementMode);
                }

                if (!await MovementHelpers.TakePathOfLocations(game, pathDeckardCain, movementMode))
                {
                    Log.Warning($"Client {game.Me.Name} {movementMode} to deckard cain failed at {game.Me.Location}");
                    return(false);
                }

                return(NPCHelpers.IdentifyItemsAtDeckardCain(game));
            }

            return(true);
        }
예제 #14
0
 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 //	* New Method: Initiate Touch Movement
 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 public void InitiateTouchMove()
 {
     m_vUserStartPosition         = WorldPosition;
     m_vUserCurrentPosition       = (CanMoveX ? CurrentPosition : CurrentPositionWithoutX);
     m_vUserPreviousFramePosition = m_vUserCurrentPosition;
     m_eMovementMode = MovementMode.MOVE;
 }
예제 #15
0
 public void GameWon()
 {
     movementSpeed *= 1.8f;
     rotateSpeed   *= 2f;
     movementMode   = MovementMode.GameWon;
     isSwarmKing    = false;
 }
예제 #16
0
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Untagged")
        {
            if (movementMode is RoamingMode)
            {
                ((RoamingMode)movementMode).changeDirection();
            }
            else
            {
                movementMode = new RoamingMode(this);
            }

            if (isSpeededUp)
            {
                speed      -= speedUp;
                isSpeededUp = false;
            }
        }
        else if (collision.gameObject.tag == "Player")
        {
            //Load battle scene
            //print("Catch you!\n");
            //Just an example:
            collision.gameObject.GetComponent <HealthManager>().ChangeHP(-10);
        }
    }
예제 #17
0
        public async Task <List <Point> > GetPathFromWaypointToArea(uint mapId, Difficulty difficulty, Area area,
                                                                    Waypoint waypoint,
                                                                    Area toArea, MovementMode movementMode)
        {
            var map = await _mapApiService.GetArea(mapId, difficulty, area);

            if (!map.AdjacentLevels.TryGetValue(toArea, out var adjacentLevel))
            {
                throw new InvalidOperationException($"Adjacent Area {toArea} does not exist for area {area}");
            }

            if (adjacentLevel.Exits.Count == 0)
            {
                throw new InvalidOperationException($"No exits for area {toArea}");
            }

            var toLocation = adjacentLevel.Exits[0];

            var entityCode = (int)waypoint.ToEntityCode();

            if (map.Npcs.TryGetValue(entityCode, out var points) && points.Count > 0)
            {
                return(GetPath(mapId, difficulty, area, map, movementMode, points.First(), toLocation));
            }

            if (map.Objects.TryGetValue(entityCode, out var objectPoints) && objectPoints.Count > 0)
            {
                return(GetPath(mapId, difficulty, area, map, movementMode, objectPoints.First(), toLocation));
            }

            return(new List <Point>());
        }
예제 #18
0
        /// <summary>
        /// The main method in every robot. You must override this to set up your
        /// robot's basic behavior.
        /// Contains the main loop.
        /// </summary>
        public override void Run()
        {
            try
            {
                PaintJob();

                this.IsAdjustGunForRobotTurn   = true;
                this.IsAdjustRadarForRobotTurn = true;
                this.IsAdjustRadarForGunTurn   = true;

                this.SetTurnRadarRightRadians(double.PositiveInfinity);

                // reset private variables
                this.previousAngle       = 0;
                this.collisionTime       = 0;
                this.currentMovementMode = MovementMode.AntiGravity;

                this.enemyBullets = new List <WaveBullet>();

                do
                {
                    // wait to gather enemy statistics before taking action
                    if (this.Time > 9)
                    {
                        Action();
                    }

                    Execute();
                } while (true);
            }
            catch (Exception e)
            {
                // for handling random exceptions that had sometimes occured at the end of round
            }
        }
예제 #19
0
        public async Task <List <Point> > GetPathToLocation(uint mapId, Difficulty difficulty, Area area, Point fromLocation, Point toLocation,
                                                            MovementMode movementMode)
        {
            var map = await _mapApiService.GetArea(mapId, difficulty, area);

            return(GetPath(mapId, difficulty, area, map, movementMode, fromLocation, toLocation));
        }
 private Vector3[] GenerateDirPathToTarget(MovementMode mode, AITargeter source, AITargeter target)
 {
     if (mode == MovementMode.AdditiveSetForward)
     {
         return new Vector3[1] {
                    (target.transform.position - source.transform.position) / 10
         }
     }
     ;
     else if (mode == MovementMode.AdditiveToTransform)
     {
         return new Vector3[1] {
                    source.transform.InverseTransformDirection(target.transform.position - source.transform.position) / 10
         }
     }
     ;
     else if (mode == MovementMode.SetToForward)
     {
         return(CircleMotion.GeneratePtToPtMotionOnForw(source, target, 16));
     }
     else
     {
         Debug.Log("Unsupported mode. [PathfindToTargetMotion]" + mode);
     }
     return(new Vector3[0]);
 }
예제 #21
0
    public void EndCombat()
    {
        if (combatMode == CombatMode.Fleeing)
        {
            // End flight

            Vector2 avgPos = new Vector2();
            members.ForEach(member => avgPos += (Vector2)member.position);
            avgPos /= members.Count;

            targetPosition = avgPos;
            position       = avgPos;
            hasTarget      = false;
            movementMode   = MovementMode.Stationary;
        }
        else if (combatMode == CombatMode.Pursuing)
        {
            targetPosition = GetPosition();
            movementMode   = MovementMode.Stationary;
        }

        inCombat   = false;
        combatMode = CombatMode.None;

        fleeingFrom   = null;
        attackedSquad = null;
    }
예제 #22
0
 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 //	* New Method: Initiate Zoom Movement
 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 public void InitiateTouchZoom()
 {
     m_vUserStartPosition    = WorldPosition;
     m_vUserCurrentPosition  = m_vUserStartPosition;
     m_fCurrentZoomDistance  = CurrentZoom;
     m_fPreviousZoomDistance = m_fCurrentZoomDistance;
     m_eMovementMode         = MovementMode.ZOOM;
 }
예제 #23
0
 public void MergeWith(Transform anchor, bool hide = true)
 {
     charController.enabled = false;
     movementMode           = MovementMode.Anchor;
     psm.anchor             = anchor;
     visible = false;
     characterContainer.gameObject.SetActive(false);
 }
    private void Awake()
    {
        //Get our rigidbody, and init originalconstraints for enable/disable code.
        LazyLoadRigidBody();
        m_OriginalConstrains = m_Rigidbody.constraints;

        m_CurrentMovementMode = MovementMode.Forward;
    }
예제 #25
0
 /// <summary>
 /// This is called not only on the start of the match but also when the game is reset
 /// </summary>
 public void Start()
 {
     setTimerTo(0);
     currentNode  = startNode;
     movementMode = MovementMode.Waiting;
     StartCoroutine(BeginningCoroutine());
     speed = UpdateGhostSpeed();
 }
예제 #26
0
 /// <summary>
 /// forces ghosts to stop moving
 /// </summary>
 public void StopMoving()
 {
     StopAllCoroutines();
     movementMode = MovementMode.Waiting;
     animator.SetBool("Dead", false);
     animator.SetFloat("DirX", 0);
     animator.SetFloat("DirY", 0);
 }
예제 #27
0
 public void ShiftMove(Vector3 moveTo, MovementMode mode)
 {
     _attacking = false;
     AnimatorStopFiring();
     _guardPosition = new Vector3(float.PositiveInfinity, 0, 0);
     _shiftQueue.Enqueue(new Command(mode, moveTo));
     ExecuteFirstQueueAction();
 }
예제 #28
0
    private void UpdateAir()
    {
        //Setear velocidad máxima
        float speedToUse = groundMaxSpeed;
        float xSpeed     = 0;

        jumpPressed       = Input.GetButton("Jump");
        jumpPressedBefore = jumpPressed;
        float aceleationToUse = jumpPressed && rb2d.velocity.y < 0 ? airGlideAccel : airAccel;

        if (Mathf.Abs(Input.GetAxis("Horizontal")) > 0.1f)
        {
            //Apply acceleration
            xSpeed = rb2d.velocity.x + Input.GetAxis("Horizontal") * aceleationToUse * Time.deltaTime;
        }
        else
        {
            //Apply Friction
            xSpeed = rb2d.velocity.x * (1 - airFriction * Time.deltaTime);
        }
        xSpeed = Mathf.Clamp(xSpeed, -speedToUse, speedToUse);

        float gravityToUse = rb2d.velocity.y > 0 ? gravityOnAir : gravityOnGround;
        //if(rb2d.velocity.y > 0)
        //	gravityToUse = gravityOnAir;

        float ySpeed = rb2d.velocity.y + gravityToUse * Time.deltaTime;

        //Chequear Salto
        if (Input.GetButtonUp("Jump") && rb2d.velocity.y > minJumpVelocity)
        {
            ySpeed = minJumpVelocity;
        }

        if (jumpPressed && rb2d.velocity.y < 0)
        {
            ySpeed = Mathf.SmoothDamp(rb2d.velocity.y, maxVericalGlideSpeed, ref velocityYSmoothing, .1f);
            planeo = false;
            anim.SetBool("planeando", planeo);
        }
        else
        {
            planeo = false;
            anim.SetBool("planeando", planeo);
        }

        rb2d.velocity = xSpeed * Vector2.right + ySpeed * Vector2.up;

        if (grounded)
        {
            PlayerMode = MovementMode.OnGround;
        }

        if (Mathf.Abs(Input.GetAxis("Vertical")) > 0.1f && grabbedTransform != null)
        {
            PlayerMode = MovementMode.OnClimbing;
        }
    }
예제 #29
0
파일: Ghost.cs 프로젝트: chaitae/Ten
    public void VacuumedAction()
    {
        VacuumCollisionHandler vacuumCol = GameObject.FindObjectOfType <VacuumCollisionHandler>();

        this.transform.SetParent(vacuumCol.gameObject.transform);
        moveMode = MovementMode.Stop;
        Debug.Log(this.name + " vacuumed");
        StartCoroutine(WaitAndDestroy(2));
    }
예제 #30
0
 public void moveTo(Vector3 target)
 {
     agent.destination    = target;
     activeEnemy          = null;
     activeMode           = MovementMode.walking;
     blockMoves           = 180;
     agent.updateRotation = true;
     hasMoveTarget        = true;
 }
예제 #31
0
파일: Unit.cs 프로젝트: Evertras/Iroth
    public void CancelMovement()
    {
        var unitMoverObject = transform.Find ("UnitMover").gameObject;

        SelectForMovement(false);

        unitMoverObject.transform.localPosition = Vector3.zero;
        unitMoverObject.transform.localRotation = Quaternion.identity;

        unitMoverObject.GetComponent<UnitMover> ().ResetMovement ();

        movementMode = Unit.MovementMode.Unselected;
    }
 /// <summary>
 /// Handle robot hit event.
 /// Use anti-gravity movement to move away from the hit robot
 /// </summary>
 /// <param name="evnt"></param>
 /// <inheritdoc/>
 public override void OnHitRobot(HitRobotEvent evnt)
 {
     this.currentMovementMode = MovementMode.AntiGravity;
     this.collisionTime = evnt.Time;
 }
예제 #33
0
 public void MoveTo(Vector2 point, MovementMode mode = MovementMode.EnterDestination)
 {
     MovementEngine.MoveTo(point, mode);
 }
 /// <summary>
 /// Handle wall hit event.
 /// Use radius sampling movement to ensure the next move position will move the robot away from the wall
 /// </summary>
 /// <param name="evnt"></param>
 /// <inheritdoc/>
 public override void OnHitWall(HitWallEvent evnt)
 {
     this.currentMovementMode = MovementMode.RadiusSampling;
     this.collisionTime = evnt.Time;
 }
        /// <summary>
        /// Computes per-frame information necessary for the constraint.
        /// </summary>
        /// <param name="dt">Time step duration.</param>
        public override void Update(float dt)
        {
            //Collect references, pick the mode, and configure the coefficients to be used by the solver.
            bool isTryingToMove = movementDirection.LengthSquared() > 0;
            if (supportData.SupportObject != null)
            {
                if (supportData.HasTraction)
                {
                    MovementMode = MovementMode.Traction;
                    if (character.StanceManager.CurrentStance == Stance.Standing)
                        maxSpeed = speed;
                    else
                        maxSpeed = crouchingSpeed;
                    maxForce = maximumForce;
                }
                else
                {
                    MovementMode = MovementMode.Sliding;
                    maxSpeed = slidingSpeed;
                    maxForce = maximumSlidingForce;
                }
            }
            else
            {
                MovementMode = MovementMode.Floating;
                maxSpeed = airSpeed;
                maxForce = maximumAirForce;
                supportEntity = null;
            }
            if (!isTryingToMove)
                maxSpeed = 0;

            maxForce *= dt;



            //Compute the jacobians.  This is basically a PointOnLineJoint with motorized degrees of freedom.
            Vector3 downDirection = character.Body.OrientationMatrix.Down;

            if (MovementMode != MovementMode.Floating)
            {
                //Compute the linear jacobians first.
                if (isTryingToMove)
                {
                    Vector3 velocityDirection;
                    Vector3 offVelocityDirection;
                    //Project the movement direction onto the support plane defined by the support normal.
                    //This projection is NOT along the support normal to the plane; that would cause the character to veer off course when moving on slopes.
                    //Instead, project along the sweep direction to the plane.
                    //For a 6DOF character controller, the lineStart would be different; it must be perpendicular to the local up.
                    Vector3 lineStart = new Vector3(movementDirection.X, 0, movementDirection.Y);
                    Vector3 lineEnd;
                    Vector3.Add(ref lineStart, ref downDirection, out lineEnd);
                    Plane plane = new Plane(character.SupportFinder.HasTraction ? supportData.Normal : supportData.Normal, 0);
                    float t;
                    //This method can return false when the line is parallel to the plane, but previous tests and the slope limit guarantee that it won't happen.
                    Toolbox.GetLinePlaneIntersection(ref lineStart, ref lineEnd, ref plane, out t, out velocityDirection);

                    //The origin->intersection line direction defines the horizontal velocity direction in 3d space.
                    velocityDirection.Normalize();


                    //The normal and velocity direction are perpendicular and normal, so the off velocity direction doesn't need to be normalized.
                    Vector3.Cross(ref velocityDirection, ref supportData.Normal, out offVelocityDirection);

                    linearJacobianA1 = velocityDirection;
                    linearJacobianA2 = offVelocityDirection;
                    linearJacobianB1 = -velocityDirection;
                    linearJacobianB2 = -offVelocityDirection;

                }
                else
                {
                    Vector3 previousLinearJacobianA1 = linearJacobianA1;
                    Vector3 previousLinearJacobianA2 = linearJacobianA2;
                    //If the character isn't trying to move, then the velocity directions are not well defined.
                    //Instead, pick two arbitrary vectors on the support plane.
                    //First guess will be based on the previous jacobian.
                    //Project the old linear jacobian onto the support normal plane.
                    float dot;
                    Vector3.Dot(ref linearJacobianA1, ref supportData.Normal, out dot);
                    Vector3 toRemove;
                    Vector3.Multiply(ref supportData.Normal, dot, out toRemove);
                    Vector3.Subtract(ref linearJacobianA1, ref toRemove, out linearJacobianA1);

                    //Vector3.Cross(ref linearJacobianA2, ref supportData.Normal, out linearJacobianA1);
                    float length = linearJacobianA1.LengthSquared();
                    if (length < Toolbox.Epsilon)
                    {
                        //First guess failed.  Try the right vector.
                        Vector3.Cross(ref Toolbox.RightVector, ref supportData.Normal, out linearJacobianA1);
                        length = linearJacobianA1.LengthSquared();
                        if (length < Toolbox.Epsilon)
                        {
                            //Okay that failed too! try the forward vector.
                            Vector3.Cross(ref Toolbox.ForwardVector, ref supportData.Normal, out linearJacobianA1);
                            length = linearJacobianA1.LengthSquared();
                            //Unless something really weird is happening, we do not need to test any more axes.
                        }

                    }
                    Vector3.Divide(ref linearJacobianA1, (float)Math.Sqrt(length), out linearJacobianA1);
                    //Pick another perpendicular vector.  Don't need to normalize it since the normal and A1 are already normalized and perpendicular.
                    Vector3.Cross(ref linearJacobianA1, ref supportData.Normal, out linearJacobianA2);

                    //B's linear jacobians are just -A's.
                    linearJacobianB1 = -linearJacobianA1;
                    linearJacobianB2 = -linearJacobianA2;

                }

                if (supportEntity != null)
                {
                    //Compute the angular jacobians.
                    Vector3 supportToContact = supportData.Position - supportEntity.Position;
                    //Since we treat the character to have infinite inertia, we're only concerned with the support's angular jacobians.
                    //Note the order of the cross product- it is reversed to negate the result.
                    Vector3.Cross(ref linearJacobianA1, ref supportToContact, out angularJacobianB1);
                    Vector3.Cross(ref linearJacobianA2, ref supportToContact, out angularJacobianB2);

                }
                else
                {
                    //If we're not standing on an entity, there are no angular jacobians.
                    angularJacobianB1 = new Vector3();
                    angularJacobianB2 = new Vector3();
                }
            }
            else
            {
                Vector3 previousLinearJacobianA1 = linearJacobianA1;
                Vector3 previousLinearJacobianA2 = linearJacobianA2;

                //If the character is floating, then the jacobians are simply the movement direction.
                //Note that in a 6DOF character, this will change- but it will still be trivial.
                //In that case, the movement direction will be a 3d vector, and the A2 jacobian will just be
                //linearJacobianA1 x downDirection.
                linearJacobianA1 = new Vector3(movementDirection.X, 0, movementDirection.Y);
                linearJacobianA2 = new Vector3(movementDirection.Y, 0, -movementDirection.X);


            }


            //Compute the target velocity (in constraint space) for this frame.  The hard work has already been done.
            targetVelocity.X = maxSpeed;
            targetVelocity.Y = 0;

            //Compute the effective mass matrix.
            if (supportEntity != null && supportEntity.IsDynamic)
            {
                float m11, m22, m1221 = 0;
                float inverseMass;
                Vector3 intermediate;

                inverseMass = character.Body.InverseMass;
                m11 = inverseMass;
                m22 = inverseMass;


                //Scale the inertia and mass of the support.  This will make the solver view the object as 'heavier' with respect to horizontal motion.
                Matrix3X3 inertiaInverse = supportEntity.InertiaTensorInverse;
                Matrix3X3.Multiply(ref inertiaInverse, supportForceFactor, out inertiaInverse);
                float extra;
                inverseMass = supportForceFactor * supportEntity.InverseMass;
                Matrix3X3.Transform(ref angularJacobianB1, ref inertiaInverse, out intermediate);
                Vector3.Dot(ref intermediate, ref angularJacobianB1, out extra);
                m11 += inverseMass + extra;
                Vector3.Dot(ref intermediate, ref angularJacobianB2, out extra);
                m1221 += extra;
                Matrix3X3.Transform(ref angularJacobianB2, ref inertiaInverse, out intermediate);
                Vector3.Dot(ref intermediate, ref angularJacobianB2, out extra);
                m22 += inverseMass + extra;


                massMatrix.M11 = m11;
                massMatrix.M12 = m1221;
                massMatrix.M21 = m1221;
                massMatrix.M22 = m22;
                Matrix2X2.Invert(ref massMatrix, out massMatrix);


            }
            else
            {
                //If we're not standing on a dynamic entity, then the mass matrix is defined entirely by the character.
                Matrix2X2.CreateScale(character.Body.Mass, out massMatrix);
            }

            //If we're trying to stand still on an object that's moving, use a position correction term to keep the character
            //from drifting due to accelerations. 
            //First thing to do is to check to see if we're moving into a traction/trying to stand still state from a 
            //non-traction || trying to move state.  Either that, or we've switched supports and need to update the offset.
            if (supportEntity != null && ((wasTryingToMove && !isTryingToMove) || (!hadTraction && supportData.HasTraction) || supportEntity != previousSupportEntity))
            {
                //We're transitioning into a new 'use position correction' state.
                //Force a recomputation of the local offset.
                //The time since transition is used as a flag.
                timeSinceTransition = 0;
            }

            //The state is now up to date.  Compute an error and velocity bias, if needed.
            if (!isTryingToMove && supportData.HasTraction && supportEntity != null)
            {
                if (timeSinceTransition >= 0 && timeSinceTransition < tractionDecelerationTime)
                    timeSinceTransition += dt;
                if (timeSinceTransition >= tractionDecelerationTime)
                {
                    Vector3.Multiply(ref downDirection, character.Body.Height * .5f, out positionLocalOffset);
                    positionLocalOffset = (positionLocalOffset + character.Body.Position) - supportEntity.Position;
                    positionLocalOffset = Matrix3X3.TransformTranspose(positionLocalOffset, supportEntity.OrientationMatrix);
                    timeSinceTransition = -1; //Negative 1 means that the offset has been computed.
                }
                if (timeSinceTransition < 0)
                {
                    Vector3 targetPosition;
                    Vector3.Multiply(ref downDirection, character.Body.Height * .5f, out targetPosition);
                    targetPosition += character.Body.Position;
                    Vector3 worldSupportLocation = Matrix3X3.Transform(positionLocalOffset, supportEntity.OrientationMatrix) + supportEntity.Position;
                    Vector3 error;
                    Vector3.Subtract(ref targetPosition, ref worldSupportLocation, out error);
                    //If the error is too large, then recompute the offset.  We don't want the character rubber banding around.
                    if (error.LengthSquared() > .15f * .15f)
                    {
                        Vector3.Multiply(ref downDirection, character.Body.Height * .5f, out positionLocalOffset);
                        positionLocalOffset = (positionLocalOffset + character.Body.Position) - supportEntity.Position;
                        positionLocalOffset = Matrix3X3.TransformTranspose(positionLocalOffset, supportEntity.OrientationMatrix);
                        positionCorrectionBias = new Vector2();
                    }
                    else
                    {
                        //The error in world space is now available.  We can't use this error to directly create a velocity bias, though.
                        //It needs to be transformed into constraint space where the constraint operates.
                        //Use the jacobians!
                        Vector3.Dot(ref error, ref linearJacobianA1, out positionCorrectionBias.X);
                        Vector3.Dot(ref error, ref linearJacobianA2, out positionCorrectionBias.Y);
                        //Scale the error so that a portion of the error is resolved each frame.
                        Vector2.Multiply(ref positionCorrectionBias, .2f / dt, out positionCorrectionBias);
                    }
                }
            }
            else
            {
                timeSinceTransition = 0;
                positionCorrectionBias = new Vector2();
            }

            wasTryingToMove = isTryingToMove;
            hadTraction = supportData.HasTraction;
            previousSupportEntity = supportEntity;

        }
        /// <summary>
        /// The main method in every robot. You must override this to set up your
        /// robot's basic behavior.
        /// Contains the main loop.
        /// </summary>
        public override void Run()
        {
            try
            {
                PaintJob();

                this.IsAdjustGunForRobotTurn = true;
                this.IsAdjustRadarForRobotTurn = true;
                this.IsAdjustRadarForGunTurn = true;

                this.SetTurnRadarRightRadians(double.PositiveInfinity);

                // reset private variables
                this.previousAngle = 0;
                this.collisionTime = 0;
                this.currentMovementMode = MovementMode.AntiGravity;

                this.enemyBullets = new List<WaveBullet>();

                do
                {
                    // wait to gather enemy statistics before taking action
                    if (this.Time > 9)
                    {
                        Action();
                    }

                    Execute();
                } while (true);
            }
            catch (Exception e)
            {
                // for handling random exceptions that had sometimes occured at the end of round
            }
        }
예제 #37
0
 public void MoveTo(Vector2 point, MovementMode mode = MovementMode.EnterDestination)
 {
     if (PathFinding.Destination != point)
     {
         Stop();
         MovementMode = mode;
         PathFinding.Player = position;
         PathFinding.Destination = point;
         PathFinding.Restart();
     }
 }
예제 #38
0
 /// <summary>
 /// Assign a given power level to a motor on the virtual robot.
 /// This allows components of your robot other than the drivebase to move.
 /// This method is designed for moving parts that do not have an actual simulated motor.
 /// One example of such a part is a linear slider.
 /// This method simulates motor power by directly adding a force to the given component, or GameObject.
 /// As a result, you must specify a movement type. This tells the program what
 /// direction the component will be moving in and whether the motion is linear or rotational.
 /// There are 3 available movement types for linear motion:
 /// <para>LINEAR_VERTICAL: Straight up and down.</para>
 /// <para>LINEAR_HORIZONTAL: Straight forward and backward.</para>
 /// <para>LINEAR_SIDEWAYS: Straight left and right.</para>
 /// For compatibility reasons, this method also enables angular motion for arms. However, this method
 /// of angular motion is obsolete and the hinge joint version of setMotor should be used instead. For
 /// compatibility, the following angulat movement types are allowed:
 /// <para>DIRECT_VERTICAL: Rotational, up and down, facing forward (or backward). Perfect for arms.</para>
 /// <para>DIRECT_HORIZONTAL: Rotational, side to side. Perfect for claws.</para>
 /// <para>DIRECT_SIDEWAYS: Rotational, up and down, facing left or right.</para>
 /// All directions are relative to the robot. The default direction is DIRECT_VERTICAL.
 /// </summary>
 /// <param name="motor">Which motor to apply this to</param>
 /// <param name="powerLevel">The power to supply to this motor</param>
 /// <param name="applyMode">The direction this power should be applied in</param>
 public void setMotor(GameObject motor, float powerLevel, MovementMode applyMode = MovementMode.DIRECT_VERTICAL)
 {
     switch (applyMode)
     {
         case MovementMode.DIRECT_VERTICAL:
             motor.rigidbody.AddRelativeTorque(powerLevel, 0, 0);
             break;
         case MovementMode.DIRECT_HORIZONTAL:
             motor.rigidbody.AddRelativeTorque(0, powerLevel, 0);
             break;
         case MovementMode.DIRECT_SIDEWAYS:
             motor.rigidbody.AddRelativeTorque(0, 0, powerLevel);
             break;
         case MovementMode.LINEAR_VERTICAL:
             motor.transform.Translate(0, 0, powerLevel);
             break;
         case MovementMode.LINEAR_HORIZONTAL:
             motor.transform.Translate(0, powerLevel, 0);
             break;
         case MovementMode.LINEAR_SIDEWAYS:
             motor.transform.Translate(powerLevel, 0, 0);
             break;
         default:
             break;
     }
 }