有人能给我一个例子,当用户按下键盘时如何改变绘制的纹理?
基本上我有 5 个精灵图像stood still
, up
, down
, left
,right
我的第一次尝试是在更新方法中创建布尔条件,例如如果keys.left
按下矩形向左移动,而对于绘制方法来绘制向左移动的角色,我的问题是他的纹理stood still
不会消失并且在移动时重叠相同不同方向。
我尝试过其他语句等,但我坚持基本动作。
So this is very pseudo code, but this is a basic approach how to do that
First we create class which contains all our informations about the player. You can add Health, Score etc aswell.
class Player
{
Texture2D Sprite;
Vector2 Position;
Vector2 Velocity;
static const float PlayerSpeed = 5;
}
Important here is the Position (top left of the sprite), the Velocity(the amount of change every second) and the sprite which is just our texture we want to use. Of course it would be better to use only one player texture and modify the source rect accordingly.
Now our input handling.
void OnKeyboard(GameTime aGameTime, KeyArg aKey)
{
if(aKey == Keys.Left)
{
mPlayer.Velocity = new Vector2(-Player.PlayerSpeed, 0);
mPlayer.Sprite = TextureManager.GetTexture("left_player");
}
else if(aKey == Keys.Right)
{
mPlayer.Velocity = new Vector2(Player.PlayerSpeed, 0);
mPlayer.Sprite = TextureManager.GetTexture("right_player");
}
mPlayer.Position += aGameTime.EllapsedMiliseconds * mPlayer.Velocity;
}
Here we just check which key was pressed, modify the velocity and change the current sprite for our player. The final line is the most important one, this modifies the players position using the velocity modified by the elapsed time of the frame. That way you have a steady movement instead despite any frame rate inconsistencies.
void Render()
{
Sprite.Draw(mPlayer.Sprite, mPlayer.Position);
}
Finally the rendering, how to render a sprite should be clear, here you just use the set sprite and the position. There is a lot of room for improvements, for example minimizing texture switches, handling sprites with alpha, and the most important one proper handling of the keyboard. You need to steadily adjust the position, but depending on how you implement it, the movement might be bound to the key repeat rate, which may not be desired.