如何制作滚动的背景
示范如何通过SpriteBatch类绘制一个滚动的背景。源码下载
绘制滚动的背景精灵
绘制滚动的背景精灵
-
创建game类。
-
加载资源,和如何绘制精灵中所讲的1-3步一样 。
-
加载背景纹理。
private ScrollingBackground myBackground; protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); myBackground = new ScrollingBackground(); Texture2D background = Content.Load<Texture2D>("starfield"); myBackground.Load(GraphicsDevice, background); }
-
确定背景纹理和屏幕的尺寸。
纹理的大小可以由他的Height和Width属性获得,屏幕的大小可以使用图形设备的Viewport属性获得。
-
通过纹理和屏幕信息,将纹理的起点设置为纹理的中心,将屏幕的初始点设置为屏幕的中心。
// class ScrollingBackground private Vector2 screenpos, origin, texturesize; private Texture2D mytexture; private int screenheight; public void Load( GraphicsDevice device, Texture2D backgroundTexture ) { mytexture = backgroundTexture; screenheight = device.Viewport.Height; int screenwidth = device.Viewport.Width; // Set the origin so that we're drawing from the // center of the top edge. origin = new Vector2( mytexture.Width / 2, 0 ); // Set the screen position to the center of the screen. screenpos = new Vector2( screenwidth / 2, screenheight / 2 ); // Offset to draw the second texture, when necessary. texturesize = new Vector2( 0, mytexture.Height ); }
-
改变Update方法中背景纹理的屏幕位置来滚动背景。
增加屏幕Y轴值的话,背景精灵以每秒100像素的速度向下移动。
protected override void Update(GameTime gameTime) { ... // The time since Update was called last. float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; // TODO: Add your game logic here. myBackground.Update(elapsed * 100); base.Update(gameTime); }
Y轴值不能大于纹理高度,这样背景就可以在屏幕顶部和底部之间来加滚动了。
public void Update( float deltaY ) { screenpos.Y += deltaY; screenpos.Y = screenpos.Y % mytexture.Height; } // ScrollingBackground.Draw
-
用LoadContent和Update中计算的起点和屏幕位置来绘制背景。
protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); myBackground.Draw(spriteBatch); spriteBatch.End(); base.Draw(gameTime); }
如果这个纹理不能覆盖屏幕,就会绘制另一个纹理,根据加载时创建的texturesize向量从屏幕偏移向量的位置减去纹理的高度。这将给你一个循环的错觉。
public void Draw( SpriteBatch batch ) { // Draw the texture, if it is still onscreen. if (screenpos.Y < screenheight) { batch.Draw( mytexture, screenpos, null, Color.White, 0, origin, 1, SpriteEffects.None, 0f ); } // Draw the texture a second time, behind the first, // to create the scrolling illusion. batch.Draw( mytexture, screenpos - texturesize, null, Color.White, 0, origin, 1, SpriteEffects.None, 0f ); }
发布时间:2009/2/18 上午8:25:33 阅读次数:7143