java - 如何使物体转向相反的方向?

标签 java

考虑出界位置为 6 和 -6。

我想让船掉头朝相反的方向移动。

这是我的代码..它仍然没有100%按照我想要的方式工作。我很好奇看看有没有人 有任何想法如何改进。 这是我的代码的逻辑。

//If the ship hits a boundary it turns around and moves in the opp.
//direction. To do this, the ship's velocty should be flipped from a 
//negative into a positive number, or from pos to neg if boundary
//is hit.

//if ship position is -5 at velocity -1 new ship pos is -6
//if ship position is -6 at velocity -1 new ship velocity is +1
//                                      new ship position is +5

这是我的代码:

public void move() 
{
    position = velocity + position;

    if (position > 5)
    {
        velocity = -velocity;
    }
    else if (position < -5)
    {
        velocity = +velocity;
    }
}

最佳答案

代码velocity = +velocity;不会将负速度更改为正速度。这相当于将速度乘以 +1,但不会改变符号。

要在出界时翻转速度符号,您需要始终乘以-1

不太清楚界限是什么,所以下面我假设它们是 6 和 -6。

position += velocity;
//make sure the ship cannot go further than the bounds
//but also make sure that the ship doesn't stand still with large velocities
if (position > 6)
{
    velocity = -velocity;
    position = 6;
}
if (position < -6)
{
    velocity = -velocity;
    position = -6;
}

关于java - 如何使物体转向相反的方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18871247/

相关文章:

java - 减少数学分解过程中的迭代

java - ORA-29532 : Java call terminated by uncaught Java exception: java. awt.HeadlessException

java - Java (Android) 中的 UDP 客户端,用于从 X-Plane 12 获取数据

java - 安卓 : Setting text in recycler view

java - JApplet Form 如何与 Servlet 通信?

java - 动态指定Install4J可下载组件URL

java - Android 中的序列化?

java - 随机选择键值对的最佳方法

java - 使用 RecyclerView 的 asynctask 在 android 中下载图像

java - 线程同步相关问题