Criando um Pong com MonoGame


Requisitos:
Monogame: http://www.monogame.net/downloads/
Visual Studio: https://www.visualstudio.com/pt-br/vs/community/
Genkai.dll: http://cafecomengine.blogspot.com.br/p/genkai-framework.html

Passo 01:


Crie um novo projeto no Visual Studio, vou nomeá-lo de PongGame. Referencie a dll "Genkai.dll" ao projeto.
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Genkai;

Na solução criada, no arquivo Game1.cs, crie duas variáveis chamadas sceneManager e inputHelperManager:
public class Game1 : Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    SceneManager sceneManager;
    InputHelperManager inputHelperManager;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }




No método Initialize() inicialize a variável inputHelperManager (e o adicione ao Services), modifique também a posição da janela do jogo e seu tamanho:
protected override void Initialize()
{
    // TODO: Add your initialization logic here
    inputHelperManager = new InputHelperManager(this);
    inputHelperManager.Add(PlayerIndex.One, KeyboardSettings.KeyboardDefault().GetKeyboardMap());

    Services.AddService(inputHelperManager);

    GameHelper.SetGameSize(GameSize.w800h600, ref graphics);
    Window.Position = GameHelper.GetCenterScreen(this);

    base.Initialize();
}


No método LoadContent() inicialize a variável sceneManager com o seguinte código (não se preocupe se no momento o Visual Studio informar algum erro):
protected override void LoadContent()
{

    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);
    Services.AddService(spriteBatch);

    // TODO: use this.Content to load your game content here
    sceneManager = new SceneManager(this);
    Services.AddService(sceneManager);

    sceneManager.Add("pong", new PongScene(this));
    sceneManager.Change("pong");
}


No método Update() digite o seguinte código:
protected override void Update(GameTime gameTime)
{
    if (inputHelperManager.One.IsPress(Buttons.Back))
        Exit();

    // TODO: Add your update logic here
    inputHelperManager.Update(gameTime);
    sceneManager.Update(gameTime);

    base.Update(gameTime);
}


e no método Draw() o seguinte código:
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(sceneManager.ActiveScene.BackColor);

    // TODO: Add your drawing code here
    sceneManager.Draw(gameTime);

    base.Draw(gameTime);
}


Passo 02:
Crie uma nova classe chama PongScene.cs. Ela será herdeira da classe Genkai.Scene. Digite então o seguinte código:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System;
using Genkai;

namespace PongGame
{
    public class PongScene : Scene
    {
        public PongScene(Game game) : base(game, TimeSpan.Zero, true) { }

Crie agora um método sobrecarregado sem retorno chamado Load():
public override void Load()
{
   base.Load();
}

dentro dele digite o seguinte código:
//Troca a cor de fundo.
BackColor = Color.Green;

//Retângulo de fundo ------------------------------------------------------------------------
AnimatedEntity backRectangle = AnimatedEntity.CreateRectangle(this.Game, new Vector2(600, 400), Color.Black);
backRectangle.SetPosition(100, 100);


Agora vamos criar o retângulo e desenvolver a lógica do jogador 01:
//Retângulo do jogador 1 --------------------------------------------------------------------
AnimatedEntity rectangleOne = AnimatedEntity.CreateRectangle(this.Game, new Vector2(10, 100), Color.White);
rectangleOne.SetPosition(backRectangle.Position.X + 20, backRectangle.Position.Y + 10);
rectangleOne.OnUpdate += (GameTime gt, AnimatedEntity e) => 
{
    //Verifica a posição e corrige se necessário
    if (!e.IsAbove(backRectangle, 20))
    {
        if (e.Input.IsDown(Buttons.DPadUp))
            e.Y -= 5;
    }
    if (!e.IsBelow(backRectangle, -20, true))
    {
        if (e.Input.IsDown(Buttons.DPadDown))
            e.Y += 5;
    }
};            


O mesmo para o jogador 02:
//Retângulo do jogador 2 --------------------------------------------------------------------
AnimatedEntity rectangleTwo = AnimatedEntity.CreateRectangle(this.Game, new Vector2(10, 100), Color.White);
rectangleTwo.SetPosition(backRectangle.Position.X + backRectangle.Width - 30, backRectangle.Position.Y + 10);            
//rectangleTwo.Input = Game.Services.GetService<InputHelperManager>().Two;
rectangleTwo.OnUpdate += (GameTime gt, AnimatedEntity e) =>
{
    //Verifica a posição e corrige se necessário
    if (!e.IsAbove(backRectangle, 20, false))
    {
        if (e.Input.IsDown(Buttons.DPadUp))
            e.Y -= 5;
    }
    if (!e.IsBelow(backRectangle, -20, true))
    {
        if (e.Input.IsDown(Buttons.DPadDown))
            e.Y += 5;
    }
};


Criemos então o retângulo da bola e sua lógica:
//Bola--------------------------------------------------------------------------------------
AnimatedEntity ball = AnimatedEntity.CreateRectangle(this.Game, new Vector2(10, 10), Color.White);
ball.SetScreenPosition(Camera, AlignType.Center);            
ball.SetVelocity(-2, -2);            
ball.OnUpdate += (GameTime gt, AnimatedEntity e) =>
{
    //Checa posição na borda
    if (e.IsAbove(backRectangle, 10) || e.IsBelow(backRectangle, -10, true))
        e.InvertVelocityY();

    //Checa colisão
    if(e.Collide(rectangleOne))
    {
        e.X = (rectangleOne.X + rectangleOne.Width) + 1;
        e.InvertVelocityX();
        if (e.X_Velocity < 20)
            e.X_Velocity += 0.5f;
    }
    if (e.Collide(rectangleTwo))
    {
        e.X = (rectangleTwo.X - rectangleTwo.Width) - 1;
        e.InvertVelocityX();
        if(e.X_Velocity > -20)
            e.X_Velocity += -0.5f;
    }

    //Checa se foi ponto
    if (e.IsOnTheLeft(backRectangle, 0, true))
    {
        e.SetScreenPosition(Camera, AlignType.Center);                    
        float x = e.X_Velocity - (e.X_Velocity - 2);
        e.X_Velocity = x;
    }
    if(e.IsOnTheRight(backRectangle, 0, false))
    {
        e.SetScreenPosition(Camera, AlignType.Center);
        float x = e.X_Velocity - (e.X_Velocity - 2);
        e.X_Velocity = x * -1;                    
    }
};


Por fim adicionamos as entidades à cena com o método Entitys.Add();
//Entidades --------------------------------------------------------------------------------
Entitys.Add("backRectangle", backRectangle);
Entitys.Add("rectangleOne", rectangleOne);
Entitys.Add("rectangleTwo", rectangleTwo);
Entitys.Add("ball", ball);

base.Load();


Rode o código e finalize colocando algum efeito de som.



Abraços.

Brand creation, trend analysis & style consulting

Lorem Ipsum has been the industry's standard dummy text ever since. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since.