Desenhando muitos bitmaps com XNA no Windows Phone 7 - parte 2
Este post é uma continuação do artigo Desenhando muitos bitmaps com XNA no Windows Phone 7 epor isso, se ainda não leu o post anterior, confere lá!
Se você é um bom leitor e já não só leu todos artigos anteriores como também fez todos os exercícios práticos, primeiramente.. PARABÉNS \/ , mas já pode ir abrindo o Visual Studio pois temos uma tarefa a concluir.
Missão: Desenhar muitos bitmaps na mesma tela do Windows Phone 7 porém utilizando melhores práticas de programação. Falamos sobre collections e arrays no ultimo post, certo? Então mão na massa.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;
namespace WindowsPhoneGame6
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Vector2[] positions;
Texture2D[] images;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
// Frame rate is 30 fps by default for Windows Phone.
TargetElapsedTime = TimeSpan.FromTicks(333333);
// Extend battery life under lock.
InactiveSleepTime = TimeSpan.FromSeconds(1);
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
images = new Texture2D[5];
images[0] = Content.Load<Texture2D>("cave1");
images[1] = Content.Load<Texture2D>("cave2");
images[2] = Content.Load<Texture2D>("cave3");
images[3] = Content.Load<Texture2D>("cave4");
images[4] = Content.Load<Texture2D>("cave5");
positions = new Vector2[5];
positions[0] = new Vector2(100, 180);
positions[1] = new Vector2(210, 180);
positions[2] = new Vector2(320, 180);
positions[3] = new Vector2(430, 180);
positions[4] = new Vector2(540, 180);
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
// TODO: Add your drawing code here
spriteBatch.Begin();
for (int n = 0; n < 5; n++)
{
spriteBatch.Draw(images[n], positions[n], Color.White);
}
spriteBatch.End();
base.Draw(gameTime);
}
}
}
Importante, o código irá gerar o mesmo resultado do teste anterior, no meu caso, o quinteto cavernoso. (tenho certeza que fez algo mais criativo do que eu)
Mas vamos voltar para nósso código, análisá-lo e destacar algumas partes?
O que fizemos de diferente?
Primeiro, nosso método LoadContent() ficou um pouquinho mais complicado
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
images = new Texture2D[5];
images[0] = Content.Load<Texture2D>("cave1");
images[1] = Content.Load<Texture2D>("cave2");
images[2] = Content.Load<Texture2D>("cave3");
images[3] = Content.Load<Texture2D>("cave4");
images[4] = Content.Load<Texture2D>("cave5");
positions = new Vector2[5];
positions[0] = new Vector2(100, 180);
positions[1] = new Vector2(210, 180);
positions[2] = new Vector2(320, 180);
positions[3] = new Vector2(430, 180);
positions[4] = new Vector2(540, 180);
}
Mas por outro lado, veja só nosso método Draw()
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
// TODO: Add your drawing code here
spriteBatch.Begin();
for (int n = 0; n < 5; n++)
{
spriteBatch.Draw(images[n], positions[n], Color.White);
}
spriteBatch.End();
base.Draw(gameTime);
}
Agora sim você viu lucro em refazermos nosso código não é mesmo? Ainda não?? Compare com o Draw() anterior
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
// TODO: Add your drawing code here
spriteBatch.Begin();
spriteBatch.Draw(image1, position1, Color.White);
spriteBatch.Draw(image2, position2, Color.White);
spriteBatch.Draw(image3, position3, Color.White);
spriteBatch.Draw(image4, position4, Color.White);
spriteBatch.Draw(image5, position5, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
Agora pense que ao invés de utilizar 5 imagens, nós estivessemos utilizando 100, e então me responda:
Quantas linhas de código eu teria que adicionar em cada um deles?
No anterior, cada imagem ocuparia uma linha de código. Já no segundo, colocaríamos 2 caracteres adicionais. Detalhe, as posições nós não otimizamos, mas poderíamos sem nenhum problema também. Estes posts são dedicados principalmente a Windows Phone 7, e como estamos focando em games, continuaremos falando bastante de XNA. Mas para os iniciantes, acredito que um pouco de conceitos de lógica, linguagem e boas práticas de programação virá bem a calhar.
até mais!
Posts anteriores
Visão geral do MVA - entendendo o roteiro de Windows Phone
O Windows Mobile e o Windows Phone
Visão geral do Windows Phone 7.5 (codinome Mango)
Visão geral do SDK do Windows Phone
Visão geral das ferramentas de desenvolvimento para Windows Phone
O que é o Windows Phone Marketplace parte 1 - Publicando sua app no Marketplace
O que é o Windows Phone Marketplace parte 2 - Publicando sua app no Marketplace
Crie seu primeiro projeto XNA 4.0 para Windows Phone 7
Entendendo o User Input no Windows Phone 7 com XNA
Utilizando gestos no Windows Phone 7
Desenhando Bitmaps com XNA no Windows Phone 7
Tratando Bitmaps como Sprites utilizando XNA no Windows Phone 7