使用libgdx和box2d将身体移到触摸位置 [英] Move a body to the touched position using libgdx and box2d
本文介绍了使用libgdx和box2d将身体移到触摸位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将没有重力的物体移动到单击或触摸位置,然后将其停止。但是,由于我的Vector3的坐标,取决于我单击的位置,它的移动速度实际上是快还是慢。另外,它的行为就像我不想要的游戏小行星一样。
I am trying to move a body with no gravity to the click or touch position and then stop it. However, depending where I click it moves really fast or really slow because of the coordinates of my Vector3. Also, it behaves like that game asteroids which I do not want.
基本上,我只需要myBody跟随鼠标的点击进行触摸即可。
Basically, I just need myBody follows the click of the mouse our touch.
在这里到目前为止:
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
camera.unproject(touchPosition.set(screenX, screenY, 0));
Vector2 velocity = new Vector2(touchPosition.x, touchPosition.y);
myBody.setLinearVelocity(velocity);
return true;
}
推荐答案
您需要规范化考虑身体本身的位置。以下代码未经测试,但可以正常工作。
You need to normalize and also take the position of the body itself into account. The following code is untested, but should work.
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
camera.unproject(touchPosition.set(screenX, screenY, 0));
// calculte the normalized direction from the body to the touch position
Vector2 direction = new Vector2(touchPosition.x, touchPosition.y);
direction.sub(myBody.getPosition());
direction.nor();
float speed = 10;
myBody.setLinearVelocity(direction.scl(speed));
return true;
}
这篇关于使用libgdx和box2d将身体移到触摸位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文