困在xna中的圆形乒乓球中的碰撞检测

时间:2015-02-13 06:18:53

标签: c# xna

我正在xna中制作Circle pong游戏。我无法将旋转垫与球碰撞。我不能在这个游戏中使用更低级的物理,因为它是单声道游戏。

我找到了一种方法,但似乎也没有用。

    private void EllasticCollisionPhysics(Ball ball, GoScreen pad)
    {
        //find normal vector

        Vector2 normal = new Vector2(pad.padV.X - ball.ballRectangle.X, pad.padV.Y - ball.ballRectangle.Y);
        //find normal vector's modulus, i.e. length
        float normalmod = (float)Math.Sqrt(Math.Pow(normal.X, 2) + Math.Pow(normal.Y, 2));

        //find unitnormal vector
        Vector2 unitnormal = new Vector2((pad.padV.X - ball.ballRectangle.X) / normalmod, (pad.padV.Y - ball.ballRectangle.Y) / normalmod);

        //find tangent vector
        Vector2 unittan = new Vector2(-1 * unitnormal.Y, unitnormal.X);

        //first ball normal speed before collision
        float inormalspeedb = unitnormal.X * velocity.X + unitnormal.Y * velocity.Y;

        //first ball tangential speed 
        float itanspeed = unittan.X * velocity.X + unittan.Y * velocity.Y;


        //Calculate normal speeds after the collision



        //Calculate first ball Velocity vector components (tangential and normal)
        Vector2 inormala = new Vector2(unitnormal.X * inormalspeedb, unitnormal.Y * inormalspeedb);
        Vector2 itana = new Vector2(unittan.X * itanspeed, unittan.Y * itanspeed);

        //Add Vector components to each balls' Velocity
        velocity = Vector2.Add(inormala, itana);

1 个答案:

答案 0 :(得分:0)

你不需要那么精确的物理学,你需要的是圆形到矩形的碰撞功能。

// circle is object with x,y,r parameters
bool intersects(CircleType circle, RectType rect)
{
    circleDistance.x = abs(circle.x - rect.x);
    circleDistance.y = abs(circle.y - rect.y);

    if (circleDistance.x > (rect.width/2 + circle.r)) { return false; }
    if (circleDistance.y > (rect.height/2 + circle.r)) { return false; }

    if (circleDistance.x <= (rect.width/2)) { return true; } 
    if (circleDistance.y <= (rect.height/2)) { return true; }

    cornerDistance_sq = (circleDistance.x - rect.width/2)^2 +
                         (circleDistance.y - rect.height/2)^2;

    return (cornerDistance_sq <= (circle.r^2));
}

添加了CircleType和RectType

public class CircleType
{
    public int x;
    public int y;
    public decimal r;
}

public class RectType
{
    public int x;
    public int y;
    public int width;
    public int height;
}