简体   繁体   English

2D球碰撞和分辨率

[英]2D Ball Collision and resolution

I have created a simple method that detects collision between the two balls by calculating the distance. 我创建了一种简单的方法,可以通过计算距离来检测两个球之间的碰撞。 I was wondering, once the collision is detected, how could I update the balls positions to not allow the balls to enter each other(intersect) 我想知道,一旦检测到碰撞,我该如何更新球的位置以不允许球彼此进入(相交)

    private void BallCollisionBlueRed()
    {
        double fDist;
        CentreAX = redBall.Left + ball.Width / 2;
        CentreAY = redBall.Top + ball.Height / 2;
        CentreBX = blueBall.Left + ball.Width / 2;
        CentreBY = blueBall.Top + ball.Height / 2;

        vDx = CentreBX - CentreAX;
        vDy = CentreBY - CentreAY;
        fDist = Math.Sqrt((vDx * vDx) + (vDy * vDy));

        if (fDist < radA + radB)
        {
           // Help!
        }
    }

vDx and vDy are only used to hold the value for the calculations. vDx和vDy仅用于保存计算值。 I am controlling both the balls with arrow keys(players), I don't want them to bounce off each other, but just not allow them to intersect. 我用箭头键(玩家)控制两个球,我不希望它们相互反弹,只是不允许它们相交。

You need to picture the interaction in your head. 您需要想象一下大脑中的交互。 When the distance is exactly zero the objects will bounce and start moving away from each other. 当距离恰好为零时,对象将反弹并开始彼此远离。

It's been too long since college to calculate the new trajectory BUT the main thing will be that, if radA + radB - fDist is, say -4, you'll need to set the new distance to radA + radB + 4. 自大学以来计算新轨迹已经很久了,但最主要的是,如果radA + radB-fDist为-4,则需要将新距离设置为radA + radB + 4。

That will accomodate for any low fps you have (until they lag so bad that they go THROUGH each other before you can detect the collision :-p 这将适用于您的任何低fps(直到它们滞后到如此之差以至于在您可以检测到碰撞之前它们会相互穿透:-p

对于此类物理学的一些好的建议,我会阅读以下博客文章: http : //www.wildbunny.co.uk/blog/2011/04/06/physics-engines-for-dummies/

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

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