internal void SetShape(Shape shape, CollisionShapeParameters parameters) { _shape = shape; Body.Shape = CreatePhysicsShape(shape, Size, parameters); }
/// <summary> /// Creates a shape to be used in the Physics Body. A physics shape is scaled to the /// size of the object. In addition, it has more vertices and some additional info /// that is used in collision detection. /// </summary> internal static IShape CreatePhysicsShape(Shape shape, Vector size, CollisionShapeParameters parameters) { if (shape is RaySegment) { RaySegment raySegment = (RaySegment)shape; Physics2DDotNet.Shapes.RaySegment singleSegment = new Physics2DDotNet.Shapes.RaySegment( new Vector2D(raySegment.Origin.X, raySegment.Origin.Y), new Vector2D(raySegment.Direction.X, raySegment.Direction.Y), raySegment.Length); return(new RaySegmentsShape(singleSegment)); } else if (shape is Ellipse) { Debug.Assert(shape.IsUnitSize); double smaller = Math.Min(size.X, size.Y); double bigger = Math.Max(size.X, size.Y); // Average between width and height. double r = smaller / 2 + (bigger - smaller) / 2; int vertexCount = (int)Math.Ceiling((2 * Math.PI * r) / parameters.MaxVertexDistance); if (Math.Abs(size.X - size.Y) <= double.Epsilon) { // We get more accurate results by using the circleshape. // in addition, the circleshape does not need a DistanceGrid // object (which is slow to initialize) because calculations // for a circleshape are much simpler. return(new CircleShape(r, vertexCount)); } else { Vector2D[] vertexes = new Vector2D[vertexCount]; double a = 0.5 * size.X; double b = 0.5 * size.Y; for (int i = 0; i < vertexCount; i++) { double t = (i * 2 * Math.PI) / vertexCount; double x = a * Math.Cos(t); double y = b * Math.Sin(t); vertexes[i] = new Vector2D(x, y); } return(new PolygonShape(vertexes, parameters.DistanceGridSpacing)); } } else { Vector2D[] originalVertexes = new Vector2D[shape.Cache.OutlineVertices.Length]; for (int i = 0; i < shape.Cache.OutlineVertices.Length; i++) { Vector v = shape.Cache.OutlineVertices[i]; if (shape.IsUnitSize) { v.X *= size.X; v.Y *= size.Y; } originalVertexes[i] = new Vector2D(v.X, v.Y); } Vector2D[] polyVertexes = VertexHelper.Subdivide(originalVertexes, parameters.MaxVertexDistance); return(new PolygonShape(polyVertexes, parameters.DistanceGridSpacing)); } }
public PhysicsBody(double width, double height, Shape shape, CollisionShapeParameters shapeParameters) : this(width, height, shape, CreatePhysicsShape(shape, new Vector(width, height), shapeParameters)) { }