user2950416
user2950416

Reputation: 1

XNA 3.1 - Not sure how to add Rectangle in enemy Class

Trying to make a 2D side scroller here

I am quite new to programming. I've tried to follow guides and tutorials with not much luck. I am aware that this is quite simple but i just cannot figure it out.

I have multiple classes for all the different characters in the game.

I have a rectangle for the main sprite character which the player will control.

But the problem is that I want to add rectangles around enemy sprites so that i can add collision into the game.

public class enemyRocks
{
    public Texture2D texture;
    public Vector2 position;
    public Vector2 velocity;
    public Rectangle rockRectangle; 

    public bool isVisible = true;

    Random random = new Random();
    int randX;

    public enemyRocks(Texture2D newTexture, Vector2 newPosition)
    {
        texture = newTexture;
        position = newPosition;


        randX = -5;
        velocity = new Vector2(randX, 0);

    }


    public void Update(GraphicsDevice graphics) 
    {
        position += velocity;

        if (position.X < 0 - texture.Width)
            isVisible = false;

    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, position, Color.White);
    }
}

I have genuinely tried many methods but it just doesn't seem to work.

Everything i've done so far gave me a "nullreferenceexception was unhandled" error.

I will take any criticism needed to improve.

Thank you for your help.

Upvotes: 0

Views: 101

Answers (1)

Davor Mlinaric
Davor Mlinaric

Reputation: 2017

you need boundingBox property on your sprites

new Rectangle((int)Position.X,(int)Position.Y,texture.Width, texture.Height);

then to check collision

if (Sprite1.BoundingBox.Intersects(Sprite2.BoundingBox))

but make sure that you load your texture before any function that uses texture. i guess your error happened on update function where you try to get width of texture that is not loaded.

Upvotes: 1

Related Questions