java - 通过触摸屏幕移动矩形
问题描述
我想通过减少 x 位置来移动具有不同 x 位置的块而不改变它们的形状。
我尝试运行以下代码,但似乎块移动到拖曳位置方式以快速(正确的药水和其他我看不到哪里)。
downBlocks=new Arraylist<Rectangle>;
for (DownBlocks downBlocks:getBlocks()){
if(Gdx.input.isTouched()) {
Vector3 touchPos = new Vector3();
touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
downBlocks.x = (int) touchPos.x - downBlocks.x;
}
}
解决方案
要进行拖动,您需要记住手指最后一次触摸屏幕的点,以便获得手指增量。附带说明一下,如果只需要调用一次,请避免将代码放入循环迭代中。为您的每个 DownBlocks 一遍又一遍地取消投影屏幕的触摸点是很浪费的。
static final Vector3 VEC = new Vector3(); // reusuable static member to avoid GC churn
private float lastX; //member variable for tracking finger movement
//In your game logic:
if (Gdx.input.isTouching()){
VEC.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(VEC);
}
if (Gdx.input.justTouched())
lastX = VEC.x; //starting point of drag
else if (Gdx.input.isTouching()){ // dragging
float deltaX = VEC.x - lastX; // how much finger has moved this frame
lastX = VEC.x; // for next frame
// Since you're working with integer units, you can round position
int blockDelta = (int)Math.round(deltaX);
for (DownBlocks downBlock : getBlocks()){
downBlock.x += blockDelta;
}
}
不过,我不建议您使用整数单位作为坐标。如果您正在做像素艺术,那么我建议使用浮点数来存储坐标,并仅在绘图时对坐标进行四舍五入。这将减少看起来生涩的运动。如果您不使用像素艺术,我会一直使用浮点坐标。这是一篇有助于理解单位的好文章。
推荐阅读
- node.js - 从用户上传的图像创建链接的最佳方法是什么?
- javascript - 使用javascript同时迭代两个字符串数组
- android - 尝试实现 RecyclerView 点击监听器时位置代码不正确
- javascript - 当我在平面列表中选择一个项目时如何更改按钮
- regex - 正则表达式的 Kotlin 性能问题
- java - Java:选择排序停止而没有任何错误消息
- ml.net - 如何为管道中间的数据创建 CustomMapping 转换?
- javascript - Vibrant.js 库未加载
- javascript - Firebase getDownloadURL 推入数组
- ssl - Thunderbird 78:如何添加安全异常?