ShadowByte
ShadowByte

Reputation: 83

XNA C# Inheritance stops object from being drawn

Base Class

Notice the draw method. It exists and the syntax is sound.

public class defaultObject
{
    // variables are here

    public defaultObject(Vector2 nPos, float nRotation, Texture2D nTexture, int nWidth, int nHeight)
    {
        // constructor business
    }

    public virtual void update()
    {
        rectangle = new Rectangle((int)position.X, (int)position.Y, width, height);
        origin = new Vector2(texture.Width / 2f, texture.Height / 2f);
    }

    public virtual void draw(SpriteBatch spatch)
    {
        spatch.Draw(texture, rectangle, null, Color.Green, rotation, origin, SpriteEffects.None, 1f);
    }
}

Derived Class

No need to override the draw method, only the update method.

public class block: defaultObject
{
    public block(Vector2 nPos, float nRotation, Texture2D nTexture, int nWidth, int nHeight)
        : base(nPos, nRotation, nTexture, nWidth, nHeight)
    { }

    public override void update()
    {
        if (rotation > (float)(Math.PI * 2))
        {
            rotation = 0;
        }

        if (rotation < 0)
        {
            rotation = (float)Math.PI * 2;
        }
    }
}

Game1.cs

Assume all the other XNA necessities are there, I'm keeping it simple for reading

PROBLEM: When I attempt to draw block a, it doesn't appear. Why?

public class Game1 : Microsoft.Xna.Framework.Game
{
    block a;

        a = new block(new Vector2(windowSize.X / 4f, windowSize.X / 2), 3.1415f, rectangleTexture, 300, 50);
    }

    protected override void Update(GameTime gameTime)
    {
        //keyboard input to manipulate a is here

        a.update();
    }

    protected override void Draw(GameTime gameTime)
    {
        a.draw(spriteBatch);
    }
}

Before I introduced this inheritance business, the block was visible.

Upvotes: 0

Views: 116

Answers (2)

Steve H
Steve H

Reputation: 5519

When you call draw, it uses the metheod from the base class defaultObject, which is fine but that method needs the rectangle and origin info which has never been set.

You need to call base.Update() at the end of block.Update() or move the rectangle/origin setting to the constructor.

Upvotes: 2

Mikhail Gubanov
Mikhail Gubanov

Reputation: 420

Try to call

base.Update()

Maybe object is drown outside the screen because of unset "rectangle" and "origin"

Upvotes: 1

Related Questions