【发布时间】:2019-04-15 23:05:39
【问题描述】:
我正在用 Java 中的 libGDX 制作游戏。我正在尝试进行碰撞检测。正如您在图像中看到的,我有一条线,它是一堵墙和一个具有指定半径的玩家。期望的位置是玩家试图进入的下一个位置。但是因为有一面墙,所以他被放置在速度矢量上的实际位置,但更接近上一个位置。我试图弄清楚如何检测到更近的位置?
我的尝试:
private void move(float deltaTime) {
float step;
beginMovementAltitude();
if (playerComponent.isWalking())
step = handleAcceleration(playerComponent.getSpeed() + playerComponent.getAcceleration());
else step = handleDeacceleration(playerComponent.getSpeed(), playerComponent.getAcceleration());
playerComponent.setSpeed(step);
if (step == 0) return;
takeStep(deltaTime, step, 0);
}
private void takeStep(float deltaTime, float step, int rotate) {
Vector3 position = playerComponent.getCamera().position;
float x = position.x;
float y = position.y;
int radius = playerComponent.getRadius();
auxEnvelope.init(x, x + radius, y, y + radius);
List<Line> nearbyLines = lines.query(auxEnvelope);
float theta;
int numberOfIntersections = 0;
float angleToMove = 0;
Gdx.app.log(step + "", "");
for (Line line : nearbyLines) {
VertexElement src = line.getSrc();
VertexElement dst = line.getDst();
auxVector3.set(playerComponent.getCamera().direction);
auxVector3.rotate(Vector3.Z, rotate);
float nextX = x + (step * deltaTime) * (auxVector3.x);
float nextY = y + (step * deltaTime) * playerComponent.getCamera().direction.y;
float dis = Intersector.distanceLinePoint(src.getX(), src.getY(), dst.getX(), dst.getY(), nextX, nextY);
boolean bodyIntersection = dis <= 0.5f;
auxVector21.set(src.getX(), src.getY());
auxVector22.set(dst.getX(), dst.getY());
auxVector23.set(nextX, nextY);
if (bodyIntersection) {
numberOfIntersections++;
if (numberOfIntersections > 1) {
return;
}
theta = auxVector22.sub(auxVector21).nor().angle();
float angle = (float) (180.0 / MathUtils.PI * MathUtils.atan2(auxVector23.y - position.y, auxVector23.x - position.x));
if (angle < 0) angle += 360;
float diff = (theta > angle) ? theta - angle : angle - theta;
if (step < 0) step *=-1;
angleToMove = (diff > 90) ? theta + 180 : theta;
}
}
if (numberOfIntersections == 0) {
moveCameraByWalking(deltaTime, step, rotate);
} else {
moveCameraInDirection(deltaTime, step, angleToMove);
}
}
【问题讨论】:
-
你尝试了什么,你的错误是什么?
-
在您提供的链接中,我没有看到将播放器置于“固定”位置的相关部分。我一开始尝试的是检查下一个位置是否与墙的距离小于半径。如果属实,我不会让玩家移动到那里。如果玩家的速度是固定的,这种行为很好。但是在我的游戏中,速度会根据输入加速和减速 - 所以如果速度高,玩家不会移动,但速度低时它会移动(在靠近墙壁减速时会产生一些“慢跑”移动效果)
-
您能否提供您在问题中描述的此尝试的代码?
-
是的,已发布到问题中
-
在第一种方法中似乎有很多行重复,这是实际代码吗?我猜不是,因为这不会编译(重复的变量名)。同样适用于第二种方法
标签: java libgdx 2d collision-detection