您的位置:首页 > 其它

自学XNA路(二)新手上路-移动背景图片

2013-03-01 02:41 190 查看
导入一个图片格式任意。

这里我导入了自己做的一个V.JPG



把文件拉到资源管理器的Content里面然后添加下面代码

Texture2D backgroundTexture;
SpriteBatch sprites;
protected override void Initialize()
{
backgroundTexture = Content.Load<Texture2D>("V");//V为文件名
sprites = new SpriteBatch(graphics.GraphicsDevice);
base.Initialize();
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Goldenrod);
sprites.Begin();
sprites.Draw(backgroundTexture, Vector2.Zero, Color.White);
sprites.End();
base.Draw(gameTime);
}
运行后就得到结果:



接着就要移动图片了.

float scrollPosition = 0;
protected override void Update(GameTime gameTime)
{
// Allows the game to exit

GamePadState gamePad=GamePad.GetState(PlayerIndex.One);
KeyboardState keyboard=Keyboard.GetState();
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed||
keyboard.IsKeyDown(Keys.Escape))
this.Exit();
float moveFactorPerSecond=200*(float)gameTime.ElapsedRealTime.TotalMilliseconds/500.0f;//每帧移动像素
if (gamePad.DPad.Up == ButtonState.Pressed || keyboard.IsKeyDown(Keys.Up))//判断按键上
scrollPosition += moveFactorPerSecond;
if (gamePad.DPad.Down == ButtonState.Pressed || keyboard.IsKeyDown(Keys.Down))//判断按键下
scrollPosition -= moveFactorPerSecond;
// TODO: Add your update logic here

base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Goldenrod);
sprites.Begin();
int resolutionWidth = graphics.GraphicsDevice.Viewport.Width;//图像宽
int resolutionHeight = graphics.GraphicsDevice.Viewport.Height;//图像高
for (int x = 0; x <= resolutionWidth / backgroundTexture.Width; x++)//填充背景图片,目前会出现刷新有问题的BUG按下会出现半截没有刷新图片露出背景
{
for (int y = -1; y <= resolutionHeight / backgroundTexture.Height; y++)
{
Vector2 position = new Vector2(x * backgroundTexture.Width, y * backgroundTexture.Height +
((int)scrollPosition) % backgroundTexture.Height);
sprites.Draw(backgroundTexture, position, Color.White);
}
}
sprites.End();
base.Draw(gameTime);
}


这样就完成自己第一个小程序,效果如下

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: