Java / Slick2D运动困难(添加动作而不是设置它?)

时间:2015-09-03 19:07:33

标签: java rotation slick2d motion

我最近从Gamemaker:Studio迁移到Java和Slick2D。我不确定如何描述我的问题,但我会尽我所能。

在Gamemaker中,有一个名为motion_add的功能,可以使用给定的参数(速度和方向)为对象添加动作。

假设我们有一个物体以20像素/帧向下移动。如果您要将该对象的角度反转180度(现在它指向上方)并运行motion_add代码,它将一直减速到0,然后再次加速。这对于浮动空间运动非常有效(这正是我想要做的)。

我的问题是,如何重新创建?这是我目前的移动代码:

private void doPlayerMovement(Input input, int delta) {
    // Calculate rotation speed
    rotateSpeed = rotateSpeedBase - (speed / 5);
    if (rotateSpeed < 0.1f) { rotateSpeed = 0.1f; }

    // Get input
    if (input.isKeyDown(Input.KEY_A)) {
        // Rotate left
        if (input.isKeyDown(Input.KEY_W)) { rotation -= rotateSpeed * delta; }
        sprite.rotate(-rotateSpeed * delta);
    } 

    if (input.isKeyDown(Input.KEY_D)) {
        // Rotate right
        if (input.isKeyDown(Input.KEY_W)) { rotation += rotateSpeed * delta; }
        sprite.rotate(rotateSpeed * delta);
    } 

    if (input.isKeyDown(Input.KEY_W)) {
        // Accelerate
        speed += acceleration * delta;
    } if (input.isKeyDown(Input.KEY_S)) {
        // Decelerate
        speed -= acceleration * delta;
    } else {
        if (speed > 0) { speed -= friction; }
    }

    // Clamping
    if (speed > maxSpeed) { speed = maxSpeed; } else if (speed < minSpeed) { speed = minSpeed; }
    if (rotation > 360 || rotation < -360) { rotation = 0; }

    // Make sure rotation catches up with image angle, if necessairy
    if (rotation != sprite.getRotation() && input.isKeyDown(Input.KEY_W)) {
        rotation = sprite.getRotation();
    }

    // Update position
    position.x += speed * Math.sin(Math.toRadians(rotation)) * delta;
    position.y -= speed * Math.cos(Math.toRadians(rotation)) * delta;

会发生什么:

A和D旋转精灵。如果按下W(加速对象),它会“控制”对象。如果对象的旋转与精灵的旋转不同,则对象的旋转将设置为精灵的旋转,那是我的问题。

执行此操作将导致对象立即以新的方向拍摄,速度不会减慢。如何让它变慢?

编辑(排序) 我敢肯定必须有一个名字,如果你要以100英里/小时的速度开车,让它以某种方式转动180度当它正在移动,然后点燃气体,它会减速然后再加速。这就是我想要实现的目标。

1 个答案:

答案 0 :(得分:1)

您必须重新创建此行为。它可能被称为惯性。您可以向对象添加方向向量,以便您拥有移动方向以及动画指向的有效方向。

然后,当您在移动时改变方向时,您必须减速才能有效地向新方向移动。

Vector movementVector=...; // choose whatever class you want
Vector pointingVector=...;

if (movementVector.x == -pointingVector.x || movementVector.y == -pointingVector.y) {
    // if pressing W then decelerate
    // if reaching speed == 0 then change movementVector value and accelerate in the other way
}