How to do c# collision detection?

后端 未结 4 935
难免孤独
难免孤独 2021-01-06 18:08

Are there any predefined methods in c# which allow for collision detection?

I am new to c# and am trying to get collision detection of two ellipses are there any pre

4条回答
  •  囚心锁ツ
    2021-01-06 18:25

    Provided that your Ellipses are always circles (i.e. their Width and Height properties are set to the same value) and they always have the Canvas.Left and Canvas.Top properties set, the following helper method checks for a collision:

    public static bool CheckCollision(Ellipse e1, Ellipse e2)
    {
        var r1 = e1.ActualWidth / 2;
        var x1 = Canvas.GetLeft(e1) + r1;
        var y1 = Canvas.GetTop(e1) + r1;
        var r2 = e2.ActualWidth / 2;
        var x2 = Canvas.GetLeft(e2) + r2;
        var y2 = Canvas.GetTop(e2) + r2;
        var d = new Vector(x2 - x1, y2 - y1);
        return d.Length <= r1 + r2;
    }
    

提交回复
热议问题