Logic and maths for dragging object with mouse.

Started by
2 comments, last by Demus79 17 years, 6 months ago
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?

HTML5, iOS and Android Game Development using Corona SDK and moai SDK

Advertisement
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;
my-eulogy - A blog about coding and gfxsdgi - Semi-Daily Game IdeaChunkyHacker - Viewer for Relic chunky formats (used in DOW)
Thank you.

HTML5, iOS and Android Game Development using Corona SDK and moai SDK


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

This topic is closed to new replies.

Advertisement