Example #1
0
    // Use this for initialization
    void Start()
    {
        Init();

        state = new MoveState(this);
        PolarCoordinates.RotateAngles(sprite.gameObject.transform, baseParameter.moveParameter.direction);
    }
	public override Vector3 MoveToTargetLateralPos(Transform xform, Vector3 target, Vector3 eTarget, FlyingDroneScript scr)
	{
        if (mvState == MoveState.turn)
        {
		    // Calculate the new rotation.
		    float dot   = GeometryClass.DotToTarget2D(xform, target);
            if (dot < scr.dotTolerance)
            {
                // Calculate the new rotation.
                Vector3 angles = xform.localEulerAngles;
                float yAngle = angles.y;
                Transform tempXform = xform;
                tempXform.LookAt(target);
                float yAngleTarget = tempXform.localEulerAngles.y;
                scr.journeyFracRotate += scr.journeyDeltaRotate;
                float yAngleChanged = Mathf.LerpAngle(yAngle, yAngleTarget, GeometryClass.MapToCurve(scr.journeyFracRotate));
                angles.y = yAngleChanged;
                xform.localEulerAngles = angles;
                
            }
            else
            {
                mvState = MoveState.move;
                scr.ResetJourney();
            }
		} else { // mvState == MoveState.move
			// Calculate new position only if rotation is already correct.
            scr.journeyFracHoriz += scr.journeyDeltaHoriz;
            Vector3 newPos = Vector3.Lerp(xform.transform.position, eTarget, GeometryClass.MapToCurve(scr.journeyFracHoriz));
            xform.position = newPos;
		}
		return xform.position;
	}
Example #3
0
    private void InitialzeStateManager()
    {
        _stateManager = new StateManager(_muffinAnimator);

        IdleState 		idle = new IdleState(_stateManager, transform);
        MoveState 		move = new MoveState(_stateManager, transform);
        TrapState 		trap = new TrapState(_stateManager, transform);
        DieState 		die	= new DieState(_stateManager, transform);
        SpinState		spin = new SpinState(_stateManager, transform);
        BlastState		blast = new BlastState(_stateManager, transform);
        ChocoRushState	chocoRush = new ChocoRushState(_stateManager, transform);

        PauseState		pause = new PauseState(_stateManager, transform);

        _stateManager.AddCharacterState(idle);
        _stateManager.AddCharacterState(move);
        _stateManager.AddCharacterState(trap);
        _stateManager.AddCharacterState(die);
        _stateManager.AddCharacterState(spin);
        _stateManager.AddCharacterState(blast);
        _stateManager.AddCharacterState(chocoRush);

        _stateManager.AddCharacterState(pause);

        _stateManager.SetDefaultState("Pause");
    }
Example #4
0
 // Use this for initialization
 void Start()
 {
     moveState = GetComponent<MoveState>();
     booster = GetComponent<Booster>();
     neutral = GetComponent<Neutral>();
     rigidbody = GetComponent<Rigidbody>();
     rigidbody.velocity = Vector3.forward * 1.0f;
 }
Example #5
0
 void Start()
 {
     rigidbody = GetComponent<Rigidbody>();
     playerRigidbody = GameObject.Find("Player").GetComponent<Rigidbody>();
     playerMoveState = GetComponentInParent<MoveState>();
     sqrLongDistance = longDistance * longDistance;
     sqrShortDistance = shortDistance * shortDistance;
 }
Example #6
0
    // Use this for initialization
    void Start()
    {
        attackParameter.damage = new Damage(30, false, 10, parent.frontDirection, false);
        baseParameter.moveParameter = new MoveParameter(parent.frontDirection, 5F);

        state = new MoveState(this);
        PolarCoordinates.RotateAngles(sprite.gameObject.transform, baseParameter.moveParameter.direction);
    }
Example #7
0
    /// <summary>
    /// �����������
    /// </summary>
    /// <param name="dir"></param>
    public virtual void Put(int dir,float power)
    {
        //�ړ���ԂɑJ��
        baseParameter.moveParameter = new MoveParameter(dir, power);
        state = new MoveState(this);

        SoundManager.Play(SoundManager.attackLight);
    }
Example #8
0
    // Use this for initialization
    void Start()
    {
        player = GameObject.FindGameObjectWithTag ("Player").transform;
        moveState = MoveState.Idle;
        idling = false;

        base.Prepare ();
    }
    void MoveDown()
    {
        LTDescr moveDownTween = LeanTween.moveY(this.gameObject,
                                originalPosition.y,
                                0.5f);
        moveDownTween.setOnStart(MoveToOriginalPosStarted);

        moveState = MoveState.Original;
    }
Example #10
0
 public void Stop()
 {
     if (State != MoveState.Stop)
     {
         State = MoveState.Stop;
         //StopAllCoroutines();
         Agent.Stop();
         ObjectAnimator.SetTrigger("Stop");
     }
 }
Example #11
0
	void Awake() {
		mat = GetComponent<Renderer>().material;

		idleState = new IdleState(this);
		moveState = new MoveState(this);
		talkState = new TalkState(this);
		loveState = new LoveState(this);

		currentState = moveState;
	}
Example #12
0
 public void SetMoveState(string state)
 {
     switch (state) {
         case "Idle":
             moveState = MoveState.Idle;
             break;
         case "Wander":
             moveState = MoveState.Wander;
             break;
         case "Follow":
             moveState = MoveState.Follow;
             break;
     }
 }
    void Update()
    {
        //set animation speed based on navAgent 'Speed' var
        animController.speed = navAgent.speed;

        //character walks if there is a navigation path set, idle all other times
        if (navAgent.hasPath)
            moveState = MoveState.Walking;
        else
            moveState = MoveState.Idle;

        //send move state info to animator controller
        animController.SetInteger("MoveState", (int)moveState);
    }
Example #14
0
    //wait for a random time, then change the waypoint
    IEnumerator DoIdleStuffs()
    {
        idling = true;
            //random values between -5 and 5
            movex = Random.value * Random.Range(-1, 2) * 3;
            movey = Random.value * Random.Range(-1, 2) * 3;

        //	Debug.Log (movex + ": " + movey);
            float timev = (Random.value + 2.0f) * 2.0f;
            yield return new WaitForSeconds (timev);
            waypoint = new Vector3 (transform.position.x + movex, transform.position.y + movey, transform.position.z);

            moveState = MoveState.Wander;
    }
Example #15
0
	// Update is called once per frame
	void Update () {
	 //Check for collision and if the colliding object's layer is of type "Shape"



    //Check for Horizontal movement
    if(Input.GetKey (KeyCode.LeftArrow))
      playerMove = MoveState.Left;
    else if(Input.GetKey (KeyCode.RightArrow))
      playerMove = MoveState.Right;
    else
      playerMove = MoveState.None;
    //check for vertical movement and if you are grounded



	}
Example #16
0
    // Use this for initialization
    void Start()
    {
        TargetSearch();

        baseParameter.moveParameter = new MoveParameter(parent.frontDirection, 5F);

        if (target == null) { state = new MoveState(this); }
        else
        {
            HomingState.Options ops = new HomingState.Options
            {
                level = HomingState.HOMINGLEVEL.Middole,
                time = 180,
                interval = 2
            };
            state = new HomingState(this, target.transform, ops);

        }
        attackParameter.damage = new Damage(30, false, 20, parent.frontDirection, false);
    }
	// Update is called once per frame
	void Update () 
	{
		switch( m_State )
		{
		case MoveState.UnActive :
			if( Time.timeSinceLevelLoad > m_StartTime )
			{
				m_State = MoveState.FindNextWayPoint ;
			}
			break ;
		case MoveState.FindNextWayPoint :
			FindNextWayPoint() ;
			break ;
		case MoveState.KeepMoving :
			KeepMoving() ;
			break ;
		case MoveState.End :
			// Component.Destroy( this ) ;
			break ;			
		}
	}
Example #18
0
    void Update()
    {
        speed = (Mathf.Clamp (((agent.remainingDistance / 4.0f) + 0.0f), 0, 2));
        anim.SetFloat ("MoveSpeed", speed);

        //Debug.Log (speed);

        //set animation speed based on navAgent 'Speed' var
        animController.speed = navAgent.speed;

        //character walks if there is a navigation path longer than the value set here, idle all other times
        if (navAgent.remainingDistance > 1.0f) {
            moveState = MoveState.Walking;
        }

        else
            moveState = MoveState.Idle;

        //send move state info to animator controller
        animController.SetInteger("MoveState", (int)moveState);
    }
Example #19
0
    // Update is called once per frame
    void Update () {
        //character walks if there is a navigation path set, idle all other times
        if (navAgent.hasPath){
            moveState = MoveState.Walking;
            animController.CrossFade("Walking", 0f);
        }

        else {
            moveState = MoveState.Idle;
            animController.CrossFade("Idle", 0f);
        }
        
        //send move state info to animator controller
        animController.SetInteger("MoveState", (int)moveState);

        //If the target is within a short distance, a new target point is assigned
        if (Vector3.Distance(transform.position, target) < 2){
            initPoints();
            target = points[Random.Range(0, points.Length)];
            navAgent.SetDestination(target);
        }
    }
Example #20
0
    void Update()
    {
        //movement
        switch (mMoveState)
        {
        case MoveState.Normal:
            mMoveHorz = moveHorzInput.GetAxis();

            //check if we are sticking to side
            if (!bodyControl.isGrounded && (bodyControl.collisionFlags & CollisionFlags.Sides) != CollisionFlags.None && mJumpState == JumpState.None)
            {
                if (bodyControl.sideFlags == M8.RigidBodyController2D.SideFlags.Left && mMoveHorz < 0f || bodyControl.sideFlags == M8.RigidBodyController2D.SideFlags.Right && mMoveHorz > 0f)
                {
                    mMoveState = MoveState.SideStick;
                }
            }
            break;

        case MoveState.SideStick:
            if (bodyControl.isGrounded)      //revert right away if grounded
            {
                mMoveState = MoveState.Normal;
                mMoveHorz  = moveHorzInput.GetAxis();
            }
            else if ((bodyControl.collisionFlags & CollisionFlags.Sides) == CollisionFlags.None)
            {
                //delay a bit (avoids stutter with uneven wall)
                if (mMoveSideCurTime < moveSideDelay)
                {
                    mMoveSideCurTime += Time.deltaTime;
                }
                else
                {
                    mMoveState = MoveState.Normal;
                    mMoveHorz  = moveHorzInput.GetAxis();
                }
            }
            else
            {
                var inpHorz = moveHorzInput.GetAxis();
                if (bodyControl.sideFlags == M8.RigidBodyController2D.SideFlags.Left && inpHorz < 0f || bodyControl.sideFlags == M8.RigidBodyController2D.SideFlags.Right && inpHorz > 0f)
                {
                    mMoveSideCurTime = 0f;     //reset delay
                }
                else if (mMoveSideCurTime < moveSideDelay)
                {
                    mMoveSideCurTime += Time.deltaTime;
                }
                else
                {
                    mMoveState = MoveState.Normal;
                    mMoveHorz  = moveHorzInput.GetAxis();
                }
            }
            break;
        }

        //determine if we can jump
        if (bodyControl.isGrounded)
        {
            canJump         = jumpEnabled;
            mLastGroundTime = Time.time;
        }
        else if (jumpEnabled)
        {
            //check if we are on contact of a side
            //determine actDir
            if (Time.time - mLastGroundTime <= jumpLastGroundDelay)
            {
                canJump = true;
            }
            else
            {
                canJump = mMoveState == MoveState.SideStick;// (bodyControl.collisionFlags & CollisionFlags.CollidedSides) != CollisionFlags.None;
            }
        }

        //act or jump
        var actState = actInput.GetButtonState();

        if (actState == M8.InputAction.ButtonState.Pressed)
        {
            bool isAct = false;
            for (int i = 0; i < mActionCallbacks.Count; i++)
            {
                if (mActionCallbacks[i]())
                {
                    isAct = true;
                }
            }

            if (!isAct && canJump && mJumpState == JumpState.None)
            {
                mMoveState = MoveState.Normal;
                mJumpState = JumpState.JumpStart;
            }
        }
    }
Example #21
0
 private void MoveStateManagerOnStateUpdated(MoveState obj)
 {
     _state = obj;
 }
 public void OnStageStart()
 {
     moveDistance = 0.0f;
     state        = MoveState.Normal;
 }
Example #23
0
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.LeftArrow))         //左
        {
            agent.Move(Vector3.left * speed.z);
        }
        else if (Input.GetKey(KeyCode.UpArrow))
        {
            agent.Move(Vector3.back * speed.z);
        }
        else if (Input.GetKey(KeyCode.DownArrow))
        {
            agent.Move(Vector3.forward * speed.z);
        }
        else if (Input.GetKey(KeyCode.RightArrow))          //下
        {
            agent.Move(Vector3.right * speed.z);
        }
        else if (Input.GetKey(KeyCode.C))
        {
        }

        Vector3?dest = null;

        //传送过程中不能操作
        if ((moveState & MoveState.Teleport) == MoveState.NONE)
        {
            if (Input.GetKey(KeyCode.D))      //右
            {
                moveDir = -1;                 //右边
                interTrans.eulerAngles = new Vector3(0, 270, 0);
                int idx = -1;
                if ((idx = CheckTrigger(false, TeleportType.DownRight)) >= 0)                 //传送到其他地方
                {
                    moveState           |= MoveState.Teleport;
                    moveState           &= ~MoveState.Normal;
                    agent.updatePosition = false;
                    lastTrigger          = teleports[idx];

                    teleportStartPos  = transform.position;
                    teleportDest      = lastTrigger.worldDestPos;
                    teleportDest.x   += modelSize.x / 2 * moveDir;
                    totalTeleportTime = Mathf.Sqrt(Mathf.Abs(teleportDest.y - transform.position.y) * 2 / gravity); //总时间
                    curTeleportTime   = 0f;
                    teleportVel       = new Vector3(moveDir * agent.speed, 0f, 0f);                                 // (teleportDest - teleportStartPos + 0.5f * new Vector3(0f, gravity, 0f)  * teleportTime * teleportTime) / teleportTime;
                }
                else
                {
                    moveState |= MoveState.Normal;
                    dest       = agent.transform.position + Vector3.left * speed.z;              //
                }
            }
            else if (Input.GetKey(KeyCode.W))
            {
                moveState |= MoveState.Normal;
                dest       = agent.transform.position + Vector3.back * speed.z;
            }
            else if (Input.GetKey(KeyCode.S))
            {
                moveState |= MoveState.Normal;
                dest       = agent.transform.position + Vector3.forward * speed.z;
            }
            else if (Input.GetKey(KeyCode.A))              //左
            {
                interTrans.eulerAngles = new Vector3(0, 90, 0);
                moveDir = 1;
                int idx = -1;
                if ((idx = CheckTrigger(false, TeleportType.DownLeft)) >= 0)                 //传送到其他地方
                {
                    moveState           |= MoveState.Teleport;
                    moveState           &= ~MoveState.Normal;
                    agent.updatePosition = false;
                    lastTrigger          = teleports[idx];

                    teleportStartPos  = transform.position;
                    teleportDest      = lastTrigger.worldDestPos;
                    teleportDest.x   += modelSize.x / 2 * moveDir;
                    totalTeleportTime = Mathf.Sqrt(Mathf.Abs(teleportDest.y - transform.position.y) * 2 / gravity);                 //总时间
                    curTeleportTime   = 0f;
                    teleportVel       = new Vector3(moveDir * agent.speed, 0f, 0f);
                }
                else
                {
                    moveState |= MoveState.Normal;
                    dest       = agent.transform.position + Vector3.right * speed.z;
                }
            }
            else               //没有一般移动
            {
                moveState &= ~MoveState.Normal;
            }

            //可以同时按下方向键和空格键
            if (Input.GetKey(KeyCode.Space))             //跳跃
            {
                if (jumpTime == 0f)
                {
                    jumpTime = 0f;
                }
                moveState |= MoveState.Jump;

                int idx = -1;
                if ((idx = CheckTrigger(false, moveDir == -1 ? TeleportType.JumpRight : TeleportType.JumpLeft)) >= 0)                 //传送到其他地方
                {
                    moveState           |= MoveState.Teleport;
                    moveState           &= ~MoveState.Normal;
                    agent.updatePosition = false;
                    lastTrigger          = teleports[idx];

                    teleportStartPos = transform.position;
                    teleportDest     = lastTrigger.worldDestPos;
                    float y = 0f;
                    if (lastTrigger.type == TeleportType.UpLeft || lastTrigger.type == TeleportType.UpRight) //向上跳需要更大的加速度
                    {
                        y                 = teleportDest.y - transform.position.y;                           // + 1f;
                        teleportVel       = new Vector3(agent.speed * moveDir, gravity * Mathf.Sqrt(2 * y / gravity), 0f);
                        totalTeleportTime = Mathf.Sqrt(2 * y / gravity);                                     // + Mathf.Sqrt(2/gravity);
                    }
                    else
                    {
                        teleportVel       = new Vector3(agent.speed * moveDir, jumpVel, 0f);
                        y                 = transform.position.y - teleportDest.y;
                        totalTeleportTime = jumpVel / gravity + Mathf.Sqrt(2 * (0.5f * jumpVel * jumpVel / gravity + transform.position.y - teleportDest.y) / gravity);
                    }
                    curTeleportTime = 0f;
                }
            }
        }

        if ((moveState & MoveState.Teleport) != MoveState.NONE)         //传送状态
        {
            if (curTeleportTime < totalTeleportTime)
            {
                curTeleportTime         += Time.deltaTime;
                transform.position       = CalcTeleportPos(curTeleportTime);
                interTrans.localPosition = Vector3.zero;
            }
            else
            {
                var tmp = transform.position;
                tmp.y = teleportDest.y;
                agent.Warp(tmp);
                agent.updatePosition = true;
                moveState           &= ~MoveState.Teleport;
                moveState           &= ~MoveState.Jump;

                totalTeleportTime = 0f;
                curTeleportTime   = -1f;
                lastTrigger       = null;
                animContrller.SetInteger("aniState", (int)PlayerAnimationNames.IDLE1);
            }
        }
        else
        {
            if ((moveState & MoveState.Normal) != MoveState.NONE)             //一般的移动
            {
                if (dest != null)
                {
                    agent.SetDestination(dest.Value);
                }
            }
            else
            {
                agent.Warp(transform.position);                 //停到当前的位置
            }

            if ((moveState & MoveState.Jump) != MoveState.NONE)             //跳跃状态
            {
                var y = jumpVel * jumpTime - 0.5f * gravity * jumpTime * jumpTime;
                jumpTime += Time.deltaTime;
                if (jumpTime > 0.1f && y < 0f)
                {
                    moveState &= ~MoveState.Jump;
                    y          = 0f;
                    jumpTime   = 0f;
                }
                interTrans.localPosition = new Vector3(0, y, 0);
            }
        }

        //动作的处理部分
        if ((moveState & MoveState.Jump) != MoveState.NONE)
        {
            animContrller.SetInteger("aniState", (int)PlayerAnimationNames.JUMP);
        }
        else if ((moveState & MoveState.Normal) != MoveState.NONE)
        {
            animContrller.SetInteger("aniState", (int)PlayerAnimationNames.RUN);
        }
        else
        {
            animContrller.SetInteger("aniState", (int)PlayerAnimationNames.IDLE1);
        }

        if (Input.mouseScrollDelta.y != 0f)
        {
            scrollDelta += Input.mouseScrollDelta.y;
            z           += Input.mouseScrollDelta.y;
            z            = Mathf.Max(z, minZ);
            z            = Mathf.Min(z, maxZ);
        }


        var temp = character.position;

        temp.z = z;

        cam.transform.position = temp;
    }
Example #24
0
        public MoveDirection Move(MoveState state)
        {
            // Наша змея
            Snake mainSnake = state.Snakes.Single(x => x.Id == state.You);
            // Противники
            IEnumerable <Snake> enemies = state.Snakes.Where(x => x.Id != state.You);

            // информация о карте
            MapInformation.map    = new int[state.Width, state.Height];
            MapInformation.height = state.Height;
            MapInformation.width  = state.Width;

            // Заполняем карту служебной имнформацией
            for (int i = 0; i < state.Width; ++i)
            {
                for (int j = 0; j < state.Height; ++j)
                {
                    MapInformation.map[i, j] = -1;
                }
            }

            // заполняем карту препятствиями
            foreach (var enemy in enemies)
            {
                foreach (var cell in enemy.Coords)
                {
                    MapInformation.map[cell.X, cell.Y] = MapInformation.barrier;
                }

                if (enemy.Coords.Length >= mainSnake.Coords.Length)
                {
                    int x = 0;
                    int y = 0;

                    // Змеи находятся напротив друг друга вертикально
                    if (Math.Abs(enemy.HeadPosition.X - mainSnake.HeadPosition.X) == 2 && (enemy.HeadPosition.Y - mainSnake.HeadPosition.Y) == 0)
                    {
                        if (enemy.HeadPosition.X > mainSnake.HeadPosition.X)
                        {
                            x = enemy.HeadPosition.X - 1;
                        }
                        else
                        {
                            x = enemy.HeadPosition.X + 1;
                        }

                        y = enemy.HeadPosition.Y;

                        MapInformation.map[x, y] = MapInformation.barrier;
                    }

                    // Змеи находятся напротив друг друга горизонтально
                    if ((enemy.HeadPosition.X - mainSnake.HeadPosition.X) == 0 && Math.Abs(enemy.HeadPosition.Y - mainSnake.HeadPosition.Y) == 2)
                    {
                        if (enemy.HeadPosition.Y > mainSnake.HeadPosition.Y)
                        {
                            y = enemy.HeadPosition.Y - 1;
                        }
                        else
                        {
                            y = enemy.HeadPosition.Y + 1;
                        }

                        x = enemy.HeadPosition.X;

                        MapInformation.map[x, y] = MapInformation.barrier;
                    }

                    // Змеи находятся в друг от друга по диагонали, но в одном шаге
                    if (Math.Abs(enemy.HeadPosition.X - mainSnake.HeadPosition.X) == 1 && Math.Abs(enemy.HeadPosition.Y - mainSnake.HeadPosition.Y) == 1)
                    {
                        MapInformation.map[mainSnake.HeadPosition.X, enemy.HeadPosition.Y] = MapInformation.barrier;
                        MapInformation.map[enemy.HeadPosition.X, mainSnake.HeadPosition.Y] = MapInformation.barrier;
                    }
                }
            }

            foreach (var cell in mainSnake.Coords)
            {
                MapInformation.map[cell.X, cell.Y] = MapInformation.barrier;
            }

            // Будем считать голову свободной ячейкой для удобства расчетов
            MapInformation.map[mainSnake.HeadPosition.X, mainSnake.HeadPosition.Y] = -1;

            // Находим путь до каждого фрукта
            List <List <Point> > paths = new List <List <Point> >();

            foreach (var fruit in state.Food)
            {
                var path = FindPath(mainSnake.HeadPosition, fruit, MapInformation.map, state.Width, state.Height);
                // Если нашли путь, добавляем его в список
                if (path.Count > 0)
                {
                    paths.Add(path);
                }
            }

            List <List <Point> > checkedPaths = new List <List <Point> >();

            foreach (var path in paths)
            {
                Point fruit         = path.Last();
                bool  dangerousPath = false;

                if (enemies.Count() > 0)
                {
                    foreach (var enemy in enemies)
                    {
                        // Если вражеская змея в шаге от фрукта
                        if ((Math.Abs(enemy.HeadPosition.X - fruit.X) == 1 && (enemy.HeadPosition.Y - fruit.Y) == 0) ||
                            ((enemy.HeadPosition.X - fruit.X) == 0 && Math.Abs(enemy.HeadPosition.Y - fruit.Y) == 1))
                        {
                            // Если нам идти более чем 1 шаг или вражеская змея большем либо равна нашей, то исключаем этот фрукт из выборки
                            if (enemy.Coords.Length >= mainSnake.Coords.Length)
                            {
                                dangerousPath = true;
                            }
                        }
                    }

                    if (!dangerousPath)
                    {
                        checkedPaths.Add(path);
                    }
                }
                else
                {
                    checkedPaths.Add(path);
                }
            }

            List <Point> pathToNearestFruit = checkedPaths.OrderBy(x => x.Count).FirstOrDefault();

            // Если нашли путь до фрукта
            if (pathToNearestFruit != null)
            {
                // Берем первую ячейку пути, в которую нам и надо шагнуть
                var nextCell = pathToNearestFruit[0];

                int translationX = mainSnake.HeadPosition.X - nextCell.X;
                int translationY = mainSnake.HeadPosition.Y - nextCell.Y;

                if (translationX == 0)
                {
                    if (translationY > 0)
                    {
                        return(new MoveDirection {
                            Move = "up", Taunt = "Moving up"
                        });
                    }
                    else
                    {
                        return(new MoveDirection {
                            Move = "down", Taunt = "Moving down"
                        });
                    }
                }

                if (translationX > 0)
                {
                    return(new MoveDirection {
                        Move = "left", Taunt = "Moving left"
                    });
                }
                else
                {
                    return(new MoveDirection {
                        Move = "right", Taunt = "Moving right"
                    });
                }
            }
            // Если не смогли найти путь до фрукта, то тянем время с помощью движения в сторону самой удаленной доступной ячейки с помощью пути найденного поиском в глубину
            else
            {
                DFSBehavior dfs = new DFSBehavior();

                return(dfs.Move(mainSnake.HeadPosition));
            }
        }
 void StartDeccelerating()
 {
     moveState             = MoveState.Deccelerating;
     deccelerationTimer    = 0;
     maxDeccelerationSpeed = currentSpeed;
 }
Example #26
0
        /// <summary>
        /// Initialization method
        /// </summary>
        public void Init()
        {
            Speed = Util.Rnd.Next(4000, 6200) / 1000000.0f;
            CurrentMove = MoveState.Intro;
            ImageSequence = ImageState.Normal;
            CurrentImage = 0;
            oldTicks = 0;
            CurrentImageSequence = 0;

            //X = 0.0f - Size.Width / 2.0f;
            //Y = -0.5f - Size.Height / 2.0f;
            X = (Util.Rnd.Next(-120, 120) / 100.0f) - (Size.Width / 2.0f); //0.0f - (Size.Width / 2.0f);
            Y = -1.2f - Size.Height;
            Z = 0.45f;
        }
Example #27
0
    public void Move(Vector2 accel, float gravity)
    {
        if (disabled)
        {
            return;
        }

        facingLockTime -= Time.deltaTime;
        KillOnOverlap();

        moveState = MoveState.Normal;

        accel *= speed;
        accel += velocity * friction;

        if (gravity != 0.0f)
        {
            accel.y = gravity;
        }

        // Using the following equations of motion:

        // - p' = 1/2at^2 + vt + p.
        // - v' = at + v.
        // - a = specified by input.

        // Where a = acceleration, v = velocity, and p = position.
        // v' and p' denote new versions, while non-prime denotes old.

        // These are found by integrating up from acceleration to velocity. Use derivation
        // to go from position down to velocity and then down to acceleration to see how
        // we can integrate back up.
        Vector2 delta = accel * 0.5f * Utils.Square(Time.deltaTime) + velocity * Time.deltaTime;

        if (swimming)
        {
            velocity = (accel * 0.35f) * Time.deltaTime + velocity;
        }
        else
        {
            velocity = accel * Time.deltaTime + velocity;
        }

        Vector2 target   = Position + delta;
        AABB    entityBB = GetBoundingBox();

        colFlags = CollideFlags.None;

        // Player size in tiles.
        Vector2Int tSize = Utils.CeilToInt(entityBB.radius * 2.0f);

        Vector2Int start = Utils.TilePos(Position);
        Vector2Int end   = Utils.TilePos(target);

        // Compute the range of tiles we could touch with our movement. We'll test for collisions
        // with the tiles in this range.
        Vector2Int min = new Vector2Int(Mathf.Min(start.x, end.x) - tSize.x, Mathf.Min(start.y, end.y) - tSize.y);
        Vector2Int max = new Vector2Int(Mathf.Max(start.x, end.x) + tSize.x, Mathf.Max(start.y, end.y) + tSize.y);

        // Tile collision checking.
        GetPossibleCollidingTiles(world, entityBB, min, max);

        // Entity collision checking.
        GetPossibleCollidingEntities(world, entityBB, min, max);

        possibleCollides.Sort(collideCompare);

        float tRemaining = 1.0f;

        for (int it = 0; it < 3 && tRemaining > 0.0f; ++it)
        {
            float   tMin   = 1.0f;
            Vector2 normal = Vector2.zero;

            CollideResult hitResult = default;
            bool          hit       = false;

            for (int i = 0; i < possibleCollides.Count; ++i)
            {
                CollideResult info   = possibleCollides[i];
                bool          result = TestTileCollision(world, entityBB, info.bb, delta, ref tMin, ref normal);

                if (result)
                {
                    hitResult = info;
                    hit       = true;
                }
            }

            MoveBy(delta * tMin);

            if (normal != Vector2.zero)
            {
                MoveBy((normal * Epsilon));
            }

            if (hit)
            {
                OnCollide(hitResult);
            }

            entityBB = GetBoundingBox();

            // Subtract away the component of the velocity that collides with the tile wall
            // and leave the remaining velocity intact.
            velocity -= Vector2.Dot(velocity, normal) * normal;
            delta    -= Vector2.Dot(delta, normal) * normal;

            delta      -= (delta * tMin);
            tRemaining -= (tMin * tRemaining);
        }

        possibleCollides.Clear();

        if (overlaps.Count > 0)
        {
            HandleOverlaps(overlaps);
        }

        overlaps.Clear();

        SetFacingDirection();
        Rebase(world);
        ApplyOverTimeDamage();

        if (DebugServices.Instance.ShowDebug)
        {
            GetBoundingBox().Draw(Color.green);
        }
    }
    //=================================================================================================================o
    void FixedUpdate()
    {
        if(speedTimer > 0){
            speedTimer -= Time.deltaTime;
        }
        if(massTimer > 0){
            massTimer -= Time.deltaTime;
        }

        RaycastHit hit;
        grounded = Physics.Raycast (hero.position + hero.up * -groundedOffsetRay,
            hero.up * -1, out hit, groundedDistance, groundLayers);

        //reverts physics to ground physics - sam
        if(speedTimer <= 0){
            if(canMove && grounded){
            rb.drag = groundDrag;
            walkSpeed = speedOrig;
            sideSpeed = speedOrig;
            speed = speedOrig;
            StartCoroutine (JumpCoolDown(0f));
            }
            else{
            rb.drag = airDrag;
            walkSpeed = airSpeed;
            sideSpeed = sideAirSpeed;
            speed = airSpeed;

            }
            }
        else{
            if(canMove && grounded){
            rb.drag = groundDrag;
            walkSpeed = speedOrig * pillMoveMultiplier;
            sideSpeed = speedOrig * pillMoveMultiplier;
            speed = speedOrig * pillMoveMultiplier;
            StartCoroutine (JumpCoolDown(0f));
            }
            else{
            rb.drag = airDrag * pillAirDragMultiplier;
            walkSpeed = airSpeed * pillMoveMultiplier;
            sideSpeed = sideAirSpeed * pillMoveMultiplier;
            speed = airSpeed * pillMoveMultiplier;

        }
        }
        if(massTimer <= 0){
            if(canMove && grounded){
            rb.drag = groundDrag;
            StartCoroutine (JumpCoolDown(0f));
            jumpPower = origJump;
            }
            else{
            rb.drag = airDrag;
            jumpPower = origJump;
            }
        }
        else{
            if(canMove && grounded){
            rb.drag = groundDrag;
            StartCoroutine (JumpCoolDown(0f));
            jumpPower = origJump * pillJumpMultiplier;
            }
            else{
            rb.drag = airDrag * 0;
            jumpPower = origJump * pillJumpMultiplier;
            }
        }

        if (canMove) //&& grounded)//grounded &&
        {

            // If any Double tap
            if (!isDoubleTap)
            {
                // Horizontal / Vertical velocity

                Vector3 curVelocity = Input.GetAxis ("Vertical") * ForwardVec(hit)
                    + Input.GetAxis ("Horizontal") * hero.right;

            if(speedTimer >= 0 ){
                speedTimer -= Time.deltaTime;
                fieldAdd -= Time.deltaTime * 2;
                Camera.main.fieldOfView = origField + fieldAdd;
                    if(Camera.main.fieldOfView <= origField){
                        Camera.main.fieldOfView = origField;
                        }
                    }
                else{
                Camera.main.fieldOfView = origField;
                    }

                //Debug.Log(Input.GetAxis("Vertical"));

                //Debug.Log("curVelocity is " +curVelocity );

                // If not receiving speed via delegate

                if (!getsSpeed)
                {
                    if(Input.GetKeyDown("joystick button 3")){
                            Debug.Log("try to swandive");
                            //animation.Play("swim");

                        }
                    // Jump
        //					if (Input.GetKey (hKey.jumpKey) && canJump && grounded && pillTimer > 0)
        //					{
        //
        //						//grounded = false;
        //						rb.drag = airDrag;
        //						walkSpeed = airSpeed;
        //						sideSpeed = sideAirSpeed;
        //						speed = airSpeed;
        //
        //						rb.AddForce (jumpPower * hero.up +
        //							rb.velocity.normalized /10f, ForceMode.VelocityChange);
        //
        //						// Jump delegate
        //						if (doJumpDel != null) { doJumpDel(); }
        //
        //
        //
        //						// Start cooldown until we can jump again
        //							StartCoroutine (JumpCoolDown(5f));
        //					}

                    if (Input.GetKey (hKey.jumpKey) && canJump && grounded)
                    {

                        //grounded = false;
                        rb.drag = airDrag;
                        walkSpeed = airSpeed;
                        sideSpeed = sideAirSpeed;
                        speed = airSpeed;

                        rb.AddForce (jumpPower * hero.up +
                            rb.velocity.normalized /10f, ForceMode.VelocityChange);

                        // Jump delegate
                        if (doJumpDel != null) { doJumpDel(); }

                        // Start cooldown until we can jump again
                            StartCoroutine (JumpCoolDown(5f));
                    }

                    // Walk, sprint and sneak speed
                    else if (moveState == MoveState.Walking || moveState == MoveState.Sneaking){
                        curSpeed = walkSpeed;
                    }

                    else if (moveState == MoveState.Sprinting) {
                        curSpeed = sprintSpeed;
                    }

                    else{
                        curSpeed = speed;
                    }

                    // Back-Side speed
                    if (Input.GetAxis ("Vertical") < 0.0f)
                    {
                        curSpeed = walkSpeed;
                    }
                    else if (Input.GetAxis ("Horizontal") != 0.0f && moveState == MoveState.Normal)
                            curSpeed = sideSpeed;
                }

                // Apply movement if descent input and not double tab
                if (curVelocity.magnitude > inputThreshold || curVelocity.magnitude < inputThreshold)
                {
                    rb.AddForce (curVelocity.normalized * curSpeed, ForceMode.VelocityChange);

                    // Stop "anti slide" timed trigger
                    if (Input.GetKeyUp (KeyCode.W) && canStopFast)
                    {
                        isAfterStop = false;
                        StartCoroutine (StopCoolDown(0.5f));
                    }
                }

                else // Don't slide if not jumping and not in evade modus
                {
                    if (!Input.GetKey(hKey.jumpKey) && isAfterTap && isAfterStop)
                    {
                        rb.velocity = new Vector3 (0.0f, rb.velocity.y, 0.0f);
                    }
                }

                // Balancing on climb collider, layer 9
                if (moveState != MoveState.Balancing)
                {
                    if (hit.transform && hit.transform.gameObject.layer == 9) // Hit climb-layer collider
                    {
                        if (doBalanceDel != null) { doBalanceDel(true); }
                        moveState = MoveState.Balancing;
                    }
                }
                else // Normal mode
                {
                    if (hit.transform && hit.transform.gameObject.layer != 9) // Hit other-layer collider
                    {
                        if (doBalanceDel != null) { doBalanceDel(false); }
                        // Back to normal
                        moveState = MoveState.Normal;
                    }
                }
            }
            else // Situaltional velocity ( Double tap )
            {
                if (isDoubleTap)
                {
                    rb.AddForce (evadeDir.normalized * 0.7f/*curSpeed*/, ForceMode.VelocityChange);
                }
                else // Don't move horizontal
                {
                    rb.velocity = new Vector3 (0.0f, rb.velocity.y, 0.0f);
                }
            }
            //rb.drag = groundDrag;
            }
        //else //in air
            //rb.drag = airDrag;

        if (!Input.GetButton("Fire1")) // If not shooting, left mouse
        {
            getsSpeed = false; // Is not receiving speed float from HeroAnim --> Back to normal
        }
    }
Example #29
0
        /// <summary>
        /// Starts the game
        /// </summary>
        /// <param name="gameTime">provides a snapshot of the gametime</param>
        public void PlayGame(GameTime gameTime)
        {
            switch (_textDisplayState)
            {
                case TextDisplayState.TextDisplaying:
                    DisplayText(gameTime);
                    break;
            }

            PreviousMoveState = moveState;

            moveState = MoveState;
            if (PreviousMoveState != moveState)
                if (moveState == MoveState.Still)
                    _encounterChecked = false;

            var motion = new Vector2();

            // Get input if the Player is not already moving
            if (MoveState == MoveState.Still)
            {
                // Pause
                if (InputHandler.ActionKeyPressed(ActionKey.Pause, PlayerIndex.One))
                    _gameState = GameState.Paused;

                // DEBUG
                // Start combat
                if (InputHandler.ActionKeyPressed(ActionKey.Back, PlayerIndex.One))
                {
                    DataManager.RandomWildPokemon();
                    _gameRef.BattleScreen.InitializeBattle(DataManager.Trainers["Trond"], DataManager.Trainers["Tall Grass"]);
                }

                //If last movement brought you onto a trigger tile
                if (_collision == CollisionType.TrainerTriggerBush)
                    GamePlayScreen.Trainers["Sabrina"].TriggerTrainer(AnimationKey.Right);
                else if (_collision == CollisionType.TrainerTrigger)
                    GamePlayScreen.Trainers["Giovanni"].TriggerTrainer(AnimationKey.Right);
                else if (_collision == CollisionType.HealingHerb && InputHandler.ActionKeyPressed(ActionKey.ConfirmAndInteract, PlayerIndex.One) && !_justConfirmedPrompt)
                {
                    foreach (var pokemonNr in PlayerTrainer.PokemonSet)
                        pokemonNr.FullRestore();

                    TextPanel.BattleText.FirstLine = "Your pokemon ate some herbs.";
                    TextPanel.BattleText.SecondLine = "They feel healthy!";
                    MoveState = MoveState.Frozen;
                    _textDisplayState = TextDisplayState.TextDisplaying;
                }
                //Decides when to encounter wild pokemon
                else if (_collision == CollisionType.Bush && !_encounterChecked)
                {
                    _encounterChecked = true;
                    var rand = new Random();
                    int tau = rand.Next(200);
                    //Console.WriteLine(tau);
                    if (tau < 18)
                    {
                        DataManager.RandomWildPokemon();
                        _gameRef.BattleScreen.InitializeBattle(DataManager.Trainers["Trond"], DataManager.Trainers["Tall Grass"]);
                        return;
                    }
                }

                _justConfirmedPrompt = false;

                // Check for sprint
                if (InputHandler.ActionKeyDown(ActionKey.Sprint, PlayerIndex.One))
                {
                    _framesPerMovement = FramesPerMovement / 2;
                }
                else
                {
                    _framesPerMovement = FramesPerMovement;
                }

                // Check for EnemyTrainer
                if (InputHandler.ActionKeyPressed(ActionKey.ConfirmAndInteract, PlayerIndex.One))
                {
                    var checkPoint = new Vector2(Sprite.Position.X + (float)Sprite.Width / 2 + _movementVector.X * Sprite.Speed,
                                                 Sprite.Position.Y + (float)Sprite.Height / 2 * 1.5f +
                                                 _movementVector.Y * Sprite.Speed);

                    // Check for EnemyTrainer
                    _map.CheckForCollisions(checkPoint, ref _encounteredEnemyTrainer);

                    if (_encounteredEnemyTrainer != null && _encounteredEnemyTrainer.CurrentState != EnemyTrainerState.BattleFinished)
                        _encounteredEnemyTrainer.TriggerTrainer(Sprite.CurrentAnimation);

                }
                else if (InputHandler.ActionKeyDown(ActionKey.Up, PlayerIndex.One))
                {
                    Sprite.CurrentAnimation = AnimationKey.Up;
                    motion.Y = -1;
                    _movementVector = motion;
                }
                else if (InputHandler.ActionKeyDown(ActionKey.Down, PlayerIndex.One))
                {
                    Sprite.CurrentAnimation = AnimationKey.Down;
                    motion.Y = 1;
                    _movementVector = motion;
                }
                else if (InputHandler.ActionKeyDown(ActionKey.Left, PlayerIndex.One))
                {
                    Sprite.CurrentAnimation = AnimationKey.Left;
                    motion.X = -1;
                    _movementVector = motion;
                }
                else if (InputHandler.ActionKeyDown(ActionKey.Right, PlayerIndex.One))
                {
                    Sprite.CurrentAnimation = AnimationKey.Right;
                    motion.X = 1;
                    _movementVector = motion;
                }
                else if (_movementJustFinished)
                {
                    _movementJustFinished = false;
                    Sprite.SetCurrentAnimationFrame(FrameKey.Idle);
                }
            }

            // If the player moves in a new direction
            if (Sprite.CurrentAnimation != _previousMovementDirection && _collision == CollisionType.Unwalkable)
                _collision = CollisionType.Walkable;

            // If the player is not already moving AND the player has initiated movement AND didn't previously try to move onto an unwalkable tile
            if (MoveState == MoveState.Still &&
                motion != Vector2.Zero &&
                _collision != CollisionType.Unwalkable)
            {
                var checkPoint = new Vector2(Sprite.Position.X + (float)Sprite.Width / 2 + motion.X * Sprite.Speed,
                                          Sprite.Position.Y + (float)Sprite.Height / 2 * 1.5f +
                                          motion.Y * Sprite.Speed);

                // Check for collisions
                _collision = _map.CheckForCollisions(checkPoint, ref _encounteredEnemyTrainer);

                if (_collision != CollisionType.Unwalkable)
                {
                    MoveState = MoveState.Moving;
                    Sprite.IsAnimating = true;
                }
                else
                {
                    _previousMovementDirection = Sprite.CurrentAnimation;
                }
            }

            // Process movement if movement is initiated
            if (MoveState == MoveState.Moving)
            {
                // FIRST FRAME: Proceed to the next animation frame
                if (_frameCounter == 0)
                {
                    if (_lastFoot == FrameKey.RightFoot)
                    {
                        Sprite.SetCurrentAnimationFrame(FrameKey.LeftFoot);
                        _lastFoot = FrameKey.LeftFoot;
                    }
                    else
                    {
                        Sprite.SetCurrentAnimationFrame(FrameKey.RightFoot);
                        _lastFoot = FrameKey.RightFoot;
                    }

                }

                // Increment the frame counter
                _frameCounter++;

                // Update the position of the sprite
                Sprite.Position += _movementVector * Sprite.Speed / _framesPerMovement;

                // MIDDLE OF MOVEMENT: Proceed to the next animation frame
                if (_frameCounter == _framesPerMovement / 2)
                    Sprite.SetCurrentAnimationFrame(FrameKey.Idle);

                // MOVEMENT FINISHED
                if (_frameCounter == _framesPerMovement)
                {
                    _movementJustFinished = true;

                    // Set position of the sprite to integers
                    Sprite.Position = new Vector2((int)Math.Round(Sprite.Position.X), (int)Math.Round(Sprite.Position.Y));

                    // Reset the frame counter
                    _frameCounter = 0;

                    // Not moving anymore
                    MoveState = MoveState.Still;

                    // Not animating anymore
                    Sprite.IsAnimating = false;

                    // Save the direction of the movement
                    _previousMovementDirection = Sprite.CurrentAnimation;
                }

                base.Update(gameTime);
            }

            Camera.LockToSprite(Sprite);

            Camera.Update(gameTime);

            // DEBUG
            //Console.Clear();
            //Console.WriteLine("Zone: " + (_map.CurrentMapComponent != null ? _map.CurrentMapComponent.Name : ""));
            //Console.WriteLine("Collision: " + _collision);
            //Console.WriteLine("Moving: " + MoveState);
            //Console.WriteLine("EnemyTrainer: " + (_encounteredEnemyTrainer != null ? _encounteredEnemyTrainer.Name : ""));

            foreach (var drawableBattleComponent in Components)
            {
                drawableBattleComponent.Position = Sprite.Position;
                drawableBattleComponent.Update(gameTime);
            }
        }
 public void Stop()
 {
     _moveState = MoveState.Stop;
     SetColliderEnabled(true);
 }
Example #31
0
    public bool ExcuteMove()
    {
        switch (moveState)
        {
        case MoveState.startPoint:
            if (animator.GetCurrentAnimatorStateInfo(0).shortNameHash == idleHash)
            {
                if (!animator.applyRootMotion)
                {
                    animator.applyRootMotion = true;
                    animator.SetBool(runningHash, true);
                    //audio.Play();
                    //FXManager.GetInstance().DustSpawn(character.position, character.rotation, null);
                    FXManager.GetInstance().Spawn("Dust", character.position, character.rotation, 1.5f);
                    //GameController.GetInstance().Invoke(() =>
                    //{
                    //    character.Find("Render").gameObject.SetActive(false);

                    //    GameController.GetInstance().Invoke(() =>
                    //    {
                    //        character.Find("Render").gameObject.SetActive(true);
                    //    }, 0.1f);
                    //}, 0.2f);
                }
                moveState = MoveState.line;
            }
            break;

        case MoveState.line:        //     |  |__->___|  |_______|  |
            if (animator.GetCurrentAnimatorStateInfo(0).shortNameHash == runHash)
            {
                float distance = (Pos[i] - character.position).magnitude;

                //character.Translate(((Pos[i] - character.position).normalized) * Time.deltaTime * speed, Space.World);

                if (!animator.isMatchingTarget)
                {
                    if (distance > 1)
                    {
                        MatchPoint(Pos[i]);
                    }
                }
                if (distance <= 0.35f)
                {
                    animator.InterruptMatchTarget(false);
                    character.Translate(Pos[i] - character.position, Space.World);
                    animator.applyRootMotion = false;
                    animator.SetBool(runningHash, false);
                    moveState = MoveState.point;
                }
            }
            break;

        case MoveState.point:       //     |  |_______|->|_______|  |
            if (animator.GetCurrentAnimatorStateInfo(0).shortNameHash == idleHash)
            {
                if (i >= Pos.Count - 1)
                {
                    moveState = MoveState.finalPoint;
                }
                else
                {
                    i++;
                    if (Pos[i] != character.position)
                    {
                        Quaternion wantedRot = Quaternion.LookRotation(Pos[i] - character.position);
                        character.rotation = wantedRot;
                        //FXManager.GetInstance().DustSpawn(character.position, character.rotation, null);
                        FXManager.GetInstance().Spawn("Dust", character.position, character.rotation, 1.5f);
                        //GameController.GetInstance().Invoke(() =>
                        //{
                        //    character.Find("Render").gameObject.SetActive(false);
                        //    GameController.GetInstance().Invoke(() =>
                        //    {
                        //        character.Find("Render").gameObject.SetActive(true);
                        //    }, 0.1f);
                        //}, 0.2f);
                    }

                    if (!animator.applyRootMotion)
                    {
                        animator.applyRootMotion = true;
                        animator.SetBool(runningHash, true);
                        //audio.Play();
                        camera.FollowTarget(character.position);

                        moveState = MoveState.line;
                    }
                }
            }
            break;

        case MoveState.finalPoint:
            animator.applyRootMotion = false;
            camera.FollowTarget(character.position);
            Pos = null;
            return(true);
        }
        return(false);
    }
Example #32
0
 /// <summary>
 /// 设置主角镜头运动状态.
 /// </summary>
 internal void SetCameraMoveType(MoveState type)
 {
     m_CameraMoveType = type;
 }
Example #33
0
    /// <summary>
    /// 创建房间
    /// </summary>
    /// <param name="Info">炮弹兵信息</param>
    /// <param name="Camp">阵营</param>
    /// <param name="DataID">战斗环境中的DataID,其他环境填0 就可</param>
    /// <param name="moveState">运动状态</param>
    /// <param name="iRole">iRole</param>
    /// <returns></returns>
    public static Role CreateRole(Transform Tstart, AnimatorState state, SoldierInfo Info, LifeMCamp Camp, int DataID, MoveState moveState, Int2 BornPos, LifeEnvironment Environment)
    {
        if (Info == null)
        {
            return(null);
        }

        return(ConnectRoleLife(Tstart, state, Info, Camp, DataID, moveState, BornPos, Environment));
    }
    public IEnumerator ResetMoveState(float waitTime)
    {
        yield return(new WaitForSeconds(waitTime));

        moveState = MoveState.Standing;
    }
Example #35
0
    /// <summary>
    /// Role 与lifeobj的关联
    /// </summary>
    /// <param name="t">角色对象的Transform</param>
    /// <param name="Info">角色信息</param>
    /// <param name="Camp">阵营</param>
    /// <param name="DataID">战斗环境中的DataID,其他环境填0 就可</param>
    /// <param name="moveState">运动状态</param>
    /// <param name="Environment">对象所出环境</param>
    public static Role ConnectRoleLife(Transform Tstart, AnimatorState state, SoldierInfo Info, LifeMCamp Camp, int DataID, MoveState moveState, Int2 BornPos, LifeEnvironment Environment)
    {
        Role RoleLife = new Role();
        bool IsPlayer = CmCarbon.GetCamp2Player(Camp);
        int  RoleType = Info.m_modeltype;

        if (RoleType == 102003)
        {
            RoleType = 1020032;
        }
        if (RoleType == 200009)
        {
            RoleType = 2000092;
        }
        RoleLife.CreateSkin(Tstart, RoleType, Info.m_name, state, IsPlayer);
        RoleLife.SetRoleLife(Info, RoleLife.RoleSkinCom.ProPerty, Environment);
        LifeObj building = RoleLife.RoleSkinCom.tRoot.gameObject.AddComponent <LifeObj>();

        if (building != null)
        {
            if (Environment == LifeEnvironment.Combat)
            {
                RoleLife.SetLifeCore(new LifeMCore(DataID, IsPlayer, LifeMType.SOLDIER, Camp, moveState));
                RoleLife.SetSkin();
            }
            if (moveState == MoveState.Walk)
            {
                RoleLife.MoveAI.SetBornPos(BornPos, 0);
            }
            building.SetLife(RoleLife as Life, RoleLife.RoleSkinCom.ProPerty);
        }
        return(RoleLife);
    }
Example #36
0
        // Update is called once per frame
        void Update()
        {
            switch (currentMoveState)
            {
            case MoveState.Regular:

                //do behavioyr for this state;
                MoveThePlayer(1);


                //transition to other states;
                if (Input.GetButtonDown("Fire3"))
                {
                    currentMoveState = MoveState.Sprinting;
                }
                if (Input.GetButtonDown("Fire1"))
                {
                    currentMoveState = MoveState.Sneaking;
                }

                if (Input.GetButtonDown("Fire2"))     //transition into dashing
                {
                    currentMoveState = MoveState.Dashing;
                    float h = Input.GetAxis("Horizontal");
                    float v = Input.GetAxis("Vertical");
                    dashDirection = new Vector3(h, 0, v);
                }

                break;

            case MoveState.Sneaking:

                //do behavioyr for this state;
                MoveThePlayer(.5f);


                //transition to other states;
                if (!Input.GetButtonDown("Fire1"))
                {
                    currentMoveState = MoveState.Regular;
                }

                break;

            case MoveState.Sprinting:

                //do behavioyr for this state;
                MoveThePlayer(2);


                //transition to other states;
                if (!Input.GetButtonDown("Fire3"))
                {
                    currentMoveState = MoveState.Regular;
                }
                if (Input.GetButtonDown("Fire1"))
                {
                    currentMoveState = MoveState.Sneaking;
                }


                break;

            case MoveState.Dashing:

                //do behavioyr for this state;
                DashThePlayer();

                dashTimer -= Time.deltaTime;

                //transition to other states;


                break;
            }
        }
        // Update is called once per frame
        void Update()
        {
            switch (currentMoveState)
            {
            case MoveState.Regular:

                //do behavior for this state;
                MoveThePlayer(1);

                //transition to other states;
                //if (Input.GetButtonDown("Fire1")) currentMoveState = MoveState.Sneaking;
                if (Input.GetButton("Fire3"))
                {
                    currentMoveState = MoveState.Sprinting;
                }

                if (Input.GetButtonDown("Fire2"))     //transition into dashing
                {
                    currentMoveState = MoveState.Dashing;
                    float h = Input.GetAxisRaw("Horizontal");
                    float v = Input.GetAxisRaw("Vertical");
                    dashDirection = new Vector3(h, 0, v);
                    dashDirection.Normalize();
                    dashTimer = .25f;

                    //clamps the length of dashDir to 1
                    if (dashDirection.sqrMagnitude > 1)
                    {
                        dashDirection.Normalize();
                    }
                }

                break;

            case MoveState.Dashing:

                //do behavioyr for this state;
                DashThePlayer();

                dashTimer -= Time.deltaTime;

                //transition to other states;
                if (dashTimer <= 0)
                {
                    currentMoveState = MoveState.Regular;
                }



                break;

            case MoveState.Sprinting:

                //do behavioyr for this state;
                MoveThePlayer(2);


                //transition to other states;
                if (!Input.GetButton("Fire3"))
                {
                    currentMoveState = MoveState.Regular;
                }
                //if (Input.GetButton("Fire1")) currentMoveState = MoveState.Sneaking;


                break;

            case MoveState.Sneaking:

                //do behavioyr for this state;
                MoveThePlayer(0.5f);


                //transition to other states;
                //if (!Input.GetButton("Fire1")) currentMoveState = MoveState.Regular;

                break;
            }
        }
 void Start()
 {
     rigidbody2D = gameObject.GetComponent <Rigidbody2D>();
     moveState   = MoveState.ideal;
     Debug.Log(moveState);
 }
Example #39
0
    // Update is called once per frame
    void Update()
    {
        // get input and desired direction based on camera and ground
        Vector2 inputDir         = GetInputDirection();
        Vector3 desiredDir       = GetDesiredDirection(inputDir);
        Vector3 desiredGroundDir = GetDesiredDirectionOnGround(desiredDir);

        Debug.DrawLine(transform.position, transform.position + new Vector3(inputDir.x, 0, inputDir.y), Color.green);
        Debug.DrawLine(transform.position, transform.position + desiredDir, Color.blue);
        //Debug.DrawLine(transform.position, transform.position + desiredGroundDir, Color.cyan);

        // update state machine
        if (state == MoveState.IDLE)
        {
            state = UpdateIDLE(inputDir, desiredGroundDir);
        }
        else if (state == MoveState.WALKING)
        {
            state = UpdateWALKINGandRUNNING(inputDir, desiredGroundDir);
        }
        else if (state == MoveState.RUNNING)
        {
            state = UpdateWALKINGandRUNNING(inputDir, desiredGroundDir);
        }
        else if (state == MoveState.CROUCHING)
        {
            state = UpdateCROUCHING(inputDir, desiredGroundDir);
        }
        else if (state == MoveState.CRAWLING)
        {
            state = UpdateCRAWLING(inputDir, desiredGroundDir);
        }
        else if (state == MoveState.AIRBORNE)
        {
            state = UpdateAIRBORNE(inputDir, desiredGroundDir);
        }
        else if (state == MoveState.CLIMBING)
        {
            state = UpdateCLIMBING(inputDir, desiredGroundDir);
        }
        else if (state == MoveState.SWIMMING)
        {
            state = UpdateSWIMMING(inputDir, desiredGroundDir);
        }
        else if (state == MoveState.MOUNTED)
        {
            state = UpdateMOUNTED(inputDir, desiredGroundDir);
        }
        else if (state == MoveState.MOUNTED_AIRBORNE)
        {
            state = UpdateMOUNTED_AIRBORNE(inputDir, desiredGroundDir);
        }
        else if (state == MoveState.MOUNTED_SWIMMING)
        {
            state = UpdateMOUNTED_SWIMMING(inputDir, desiredGroundDir);
        }
        else if (state == MoveState.DEAD)
        {
            state = UpdateDEAD(inputDir, desiredGroundDir);
        }
        else
        {
            Debug.LogError("Unhandled Movement State: " + state);
        }

        // cache this move's state to detect landing etc. next time
        if (!controller.isGrounded)
        {
            lastFall = controller.velocity;
        }

        // move depending on latest moveDir changes
        controller.Move(moveDir * Time.deltaTime); // note: returns CollisionFlags if needed

        // calculate which leg is behind, so as to leave that leg trailing in the jump animation
        // (This code is reliant on the specific run cycle offset in our animations,
        // and assumes one leg passes the other at the normalized clip times of 0.0 and 0.5)
        float runCycle = Mathf.Repeat(animator.GetCurrentAnimatorStateInfo(0).normalizedTime + runCycleLegOffset, 1);

        jumpLeg = (runCycle < 0.5f ? 1 : -1);// * move.z;
    }
    void Start()
    {
        // Make the husband controllable
        active = true;

        // GameObject initialization
        husband = gameObject;

        // Initialize GameObject properties
        rBody = husband.GetComponent<Rigidbody2D>();
        rBody.freezeRotation = true;

        husbandCollider = husband.GetComponent<Collider2D>();

        // Variable properties
        playerMove = new MoveState();
        playerMove = MoveState.None;
    }
 void StartIdle()
 {
     moveState     = MoveState.Idle;
     body.velocity = Vector3.zero;
 }
 void StartMoving()
 {
     moveState         = MoveState.Moving;
     accelerationTimer = 0;
     InitializeCamera();
 }
Example #43
0
        protected float CalculateSpread(AimingState aimingState, MoveState moveState,
                                        PostureState postureState, float velocityMagitude)
        {
            float baseSpread = m_BaseSpread;

            if (m_ShotSpread != 0f)
            {
                baseSpread *= m_ShotSpread;
            }

            float aimingModifierSpread  = 1f;
            float moveModifierSpread    = 1f;
            float postureModifierSpread = 1f;

            switch (aimingState)
            {
            case AimingState.Stand:
                break;

            case AimingState.Aim:
                aimingModifierSpread = m_AimingModifierSpread;
                break;

            case AimingState.ADS:
                aimingModifierSpread = m_ADSModifierSpread;
                break;

            default:
                break;
            }

            switch (moveState)
            {
            case MoveState.Stand:
                break;

            case MoveState.Walk:
                moveModifierSpread = m_WalkModifierSpread;
                break;

            case MoveState.Run:
                moveModifierSpread = m_RunModifierSpread;
                break;

            case MoveState.Jump:
                moveModifierSpread = m_JumpModifierSpread;
                break;

            default:
                break;
            }

            switch (postureState)
            {
            case PostureState.Stand:
                break;

            case PostureState.Crouch:
                postureModifierSpread = m_CrouchModifierSpread;
                break;

            case PostureState.Prone:
                postureModifierSpread = m_ProneModifierSpread;
                break;

            default:
                break;
            }
            float spread = baseSpread * aimingModifierSpread + m_FiringBaseSpread * postureModifierSpread * moveModifierSpread + m_ShotSpread * 30.0f;

            return(spread);
        }
Example #44
0
        private void PickState(GameTime gameTime)
        {
            keysCombo = control.KeysDown(gameTime);
            if ((moveState != MoveState.Jump) && (moveState != MoveState.Cast))
            {
                switch (keysCombo)
                {
                case KeysCombo.RightArrow:
                    if (oldKeysCombo != KeysCombo.RightArrow)
                    {
                        currentFrame = walkRightStartFrame;
                    }

                    animationTimer += gameTime.ElapsedGameTime.Milliseconds;
                    if (animationTimer > walkPerFrame)
                    {
                        animationTimer = 0;
                        if ((position.X + charWidth) < screenWidth && !isWizMonColl)
                        {
                            position.X += walkSpeed;
                        }
                        currentFrame++;
                        if (currentFrame > walkRightEndFrame)
                        {
                            currentFrame = walkRightStartFrame;
                        }
                    }
                    break;

                case KeysCombo.LeftArrow:
                    if (oldKeysCombo != KeysCombo.LeftArrow)
                    {
                        currentFrame = walkLeftStartFrame;
                    }

                    animationTimer += gameTime.ElapsedGameTime.Milliseconds;
                    if (animationTimer > walkPerFrame)
                    {
                        animationTimer = 0;
                        if (position.X > 0)
                        {
                            position.X -= walkSpeed;
                        }
                        currentFrame++;
                        if (currentFrame > walkLeftEndFrame)
                        {
                            currentFrame = walkLeftStartFrame;
                        }
                    }
                    break;

                case KeysCombo.UpArrow:
                    currentFrame = jumpRightStartFrame;
                    moveState    = MoveState.Jump;
                    posYModifier = basicPosMofifier;
                    jumpMovement = 0;
                    break;

                case KeysCombo.UpRightArrows:
                    currentFrame = jumpRightStartFrame;
                    moveState    = MoveState.Jump;
                    posYModifier = basicPosMofifier;
                    jumpMovement = 10;
                    break;

                case KeysCombo.UpLeftArrows:
                    currentFrame = jumpLeftStartFrame;
                    moveState    = MoveState.Jump;
                    posYModifier = basicPosMofifier;
                    jumpMovement = -10;
                    break;

                case KeysCombo.W:
                    if (spellParams["lighting"].SpellCost <= mana)
                    {
                        currentFrame       = castingStartFrame;
                        moveState          = MoveState.Cast;
                        castMagicFrame     = 110;
                        castStartXPosition = position.X + castWidth / 4 * 3;
                        castStartYPosition = position.Y - 100;
                        mana -= spellParams["lighting"].SpellCost;
                        spells.Add(new CharacterSpell("lighting", spellParams["lighting"].SpellPower, spellsTextures[0], castStartXPosition, castStartYPosition, gameTime, 0, 9, 4, 3, 30, 20));
                    }
                    else
                    {
                        noMana = true;
                    }
                    break;

                case KeysCombo.A:
                    if (spellParams["water"].SpellCost <= mana)
                    {
                        currentFrame       = castingStartFrame;
                        moveState          = MoveState.Cast;
                        castMagicFrame     = 110;
                        castStartXPosition = position.X + castWidth / 4 * 3;
                        castStartYPosition = position.Y;
                        mana -= spellParams["water"].SpellCost;
                        spells.Add(new CharacterSpell("water", spellParams["water"].SpellPower, spellsTextures[1], castStartXPosition, castStartYPosition, gameTime, 5, 12, 5, 5, 30, 20));
                    }
                    else
                    {
                        noMana = true;
                    }
                    break;

                case KeysCombo.S:
                    if (spellParams["gravity"].SpellCost <= mana)
                    {
                        currentFrame       = castingStartFrame;
                        moveState          = MoveState.Cast;
                        castMagicFrame     = 110;
                        castStartXPosition = position.X + castWidth / 4 * 3;
                        castStartYPosition = position.Y;
                        mana -= spellParams["gravity"].SpellCost;
                        spells.Add(new CharacterSpell("gravity", spellParams["gravity"].SpellPower, spellsTextures[2], castStartXPosition, castStartYPosition, gameTime, 4, 10, 5, 4, 30, 20));
                    }
                    else
                    {
                        noMana = true;
                    }
                    break;

                case KeysCombo.D:
                    if (spellParams["shield"].SpellCost <= mana)
                    {
                        currentFrame       = castingStartFrame;
                        moveState          = MoveState.Cast;
                        castMagicFrame     = 110;
                        castStartXPosition = position.X;
                        castStartYPosition = position.Y;
                        mana -= spellParams["shield"].SpellCost;
                        spells.Add(new CharacterSpell("shield", spellParams["shield"].SpellPower, spellsTextures[3], castStartXPosition, castStartYPosition, gameTime, 0, 0, 1, 1, 30, 0));
                    }
                    else
                    {
                        noMana = true;
                    }
                    break;

                case KeysCombo.DownLeftX:
                    if (spellParams["special"].SpellCost <= mana && specialAbilityLeft)
                    {
                        currentFrame       = castingStartFrame;
                        moveState          = MoveState.Cast;
                        castMagicFrame     = 110;
                        castStartXPosition = position.X + 50;
                        castStartYPosition = position.Y - 150;
                        mana -= spellParams["special"].SpellCost;
                        specialAbilityLeft = false;
                        spells.Add(new CharacterSpell("special", spellParams["special"].SpellPower, spellsTextures[4], castStartXPosition, castStartYPosition, gameTime, 0, 15, 6, 6, 5, 30));
                    }
                    else
                    {
                        noMana = true;
                    }
                    break;

                default:
                    animationTimer += gameTime.ElapsedGameTime.Milliseconds;
                    if (animationTimer > idlePerFrame)
                    {
                        animationTimer = 0;
                        currentFrame++;
                        if (currentFrame > idleEndFrame)
                        {
                            currentFrame = idleStartFrame;
                        }
                    }
                    break;
                }
                oldKeysCombo = keysCombo;
            }

            // condition to continue idle when the cast button is pressed, but the wizard has not enough mana
            if (noMana)
            {
                animationTimer += gameTime.ElapsedGameTime.Milliseconds;
                if (animationTimer > idlePerFrame)
                {
                    animationTimer = 0;
                    currentFrame++;
                    if (currentFrame > idleEndFrame)
                    {
                        currentFrame = idleStartFrame;
                    }
                }
                noMana = false;
            }

            // perform additional action
            switch (moveState)
            {
            case MoveState.Jump:
                Jump(gameTime);
                break;

            case MoveState.Cast:
                Cast(gameTime);
                break;

            default:
                break;
            }
        }
Example #45
0
		//**********************************************************************

		void Start ()
		{
				playerMoveState = MoveState.Ground;
		}
Example #46
0
        public void changeState()
        {
            MoveState state = owner.getMoveState();

            state.ChangeMove(changeSpeed, changeVector3);
        }
 /// <summary>
 /// 重置抛物线--Editor调用
 /// </summary>
 public void ResetParabola()
 {
     _moveState = MoveState.None;
     transform.localPosition = Vector3.zero;
     _rotateTf.rotation      = Quaternion.identity;
 }
Example #48
0
 private void Idle()
 {
     _moveState = MoveState.Idle;
     _animatorController.Play("Idle");
 }
    //=================================================================================================================o
    void Update()
    {
        // MAIN INPUT
        if (canMove && !isDoubleTap)
        {
            // Stop Rotation if Left Shift is pressed
            if (!Input.GetKey (hKey.sprintToggleKey))
            {
                float rotato = Input.GetAxisRaw ("Rotato") * mouseRotSpeed * Time.deltaTime;
                hero.RotateAround (hero.up, rotato);

                DoubleTap ();
            }

            // Switch states if not balancing
            if (moveState != MoveState.Balancing)
            {
                // Left Shift to toggle sprint
                if (Input.GetKeyDown (hKey.sprintToggleKey) && moveState != MoveState.Sneaking && Grounded)
                {
                    moveState = moveState != MoveState.Sprinting ? MoveState.Sprinting : MoveState.Normal;
                }

                // Switch Walk/Run with X
                else if (Input.GetKeyDown (hKey.walkToggleKey))
                {
                    // Walking if not already else Normal
                    moveState = moveState != MoveState.Walking ? MoveState.Walking : MoveState.Normal;
                }

                // Sneak mode
                else if (Input.GetKeyDown (hKey.sneakToggleKey))
                {
                    // Sneaking if not already else Normal
                    moveState = moveState != MoveState.Sneaking ? MoveState.Sneaking : MoveState.Normal;

                    bool b = moveState == MoveState.Sneaking ? true : false;
                    // Sneak state delegate
                    if (doSneakDel != null) { doSneakDel (b); }
                }

                // Switch Combat mode if not in "Cooldown"
                else if (Input.GetKeyDown (hKey.readyWeaponKey))
                {
                    // Combat stance if not already else Normal
                    if (hAnim.mainState != HeroAnim.MainState.Combat)
                        moveState = MoveState.CombatStance;
                    else
                        moveState = MoveState.Normal;

                    // Combat state delegate
                    if (doCombatDel != null) { doCombatDel(); }
                }
                else if (Input.GetKeyDown(hKey.nextWeaponKey))
                {
                    if (hAnim.mainState != HeroAnim.MainState.Combat && !hAnim.isWeaponDraw)
                    {
                        // cycle through weapon states
                        hAnim.weaponState++; // Next
                        if (hAnim.weaponState > HeroAnim.WeaponState.None) // Last in the enum
                            hAnim.weaponState = HeroAnim.WeaponState.Unarmed; // Start at the first

                        // WeaponSwitch state delegate
                        if (doSwitchWeapDel != null) { doSwitchWeapDel(); }
                    }
                }
            }
        }
    }
 public void SetSpeed(float x, float y, float z)
 {
     _velocity  = new Vector3(x, y, z);
     _moveState = MoveState.None;
 }
Example #51
0
        /// <summary>
        /// Displays text
        /// </summary>
        /// <param name="gameTime">provides a snapshot of the gametime</param>
        private void DisplayText(GameTime gameTime)
        {
            TextPanel.Visible = true;
            TextPanel.TextPromptArrow.Visible = false;

            TextPanel.TextPromptArrow.WaitingForTextToAppear(gameTime);

            if (GamePlayScreen.Player.TextPanel.TextPromptArrow.State == TextArrowState.Clicked) {
                GamePlayScreen.Player.TextPanel.Visible = false;
                _textDisplayState = TextDisplayState.TextNotDisplaying;
                _justConfirmedPrompt = true;
                TextPanel.BattleText.FirstLine = "";
                TextPanel.BattleText.SecondLine = "";
                MoveState = MoveState.Still;
            }
        }
Example #52
0
        public void DrawGraph(Graphics g, Bitmap BackBuffer, Graphics BackBufferGraphics)
        {
            int PlotCount    = parent.PlotCount;
            int Plot2ndCount = parent.Plot2ndCount;

            Pen        p  = new Pen(Color.Gray, 1);
            SolidBrush b  = new SolidBrush(parent.GetLineColor(parent.comboBoxKmlOptColor));
            Font       f  = new Font("Tahoma", 8F * parent.df, System.Drawing.FontStyle.Regular);
            Font       f2 = new Font("Tahoma", 12F * parent.df, System.Drawing.FontStyle.Bold);

            int x0 = BackBuffer.Width / 24;         //10   4.16%
            int y0 = BackBuffer.Height * 472 / 508; //h-18

            int  Psize             = parent.GetLineWidth(parent.comboBoxKmlOptWidth);
            bool intersectionValid = false;

            Debug.Write(scaleCmd.ToString() + " " + drawMode);
            if (parent.CurrentPlotIndex >= 0 || PlotCount > 0 || (y2 != null && Plot2ndCount > 0))
            {
                if (alignT2f && parent.CurrentPlotIndex >= 0 && y2 != null && Plot2ndCount > 0)
                {
                    GetIntersection();
                    intersectionValid = true;
                    x2Ofs             = x[parent.CurrentPlotIndex] - xs;
                }
                else
                {
                    x2Ofs = 0;
                }

                if (scaleCmd == ScaleCmd.DoAutoscale || scaleCmd == ScaleCmd.DoAutoscaleNoUndo)
                {
                    Autoscale(true);
                }
                else if (scaleCmd == ScaleCmd.DoYAutoscale)
                {
                    Autoscale(false);
                }
                else if (scaleCmd == ScaleCmd.DoRedraw)
                {
                    Index2draw = -1;
                }
                scaleCmd = ScaleCmd.Nothing;

                int xEdgeDist, yEdgeDist;
                if (y2 != null && Plot2ndCount > 1)     //keep 1/3 of "T2F in advance" visible
                {
                    xEdgeDist = (xMaxOrg - xMinOrg) / 3;
                    yEdgeDist = (yMaxOrg - yMinOrg) / 3;
                }
                else
                {
                    xEdgeDist = 0;
                    yEdgeDist = 0;
                }

                if (parent.CurrentPlotIndex >= 0 && moveState == MoveState.Nothing)
                {
                    if (drawMode == DrawMode.KeepAutoscale)
                    {
                        if (x[parent.CurrentPlotIndex] > xMaxOrg || y[parent.CurrentPlotIndex] > yMaxOrg || y[parent.CurrentPlotIndex] < yMinOrg ||
                            Plot2ndCount > 0 && (x2[0] + x2Ofs <xMinOrg || x2[Plot2ndCount - 1] + x2Ofs> xMaxOrg || Math.Abs(x2Ofs - x2OfsDrawn) > (xMaxOrg - xMinOrg) / 32))
                        {
                            Autoscale(true);
                        }
                    }
                    else if (drawMode == DrawMode.Track)
                    {
                        bool needUpdateScaling = false;

                        while (x[parent.CurrentPlotIndex] + xEdgeDist > xMaxOrg)
                        {
                            xMax             += xDiv;
                            xMin             += xDiv;
                            xMaxOrg           = xMax * xScaleQ / xScaleP * xUnit;
                            needUpdateScaling = true;
                        }
                        while (x[parent.CurrentPlotIndex] < xMinOrg)
                        {
                            xMax             -= xDiv;
                            xMin             -= xDiv;
                            xMinOrg           = xMin * xScaleQ / xScaleP * xUnit;
                            needUpdateScaling = true;
                        }
                        while (y[parent.CurrentPlotIndex] + yEdgeDist > yMaxOrg)
                        {
                            yMax             += yDiv;
                            yMin             += yDiv;
                            yMaxOrg           = yMax * yScaleQ / yScaleP;
                            needUpdateScaling = true;
                        }
                        while (y[parent.CurrentPlotIndex] - yEdgeDist < yMinOrg)
                        {
                            yMin             -= yDiv;
                            yMax             -= yDiv;
                            yMinOrg           = yMin * yScaleQ / yScaleP;
                            needUpdateScaling = true;
                        }
                        if (needUpdateScaling || Math.Abs(x2Ofs - x2OfsDrawn) > (xMaxOrg - xMinOrg) / 32)
                        {
                            UpdateScaling(true);
                        }
                    }
                }

                if (moveState == MoveState.Move || moveState == MoveState.MoveEnd)
                {
                    int xDelta = parent.MouseShiftX * (xMaxSave - xMinSave) / (int)xFactor * xScaleP / xScaleQ;     //test XScale
                    int yDelta = parent.MouseShiftY * (yMaxSave - yMinSave) / yFactor * yScaleP / yScaleQ;
                    if (moveState == MoveState.MoveEnd)
                    {
                        moveState = MoveState.Nothing;
                    }
                    bool xChanged = false, yChanged = false;
                    if (Math.Abs(parent.MouseShiftX) > BackBuffer.Width / 20)
                    {
                        xChanged = true;
                    }
                    if (Math.Abs(parent.MouseShiftY) > BackBuffer.Height / 20)
                    {
                        yChanged = true;
                    }
                    bool shift;
                    if (mousePos == MousePos.middle)    //shift
                    {
                        int vz;
                        if (xChanged)
                        {
                            if (parent.MouseShiftX < 0)
                            {
                                vz = -1;
                            }
                            else
                            {
                                vz = 1;
                            }
                            xDelta = (xDelta * vz / xDiv) * xDiv * vz;
                            xMin   = xMinSave - xDelta;
                            xMax   = xMaxSave - xDelta;
                            xUnit  = 1;
                        }
                        if (yChanged)
                        {
                            if (parent.MouseShiftY < 0)
                            {
                                vz = -1;
                            }
                            else
                            {
                                vz = 1;
                            }
                            yDelta = (yDelta * vz / yDiv) * yDiv * vz;
                            yMin   = yMinSave + yDelta;
                            yMax   = yMaxSave + yDelta;
                        }
                        shift = true;
                    }
                    else                                             //zoom
                    {
                        xMax = xMaxSave; xMin = xMinSave; xUnit = 1; //return to default unit
                        if (xChanged)
                        {
                            if (parent.MouseClientX < BackBuffer.Width * 40 / 480)
                            {
                                xMin = xMinSave - xDelta;
                            }                                                                                         //20
                            else if (parent.MouseClientX > BackBuffer.Width * 440 / 480)
                            {
                                xMax = xMaxSave - xDelta;
                            }                                                                                             //w-20
                            else if (parent.MouseShiftX > 0)
                            {
                                xMax = xMaxSave - xDelta;
                            }
                            else
                            {
                                xMin = xMinSave - xDelta;
                            }
                        }
                        if (yChanged)
                        {
                            if (parent.MouseClientY < BackBuffer.Width * 40 / 480)
                            {
                                yMax = yMaxSave + yDelta;
                            }                                                                                       //20
                            else if (parent.MouseClientY > BackBuffer.Height * 460 / 508)
                            {
                                yMin = yMinSave + yDelta;
                            }                                                                                              //h-24
                            else if (parent.MouseShiftY > 0)
                            {
                                yMin = yMinSave + yDelta;
                            }
                            else
                            {
                                yMax = yMaxSave + yDelta;
                            }
                        }
                        shift = false;
                    }
                    if (xChanged || yChanged)
                    {
                        UpdateScaling(shift);
                        if (drawMode == DrawMode.KeepAutoscale)
                        {
                            drawMode = DrawMode.Track;
                        }
                        if (parent.CurrentPlotIndex >= 0 && (x[parent.CurrentPlotIndex] + xEdgeDist > xMaxOrg || x[parent.CurrentPlotIndex] < xMinOrg || y[parent.CurrentPlotIndex] + yEdgeDist > yMaxOrg || y[parent.CurrentPlotIndex] - yEdgeDist < yMinOrg))
                        {
                            drawMode = DrawMode.Draw;
                        }
                    }
                    else
                    {
                        Index2draw = -1;
                    }
                }


                if (Index2draw < 0)
                {
                    //Debug.WriteLine("Draw full");
                    Index2draw = 0;
                    BackBufferGraphics.Clear(Form1.bkColor);

                    //Draw grid
                    int xFac = parent.NoBkPanel.Width * 11 / 12;
                    int yFac = parent.NoBkPanel.Height * 9 / 10;
                    for (int i = xMin; i <= xMax; i += xDiv)
                    {
                        BackBufferGraphics.DrawLine(p, x0 + (int)((i - xMin) * xFac / xSector), y0, x0 + (int)((i - xMin) * xFac / xSector), y0 - (yMax - yMin) * yFac / ySector);
                    }
                    for (int i = yMin; i <= yMax; i += yDiv)
                    {
                        BackBufferGraphics.DrawLine(p, x0, y0 - (i - yMin) * yFac / ySector, x0 + (int)((xMax - xMin) * xFac / xSector), y0 - (i - yMin) * yFac / ySector);
                    }

                    //Draw text
                    String xMaxStr = xMax.ToString();
                    SizeF  size    = BackBufferGraphics.MeasureString(xMaxStr, f);
                    BackBufferGraphics.DrawString(xMin.ToString(), f, b, BackBuffer.Width * 4 / 480, BackBuffer.Height * 480 / 508);
                    BackBufferGraphics.DrawString(xMaxStr, f, b, BackBuffer.Width * 476 / 480 - size.Width, BackBuffer.Height * 480 / 508);
                    BackBufferGraphics.DrawString(xLabel1 + xDiv.ToString() + xLabel2, f, b, BackBuffer.Width * 160 / 480, BackBuffer.Height * 480 / 508);
                    BackBufferGraphics.DrawString(yMax.ToString(), f, b, BackBuffer.Width * 2 / 480, BackBuffer.Height * 4 / 508);
                    BackBufferGraphics.DrawString(yMin.ToString(), f, b, BackBuffer.Width * 2 / 480, BackBuffer.Height * 460 / 508);
                    BackBufferGraphics.DrawString(title1 + yDiv.ToString() + title2, f2, b, BackBuffer.Width * 120 / 480, BackBuffer.Height * 4 / 508);
                    String drawModeStr = null;;
                    if (drawMode == DrawMode.KeepAutoscale)
                    {
                        drawModeStr = "auto";
                    }
                    else if (drawMode == DrawMode.Track)
                    {
                        drawModeStr = "track";
                    }
                    if (drawModeStr != null)
                    {
                        size = BackBufferGraphics.MeasureString(drawModeStr, f);
                        BackBufferGraphics.DrawString(drawModeStr, f, b, BackBuffer.Width * 460 / 480 - size.Width, BackBuffer.Height * 14 / 508);
                    }

                    if (y2 != null && Plot2ndCount > 0 && !hideT2f)
                    {                    //Draw line T2F
                        p.Color = parent.GetLineColor(parent.comboBoxLine2OptColor);
                        p.Width = parent.GetLineWidth(parent.comboBoxLine2OptWidth) / 2;
                        if (alignT2f)
                        {
                            b.Color = p.Color;
                            String x2OfsStr = (x2Ofs * xScaleP / (xScaleQ * xUnit)).ToString();
                            size = BackBufferGraphics.MeasureString(x2OfsStr, f);
                            BackBufferGraphics.DrawString(x2OfsStr, f, b, BackBuffer.Width * 460 / 480 - size.Width, BackBuffer.Height * 448 / 508);
                        }
                        x2OfsDrawn = x2Ofs;

                        int j1, j2;
                        for (j1 = 0; j1 < Plot2ndCount - 1; j1++)   //ignore not visible
                        {
                            if (x2[j1 + 1] + x2OfsDrawn >= xMinOrg)
                            {
                                break;
                            }
                        }
                        while (y2[j1] == Int16.MinValue)     //ignore invalids at the beginning
                        {
                            j1++;
                            if (j1 >= Plot2ndCount)
                            {
                                break;
                            }
                        }
                        if (j1 >= Plot2ndCount - 1)
                        {
                            j2 = j1;                            //draw single point  - working?
                        }
                        else
                        {
                            j2 = j1 + 1;
                        }
                        for (; j2 < Plot2ndCount; j2++)
                        {
                            while (y2[j2] == Int16.MinValue)
                            {
                                if (++j2 >= Plot2ndCount)
                                {
                                    goto exit2;
                                }
                            }
                            if (x2[j1] + x2OfsDrawn > xMaxOrg)
                            {
                                goto exit2;                                     //not visible
                            }
                            BackBufferGraphics.DrawLine(p, x0 + (int)((x2[j1] - xMinOrg + x2OfsDrawn) * xFactor / xUnit / xSector), y0 - (y2[j1] - yMinOrg) * yFactor / ySector,
                                                        x0 + (int)((x2[j2] - xMinOrg + x2OfsDrawn) * xFactor / xUnit / xSector), y0 - (y2[j2] - yMinOrg) * yFactor / ySector);
                            j1 = j2;
                        }
                        exit2 :;
                    }
                }

                p.Color = parent.GetLineColor(parent.comboBoxKmlOptColor);
                if (PlotCount > 0 && !hideTrack)
                {
                    Debug.WriteLine(Index2draw);
                    //Draw line
                    p.Width = Psize / 2;
                    int i1 = Index2draw, i2;
                    for (i1 = 0; i1 < PlotCount - 1; i1++)   //ignore not visible
                    {
                        if (x[i1 + 1] >= xMinOrg)
                        {
                            break;
                        }
                    }
                    while (y[i1] == Int16.MinValue)     //ignore invalids at the beginning
                    {
                        i1++;
                        if (i1 >= PlotCount)
                        {
                            break;
                        }
                    }
                    if (i1 >= PlotCount - 1)
                    {
                        i2 = i1;                         //draw single point
                    }
                    else
                    {
                        i2 = i1 + 1;
                    }
                    for (; i2 < PlotCount; i2++)
                    {
                        while (y[i2] == Int16.MinValue)
                        {
                            if (++i2 >= PlotCount)
                            {
                                goto exit;
                            }
                        }
                        if (x[i1] > xMaxOrg)
                        {
                            goto exit;                       //not visible
                        }
                        BackBufferGraphics.DrawLine(p, x0 + (int)((x[i1] - xMinOrg) * xFactor / xUnit / xSector), y0 - (y[i1] - yMinOrg) * yFactor / ySector,
                                                    x0 + (int)((x[i2] - xMinOrg) * xFactor / xUnit / xSector), y0 - (y[i2] - yMinOrg) * yFactor / ySector);
                        Index2draw = i2;
                        i1         = i2;
                    }
                    exit :;
                }
            }
            else
            {
                BackBufferGraphics.Clear(Form1.bkColor);
                BackBufferGraphics.DrawString(title1 + title2, f2, b, BackBuffer.Width * 120 / 480, BackBuffer.Height * 4 / 508);
                BackBufferGraphics.DrawString("no data to plot", f2, b, BackBuffer.Width * 20 / 480, BackBuffer.Height * 80 / 508);
            }
            g.DrawImage(BackBuffer, 0, 0);                  // draw back buffer on screen
            //Draw current point
            if (y2 != null && Plot2ndCount > 0 && !hideT2f) //draw point with index of intersection to t2f
            {
                if (!intersectionValid)
                {
                    GetIntersection();
                }
                b.Color = GpsUtils.Utils.modifyColor(parent.GetLineColor(parent.comboBoxLine2OptColor), +180);
                g.FillEllipse(b, x0 + (int)((xs - xMinOrg + x2OfsDrawn) * xFactor / xUnit / xSector) - Psize, y0 - (ys - yMinOrg) * yFactor / ySector - Psize, 2 * Psize, 2 * Psize);
            }
            if (parent.CurrentPlotIndex >= 0 && !hideTrack)        //draw current point
            {
                b.Color = p.Color;
                g.FillEllipse(b, x0 + (int)((x[parent.CurrentPlotIndex] - xMinOrg) * xFactor / xUnit / xSector) - Psize, y0 - (y[parent.CurrentPlotIndex] - yMinOrg) * yFactor / ySector - Psize, 2 * Psize, 2 * Psize);
            }
        }
Example #53
0
        /// <summary>
        /// Very unsecure way of doing moving on a screen that is of unknown size in ogl window....
        /// </summary>
        public void Move()
        {
            ticks = System.DateTime.Now.Ticks / TimeSpan.TicksPerSecond;

            if (this.oldTicks != 0)
            {
                #region Timed move - disabled
                /*
                //Console.WriteLine(DateTime.Now.ToString("hh:mm:ss.ffffff") + ": " + this.ticks + "-" + this.oldTicks + "=" + (this.ticks - this.oldTicks));

                if ((this.ticks - this.oldTicks) % 3 == 2)
                {
                    CurrentImage++;
                    if (CurrentImage > 7)
                    {
                        CurrentImage = 0;
                    }
                }

                if (
                    (CurrentMove == 0 && (this.ticks - this.oldTicks) > 6) ||
                    (CurrentMove == 1 && (this.ticks - this.oldTicks) > 6) ||
                    (CurrentMove == 2 && (this.ticks - this.oldTicks) > 13) ||
                    (CurrentMove == 3 && (this.ticks - this.oldTicks) > 13)
                   )
                {
                    if (CurrentMove == 3)
                    {
                        CurrentMove = 1;
                    }
                    CurrentMove++;
                    oldTicks = ticks;
                    //Console.WriteLine(DateTime.Now.ToString("hh:mm:ss.ffffff") + ": change move");
                }

                // Make move, this is so not good to have constant sizes on edges...
                switch (CurrentMove)
                {
                    case 0:
                        if (Y < 1.0f)
                        {
                            Y += Speed;
                        }
                        break;
                    case 3:
                    case 1:
                        if (X > -2.0f)
                        {
                            X -= Speed;
                        }
                        break;
                    case 2:
                        if (X < 2.0f)
                        {
                            X += Speed;
                        }
                        break;
                    default:
                        break;
                }
                */
                #endregion

                //Image selection
                if (CurrentImageSequence >= 10)
                {
                    CurrentImageSequence = 0;
                    switch (Util.Rnd.Next(0, 1000) / 100)
                    {
                        case 4: // Normal stop
                        case 3:
                        case 5:
                            ImageSequence = ImageState.NormalStop;
                            CurrentMove = MoveState.Stop;
                            break;
                        case 6: // Steroid
                        case 7:
                            ImageSequence = ImageState.Steroid;
                            CurrentMove = (MoveState)(Util.Rnd.Next(0, 999) / 500);
                            break;
                        case 8:// Steroid stop
                        case 9:
                            ImageSequence = ImageState.SteroidStop;
                            CurrentMove = MoveState.Stop;
                            break;
                        default: // Normal
                            ImageSequence = ImageState.Normal;
                            CurrentMove = (MoveState)(Util.Rnd.Next(0, 999) / 500);
                            break;
                    }
                }

                //Console.WriteLine((((this.ticks - this.oldTicks) / TimeSpan.TicksPerSecond) % 2) + ", " + ((this.ticks - this.oldTicks) / TimeSpan.TicksPerSecond));
                if (this.ticks != this.oldTicks && (
                    ( (((this.ticks - this.oldTicks) / TimeSpan.TicksPerSecond) % 2) == 0)
                   ))
                {
                    /*
                    CurrentImage++;

                    if (CurrentImage > 7)
                    {
                        CurrentImage = 0;
                    }*/

                    switch (ImageSequence)
                    {
                        case ImageState.Normal: //0,1,2,3,4,5
                        case ImageState.NormalStop:
                            CurrentImage++;
                            if (CurrentImage > 5)
                            {
                                CurrentImage = 0;
                            }
                            break;
                        case ImageState.Steroid: //0,1,2,3,6,7
                        case ImageState.SteroidStop:
                            CurrentImage++;
                            if (CurrentImage > 3 && CurrentImage < 6)
                            {
                                CurrentImage = 6;
                            }
                            else if (CurrentImage > 7)
                            {
                                CurrentImage = 0;
                            }
                            break;
                        default:
                            break;
                    }

                    oldTicks = ticks;
                    CurrentImageSequence++;
                }

                // Movements, fixed size :(
                switch (CurrentMove)
                {
                    case MoveState.Intro:
                        if (Y + Size.Height < 0.0f)
                        {
                            Y += 0.003f;
                        }
                        else
                        {
                            if ((Util.Rnd.Next(0, 1000) / 500.0) > 1.0)
                            {
                                CurrentMove = MoveState.MoveRight;
                            }
                            else
                            {
                                CurrentMove = MoveState.MoveLeft;
                            }

                        }
                        break;
                    case MoveState.MoveRight:
                        if (X - Size.Width > -2.0f)
                        {
                            X -= Speed;
                        }
                        else
                        {
                            CurrentMove = MoveState.MoveLeft;
                        }
                        break;
                    case MoveState.MoveLeft:
                        if (X + Size.Width < 1.5f)
                        {
                            X += Speed;
                        }
                        else
                        {
                            CurrentMove = MoveState.MoveRight;
                        }
                        break;
                    default: //MoveState.Stop
                        break;
                }
            }
            else if (oldTicks == 0)
            {
                oldTicks = ticks;
            }
        }
Example #54
0
 public void Enable()
 {
     m_ElapsedTime = 0.0f;
     m_State       = MoveState.In;
 }
    void Update()
    {
        // Horizontal movement
        if(Input.GetKey (KeyCode.LeftArrow) && active) {
            playerMove = MoveState.Left;
        } else if(Input.GetKey (KeyCode.RightArrow) && active) {
            playerMove = MoveState.Right;
        } else {
            playerMove = MoveState.None;
        }

        // Jumping
        if(((Input.GetKey(KeyCode.Space) && active)|| Input.GetKey(KeyCode.UpArrow)) && grounded && active) {
            rBody.velocity = new Vector2(0, JUMP_HEIGHT);;
        }
    }
Example #56
0
 public void Disable()
 {
     m_ElapsedTime = 0.0f;
     m_State       = MoveState.Out;
 }
    // Update movement state machine + crouch state
    void UpdateMoveState(Vector2 input2d)
    {
        switch (moveState)
        {
        case MoveState.IDLE:
            if (crouchEnabled && CrossPlatformInputManager.GetButtonDown("Crouch"))
                isCrouching = crouchEnabled && !isCrouching;
            if (!Mathf.Approximately(input2d.magnitude, 0) && characterController.isGrounded) {
                if (walkEnabled)
                    moveState = MoveState.WALKING;
                if (runEnabled && CrossPlatformInputManager.GetButtonDown("Sprint")) {
                    moveState = MoveState.RUNNING;
                    isCrouching = false;
                }
            }
            break;

        case MoveState.WALKING:
            if (crouchEnabled && CrossPlatformInputManager.GetButtonDown("Crouch"))
                isCrouching = crouchEnabled && !isCrouching;
            if (Mathf.Approximately(input2d.magnitude, 0)) {
                if (runEnabled && CrossPlatformInputManager.GetButtonDown("Sprint")) {
                    moveState = MoveState.RUNNING;
                    isCrouching = false;
                }
            }
            if (walkEnabled || Mathf.Approximately(input2d.magnitude, 0) || !characterController.isGrounded)
                moveState = MoveState.IDLE;
            break;

        case MoveState.RUNNING:
            if (!runEnabled || CrossPlatformInputManager.GetButtonDown("Sprint"))
                moveState = MoveState.WALKING;
            if (walkEnabled || Mathf.Approximately(input2d.magnitude, 0) || !characterController.isGrounded)
                moveState = MoveState.IDLE;
            if (crouchEnabled && slideEnabled && CrossPlatformInputManager.GetButtonDown("Crouch")) {
                timeSlideStart = Time.time;
                moveState = MoveState.SLIDING;
            }
            break;

        case MoveState.SLIDING:
            isCrouching = true;
            if (!crouchEnabled || !slideEnabled || Time.time - timeSlideStart > slideDuration
                || !characterController.isGrounded)
            {
                moveState = MoveState.WALKING;
            }
            break;
        }

        if (!crouchEnabled)
            isCrouching = false;
    }
Example #58
0
 private void Awake()
 {
     _playerMoveState = GetComponent <MoveState>();
     _playerShotState = GetComponent <ShotState>();
 }
Example #59
0
		void FixedUpdate ()
		{
				#region Input Management
				forwardInput = (float)Input.GetAxis ("Forward");
				lateralInput = (float)Input.GetAxis ("Lateral");
				jumpInput = (float)Input.GetAxis ("Jump");
				#endregion
				

				//print (rigidbody.velocity);
				#region Determine State
				if (isGrounded == false)
						playerMoveState = MoveState.Air;
				else if (forwardInput != 0 || lateralInput != 0)
						playerMoveState = MoveState.Ground;
				else if (forwardInput * lateralInput == 0 && isGrounded)
						playerMoveState = MoveState.GroundIdle;
				#endregion

				#region Firing Check
				if (Input.GetMouseButtonDown (0) && fireDelayCounter < 0) {
						fireDelayCounter = fireDelay;
						Fire ();
				}
				#endregion

				#region Jump
				if (jumpInput != 0 && isGrounded && jumpDelayCounter < 0) {
						playerMoveState = MoveState.Jump;
						jumpDelayCounter = jumpDelay;
				}
				jumpDelayCounter -= Time.fixedDeltaTime;
				#endregion
				
				#region State machine

				switch (playerMoveState) {
				case MoveState.Ground: //********************************************
						rigidbody.drag = 10f;
						moveDir = new Vector3 (lateralInput, 0, forwardInput).normalized;
						if (rigidbody.velocity.magnitude < maxSpeed_Ground && isGrounded && jumpDelayCounter < 0) {
								rigidbody.AddRelativeForce (moveDir * accel_Ground);
						}
						break;

				case MoveState.Air: //********************************************
						rigidbody.drag = 0f;
						moveDir = new Vector3 (lateralInput, 0, forwardInput).normalized;

						/** This section curbs the movement so air strafing is possible but player input can still steer player without breaching max speed */
						if (Mathf.Abs (transform.InverseTransformDirection (rigidbody.velocity).x) > maxSpeed_Air) {
								if (Mathf.Sign (lateralInput) == Mathf.Sign (transform.InverseTransformDirection (rigidbody.velocity).x)) {
										moveDir.x = 0;
								}
						}

						if (Mathf.Abs (transform.InverseTransformDirection (rigidbody.velocity).z) > maxSpeed_Air) {
								if (Mathf.Sign (forwardInput) == Mathf.Sign (transform.InverseTransformDirection (rigidbody.velocity).z)) {
										moveDir.z = 0;
								}
						}
						rigidbody.AddRelativeForce (moveDir * accel_Air);
						break;

				case MoveState.Stun: //********************************************
			
						break;

				case MoveState.GroundIdle: //********************************************
						rigidbody.drag = 10f;
						break;

				case MoveState.Jump: //********************************************
						rigidbody.drag = 0f;
						rigidbody.AddRelativeForce (new Vector3 ((lateralInput * jumpForce) / 2f, jumpForce, (forwardInput * jumpForce) / 2f), ForceMode.Impulse);
						break;

				default: //********************************************
						break;

	
				}
				#endregion

				moveDir = Vector3.zero;
				fireDelayCounter -= Time.fixedDeltaTime;
				transform.Translate (0, 0, .0000000001f); //Necessary for Unity's handling of adding force to a rigidbody that has a collider grow into it if it's not moving
		}
Example #60
0
    IEnumerator ZigzagBehaviour()
    {
        float currentMovementDuration = 0f;
        float moveDownDuration        = 1f;
        float shortLeftDuration       = 1f;
        float moveLeftDuration        = 3f;
        float moveRightDuration       = 3f;

        Vector2 position = transform.position;

        while (true)
        {
            if (moveState == MoveState.Idle)
            {
                moveState = MoveState.FirstDown;
                currentMovementDuration = 0;
                yield return(null);
            }

            if (moveState == MoveState.FirstDown)
            {
                if (currentMovementDuration < moveDownDuration)
                {
                    position.y -= moveSpeed * Time.deltaTime;
                    currentMovementDuration += Time.deltaTime;
                    transform.position       = position;
                    yield return(null);
                }
                else
                {
                    moveState = MoveState.ShortLeft;
                    currentMovementDuration = 0;
                    yield return(null);
                }
            }

            if (moveState == MoveState.ShortLeft)
            {
                if (currentMovementDuration < shortLeftDuration)
                {
                    position.x -= moveSpeed * Time.deltaTime;
                    currentMovementDuration += Time.deltaTime;
                    transform.position       = position;
                    yield return(null);
                }
                else
                {
                    moveState = MoveState.DownBeforeRight;
                    currentMovementDuration = 0;
                    yield return(null);
                }
            }

            if (moveState == MoveState.DownBeforeRight)
            {
                if (currentMovementDuration < moveDownDuration)
                {
                    position.y -= moveSpeed * Time.deltaTime;
                    currentMovementDuration += Time.deltaTime;
                    transform.position       = position;
                    yield return(null);
                }
                else
                {
                    moveState = MoveState.Right;
                    currentMovementDuration = 0;
                    yield return(null);
                }
            }

            if (moveState == MoveState.Right)
            {
                if (currentMovementDuration < moveRightDuration)
                {
                    position.x += moveSpeed * Time.deltaTime;
                    currentMovementDuration += Time.deltaTime;
                    transform.position       = position;
                    yield return(null);
                }
                else
                {
                    moveState = MoveState.DownBeforeLeft;
                    currentMovementDuration = 0;
                    yield return(null);
                }
            }

            if (moveState == MoveState.DownBeforeLeft)
            {
                if (currentMovementDuration < moveDownDuration)
                {
                    position.y -= moveSpeed * Time.deltaTime;
                    currentMovementDuration += Time.deltaTime;
                    transform.position       = position;
                    yield return(null);
                }
                else
                {
                    moveState = MoveState.Left;
                    currentMovementDuration = 0;
                    yield return(null);
                }
            }

            if (moveState == MoveState.Left)
            {
                if (currentMovementDuration < moveLeftDuration)
                {
                    position.x -= moveSpeed * Time.deltaTime;
                    currentMovementDuration += Time.deltaTime;
                    transform.position       = position;
                    yield return(null);
                }
                else
                {
                    moveState = MoveState.DownBeforeRight;
                    currentMovementDuration = 0;
                    yield return(null);
                }
            }

            yield return(null);
        }
    }