eclmist
eclmist

Reputation: 161

Accessing a protected variable that is constantly changing

I am trying to access a protected variable through a derived class. It all works until the variable starts changing, as the variable that the derived class gets never changes.

Simplified parent class (stripped of unimportant stuff):

class Player
{
    protected Vector2 planeVec = new Vector2 (480/2, 600);

    public void Update(KeyboardState keyboard)
    {
        if (keyboard.IsKeyDown(Keys.Down)
        {
            planeVec.Y += 5;
        }
    }
}

and here is the simplified derived class:

class Projectiles : Player
{
    List<Vector2> bullets = new List<Vector2>();

    public void Update()
    {
        if (Keyboard.GetState().IsKeyDown(Keys.Space))               
        {
            bullets.Add(planeVec);
        }
    }
}

The Vector2 values for bullets always registers a value of (480/2, 600) regardless of how much planeVec changes throughout runtime.

What am I doing wrong?

Upvotes: 1

Views: 58

Answers (1)

sasha_gud
sasha_gud

Reputation: 1735

How do you call Update() method for Projectiles class?

The following will not work, since base class Update() is not called in this case:

    Projectiles a = new Projectiles();
    a.Update();
    a.Update();

The following code will only call base class method:

    Projectiles a = new Projectiles();
    ((Player)a).Update();
    ((Player)a).Update();

I suggest to update Projectiles.Update() the following way:

public void Update()
{
    base.Update();
    if (Keyboard.GetState().IsKeyDown(Keys.Space))               
    {
        bullets.Add(planeVec);
    }
}

Adding base.Update() will first call base class method that will update the current state.

EDIT:

I'd also recommend to make base Update() method virtual and override it in the derived class. This will allow to avoid problems described in example above.

Upvotes: 1

Related Questions