简体   繁体   English

触摸屏幕即可移动矩形

[英]Move rectangle by touching the screen

I want to move blocks with different x-positions without changing their shape by reducing the x-position. 我想移动具有不同x位置的块而不通过减小x位置来更改其形状。

I have tried to run the following code, but it seems like the blocks move to a tow position way to fast (correct potion and other i can't see where). 我试图运行以下代码,但似乎块移动到拖曳位置的方式更快(正确的药水和其他我看不到的地方)。

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;
    }
}

To do a drag, you need to remember the point where the finger last touched the screen so you can get a finger delta. 要进行拖动,您需要记住手指最后一次触摸屏幕的位置,以便获得手指增量。 And as a side note, avoid putting code inside your loop iteration if it only needs to be called once. 另外,如果只需要调用一次,则避免将代码放入循环迭代中。 It's wasteful to unproject the screen's touch point over and over for every one of your DownBlocks. 反复为每个DownBlock取消投影屏幕的触摸点是很浪费的。

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;
    }
}

I don't recommend using integer units for your coordinates, though. 不过,我不建议您使用整数单位作为坐标。 If you are doing pixel art, then I recommend using floats for storing coordinates, and rounding off the coordinates only when drawing. 如果您要进行像素画,则建议使用浮点数来存储坐标,并且仅在绘制时才对坐标进行四舍五入。 That will reduce jerky-looking movement. 那将减少看起来像生涩的运动。 If you are not using pixel art, I would just use float coordinates all the way. 如果您不使用像素图,我会一直使用浮动坐标。 Here's a good article to help understand units. 这是一篇很好的文章,可以帮助您理解单位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM