- Home /
Maintain x axis distance between a 2d rigidbody and mouse
Hey guys,
I'm trying to make it so that when the mouse is clicked and held, that the initial distance in the x axis between the 2d rigidbody and the mouse is maintained when the mouse is moved. This 2d rigidbody does not have a collider, so that is not a concern. The y position of the 2d rigidbody is set separately. This is made a little more complicated in that the main camera follows the main character, which is not the 2d rigidbody I've been talking about, so that affects the mouse position.
I created a separate rigid body that follows the mouse, and then I try to compare the transform locations each fixed frame, and move the 2d rigidbody accordingly. This is how I've tried to set the x position of the 2d rigidbody:
desiredObjectLocation.x = lastObjectLocation.x + (mouseLocation.x - lastMouseLocation.x) - (player.position.x - lastCharacterLocation.x);
It's close to working, but I'm missing something. When I move the mouse, the distance between the mouse and the 2d rigid body slowly gets larger or smaller, but I need it to be exact (or closer to).
Can you guys see a small fix to my code, or have a different way of doing this?
Thank you! Andrew
Answer by wibble82 · Mar 06, 2014 at 08:29 PM
I could be wrong but you might be suffering from a level of feedback due to your calculations changing every frame (it depends where you're setting those 'last x' variables). Floating point numbers are not perfect, so tiny errors can build up over multiple frames if you aren't careful. This often exhibits itself as things slowly drifting away from the correct solution.
How about:
when the user first clicks, store the x offset from the mouse to the object
every frame, set the desired x position to the new mouse position plus the original x offset
That way, you've calculated the important number up front, and every frame are just updating the new position. As a result, inaccuracies can't build up and you should see more stable behavior.
Thanks for your comment wibble. I wish I had a reputation high enough to up vote you.
I've been staring at the code for the longest time trying to figure out where there feedback is co$$anonymous$$g from, but I just can't find it. I update the "last x" variables at the end of each fixedupdate frame.
After I couldn't figure out the above, I tried something similar to what you suggested, but it has weird outcomes because the main character is attached to the 2d rigid body by a 2d spring joint.