public void Jump() { if (State == VerticalState.Stop) { State = VerticalState.JumpStart; } }
private void VerticalMovement() { if (_verticalState != VerticalState.Sliding) { var speed = _currentVelocity * Time.deltaTime; var threshold = Settings.Instance.JumpingVelocity * Time.deltaTime; if (transform.position.y >= _destination.y - threshold && transform.position.y <= _destination.y + threshold && _currentVelocity < 0) { var pos = transform.position; pos.y = _destination.y; transform.position = pos; _verticalState = VerticalState.None; } else { if (speed < 0) { _verticalState = VerticalState.Falling; } transform.Translate(Vector3.up * speed, Space.World); } _currentVelocity -= Settings.Instance.Gravity; } else { _currentSlidingTime += Time.deltaTime; if (_currentSlidingTime >= Settings.Instance.SlidingTime) { _verticalState = VerticalState.None; StartCoroutine(SlidePlayer(false)); } } }
private void Start() { groundDistance = collider.bounds.extents.y + GROUND_DISTANCE_OFFSET; state = GetComponent <VerticalState>(); jumpAction = GetComponent <JumpAction>(); jumpBuffer = GetComponent <JumpBuffer>(); }
/// <summary> /// This method tells the player what to do based on what state he is in /// </summary> public void checkState() { if (vState == VerticalState.falling) { //Subtract gravity velocity.Y += gravity; } else if (vState == VerticalState.jumping) { //Subtract gravity velocity.Y += gravity; //Check to see if the player needs to start falling if (velocity.Y >= 0) { vState = VerticalState.falling; } } else if (hState == HorizontalState.standing) { //If the horizontal state is standing, then the player is neither jumping or falling vState = VerticalState.none; } else if (hState == HorizontalState.walkingLeft) { vState = VerticalState.none; } else if (hState == HorizontalState.walkingRight) { vState = VerticalState.none; } }
private void UpdateState() { switch (State) { case VerticalState.Stop: Speed = 0; break; case VerticalState.JumpStart: Speed = jumpInitialSpeed; State = VerticalState.Rising; break; case VerticalState.Rising: UpdateSpeed(upwardsGravity); if (Speed < 0) { State = VerticalState.Falling; } break; case VerticalState.Falling: UpdateSpeed(fallingGravity); break; case VerticalState.Gliding: Speed = -glidingSpeed; break; } }
private void RayBottom() { var ray = new Ray(BottomRaySource.position, Vector3.down); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { var platform = hit.transform.gameObject.GetComponentInChildren <Platform>(); if (platform != null) { if (_verticalState == VerticalState.None && transform.position.y > 0) { _verticalState = VerticalState.Falling; _currentVelocity = 0; _destination.y = 0; } _onTopOf = OnTopOf.Platform; return; } var element = hit.transform.gameObject.GetComponentInChildren <Element>(); if (element != null && element.ElementType == ElementType.Obstacle) { _onTopOf = OnTopOf.Obstacle; if (_verticalState == VerticalState.Jumping | _verticalState == VerticalState.Falling) { _destination.y = hit.point.y; } return; } } }
public void DownAction() { VerticalState.DownAction(this); if (HorizontalState is RunningLeftAvatar || HorizontalState is RunningRightAvatar) { VerticalState = new IdleAvatar(); } }
private void SetStateV(VerticalState s) { if (prevStateV != curStateV) { walkDown.resetEnd(); } prevStateV = curStateV; curStateV = s; }
// Use this for initialization void Start() { InitializeRun(); currentVState = VerticalState.running; //Initially running currentHState = HorizontalState.running; //currentVIState = InputState.None; //currentHIState = InputState.None; targetLane = _movement.currentLane; StartCoroutine(queueEvents()); }
public void Glide(bool active = true) { if (active && State == VerticalState.Falling) { State = VerticalState.Gliding; } else if (!active && State == VerticalState.Gliding) { State = VerticalState.Falling; } }
void Awake() { stateMachine = GetComponent <VerticalState>(); groundDistance = GetComponent <GroundDistance>(); jumpBuffer = GetComponent <JumpBuffer>(); SOUNDS = new AudioClip[3] { soundLevel1, soundLevel2, soundLevel3 }; thrust_index = 0; isBuffering = false; }
private void SwipeVertical(InputManager.SwipeDirection swipeDirection) { switch (swipeDirection) { case InputManager.SwipeDirection.Top: _verticalState = VerticalState.Jumping; _currentVelocity = Settings.Instance.JumpingVelocity; break; case InputManager.SwipeDirection.Bottom: _verticalState = VerticalState.Sliding; _currentSlidingTime = 0; StartCoroutine(SlidePlayer(true)); break; } }
/// <summary> /// Jump with the specified vertical velocity. /// </summary> /// <param name='jumpAmount'> /// vertical jump amount /// </param> public void Jump(float jumpAmount) { if (this.CurrentVerticalState == VerticalState.Grounded && this.CanJump) { VerticalSpeed = 0; this.VerticalSpeed = jumpAmount; this.CurrentVerticalState = VerticalState.Airborn; } //Double Jump else if (this.CurrentVerticalState == VerticalState.Airborn && this.CanJump) { VerticalSpeed = 0; this.VerticalSpeed = jumpAmount;// * (0.9f); this.CanJump = false; } }
public void FacePlayer(HorizontalState playerH, VerticalState playerV) { moveTimer = 0; if (playerH == HorizontalState.Left) //face right { Console.WriteLine("left"); offsetX = 9; flipped = false; } else if (playerH == HorizontalState.Right) //face left { Console.WriteLine("right"); flipped = true; offsetX = 9; } else { Console.WriteLine("hNone"); offsetX = 0; } if (playerV == VerticalState.Down) //face up { Console.WriteLine("down"); offsetY = 54; } else if (playerV == VerticalState.Up) //face down { Console.WriteLine("up"); offsetY = 0; } else { Console.WriteLine("vNone"); offsetY = 27; } offsetY += 27 * 3; Console.WriteLine("OffsetX: " + offsetX); Console.WriteLine("OffsetY: " + offsetY); }
public void UpAction() { if (VerticalState is CrouchingAvatar) { VerticalState = new IdleAvatar(); } else if (!(VerticalState is JumpingAvatar || VerticalState is FallingAvatar)) { VerticalState.UpAction(this); if (PowerState is SuperState || PowerState is FireState) { Game1.SoundMap["SuperJump"].Play(); } else { Game1.SoundMap["NormalJump"].Play(); } _velocity.Y = -3.2f; } }
public Player(float x, float y) { Rectangle src = Sprites.GetSlice(Element.Player); Position = new Vector2(x, y); Velocity = Vector2.Zero; Dst = new Rectangle((int)x, (int)y, src.Width, src.Height); ElementType = Element.Player; Visible = true; XState = HorizontalState.Stopped; YState = VerticalState.Falling; HState = HealthState.Normal; PlayerAnimation = new Animation( TimeSpan.FromMilliseconds(200f), src.Width, src.Height, Sprites.GetTexture(Element.Player).Width / src.Width, true); Direction = 1; }
// Start is called before the first frame update void Start() { Application.targetFrameRate = 300; verticalState = VerticalState.PositionLock; cameraCache = GetComponent <Camera>(); }
public void SetVerticalState(VerticalState state) { verticalState = state; }
public void Fall() => State = VerticalState.Falling;
public NPC(World world, ContentManager content, Player player, int steps, bool vertical, int posX, int posY, KeyboardState prevState, string[] messages, int textWidth = 26, int textHeight = 3, int width = 17, int height = 27) { this.width = width; this.height = height; if (vertical) { offsetX = 0; offsetY = 0; } else { offsetX = 9; //multiplied in draw by width offsetY = 27; } if (vertical) { curStateH = HorizontalState.None; } else { curStateV = VerticalState.None; } this.textWidth = textWidth; this.textHeight = textHeight; this.messages = messages; speaking = false; backwards = false; curStep = 1; this.steps = steps; this.vertical = vertical; animSpeed = 0.25f; isMoving = false; this.player = player; flipped = false; //body = new Body(world, new Vector2(0, 0)); bodyWidth = ConvertUnits.ToSimUnits(width); bodyHeight = ConvertUnits.ToSimUnits(height / 2); body = BodyFactory.CreateRectangle(world, bodyWidth, bodyHeight, 0.1f); body.UserData = this; //body = BodyFactory.CreateRectangle(world, 10, 10, 1, new Vector2(0,0)); //body.Position = new Vector2(8 * 31, 23*16); body.BodyType = BodyType.Kinematic; body.Position = ConvertUnits.ToSimUnits(posX * 16, posY * 16); body.OnCollision += OnCollisionHandler; //body.OnSeparation += EndContactHandler; leftFixt = FixtureFactory.AttachEdge(new Vector2(-bodyWidth / 2 - 0.02f, -bodyHeight / 2 + 0.01f), new Vector2(-bodyWidth / 2 - 0.02f, bodyHeight / 2 - 0.01f), body); leftFixt.IsSensor = true; leftFixt.OnCollision += leftHandler; leftFixt.OnSeparation += leftHandlerEnd; rightFixt = FixtureFactory.AttachEdge(new Vector2(bodyWidth / 2 + 0.02f, -bodyHeight / 2 + 0.01f), new Vector2(bodyWidth / 2 + 0.02f, bodyHeight / 2 - 0.01f), body); rightFixt.IsSensor = true; rightFixt.OnCollision += rightHandler; rightFixt.OnSeparation += rightHandlerEnd; upFixt = FixtureFactory.AttachEdge(new Vector2(-bodyWidth / 2 + 0.01f, -bodyHeight / 2 - 0.02f), new Vector2(bodyWidth / 2 - 0.01f, -bodyHeight / 2 - 0.02f), body); upFixt.IsSensor = true; upFixt.OnCollision += upHandler; rightFixt.OnSeparation += rightHandlerEnd; downFixt = FixtureFactory.AttachEdge(new Vector2(-bodyWidth / 2 + 0.01f, bodyHeight / 2 + 0.02f), new Vector2(bodyWidth / 2 - 0.01f, bodyHeight / 2 + 0.02f), body); downFixt.IsSensor = true; downFixt.OnCollision += downHandler; downFixt.OnSeparation += downHandlerEnd; x = posX; y = posY; tex = content.Load <Texture2D>("Map/Tazmily/Hinawa/Hinawa"); timer = 0; moveTimer = 0; tempStopped = false; walkDown = new Animation(0, 3, 0); posOffY = (int)(-height + ConvertUnits.ToDisplayUnits(bodyHeight) / 2); posOffX = (int)(-ConvertUnits.ToDisplayUnits(bodyWidth) / 2); }
/// <summary> /// Updates the player position based on GamePad or Keyboard input /// </summary> /// <param name="gameTime">The GameTime object</param> public void Update(GameTime gameTime) { Vector2 direction = Vector2.Zero; // Use GamePad for input var gamePad = GamePad.GetState(0); // The thumbstick value is a vector2 with X & Y between [-1f and 1f] and 0 if no GamePad is available direction.X = gamePad.ThumbSticks.Left.X; // We need to inverty the Y axis direction.Y = -gamePad.ThumbSticks.Left.Y; var keyboard = Keyboard.GetState(); switch (verticalState) { case VerticalState.Ground: if (keyboard.IsKeyDown(Keys.Space)) { verticalState = VerticalState.Jumping; jumpTimer = new TimeSpan(0); } break; case VerticalState.Jumping: jumpTimer += gameTime.ElapsedGameTime; direction.Y -= (250 / (float)jumpTimer.TotalMilliseconds); jumpHeight = (250 / (float)jumpTimer.TotalMilliseconds); if (jumpTimer.TotalMilliseconds >= JUMP_TIME) { verticalState = VerticalState.Falling; } break; case VerticalState.Falling: direction.Y += jumpHeight; break; } // Override with keyboard input if (keyboard.IsKeyDown(Keys.Left) || keyboard.IsKeyDown(Keys.A)) { direction.X -= 1; } if (keyboard.IsKeyDown(Keys.Right) || keyboard.IsKeyDown(Keys.D)) { direction.X += 1; } //if(keyboard.IsKeyDown(Keys.Up) || keyboard.IsKeyDown(Keys.W)) // { // direction.Y -= 1; // } //if(keyboard.IsKeyDown(Keys.Down) || keyboard.IsKeyDown(Keys.S)) // { // direction.Y += 1; // } angle = 0; Position += (float)gameTime.ElapsedGameTime.TotalSeconds * Speed * direction; if (Position.Y > origin.Y && verticalState == VerticalState.Falling) { Position = new Vector2(Position.X, oldPosition.Y); verticalState = VerticalState.Ground; } }
internal void Update(float delta, List<Tile> tiles) { TryingToMove = false; bool pushing = false; bool carrying = XState.Equals(HorizontalState.Carrying); #region Trying to move if (Math.Abs(Velocity.X) == 0) TryingToMove = true; #endregion #region Gravity Velocity.Y += WorldSettings.GRAVITY; #endregion #region Update Position/Velocity and Resolve Collision ResolveXCollision(delta, tiles); ResolveYCollision(delta, tiles); #endregion #region Air Friction Velocity.X *= WorldSettings.AIR_FRICTION; #endregion #region Rounding if (Math.Abs(Velocity.X) < WorldSettings.SLIDING_CUTOFF) Velocity.X = 0; #endregion #region UpdateDst UpdateDst(); #endregion #region Next Vertical State Rectangle nextDst = Dst; bool onGround = false; nextDst.Y += (int)Math.Ceiling(Velocity.Y + WorldSettings.GRAVITY * delta); foreach (Tile t in tiles) if (t.Solid) if (nextDst.Intersects(t.Dst)) onGround = true; #endregion #region Next Horizontal State nextDst = Dst; nextDst.X += (int)Math.Round((Velocity.X + MoveSpeed * Direction) * delta); Tile tileToPush = null; foreach (Tile t in tiles) if (t.Solid) if (nextDst.Intersects(t.Dst)) if (t.Pushable) tileToPush = t; if (tileToPush != null) { if (!XState.Equals(HorizontalState.Carrying)) { pushing = true; Game1.Events.Notify(Event.PlayerPushesTile, new object[] { this, tileToPush }); } } #endregion // Update States if (onGround) YState = VerticalState.OnGround; else if (Velocity.Y < 0) YState = VerticalState.Jumping; else if (Velocity.Y > 0) YState = VerticalState.Falling; if (HState.Equals(HealthState.Hurt)) { HurtCounter--; if (HurtCounter <= 0) HState = HealthState.Normal; } if (carrying || pushing) { } else if (Velocity.X == 0) XState = HorizontalState.Stopped; else XState = HorizontalState.Walking; // Lock on moving platforms if (LockOnTileTile != null) { Vector2 tileDisplacement = LockOnTileTile.Movement.GetDisplacement(); if (LockToHorizontalTile) Position.X += tileDisplacement.X; if (LockToVerticalTile) { Position.Y = LockOnTileTile.Position.Y - Dst.Height - 3; // Cancel Out Gravity Velocity.Y -= WorldSettings.GRAVITY * delta; } UpdateDst(); if (!YState.Equals(VerticalState.OnGround)) ReleaseLocks(); } }
// Avoid weird movements in the event of fps loss void FixedUpdate() { // VERTICAL STATE MACHINE if (currentVState != VerticalState.dead && currentHState != HorizontalState.changingDirection && currentHState != HorizontalState.changingOrientation && currentHState != HorizontalState.slowingDown) { switch (currentVState) { case VerticalState.running: if (inputManager.playerInputs.Jump) { currentVState = VerticalState.jumping; _movement.Jump(); break; } if (inputManager.playerInputs.Slide) { currentVState = VerticalState.sliding; _movement.Slide(); break; } break; case VerticalState.jumping: bool jumpFinished = _movement.Jumping(); if (jumpFinished) { currentVState = VerticalState.running; } break; case VerticalState.sliding: if (inputManager.playerInputs.Jump) { currentVState = VerticalState.springing; _movement.SpringMovement(); } else // Maybe erase this else if things start to go bad { bool slideFinishing = _movement.Sliding(inputManager.playerInputs.Slide); if (slideFinishing) { currentVState = VerticalState.finishSliding; } } break; case VerticalState.springing: bool springFinished = _movement.FinishSliding(); if (springFinished) { currentVState = VerticalState.jumping; } break; case VerticalState.finishSliding: if (inputManager.playerInputs.Jump) { currentVState = VerticalState.springing; _movement.SpringMovement(); } else { bool isFinished = _movement.FinishSliding(); if (isFinished) { currentVState = VerticalState.running; } } break; default: break; } } // HORIZONTAL STATE MACHINE if (currentHState != HorizontalState.dead) { switch (currentHState) { case HorizontalState.running: _movement.CorrectPosition(); if (_movement.CheckIfCrossRoads()) { currentHState = HorizontalState.slowingDown; } else if (_movement.MoveToCenter()) { currentHState = HorizontalState.movingToCenter; } checkSwitchLanes(); _movement.SetForwardSpeed(inputManager.playerInputs.ChangeSpeed); _movement.SetForwardMovement(); break; case HorizontalState.movingToCenter: bool finishedMovingToCenter = _movement.MovingToCenter(); if (finishedMovingToCenter) { currentHState = HorizontalState.running; } break; case HorizontalState.slowingDown: bool finishedSlowDown = _movement.SlowDown(); if (finishedSlowDown) { _eventBroker.emitChoosingLane(); currentHState = HorizontalState.changingDirection; } break; case HorizontalState.changingDirection: changeDirection(); break; case HorizontalState.changingOrientation: bool finishedChange = _movement.changeOrientation(); if (finishedChange) { currentHState = HorizontalState.changingDirection; } break; case HorizontalState.switchingLane: if (_movement.CheckIfCrossRoads()) { currentHState = HorizontalState.slowingDown; } SwitchingLanes(); break; default: break; } //Move player _movement.Move(); } }
public static bool SetPlayerVerticalState(VerticalState nextState) { if (player == null) { return false; } CharacterMotor motor = player.GetComponentInChildren<CharacterMotor>(); if (motor == null) { return false; } return motor.ChangeState(nextState); }
public override void Death() { currentHState = HorizontalState.dead; currentVState = VerticalState.dead; Destroy(gameObject); }
public void Update(GameTime gameTime) { var keyboard = Keyboard.GetState(); var viewport = game.GraphicsDevice.Viewport; if (Position.X > 960) { Position.X = 960; } // Vertical movement switch (verticalState) { case VerticalState.Ground: if (keyboard.IsKeyDown(Keys.Space)) { verticalState = VerticalState.Jumping; jumpTimer = new TimeSpan(0); } break; case VerticalState.Jumping: jumpTimer += gameTime.ElapsedGameTime; // Simple jumping with platformer physics Position.Y -= (JumpHeight / (float)jumpTimer.TotalMilliseconds); if (jumpTimer.TotalMilliseconds >= JUMP_TIME) { verticalState = VerticalState.Falling; } break; case VerticalState.Falling: Position.Y += speed; if (Position.Y > 450) { Position.Y = 450; verticalState = VerticalState.Ground; } break; } // Horizontal movement if (keyboard.IsKeyDown(Keys.Left)) { if (verticalState == VerticalState.Jumping || verticalState == VerticalState.Falling) { animationState = PlayerAnimState.JumpingLeft; } else { animationState = PlayerAnimState.WalkingLeft; } Position.X -= speed; } else if (keyboard.IsKeyDown(Keys.Right)) { if (verticalState == VerticalState.Jumping || verticalState == VerticalState.Falling) { animationState = PlayerAnimState.JumpingRight; } else { animationState = PlayerAnimState.WalkingRight; } Position.X += speed; } else { animationState = PlayerAnimState.Idle; } // Apply animations switch (animationState) { case PlayerAnimState.Idle: currentFrame = 0; animationTimer = new TimeSpan(0); break; case PlayerAnimState.JumpingLeft: spriteEffects = SpriteEffects.None; currentFrame = 7; break; case PlayerAnimState.JumpingRight: spriteEffects = SpriteEffects.FlipHorizontally; currentFrame = 7; break; case PlayerAnimState.WalkingLeft: animationTimer += gameTime.ElapsedGameTime; spriteEffects = SpriteEffects.None; // Walking frames are 9 & 10 if (animationTimer.TotalMilliseconds > FRAME_RATE * 2) { animationTimer = new TimeSpan(0); } currentFrame = (int)Math.Floor(animationTimer.TotalMilliseconds / FRAME_RATE) + 9; break; case PlayerAnimState.WalkingRight: animationTimer += gameTime.ElapsedGameTime; spriteEffects = SpriteEffects.FlipHorizontally; // Walking frames are 9 & 10 if (animationTimer.TotalMilliseconds > FRAME_RATE * 2) { animationTimer = new TimeSpan(0); } currentFrame = (int)Math.Floor(animationTimer.TotalMilliseconds / FRAME_RATE) + 9; break; } Debug.WriteLine($"X {Position.X}"); }
/// <summary> /// This method updates the state of the player based on position and keys pressed. /// </summary> /// <param name="kbState">This is the current KeyBoardState</param> /// <param name="prevState">This is the previouse KeyBoardState</param> public void move(KeyboardState kbState, KeyboardState prevState) { //Print out debugging info //Console.WriteLine("VSTATE: " + vState); //Console.WriteLine("HSTATE: " + hState); //Console.WriteLine("POSITION: " + " ( " + position.X + ", " + position.Y + " ) "); //Console.WriteLine("VELOCITY: " + " ( " + velocity.X + ", " + velocity.Y + " ) "); //Set the x velocity to 0 automatically and set the horizontal state to standing by default velocity.X = 0; hState = HorizontalState.standing; //Check key presses to move player if (kbState.IsKeyDown(Keys.Left) && kbState.IsKeyUp(Keys.Right)) { //Move left as long as there is room if (position.X > 0 + xSpeed) { hState = HorizontalState.walkingLeft; //Move the player to the left velocity.X = -1 * xSpeed; } } if (kbState.IsKeyDown(Keys.Right) && kbState.IsKeyUp(Keys.Left)) { //Move right as long as there is room if (position.X < ((float)screenWidth - xSpeed) / 2 - texture.Width / 2) { hState = HorizontalState.walkingRight; //Move the player to the right velocity.X = xSpeed; } else { world.movePlatforms((int)xSpeed); for (int i = 0; i < torches.Length; i++) { if (torches[i].Falling == false) { torches[i].Location = new Vector2(torches[i].Location.X - xSpeed, torches[i].Location.Y); } } hState = HorizontalState.walkingRight; } } // Jumping/Falling if (kbState.IsKeyDown(Keys.Up)) // If the player is currently pressing up. { if (vState == VerticalState.none || vState == VerticalState.fallingPlatform) // If the player's veritcal state is none (not falling or jumping) or the player is on a Falling Platform. { currentPlatform = null; vState = VerticalState.jumping; velocity.Y = -2 * ySpeed; } } else if (vState == VerticalState.jumping) // If the player is currently not pressing up and is jumping. { // Stop the jump. vState = VerticalState.falling; velocity.Y = -0.50f * velocity.Y; } //Check for collision detection if (vState == VerticalState.falling) { foreach (Platform p in world.getPlatforms()) { if (body.Intersects(p.Bounds)) { // && (position.X > p.Bounds.Left - 50 *.75) && (position.X < p.Bounds.Right - 50 * .75) if (position.Y + 50 < p.Bounds.Top + 18) { position.Y = p.Bounds.Top - 49; vState = VerticalState.none; velocity.Y = 0; currentPlatform = p; } } } } if (vState == VerticalState.none) { bool isColliding = false; foreach (Platform p in world.getPlatforms()) { if (body.Intersects(p.Bounds)) { isColliding = true; } } if (!isColliding) { vState = VerticalState.falling; currentPlatform = null; } } if (vState == VerticalState.fallingPlatform) // Check to see if the player is still on the platform horizontally. { if (position.X + 50 < currentPlatform.Bounds.Left || position.X > currentPlatform.Bounds.Right) { vState = VerticalState.falling; currentPlatform = null; } } if (position.Y >= screenHeight - 50) // If the player is at the bottom of the screen. { if (vState == VerticalState.falling || vState == VerticalState.fallingPlatform) // If the player's vertical state is falling or fallingPlatform. { position.Y = screenHeight - 50; vState = VerticalState.none; velocity.Y = 0; } } //Add our velocity to our position vector position.X += velocity.X; position.Y += velocity.Y; body.X = (int)position.X; body.Y = (int)position.Y; //Check to see if player is throwing torches throwTorches(kbState, prevState); //Update all torches, if any for (int i = 0; i < torches.Length; i++) { torches[i].update(); } }
public void Stop() => State = VerticalState.Stop;
public override void Death() { currentHState = HorizontalState.dead; currentVState = VerticalState.dead; }
// Use this for initialization void Start() { InitializeRun(); currentVState = VerticalState.running; //Initially running currentHState = HorizontalState.running; }
/// <summary> /// This method tells the player what to do based on what state he is in /// </summary> public void checkState() { if (vState == VerticalState.falling) { //Subtract gravity velocity.Y += gravity; } else if (vState == VerticalState.jumping) { //Subtract gravity velocity.Y += gravity; //Check to see if the player needs to start falling if (velocity.Y >= 0) { vState = VerticalState.falling; } } else if (hState == HorizontalState.standing) { //If the horizontal state is standing, then the player is neither jumping or falling vState = VerticalState.none; } else if (hState == HorizontalState.walkingLeft) { vState = VerticalState.none; } else if(hState == HorizontalState.walkingRight) { vState = VerticalState.none; } }
/// <summary> /// This method updates the state of the player based on position and keys pressed. /// </summary> /// <param name="kbState">This is the current KeyBoardState</param> /// <param name="prevState">This is the previouse KeyBoardState</param> public void move(KeyboardState kbState, KeyboardState prevState, Powerup tPower) { //Print out debugging info //Console.WriteLine("VSTATE: " + vState); //Console.WriteLine("HSTATE: " + hState); //Console.WriteLine("POSITION: " + " ( " + position.X + ", " + position.Y + " ) "); //Console.WriteLine("VELOCITY: " + " ( " + velocity.X + ", " + velocity.Y + " ) "); //Set the x velocity to 0 automatically and set the horizontal state to standing by default velocity.X = 0; hState = HorizontalState.standing; //Check key presses to move player if ((kbState.IsKeyDown(Keys.Left) && kbState.IsKeyUp(Keys.Right)) || (kbState.IsKeyDown(Keys.A) && kbState.IsKeyUp(Keys.D))) { //Move left as long as there is room if (position.X > 0 + xSpeed) { hState = HorizontalState.walkingLeft; //Move the player to the left velocity.X = -1 * xSpeed; } animCycle.lastFrame(); } if ((kbState.IsKeyDown(Keys.Right) && kbState.IsKeyUp(Keys.Left)) || (kbState.IsKeyDown(Keys.D) && kbState.IsKeyUp(Keys.A))) { //Move right as long as there is room if (position.X < ((float)screenWidth - xSpeed)/2 - texture.Width / 2) { hState = HorizontalState.walkingRight; //Move the player to the right velocity.X = xSpeed; } else { world.bg.scroll((int)xSpeed-3); world.movePlatforms((int)xSpeed); for (int i = 0; i < torches.Length; i++) { if (torches[i].Falling == false) { torches[i].Location = new Vector2(torches[i].Location.X - xSpeed, torches[i].Location.Y); } } hState = HorizontalState.walkingRight; world.rocks.scroll((int)xSpeed - 1); } animCycle.nextFrame(); } // Jumping/Falling if (kbState.IsKeyDown(Keys.Up) || kbState.IsKeyDown(Keys.Space) || kbState.IsKeyDown(Keys.W)) // If the player is currently pressing up. { if (vState == VerticalState.none || vState == VerticalState.fallingPlatform) // If the player's veritcal state is none (not falling or jumping) or the player is on a Falling Platform. { currentPlatform = null; vState = VerticalState.jumping; velocity.Y = -2 * ySpeed; } } else if (vState == VerticalState.jumping) // If the player is currently not pressing up and is jumping. { // Stop the jump. vState = VerticalState.falling; velocity.Y = -0.5f * velocity.Y; } //Check for collision detection if(vState == VerticalState.falling) { foreach (Platform p in world.getPlatforms()) { if (body.Intersects(p.Bounds)) { // && (position.X > p.Bounds.Left - 50 *.75) && (position.X < p.Bounds.Right - 50 * .75) if (position.Y + 44 < p.Bounds.Top + 18) { position.Y = p.Bounds.Top - 43; vState = VerticalState.none; velocity.Y = 0; currentPlatform = p; } } } } if (vState == VerticalState.none) { bool isColliding = false; foreach (Platform p in world.getPlatforms()) { if (body.Intersects(p.Bounds)) { isColliding = true; } } if (!isColliding) { vState = VerticalState.falling; currentPlatform = null; } } if (vState == VerticalState.fallingPlatform) // Check to see if the player is still on the platform horizontally. { if (position.X + 50 < currentPlatform.Bounds.Left || position.X > currentPlatform.Bounds.Right) { vState = VerticalState.falling; currentPlatform = null; } } if (position.Y >= screenHeight - 44) // If the player is at the bottom of the screen. { if (vState == VerticalState.falling || vState == VerticalState.fallingPlatform) // If the player's vertical state is falling or fallingPlatform. { world.reset(tPower); } } //Add our velocity to our position vector position.X += velocity.X; position.Y += velocity.Y; body.X = (int)position.X; body.Y = (int)position.Y; //Check to see if player is throwing torches throwTorches(kbState, prevState, tPower); //Update all torches, if any for (int i = 0; i < torches.Length; i++) { torches[i].update(); } }
public void reset(Powerup tp) { position = new Vector2(150, 50); body = new Rectangle((int)position.X, (int)position.Y, 50, 50); velocity = new Vector2(0, 0); hState = HorizontalState.standing; //Make an array of three torches torches = new Torch[999]; for (int i = 0; i < torches.Length; i++) { torches[i] = new Torch(this, flameTexture, world); } vState = VerticalState.none; tp.setUses(3); }
public void Update(GameTime gameTime) { var keyboardState = Keyboard.GetState(); switch (verticalState) { case VerticalState.Ground: if (keyboardState.IsKeyDown(Keys.Space)) { verticalState = VerticalState.Jumping; jumpTimer = new TimeSpan(0); } break; case VerticalState.Jumping: jumpTimer += gameTime.ElapsedGameTime; // Simple jumping with platformer physics Bounds.Y -= (250 / (float)jumpTimer.TotalMilliseconds); if (jumpTimer.TotalMilliseconds >= JUMP_TIME) { verticalState = VerticalState.Falling; } break; case VerticalState.Falling: Bounds.Y += vSpeed; // TODO: This needs to be replaced with collision logic if (Bounds.Y > game.GraphicsDevice.Viewport.Height || Bounds.Y == game.GraphicsDevice.Viewport.Height) { verticalState = VerticalState.Ground; Bounds.Y = game.GraphicsDevice.Viewport.Height; } break; } // horizontal movement if (keyboardState.IsKeyDown(Keys.Left)) { // move left horizontalState = HorizontalState.Left; Bounds.X -= speed * (float)gameTime.ElapsedGameTime.TotalMilliseconds; } else if (keyboardState.IsKeyDown(Keys.Right)) { // move right horizontalState = HorizontalState.Right; Bounds.X += speed * (float)gameTime.ElapsedGameTime.TotalMilliseconds; } else { horizontalState = HorizontalState.Idle; } // Stop the ship from going off-screen /* * if (Bounds.X < 0) * { * Bounds.X = 0; * } * if (Bounds.X > game.GraphicsDevice.Viewport.Width - Bounds.Width) * { * Bounds.X = game.GraphicsDevice.Viewport.Width - Bounds.Width; * } */ }
private void FixedUpdate() { // Vertical state switch (State) { case VerticalState.Grounded: { // Check if we should be falling float groundDistance = Utils.MultiRaycast(Vector2.down, PlayerVars.FallSpeedBase + Extents.y, new Vector2[] { new Vector2(_col.bounds.center.x - Extents.x + EdgeRayOffset, Center.y), Center, new Vector2(Center.x + Extents.x - EdgeRayOffset, Center.y) }, CollisionMask, Color.blue); if (groundDistance - Extents.y > 0) { State = VerticalState.Falling; } break; } case VerticalState.Jumping: // Clamp distance to targetHeight float targetDistance = PlayerVars.JumpSpeedBase + Extents.y; bool reachedPeak = false; if (Center.y + targetDistance >= _targetJumpHeight) { targetDistance = _targetJumpHeight - Center.y; reachedPeak = true; } // Check for collision if return from raycasts is lower than targetdistance we must have hit something, set falling float jumpDistance = Utils.MultiRaycast(Vector2.up, targetDistance, new Vector2[] { new Vector2(Center.x - Extents.x + EdgeRayOffset, Center.y), Center, new Vector2(Center.x + Extents.x - EdgeRayOffset, Center.y) }, CollisionMask, Color.blue); // Change state to falling if (jumpDistance < targetDistance || reachedPeak) { State = VerticalState.Falling; } // apply jumpDistance jumpDistance -= Extents.y; if (jumpDistance > 0) { transform.Translate(Vector2.up * jumpDistance); } break; case VerticalState.Falling: float fallingDistance = Utils.MultiRaycast(Vector2.down, PlayerVars.FallSpeedBase + Extents.y, new Vector2[] { new Vector2(Center.x - Extents.x + EdgeRayOffset, Center.y), Center, new Vector2(Center.x + Extents.x - EdgeRayOffset, Center.y) }, CollisionMask, Color.blue); fallingDistance -= Extents.y; if (fallingDistance >= 0.001f) { transform.Translate(Vector2.down * fallingDistance); } else { // If we have stopped falling, change state to Grounded State = VerticalState.Grounded; } break; } // Horizontal state if (_moveInput != 0) { float distance = PlayerVars.MoveSpeedBase + Extents.x; Vector2 direction = _moveInput > 0 ? Vector2.right : Vector2.left; distance = Utils.MultiRaycast(direction, distance, new Vector2[] { new Vector2(Center.x, Center.y + Extents.y - EdgeRayOffset), Center, new Vector2(Center.x, Center.y - Extents.y + EdgeRayOffset), }, CollisionMask, Color.blue); distance -= Extents.x; transform.Translate(direction * distance); } }
/// <summary> /// This method updates the state of the player based on position and keys pressed. /// </summary> /// <param name="kbState">This is the current KeyBoardState</param> /// <param name="prevState">This is the previouse KeyBoardState</param> public void move(KeyboardState kbState, KeyboardState prevState) { //Print out debugging info Console.WriteLine("VSTATE: " + vState); Console.WriteLine("HSTATE: " + hState); //Console.WriteLine("POSITION: " + " ( " + position.X + ", " + position.Y + " ) "); //Console.WriteLine("VELOCITY: " + " ( " + velocity.X + ", " + velocity.Y + " ) "); //Set the x velocity to 0 automatically and set the horizontal state to standing by default velocity.X = 0; hState = HorizontalState.standing; //Check key presses to move player if (kbState.IsKeyDown(Keys.Left)) { //Move left as long as there is room if (position.X > 0 + speed) { hState = HorizontalState.walkingLeft; //Move the player to the left velocity.X = -1 * speed; } } if (kbState.IsKeyDown(Keys.Right)) { //Move right as long as there is room if (position.X < ((float)screenWidth - speed)/2 - texture.Width / 2) { hState = HorizontalState.walkingRight; //Move the player to the right velocity.X = speed; } else { world.movePlatforms((int)speed); } } //Have the player jump if (kbState.IsKeyDown(Keys.Up) && prevState.IsKeyUp(Keys.Up) && vState == VerticalState.none) { //Set our new player state vState = VerticalState.jumping; velocity.Y = -2 * speed; } //Check to see if our player is standing on anything if (position.Y >= screenHeight - 50 && vState == VerticalState.falling) { position.Y = screenHeight - 50; vState = VerticalState.none; velocity.Y = 0; } //Add our velocity to our position vector position.X += velocity.X; position.Y += velocity.Y; }
private void Update() { switch (State) { case VerticalState.Grounded: if (Input.GetKey(KeyCode.Space)) { _targetJumpHeight = Center.y + Extents.y + (PlayerVars.JumpHeightBase * PlayerVars.JumpHeightModifier[PlayerVars.JumpHeightCurModifier]) + 0.2f; State = VerticalState.Jumping; } break; case VerticalState.Jumping: break; case VerticalState.Falling: break; } _moveInput = Input.GetAxisRaw("Horizontal"); if (_moveInput < 0) { BodySprite.transform.localScale = new Vector3(-1, 1, 1); } else if (_moveInput > 0) { BodySprite.transform.localScale = new Vector3(1, 1, 1); } // Get the current target ItemParams item = GetTarget(); // Left Click if (Input.GetMouseButton(0)) { if (_canSwing) { item.ClickType = ClickType.Left; PlayerInventory.UseSelectedItem(item); StartCoroutine(SwingTimer()); } } // Right Click if (Input.GetMouseButtonDown(1)) { item.ClickType = ClickType.Right; PlayerInventory.UseSelectedItem(item); } // UI Slot selection // TODO: Should this be in a separate script? if (Input.GetKeyDown(KeyCode.Alpha1)) { PlayerInventory.ChangeSelectedSlot(0); } if (Input.GetKeyDown(KeyCode.Alpha2)) { PlayerInventory.ChangeSelectedSlot(1); } float scroll = Input.GetAxisRaw("Mouse ScrollWheel"); if (scroll != 0) { if (scroll > 0) { PlayerInventory.ChangeSelectedSlot(PlayerInventory.SelectedSlot - 1); } else { PlayerInventory.ChangeSelectedSlot(PlayerInventory.SelectedSlot + 1); } } }
// Avoid weird movements in the event of fps loss void FixedUpdate() { // VERTICAL STATE MACHINE if (currentVState != VerticalState.dead) { switch (currentVState) { case VerticalState.running: if (currentIState.Jump) { currentVState = VerticalState.jumping; _movement.Jump(); break; } if (currentIState.Slide) { currentVState = VerticalState.sliding; _movement.Slide(); break; } break; case VerticalState.jumping: bool jumpFinished = _movement.Jumping(); if (jumpFinished) { currentVState = VerticalState.running; } break; case VerticalState.sliding: if (currentIState.Jump) { currentVState = VerticalState.springing; _movement.SpringMovement(); } else // Maybe erase this else if things start to go bad { bool slideFinishing = _movement.Sliding(currentIState.Slide); if (slideFinishing) { currentVState = VerticalState.finishSliding; } } break; case VerticalState.springing: bool springFinished = _movement.FinishSliding(); if (springFinished) { currentVState = VerticalState.jumping; } break; case VerticalState.finishSliding: if (currentIState.Jump) { currentVState = VerticalState.springing; _movement.SpringMovement(); } else { bool isFinished = _movement.FinishSliding(); if (isFinished) { currentVState = VerticalState.running; } } break; default: break; } } // HORIZONTAL STATE MACHINE if (currentHState != HorizontalState.dead) { switch (currentHState) { case HorizontalState.running: _movement.CorrectPosition(); checkSwitchLanes(); break; case HorizontalState.switchingLane: SwitchingLanes(); break; default: break; } //Move player if (moving) { _movement.Move(); } } }
/// <summary> /// Will attempt to change this character's present VerticalState to the specified state. /// Will not do anything if the state could not be changed. /// </summary> /// <param name="nextState">The state to try and change to. </param> /// <returns>TRUE if it was successful, else false.</returns> public bool ChangeState(VerticalState nextState) { currentVerticalState = nextState; return nextState == currentVerticalState; }