简体   繁体   English

Java反弹物理:永无止境的反弹

[英]Java bounce physics : never ending bounce

I have recently started programming games in java. 我最近开始用Java编程游戏。 I come from a C# / XNA background and i already have experience in game development. 我来自C#/ XNA背景,并且已经有游戏开发经验。 However I have a problem in my java game. 但是我的java游戏有问题。 I have a bouncing script which makes a in-game "particle" bounce upon collision with a solid surface, such as the ground. 我有一个弹跳脚本,当与固体表面(例如地面)碰撞时,该弹跳脚本会使游戏中的“粒子”反弹。 Here is a snippet of the code that manages the bouncing. 这是管理弹跳的代码片段。

private final void respondY(Rectangle r)
{
    if(!r.intersects(getBounds())) // If not colliding, return
        return;

    if(Yvel > 0) // If falling...
    {
        if(r.y < Y + Height) //Another collision test
        {
            Y = r.y - Height; // Set Y to top of object
            Yvel *= -bounce; // Bounce (Here is the problem)
            onFloor = true;
        }
    }
    else if(Yvel < 0) // If hit ceiling
    {
        if(Y < r.y + r.height) // Collision test
        {
            Y = r.y + r.height; // Set Y to bottom of object
            Yvel = 0; // No bouncing here
        }
    }
}

The problem is that the object bounces upon the floor as it should, but after a while the object bounces constantly at the same height where I want it to stop bouncing when it got to that constant height. 问题在于物体会按原样在地板上弹起,但过一会儿,物体会以相同的高度不断弹跳,直到我达到该恒定高度时我希望它停止弹跳。

NOTE: 注意:

  • Yvel is a int that is the vertical velocity of the object Yvel是一个整数,它是物体的垂直速度

  • Bounce is a float that controls how "bouncy" a object is. 弹跳是一个浮点,用于控制对象的“弹跳”程度。 eg 0.5 means that it bounces half as high as it fell 例如0.5表示它的弹跳是跌落的一半

Thanks in advance! 提前致谢! Please note that this is my first post so if I make mistakes please point them out in a constructive manner. 请注意,这是我的第一篇文章,因此,如果我犯了错误,请以建设性的方式指出。

The float (and double ) types are imprecise. float (和double )类型不精确。 This especially causes problems when dealing with very small numbers - in fact there's a smallest representable number and a finite quantity of possible numbers that can be represented (and bit like quantum physics). 这在处理非常小的数字时尤其会引起问题-实际上,存在最小的可表示数字和有限数量的可以表示的可能数字(并且有点像量子物理学)。 The number stored by a float is actually the closest number possible to represent to the calculation result. float存储的数字实际上是最可能代表计算结果的数字。

What's happening is the velocity calculation never reaches zero, because the result of multiplying the smallest number float can represent by a value >= .5 is itself. 发生的事情是速度计算永远不会达到零,因为将最小float乘以> = .5的值所得到的结果就是它本身。

I would force it to zero by putting a low threshold on the calculation result: 我通过在计算结果上设置一个低阈值来将其强制为零:

Yvel = Yvel * -bounce;
if (Yvel < .000001F)
    Yvel = 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM