台球移动算法
我正在尝试在 Java2ME 中移动台球。当速度稳定时很容易。我根据 x 和 y 速度更改球的 x 和 y 坐标。它们都是整数。没问题。然而,普通的台球必须先快速移动,然后减速并停止。因为球的 x 和 y 坐标是整数,所以我无法按百分比减小 x 和 y 速度。我的意思是,如果速度是 9 并且我想将其降低 10%,我不能执行“9 * 0.1”,因为它必须是整数。我知道坐标不能是双重的。我能做些什么? 代码:
public void move() {
//... Move the ball at the given velocity.
m_x += m_velocityX; // m_x: x coordinate of the ball
m_y += m_velocityY; // m_y: y coordinate of the ball
//... ball hits the borders and change the way
if (m_x < 0) { // If at or beyond left side
m_x = 0; // Place against edge and
m_velocityX = -m_velocityX; // reverse direction.
} else if (m_x > m_rightBound) { // If at or beyond right side
m_x = m_rightBound; // Place against right edge.
m_velocityX = -m_velocityX; // Reverse direction.
}
if (m_y < 0) { // if we're at top
m_y = 0;
m_velocityY = -m_velocityY;
} else if (m_y > m_bottomBound) { // if we're at bottom
m_y = m_bottomBound;
m_velocityY = -m_velocityY;
}
}
I am trying to move a pool ball in Java2ME. It is easy when the velocity is stable. I change the x and y coordinate of the ball according to x and y velocity. They are all integers. No problem. However a normal pool ball has to go first fast then slowdown and stop. Because the x and y coordinates of the ball are integers, I can't decrease the x and y velocity by percentage. I mean if the velocity is 9 and I want to decrease it by 10% I cant do it "9 * 0.1" because it has to be an integer. I know the coordinates can't be double. What can I do?
the code:
public void move() {
//... Move the ball at the given velocity.
m_x += m_velocityX; // m_x: x coordinate of the ball
m_y += m_velocityY; // m_y: y coordinate of the ball
//... ball hits the borders and change the way
if (m_x < 0) { // If at or beyond left side
m_x = 0; // Place against edge and
m_velocityX = -m_velocityX; // reverse direction.
} else if (m_x > m_rightBound) { // If at or beyond right side
m_x = m_rightBound; // Place against right edge.
m_velocityX = -m_velocityX; // Reverse direction.
}
if (m_y < 0) { // if we're at top
m_y = 0;
m_velocityY = -m_velocityY;
} else if (m_y > m_bottomBound) { // if we're at bottom
m_y = m_bottomBound;
m_velocityY = -m_velocityY;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果速度必须是积分,只需将值更新为浮点计算的下限即可。因此,要将速度降低 10%:
有一天您可能想做一些更奇特的事情,但这看起来很简单且可行。
If the velocity must be integral, just update the values to the floor of the floating-point calculation. So to reduce velocity by 10%:
You might want to do something fancier someday, but this seems simple and workable.
您应该将球速度存储为
速度
和角度
。此外,提到的每个变量都应该是
float
或double
。那么一切都会变得更容易,也更准确。
该算法将是:
You should store the ball speed as
velocity
andangle
.Also, every variable mentioned should be
float
ordouble
.Then everything will be easier, and much more accurate.
The algorithm will then be:
大约如下......
About like below...