如何使图像沿 x 轴反弹?
我有一个图像在增量时间(dt)内以给定速度水平移动。但问题是,当图像到达世界大小的尽头时,图像不会反弹。我怎样才能使图像向后反弹,以便将其保留在世界内部?
任何帮助都可以。
到目前为止,这是我尝试过的:
@Override
public void move(long dt)
{
// v = dx / dt
// dx m = v m/s . dt s
double dt_s = dt / 1e9;
double dx_m = speed * dt_s;
double left_wall = 0;
double right_wall = board.x1_world;
if (x <= right_wall)
{
x += dx_m;
if (x >= right_wall)
{
x = right_wall;
x *= -dx_m;
}
}
}
I have an image which moves horizontally with a given speed over a delta time(dt). But the problem is,the image doesn't bounces off when it reaches the end of the size of the world.How can i make the image bounces off backward so it would be kept inside the world?
Any help will do.
Here's what i've tried so far:
@Override
public void move(long dt)
{
// v = dx / dt
// dx m = v m/s . dt s
double dt_s = dt / 1e9;
double dx_m = speed * dt_s;
double left_wall = 0;
double right_wall = board.x1_world;
if (x <= right_wall)
{
x += dx_m;
if (x >= right_wall)
{
x = right_wall;
x *= -dx_m;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当图像的 x 坐标到达边界时,只需更改水平速度的方向(将其乘以 -1)。但您应该使用这样的条件:
而不仅仅是
x >= right_wall
,因为这样做,图像在“触及”世界尽头时会反弹。When the x coordinate of your images reach an border, just change the orientation of the horizontal speed (multiply it for -1). But you should use an condition like this:
Instead of just
x >= right_wall
, because doing so, the image will bounce when it "touchs" the end of the world.除了按照 @Oscar 的建议单独检查每一端之外,您可能还需要考虑图像的有限宽度,如
地铁
模拟。In addition to checking each end separately, as suggested by @Oscar, you may need to account for the image's finite width, as shown in this
Subway
simulation.