Libgdx 1.9.8:如何同步拖拽时精灵/角色与光标位置?
Hey there! I’ve run into this exact issue with LibGDX’s DragAndDrop system before—default behavior sticks the drag actor’s top-left corner to the cursor, which looks totally off for inventory items. Let’s get that sprite centered properly.
The Root Cause
LibGDX’s Payload class defaults to aligning the top-left corner of your drag actor with the cursor position. To center it, you just need to add an offset equal to half the sprite’s width and height.
Step-by-Step Fix
Here’s how to adjust your Source implementation to handle the offset correctly:
import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop; // Assume your inventory slot is an Actor subclass like this public class ItemSlotSource extends DragAndDrop.Source { private final ItemSlot itemSlot; public ItemSlotSource(ItemSlot itemSlot) { super(itemSlot); this.itemSlot = itemSlot; } @Override public DragAndDrop.Payload dragStart(InputEvent event, float x, float y, int pointer) { DragAndDrop.Payload payload = new DragAndDrop.Payload(); Actor itemSprite = itemSlot.getItemDisplaySprite(); // Get your visible item sprite payload.setDragActor(itemSprite); // Calculate offset to center the sprite on the cursor // Use scaled dimensions if your sprite has scale applied! float spriteWidth = itemSprite.getWidth() * itemSprite.getScaleX(); float spriteHeight = itemSprite.getHeight() * itemSprite.getScaleY(); float centerOffsetX = spriteWidth / 2f; float centerOffsetY = spriteHeight / 2f; // Set the offset—this tells LibGDX where to place the cursor relative to the drag actor payload.setOffset(centerOffsetX, centerOffsetY); return payload; } }
Key Notes to Avoid Headaches
- Scaled Sprites: If you’ve applied
setScale()to your item sprite, always multiply the base width/height by the scale value (like in the example above). Using rawgetWidth()/getHeight()will give you incorrect offsets for scaled assets. - Actor Positioning: If your
ItemSlotis inside aTableorContainerwith padding/margins, you don’t need to adjust for that—LibGDX handles stage coordinate conversion automatically in the dragStart event. - Testing: After adding the offset, test with different item sizes to make sure all sprites center correctly. Small icons and large equipment sprites should both align properly.
Quick Troubleshoot Check
If you’re still seeing a slight offset, double-check:
- That you’re using the visible drag actor (not a hidden placeholder) to calculate dimensions.
- That your sprite’s origin hasn’t been changed with
setOrigin()—if it has, you might need to adjust the offset calculation to match the origin point.
That should get your inventory items dragging perfectly centered on the cursor! 🎮
内容的提问来源于stack exchange,提问作者Redas Shuliakas

