Sign in to follow this  
utilae

Logic and maths for dragging object with mouse.

Recommended Posts

Hi, I am using C++ I am trying to move an object (looks like a square image) based on the mouse be over the image, the left button being down and when the mouse is moved the object moves. Right now, I can move the object but only by having the object be centered around my mouse when I click. I would like to have the mouse stay relative to where it was clicked on the object, eg if you click in the top left, then the mouse stays in the top left while the object moves with the mouse. Here's what I have so far:
//move object
if(m_bMoveable==true)
{
   //mouse in object
   if(PtInRect(&m_recPos,m_pMouse->m_ptCurrentMousePos)==true)
   {
      if(m_pMouse->m_nMouseState==1)//left mouse button down
      {
         //move object - sets object to be centered on mouse
         //want object to stay with mouse according to where mouse is in object
         float nHeight=(m_recPos.bottom-m_recPos.top)/2;
         float nWidth=(m_recPos.right-m_recPos.left)/2;
         m_recPos.top=m_pMouse->m_ptCurrentMousePos.y-nHeight;
         m_recPos.left=m_pMouse->m_ptCurrentMousePos.x-nWidth;
         m_recPos.right=m_pMouse->m_ptCurrentMousePos.x+nWidth;
         m_recPos.bottom=m_pMouse->m_ptCurrentMousePos.y+nHeight;
      }

   }
}

Anyone able to help?

Share this post


Link to post
Share on other sites
Calculate the offset from the corner on mouse down and then use that offset to position the object later.

MouseDown:
offset.X = mouse.X - obj.X;
offset.Y = mouse.Y - obj.Y;

MouseMove
obj.X = mouse.X - offset.X;
obj.Y = mouse.Y - offset.Y;

Share this post


Link to post
Share on other sites

Howabout making a "draggable" object such as

class InterfaceDraggable
{
public:
virtual void Move(int DeltaX,int DeltaY) = 0;
virtual bool HitTest(int MouseX,int MouseY) = 0;

};

Then, on the event of pushing the mouse button, you'll go through your objects and find the object which responds to the HitTest with positive result. Keep the pointer to this/these objects and until you get "mouse up" event (when you set the draggedobject list to NULL) you can pass the Move events with the mouse movement deltas. This way the object stays in a relation with the cursor always. Although changing the point of view may screw it up.

Cheers

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this