0
\$\begingroup\$

I already have a MouseMotionListener with the mouseDragged method implemented. I can drag an object with the mouse, but it doesn't matter where I put the mouse inside the object, it will move it's origin point to the mouse.

I know that this is what the simple x = mouseX; y = mouseY code should do, but what is the code to drag the object relative to the position of the mouse inside the shape?

I tried this, but it doesn't work when the object is in the position 0:

x = mouseX - (mouseX - x);
y = mouseY - (mouseY - y);

The code doesn't work because when X and Y are 0, it is basically x = mouseX - mouseX; y = mouseY - mouseY, that is 0 both. What is the algorithm that is "0-pos-proof" that I can use?

\$\endgroup\$
0
\$\begingroup\$

I believe you should ignore the position of the mouse and the game object while moving, they should not really make any difference, right? Focus on just offseting the game object's position acording to how much the mouse has moved while the button is pressed.

EX:

 public void Update()
{
    if(Input.GetMouseButton(1) && isDragging)
    {
        transform.Translate(Input.GetAxis("Horizontal") * Time.deltaTime, Input.GetAxis("Vertical") * Time.deltaTime, 0);
    }
}

I really don't know if this code will work, just hope it helps you.

\$\endgroup\$
  • \$\begingroup\$ How does I calculate how much the mouse moved? I tried creating a oldMouseX and oldMouseY variable that is set when the mouse is pressed, then increasing X and Y by currentX - oldMouseX and currentY - oldMouseY, but with the most minimal movement of the mouse the object moves out of the screen. \$\endgroup\$ – Taarak Sep 24 '18 at 14:58
  • \$\begingroup\$ Post the code you used to try and do this, and maybe someone can help you. There are many variables in play here, no one will be able to help you without more information about your problem. \$\endgroup\$ – Thales Donizetti Sep 24 '18 at 16:26
  • \$\begingroup\$ Nevermind the problem was that I was using oldMouseY in both X and Y axis, so it just started teleporting around when I clicked. Thanks :D \$\endgroup\$ – Taarak Sep 24 '18 at 21:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.