jueves, 8 de abril de 2010

Desarrollo de un juego 2D con XNA V - Insertar y controlar un sprite



Estimados amigos

Nuevamente, bienvenidos a este blog.

En el post de hoy seguiremos extendiendo el caso presentado anteriormente. La última vez quedamos con un juego que solo muestra un fondo espacial. Hoy, agregaremos un sprite, un objeto de juego que puede ser controlado por teclado. El sprite en cuestión será un cañon, el que al presionar las teclas izquierda o derecha rotara sobre su centro.

Tal como indiqué en el post anterior, los sprites, como los fondos son texturas(Texture2D) pero los sprites, al no ser estáticos sino que tienen posiciones, rotaciones, transformaciones que a lo largo del juego varían han de implementarse de una forma un tanoto distinta.

Para empezar, vamos a crear una clase que contendrá los datos pertinentes a posición, rotación, su centro y a la imagen en si que representará a nuestro objeto de juego. Implementada esta clase y su constructor, veremos las modificaciones necesarias para desplegarlo en pantalla y para controlar su movimiento con nuestro teclado.

Al igual que en el post anterior, dejo acá la lista de videos de lo hecho para que sea mas fácil seguirlo y a continuación los codigos fuentes modificados.

LISTA DE VIDEOS


Acá el código de nuestra clase GameObject



   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using Microsoft.Xna.Framework;
   5:  using Microsoft.Xna.Framework.Audio;
   6:  using Microsoft.Xna.Framework.Content;
   7:  using Microsoft.Xna.Framework.GamerServices;
   8:  using Microsoft.Xna.Framework.Graphics;
   9:  using Microsoft.Xna.Framework.Input;
  10:  using Microsoft.Xna.Framework.Media;
  11:  using Microsoft.Xna.Framework.Net;
  12:  using Microsoft.Xna.Framework.Storage;
  13:   
  14:  namespace JuegoXNADemo1
  15:  {
  16:      class GameObject
  17:      {
  18:          public Texture2D Sprite;
  19:          public Vector2 Position;
  20:          public float Rotation;
  21:          public Vector2 Center;
  22:   
  23:          public GameObject(Texture2D LoadedTexture)
  24:          {
  25:              Rotation = 0.0f;
  26:              Position = Vector2.Zero;
  27:              Sprite = LoadedTexture;
  28:              Center = new Vector2(Sprite.Width / 2, Sprite.Height / 2);
  29:          }
  30:   
  31:      }
  32:  }

Y ahora el código de nuestra clase Game1



   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using Microsoft.Xna.Framework;
   5:  using Microsoft.Xna.Framework.Audio;
   6:  using Microsoft.Xna.Framework.Content;
   7:  using Microsoft.Xna.Framework.GamerServices;
   8:  using Microsoft.Xna.Framework.Graphics;
   9:  using Microsoft.Xna.Framework.Input;
  10:  using Microsoft.Xna.Framework.Media;
  11:  using Microsoft.Xna.Framework.Net;
  12:  using Microsoft.Xna.Framework.Storage;
  13:   
  14:  namespace JuegoXNADemo1
  15:  {
  16:   
  17:      public class Game1 : Microsoft.Xna.Framework.Game
  18:      {
  19:          GraphicsDeviceManager graphics;
  20:          SpriteBatch spriteBatch;
  21:          Texture2D backgroundTexture;
  22:          Rectangle viewPortRect;
  23:          GameObject Cannon;
  24:   
  25:          public Game1()
  26:          {
  27:              graphics = new GraphicsDeviceManager(this);
  28:              Content.RootDirectory = "Content";
  29:          }
  30:   
  31:          /// <summary>
  32:          /// Allows the game to perform any initialization it needs to before starting to run.
  33:          /// This is where it can query for any required services and load any non-graphic
  34:          /// related content.  Calling base.Initialize will enumerate through any components
  35:          /// and initialize them as well.
  36:          /// </summary>
  37:          protected override void Initialize()
  38:          {
  39:              // TODO: Add your initialization logic here
  40:   
  41:              base.Initialize();
  42:          }
  43:   
  44:          /// <summary>
  45:          /// LoadContent will be called once per game and is the place to load
  46:          /// all of your content.
  47:          /// </summary>
  48:          protected override void LoadContent()
  49:          {
  50:              // Create a new SpriteBatch, which can be used to draw textures.
  51:              spriteBatch = new SpriteBatch(GraphicsDevice);
  52:              backgroundTexture = Content.Load<Texture2D>("background");
  53:              Cannon = new GameObject(Content.Load<Texture2D>("cannon"));
  54:              Cannon.Position = new Vector2(120,graphics.GraphicsDevice.Viewport.Height-80);
  55:              viewPortRect = new Rectangle(0, 0, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height);
  56:              // TODO: use this.Content to load your game content here
  57:          }
  58:   
  59:          /// <summary>
  60:          /// UnloadContent will be called once per game and is the place to unload
  61:          /// all content.
  62:          /// </summary>
  63:          protected override void UnloadContent()
  64:          {
  65:              // TODO: Unload any non ContentManager content here
  66:          }
  67:   
  68:          /// <summary>
  69:          /// Allows the game to run logic such as updating the world,
  70:          /// checking for collisions, gathering input, and playing audio.
  71:          /// </summary>
  72:          /// <param name="gameTime">Provides a snapshot of timing values.</param>
  73:          protected override void Update(GameTime gameTime)
  74:          {
  75:              // Allows the game to exit
  76:              if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
  77:                  this.Exit();
  78:   
  79:              KeyboardState keyboardState = Keyboard.GetState();
  80:              if(keyboardState.IsKeyDown(Keys.Left ))
  81:              {
  82:                  Cannon.Rotation -= 0.1f;
  83:              }
  84:              if (keyboardState.IsKeyDown(Keys.Right ))
  85:              {
  86:                  Cannon.Rotation += 0.1f;
  87:              }
  88:              // TODO: Add your update logic here
  89:   
  90:              base.Update(gameTime);
  91:          }
  92:   
  93:          /// <summary>
  94:          /// This is called when the game should draw itself.
  95:          /// </summary>
  96:          /// <param name="gameTime">Provides a snapshot of timing values.</param>
  97:          protected override void Draw(GameTime gameTime)
  98:          {
  99:              GraphicsDevice.Clear(Color.CornflowerBlue);
 100:   
 101:              spriteBatch.Begin();
 102:              spriteBatch.Draw(backgroundTexture,viewPortRect,Color.White );
 103:              spriteBatch.Draw(Cannon.Sprite,Cannon.Position, null, Color.White, Cannon.Rotation, Cannon.Center, 1.0f,SpriteEffects.None, 0);
 104:              spriteBatch.End();
 105:   
 106:              // TODO: Add your drawing code here
 107:   
 108:   
 109:              base.Draw(gameTime);
 110:          }
 111:      }
 112:  }

Bueno, como siempre, gracias por su atención, un abrazo y hasta la próxima.

Manuel Gatica Holtmann

No hay comentarios:

Publicar un comentario

-__-