sábado, 3 de dezembro de 2011

063 - AmareloGameEngine[3]: Tornando o seu teclado útil

Nos posts anteriores, aprendemos a montar o esqueleto de nosso jogo ( e de futuros jogos que usem a AmareloGameEngine ) e adicionar assets ao jogo ( imagens de fundo, sprite do personagem...). Vamos tentar agora fazer algo aparentemente simples: mover o personagem.

5. Captura de teclado
Até aqui, não elaboramos nenhum código para captura de entrada de teclado ou mouse. Nos exemplos anteriores, possivelmente o seu jogo gerará uma exceção de referência nula caso você aperte qualquer botão do teclado como esse:



Precisamos criar dois métodos para tratar essa exceção: um método para quando o jogador apertar o botão e outro para quando soltar o mesmo botão.
  • Ao final do arquivo "Game1.cs" , crie dois novos métodos
 public void tecla (object o, KeyBoardEvent e) //chamada quando o jogador aperta o botao  
 {  
 }  


 public void teclaR (object o, KeyBoardEvent e) //chamada quando o jogador solta o botao q apertou  
 {  
 }  

  • No  initialize() adicione essas linhas:
 this.inputEngine.KeyPressed += tecla;  
 this.inputEngine.KeyReleased += teclaR;  


  • No escopo da classe, crie um array de quatro booleanos:
 bool[] teclas = { false, false, false, false };  


Cada posição do array indicará uma direção: Vamos definir:
   -- 0 como esquerda
   -- 1 como direita
   -- 2 como para cima
   -- 3 como para baixo

  • No método tecla(), faça um conjunto de if's como segue:
 if (e.Key == Keys.Left)  
 {  
   teclas[0] = true;  
 }  
 else if (e.Key == Keys.Right)  
 {  
   teclas[1] = true;  
 }  
 else if (e.Key == Keys.Up)  
 {  
   teclas[2] = true;  
 }  
 else if (e.Key == Keys.Down)  
 {  
   teclas[3] = true;  
 }  


  • E no método teclaR(), faça o mesmo conjunto de if's, retornando false ao invés de true.
 if (e.Key == Keys.Left)  
 {  
   teclas[0] = false;  
 }  
 else if (e.Key == Keys.Right)  
 {  
   teclas[1] = false;  
 }  
 else if (e.Key == Keys.Up)  
 {  
   teclas[2] = false;  
 }  
 else if (e.Key == Keys.Down)  
 {  
   teclas[3] = false;  
 }  


  • No método update(), faça outro conjunto de if's usando o estado da variável teclas:
 if (teclas[0])  
 {  
   s[CHAR1].posX--;  
 }  
 else if (teclas[1])  
 {  
   s[CHAR1].posX++;  
 }  
 else if (teclas[2])  
 {  
   s[CHAR1].posY--;  
 }  
 else if (teclas[3])  
 {  
   s[CHAR1].posY++;  
 }  


  • Esse é o nosso código até o momento
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 Amarelo;  
12:  using Amarelo.GameEngine;  
13:  namespace testetutorial  
14:  {  
15:    /// <summary>  
16:    /// This is the main type for your game  
17:    /// </summary>  
18:    public class testetutorial : Amarelo.AmareloGame  
19:    {  
20:      public const int BACKGROUND = 0;  
21:      public const int CHAR1 = 1;  
22:      List<Sprite> s = new List<Sprite>(); //Cria uma lista de sprites  
23:      bool[] teclas = { false, false, false, false };  
24:      public testetutorial(GameConfig cg) : base(cg)  
25:      {  
26:        Content.RootDirectory = "Content";  
27:      }  
28:      /// <summary>  
29:      /// This is called when the game should draw itself.  
30:      /// </summary>  
31:      /// <param name="gameTime">Provides a snapshot of timing values.</param>  
32:      protected override void Draw(GameTime gameTime)  
33:      {  
34:        GraphicsDevice.Clear(Color.CornflowerBlue);  
35:        // TODO: Add your drawing code here  
36:        base.Draw(gameTime);  
37:      }  
38:      protected override void initialize()  
39:      {  
40:        this.inputEngine.KeyPressed += tecla;  
41:        this.inputEngine.KeyReleased += teclaR;  
42:        //throw new NotImplementedException();  
43:      }  
44:      protected override void loadContent()  
45:      {  
46:        s.Add(new Sprite("backg", Content.Load<Texture2D>("Imagens\\background_01"), 0)); //Carrega o background na lista  
47:        s.Add(new Sprite("char1", Content.Load<Texture2D>("Sprites\\char_black"), 1)); //Carrega a sprite do personagem na lista  
48:        this.graphicsEng.addSprite(s[BACKGROUND]); //adiciona o background  
49:        this.graphicsEng.addSprite(s[CHAR1]); //adiciona a sprite  
50:      }  
51:      protected override void unloadContent()  
52:      {  
53:        //throw new NotImplementedException();  
54:      }  
55:      protected override void update(GameTime time)  
56:      {  
57:        if (teclas[0])  
58:        {  
59:          s[CHAR1].posX--;  
60:        }  
61:        else if (teclas[1])  
62:        {  
63:          s[CHAR1].posX++;  
64:        }  
65:        else if (teclas[2])  
66:        {  
67:          s[CHAR1].posY--;  
68:        }  
69:        else if (teclas[3])  
70:        {  
71:          s[CHAR1].posY++;  
72:        }  
73:      }  
74:      public void tecla(object o, KeyBoardEvent e) //chamada quando o jogador aperta o botao  
75:      {  
76:        if (e.Key == Keys.Left)  
77:        {  
78:          teclas[0] = true;  
79:        }  
80:        else if (e.Key == Keys.Right)  
81:        {  
82:          teclas[1] = true;  
83:        }  
84:        else if (e.Key == Keys.Up)  
85:        {  
86:          teclas[2] = true;  
87:        }  
88:        else if (e.Key == Keys.Down)  
89:        {  
90:          teclas[3] = true;  
91:        }  
92:      }  
93:      public void teclaR(object o, KeyBoardEvent e) //chamada quando o jogador solta o botao q apertou  
94:      {  
95:        if (e.Key == Keys.Left)  
96:        {  
97:          teclas[0] = false;  
98:        }  
99:        else if (e.Key == Keys.Right)  
100:        {  
101:          teclas[1] = false;  
102:        }  
103:        else if (e.Key == Keys.Up)  
104:        {  
105:          teclas[2] = false;  
106:        }  
107:        else if (e.Key == Keys.Down)  
108:        {  
109:          teclas[3] = false;  
110:        }  
111:      }  
112:    }  
113:  }  


  • Salve e teste
  • Agora apertando as teclas esquerda, direita, pra cima e pra baixo, o seu personagem irá se deslocar para a direção desejada sem gerar possíveis erros de referência nula.
  • A seguir, construiremos a física do nosso jogo: faremos o personagem pular, cair, andar sobre uma superfície sólida, etc...

Nenhum comentário:

Postar um comentário