2015-04-10 2 views
0

В игровой части моей игры, где вы проверяете ввод, почему состояние, которое мой объект ранее не используется, не используется в дальнейших оценках моей функции?Объект игры, не сохраняющий состояние в MonoGame

Мой игровой класс:

using System; 
using System.Collections.Generic; 
using Microsoft.Xna.Framework; 
using Microsoft.Xna.Framework.Content; 
using Microsoft.Xna.Framework.Graphics; 
using Microsoft.Xna.Framework.Input; 
using Microsoft.Xna.Framework.Storage; 
using Microsoft.Xna.Framework.GamerServices; 
using System.Diagnostics; 

namespace MonoRPG 
{ 
    public class Game1 : Game 
    { 

     GraphicsDeviceManager graphics; 
     SpriteBatch spriteBatch; 


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

     } 

     protected override void Initialize() 
     { 
      base.Initialize(); 
     } 

     protected override void LoadContent() 
     { 
      // Create a new SpriteBatch, which can be used to draw textures. 
      spriteBatch = new SpriteBatch(GraphicsDevice); 
     } 

     protected override void UnloadContent() 
     { 
     } 


     protected override void Update(GameTime gameTime) 
     { 
      if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) 
       Exit(); 

      Player playerObject = new Player(this, this.Content, this.spriteBatch); 
      KeyboardState oldState; 
      KeyboardState newState = Keyboard.GetState(); 

      if (newState.IsKeyDown(Keys.Right)) 
      { 
       Debug.WriteLine("right key pressed"); 
      } 

      oldState = newState; 


      base.Update(gameTime); 
     } 

     protected override void Draw(GameTime gameTime) 
     { 
      GraphicsDevice.Clear(Color.CornflowerBlue); 

      renderMap createMap = new renderMap(this, this.Content, this.spriteBatch); 
      Player playerObject = new Player(this, this.Content, this.spriteBatch); 

      createMap.RenderMap(); 
      playerObject.drawPlayer(); 
      playerObject.positionX = playerObject.positionX + 10; 

      base.Draw(gameTime); 
     } 
    } 
} 

И мой игрок Класс:

using System; 
using System.Collections.Generic; 
using Microsoft.Xna.Framework; 
using Microsoft.Xna.Framework.Content; 
using Microsoft.Xna.Framework.Graphics; 
using Microsoft.Xna.Framework.Input; 
using Microsoft.Xna.Framework.Storage; 
using Microsoft.Xna.Framework.GamerServices; 
using System.Diagnostics; 

namespace MonoRPG 
{ 
    public class Player 
    { 
     public int positionX = 0; 
     public int positionY = 0; 

     Game1 draw = new Game1(); 
     ContentManager gameContent; 
     SpriteBatch playerSprites; 
     KeyboardState oldState; 


     public Player(Game1 canvas, ContentManager content, SpriteBatch spriteBatch) 
     { 
      draw = canvas; 
      gameContent = content; 
      playerSprites = spriteBatch; 
     } 

     public Player() 
     { 

     } 


     public void drawPlayer() 
     { 
      Texture2D playerTexture = gameContent.Load<Texture2D>("player/player.png"); 

      playerSprites.Begin(); 
      playerSprites.Draw(playerTexture, new Vector2(positionX, positionY), Color.Red); 
      playerSprites.End(); 
     } 

     public void playerMove(KeyboardState keyState, KeyboardState oldState) 
     { 
      positionX = positionX + 1; 
     } 

    } 
} 

Розыгрыш работает нормально, но положение прямоугольника спрайт Я использую для игрока не будет изменение. Является ли проблема связана с тем, как я создаю объекты? Я попытался объявить вне функций, но тогда я не могу использовать ключевое слово this. Как я могу вызвать функции на существующих объектах?

ответ

1

Вы должны инициализировать (создавать) объекты в методах Initialize или LoadContent. Объект должен создаваться только один раз, а не каждое обновление игры. Initialize и LoadContent происходит только один раз, при запуске игры (сначала Initialize, LoadContent, когда вы позвоните base.Initialize()).

Когда вы помещаете код в метод Update, он выполняется при каждом обновлении (обычно, в каждом фрейме) игры. Ваш код должен выглядеть как этот

Player player; 
KeyboardState oldState; // player and oldState belongs to the whole game 

protected override void Initialize() { 
    // remember that spriteBatch is still null here 
    player = new Player(this, Content, spriteBatch); 
    // the line below initializes the spriteBatch 
    // check the comments to see why this exact code won't work 
    base.Initialize(); 
} 

protected override void Update(GameTime gameTime) { 
    KeyboardState newState = Keyboard.GetState(); // newState belongs to this exact update only 

    if (newState.IsKeyDown(Keys.Right) && oldState.IsKeyUp(Keys.Right)) { 
     player.playerMove(newState, oldState); // not sure why you wish to pass these arguments? 
    } 

    oldState = newState; 
} 

protected override void Draw(GameTime gameTime) { 
    GraphicsDevice.Clear(Color.CornflowerBlue); 

    renderMap createMap = new renderMap(this, this.Content, this.spriteBatch); 

    createMap.RenderMap(); 

    // the player here is the same player in the Update method 
    player.drawPlayer(); 

    base.Draw(gameTime); 
} 
+0

Когда я инициализировать их в инициализации функции я начала получать исключения nullreference в Player.cs говоря, что playerSprites Isnt указывает на экземпляр объекта? – user3585434

+0

@ user3585434, как я уже сказал, «LoadContent» выполняет ПОСЛЕ «Инициализация». Вы можете переместить 'new Player()' ro 'LoadContent' или' new SpriteBatch() 'в' Initialize', чтобы создать пакет спрайтов до создания проигрывателя. Во всяком случае, довольно плохая практика передавать спрайт-партии при создании новых игровых объектов (передавать их только в методе 'Draw'). – Mephy

+0

это именно то, что мне нужно, спасибо, я буду держать это в уме! – user3585434

Смежные вопросы