- Declare 2 member variables in
Player.cs
, and initialize them in the constructor and in OnEnterStage
:
public class Player : Entity
{
float _moveSpeed;
Axis2 _moveAxis;
public Player()
{
_moveSpeed = 50.0f;
}
protected override void OnEnterStage(Stage stage)
{
base.OnEnterStage(stage);
_moveAxis = stage.Game.Controls.RightAnalog;
}
...
_moveSpeed
should be self-explanatory, and by assigning the RightAnalog property to _moveAxis
, we can query it for input from the arrow keys (whereas LeftAnalog would refer to WASD).
- In the player's
OnUpdate
method, modify the X
and Y
properties based on which keys are being pressed.
if(_moveAxis.X.IsPositive)
X += _moveSpeed * (float)dt;
else if(_moveAxis.X.IsNegative)
X -= _moveSpeed * (float)dt;
if(_moveAxis.Y.IsPositive)
Y += _moveSpeed * (float)dt;
else if(_moveAxis.Y.IsNegative)
Y -= _moveSpeed * (float)dt;
dt
is the delta time (the time since last frame). Factoring it into the movement mode keeps the gameplay framerate independent.
Animating player movement
- Duplicate the player's image and modify it slightly to create a 2-frame walk cycle. Rename them to
player_0
and player_1
.
- Add another member variable to the Player class for our walk animation:
- Create the animation after graphics have been loaded:
protected override void OnLoadGraphics(Graphics graphics)
{
_walkAnim = graphics.CreateAnimation("Resources", "player_#")(0, 1);
_walkAnim.Period = 0.25f;
_walkAnim.IsPaused = true;
Image image = _walkAnim.GetFrame(0);
_sprite = Add(
new Sprite(_walkAnim, Game.Swatches.Player),
new Vector2i(-image.Width / 2, -image.Height / 2));
}
- In the update method, start and stop the animation based on whether the player is moving or not:
if(_moveAxis.JustBecameZero)
{
_walkAnim.Reset();
_walkAnim.IsPaused = true;
}
else if(_moveAxis.JustBecameNonzero)
{
_walkAnim.IsPaused = false;
}
Facing Moving Direction
- Still in the
Player.cs
update method, add some code to flip the sprite horizontally when the player is moving to the left:
if(_moveAxis.X.IsPositive)
_sprite.FlipX = false;
else if(_moveAxis.X.IsNegative)
_sprite.FlipX = true;
Stay in Bounds
- Create a new method in the Player class:
void CheckBounds()
{
Vector2f gameSize = (Vector2f)Stage.Game.Graphics.Size;
Vector2f mySize = (Vector2f)_sprite.Size;
if(X < mySize.X * 0.5f)
X = mySize.X * 0.5f;
else if(X > gameSize.X - mySize.X * 0.5f)
X = gameSize.X - mySize.X * 0.5f;
if(Y < mySize.Y * 0.5f)
Y = mySize.Y * 0.5f;
else if(Y > gameSize.Y - mySize.Y * 0.5f)
Y = gameSize.Y - mySize.Y * 0.5f;
}
- and call the method at the end of the player's update method.
Prev Page :: Back to Index :: Next Page