I have recently started learning Object oriented programming and design.

I had made a small program using the procedural design to move a block after selecting it in XNA.

I then tried to make the same program with an Object centered Design, but I am not able to make it work. The block is to change color when clicked but isn't in the OO version and I am not able to figure out why :(( .

I have uploaded both the solutions, I want the OOP version to works as the procedural one is working. i.e. Change color when clicked on it and move and change color back and not move if not selected(it isn't blue).

Not pasting the code as the OOP version is spread among 4 files and I have no clue which one is Infected :(.

Member Avatar for dekster

You forgot to initialize rTexture, so it can't very well contain the mouse point. Change the textureImage in the Unit class to protected, too, and add this to the constructors:

rTexture = new Rectangle((int)position.X, (int)position.Y, textureImage.Width, textureImage.Height);

In this case there were only very few factors involved that could be responsible for the error, so this is pretty easy to debug. Use Console.WriteLine() to check if the variables involved have the values they were supposed to have to see where the problem lies. For example:

if (currMouseState.LeftButton == ButtonState.Pressed)
            {
                mClick = new Point(currMouseState.X, currMouseState.Y);

                Console.WriteLine(rTexture);
                Console.WriteLine(mClick);

                if (!tselected && rTexture.Contains(mClick))
                {
                    tselected = true;
                }
                else if (tselected && !rTexture.Contains(mClick))
                {
                    tselected = false;
                }
            }

If a line gets printed to the console, you know that the mouse state and the unit get updated correctly, what values the rectangle and the point have and thus if your if-clause works right.

Thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.