How can i use GameTime in other class??

I’m making a very small game and i want that the player have its own class and obviously it have its own update metod (overrided) so in the update function is the player’s movement but i can’t use gametime because is in the game class. I saw many tutorials about moving a sprite, but the movement instructions are in the game class so by default they can use it. I tried to instanciated another GameTime, but it returns 0 becuase is another GameTime. How can i use (float)gameTime.ElapsedGameTime.TotalSeconds in the player class??

Hello there! So if you want your player to have its own class, let’s say a “Player” class, you need to pass the GameTime value from your main game class to your player class. Something like this :

• In the file Player.cs :

public class Player
{
    public void Update(GameTime gameTime)
    {
        // do stuff with gameTime
    }
}

• In the file Game1.cs :

public class Game1 : Game
{
    private Player _player;

    protected override void Initialize()
    {
        _player = new Player();
        base.Initialize();
    }

    protected override void Update(GameTime gameTime)
    {
        _player.Update(gameTime);
        base.Update(gameTime);
    }

    // here are the others methods from the Game class such as LoadContent(), UnloadContent(), Draw()...
}

Hope it helps! :blush:

1 Like

Thanks for the help!
But for some reason the Player1.Update is not working the program is taking the Update method of Game1 and i don’t know why it has the Player1. Maybe is because the player class inherits from a sprite class and the sprite class inherits from Game1, please help me :frowning:

Ok so, I don’t understand exactly how your code is organized😅, so I have some questions:

So, you created a class named “Player1”, right? Where do you create an instance of this Player1? (meaning, is there a “new Player1()” in your code)?
And so you also have a custom sprite class? But why does it inherit from the Game1 class? And why does the player class inherits from this sprite class?
What is in your Game1.Update method? Is there a call to the Player1.Update method there?

Maybe you can provide some sample code to make it easier to understand?:slightly_smiling_face:

As far I can tell, I’d recommend to avoid inheritance as much as possible because it causes all sorts of headaches and it’s usually better to keep things separated into very distinct classes. But again we have to look at how your code is organized to better fix the problem :blush:

I’ve got it. so thats my code:
For Sprite its that:

namespace Pong {
    public class Sprite : Game1
    {
        protected Texture2D texture { get; set; }

        public Vector2 origin;
        public Vector2 velocity = new Vector2(1, 1);

        protected int Columns { get; set; }
        protected int Rows { get; set; }
        protected int CurrentFrame;
        protected int TotalFrames;

        public Vector2 position;

        public Rectangle collider { get { return new Rectangle((int)position.X, (int)position.Y, texture.Width, texture.Height); } }

        public Sprite(int r, int c) 
        {
            Columns = c;
            Rows = r;
        }

        public void Draw(SpriteBatch spriteBatch, Vector2 location) 
        {
            int spriteWidth = texture.Width / Columns;
            int spriteHeight = texture.Height / Rows;
            int row = (int)((float)CurrentFrame / (float)Columns);
            int column = CurrentFrame % Columns;

            Rectangle sourceRectangle = new Rectangle(spriteWidth * column, spriteHeight * row, spriteWidth, spriteHeight);
            Rectangle desitinationRectangle = new Rectangle((int)location.X, (int)location.Y, spriteWidth, spriteHeight);
            spriteBatch.Draw(texture, desitinationRectangle, sourceRectangle, Color.White);
        }

        protected override void Update(GameTime gt)
        {

        }

        //Collision

        protected bool touchingLeft(Sprite sprite)
        {
            return this.collider.Right + this.velocity.X > sprite.collider.Left &&
                   this.collider.Left < sprite.collider.Left &&
                   this.collider.Bottom > sprite.collider.Top &&
                   this.collider.Top < sprite.collider.Bottom;
        }

        protected bool touchingRight(Sprite sprite)
        {
            return this.collider.Left + this.velocity.X < sprite.collider.Right &&
                   this.collider.Right > sprite.collider.Right &&
                   this.collider.Bottom > sprite.collider.Top &&
                   this.collider.Top < sprite.collider.Bottom;
        }
    }
}

The Sprite Class inherit from Game1 beacuase i want to use the GraphicsDeviceManager properties in the other classe i know that that’s weird but i don’t know another form to get GDM properties in other classes

The player class inherit sprite class because it has all the properties that a player need.
so the game1 class is here:

public class Game1 : Game {

        public GraphicsDeviceManager graphics;
        public SpriteBatch spriteBatch;

        private Sprite Player1;
        private Sprite Player2;

        private Sprite ball;

        public Game1() //This is the constructor, this function is called whenever the game class is created.
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            //graphics.PreferredBackBufferHeight = 1080;
            //graphics.PreferredBackBufferWidth = 1920;
        }

        /// <summary>
        /// This function is automatically called when the game launches to initialize any non-graphic variables.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();
        }

        /// <summary>
        /// Automatically called when your game launches to load any game assets (graphics, audio etc.)
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            var texture = TextureLoader.Load("sprite_atlas", Content);
            var ballTexture = TextureLoader.Load("ball", Content);

            Player1 = new Player(1, texture, 1, 2);
            Player1.position = new Vector2(50, 20);
            Player2 = new Player(2, texture, 1, 2);
            Player2.position = new Vector2((graphics.PreferredBackBufferWidth - texture.Width) - 50, 70);

            ball = new Ball(ballTexture, 1, 1);
            ball.position = new Vector2(Window.ClientBounds.Width / 2, Window.ClientBounds.Height / 2);
        }

        /// <summary>
        /// Called each frame to update the game. Games usually runs 60 frames per second.
        /// Each frame the Update function will run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        protected override void Update(GameTime gameTime)
        {
            Player1.Update(gameTime);
            Player2.Update(gameTime);

            ball.Update(gameTime);

            //Update the things FNA handles for us underneath the hood:
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game is ready to draw to the screen, it's also called each frame.
        /// </summary>
        protected override void Draw(GameTime gameTime)
        {
            //This will clear what's on the screen each frame, if we don't clear the screen will look like a mess:
            GraphicsDevice.Clear(Color.Black);
            spriteBatch.Begin();

            Player1.Draw(spriteBatch, Player1.position);
            Player2.Draw(spriteBatch, Player2.position);

            ball.Draw(spriteBatch, ball.position);

            spriteBatch.End();
            //Draw the things FNA handles for us underneath the hood:
            base.Draw(gameTime);
        }
    }

So my main question is how can i improve my code and how can i use GDM properties in other classes

It struck me as kind of weird that you were inheriting the Game1 class like that. I’m not sure that’s your problem, but if it’s access to properties you need, why not just pass them across when you instantiate your sprite?

(ie, dependency injection)

public class Sprite
{
  private Game1 _host;

  public Sprite(Game1 host)
  {
    _host = host;
    // now you can use _host to access Game1's properties.
  }

  public void Update(GameTime gameTime)
  {
    // Do some update-y type stuff!
  }
}

public class Game1 : Game
{
  private GraphicsDeviceManager _graphics;
  public GraphicsDeviceManager Graphics => _graphics

  private Sprite _mySprite;
 
  public Game1()
  {
    _mySprite = new Sprite(this);
  }

  public override void Update(GameTime gameTime)
  {
    _mySprite.Update(gameTime); // You can also just give the sprite GameTime when you update it :)
  }
}