External class does not work the way expected

My player class is initiated like this.
namespace Space_Battles
{
class Player : CommonMethods
Common Methods contains methods that I will share with other classes.
The common Method class is below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
 
namespace Space_Battles
{
    public class CommonMethods
    {
        #region Fields
 
        private KeyboardState keyboard = Keyboard.GetState();
        private GameTime gameTime;
 
 
 
        #endregion
 
        #region Methods and Functions
 
        public double HealthMatters(double health, double Amount)
        {
            health += Amount;
            return health;
        }
 
        public float UserInput(float RotAngleInRadians, float RotSpeedUpFactor)
        {
 
            if (keyboard.IsKeyDown(Keys.D))
            {
 
                rotateTheShip(1, RotAngleInRadians, RotSpeedUpFactor);
 
            }
 
            if (keyboard.IsKeyDown(Keys.A))
            {
                rotateTheShip(2, RotAngleInRadians, RotSpeedUpFactor);
            }
 
            return RotAngleInRadians;
 
        }
 
 
 
        public float rotateTheShip(int num, float rotAngleInRadians, float rotSpeedUpFactor)
        {
            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
            float circle = MathHelper.Pi * 2;
 
            if (num == 1)
            {
                rotAngleInRadians += elapsed + rotSpeedUpFactor;
                //rotAngleInRadians += (float)(elapsed * Math.PI / 180);
            }
            else
            {
                rotAngleInRadians -= elapsed + rotSpeedUpFactor;
                //rotAngleInRadians -= (float)(elapsed * Math.PI / 180);
            }
 
            rotAngleInRadians = rotAngleInRadians % circle;
            return rotAngleInRadians;
        }
 
 
 
 
 
 
        #endregion
    }
 
}

now when I call
if (keyboard.IsKeyDown(Keys.D))
{
rotateTheShip(1, rotAngleInRadians, RotSpeedUpFactor);
ApplyBreaks();

}

this error is thrown.

Can someone tell me the reason for this error and what I should do to correct it.

From what I can see you are trying to call gameTime, but you have not actually passed it to the function from your main game class? Maybe try passing GameTime gameTime to rotateTheShip from the main game class.

You haven’t passed “gameTime” to the function, or either initialised the class variable “gameTime” at the top of the class. Because this hasn’t been initilised, is the reason for the error.

1 Like

Can you please show me the lines of code please and where to put it? I tried putting the line GameTime gameTime in many places to no avail.

In the method parameters you need to put the gameTime variable, or set it in the variable at the top when you initialize the class

public float rotateTheShip(GameTime gameTime, int num, float rotAngleInRadians, float rotSpeedUpFactor)

As you’re methods in the class are not static, it looks like you are initialiing the class each time

CommonMethods commonMethods = New CommonMethods();

then your calling the rotateTheShip like:

commonMethods.rotateTheShip(1, rotAngleInRadians, RotSpeedUpFactor);

is this right? If so what I would do is pass the gameTime variable into the new instance and then set the gameTime variable in the constructor method of the CommonMethods Class.

CommonMethods commonMethods = New CommonMethods(gameTime);

Would need to see more of your code around how your calling the rotateTheShip method to know for sure.

All the rotating code is given above

I mean the code around your code calling the rotating… you would have something like:

In your main “GAME” class - the one created when you create a new project you will have an “Update” method

e.g.

protected override void Update(GameTime gameTime)
{
    // in here you would call your class objects update methods (ships, etc) and pass the gameTime variable into them. to cut all that out and just do the rotate example:

    CommonMethods commonMethods = New CommonMethods(gameTime);
    if (keyboard.IsKeyDown(Keys.D))
    {
         commonMethods.rotateTheShip(1, rotAngleInRadians, RotSpeedUpFactor);
         ApplyBreaks();
    }
}

Then in your “CommonMethods” class create a constructor and set the class variable “gameTime” to be the one passed in.

public CommonMethods(GameTime gameTime)
{
    _gameTime = gameTime;
}

Hope this helps

I a not initializing Common methods as it is inherited by the Main player class as I have shown right at the beginning of my question. The Health reduction function works perfectly… It is something to do with this GameTime variable… I wrote a few lines to check if the health reduction works and printed the output to the console and it worked perfectly.

Ahh. OK. Looks like your calling it from the “UserInput” method. you need to pass in the gameTime variable into there. then pass that variable into the rotateTheShip method

I’m guessing your player class has the “Update(GameTime gameTime)” method in it which is called from the main game loop, if so then pass that gameTime into the UserInput method in the commonMethods, then pass it down to the rotateTheShipMethod.

Alternative, make the CommonMethods.gameTime varaiable public and update it in mainPlayer.update(…) method.

Care to share the main player class?

Here is the player class. Still it’s not working… i’m trying…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
 
 
namespace Space_Battles
{
    class Player : CommonMethods
    {
        #region Fields
 
        Texture2D spriteStop;
        Texture2D spriteMove;
        Texture2D spriteBrake;
        Texture2D playerSprite;
        Texture2D lazer;
        Rectangle drawRectangle;
 
        SoundEffect thrust;
        SoundEffectInstance thrustInst;
        SoundEffect fire;
        //SoundEffectInstance fireInst;
        SoundEffect explode;
        SoundEffect alienAlertSound;
        SoundEffectInstance alienAlertSndIns;
 
        Vector2 spriteRotOrigin;
        Vector2 spritePos;
        float orientation; // current angle of the player
        float RotSpeedUpFactor = 0.03f;
        Vector2 heading;
 
        int gunHeatTimer = 0; // slows down gun firing
        int gunCoolTimer = 0; // cool the gun if not firing
 
        int VarColor = 255;
        public int gunHeat = 0; // gun stops firing when reach max then have to wait till cool down
        int VarOpacity = 255;
        double health = 100;
        double healthReduce = 0;
 
 
        public bool canShoot = false; //default
        public bool playerSHoot = false; // default
        bool alienAlertSoundOn = false;
 
        float rotAngleInRadians = 0;
 
        float spritePosX;
        float spritePosY;
 
        float VelocityX;
        float VelocityY;
        float previousVelX;
        float previousVelY;
 
        float speed = 0.01f;
 
        float lazerX;
        float lazerY;
 
 
 
        #endregion
 
        #region Constructors
        /// <summary>
        ///
        /// </summary>
        /// <param name="contentManager"></param>
        /// <param name="idleSprite"></param>
        /// <param name="firingSprite"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public Player(ContentManager contentManager, string idleSprite, string firingSprite,
            string brakingSprite, string lazerSprite, float x, float y, string explodeSound,
            string fireSound, string thrustSound, string alertSound)
        {
            // movement sprites
            spriteStop = contentManager.Load<Texture2D>(idleSprite); // idle
            spriteMove = contentManager.Load<Texture2D>(firingSprite); // firing
            spriteBrake = contentManager.Load<Texture2D>(brakingSprite); // braking
            lazer = contentManager.Load<Texture2D>(lazerSprite); // hero lazer shot
            playerSprite = spriteStop; // Default Hero
 
            // thrust sound and parameters
            this.thrust = contentManager.Load<SoundEffect>(thrustSound);
            this.thrustInst = thrust.CreateInstance();
            this.thrustInst.Volume = 0.15f;
            this.thrustInst.Pitch = -0.2f;
            this.thrustInst.IsLooped = true;
 
            // fire lazer sound and parameters
            this.fire = contentManager.Load<SoundEffect>(fireSound);
            this.explode = contentManager.Load<SoundEffect>(explodeSound);
            this.alienAlertSound = contentManager.Load<SoundEffect>(alertSound);
            this.alienAlertSndIns = alienAlertSound.CreateInstance();
            this.alienAlertSndIns.Volume = 0.3f;
            this.alienAlertSndIns.Pitch = .05f;
            this.alienAlertSndIns.IsLooped = false;
 
            spriteRotOrigin = new Vector2(playerSprite.Width / 2, playerSprite.Height / 2);
            spritePosX = x - playerSprite.Width / 2;
            spritePosY = y - playerSprite.Height / 2;
            spritePos = new Vector2(spritePosX, spritePosY);
            //drawRectangle = new Rectangle((int)spritePosX, (int)spritePosY,
            //    sprite.Width / 2, sprite.Height / 2);
        }
 
        #endregion
 
        #region Properties
 
        public Rectangle CollisionRectangle
        {
            get { return drawRectangle; }
        }
 
        public Double Health
        {
            get { return health; }
            set
            {
                health = value;
                if (health <= 0)
                {
                    health = 0;
                }
            }
        }
        #endregion
 
 
 
 
        #region Public methods
 
        public void Update(GameTime gameTime, KeyboardState keyboard, int screenWidth, int screenHeight)
        {
            Health = HealthMatters(Health, Constants.playerHealthReduceAmount);
            Console.WriteLine("health: " + Health);
            // the reduction amount to be added later
 
            if (Health > 0)
            {
 
                //rotAngleInRadians = UserInput(rotAngleInRadians, RotSpeedUpFactor);
 
                //rotate player CLOCKWISE
                if (keyboard.IsKeyDown(Keys.D))
                {
                    rotateTheShip(1, gameTime, rotAngleInRadians, RotSpeedUpFactor);
                    ApplyBreaks();
 
                }
                //rotate player ANTICLOCKWISE
                if (keyboard.IsKeyDown(Keys.A))
                {
                    rotateTheShip(2, gameTime, rotAngleInRadians, RotSpeedUpFactor);
                    ApplyBreaks();
 
                }
 
                // hero move
                if (keyboard.IsKeyDown(Keys.W))
                {
                    playerSprite = spriteMove;
                    previousVelX = VelocityX;
                    previousVelY = VelocityY;
 
                    //Accellerate();
                    this.thrustInst.Play();
                    WithinLimits();
 
                    VelocityX += (float)(Math.Sin(rotAngleInRadians) * speed *
                        gameTime.ElapsedGameTime.TotalMilliseconds);
 
                    VelocityY += (float)(-Math.Cos(rotAngleInRadians) * speed *
                        gameTime.ElapsedGameTime.TotalMilliseconds );
 
                    heading = new Vector2((float)Math.Cos(rotAngleInRadians),
                        (float)Math.Sin(rotAngleInRadians));
 
 
                }
 
                //hero brake
                else if (keyboard.IsKeyDown(Keys.S))
                {
                    playerSprite = spriteBrake;
                    this.thrustInst.Play();
                    ApplyBreaks();
                    Decellarate();
                }
 
                // hero stop
                else
                {
                    playerSprite = spriteStop;
                    this.thrustInst.Stop();
                }
 
                MoveThePlayer(heading, speed);
 
                spritePos = new Vector2(spritePosX, spritePosY);
 
                drawRectangle = new Rectangle((int)spritePosX, (int)spritePosY,
                    playerSprite.Width, playerSprite.Height);
 
                PlayerScreenWrapAround(screenWidth, screenHeight);
 
 
                //hero fire
                {
                if (canShoot == false)
                    gunHeatTimer += gameTime.ElapsedGameTime.Milliseconds;
                }
 
                if (gunHeatTimer > Constants.gunCoolLimit && gunHeat <= 110)
                {
                    canShoot = true;
                    gunHeatTimer = 0;
                }
 
                if (keyboard.IsKeyDown(Keys.Space) && canShoot)
                {
                    canShoot = false;
                    gunHeat += 1;
                    //heroShoot = true;
                    this.fire.Play(0.2f, 0.1f, 0);
 
                    MakeProjectile(); // call the sub routine to make the projectile and add to the list
 
                    foreach (Energy cell in Game1.heatCells)
                    {
                        if (cell.celOpacity < 255 && gunHeat > 0)
                        {
                            cell.celOpacity += 25;
                            if (cell.celOpacity > 255)
                            {
                                cell.celOpacity = 255;
                            }
                            break;
                        }
                    }
                }
 
                if (keyboard.IsKeyUp(Keys.Space))
                {
                    gunCoolTimer += gameTime.ElapsedGameTime.Milliseconds;
                    playerSHoot = false;
                }
 
                if (!playerSHoot && gunCoolTimer > Constants.gunCoolControl && gunHeat > 0)
                {
                    gunHeat -= 1;
                    gunCoolTimer = 0;
                    playerSHoot = true;
 
                    // cool the gun
                    for (var i = Game1.heatCells.Count - 1; i >= 0; i--)
                    {
                        if (Game1.heatCells[i].celOpacity > 0)
                        {
                            Game1.heatCells[i].celOpacity -= 25;
                            break;
                        }
                    }
                }
 
                if (Constants.enemyAlert && alienAlertSndIns.State == SoundState.Stopped)
                {
                    this.alienAlertSndIns.Play();
                    alienAlertSoundOn = true;
                }
 
                if (Constants.enemyAlert == false)
                {
                    alienAlertSoundOn = false;
                }
            }
        }
 
 
        public void Draw(SpriteBatch spriteBatch, SpriteFont font, float scale)
        {
            // null - source area in teture to draw null for the whole texture
            // 1.0f scale value
            // 0f layer depth
 
            spriteBatch.Draw(playerSprite, spritePos, null,
                Color.FromNonPremultiplied(255, VarColor, 255, VarOpacity),
                rotAngleInRadians, spriteRotOrigin, scale, SpriteEffects.None, 0f);
 
 
 
            // draw some info for debugging
 
            spriteBatch.DrawString(font, "speed :" + speed,
                new Vector2(spritePosX, spritePosY), Color.White);
            spriteBatch.DrawString(font, "rotAngle :" + Convert.ToString(rotAngleInRadians),
            new Vector2(spritePosX, spritePosY + 50), Color.White);
 
            //spriteBatch.DrawString(font, "lazerX :" + Convert.ToString(lazerX),
            //new Vector2(10, 150), Color.White);
            //spriteBatch.DrawString(font, "lazerY :" + Convert.ToString(lazerY),
            //new Vector2(10, 200), Color.White);
 
        }
 
        public void MakeProjectile()
        {
            // the code below will position a projectile at the top
            // of any rotating sprite facing the sprite direction
 
            lazerX = spritePosX + playerSprite.Width / 2 * (float)Math.Sin(rotAngleInRadians);
            lazerY = spritePosY - playerSprite.Height / 2 * (float)Math.Cos(rotAngleInRadians);
 
            Projectile projectile = new Projectile(lazer, "heroLazer",
                lazerX, lazerY, rotAngleInRadians, Constants.LazerSpeed);
 
            Game1.AddProjectile(projectile);
        }
 
        public void Accellerate()
        {
            speed += Constants.playerVelInc / 10;
 
            if (speed > Constants.playerMoveLimit / 10)
            {
                speed = Constants.playerMoveLimit / 10;
            }
            WithinLimits();
        }
 
        public void Decellarate()
        {
            speed += Constants.playerVelDec;
 
            if (speed < 0)
            {
                speed = 0;
            }
        }
 
        public void ApplyBreaks()
        {
            VelocityX *= .985f;
            VelocityY *= .985f;
        }
 
        public void PlayerScreenWrapAround(int screenWidth, int screenHeight)
        {
            if (spritePosX > screenWidth)
            {
                spritePosX = 1;
            }
 
            if (spritePosX < 0)
            {
                spritePosX = screenWidth + 1;
            }
 
            if (spritePosY > screenHeight)
            {
                spritePosY = 1;
            }
 
            if (spritePosY < 0)
            {
                spritePosY = screenHeight;
            }
        }
 
        public void MoveThePlayer(Vector2 heading, float currentSpeed)
        {
            spritePosX += VelocityX;
            spritePosY += VelocityY;
            Constants.playerSpriteCenter = new Vector2(spritePosX, spritePosY);
        }
 
        public void WithinLimits()
        {
            if (VelocityY > Constants.UpperLimit)
            {
                VelocityY = previousVelY;
            }
 
            if (VelocityX > Constants.UpperLimit)
            {
                VelocityX = previousVelX;
            }
 
            if (VelocityY < Constants.LowerLimit)
            {
                VelocityY = previousVelY;
            }
 
   [quote="Harag, post:9, topic:10138, full:true"]
Ahh. OK. Looks like your calling it from the "UserInput" method. you need to pass in the gameTime variable into there. then pass that variable into the rotateTheShip method

I'm guessing your player class has the "Update(GameTime gameTime)" method in it which is called from the main game loop, if so then pass that gameTime into the UserInput method in the commonMethods, then pass it down to the rotateTheShipMethod.

Alternative, make the CommonMethods.gameTime varaiable public and update it in mainPlayer.update(...) method.

Care to share the main player class?
[/quote]

[quote="Harag, post:9, topic:10138, full:true"]
Ahh. OK. Looks like your calling it from the "UserInput" method. you need to pass in the gameTime variable into there. then pass that variable into the rotateTheShip method

I'm guessing your player class has the "Update(GameTime gameTime)" method in it which is called from the main game loop, if so then pass that gameTime into the UserInput method in the commonMethods, then pass it down to the rotateTheShipMethod.

Alternative, make the CommonMethods.gameTime varaiable public and update it in mainPlayer.update(...) method.

Care to share the main player class?
[/quote]


            {
                VelocityX = previousVelX;
            }
        }
 
        #endregion
    }
}

Got the code to work after a few adjustments. If anyone is interested I can post it.

Excellent! Been busy at work so not had time to reply until now, just taken a look, looks like the above code you are passing in the gametime to the rotateTheShip(…) method so as long as the correct gameTime is passed into your Update method all should be good from what I can see.

Keep at it !

That would help people with the same issue in future, and conclude this thread.