Exemplo n.º 1
0
    //Determines state depending on whether or not it can "see" the player within it's aura
    public void DetermineState()
    {
        Vector3 vectorToPlayer = transform.position -player.transform.position;

        //If player is within aura
        if(vectorToPlayer.magnitude<auraAmount){

            RaycastHit hit;
            //If there's nothing blocking our "view" to the player
            if(Physics.Raycast(transform.position,player.transform.position-transform.position,out hit)){
                if(hit.collider.tag=="Player"){
                    currWaypoint=hit.collider.transform;
                    currMovementState=MovementState.SEEKINGPLAYER;
                    //gameObject.BroadcastMessage("Activate",SendMessageOptions.DontRequireReceiver);
                }
            }
            else{
                if(currMovementState==MovementState.SEEKINGPLAYER){
                    //gameObject.BroadcastMessage("Deactivate",SendMessageOptions.DontRequireReceiver);
                }

                currMovementState=MovementState.WAYPOINTING;
            }
        }
        else{
            if(currMovementState==MovementState.SEEKINGPLAYER){
                currWaypoint=waypoints[currWaypointIndex];
                //gameObject.BroadcastMessage("Deactivate",SendMessageOptions.DontRequireReceiver);
            }

            currMovementState=MovementState.WAYPOINTING;
        }
    }
Exemplo n.º 2
0
 /// <summary>
 /// Constructor
 /// </summary>
 public MovementBehavior()
 {
     this.Target = Vector2.Zero;
     this.Path = new Queue<Vector2>();
     this.DrawablePathLines = new List<LinePrimitive>();
     this.State = MovementState.ApproachTarget;
 }
Exemplo n.º 3
0
    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag== "Ball") {

            PointManagement.GetInstance().incrementScore(points);

            if(phase==MovementState.DefaultPosition){
                phase=MovementState.FirstMove;
                dragSound.Play();
            }
            if(phase==MovementState.FirstPosition){
                phase=MovementState.SecondMove;
                dragSound.Play();
            }
            }if(phase==MovementState.SecondPosition){
                phase=MovementState.ThirdMove;
                dragSound.Play();
            }

        Vector3 pPos = collision.transform.position;
        Vector3 bPos = this.transform.position;
        Vector3 b2P = pPos-bPos;
        b2P = b2P.normalized *power;
        //bumperObject.transform.position = bPos +b2P;
        ball.AddForceAtPosition(b2P, this.transform.position, ForceMode2D.Impulse);
    }
	// Use this for initialization
	void Start ()
	{
		if (!isLocalPlayer) {
			return;
		}

		this.rigidbody = this.GetComponent<Rigidbody> ();

		state = MovementState.Walking;

		walkSpeed = 6;
		sprintSpeed = 10;
		crouchSpeed = 2;
		jumpForce = 400;

		isGrounded = true;
		isJumpReady = true;

		walkSource = this.gameObject.AddComponent<AudioSource>();
		runSource = this.gameObject.AddComponent<AudioSource>();
		walkSource.clip = walkSound;
		runSource.clip = runSound;
		walkSource.loop = true;
		runSource.loop = true;

		staminaScript = this.GetComponent <Player_Stamina>();
		StartCoroutine ("SprintStamina");
	}
Exemplo n.º 5
0
        private static void HandleMovement(ref Point coordinate, MovementState state)
        {
            switch (state)
            {
                case MovementState.Down:
                    {
                        coordinate.Y++;
                        break;
                    }

                case MovementState.Up:
                    {
                        coordinate.Y--;
                        break;
                    }

                case MovementState.Left:
                    {
                        coordinate.X--;
                        break;
                    }

                case MovementState.Right:
                    {
                        coordinate.X++;
                        break;
                    }
            }
        }
Exemplo n.º 6
0
    //Should the bullet
    private void fireWeapon(GameObject player)
    {
        //Player on right
        //Seperating them as later we might want to specify a start position based on which side it is
        //player on right
        movementState=MovementState.Firing;
        audio.PlayOneShot(strike);
        if(transform.position.x<player.transform.position.x){

            Vector3 spawnPos = transform.position;
            spawnPos.z=player.transform.position.z;
            spawnPos.x+=0.5f;

            Projectile proj = Instantiate(projectile,spawnPos,projectile.transform.rotation) as Projectile;

            BombProjectile bomb = proj.GetComponent("BombProjectile") as BombProjectile;

            if(bomb!=null){
                bomb.groundHeight=transform.position.y-transform.localScale.y/2;
            }
            proj.shoot(false,speedOfProjectile,rangeOfWeapon+2);
        }
        else{
            Vector3 spawnPos = transform.position;
            spawnPos.z=player.transform.position.z;
            spawnPos.x-=0.5f;

            Projectile proj = Instantiate(projectile,spawnPos,projectile.transform.rotation) as Projectile;
            proj.shoot(true,speedOfProjectile,rangeOfWeapon+2);
        }
    }
    /// <summary>
    /// Disenganges the unit from combat and starts them moving towrads their original destination.
    /// The unit will begin searching for new targets and will switch to their longest ranged weapon.
    /// </summary>
    public void Disengage()
    {
        mAttackState = AttackState.kIdle;
        mMovementState = MovementState.kMoving;

        SwitchToWeapon(mWeapons.Count - 1); // longest range weapon
        this.collider2D.enabled = true;
    }
    // Use this for initialization
    protected override void Start()
    {
        base.Start ();
        movementState = MovementState.Rising;
        gunLine = GetComponent <LineRenderer> ();
        this.audios = GetComponent<AudioSource> ();

        body = GetComponent<Rigidbody> ();
    }
 // Update is called once per frame
 void Update()
 {
     if (currentMovementState == null)
     {
         currentMovementState = new Idle(this);
     }
     currentMovementState.Update();
     MoveState = currentMovementState.ToString().Replace("CharacterMovementController", "");
 }
Exemplo n.º 10
0
 public MoveRotate(MovementState movement, RotationState rotation, List<RoomItem> items, int delay, Room room, WiredHandler handler, uint itemID)
 {
     this.movement = movement;
     this.rotation = rotation;
     this.items = items;
     this.delay = delay;
     this.room = room;
     this.handler = handler;
     this.cycles = 0;
     this.itemID = itemID;
     this.isDisposed = false;
 }
Exemplo n.º 11
0
        public override void Update(GameTime gameTime)
        {
            if (CurrentMovementState != MovementState.None)
            {
                bool stopped = false;

                double movementAmount = (MovementSpeed * gameTime.ElapsedGameTime.TotalSeconds);

                TotalMovementAmount += movementAmount;

                if (TotalMovementAmount >= 32)
                {
                    movementAmount = movementAmount - (TotalMovementAmount - 32);
                    TotalMovementAmount = 0;
                    stopped = true;
                }

                if (CurrentMovementState == MovementState.North)
                {
                    _y -= movementAmount;
                }
                else if (CurrentMovementState == MovementState.East)
                {
                    _x += movementAmount;
                }
                if (CurrentMovementState == MovementState.South)
                {
                    _y += movementAmount;
                }
                if (CurrentMovementState == MovementState.West)
                {
                    _x -= movementAmount;
                }

                if (stopped)
                {
                    CurrentMovementState = MovementState.None;
                    this.Sprite.StopAnimate();
                }

            }

            if (ElementManager.GetIntersections(this, new List<Type>() { typeof(Car) }).Any())
            {
                // death routine
                this.X = 320;
                this.Y = 448;
            }

            base.Update(gameTime);
        }
Exemplo n.º 12
0
    void Awake()
    {
        // Refs
          //_pom = GetComponent<PoManager>();

          // Randomise a bit
          HoppingTime += HoppingTime * UnityEngine.Random.Range(-0.5f, 0.5f);
          HoppingForceRangeFromTo += HoppingForceRangeFromTo * (UnityEngine.Random.Range(-0.5f, 0.5f));

          // Ready to go
          _movementState = MovementState.Idle;
          _hopTimer = HoppingTime;
          _timeToDestinationTimer = MaxTimeToDestination;
    }
Exemplo n.º 13
0
    public override MovementState UpdateState(ref Vector3 velocity, ref Vector3 externalForces)
    {
        col = GetComponent<Collider2D>();

        //check to see if the tether has been thrown
        if (isThrown)
        {
            //check if temp exists, and if so, is it moving
            if (temp && !temp.Moving)
            {
                //find the angle between the player and the stopped weapon
                //then pull the player continuously towards the tether
                Vector2 pullDirection = temp.transform.position - player.transform.position;
                velocity = pullDirection * tetherForce;

                //check for collisions in the x  and y directions that the player is moving
                if ((controller.collisions.Left && direction.x < 0) || (controller.collisions.Right && direction.x > 0))
                {
                    velocity.x = 0;
                }
                if ((controller.collisions.Above && direction.y > 0) || (controller.collisions.Below && direction.x < 0))
                {
                    velocity.y = 0;
                }

                DecayExternalForces(ref externalForces);
                controller.Move(velocity * Time.deltaTime + externalForces * Time.deltaTime);
            }
            //If no on existing, exit the state
            if (!temp)
            {
                return checkState();
            }

            //otherwise update the state as it would if the tether wasn't thrown
            else
            {
                currentState = checkState();
                currentState = currentState.UpdateState(ref velocity, ref externalForces);
            }
        }
        //if not thrown, exit state
        else
        {
            return checkState();
        }

        timeLeft -= Time.deltaTime;
        return null;
    }
    // Update is called once per frame
    void Update()
    {
        //get axis input from player (W, A, S, and D keys/Arrow keys)
        float verticalAxis = Input.GetAxis("Vertical");
        float horizontalAxis = Input.GetAxis("Horizontal");

        //if there is any player input...
        if (verticalAxis != 0)
        {
            //if player input is negative on the horizontal axis (pressing A)...
            //AND the current turn angle is greater than our lowest blend threshold...
            if (horizontalAxis < 0 && currentTurnAngle > -3)
            {
                    currentTurnAngle -= turnIncrement;	//decrease the turn angle by turnIncrement
            }
            //if player input is positive on the horizontal axis (pressing D)...
            //AND the current turn angle is less than our highest blend threshold...
            else if (horizontalAxis > 0 && currentTurnAngle < 3)
            {
                currentTurnAngle += turnIncrement;		//increase the turn angle by turnIncrement
            }
            //if there is forward input, but no turn input...
            else
            {
                //if there is still turning on the negative axis...
                if (currentTurnAngle < 0)
                    currentTurnAngle += turnIncrement;	//decrease the turn angle until it reaches 0
                //if there is still turning on the positive axis...
                else if (currentTurnAngle > 0)
                    currentTurnAngle -= turnIncrement;	//decrease the turn angle until it reaches 0
            }

            //always set the player state to moving if there is any input
            currentMovementState = MovementState.Moving;
        }
        else	//default to idle if no input
        {
            currentTurnAngle = 0;	//resets the currentTurnAngle to 0 so that new idle position faces 'straight'
            currentMovementState = MovementState.Idle;	//set movement state to idle if no input
        }

        //send the current movement state to our character controller
        animController.SetInteger("MovementState", (int)currentMovementState);

        //send the current turn angle to our character controller
        animController.SetFloat("TurnDirection", currentTurnAngle);
    }
 void IHasSequentialStates.goToNextState()
 {
     MovementState nextState = MovementState.Destroy;
     switch (movementState) {
     case MovementState.Rising:
         nextState = MovementState.Hovering;
         break;
     case MovementState.Hovering:
         setTargetToPlayer();
         audios.Play();
         nextState = MovementState.Shooting;
         break;
     case MovementState.Shooting:
         nextState = MovementState.Destroy;
         break;
     default:
         nextState = MovementState.Destroy;
         break;
     }
     this.movementState = nextState;
 }
Exemplo n.º 16
0
 private void setState(string state)
 {
     switch(state)
     {
         case "none":
             {
                 movementState = MovementState.none;
                 break;
             }
         case "walk":
             {
                 movementState = MovementState.walk;
                 break;
             }
         case "traverse":
             {
                 movementState = MovementState.traverse;
                 break;
             }
     }
 }
    // Update is called once per frame
    void Update()
    {
        //get axis input from player (W, A, S, and D keys/Arrow keys)
        float verticalAxis = Input.GetAxis("Vertical");
        float horizontalAxis = Input.GetAxis("Horizontal");

        //get the forward-facing direction of the camera
        Vector3 cameraForward = mainCamera.TransformDirection(Vector3.forward);
        cameraForward.y = 0;	//set to 0 because of camera rotation on the X axis

        //get the right-facing direction of the camera
        Vector3 cameraRight = mainCamera.TransformDirection(Vector3.right);

        //determine the direction the player will face based on input and the camera's right and forward directions
        Vector3 targetDirection = horizontalAxis * cameraRight + verticalAxis * cameraForward;

        //normalize the direction the player should face
        Vector3 lookDirection = targetDirection.normalized;

        //rotate the player to face the correct direction ONLY if there is any player input
        if (lookDirection != Vector3.zero)
            transform.rotation = Quaternion.LookRotation(lookDirection);

        //if there is any player input...
        if (verticalAxis != 0 || horizontalAxis != 0)
        {
            //if the run modifier key is pressed
            if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
                currentMovementState = MovementState.Running;	//set movement state to running
            else	//if there is no movement modifier
                currentMovementState = MovementState.Walking;	//set movement state to walking
        }
        else	//default to idle if no input
        {
            currentMovementState = MovementState.Idle;	//set movement state to idle
        }

        //send the current movement state to the character controller
        animController.SetInteger("MovementState", (int)currentMovementState);
    }
Exemplo n.º 18
0
    // Use this for initialization
    void Start () 
	{
		// find spawnposition
		GameObject spawn = GameObject.Find ("SPAWN POSITION");
		if (spawn == null) {
			Debug.LogError ("NO SPAWN POSITION OBJECT! Spawn at Camera center");
			spawnPosition = Camera.main.transform;
		} else {
			spawnPosition = spawn.transform;
		}

		// find spawn emitter
		foreach (ParticleSystem p in GetComponentsInChildren<ParticleSystem>(false)) {
			if (p.name == "Spawn") {
				spawnEmitter = p;
				break;
			}
		}

		if (ground_layers == null)
			Debug.LogError ("GroundLayer not set in CharacterMovement component");

		if (water_layers == null)
			Debug.LogError ("WaterLayer not set in CharacterMovement component");
		
		// init
        currentState = MovementState.GROUNDED;
        _collider = GetComponent<BoxCollider2D>();
		_headCollider = GetComponent<EdgeCollider2D> ();
        rigidbody = GetComponent<Rigidbody2D>();
		foreach (Animator a in GetComponentsInChildren<Animator>()) {
			if(a.name == "IK")
				_anim = a;
		}
		if (_anim == null)
			Debug.LogError ("AnimationController from IK in CharacterMovement not found");
		// spawn player
		Spawn ();
    }
Exemplo n.º 19
0
 public override void Update()
 {
     base.Update();
     CurrentAnimation = idleAnimation;
     movement = MovementState.IdleState;
     Input();
     Console.WriteLine(X + "    " +Y);
     foreach (var obj in CheckCollisions())
     {
         if (obj.OtherHitBox == "Inner")
         {
             X = lastPlayerX;
             Y = lastPlayerY;
         }
         if(obj.OtherHitBox == "InnerDoor") //differenza tra startswhit e endswhit
         {
             Console.WriteLine("Inner");
             X = lastPlayerX;
             Y = lastPlayerY;
         }
     }
 }
    void Update()
    {
        float verticalAxis = Input.GetAxis("Vertical");
        float horizontalAxis = Input.GetAxis("Horizontal");

        if (verticalAxis != 0 || horizontalAxis != 0)
        {
            if (Input.GetKey(KeyCode.LeftShift))
                currentMovementState = MovementState.Running;
            else
                currentMovementState = MovementState.Walking;
        }
        else
            currentMovementState = MovementState.Idle;

        animController.SetInteger("MovementState", (int)currentMovementState);
        animController.SetFloat("VerticalAxis", verticalAxis);
        animController.SetFloat("HorizontalAxis", horizontalAxis);

        Vector3 camForward = Camera.main.transform.forward;
        camForward.y = 0;
        transform.LookAt(transform.position + camForward);
    }
Exemplo n.º 21
0
        protected override void Update()
        {
            if (PlayerCharacterEntity == null || !PlayerCharacterEntity.IsOwnerClient)
            {
                return;
            }

            base.Update();
            UpdateLookAtTarget();
            tempDeltaTime    = Time.deltaTime;
            turnTimeCounter += tempDeltaTime;

            // Hide construction UI
            if (CurrentBuildingEntity == null)
            {
                if (CacheUISceneGameplay.uiConstructBuilding.IsVisible())
                {
                    CacheUISceneGameplay.uiConstructBuilding.Hide();
                }
            }
            if (ActiveBuildingEntity == null)
            {
                if (CacheUISceneGameplay.uiCurrentBuilding.IsVisible())
                {
                    CacheUISceneGameplay.uiCurrentBuilding.Hide();
                }
            }

            IsBlockController = CacheUISceneGameplay.IsBlockController();
            // Lock cursor when not show UIs
            Cursor.lockState = !IsBlockController ? CursorLockMode.Locked : CursorLockMode.None;
            Cursor.visible   = IsBlockController;

            CacheGameplayCameraControls.updateRotation = !IsBlockController;
            // Clear selected entity
            SelectedEntity = null;

            // Update crosshair (with states from last update)
            if (isDoingAction)
            {
                UpdateCrosshair(currentCrosshairSetting, currentCrosshairSetting.expandPerFrameWhileAttacking);
            }
            else if (movementState.HasFlag(MovementState.Forward) ||
                     movementState.HasFlag(MovementState.Backward) ||
                     movementState.HasFlag(MovementState.Left) ||
                     movementState.HasFlag(MovementState.Right) ||
                     movementState.HasFlag(MovementState.IsJump))
            {
                UpdateCrosshair(currentCrosshairSetting, currentCrosshairSetting.expandPerFrameWhileMoving);
            }
            else
            {
                UpdateCrosshair(currentCrosshairSetting, -currentCrosshairSetting.shrinkPerFrame);
            }

            // Clear controlling states from last update
            isDoingAction = false;
            movementState = MovementState.None;
            UpdateActivatedWeaponAbility(tempDeltaTime);

            if (IsBlockController || GenericUtils.IsFocusInputField())
            {
                mustReleaseFireKey = false;
                PlayerCharacterEntity.KeyMovement(Vector3.zero, MovementState.None);
                DeactivateWeaponAbility();
                return;
            }

            // Find target character
            Ray     ray                = CacheGameplayCameraControls.CacheCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
            Vector3 forward            = CacheGameplayCameraControls.CacheCameraTransform.forward;
            Vector3 right              = CacheGameplayCameraControls.CacheCameraTransform.right;
            float   distanceFromOrigin = Vector3.Distance(ray.origin, PlayerCharacterEntity.CacheTransform.position);
            float   aimDistance        = distanceFromOrigin;

            // Calculating aim distance, also read attack inputs here
            // Attack inputs will be used to calculate attack distance
            if (CurrentBuildingEntity == null)
            {
                // Attack with right hand weapon
                tempPressAttackRight = InputManager.GetButton("Fire1");
                if (weaponAbility == null && leftHandWeapon != null)
                {
                    // Attack with left hand weapon if left hand weapon not empty
                    tempPressAttackLeft = InputManager.GetButton("Fire2");
                }
                else if (weaponAbility != null)
                {
                    // Use weapon ability if it can
                    tempPressWeaponAbility = InputManager.GetButtonDown("Fire2");
                }
                // Is left hand attack when not attacking with right hand
                // So priority is right > left
                isLeftHandAttacking = !tempPressAttackRight && tempPressAttackLeft;

                // Calculate aim distance by skill or weapon
                if (queueSkill != null && queueSkill.IsAttack())
                {
                    // Increase aim distance by skill attack distance
                    aimDistance += PlayerCharacterEntity.GetSkillAttackDistance(queueSkill, isLeftHandAttacking);
                }
                else
                {
                    // Increase aim distance by attack distance
                    aimDistance += PlayerCharacterEntity.GetAttackDistance(isLeftHandAttacking);
                }
            }
            actionLookDirection   = aimPosition = ray.origin + ray.direction * aimDistance;
            actionLookDirection.y = PlayerCharacterEntity.CacheTransform.position.y;
            actionLookDirection   = actionLookDirection - PlayerCharacterEntity.CacheTransform.position;
            actionLookDirection.Normalize();
            // Prepare variables to find nearest raycasted hit point
            float tempDistance;
            float tempNearestDistance = float.MaxValue;

            // Find for enemy character
            if (CurrentBuildingEntity == null)
            {
                int tempCount = Physics.RaycastNonAlloc(ray, raycasts, aimDistance);
                for (int tempCounter = 0; tempCounter < tempCount; ++tempCounter)
                {
                    tempHitInfo = raycasts[tempCounter];

                    tempEntity = tempHitInfo.collider.GetComponent <BaseGameEntity>();
                    // Find building entity from building material
                    if (tempEntity == null)
                    {
                        tempBuildingMaterial = tempHitInfo.collider.GetComponent <BuildingMaterial>();
                        if (tempBuildingMaterial != null)
                        {
                            tempEntity = tempBuildingMaterial.buildingEntity;
                        }
                    }
                    if (tempEntity == null || tempEntity == PlayerCharacterEntity)
                    {
                        continue;
                    }
                    // Target must be alive
                    if (tempEntity is IDamageableEntity && (tempEntity as IDamageableEntity).IsDead())
                    {
                        continue;
                    }
                    // Target must be in front of player character
                    if (!PlayerCharacterEntity.IsPositionInFov(15f, tempEntity.CacheTransform.position, forward))
                    {
                        continue;
                    }
                    // Set aim position and found target
                    tempDistance = Vector3.Distance(CacheGameplayCameraControls.CacheCameraTransform.position, tempHitInfo.point);
                    if (tempDistance < tempNearestDistance)
                    {
                        tempNearestDistance = tempDistance;
                        aimPosition         = tempHitInfo.point;
                        if (tempEntity != null)
                        {
                            SelectedEntity = tempEntity;
                        }
                    }
                }
                // Show target hp/mp
                CacheUISceneGameplay.SetTargetEntity(SelectedEntity);
            }
            else
            {
                // Clear area before next find
                CurrentBuildingEntity.buildingArea = null;
                // Find for position to construction building
                bool         foundSnapBuildPosition = false;
                int          tempCount    = Physics.RaycastNonAlloc(ray, raycasts, gameInstance.buildDistance);
                BuildingArea buildingArea = null;
                for (int tempCounter = 0; tempCounter < tempCount; ++tempCounter)
                {
                    tempHitInfo = raycasts[tempCounter];
                    tempEntity  = tempHitInfo.collider.GetComponentInParent <BuildingEntity>();
                    if (tempEntity == null || tempEntity == CurrentBuildingEntity)
                    {
                        continue;
                    }

                    buildingArea = tempHitInfo.transform.GetComponent <BuildingArea>();
                    if (buildingArea == null ||
                        (buildingArea.buildingEntity != null && buildingArea.buildingEntity == CurrentBuildingEntity) ||
                        !CurrentBuildingEntity.buildingType.Equals(buildingArea.buildingType))
                    {
                        continue;
                    }

                    // Set aim position
                    tempDistance = Vector3.Distance(CacheGameplayCameraControls.CacheCameraTransform.position, tempHitInfo.point);
                    if (tempDistance < tempNearestDistance)
                    {
                        aimPosition = tempHitInfo.point;
                        CurrentBuildingEntity.buildingArea = buildingArea;
                        if (buildingArea.snapBuildingObject)
                        {
                            foundSnapBuildPosition = true;
                            break;
                        }
                    }
                }
                // Update building position
                if (!foundSnapBuildPosition)
                {
                    CurrentBuildingEntity.CacheTransform.position = aimPosition;
                    // Rotate to camera
                    Vector3 direction = (aimPosition - CacheGameplayCameraControls.CacheCameraTransform.position).normalized;
                    direction.y = 0;
                    CurrentBuildingEntity.transform.rotation = Quaternion.LookRotation(direction);
                }
            }

            // If mobile platforms, don't receive input raw to make it smooth
            bool    raw           = !InputManager.useMobileInputOnNonMobile && !Application.isMobilePlatform;
            Vector3 moveDirection = Vector3.zero;

            forward.y = 0f;
            right.y   = 0f;
            forward.Normalize();
            right.Normalize();
            float inputV = InputManager.GetAxis("Vertical", raw);
            float inputH = InputManager.GetAxis("Horizontal", raw);

            moveDirection += forward * inputV;
            moveDirection += right * inputH;
            // Set movement state by inputs
            switch (mode)
            {
            case Mode.Adventure:
                if (inputV > 0.5f || inputV < -0.5f || inputH > 0.5f || inputH < -0.5f)
                {
                    movementState = MovementState.Forward;
                }
                moveLookDirection = moveDirection;
                break;

            case Mode.Combat:
                moveDirection += forward * inputV;
                moveDirection += right * inputH;
                if (inputV > 0.5f)
                {
                    movementState |= MovementState.Forward;
                }
                else if (inputV < -0.5f)
                {
                    movementState |= MovementState.Backward;
                }
                if (inputH > 0.5f)
                {
                    movementState |= MovementState.Right;
                }
                else if (inputH < -0.5f)
                {
                    movementState |= MovementState.Left;
                }
                moveLookDirection = actionLookDirection;
                break;
            }

            // normalize input if it exceeds 1 in combined length:
            if (moveDirection.sqrMagnitude > 1)
            {
                moveDirection.Normalize();
            }

            if (CurrentBuildingEntity != null)
            {
                mustReleaseFireKey = false;
                // Building
                tempPressAttackRight = InputManager.GetButtonUp("Fire1");
                if (tempPressAttackRight)
                {
                    if (showConfirmConstructionUI)
                    {
                        // Show confirm UI
                        if (!CacheUISceneGameplay.uiConstructBuilding.IsVisible())
                        {
                            CacheUISceneGameplay.uiConstructBuilding.Show();
                        }
                    }
                    else
                    {
                        // Build when click
                        ConfirmBuild();
                    }
                }
                else
                {
                    // Update move direction
                    if (moveDirection.magnitude != 0f)
                    {
                        targetLookDirection = moveLookDirection;
                    }
                }
            }
            else
            {
                // Have to release fire key, then check press fire key later on next frame
                if (mustReleaseFireKey)
                {
                    tempPressAttackRight = false;
                    tempPressAttackLeft  = false;
                    if (!isLeftHandAttacking &&
                        (InputManager.GetButtonUp("Fire1") ||
                         !InputManager.GetButton("Fire1")))
                    {
                        mustReleaseFireKey = false;
                    }
                    if (isLeftHandAttacking &&
                        (InputManager.GetButtonUp("Fire2") ||
                         !InputManager.GetButton("Fire2")))
                    {
                        mustReleaseFireKey = false;
                    }
                }
                // Not building so it is attacking
                tempPressActivate   = InputManager.GetButtonDown("Activate");
                tempPressPickupItem = InputManager.GetButtonDown("PickUpItem");
                tempPressReload     = InputManager.GetButtonDown("Reload");
                if (queueSkill != null || tempPressAttackRight || tempPressAttackLeft || tempPressActivate || PlayerCharacterEntity.IsPlayingActionAnimation())
                {
                    // Find forward character / npc / building / warp entity from camera center
                    targetPlayer   = null;
                    targetNpc      = null;
                    targetBuilding = null;
                    if (tempPressActivate && !tempPressAttackRight && !tempPressAttackLeft)
                    {
                        if (SelectedEntity is BasePlayerCharacterEntity)
                        {
                            targetPlayer = SelectedEntity as BasePlayerCharacterEntity;
                        }
                        if (SelectedEntity is NpcEntity)
                        {
                            targetNpc = SelectedEntity as NpcEntity;
                        }
                        if (SelectedEntity is BuildingEntity)
                        {
                            targetBuilding = SelectedEntity as BuildingEntity;
                        }
                    }
                    // While attacking turn to camera forward
                    tempCalculateAngle = Vector3.Angle(PlayerCharacterEntity.CacheTransform.forward, actionLookDirection);
                    if (tempCalculateAngle > 15f)
                    {
                        if (queueSkill != null && queueSkill.IsAttack())
                        {
                            turningState = TurningState.UseSkill;
                        }
                        else if (tempPressAttackRight || tempPressAttackLeft)
                        {
                            turningState = TurningState.Attack;
                        }
                        else if (tempPressActivate)
                        {
                            turningState = TurningState.Activate;
                        }
                        turnTimeCounter     = ((180f - tempCalculateAngle) / 180f) * turnToTargetDuration;
                        targetLookDirection = actionLookDirection;
                        // Set movement state by inputs
                        if (inputV > 0.5f)
                        {
                            movementState |= MovementState.Forward;
                        }
                        else if (inputV < -0.5f)
                        {
                            movementState |= MovementState.Backward;
                        }
                        if (inputH > 0.5f)
                        {
                            movementState |= MovementState.Right;
                        }
                        else if (inputH < -0.5f)
                        {
                            movementState |= MovementState.Left;
                        }
                    }
                    else
                    {
                        // Attack immediately if character already look at target
                        if (queueSkill != null && queueSkill.IsAttack())
                        {
                            UseSkill(isLeftHandAttacking, aimPosition);
                            isDoingAction = true;
                        }
                        else if (tempPressAttackRight || tempPressAttackLeft)
                        {
                            Attack(isLeftHandAttacking);
                            isDoingAction = true;
                        }
                        else if (tempPressActivate)
                        {
                            Activate();
                        }
                    }
                    // If skill is not attack skill, use it immediately
                    if (queueSkill != null && !queueSkill.IsAttack())
                    {
                        UseSkill(false);
                    }
                    queueSkill = null;
                }
                else if (tempPressWeaponAbility)
                {
                    switch (weaponAbilityState)
                    {
                    case WeaponAbilityState.Activated:
                    case WeaponAbilityState.Activating:
                        DeactivateWeaponAbility();
                        break;

                    case WeaponAbilityState.Deactivated:
                    case WeaponAbilityState.Deactivating:
                        ActivateWeaponAbility();
                        break;
                    }
                }
                else if (tempPressPickupItem)
                {
                    // Find for item to pick up
                    if (SelectedEntity != null)
                    {
                        PlayerCharacterEntity.RequestPickupItem((SelectedEntity as ItemDropEntity).ObjectId);
                    }
                }
                else if (tempPressReload)
                {
                    // Reload ammo when press the button
                    ReloadAmmo();
                }
                else
                {
                    // Update move direction
                    if (moveDirection.magnitude != 0f)
                    {
                        targetLookDirection = moveLookDirection;
                    }
                }
                // Setup releasing state
                if (tempPressAttackRight && rightHandWeapon != null && rightHandWeapon.fireType == FireType.SingleFire)
                {
                    // The weapon's fire mode is single fire, so player have to release fire key for next fire
                    mustReleaseFireKey = true;
                }
                else if (tempPressAttackLeft && leftHandWeapon != null && leftHandWeapon.fireType == FireType.SingleFire)
                {
                    // The weapon's fire mode is single fire, so player have to release fire key for next fire
                    mustReleaseFireKey = true;
                }
                // Auto reload
                if (!tempPressAttackRight && !tempPressAttackLeft && !tempPressReload &&
                    (PlayerCharacterEntity.EquipWeapons.rightHand.IsAmmoEmpty() ||
                     PlayerCharacterEntity.EquipWeapons.leftHand.IsAmmoEmpty()))
                {
                    // Reload ammo when empty and not press any keys
                    ReloadAmmo();
                }
            }
            SetAimPosition(aimPosition);

            // Hide Npc UIs when move
            if (moveDirection.magnitude != 0f)
            {
                HideNpcDialogs();
                PlayerCharacterEntity.StopMove();
                PlayerCharacterEntity.SetTargetEntity(null);
            }
            // If jumping add jump state
            if (InputManager.GetButtonDown("Jump"))
            {
                movementState |= MovementState.IsJump;
            }

            PlayerCharacterEntity.KeyMovement(moveDirection, movementState);
        }
Exemplo n.º 22
0
 void RunOutOfGas()
 {
     currMovementState = MovementState.OutOfGas;
     Camera.main.GetComponent <HoverFollowCam> ().enabled = false;
 }
        protected void UpdatePosition(float timeIncrement = 0, bool catchOutOfRange = false)
        {
//			this.currentTime+=timeIncrement;
            this.currentFractionalIndex += (timeIncrement / this.updateInterval);
//			currentIndex = (int) (this.currentTime/this.updateInterval);
            currentIndex = (int)this.currentFractionalIndex;
            if (catchOutOfRange && currentIndex >= this.resetIndex)
            {
                this.currentIndex = this.resetIndex - 1;
            }

            float percent = GetPathPercent();

            //Calculate up vector
            if (this.lerpUpVector)
            {
                float upVectorPercent = percent / endUpVectorPercent;
                upVectorPercent = Mathf.Clamp01(upVectorPercent);

                this.upVector = Vector3.Lerp(startUpVector, endUpVector, upVectorPercent);
            }



            if (pathPercentUpdated != null)
            {
                pathPercentUpdated(percent);
            }

            if (this.currentIndex >= this.resetIndex)
            {
                if (this.autoLoop)
                {
                    this.currentFractionalIndex = 0;
//					this.currentTime = 0;
                    this.currentIndex = 0;
                }
                else
                {
                    if (this.pathCompleted != null)
                    {
                        this.pathCompleted();
                    }

                    this.myMovementState = MovementState.Idle;
                    return;
                }
            }

            this.transform.position = smoothedPath [currentIndex];

            int lookAtIndex = this.currentIndex + this.lookOffset;

            if (this.closedLoop)
            {
                lookAtIndex %= pathLength;
            }

            if (shouldLookRotate)
            {
                this.transform.rotation = GetRotation(currentIndex, lookAtIndex);
            }
        }
Exemplo n.º 24
0
 private void OnCompleteMoveDown()
 {
     rotationSpeed    = 2.5f;
     curMovementState = MovementState.Normal;
     curRadiusState   = RadiusState.DecRadius;
 }
Exemplo n.º 25
0
 void UnlockFromTarget()
 {
     currMovementState = MovementState.Drive;
     EndTarget ();
     isTargeting = false;
     Camera.main.GetComponent<HoverFollowCam> ().thisCameraMode = HoverFollowCam.CameraMode.normalMode;
 }
Exemplo n.º 26
0
    void Update()
    {
        Health health = GetComponent <Health>();

        if (health.dead)
        {
            camera.active = false;
            return;
        }

        UpdateLook();

        MovementState prevMovementState = movementState;

        bool switchWeapon          = false;
        int  prevActiveWeaponIndex = activeWeaponIndex;

        if (canPickupWeapon &&
            // @GACK: really need a better way to know if you are trying to pick up a weapon when you have
            // a weapon already
            (activeWeaponIndex < 0 || candidateWeapon != weapons[activeWeaponIndex]))
        {
            if (ButtonPressed("Reload", localPlayerNum))
            {
                // @NOTE: when we pickup a weapon we havent left the trigger
                // so we want to manually deactivate the prompt message here
                pickupTextPrompt.active = false;

                if (weapons[0] == null)
                {
                    weapons[0]        = candidateWeapon;
                    activeWeaponIndex = 0;
                }
                else if (weapons[1] == null)
                {
                    weapons[1]        = candidateWeapon;
                    activeWeaponIndex = 1;
                }
                else
                {
                    Rigidbody oldBody = weapons[activeWeaponIndex].GetComponent <Rigidbody>();
                    oldBody.isKinematic = false;

                    Gun oldGun = weapons[activeWeaponIndex].GetComponent <Gun>();
                    oldGun.SetDroppedPosition();
                    oldGun.owned = false;

                    weapons[activeWeaponIndex] = candidateWeapon;
                }

                SetActiveGun(candidateWeapon);
            }
        }

        if (ButtonPressed("Switch", localPlayerNum))
        {
            int attemptedWeaponIndex = (activeWeaponIndex + 1) % 2;

            GameObject nextWeapon = weapons[attemptedWeaponIndex];

            if (nextWeapon != null)
            {
                nextWeapon.transform.SetParent(weaponHand.transform);

                Gun gun = nextWeapon.GetComponent <Gun>();
                gun.SetHeldPosition();

                Image image = reticule.GetComponent <Image>();
                image.sprite = gun.reticule;

                activeWeaponIndex = attemptedWeaponIndex;
            }
        }

        if (prevActiveWeaponIndex >= 0 && activeWeaponIndex != prevActiveWeaponIndex)
        {
            GameObject prevWeapon = weapons[prevActiveWeaponIndex];

            SetInactiveGun(prevWeapon);
        }

        if (activeWeaponIndex >= 0)
        {
            GameObject activeWeapon = weapons[activeWeaponIndex];
            Gun        gun          = activeWeapon.GetComponent <Gun>();

            Debug.DrawRay(gunRay.origin, gunRay.direction, Color.red);

            if (GetAxis("Fire", localPlayerNum) < -0.5f)
            {
                // @GACK: its real gross to set this in the controller and not in the gun itself
                // Why do I feel like Unity is making me do this!!!!!?????
                bool wasTriggerHeld = gun.triggerHeld;

                if (gun.automatic)
                {
                    if (gun.Fire(this.gameObject, gunRay, camera.transform.rotation))
                    {
                        timeFired = Time.time;
                        maxRecoil = gun.recoil;
                    }

                    gun.triggerHeld = true;
                }
                else
                {
                    if (!wasTriggerHeld)
                    {
                        if (gun.Fire(this.gameObject, gunRay, camera.transform.rotation))
                        {
                            timeFired = Time.time;
                            maxRecoil = gun.recoil;
                        }
                        gun.triggerHeld = true;
                    }
                }
            }
            else
            {
                gun.triggerHeld = false;
            }

            // @TODO: only if we havent picked up a weapon!
            if (ButtonPressed("Reload", localPlayerNum))
            {
                gun.Reload();
            }
        }



        Vector2 direction = new Vector2(GetAxis("MoveX", localPlayerNum), -GetAxis("MoveY", localPlayerNum));

        Vector3 force = new Vector3();

        // @TODO: stop moving when there is no input

        RaycastHit hit;
        Vector3    rayDir  = new Vector3(0, -1, 0);
        Vector3    rayOrig = this.transform.position;
        Ray        ray     = new Ray(rayOrig, rayDir);

        Debug.DrawRay(rayOrig, rayDir, Color.red);

        if (characterController.isGrounded)
        {
            if (movementState == MovementState.Falling)
            {
                float fallingSpeed = Math.Abs(velocity.y);

                Debug.Log(fallingSpeed);

                if (fallingSpeed > 30)
                {
                    float maxFallingSpeed = 50;

                    float diff = maxFallingSpeed - fallingSpeed;
                    if (diff < 0)
                    {
                        diff = 0;
                    }

                    float t = diff / maxFallingSpeed;

                    int shieldDamage = (int)(80 - (80 * t));
                    int damage       = (int)(30 - (30 * t));

                    health.DamagePlayer(damage, shieldDamage, false, 0.0f);
                }
            }

            movementState = MovementState.OnGround;
            velocity      = Vector3.zero;
        }

        if (movementState == MovementState.Crouching)
        {
            standingHitboxes.active  = false;
            crouchingHitboxes.active = true;
        }
        else
        {
            standingHitboxes.active  = true;
            crouchingHitboxes.active = false;
        }

        // Debug.Log(characterController.isGrounded);
        // Debug.Log(movementState);

        if (movementState == MovementState.OnGround)
        {
            canBoost = true;
            //Vector3 surfaceNormal = hit.normal;

            //Debug.DrawLine(hit.point, hit.point + surfaceNormal, Color.blue);

            // Vector3 playerForward = this.transform.rotation * Vector3.forward;

            // Vector3 groundX = Vector3.Cross(surfaceNormal, playerForward).normalized;
            // Vector3 groundZ = Vector3.Cross(groundX, surfaceNormal).normalized;

            // Debug.DrawLine(this.transform.position, this.transform.position + groundX, Color.red);
            // Debug.DrawLine(this.transform.position, this.transform.position + groundZ, Color.red);

            force = new Vector3(speed * direction.x, 0, speed * direction.y);
            force = this.transform.rotation * force;

            movementState = MovementState.OnGround;
        }


        if (!characterController.isGrounded &&
            movementState != MovementState.Jump && movementState != MovementState.Boost)
        {
            movementState = MovementState.Falling;
        }

        if (movementState == MovementState.OnGround)
        {
            bool jumped = ButtonPressed("Jump", localPlayerNum);

            if (jumped)
            {
                force         = Vector3.zero;
                timeSinceJump = 0.0f;

                movementState = MovementState.Jump;

                velocity = Vector3.zero;
            }
        }

        // @TODO: make sure we havent jumped this same frame, because our button press is still true
        if (canBoost && (movementState == MovementState.Jump ||
                         movementState == MovementState.Falling))
        {
            if (ButtonPressed("Jump", localPlayerNum) && prevMovementState != MovementState.OnGround)
            {
                canBoost       = false;
                movementState  = MovementState.Boost;
                timeSinceBoost = 0;

                ParticleSystem particles = boostParticles.GetComponent <ParticleSystem>();
                particles.Play();
            }
        }

        if (movementState == MovementState.Jump)
        {
            timeSinceJump += Time.deltaTime;

            velocity.x = 0;
            velocity.z = 0;
            force      = new Vector3(horzAirSpeed * direction.x, 0, vertAirSpeed * direction.y);
            force      = this.transform.rotation * force;

            force = force + CalculateJumpForce(timeSinceJump);

            // @TODO: this is too small a hop
            if (timeSinceJump >= jumpDuration || !ButtonHeld("Jump", localPlayerNum))
            {
                movementState = MovementState.Falling;
            }
        }

        if (movementState == MovementState.Boost)
        {
            timeSinceBoost += Time.deltaTime;

            velocity.x = 0;
            velocity.z = 0;

            // @TODO: look at the direction when you first boost, apply a large force along that direction
            // for some duration, then return to normal air control

            force = new Vector3(horzBoostSpeed * direction.x, 0, vertBoostSpeed * direction.y);
            force = this.transform.rotation * force;

            force = force + (CalculateBoostForce(timeSinceBoost));

            if (timeSinceBoost >= boostDuration)
            {
                movementState = MovementState.Falling;
            }
        }

        if (movementState == MovementState.Falling)
        {
            velocity.x = 0;
            velocity.z = 0;

            force = new Vector3(horzAirSpeed * direction.x, 0, vertAirSpeed * direction.y);
            force = this.transform.rotation * force;
        }


        //if (!characterController.isGrounded) {
        Vector3 gravityForce = (-Vector3.up * gravity);

        force = force + gravityForce;
        //}

        velocity += force * Time.deltaTime;
        //Debug.Log(velocity);

        characterController.Move(velocity * Time.deltaTime);

        float timeSinceFired = Time.time - timeFired;
        float recoilDuration = 0.15f;

        if (timeSinceFired < recoilDuration)
        {
            float t          = timeSinceFired / recoilDuration;
            float currRecoil = Mathf.Lerp(maxRecoil, 0.0f, t);
            RecoilLook(currRecoil);
        }
    }
Exemplo n.º 27
0
    private void ProcessAttack()
    {
        float         xAxisInput     = GetXAxisInput();
        float         yAxisInput     = GetYAxisInput();
        bool          attackInput    = GetAttackInput();
        MovementState movementState  = playerState.GetCurrentMovementState();
        ActiveState   activeState    = playerState.GetCurrentActiveState();
        int           movementFrames = playerState.GetCurMovementStateFrame();

        if (attackInput)
        {
            // Ground jab
            if (xAxisInput == 0 && yAxisInput == 0)
            {
                if (movementState == MovementState.Idle &&
                    movementState != MovementState.Attack)
                {
                    SetPlayerAttackState(AttackID.Jab01);
                }
                // Second jab (when jab 1 is in progress and you input attack input)
                else if (movementState == MovementState.Attack &&
                         activeState == ActiveState.Active &&
                         _curAttackId == (int)AttackID.Jab01)
                {
                    SetPlayerAttackState(AttackID.Jab02);
                }
                // Third jab
                else if (movementState == MovementState.Attack &&
                         activeState == ActiveState.Active &&
                         _curAttackId == (int)AttackID.Jab02)
                {
                    SetPlayerAttackState(AttackID.Jab03);
                }
            }
            else if (xAxisInput != 0 || yAxisInput != 0)
            {
                // Forward tilt attack
                if (_isOnGround && xAxisInput != 0 &&
                    (movementState == MovementState.Walk ||
                     movementState != MovementState.Idle))
                {
                    SetPlayerAttackState(AttackID.FTilt01);
                }
                // Up tilt attack
                else if (_isOnGround && yAxisInput > 0 &&
                         (movementState == MovementState.Walk ||
                          movementState == MovementState.Idle))
                {
                    SetPlayerAttackState(AttackID.UTilt01);
                }
                // Down tilt attack
                else if (_isOnGround && yAxisInput < 0 &&
                         (movementState == MovementState.Walk ||
                          movementState == MovementState.Idle))
                {
                    SetPlayerAttackState(AttackID.DTilt01);
                }
            }

            // Nair (Neutral air input)
            if (xAxisInput == 0 && yAxisInput == 0 &&
                (attackInput && (movementState == MovementState.Jump && movementState != MovementState.Attack) ||
                 attackInput && (movementState == MovementState.Fall && movementState != MovementState.Attack)))
            {
                SetPlayerAttackState(AttackID.Nair01);
            }
            // Fair (Forward air)
            else if (xAxisInput != 0 &&
                     (attackInput && (movementState == MovementState.Jump && movementState != MovementState.Attack) ||
                      attackInput && (movementState == MovementState.Fall && movementState != MovementState.Attack)))
            {
                SetPlayerAttackState(AttackID.Fair01);
            }
            // Uair (Forward air)
            else if (xAxisInput == 0 && yAxisInput > 0 &&
                     (attackInput && (movementState == MovementState.Jump && movementState != MovementState.Attack) ||
                      attackInput && (movementState == MovementState.Fall && movementState != MovementState.Attack)))
            {
                SetPlayerAttackState(AttackID.Uair01);
            }
            // Dair (Forward air)
            else if (xAxisInput == 0 && yAxisInput < 0 &&
                     (attackInput && (movementState == MovementState.Jump && movementState != MovementState.Attack) ||
                      attackInput && (movementState == MovementState.Fall && movementState != MovementState.Attack)))
            {
                SetPlayerAttackState(AttackID.Dair01);
            }
        }
        //
        if (movementState == MovementState.Attack)
        {
            ProcessAttack(_frameData.attacks[_curAttackId]);
        }
        if (movementState == MovementState.Hit)
        {
            ProcessMovementStateFrames(MovementState.Hit, _frameData.hit, MovementState.Idle);
        }
    }
Exemplo n.º 28
0
        internal void RefreshMovementCache()
        {
            // If we aren't in the game of a world is loading, don't do anything yet
                     if (!ZetaDia.IsInGame||ZetaDia.IsLoadingWorld)
                          return;

                     if (DateTime.Now.Subtract(LastUpdatedMovementData).TotalMilliseconds>150)
                     {
                          LastUpdatedMovementData=DateTime.Now;

                          //These vars are used to accuratly predict what the bot is doing (Melee Movement/Combat)
                          using (ZetaDia.Memory.AcquireFrame())
                          {
                                try
                                {
                                     ActorMovement botMovement=ZetaDia.Me.Movement;
                                     isMoving=botMovement.IsMoving;
                                     curSpeedXY=botMovement.SpeedXY;
                                     curRotation=botMovement.Rotation;
                                     curMoveState=botMovement.MovementState;
                                } catch
                                {

                                }
                          }
                     }
        }
Exemplo n.º 29
0
        private void Move(MovementState movementState, GameTime gameTime)
        {
            float movementAmount = (float)(MovementSpeed * gameTime.ElapsedGameTime.TotalSeconds);

              if(movementState == MovementState.North)
              {
            this.Position.Y -= movementAmount;
              }
              else if(movementState == MovementState.East)
              {
            this.Position.X += movementAmount;
              }
              if(movementState == MovementState.South)
              {
            this.Position.Y += movementAmount;
              }
              if(movementState == MovementState.West)
              {
            this.Position.X -= movementAmount;
              }
        }
Exemplo n.º 30
0
 public void TeleportTo(Vector3 position)
 {
     movementState = MovementState.Idle;
     this.position = position;
 }
Exemplo n.º 31
0
 protected void DamagePhysics(Vector3 newSpeed, bool outOfHealth)
 {
     currentState = outOfHealth ? MovementState.DYING : MovementState.DAMAGED;
     timerStart   = Time.time;
     currentSpeed = newSpeed;
 }
Exemplo n.º 32
0
	void SetCurrentState(MovementState state) {
		currentState = state;
		lastStateChange = Time.time;
	}
Exemplo n.º 33
0
    // Update is called once per frame
    void Update()
    {
        Vector3 direction;
        float   distanceToTravel;

        //Debug.Log("Current State: " + currentState);

        switch (currentState)
        {
        case MovementState.Forward:
            direction        = travelDistance.normalized;
            distanceToTravel = speed * Time.deltaTime * PlayerControllerWSAD.gameTimeScale;
            transform.Translate(direction * distanceToTravel);

            distanceTraveled += distanceToTravel;

            if (distanceTraveled >= travelDistance.magnitude)
            {
                currentState  = MovementState.Waiting;
                previousState = MovementState.Forward;
                waitTimer     = waitDuration;
            }
            break;

        case MovementState.Back:
            direction        = -travelDistance.normalized;
            distanceToTravel = speed * Time.deltaTime * PlayerControllerWSAD.gameTimeScale;
            transform.Translate(direction * distanceToTravel);

            distanceTraveled += distanceToTravel;

            if (distanceTraveled >= travelDistance.magnitude)
            {
                currentState  = MovementState.Waiting;
                previousState = MovementState.Back;
                waitTimer     = waitDuration;
            }
            break;

        case MovementState.Waiting:

            waitTimer -= Time.deltaTime * PlayerControllerWSAD.gameTimeScale;
            if (waitTimer <= 0)
            {
                distanceTraveled = 0;


                if (previousState == MovementState.Forward)
                {
                    currentState = MovementState.Back;
                }
                else
                {
                    currentState = MovementState.Forward;
                }
            }
            break;

        default:
            break;
        }
    }
Exemplo n.º 34
0
 // Start is called before the first frame update
 void Start()
 {
     currentState = MovementState.Forward;
     initialPos   = transform.position;
     targetPos    = initialPos + travelDistance;
 }
Exemplo n.º 35
0
    //Wander state
    IEnumerator MMovingState()
    {
        while (movementState == MovementState.MMoving)
        {
            //Wander code... Create a random angle and convert it to radians
            float randomAngle = (float)(3.14/180)*Random.Range(0,360);
            //Normalize direction vector, as we will be using it to calculate where we place the circle
            Vector3 tempV = agent.velocity;
            Vector3.Normalize (tempV);
            //Using our relative position, 5 units in front of us. Use the generated angle to find the point on the circle that we want to go to
            agent.destination =  transform.position + tempV * 3 + new Vector3(Mathf.Cos (randomAngle)*3,0,Mathf.Sin (randomAngle)*3);
            //Check to see if we are within the arena bounds, if not, push our projected vector back inside
            if(agent.destination.x > 24)
                agent.destination = agent.destination + new Vector3(-7,0,0);
            if(agent.destination.x < -24)
                agent.destination = agent.destination + new Vector3(7,0,0);
            if(agent.destination.z > 24)
                agent.destination = agent.destination + new Vector3(0,0,-7);
            if(agent.destination.z < -24)
                agent.destination = agent.destination + new Vector3(0,0,7);

            if(seesPlayer)
            {
                agent.destination = transform.position;
                movementState = MovementState.MIdle;
            }
            yield return 0;
        }
                        NextMovementState ();
    }
Exemplo n.º 36
0
 public abstract void KeyMovement(Vector3 moveDirection, MovementState moveState);
Exemplo n.º 37
0
 void LockOnToTarget()
 {
     currMovementState = MovementState.Target;
     BeginTarget ();
     isTargeting = true;
     Camera.main.GetComponent<HoverFollowCam> ().thisCameraMode = HoverFollowCam.CameraMode.targetMode;
 }
Exemplo n.º 38
0
 void SetState(MovementState state)
 {
     m_State = state;
 }
Exemplo n.º 39
0
        public static void HandleSave(GameClient Session, int itemID, Room room, ClientPacket clientMessage)
        {
            Item roomItem = room.GetRoomItemHandler().GetItem(itemID);

            if (roomItem == null)
            {
                return;
            }
            if (roomItem.WiredHandler != null)
            {
                roomItem.WiredHandler.Dispose();
                roomItem.WiredHandler = null;
            }

            switch (roomItem.GetBaseItem().InteractionType)
            {
                #region Trigger
            case InteractionType.triggertimer:
                clientMessage.PopInt();
                int cycleCount = clientMessage.PopInt();
                HandleTriggerSave(new Timer(roomItem, room.GetWiredHandler(), cycleCount, room.GetGameManager()), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.triggerroomenter:
                clientMessage.PopInt();
                string userName = clientMessage.PopString();
                HandleTriggerSave(new EntersRoom(roomItem, room.GetWiredHandler(), room.GetRoomUserManager(), !string.IsNullOrEmpty(userName), userName), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.triggercollision:
                HandleTriggerSave(new Collision(roomItem, room.GetWiredHandler(), room.GetRoomUserManager()), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.triggergameend:
                HandleTriggerSave(new GameEnds(roomItem, room.GetWiredHandler(), room.GetGameManager()), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.triggergamestart:
                HandleTriggerSave(new GameStarts(roomItem, room.GetWiredHandler(), room.GetGameManager()), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.triggerrepeater:
                clientMessage.PopInt();
                int cyclesRequired = clientMessage.PopInt();
                HandleTriggerSave(new Repeater(room.GetWiredHandler(), roomItem, cyclesRequired), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.triggerrepeaterlong:
                clientMessage.PopInt();
                int cyclesRequiredlong = clientMessage.PopInt();
                HandleTriggerSave(new Repeaterlong(room.GetWiredHandler(), roomItem, cyclesRequiredlong), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.triggeronusersay:
                clientMessage.PopInt();
                bool   isOwnerOnly    = clientMessage.PopInt() == 1;
                string triggerMessage = clientMessage.PopString();
                HandleTriggerSave(new UserSays(roomItem, room.GetWiredHandler(), isOwnerOnly, triggerMessage, room), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.triggercommand:
                HandleTriggerSave(new UserCommand(roomItem, room.GetWiredHandler(), room), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_trg_bot_reached_avtr:
                clientMessage.PopInt();

                string NameBotReached = clientMessage.PopString();
                HandleTriggerSave(new BotReadchedAvatar(roomItem, room.GetWiredHandler(), NameBotReached), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.triggercollisionuser:
                HandleTriggerSave(new UserCollision(roomItem, room.GetWiredHandler(), room), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.triggerscoreachieved:
                clientMessage.PopInt();
                int scoreLevel = clientMessage.PopInt();
                HandleTriggerSave(new ScoreAchieved(roomItem, room.GetWiredHandler(), scoreLevel, room.GetGameManager()), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.triggerstatechanged:
                clientMessage.PopInt();
                clientMessage.PopBoolean();
                clientMessage.PopBoolean();
                List <Item> items1 = GetItems(clientMessage, room, itemID);
                int         delay1 = clientMessage.PopInt();
                HandleTriggerSave(new SateChanged(room.GetWiredHandler(), roomItem, items1, delay1), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.triggerwalkonfurni:
                clientMessage.PopInt();
                clientMessage.PopString();
                List <Item> items2          = GetItems(clientMessage, room, itemID);
                int         requiredCycles1 = clientMessage.PopInt();
                HandleTriggerSave(new WalksOnFurni(roomItem, room.GetWiredHandler(), items2, requiredCycles1), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.triggerwalkofffurni:
                clientMessage.PopInt();
                clientMessage.PopString();
                List <Item> items3          = GetItems(clientMessage, room, itemID);
                int         requiredCycles2 = clientMessage.PopInt();
                HandleTriggerSave(new WalksOffFurni(roomItem, room.GetWiredHandler(), items3, requiredCycles2), room.GetWiredHandler(), room, roomItem);
                break;

                #endregion
                #region Action
            case InteractionType.actiongivescore:
                clientMessage.PopInt();
                int scoreToGive     = clientMessage.PopInt();
                int maxCountPerGame = clientMessage.PopInt();
                HandleTriggerSave(new GiveScore(maxCountPerGame, scoreToGive, room.GetGameManager(), itemID), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_act_give_score_tm:
                clientMessage.PopInt();
                int scoreToGive2     = clientMessage.PopInt();
                int maxCountPerGame2 = clientMessage.PopInt();
                int TeamId           = clientMessage.PopInt();
                HandleTriggerSave(new GiveScoreTeam(TeamId, maxCountPerGame2, scoreToGive2, room.GetGameManager(), itemID), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.actionposreset:
                clientMessage.PopInt();
                int EtatActuel      = clientMessage.PopInt();
                int DirectionActuel = clientMessage.PopInt();
                int PositionActuel  = clientMessage.PopInt();
                clientMessage.PopBoolean();
                clientMessage.PopBoolean();

                List <Item> itemsposrest          = GetItems(clientMessage, room, itemID);
                int         requiredCyclesposrest = clientMessage.PopInt();
                HandleTriggerSave(new PositionReset(itemsposrest, requiredCyclesposrest, room.GetRoomItemHandler(), room.GetWiredHandler(), itemID, EtatActuel, DirectionActuel, PositionActuel), room.GetWiredHandler(), room, roomItem);

                break;

            case InteractionType.actionmoverotate:
                clientMessage.PopInt();
                MovementState movement = (MovementState)clientMessage.PopInt();
                RotationState rotation = (RotationState)clientMessage.PopInt();
                clientMessage.PopBoolean();
                clientMessage.PopBoolean();
                List <Item> items4 = GetItems(clientMessage, room, itemID);
                int         delay2 = clientMessage.PopInt();
                HandleTriggerSave(new MoveRotate(movement, rotation, items4, delay2, room, room.GetWiredHandler(), itemID), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.actionresettimer:
                clientMessage.PopInt();
                clientMessage.PopInt();
                clientMessage.PopString();
                int delay3 = clientMessage.PopInt();
                HandleTriggerSave(new TimerReset(room, room.GetWiredHandler(), delay3, itemID), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.highscore:
            case InteractionType.highscorepoints:

                break;

            case InteractionType.actionshowmessage:
                clientMessage.PopInt();
                string MessageWired     = clientMessage.PopString();
                int    CountItemMessage = clientMessage.PopInt();
                int    DelayMessage     = clientMessage.PopInt();
                HandleTriggerSave(new ShowMessage(MessageWired, room.GetWiredHandler(), itemID, DelayMessage), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.superwired:
                clientMessage.PopInt();
                string MessageSuperWired   = clientMessage.PopString();
                int    CountItemSuperWired = clientMessage.PopInt();
                int    DelaySuperWired     = clientMessage.PopInt();
                HandleTriggerSave(new SuperWired(MessageSuperWired, DelaySuperWired, Session.GetHabbo().HasFuse("fuse_superwired"), Session.GetHabbo().Rank > 7, room.GetWiredHandler(), itemID), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.actiongivereward:
                if (!Session.GetHabbo().HasFuse("fuse_superwired"))
                {
                    return;
                }
                //clientMessage.PopInt();
                //WiredSaver.HandleTriggerSave((IWiredTrigger)new GiveReward(clientMessage.PopString(), room.GetWiredHandler(), itemID), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.actionkickuser:
                clientMessage.PopInt();
                HandleTriggerSave(new KickUser(clientMessage.PopString(), room.GetWiredHandler(), itemID, room), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.actionteleportto:
                clientMessage.PopInt();
                clientMessage.PopString();
                List <Item> items6 = GetItems(clientMessage, room, itemID);
                int         delay4 = clientMessage.PopInt();
                HandleTriggerSave(new TeleportToItem(room.GetGameMap(), room.GetWiredHandler(), items6, delay4, itemID), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_act_endgame_team:
                clientMessage.PopInt();
                int TeamId3 = clientMessage.PopInt();
                HandleTriggerSave(new TeamGameOver(TeamId3, roomItem.Id, room), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.actiontogglestate:
                clientMessage.PopInt();
                clientMessage.PopString();
                List <Item> items7 = GetItems(clientMessage, room, itemID);
                int         delay5 = clientMessage.PopInt();
                HandleTriggerSave(new ToggleItemState(room.GetGameMap(), room.GetWiredHandler(), items7, delay5, roomItem), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_act_call_stacks:
                clientMessage.PopInt();
                clientMessage.PopString();
                List <Item> itemsExecute = GetItems(clientMessage, room, itemID);
                int         StackDeley   = clientMessage.PopInt();
                HandleTriggerSave(new ExecutePile(itemsExecute, StackDeley, room.GetWiredHandler(), roomItem), room.GetWiredHandler(), room, roomItem);

                break;

            case InteractionType.actionflee:
                clientMessage.PopInt();
                clientMessage.PopString();
                List <Item> itemsflee = GetItems(clientMessage, room, itemID);
                HandleTriggerSave(new Escape(itemsflee, room, room.GetWiredHandler(), roomItem.Id), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.actionchase:
                clientMessage.PopInt();
                clientMessage.PopString();
                List <Item> itemschase = GetItems(clientMessage, room, itemID);
                HandleTriggerSave(new Chase(itemschase, room, room.GetWiredHandler(), roomItem.Id), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.collisionteam:
                clientMessage.PopInt();
                int TeamIdCollision = clientMessage.PopInt();
                HandleTriggerSave(new CollisionTeam(TeamIdCollision, room, room.GetWiredHandler(), roomItem.Id), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.collisioncase:
                clientMessage.PopInt();
                clientMessage.PopString();
                List <Item> itemscollision = GetItems(clientMessage, room, itemID);
                HandleTriggerSave(new CollisionCase(itemscollision, room, room.GetWiredHandler(), roomItem.Id), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.actionmovetodir:
                clientMessage.PopInt();

                MovementDirection StarDirect = (MovementDirection)clientMessage.PopInt();
                WhenMovementBlock WhenBlock  = (WhenMovementBlock)clientMessage.PopInt();

                clientMessage.PopBoolean();
                clientMessage.PopBoolean();

                List <Item> itemsmovetodir = GetItems(clientMessage, room, itemID);
                int         delaymovetodir = clientMessage.PopInt();

                HandleTriggerSave(new MoveToDir(itemsmovetodir, room, room.GetWiredHandler(), roomItem.Id, StarDirect, WhenBlock), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_act_bot_clothes:
                clientMessage.PopInt();

                string NameAndLook = clientMessage.PopString();

                string[] SplieNAL = NameAndLook.Split('\t');
                if (SplieNAL.Length != 2)
                {
                    break;
                }

                HandleTriggerSave(new BotClothes(SplieNAL[0], SplieNAL[1], room.GetWiredHandler(), roomItem.Id), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_act_bot_teleport:
                clientMessage.PopInt();

                string NameBot = clientMessage.PopString();

                List <Item> itemsbotteleport = GetItems(clientMessage, room, itemID);

                HandleTriggerSave(new BotTeleport(NameBot, itemsbotteleport, room.GetGameMap(), room.GetWiredHandler(), roomItem.Id), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_act_bot_follow_avatar:
                clientMessage.PopInt();

                bool   IsFollow      = (clientMessage.PopInt() == 1);
                string NameBotFollow = clientMessage.PopString();

                HandleTriggerSave(new BotFollowAvatar(NameBotFollow, IsFollow, room.GetWiredHandler(), roomItem.Id), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_act_bot_give_handitem:
                clientMessage.PopInt();

                HandleTriggerSave(new BotGiveHanditem("", room.GetWiredHandler(), roomItem.Id), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_act_bot_move:
                clientMessage.PopInt();

                string NameBotMove = clientMessage.PopString();

                List <Item> itemsbotMove = GetItems(clientMessage, room, itemID);

                HandleTriggerSave(new BotMove(NameBotMove, itemsbotMove, room.GetWiredHandler(), roomItem.Id), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_act_user_move:
                clientMessage.PopInt();
                clientMessage.PopString();
                List <Item> itemsUserMove = GetItems(clientMessage, room, itemID);

                int delayusermove = clientMessage.PopInt();
                HandleTriggerSave(new UserMove(itemsUserMove, delayusermove, room.GetWiredHandler(), roomItem.Id), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_act_bot_talk_to_avatar:
                clientMessage.PopInt();
                bool IsCrier = (clientMessage.PopInt() == 1);

                string BotNameAndMessage = clientMessage.PopString();

                string[] SplieNAM = BotNameAndMessage.Split('\t');
                if (SplieNAM.Length != 2)
                {
                    break;
                }
                string NameBotTalk = SplieNAM[0];
                string MessageBot  = SplieNAM[1];


                HandleTriggerSave(new BotTalkToAvatar(NameBotTalk, MessageBot, IsCrier, room.GetWiredHandler(), roomItem.Id), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_act_bot_talk:
                clientMessage.PopInt();
                bool IsCrier2 = (clientMessage.PopInt() == 1);

                string BotNameAndMessage2 = clientMessage.PopString();

                string[] SplieNAM2 = BotNameAndMessage2.Split('\t');
                if (SplieNAM2.Length != 2)
                {
                    break;
                }
                string NameBotTalk2 = SplieNAM2[0];
                string MessageBot2  = SplieNAM2[1];


                HandleTriggerSave(new BotTalk(NameBotTalk2, MessageBot2, IsCrier2, room.GetWiredHandler(), roomItem.Id), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_act_leave_team:
                HandleTriggerSave(new TeamLeave(roomItem.Id), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_act_join_team:
                clientMessage.PopInt();
                int TeamId4 = clientMessage.PopInt();
                HandleTriggerSave(new TeamJoin(TeamId4, roomItem.Id), room.GetWiredHandler(), room, roomItem);
                break;

                #endregion
                #region Condition
            case InteractionType.superwiredcondition:
                clientMessage.PopInt();
                HandleTriggerSave((IWiredCondition) new SuperWiredCondition(roomItem, clientMessage.PopString(), Session.GetHabbo().HasFuse("fuse_superwired")), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.conditionfurnishaveusers:
                clientMessage.PopInt();
                clientMessage.PopString();

                List <Item> items10 = GetItems(clientMessage, room, itemID);
                HandleTriggerSave((IWiredCondition) new FurniHasUser(roomItem, items10), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.conditionfurnishavenousers:
                clientMessage.PopInt();
                clientMessage.PopString();

                List <Item> items12 = GetItems(clientMessage, room, itemID);
                HandleTriggerSave((IWiredCondition) new FurniHasNoUser(roomItem, items12), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.conditionstatepos:
                clientMessage.PopInt();
                int EtatActuel2      = clientMessage.PopInt();
                int DirectionActuel2 = clientMessage.PopInt();
                int PositionActuel2  = clientMessage.PopInt();
                clientMessage.PopBoolean();
                clientMessage.PopBoolean();

                HandleTriggerSave((IWiredCondition) new FurniStatePosMatch(roomItem, GetItems(clientMessage, room, itemID), EtatActuel2, DirectionActuel2, PositionActuel2), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_cnd_stuff_is:
                clientMessage.PopInt();
                clientMessage.PopString();

                HandleTriggerSave((IWiredCondition) new FurniStuffIs(roomItem, GetItems(clientMessage, room, itemID)), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_cnd_not_stuff_is:
                clientMessage.PopInt();
                clientMessage.PopString();

                HandleTriggerSave((IWiredCondition) new FurniNotStuffIs(roomItem, GetItems(clientMessage, room, itemID)), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.conditionstateposNegative:
                clientMessage.PopInt();
                int EtatActuel3      = clientMessage.PopInt();
                int DirectionActuel3 = clientMessage.PopInt();
                int PositionActuel3  = clientMessage.PopInt();
                clientMessage.PopBoolean();
                clientMessage.PopBoolean();

                List <Item> items17 = GetItems(clientMessage, room, itemID);
                HandleTriggerSave((IWiredCondition) new FurniStatePosMatchNegative(roomItem, items17, EtatActuel3, DirectionActuel3, PositionActuel3), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.conditiontimelessthan:
                clientMessage.PopInt();
                int cycleCount2 = clientMessage.PopInt();
                HandleTriggerSave((IWiredCondition) new LessThanTimer(cycleCount2, room, roomItem), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.conditiontimemorethan:
                clientMessage.PopInt();
                int cycleCount3 = clientMessage.PopInt();
                HandleTriggerSave((IWiredCondition) new MoreThanTimer(cycleCount3, room, roomItem), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.conditiontriggeronfurni:
                clientMessage.PopInt();
                clientMessage.PopString();

                List <Item> items9 = GetItems(clientMessage, room, itemID);
                HandleTriggerSave((IWiredCondition) new TriggerUserIsOnFurni(roomItem, items9), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.conditiontriggeronfurniNegative:
                clientMessage.PopInt();
                clientMessage.PopString();

                List <Item> items14 = GetItems(clientMessage, room, itemID);
                HandleTriggerSave((IWiredCondition) new TriggerUserIsOnFurniNegative(roomItem, items14), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.conditionhasfurnionfurni:
                clientMessage.PopInt();
                clientMessage.PopString();

                List <Item> items13 = GetItems(clientMessage, room, itemID);
                HandleTriggerSave((IWiredCondition) new HasFurniOnFurni(roomItem, items13), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.conditionhasfurnionfurniNegative:
                clientMessage.PopInt();
                clientMessage.PopString();

                List <Item> items15 = GetItems(clientMessage, room, itemID);
                HandleTriggerSave((IWiredCondition) new HasFurniOnFurniNegative(roomItem, items15), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.conditionactoringroup:
                HandleTriggerSave((IWiredCondition) new HasUserInGroup(roomItem), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_cnd_not_user_count:
                clientMessage.PopInt();
                int UserCountMin = clientMessage.PopInt();
                int UserCountMax = clientMessage.PopInt();
                HandleTriggerSave((IWiredCondition) new RoomUserNotCount(roomItem, UserCountMin, UserCountMax), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_cnd_user_count_in:
                clientMessage.PopInt();
                int UserCountMin2 = clientMessage.PopInt();
                int UserCountMax2 = clientMessage.PopInt();
                HandleTriggerSave((IWiredCondition) new RoomUserCount(roomItem, UserCountMin2, UserCountMax2), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.conditionnotingroup:
                HandleTriggerSave((IWiredCondition) new HasUserNotInGroup(roomItem), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_cnd_actor_in_team:
                clientMessage.PopInt();
                int TeamId5 = clientMessage.PopInt();
                HandleTriggerSave((IWiredCondition) new ActorInTeam(roomItem.Id, TeamId5), room.GetWiredHandler(), room, roomItem);
                break;

            case InteractionType.wf_cnd_not_in_team:
                clientMessage.PopInt();
                int TeamId2 = clientMessage.PopInt();
                HandleTriggerSave((IWiredCondition) new ActorNotInTeam(roomItem.Id, TeamId2), room.GetWiredHandler(), room, roomItem);
                break;
                #endregion
            }
            Session.SendPacket(new ServerPacket(ServerPacketHeader.WiredSavedComposer));
        }
Exemplo n.º 40
0
    void RunToTarget(Vector3 target)
    {
        velocity.x = baseVelocityX * Mathf.Sign(target.x - thisNode.transform.position.x);

        movementState = MovementState.aerial;
    }
Exemplo n.º 41
0
 public void SetState(MovementState state)
 {
     movementState = state;
 }
Exemplo n.º 42
0
    // Update is called once per frame
    void Update()
    {
        if (cursor == null)
        {
            cursor = GameObject.FindGameObjectWithTag("Player");
        }
        switch (ms)
        {
        case MovementState.NO_MOVE:
            //here pointer on collision with all object
            ray = cam.ScreenPointToRay(fixedPointer);
            Physics.Raycast(ray, out hit);

            if (hit.collider != null)
            {
                cursor.transform.position = hit.point;
            }
            if (selectable && hit.collider != null)
            {
                //if on a obj for 1 sec, take that as selected
                if (hit.collider.gameObject.GetComponent <Selectable>() != null)
                {
                    if (hit.collider.gameObject.Equals(focused))
                    {
                        time += Time.deltaTime;
                        if (time >= TIME_FOR_SELECTION)
                        {
                            //this object must be selected
                            sceneMgr.selectObject(focused);
                            selectable = false;
                            time       = 0;
                            selected   = focused;
                        }
                    }
                    else
                    {
                        focused = hit.collider.gameObject;
                    }
                }
                else
                {
                    time = 0;
                }
            }
            break;

        case MovementState.MOVEXZ:
            //here pointer on collison with plane
            if (selected != null)
            {
                ray = cam.ScreenPointToRay(fixedPointer);
                if (planeXZ.Raycast(ray, out rayDist))
                {
                    cursor.transform.position = ray.GetPoint(rayDist);
                    sceneMgr.translate(cursor.transform.position, false);
                }
            }
            else
            {
                ms = MovementState.NO_MOVE;
            }
            break;

        case MovementState.MOVEY:
            //here pointer on collision with perpendicular plane
            if (selected != null)
            {
                direction   = -cam.transform.position + selected.transform.position;
                direction.y = 0;
                planeY.SetNormalAndPosition(direction.normalized, selected.transform.position);
                ray = cam.ScreenPointToRay(fixedPointer);
                if (planeY.Raycast(ray, out rayDist))
                {
                    Debug.Log(ray.GetPoint(rayDist));
                    cursor.transform.position = ray.GetPoint(rayDist);
                    sceneMgr.translate(cursor.transform.position, false);
                }
            }
            else
            {
                ms = MovementState.NO_MOVE;
            }
            break;
        }
    }
Exemplo n.º 43
0
        private void DoWalk()
        {
            var curVelocity = rb.velocity;

            _move = new Vector2(_dir.x, curVelocity.y);

            // Moved?
            if (_move == Vector2.zero && GetMoveDeltaSquared <= tolerance.Squared())
            {
                mState = MovementState.IDLE;
            }
            else
            {
                switch (cState)
                {
                case CollisionState.AIR:
                    _targetDrag = airDrag;
                    if (_targetSpeed > runSpeed)
                    {
                        break;
                    }
                    _targetSpeed = airSpeed;
                    break;

                case CollisionState.GROUND:
                    _targetDrag = drag;
                    if (_targetSpeed >= runSpeed)
                    {
                        break;
                    }
                    _targetSpeed = moveSpeed;
                    break;

                case CollisionState.WALL:
                case CollisionState.LEDGE:
                    _targetDrag = drag;
                    if (_targetSpeed < moveSpeed)
                    {
                        _targetSpeed = moveSpeed;
                    }
                    break;

                case CollisionState.CEILING:
                    _targetSpeed = airSpeed;
                    break;

                default:
                    _targetSpeed = moveSpeed;
                    _targetDrag  = drag;
                    _curAccel    = accel;
                    break;
                }

                mState = MovementState.WALK;

                Debug.Log($"Prev Speed: {_prevSpeed} | Target Speed: {_targetSpeed}");

                if (!_transition && _prevSpeed != _targetSpeed)
                {
                    _transition = true;
                    _curAccel   = _prevSpeed < _targetSpeed ? accel : decel;
                    _timer.NewDuration(_curAccel);
                    Debug.Log("Transitioning...");
                }

                if (_transition)
                {
                    _curDrag    = Mathf.Lerp(_prevDrag, _targetDrag, dragCurve.Evaluate(_timer.PercentageDone));
                    _curSpeed   = Mathf.Lerp(_prevSpeed, _targetSpeed, accelCurve.Evaluate(_timer.PercentageDone));
                    _transition = !_timer.IsDone;
                    Debug.Log($"Current Speed: {_curSpeed}");
                }
                //else
                //{
                //    _curDrag = _targetDrag;
                //    curSpeed = _targetSpeed;
                //}

                _move.Set(_move.x * _curSpeed, _move.y);
                _smoothVel  = Vector2.SmoothDamp(curVelocity, _move, ref _smoothVel, _curDrag);
                rb.velocity = _smoothVel;
            }

            OnMove?.Raise(mState);

            // Get previous states
            _prevPos = _t.position;
            if (!_transition)
            {
                _prevDrag  = _curDrag;
                _prevSpeed = _targetSpeed;
            }
        }
Exemplo n.º 44
0
 void RunOutOfGas()
 {
     currMovementState = MovementState.OutOfGas;
     Camera.main.GetComponent<HoverFollowCam> ().enabled = false;
 }
Exemplo n.º 45
0
    /// <summary>
    /// This function is called every fixed framerate frame, if the MonoBehaviour is enabled.
    /// </summary>
    void FixedUpdate()
    {
        // For convenience
        bodyBox = new Rect(
            bodyCd.bounds.min.x,
            bodyCd.bounds.min.y,
            bodyCd.bounds.size.x,
            bodyCd.bounds.size.y
            );

        // Set default values
        finalAccel = accel;

        // --- Gravity ---
        // If enemy is not grounded, apply gravity
        if (!grounded)
        {
            velocity = new Vector2(velocity.x, Mathf.Max(velocity.y - gravity, -maxFall));
        }

        // Check if enemy is falling
        if (velocity.y < 0)
        {
            if (state.Missing(MovementState.Falling))
            {
                state = state.Include(MovementState.Falling);
                if (OnFall != null)
                {
                    OnFall(this, System.EventArgs.Empty);
                }
            }
        }

        // Determine first and last rays
        Vector2 minDownRay = new Vector2(bodyBox.xMin, bodyBox.center.y);
        Vector2 maxDownRay = new Vector2(bodyBox.xMax, bodyBox.center.y);

        // Calculate ray distance (if not grounded, set to current fall speed)
        float rayDownDistance = bodyBox.height / 2 + ((grounded) ? 0 : Mathf.Abs(velocity.y * Time.deltaTime));

        // Check below for ground
        RaycastHit2D[] hitDownInfo         = new RaycastHit2D[vRays];
        bool           hit                 = false;
        float          closestDownHit      = float.MaxValue;
        int            closestDownHitIndex = 0;

        for (int i = 0; i < vRays; i++)
        {
            // Create and cast ray
            float   lerpDistance = (float)i / (float)(vRays - 1);
            Vector2 rayOrigin    = Vector2.Lerp(minDownRay, maxDownRay, lerpDistance);
            Ray2D   ray          = new Ray2D(rayOrigin, Vector2.down);
            hitDownInfo[i] = Physics2D.Raycast(rayOrigin, Vector2.down, rayDownDistance, RayLayers.downRay);

            // Check raycast results and keep track of closest ground hit
            if (hitDownInfo[i].fraction > 0)
            {
                hit = true;
                if (hitDownInfo[i].fraction < closestDownHit)
                {
                    closestDownHit      = hitDownInfo[i].fraction;
                    closestDownHitIndex = i;
                    closestDownHitInfo  = hitDownInfo[i];
                }
            }
        }

        // If enemy hits ground, snap to the closest ground
        if (hit)
        {
            // Check if enemy is landing this frame
            if (state.Has(MovementState.Falling) && state.Missing(MovementState.Landing))
            {
                if (OnLand != null)
                {
                    OnLand(this, System.EventArgs.Empty);
                }
                state = state.Include(MovementState.Landing);
                state = state.Remove(MovementState.Jumping);
            }
            grounded = true;
            state    = state.Remove(MovementState.Falling);
            velocity = new Vector2(velocity.x, 0);
        }
        else
        {
            grounded = false;
        }

        // --- Behavior ---
        // Idle behavior
        if (behaviorState.Has(BehaviorState.Idle))
        {
            behaviorTime += Time.deltaTime;

            // Set new behavior
            if (behaviorTime > idleBehaviorTime)
            {
                float newHAxis = Random.Range(-1, 1);
                // Flip sprite if changing direction of movement
                if (newHAxis != 0 && newHAxis != ((rend.flipX) ? -1 : 1))
                {
                    rend.flipX = !rend.flipX;
                }
                hAxis            = newHAxis;
                behaviorTime     = 0f;
                idleBehaviorTime = GetNewIdleBehaviorTime();
                //Debug.Log("Rolled: " + hAxis + " for " + idleBehaviorTime);
            }
        }

        // --- Lateral Collisions & Movement ---
        ApplyGroundEffects();

        // Move horizontally
        float newVelocityX = velocity.x;

        if (hAxis != 0)
        {
            newVelocityX += finalAccel * hAxis;
            newVelocityX  = Mathf.Clamp(newVelocityX, -maxSpeed, maxSpeed);
        }
        // Decelerate if moving without input
        else if (velocity.x != 0)
        {
            int decelDir = (velocity.x > 0) ? -1 : 1;
            // Ensure enemy doesn't decelerate past zero
            newVelocityX += (velocity.x > 0) ?
                            ((newVelocityX + finalAccel * decelDir) < 0) ?
                            -newVelocityX : finalAccel * decelDir
                                        : ((newVelocityX + finalAccel * decelDir) > 0) ?
                            -newVelocityX : finalAccel * decelDir;
        }
        // Account for slope
        if (Mathf.Abs(closestDownHitInfo.normal.x) > 0.1f)
        {
            float friction = 0.7f;
            newVelocityX = Mathf.Clamp((newVelocityX - (closestDownHitInfo.normal.x * friction)), -maxSpeed, maxSpeed);
            Vector2 newPosition = transform.position;
            newPosition.y     += -closestDownHitInfo.normal.x * Mathf.Abs(newVelocityX) * Time.deltaTime * ((newVelocityX - closestDownHitInfo.normal.x > 0) ? 1 : -1);
            transform.position = newPosition;
            state = state.Remove(MovementState.Landing);
        }

        velocity = new Vector2(newVelocityX, velocity.y);

        // Lateral collisions
        bool lateralCollision = false;

        // Determine first and last rays
        Vector2 minLatRay = new Vector2(bodyBox.center.x, bodyBox.yMin);
        Vector2 maxLatRay = new Vector2(bodyBox.center.x, bodyBox.yMax);

        // Calculate ray distance and determine direction of movement
        float   rayDistance  = bodyBox.width / 2 + Mathf.Abs(newVelocityX * Time.deltaTime);
        Vector2 rayDirection = (newVelocityX > 0) ? Vector2.right : Vector2.left;

        RaycastHit2D[] latHitInfo         = new RaycastHit2D[hRays];
        float          closestLatHit      = float.MaxValue;
        int            closestLatHitIndex = 0;
        float          lastFraction       = 0;
        int            numHits            = 0; // for debugging

        for (int i = 0; i < hRays; i++)
        {
            // Create and cast ray
            float   lerpDistance = (float)i / (float)(hRays - 1);
            Vector2 rayOrigin    = Vector2.Lerp(minLatRay, maxLatRay, lerpDistance);
            latHitInfo[i] = Physics2D.Raycast(rayOrigin, rayDirection, rayDistance, RayLayers.sideRay);
            Debug.DrawRay(rayOrigin, rayDirection * rayDistance, Color.cyan, Time.deltaTime);
            // Check raycast results
            if (latHitInfo[i].fraction > 0)
            {
                lateralCollision = true;
                numHits++;                         // for debugging
                if (latHitInfo[i].fraction < closestLatHit)
                {
                    closestLatHit      = latHitInfo[i].fraction;
                    closestLatHitIndex = i;
                }
                // If more than one ray hits, check the slope of what player is colliding with
                if (lastFraction > 0)
                {
                    float slopeAngle = Vector2.Angle(latHitInfo[i].point - latHitInfo[i - 1].point, Vector2.right);
                    // If we hit a wall, snap to it
                    if (Mathf.Abs(slopeAngle - 90) < angleLeeway)
                    {
                        transform.Translate(rayDirection * (latHitInfo[i].distance - bodyBox.width / 2));
                        if (OnLateralCollision != null)
                        {
                            OnLateralCollision(this, System.EventArgs.Empty);
                        }
                        velocity = new Vector2(0, velocity.y);

                        break;
                    }
                }
                lastFraction = latHitInfo[i].fraction;
            }
        }

        // TODO: Ceiling collisions?
        // TODO: Check if accel/decel is making enemy sink into slopes
    }
Exemplo n.º 46
0
 private void EndTravel()
 {
     circleCollider.enabled = true;
     movementState          = MovementState.Normal;
     AddStartingForce();
 }
Exemplo n.º 47
0
 private void Start()
 {
     _selfTransform = GetComponent <Transform>();
     _rigidbody     = GetComponent <Rigidbody2D>();
     movementState  = MovementState.Ground;
 }
Exemplo n.º 48
0
 public void FreezeMovement()
 {
     movementState = MovementState.Frozen;
 }
Exemplo n.º 49
0
 protected bool IsGroundedAndMovementStateChanged(MovementState priorMovementState)
 {
     return(JumpingState == JumpingState.Grounded && MovementState != priorMovementState);
 }
Exemplo n.º 50
0
 public void FreeMovement()
 {
     movementState = MovementState.Free;
     Debug.Log("Free");
 }
 public void StopMoving()
 {
     this.myMovementState = MovementState.Idle;
 }
Exemplo n.º 52
0
 public Follow(string ownerName)
 {
     this.ownerName = ownerName;
     this.state     = MovementState.HIGH_NOTFOUND;
 }
Exemplo n.º 53
0
 public InputEvent(float startTime, MovementState movementState)
 {
     this.startTime     = startTime;
     this.movementState = movementState;
     isMovementState    = true;
 }
Exemplo n.º 54
0
 public void RegisterState(MovementState stateName, IState state)
 {
     m_registeredStates.Add(stateName, state);
 }
Exemplo n.º 55
0
 //Not moving, if I don't see the player for awhile, then go wander
 IEnumerator MIdleState()
 {
     mIdleTimer = 0;
     while (movementState == MovementState.MIdle)
     {
         if(seesPlayer)
             mIdleTimer = 0;
         else
             mIdleTimer++;
         if(mIdleTimer > mIdleTime + Random.Range (-100,100)  && !flee)
             movementState = MovementState.MMoving;
         yield return 0;
     }
     if (!flee) {
                     NextMovementState ();
             }
 }
Exemplo n.º 56
0
    public void StartMoveCurve(Transform startPoint, Transform сontrolPoint, Transform endPoint)
    {
        movementState = MovementState.MoveCurve;

        InitBezPoints(startPoint, сontrolPoint, endPoint);
    }
Exemplo n.º 57
0
    //Search state (knows where player is and will head to the player's location)
    IEnumerator MSearchState()
    {
        mIdleTimer = 0;
        int stuckTimer = 0;

        while (movementState == MovementState.MSearch)
        {
            //I've arrived at my location, if idle too long, then go back to idle state
            if(Vector3.Distance(transform.position,agent.destination) < 3)
                mIdleTimer++;
            //I'm stuck and haven't moved in a while, go back to idle state
            if(agent.velocity.magnitude < 1)
                stuckTimer++;
            if(seesPlayer || mIdleTimer > mIdleTime + 200 || stuckTimer > 300  && !flee)
            {
                agent.destination = transform.position;
                movementState = MovementState.MIdle;
            }
            yield return 0;
        }
            NextMovementState();
    }
Exemplo n.º 58
0
    private void StopMoveCurve()
    {
        movementState = MovementState.MoveForward;

        //Можно было бы вызывать остановку движения по кривой при OnTriggerExit у поворота, но коллайдер поворота и игрока может быть разным
    }
Exemplo n.º 59
0
        public void LoadFromDatabase(IQueryAdapter dbClient, Room insideRoom)
        {
            dbClient.setQuery("SELECT trigger_data FROM trigger_item WHERE trigger_id = @id ");
            dbClient.addParameter("id", (int)this.itemID);
            this.delay = dbClient.getInteger();

            dbClient.setQuery("SELECT rotation_status, movement_status FROM trigger_rotation WHERE item_id = @id");
            dbClient.addParameter("id", (int)this.itemID);
            DataRow dRow = dbClient.getRow();
            if (dRow != null)
            {
                this.rotation = (RotationState)Convert.ToInt32(dRow[0]);
                this.movement = (MovementState)Convert.ToInt32(dRow[1]);
            }
            else
            {
                rotation = RotationState.none;
                movement = MovementState.none;
            }

            dbClient.setQuery("SELECT triggers_item FROM trigger_in_place WHERE original_trigger = " + this.itemID);
            DataTable dTable = dbClient.getTable();
            RoomItem targetItem;
            foreach (DataRow dRows in dTable.Rows)
            {
                targetItem = insideRoom.GetRoomItemHandler().GetItem(Convert.ToUInt32(dRows[0]));
                if (targetItem == null || this.items.Contains(targetItem))
                {
                    continue;
                }

                this.items.Add(targetItem);
            }
        }
Exemplo n.º 60
0
 public StateMovementHandler(MovementState belongingTo, Player player)
 {
     stateBelongingToo = belongingTo;
     this.player       = player;
 }