c# XNA drag and drop sprites and update position in list.

  • (2 Pages)
  • +
  • 1
  • 2

19 Replies - 9343 Views - Last Post: 23 January 2012 - 11:57 AM

#1 Kathy123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 21-January 12

c# XNA drag and drop sprites and update position in list.

Posted 21 January 2012 - 04:45 AM

Hello, this is my first post to this site. I'm very new at programming and have been having some difficulties.
At the moment I have a list of objects (circles) and when i click the mouse,a circle appears on the screen according to the mouse position. My plan is to be able to pick any circle up and drag it and update its position in the list.

I firstly need to be able to detect the mouse click on the sprite so Ive created a MouseOnCircle method. However when I run the program, It will only detect if the mouse is on the last circle I have created. Please advise.

This post has been edited by ShadowsEdge19: 23 January 2012 - 01:05 PM


Is This A Good Question/Topic? 0
  • +

Replies To: c# XNA drag and drop sprites and update position in list.

#2 ShadowsEdge19  Icon User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Re: c# XNA drag and drop sprites and update position in list.

Posted 21 January 2012 - 06:27 AM

Can we get a mod to move this to the XNA forum please?

As for your problem it might be easier to accomplish this if you created a separate Object Class for Circle, that way you can treat each Circle uniquely and they won't get mixed up if you do it correctly. I've done a very similar project to this so I can definitely help you, although I was using rectangles instead I was still using a mouse drag-and-drop and even a draw order system.
Was This Post Helpful? 0
  • +
  • -

#3 Kathy123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 21-January 12

Re: c# XNA drag and drop sprites and update position in list.

Posted 21 January 2012 - 07:11 AM

Thank you for your reply,

I've only just joined this site, i don't know how to move it to the XNA forum.

Since I am new to this, I've never tried creating another class, so I don't know how I would do this or how to call it in my main class. Could you suggest how I should make an object class with my current code or point me to a helpful tutorial?
Was This Post Helpful? 0
  • +
  • -

#4 ShadowsEdge19  Icon User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Re: c# XNA drag and drop sprites and update position in list.

Posted 21 January 2012 - 07:57 AM

Don't worry about moving the topic yourself, the forum moderators can handle that, I can't myself since I'm not a Forum Leader for this forum but I am one in the XNA forum.

As for creating a class, in your version of Visual Studio you should see the Solution Explorer panel that shows all the files and folders for your project, this is by default on the far right of the program.

Hover your mouse on the line just under where it says "Solution '<project name>' (2 projects)" where it says the project name in bold black lettering. Right click on that line and go to the Add -> Class.. and it should bring up the templates list with a default name for your class at the bottom "Class1.cs", change that to what you want.

Now since this is XNA we need to put some default stuff into the class you just created in order for you to use it as a drawable item.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace ProjectName
{
    public class Circle
    {

        // Some variables for this object class, i.e. Attributes

        // The 'constructor' method
        public Circle()
        {

        }

        // Some XNA specific methods
        public void LoadContent(ContentManager content)
        {

        }

        public void Draw(SpriteBatch spriteBatch)
        {
        
        }
    }
}



Here's an example about how to do the above.

Here's a C# example on how to use the class

Now from your main screen you have the LoadContent(), Update() and Draw() methods, in each of those (except the Update() since there is nothing to update with your circle) you can call your Circle class that you created in the screen constructor.

In your Game1 variables area:

Circle newCircle;



In your Game1()
newCircle = new Circle();



So in LoadContent() you would do:

Content.RootDirectory = "Content";
newCircle.LoadContent(Content);



in your Draw():

newCircle.Draw(spriteBatch);


This post has been edited by ShadowsEdge19: 21 January 2012 - 09:13 AM

Was This Post Helpful? 0
  • +
  • -

#5 Kathy123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 21-January 12

Re: c# XNA drag and drop sprites and update position in list.

Posted 21 January 2012 - 09:08 AM

Thank you, I have created my own circle class and copied and pasted the rest of my code over. However now when I run the program, i am getting an error saying ""ArgumentNullException was unhandled""
This error is turning up in my draw method in my Circle class:

 public void Draw(SpriteBatch spriteBatch)
        {
            foreach (Vector2 circlePosition in circles)
            {
                spriteBatch.Draw(circle, circlePosition, Color.White); // this is where the error is
            }



This is my main class draw method.
 protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.White);

            spriteBatch.Begin();

            planet.Draw(spriteBatch);


            spriteBatch.End();

            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }


Was This Post Helpful? 0
  • +
  • -

#6 ShadowsEdge19  Icon User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Re: c# XNA drag and drop sprites and update position in list.

Posted 21 January 2012 - 09:55 AM

What you are trying to do is draw all of your "circlePositions" from just one Circle object like you were trying to do before, but it won't work like that now.

You should give your circle class some Attributes that exist only for that object and not in the Game1 class:

Circle class

Texture2D circleTex;
Rectangle circlePosition;



Load the texture in LoadContent(), set the circlePosition from either the Circle() constructor or pass it through to the Draw() from Game1 class.

public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(circleTex, circlePosition, Color.White); // this is where the error is
}
[/code]

I presume your "planet" variable is of type Circle, so in your Game1.Draw() you are drawing 1 instance of Circle, that is correct. If you wish to have more Circles you should use List<Circle>().

So in Game1.Draw()

protected override void Draw(GameTime gameTime)
       {
           GraphicsDevice.Clear(Color.White);

           spriteBatch.Begin();

           foreach (Circle c in planets)
           {
               c.Draw(spriteBatch);
           }

           spriteBatch.End();

           // TODO: Add your drawing code here

           base.Draw(gameTime);
       }



Planets being created like so:

List<Circle> planets = new List<Circle>();


Edit: I forgot to mention, the basic override for spritebatch.Draw() takes (Texture2D, Rectangle, Color) NOT (Texture2D, Vector2, Color)

This post has been edited by ShadowsEdge19: 21 January 2012 - 10:07 AM

Was This Post Helpful? 0
  • +
  • -

#7 Kathy123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 21-January 12

Re: c# XNA drag and drop sprites and update position in list.

Posted 21 January 2012 - 12:08 PM

I have got attributes that exists only for that class. I changed my draw method to what you suggested and it got rid of the errors! But now im getting another error of the same type in my MouseOnCircle Method. I will pasted the whole code up this time.


    public class Circle
    {
        Vector2 circlePosition;
        Texture2D texture;
        bool mouseWasPressed = false;
        public List<Vector2> circles = new List<Vector2>();

        public Circle(Texture2D texture, Vector2 circlePosition)
        {
            this.texture = texture;
            this.circlePosition = circlePosition;
        }

        public void LoadContent(ContentManager Content)
        {
            texture = Content.Load<Texture2D>("circle");
        }


        public void Update(GameTime gameTime)
        {

            MouseState mouseState = Mouse.GetState();

            if (mouseState.LeftButton == ButtonState.Pressed)
            {
                MouseOnCircle(mouseState); //sets mouseOverSprite

                if (MouseOverSprite == false)
                {
                    if (mouseWasPressed == false)
                    {
                        mouseWasPressed = true;  // New mouse press, not over sprite, so new Circle created.
                        circlePosition.X = mouseState.X;
                        circlePosition.Y = mouseState.Y;

                        circles.Add(circlePosition);
                        System.Diagnostics.Debug.WriteLine(circlePosition);
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("ON SPRITE");// mouse click is on a sprite. So no new circle is created.
                    mouseWasPressed = true;
                }
            }
            else // mouse not currently pressed
            {
                mouseWasPressed = false;
            }
        }
        bool MouseOverSprite = false;
        public void MouseOnCircle(MouseState mouseState)
        {
            foreach (Vector2 circlePosition in circles)
            {
                if
               ((mouseState.X >= circlePosition.X) && mouseState.X <= (circlePosition.X + texture.Width) &&

                      mouseState.Y >= circlePosition.Y && mouseState.Y <= (circlePosition.Y + texture.Height))
                {
                    MouseOverSprite = true;
                }
                else
                {
                    MouseOverSprite = false;
                }
            }
        }


        public void Draw(SpriteBatch spriteBatch)
        {     
            foreach (Vector2 circlePosition in circles)
            {
                spriteBatch.Draw(texture, circlePosition, Color.White);
            }
      

        }
    } 



MAIN CLASS :

  public class Game1 : Microsoft.Xna.Framework.Game
    {

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        List<Circle> planets = new List<Circle>();
        Texture2D texture;
        Vector2 circlePosition;
        Circle planet;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

        }

        protected override void Initialize()
        {
          
            this.IsMouseVisible = true;

            base.Initialize();
        }

        protected override void LoadContent()
        {

            planet = new Circle(texture, circlePosition);
            spriteBatch = new SpriteBatch(GraphicsDevice);
          
        }

            
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        protected override void Update(GameTime gameTime)
        {

            planet.Update(gameTime);

        }
       
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.White);

            spriteBatch.Begin();

            foreach (Circle circle in planets)
            {
                circle.Draw(spriteBatch);         
            }


            spriteBatch.End();

            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }
    }
} 

Was This Post Helpful? 0
  • +
  • -

#8 ShadowsEdge19  Icon User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Re: c# XNA drag and drop sprites and update position in list.

Posted 21 January 2012 - 12:58 PM

Try to use a different name than circlePosition during your foreach loop as you are already using a variable named that already.

In your Circle variables area:

Vector2 circlePosition;


In your MouseOnCircle() method:

foreach (Vector2 circlePosition in circles)


I normally just use the initials of the variable to represent stuff in foreach loops:

foreach (Vector2 cp in circles)

This post has been edited by ShadowsEdge19: 21 January 2012 - 12:58 PM

Was This Post Helpful? 0
  • +
  • -

#9 Kathy123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 21-January 12

Re: c# XNA drag and drop sprites and update position in list.

Posted 21 January 2012 - 01:10 PM

Ok i changed it all to CP. Its still giving the same error. These two lines are highlighted and it says:

NullReferenceException was unhandled. Object reference not set to an instance of an object.

((mouseState.X >= cp.X) && mouseState.X <= (cp.X + texture.Width) &&

                      mouseState.Y >= cp.Y && mouseState.Y <= (cp.Y + texture.Height)) 

Was This Post Helpful? 0
  • +
  • -

#10 ShadowsEdge19  Icon User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Re: c# XNA drag and drop sprites and update position in list.

Posted 21 January 2012 - 03:11 PM

In your Game1 class you never initialized the Vector2 circlePosition that you sent to Circle():

planet = new Circle(texture, circlePosition);

Was This Post Helpful? 0
  • +
  • -

#11 Kathy123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 21-January 12

Re: c# XNA drag and drop sprites and update position in list.

Posted 21 January 2012 - 04:15 PM

Ok I have fixed all the errors, however now when i run the circle image will not come up. I can click and the output window shows the coordinates of where I am clicking. Just no image is showing up.

    
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        List<Circle> planets = new List<Circle>();
        Vector2 circlePosition = new Vector2();
        Circle planet;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

        }

        protected override void Initialize()
        {
          
            this.IsMouseVisible = true;

            base.Initialize();
        }

        protected override void LoadContent()
        {

            planet = new Circle(Content.Load<Texture2D>("circle"), circlePosition);
            spriteBatch = new SpriteBatch(GraphicsDevice);
          
        }

            
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        protected override void Update(GameTime gameTime)
        {

            planet.Update(gameTime);

        }
       
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.White);

            spriteBatch.Begin();

            foreach (Circle C in planets)
            {
                C.Draw(spriteBatch);         
            }


            spriteBatch.End();

            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }








Was This Post Helpful? 0
  • +
  • -

#12 Kathy123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 21-January 12

Re: c# XNA drag and drop sprites and update position in list.

Posted 21 January 2012 - 04:16 PM

Ok I have fixed all the errors, however now when i run the circle image will not come up. I can click and the output window shows the coordinates of where I am clicking. Just no image is showing up.

    
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        List<Circle> planets = new List<Circle>();
        Vector2 circlePosition = new Vector2();
        Circle planet;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

        }

        protected override void Initialize()
        {
          
            this.IsMouseVisible = true;

            base.Initialize();
        }

        protected override void LoadContent()
        {

            planet = new Circle(Content.Load<Texture2D>("circle"), circlePosition);
            spriteBatch = new SpriteBatch(GraphicsDevice);
          
        }

            
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        protected override void Update(GameTime gameTime)
        {

            planet.Update(gameTime);

        }
       
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.White);

            spriteBatch.Begin();

            foreach (Circle C in planets)
            {
                C.Draw(spriteBatch);         
            }


            spriteBatch.End();

            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }








Was This Post Helpful? 0
  • +
  • -

#13 ShadowsEdge19  Icon User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Re: c# XNA drag and drop sprites and update position in list.

Posted 21 January 2012 - 04:48 PM

I think you are confusing yourself at the moment with having one Circle called "planet" and another List<Circle> called "planets", you have called the Draw() only for the "planets" but only loaded the texture for "planet", and also only Updated() "planet" and not "planets".
Was This Post Helpful? 0
  • +
  • -

#14 Kathy123  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 21-January 12

Re: c# XNA drag and drop sprites and update position in list.

Posted 22 January 2012 - 05:10 AM

ok I understand what I am doing wrong here. I have now loaded the texture for planet, and updated planet and called draw() for planet. The program now runs like it did when I first posted on this forum. However this means I am no longer using
List<Circle> planets = new List<Circle>(); 


Is this right? Is this because a list is already specified in the Circle class?
Was This Post Helpful? 0
  • +
  • -

#15 ShadowsEdge19  Icon User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Re: c# XNA drag and drop sprites and update position in list.

Posted 22 January 2012 - 06:16 AM

You don't need a list in Circle unless you are planning on making a more complicated version of it that holds several co-ordinates for one object.

You either have A Circle, i.e. a single Planet
Or you have a List of Circles, i.e. multiple Planets

Both of those types should only exist in Game1 or another class that needs to use Circle.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2