如何在C++ GLUT中实现2D物体类橡胶效果的释放触发式拖拽移动
Hey there! Let's get that rubbery drag effect working exactly how you want it. The key issue with your current setup is that you're updating the object's position while dragging (even with a delay), but what you really need is to separate the "tracking the target" phase from the "moving to the target" phase.
Here's a step-by-step breakdown of the correct logic, plus fixes for your current problem:
Core Concept
We'll split the interaction into three clear phases:
- Detect a valid click on the object
- Track the target position without moving the object during drag
- Trigger the rubbery smooth movement only when the mouse is released
Step 1: Handle Initial Mouse Down
When the user presses the mouse button:
- Check if the click position is inside your 2D object's collision bounds (use point-in-rect or point-in-shape logic, depending on your object's shape)
- If it is, set a boolean flag like
isDragging = true— don't modify the object's position here - If not, ignore the click entirely
Step 2: Track Target Position During Drag
While isDragging is true and the mouse is moving:
- Simply update a
targetPositionvariable to match the current mouse position - Do NOT update the object's actual position during this phase. This is why your current setup has that laggy follow — you're trying to animate mid-drag instead of just tracking the end point.
- Optional: Draw a temporary preview (like a semi-transparent shadow or outline) at
targetPositionso the user can see where the object will move to.
Step 3: Trigger Rubber Movement On Mouse Release
When the user releases the mouse button:
- If
isDraggingistrue, setisDragging = false - Now start your rubbery animation logic to move the object from its current position to
targetPosition. A simple damping formula works great for that rubbery feel:
// Example in JS (adjust syntax for your engine/language) const damping = 0.15; // Lower = slower, bouncier movement object.x += (targetPosition.x - object.x) * damping; object.y += (targetPosition.y - object.y) * damping;
Run this calculation every frame until the object is close enough to targetPosition (add a small threshold to stop the animation once it's near enough to avoid jitter).
Why Your Current Setup Isn't Working
That delayed follow you're seeing happens because you're applying the damping animation while dragging. The object is trying to catch up to the mouse every frame during the drag, resulting in that laggy trail. By moving the animation logic to only run after release, you get the exact behavior you want: object stays put until you let go, then smoothly rubber-bands to the target.
内容的提问来源于stack exchange,提问作者Alonzo Robbe

