我正在用libgdx创建一个游戏,我用舞台和演员来制作游戏中的实体。但问题是我不能让演员呆在舞台或银幕里。当我把演员拖到最低、最高、最左或最右边的屏幕上时,它就会从屏幕上消失。我要它留在屏幕里。
我该怎么办?请帮帮忙。
这是我用来拖动我的演员的代码片段。
addListener(新的DragListener(){ @重写公共布尔型touchDown(InputEvent事件,浮点数x,浮点数y,int指针,int按钮)){ camera.unproject(dimension.set(x,y,0));System.out.println("clicked "+ x+,“+y”);返回true;}@覆盖公共空touchDragged(InputEvent事件,浮点数x,浮点数y,int指针){ moveBy(x-(getWidth()/2),y-(getHeight()/3));}@覆盖公共super.touchUp(InputEvent事件,浮点数x,浮点数y,int指针,int按钮){super.touchUp(事件,x,y,指针,按钮);}};};
发布于 2016-01-17 16:14:28
Stage
确实有getWidth
和getHeight
方法。它们返回由内部Viewport
管理的世界大小。Window
类具有可选的拖动行为和keepWithinStage
参数。
这是来自LibGDX 1.8.0 (Window
类)的代码片段:
public void touchDragged (InputEvent event, float x, float y, int pointer) {
if (!dragging) return;
float width = getWidth(), height = getHeight();
float windowX = getX(), windowY = getY();
float minWidth = getMinWidth(), maxWidth = getMaxWidth();
float minHeight = getMinHeight(), maxHeight = getMaxHeight();
Stage stage = getStage();
boolean clampPosition = keepWithinStage && getParent() == stage.getRoot();
if ((edge & MOVE) != 0) {
float amountX = x - startX, amountY = y - startY;
windowX += amountX;
windowY += amountY;
}
if ((edge & Align.left) != 0) {
float amountX = x - startX;
if (width - amountX < minWidth) amountX = -(minWidth - width);
if (clampPosition && windowX + amountX < 0) amountX = -windowX;
width -= amountX;
windowX += amountX;
}
if ((edge & Align.bottom) != 0) {
float amountY = y - startY;
if (height - amountY < minHeight) amountY = -(minHeight - height);
if (clampPosition && windowY + amountY < 0) amountY = -windowY;
height -= amountY;
windowY += amountY;
}
if ((edge & Align.right) != 0) {
float amountX = x - lastX;
if (width + amountX < minWidth) amountX = minWidth - width;
if (clampPosition && windowX + width + amountX > stage.getWidth()) amountX = stage.getWidth() - windowX - width;
width += amountX;
}
if ((edge & Align.top) != 0) {
float amountY = y - lastY;
if (height + amountY < minHeight) amountY = minHeight - height;
if (clampPosition && windowY + height + amountY > stage.getHeight())
amountY = stage.getHeight() - windowY - height;
height += amountY;
}
lastX = x;
lastY = y;
setBounds(Math.round(windowX), Math.round(windowY), Math.round(width), Math.round(height));
}
您可以通过将X夹紧到0和stage.getWidth() - actor.getWidth()
来简化这一点,并为Y做同样的操作。
https://stackoverflow.com/questions/34793994
复制相似问题