Inheritance: MonoBehaviour
        /// <summary>
        /// Constructs a new demo.
        /// </summary>
        /// <param name="game">Game owning this demo.</param>
        public RayCastTestDemo(DemosGame game)
            : base(game)
        {
            Space.Add(new Box(new Vector3(0, -0.5f, 0), 50, 1, 50));

            //Put whatever you'd like to ray cast here.
            var capsule = new Capsule(new Vector3(0, 1.2f, 0), 1, 0.6f);
            capsule.AngularVelocity = new Vector3(1, 1, 1);
            Space.Add(capsule);

            var cylinder = new Cylinder(new Vector3(0, 5, 0), 2, .5f);
            cylinder.AngularVelocity = new Vector3(1, -1, 1);
            Space.Add(cylinder);

            var points = new List<Vector3>();

            var random = new Random(0);
            for (int k = 0; k < 40; k++)
            {
                points.Add(new Vector3(1 * (float)random.NextDouble(), 3 * (float)random.NextDouble(), 2 * (float)random.NextDouble()));
            }
            var convexHull = new ConvexHull(new Vector3(0, 10, 0), points);
            convexHull.AngularVelocity = new Vector3(-1, 1, 1);
            Space.Add(convexHull);


            game.Camera.Position = new Vector3(-10, 5, 10);
            game.Camera.Yaw((float)Math.PI / -4f);
            game.Camera.Pitch(-(float)Math.PI / 9f);

            //Starter ray.
            origin = new Vector3(10, 5, 0);
            direction = new Vector3(-3, -1, 0);

        }
 public CharacterAge(CharacterAgeState _stateName, BoneAnimation _boneAnimation, Transform _sectionTarget, Capsule _capsule)
 {
     stateName = _stateName;
     boneAnimation = _boneAnimation;
     sectionTarget = _sectionTarget;
     capsule = _capsule;
 }
 public CapsuleObject(Vector3 pos, float height, float radius, float mass,Matrix? orientation,MaterialDescription md = null)
     : base(md,mass)
 {
     if (!orientation.HasValue)
         orientation = Matrix.Identity;
     
     entity = new Capsule(pos, height, radius, mass);
     entity.Orientation = Quaternion.CreateFromRotationMatrix(orientation.Value);            
 }
示例#4
0
 /// <summary>
 /// Create capsule model physics.
 /// </summary>
 /// <param name="game">The game.</param>
 /// <param name="model">The visual model.</param>
 /// <param name="position">The position of the sphere entity.</param>
 /// <param name="mass">The physics mass.</param>
 public CapsuleModelPhysics(XiGame game, Model model, Vector3 position, float mass)
 {
     this.game = game;
     Vector3[] vertices;
     int[] indices;
     model.GetVerticesAndIndices(out vertices, out indices);
     BoundingSphere boundingSphere = BoundingSphere.CreateFromPoints(vertices);
     body = new Capsule(position, boundingSphere.Radius, boundingSphere.Radius * 0.5f, mass);
     game.SceneSpace.Add(body);
 }
        /// <summary>
        /// Create a car Actor which can interface with the BEPU physics engine
        /// </summary>
        /// <param name="position"></param>
        /// <param name="orientation"></param>
        public BepuCarActor(Game game, CarModelRenderer renderer, Matrix worldMatrix)
            : base(game, renderer)
        {
            emitter_ = new AudioEmitter();
            CarSoundEmitters.AudioEmitters.Add(emitter_);

            // create a pin (for keeping the car stuck to the track)
            Capsule pin = new Capsule(new Vector3(0, -0.7f, -2), 0.6f, 0.12f, 1);
            pin.Bounciness = 0f;
            pin.DynamicFriction = 0f;
            pin.StaticFriction = 0f;

            // create a body:
            CompoundBody body = new CompoundBody();
            body.AddBody(new Box(new Vector3(0, 0, 0), 2.5f, .75f, 4.5f, 60));
            body.AddBody(new Box(new Vector3(0, .75f / 2 + .3f / 2, .5f), 2.5f, .3f, 2f, 1));
            body.AddBody(pin);
            body.CenterOfMassOffset = new Vector3(0, -.5f, 0);

            body.WorldTransform = worldMatrix;
            body.LinearVelocity = Vector3.Zero;
            body.AngularVelocity = Vector3.Zero;
            // construct the car:
            car = new Vehicle(body);

            // attach wheels:
            Matrix wheelGraphicRotation = Matrix.CreateFromAxisAngle(Vector3.Forward, MathHelper.PiOver2);
            for (int i = 0; i < 4; i++)
            {
                Wheel wheel = new Wheel(
                                 new RaycastWheelShape(.375f, wheelGraphicRotation),
                                 new WheelSuspension(2000, 100f, Vector3.Down, .8f,
                                     new Vector3(
                                         ( i <= 1 ) ? -1.1f : 1.1f,
                                         0,
                                         ( (i & 1) == 0 ) ? 1.8f : - 1.8f)),
                                 new WheelDrivingMotor(2.5f, 30000, 10000),
                                 new WheelBrake(1.5f, 2, .02f),
                                 new WheelSlidingFriction(4, 5));

                car.AddWheel(wheel);

                // adjust additional values
                wheel.Shape.FreezeWheelsWhileBraking = true;
                wheel.Suspension.SolverSettings.MaximumIterations = 2;
                wheel.Brake.SolverSettings.MaximumIterations = 2;
                wheel.SlidingFriction.SolverSettings.MaximumIterations = 2;
                wheel.DrivingMotor.SolverSettings.MaximumIterations = 2;

            }

            // add it to physics
            Engine.currentWorld.Space.Add(car);
        }
示例#6
0
		public void LinearCapsuleSweep()
		{
			using( CreateCoreAndScene() )
			{
				CreateBoxActor( 0, 0, 20 );

				Capsule capsule = new Capsule( new Vector3( 0, -5, 0 ), new Vector3( 0, 5, 0 ), 10 );

				var sweepHits = this.Scene.LinearCapsuleSweep( capsule, new Vector3( 0, 0, 1000 ), SweepFlags.Dynamics | SweepFlags.Statics, "Dummy Object" );

				Assert.IsTrue( sweepHits.Length == 1, "The linear capsule sweep should of returned 1 hit. Hits returned: {0}", sweepHits.Length );
			}
		}
 public CharacterControllerConvexCast()
 {
     Body = new Capsule(Vector3.Zero, 1.7f, .3f, 10);
     //Making the character a continuous object prevents it from flying through walls which would be pretty jarring from a player's perspective.
     Body.PositionUpdateMode = PositionUpdateMode.Continuous;
     Body.LocalInertiaTensorInverse = new Matrix3X3();
     Body.CollisionInformation.Events.CreatingPair += RemoveFriction;
     GlueSpeed = 20;
     StepHeight = 1;
     //construct the casting shape.  It should be a little smaller than the character's radius.
     castShape = new CylinderShape(0, Body.Radius * .8f);
     castShape.CollisionMargin = 0;
 }
        /// <summary>
        /// Constructs a new demo.
        /// </summary>
        /// <param name="game">Game owning this demo.</param>
        public PersistentManifoldStressTestDemo(DemosGame game)
            : base(game)
        {
            var ground = new Box(new Vector3(0, -.5f, 0), 200, 1, 200);
            Space.Add(ground);



            var spawnVolume = new BoundingBox
                {
                    Min = new Vector3(-25, 2, -25),
                    Max = new Vector3(25, 102, 25)
                };

            var span = spawnVolume.Max - spawnVolume.Min;

            NarrowPhaseHelper.Factories.ConvexConvex.EnsureCount(30000);

            var random = new Random(5);
            for (int i = 0; i < 5000; ++i)
            {
                Vector3 position;
                position.X = spawnVolume.Min.X + (float)random.NextDouble() * span.X;
                position.Y = spawnVolume.Min.Y + (float)random.NextDouble() * span.Y;
                position.Z = spawnVolume.Min.Z + (float)random.NextDouble() * span.Z;

                var entity = new Capsule(position, 2, 0.8f, 10);
                Space.Add(entity);
            }

            for (int i = 0; i < 60; ++i)
            {
                Space.Update();
            }

            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;
            
            var start = Stopwatch.GetTimestamp();
            for (int i = 0; i < 1000; ++i)
            {
                Space.Update();
            }
            var end = Stopwatch.GetTimestamp();
            var time = (end - start) / (double)Stopwatch.Frequency;

            Console.WriteLine("Time: {0}", time);
 
            game.Camera.Position = new Vector3(-10, 10, 10);
            game.Camera.Yaw((float)Math.PI / -4f);
            game.Camera.Pitch((float)Math.PI / 9f);
        }
示例#9
0
        public CarDemo()
        {
            int alpha = 255;
            int colA = Color.FromArgb(alpha, 51, 58, 51).ToArgb();
            int colB = Color.FromArgb(alpha, 51, 102, 170).ToArgb();
            int colC = Color.FromArgb(alpha, 170, 187, 187).ToArgb();
            int colD = Color.FromArgb(alpha, 102, 153, 170).ToArgb();
            int colE = Color.FromArgb(alpha, 119, 136, 119).ToArgb();
            int colPad = Color.FromArgb(alpha, 153, 102, 51).ToArgb();

            APEngine.init((float) 1 / 4);

            Vector massLessForces = new Vector(0, 3);
            APEngine.addMasslessForce(massLessForces);

            Surfaces surfaces = new Surfaces(colA, colB, colC, colD, colE, colPad);
            APEngine.addGroup(surfaces);

            Bridge bridge = new Bridge(colB, colC, colD);
            APEngine.addGroup(bridge);

            Capsule capsule = new Capsule(colC);
            APEngine.addGroup(capsule);

            rotator = new Rotator(colB, colE);
            APEngine.addGroup(rotator);

            SwingDoor swingDoor = new SwingDoor(colC);
            APEngine.addGroup(swingDoor);

            car = new Car(colC, colE);
            APEngine.addGroup(car);

            car.addCollidable(surfaces);
            car.addCollidable(bridge);
            car.addCollidable(rotator);
            car.addCollidable(swingDoor);
            car.addCollidable(capsule);

            capsule.addCollidable(surfaces);
            capsule.addCollidable(bridge);
            capsule.addCollidable(rotator);
            capsule.addCollidable(swingDoor);
        }
示例#10
0
 /// <summary>Checks if the provided capsule overlaps any other collider in the scene.</summary>
 /// <param name="capsule">Capsule to check for overlap.</param>
 /// <param name="rotation">Orientation of the capsule.</param>
 /// <param name="layer">Layers to consider for the query. This allows you to ignore certain groups of objects.</param>
 /// <returns>True if there is overlap with another object, false otherwise.</returns>
 public static bool CapsuleOverlapAny(Capsule capsule, Quaternion rotation, ulong layer = 18446744073709551615)
 {
     return(Internal_capsuleOverlapAny(ref capsule, ref rotation, layer));
 }
示例#11
0
        /// <summary>
        ///     Detectar colision entre un Ray y una Capsula
        ///     Basado en: http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrLine3Capsule3.cpp
        /// </summary>
        /// <param name="ray">Ray</param>
        /// <param name="capsule">Capsula</param>
        /// <param name="t">Menor instante de colision</param>
        /// <returns>True si hay colision</returns>
        private bool intersectRayCapsule(TgcRay.RayStruct ray, Capsule capsule, out float t)
        {
            t = -1;
            var origin = ray.origin;
            var dir    = ray.direction;

            // Create a coordinate system for the capsule.  In this system, the
            // capsule segment center C is the origin and the capsule axis direction
            // W is the z-axis.  U and V are the other coordinate axis directions.
            // If P = x*U+y*V+z*W, the cylinder containing the capsule wall is
            // x^2 + y^2 = r^2, where r is the capsule radius.  The finite cylinder
            // that makes up the capsule minus its hemispherical end caps has z-values
            // |z| <= e, where e is the extent of the capsule segment.  The top
            // hemisphere cap is x^2+y^2+(z-e)^2 = r^2 for z >= e, and the bottom
            // hemisphere cap is x^2+y^2+(z+e)^2 = r^2 for z <= -e.
            var U = capsule.segment.dir;
            var V = U;
            var W = U;

            generateComplementBasis(ref U, ref V, W);
            var rSqr   = capsule.radius * capsule.radius;
            var extent = capsule.segment.extent;

            // Convert incoming line origin to capsule coordinates.
            var diff = origin - capsule.segment.center;
            var P    = new Vector3(Vector3.Dot(U, diff), Vector3.Dot(V, diff), Vector3.Dot(W, diff));

            // Get the z-value, in capsule coordinates, of the incoming line's unit-length direction.
            var dz = Vector3.Dot(W, dir);

            if (FastMath.Abs(dz) >= 1f - float.Epsilon)
            {
                // The line is parallel to the capsule axis.  Determine whether the line intersects the capsule hemispheres.
                var radialSqrDist = rSqr - P.X * P.X - P.Y * P.Y;
                if (radialSqrDist < 0f)
                {
                    // Line outside the cylinder of the capsule, no intersection.
                    return(false);
                }

                // line intersects the hemispherical caps
                var zOffset = FastMath.Sqrt(radialSqrDist) + extent;
                if (dz > 0f)
                {
                    t = -P.Z - zOffset;
                }
                else
                {
                    t = P.Z - zOffset;
                }
                return(true);
            }

            // Convert incoming line unit-length direction to capsule coordinates.
            var D = new Vector3(Vector3.Dot(U, dir), Vector3.Dot(V, dir), dz);

            // Test intersection of line P+t*D with infinite cylinder x^2+y^2 = r^2.
            // This reduces to computing the roots of a quadratic equation.  If
            // P = (px,py,pz) and D = (dx,dy,dz), then the quadratic equation is
            //   (dx^2+dy^2)*t^2 + 2*(px*dx+py*dy)*t + (px^2+py^2-r^2) = 0
            var a0    = P.X * P.X + P.Y * P.Y - rSqr;
            var a1    = P.X * D.X + P.Y * D.Y;
            var a2    = D.X * D.X + D.Y * D.Y;
            var discr = a1 * a1 - a0 * a2;

            if (discr < 0f)
            {
                // Line does not intersect infinite cylinder.
                return(false);
            }

            float root, inv, tValue, zValue;
            var   quantity = 0;

            if (discr > float.Epsilon)
            {
                // Line intersects infinite cylinder in two places.
                root   = FastMath.Sqrt(discr);
                inv    = 1f / a2;
                tValue = (-a1 - root) * inv;
                zValue = P.Z + tValue * D.Z;
                if (FastMath.Abs(zValue) <= extent)
                {
                    quantity++;
                    t = tValue;
                }

                tValue = (-a1 + root) * inv;
                zValue = P.Z + tValue * D.Z;
                if (FastMath.Abs(zValue) <= extent)
                {
                    quantity++;
                    t = TgcCollisionUtils.min(t, tValue);
                }

                if (quantity == 2)
                {
                    // Line intersects capsule wall in two places.
                    return(true);
                }
            }
            else
            {
                // Line is tangent to infinite cylinder.
                tValue = -a1 / a2;
                zValue = P.Z + tValue * D.Z;
                if (FastMath.Abs(zValue) <= extent)
                {
                    t = tValue;
                    return(true);
                }
            }

            // Test intersection with bottom hemisphere.  The quadratic equation is
            // t^2 + 2*(px*dx+py*dy+(pz+e)*dz)*t + (px^2+py^2+(pz+e)^2-r^2) = 0
            // Use the fact that currently a1 = px*dx+py*dy and a0 = px^2+py^2-r^2.
            // The leading coefficient is a2 = 1, so no need to include in the
            // construction.
            var PZpE = P.Z + extent;

            a1   += PZpE * D.Z;
            a0   += PZpE * PZpE;
            discr = a1 * a1 - a0;
            if (discr > float.Epsilon)
            {
                root   = FastMath.Sqrt(discr);
                tValue = -a1 - root;
                zValue = P.Z + tValue * D.Z;
                if (zValue <= -extent)
                {
                    quantity++;
                    t = TgcCollisionUtils.min(t, tValue);
                    if (quantity == 2)
                    {
                        return(true);
                    }
                }

                tValue = -a1 + root;
                zValue = P.Z + tValue * D.Z;
                if (zValue <= -extent)
                {
                    quantity++;
                    t = TgcCollisionUtils.min(t, tValue);
                    if (quantity == 2)
                    {
                        return(true);
                    }
                }
            }
            else if (FastMath.Abs(discr) <= float.Epsilon)
            {
                tValue = -a1;
                zValue = P.Z + tValue * D.Z;
                if (zValue <= -extent)
                {
                    quantity++;
                    t = TgcCollisionUtils.min(t, tValue);
                    if (quantity == 2)
                    {
                        return(true);
                    }
                }
            }

            // Test intersection with top hemisphere.  The quadratic equation is
            // t^2 + 2*(px*dx+py*dy+(pz-e)*dz)*t + (px^2+py^2+(pz-e)^2-r^2) = 0
            // Use the fact that currently a1 = px*dx+py*dy+(pz+e)*dz and
            // a0 = px^2+py^2+(pz+e)^2-r^2.  The leading coefficient is a2 = 1, so
            // no need to include in the construction.
            a1   -= 2f * extent * D.Z;
            a0   -= 4 * extent * P.Z;
            discr = a1 * a1 - a0;
            if (discr > float.Epsilon)
            {
                root   = FastMath.Sqrt(discr);
                tValue = -a1 - root;
                zValue = P.Z + tValue * D.Z;
                if (zValue >= extent)
                {
                    quantity++;
                    t = TgcCollisionUtils.min(t, tValue);
                    if (quantity == 2)
                    {
                        return(true);
                    }
                }

                tValue = -a1 + root;
                zValue = P.Z + tValue * D.Z;
                if (zValue >= extent)
                {
                    quantity++;
                    t = TgcCollisionUtils.min(t, tValue);
                    if (quantity == 2)
                    {
                        return(true);
                    }
                }
            }
            else if (FastMath.Abs(discr) <= float.Epsilon)
            {
                tValue = -a1;
                zValue = P.Z + tValue * D.Z;
                if (zValue >= extent)
                {
                    quantity++;
                    t = TgcCollisionUtils.min(t, tValue);
                    if (quantity == 2)
                    {
                        return(true);
                    }
                }
            }

            return(quantity > 0);
        }
示例#12
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-13f, 6, -13f);
            camera.Yaw      = MathHelper.Pi * 3f / 4;
            camera.Pitch    = MathHelper.Pi * 0.05f;

            //The PositionFirstTimestepper is the simplest timestepping mode, but since it integrates velocity into position at the start of the frame, directly modified velocities outside of the timestep
            //will be integrated before collision detection or the solver has a chance to intervene. That's fine in this demo. Other built-in options include the PositionLastTimestepper and the SubsteppingTimestepper.
            //Note that the timestepper also has callbacks that you can use for executing logic between processing stages, like BeforeCollisionDetection.
            Simulation = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10f, 0)), new PositionFirstTimestepper());

            using (var compoundBuilder = new CompoundBuilder(BufferPool, Simulation.Shapes, 8))
            {
                {
                    //Note that, in bepuphysics v2, there is no 'recentering' when constructing a shape. The pose you pass in for a child is exactly the pose that the compound will use,
                    //even if the 'true' center of mass isn't at the local origin.
                    //Instead, if recentering is desired, it should performed ahead of time. The CompoundBuilder can help with this.
                    //We'll construct this compound using shapes far from the origin, and then use the CompoundBuilder overload that recenters the children and outputs the computed center.
                    var capsuleChildShape = new Capsule(0.5f, 0.5f);
                    var capsuleLocalPose  = new RigidPose {
                        Position = new Vector3(-0.5f, 4, 4), Orientation = Quaternion.Identity
                    };
                    var boxChildShape = new Box(0.5f, 1f, 1.5f);
                    var boxLocalPose  = new RigidPose {
                        Position = new Vector3(0.5f, 4, 4), Orientation = Quaternion.Identity
                    };

                    //All allocations from the buffer pool used for the final compound shape will be disposed when the demo is disposed. Don't have to worry about leaks in these demos.
                    compoundBuilder.Add(capsuleChildShape, capsuleLocalPose, 1);
                    compoundBuilder.Add(boxChildShape, boxLocalPose, 1);
                    compoundBuilder.BuildDynamicCompound(out var compoundChildren, out var compoundInertia, out var compoundCenter);
                    compoundBuilder.Reset();
                    Simulation.Bodies.Add(BodyDescription.CreateDynamic(compoundCenter, compoundInertia, new CollidableDescription(Simulation.Shapes.Add(new Compound(compoundChildren)), 0.1f), new BodyActivityDescription(0.01f)));
                }

                //Build a stack of sphere grids to stress manifold reduction heuristics in a convex-ish situation.
                {
                    var         gridShape      = new Sphere(0.5f);
                    const float gridSpacing    = 1.5f;
                    const int   gridWidth      = 3;
                    var         gridShapeIndex = Simulation.Shapes.Add(gridShape);
                    gridShape.ComputeInertia(1, out var gridBoxInertia);
                    float localPoseOffset = -0.5f * gridSpacing * (gridWidth - 1);
                    for (int i = 0; i < gridWidth; ++i)
                    {
                        for (int j = 0; j < gridWidth; ++j)
                        {
                            compoundBuilder.Add(gridShapeIndex, new RigidPose(new Vector3(localPoseOffset, 0, localPoseOffset) + new Vector3(gridSpacing) * new Vector3(i, 0, j)), gridBoxInertia.InverseInertiaTensor, 1);
                        }
                    }
                    compoundBuilder.BuildDynamicCompound(out var gridChildren, out var gridInertia, out var center);
                    compoundBuilder.Reset();
                    var gridCompound    = new Compound(gridChildren);
                    var bodyDescription = BodyDescription.CreateDynamic(RigidPose.Identity, gridInertia, new CollidableDescription(Simulation.Shapes.Add(gridCompound), 0.1f), new BodyActivityDescription(0.01f));
                    for (int i = 0; i < 4; ++i)
                    {
                        bodyDescription.Pose.Position = new Vector3(0, 2 + i * 3, 0);
                        Simulation.Bodies.Add(bodyDescription);
                    }
                }

                //Build a table and use it for a couple of different tests.
                {
                    var legShape = new Box(0.2f, 1, 0.2f);
                    legShape.ComputeInertia(1f, out var legInverseInertia);
                    var legShapeIndex = Simulation.Shapes.Add(legShape);
                    var legPose0      = new RigidPose {
                        Position = new Vector3(-1.5f, 0, -1.5f), Orientation = Quaternion.Identity
                    };
                    var legPose1 = new RigidPose {
                        Position = new Vector3(-1.5f, 0, 1.5f), Orientation = Quaternion.Identity
                    };
                    var legPose2 = new RigidPose {
                        Position = new Vector3(1.5f, 0, -1.5f), Orientation = Quaternion.Identity
                    };
                    var legPose3 = new RigidPose {
                        Position = new Vector3(1.5f, 0, 1.5f), Orientation = Quaternion.Identity
                    };
                    compoundBuilder.Add(legShapeIndex, legPose0, legInverseInertia.InverseInertiaTensor, 1);
                    compoundBuilder.Add(legShapeIndex, legPose1, legInverseInertia.InverseInertiaTensor, 1);
                    compoundBuilder.Add(legShapeIndex, legPose2, legInverseInertia.InverseInertiaTensor, 1);
                    compoundBuilder.Add(legShapeIndex, legPose3, legInverseInertia.InverseInertiaTensor, 1);
                    var tableTopPose = new RigidPose {
                        Position = new Vector3(0, 0.6f, 0), Orientation = Quaternion.Identity
                    };
                    var tableTopShape = new Box(3.2f, 0.2f, 3.2f);
                    compoundBuilder.Add(tableTopShape, tableTopPose, 3);

                    compoundBuilder.BuildDynamicCompound(out var tableChildren, out var tableInertia, out var tableCenter);
                    compoundBuilder.Reset();
                    var table            = new Compound(tableChildren);
                    var tableDescription = new BodyDescription
                    {
                        Activity = new BodyActivityDescription {
                            SleepThreshold = 0.01f, MinimumTimestepCountUnderThreshold = 32
                        },
                        Collidable = new CollidableDescription
                        {
                            Shape             = Simulation.Shapes.Add(table),
                            SpeculativeMargin = 0.1f,
                        },
                        LocalInertia = tableInertia,
                        Pose         = new RigidPose {
                            Orientation = Quaternion.Identity
                        }
                    };

                    //Stack some tables.
                    {
                        for (int i = 0; i < 10; ++i)
                        {
                            tableDescription.Pose.Position = new Vector3(10, 3 + i * 1.4f, 10);
                            Simulation.Bodies.Add(tableDescription);
                        }
                    }
                    {
                        for (int k = 0; k < 5; ++k)
                        {
                            tableDescription.Pose.Position = new Vector3(64 + k * 3, 6 + k * 1.4f, 32);
                            Simulation.Bodies.Add(tableDescription);
                        }
                        //for (int i = 0; i < 10; ++i)
                        //{
                        //    for (int j = 0; j < 20; ++j)
                        //    {
                        //        for (int k = 0; k < 10; ++k)
                        //        {
                        //            tableDescription.Pose.Position = new Vector3(32 + i * 6, 6 + j * 1.4f, 16 + k * 6);
                        //            Simulation.Bodies.Add(tableDescription);
                        //        }
                        //    }
                        //}
                    }

                    //Put a table on top of a sphere to stress out nonconvex reduction for divergent normals.
                    {
                        tableDescription.Pose.Position = new Vector3(10, 6, 0);
                        Simulation.Bodies.Add(tableDescription);

                        var sphereShape       = new Sphere(3);
                        var sphereIndex       = Simulation.Shapes.Add(sphereShape);
                        var sphereDescription = new StaticDescription
                        {
                            Collidable = new CollidableDescription
                            {
                                Shape             = sphereIndex,
                                SpeculativeMargin = 0.1f,
                            },
                            Pose = new RigidPose {
                                Position = new Vector3(10, 2, 0), Orientation = Quaternion.Identity
                            }
                        };
                        Simulation.Statics.Add(sphereDescription);
                    }

                    //Put another table on the ground, but with a clamp-ish thing on it that generates opposing normals.
                    {
                        tableDescription.Pose.Position = new Vector3(10, 3, -10);
                        Simulation.Bodies.Add(tableDescription);

                        var clampPieceShape = new Box(2f, 0.1f, 0.3f);
                        clampPieceShape.ComputeInertia(1f, out var clampPieceInverseInertia);
                        var clampPieceShapeIndex = Simulation.Shapes.Add(clampPieceShape);
                        var clamp0 = new RigidPose {
                            Position = new Vector3(0, -0.2f, -1.1f), Orientation = Quaternion.Identity
                        };
                        var clamp1 = new RigidPose {
                            Position = new Vector3(0, 0.2f, -1.1f), Orientation = Quaternion.Identity
                        };
                        var clamp2 = new RigidPose {
                            Position = new Vector3(0, -0.2f, 0), Orientation = Quaternion.Identity
                        };
                        var clamp3 = new RigidPose {
                            Position = new Vector3(0, 0.2f, 0), Orientation = Quaternion.Identity
                        };
                        var clamp4 = new RigidPose {
                            Position = new Vector3(0, -0.2f, 1.1f), Orientation = Quaternion.Identity
                        };
                        var clamp5 = new RigidPose {
                            Position = new Vector3(0, 0.2f, 1.1f), Orientation = Quaternion.Identity
                        };
                        compoundBuilder.Add(clampPieceShapeIndex, clamp0, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp1, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp2, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp3, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp4, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp5, clampPieceInverseInertia.InverseInertiaTensor, 1);

                        compoundBuilder.BuildDynamicCompound(out var clampChildren, out var clampInertia, out var clampCenter);
                        compoundBuilder.Reset();
                        var clamp            = new Compound(clampChildren);
                        var clampDescription = new BodyDescription
                        {
                            Activity = new BodyActivityDescription {
                                SleepThreshold = 0.01f, MinimumTimestepCountUnderThreshold = 32
                            },
                            Collidable = new CollidableDescription
                            {
                                Shape             = Simulation.Shapes.Add(clamp),
                                SpeculativeMargin = 0.1f,
                            },
                            LocalInertia = clampInertia,
                            Pose         = new RigidPose {
                                Position = tableDescription.Pose.Position + new Vector3(2f, 0.3f, 0), Orientation = Quaternion.Identity
                            }
                        };
                        Simulation.Bodies.Add(clampDescription);
                    }
                }

                //Create a tree-accelerated big compound.
                {
                    var random = new Random(5);
                    var treeCompoundBoxShape      = new Box(0.5f, 1.5f, 1f);
                    var treeCompoundBoxShapeIndex = Simulation.Shapes.Add(treeCompoundBoxShape);
                    treeCompoundBoxShape.ComputeInertia(1, out var childInertia);
                    for (int i = 0; i < 128; ++i)
                    {
                        RigidPose localPose;
                        localPose.Position = new Vector3(12, 6, 12) * (0.5f * new Vector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()) - Vector3.One);
                        float orientationLengthSquared;
                        do
                        {
                            localPose.Orientation    = new Quaternion((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble());
                            orientationLengthSquared = QuaternionEx.LengthSquared(ref localPose.Orientation);
                        }while (orientationLengthSquared < 1e-9f);
                        QuaternionEx.Scale(localPose.Orientation, 1f / MathF.Sqrt(orientationLengthSquared), out localPose.Orientation);
                        //Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), MathF.PI, out localPose.Orientation);

                        compoundBuilder.Add(treeCompoundBoxShapeIndex, localPose, childInertia.InverseInertiaTensor, 1);
                    }
                    compoundBuilder.BuildDynamicCompound(out var children, out var inertia, out var center);
                    compoundBuilder.Reset();

                    var compound = new BigCompound(children, Simulation.Shapes, BufferPool);
                    //var compound = new Compound(children);
                    var compoundIndex = Simulation.Shapes.Add(compound);
                    for (int i = 0; i < 8; ++i)
                    {
                        Simulation.Bodies.Add(BodyDescription.CreateDynamic(new Vector3(0, 4 + 5 * i, 32), inertia, new CollidableDescription(compoundIndex, 0.1f), new BodyActivityDescription(0.01f)));
                    }
                }
            }

            //Prevent stuff from falling into the infinite void.
            {
                var boxShape          = new Box(256, 1, 256);
                var groundShapeIndex  = Simulation.Shapes.Add(boxShape);
                var groundDescription = new StaticDescription
                {
                    Collidable = new CollidableDescription
                    {
                        Shape             = groundShapeIndex,
                        SpeculativeMargin = 0.1f,
                    },
                    Pose = new RigidPose {
                        Position = new Vector3(0, 0, 0), Orientation = Quaternion.Identity
                    }
                };
                Simulation.Statics.Add(groundDescription);
            }
            const int planeWidth  = 48;
            const int planeHeight = 48;

            DemoMeshHelper.CreateDeformedPlane(planeWidth, planeHeight,
                                               (int x, int y) =>
            {
                Vector2 offsetFromCenter = new Vector2(x - planeWidth / 2, y - planeHeight / 2);
                return(new Vector3(offsetFromCenter.X, MathF.Cos(x / 4f) * MathF.Sin(y / 4f) - 0.01f * offsetFromCenter.LengthSquared(), offsetFromCenter.Y));
            }, new Vector3(2, 1, 2), BufferPool, out var planeMesh);
            Simulation.Statics.Add(new StaticDescription(new Vector3(64, 4, 32), QuaternionEx.CreateFromAxisAngle(new Vector3(0, 1, 0), MathF.PI / 2),
                                                         new CollidableDescription(Simulation.Shapes.Add(planeMesh), 0.1f)));
        }
示例#13
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-13f, 6, -13f);
            camera.Yaw      = MathHelper.Pi * 3f / 4;
            camera.Pitch    = MathHelper.Pi * 0.05f;
            Simulation      = Simulation.Create(BufferPool, new TestCallbacks());
            Simulation.PoseIntegrator.Gravity = new Vector3(0, -10, 0);

            using (var compoundBuilder = new CompoundBuilder(BufferPool, Simulation.Shapes, 8))
            {
                {
                    //Note that, in bepuphysics v2, there is no 'recentering' when constructing a shape. The pose you pass in for a child is exactly the pose that the compound will use,
                    //even if the 'true' center of mass isn't at the local origin.
                    //Instead, if recentering is desired, it should performed ahead of time. The CompoundBuilder can help with this.
                    //We'll construct this compound using shapes far from the origin, and then use the CompoundBuilder overload that recenters the children and outputs the computed center.
                    var capsuleChildShape = new Capsule(0.5f, 0.5f);
                    var capsuleLocalPose  = new RigidPose {
                        Position = new Vector3(-0.5f, 4, 4), Orientation = BepuUtilities.Quaternion.Identity
                    };
                    var boxChildShape = new Box(0.5f, 1f, 1.5f);
                    var boxLocalPose  = new RigidPose {
                        Position = new Vector3(0.5f, 4, 4), Orientation = BepuUtilities.Quaternion.Identity
                    };

                    //All allocations from the buffer pool used for the final compound shape will be disposed when the demo is disposed. Don't have to worry about leaks in these demos.
                    compoundBuilder.Add(capsuleChildShape, capsuleLocalPose, 1);
                    compoundBuilder.Add(boxChildShape, boxLocalPose, 1);
                    compoundBuilder.BuildDynamicCompound(out var compoundChildren, out var compoundInertia, out var compoundCenter);
                    compoundBuilder.Reset();
                    var compound            = new Compound(compoundChildren);
                    var compoundDescription = new BodyDescription
                    {
                        Activity = new BodyActivityDescription {
                            SleepThreshold = 0.01f, MinimumTimestepCountUnderThreshold = 32
                        },
                        Collidable = new CollidableDescription
                        {
                            Shape             = Simulation.Shapes.Add(compound),
                            SpeculativeMargin = 0.1f,
                        },
                        LocalInertia = compoundInertia,
                        Pose         = new RigidPose {
                            Position = compoundCenter, Orientation = BepuUtilities.Quaternion.Identity
                        },
                    };

                    Simulation.Bodies.Add(compoundDescription);
                }

                //Build a stack of sphere grids to stress manifold reduction heuristics in a convex-ish situation.
                {
                    var         gridShape      = new Sphere(0.5f);
                    const float gridSpacing    = 1.5f;
                    const int   gridWidth      = 3;
                    var         gridShapeIndex = Simulation.Shapes.Add(gridShape);
                    gridShape.ComputeInertia(1, out var gridBoxInertia);
                    float localPoseOffset = -0.5f * gridSpacing * (gridWidth - 1);
                    for (int i = 0; i < gridWidth; ++i)
                    {
                        for (int j = 0; j < gridWidth; ++j)
                        {
                            var localPose = new RigidPose
                            {
                                Orientation = BepuUtilities.Quaternion.Identity,
                                Position    = new Vector3(localPoseOffset, 0, localPoseOffset) + new Vector3(gridSpacing) * new Vector3(i, 0, j)
                            };
                            compoundBuilder.Add(gridShapeIndex, localPose, gridBoxInertia.InverseInertiaTensor, 1);
                        }
                    }
                    compoundBuilder.BuildDynamicCompound(out var gridChildren, out var gridInertia, out var center);
                    compoundBuilder.Reset();
                    var gridCompound    = new Compound(gridChildren);
                    var bodyDescription = new BodyDescription
                    {
                        Activity = new BodyActivityDescription {
                            SleepThreshold = 0.01f, MinimumTimestepCountUnderThreshold = 32
                        },
                        Collidable = new CollidableDescription
                        {
                            Shape             = Simulation.Shapes.Add(gridCompound),
                            SpeculativeMargin = 0.1f,
                        },
                        LocalInertia = gridInertia,
                        Pose         = new RigidPose {
                            Orientation = BepuUtilities.Quaternion.Identity
                        }
                    };

                    for (int i = 0; i < 4; ++i)
                    {
                        bodyDescription.Pose.Position = new Vector3(0, 2 + i * 3, 0);
                        //if (i == 0)
                        //    gridDescription.LocalInertia = new BodyInertia();
                        //else
                        //    gridDescription.LocalInertia = gridInertia;
                        Simulation.Bodies.Add(bodyDescription);
                    }
                }

                //Build a table and use it for a couple of different tests.
                {
                    var legShape = new Box(0.2f, 1, 0.2f);
                    legShape.ComputeInertia(1f, out var legInverseInertia);
                    var legShapeIndex = Simulation.Shapes.Add(legShape);
                    var legPose0      = new RigidPose {
                        Position = new Vector3(-1.5f, 0, -1.5f), Orientation = BepuUtilities.Quaternion.Identity
                    };
                    var legPose1 = new RigidPose {
                        Position = new Vector3(-1.5f, 0, 1.5f), Orientation = BepuUtilities.Quaternion.Identity
                    };
                    var legPose2 = new RigidPose {
                        Position = new Vector3(1.5f, 0, -1.5f), Orientation = BepuUtilities.Quaternion.Identity
                    };
                    var legPose3 = new RigidPose {
                        Position = new Vector3(1.5f, 0, 1.5f), Orientation = BepuUtilities.Quaternion.Identity
                    };
                    compoundBuilder.Add(legShapeIndex, legPose0, legInverseInertia.InverseInertiaTensor, 1);
                    compoundBuilder.Add(legShapeIndex, legPose1, legInverseInertia.InverseInertiaTensor, 1);
                    compoundBuilder.Add(legShapeIndex, legPose2, legInverseInertia.InverseInertiaTensor, 1);
                    compoundBuilder.Add(legShapeIndex, legPose3, legInverseInertia.InverseInertiaTensor, 1);
                    var tableTopPose = new RigidPose {
                        Position = new Vector3(0, 0.6f, 0), Orientation = BepuUtilities.Quaternion.Identity
                    };
                    var tableTopShape = new Box(3.2f, 0.2f, 3.2f);
                    compoundBuilder.Add(tableTopShape, tableTopPose, 3);

                    compoundBuilder.BuildDynamicCompound(out var tableChildren, out var tableInertia, out var tableCenter);
                    compoundBuilder.Reset();
                    var table            = new Compound(tableChildren);
                    var tableDescription = new BodyDescription
                    {
                        Activity = new BodyActivityDescription {
                            SleepThreshold = 0.01f, MinimumTimestepCountUnderThreshold = 32
                        },
                        Collidable = new CollidableDescription
                        {
                            Shape             = Simulation.Shapes.Add(table),
                            SpeculativeMargin = 0.1f,
                        },
                        LocalInertia = tableInertia,
                        Pose         = new RigidPose {
                            Orientation = BepuUtilities.Quaternion.Identity
                        }
                    };

                    //Stack some tables.
                    {
                        for (int i = 0; i < 10; ++i)
                        {
                            tableDescription.Pose.Position = new Vector3(10, 3 + i * 1.4f, 10);
                            Simulation.Bodies.Add(tableDescription);
                        }
                    }

                    //Put a table on top of a sphere to stress out nonconvex reduction for divergent normals.
                    {
                        tableDescription.Pose.Position = new Vector3(10, 6, 0);
                        Simulation.Bodies.Add(tableDescription);

                        var sphereShape       = new Sphere(3);
                        var sphereIndex       = Simulation.Shapes.Add(sphereShape);
                        var sphereDescription = new StaticDescription
                        {
                            Collidable = new CollidableDescription
                            {
                                Shape             = sphereIndex,
                                SpeculativeMargin = 0.1f,
                            },
                            Pose = new RigidPose {
                                Position = new Vector3(10, 2, 0), Orientation = BepuUtilities.Quaternion.Identity
                            }
                        };
                        Simulation.Statics.Add(sphereDescription);
                    }

                    //Put another table on the ground, but with a clamp-ish thing on it that generates opposing normals.
                    {
                        tableDescription.Pose.Position = new Vector3(10, 3, -10);
                        Simulation.Bodies.Add(tableDescription);

                        var clampPieceShape = new Box(2f, 0.1f, 0.3f);
                        clampPieceShape.ComputeInertia(1f, out var clampPieceInverseInertia);
                        var clampPieceShapeIndex = Simulation.Shapes.Add(clampPieceShape);
                        var clamp0 = new RigidPose {
                            Position = new Vector3(0, -0.2f, -1.1f), Orientation = BepuUtilities.Quaternion.Identity
                        };
                        var clamp1 = new RigidPose {
                            Position = new Vector3(0, 0.2f, -1.1f), Orientation = BepuUtilities.Quaternion.Identity
                        };
                        var clamp2 = new RigidPose {
                            Position = new Vector3(0, -0.2f, 0), Orientation = BepuUtilities.Quaternion.Identity
                        };
                        var clamp3 = new RigidPose {
                            Position = new Vector3(0, 0.2f, 0), Orientation = BepuUtilities.Quaternion.Identity
                        };
                        var clamp4 = new RigidPose {
                            Position = new Vector3(0, -0.2f, 1.1f), Orientation = BepuUtilities.Quaternion.Identity
                        };
                        var clamp5 = new RigidPose {
                            Position = new Vector3(0, 0.2f, 1.1f), Orientation = BepuUtilities.Quaternion.Identity
                        };
                        compoundBuilder.Add(clampPieceShapeIndex, clamp0, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp1, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp2, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp3, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp4, clampPieceInverseInertia.InverseInertiaTensor, 1);
                        compoundBuilder.Add(clampPieceShapeIndex, clamp5, clampPieceInverseInertia.InverseInertiaTensor, 1);

                        compoundBuilder.BuildDynamicCompound(out var clampChildren, out var clampInertia, out var clampCenter);
                        compoundBuilder.Reset();
                        var clamp            = new Compound(clampChildren);
                        var clampDescription = new BodyDescription
                        {
                            Activity = new BodyActivityDescription {
                                SleepThreshold = 0.01f, MinimumTimestepCountUnderThreshold = 32
                            },
                            Collidable = new CollidableDescription
                            {
                                Shape             = Simulation.Shapes.Add(clamp),
                                SpeculativeMargin = 0.1f,
                            },
                            LocalInertia = clampInertia,
                            Pose         = new RigidPose {
                                Position = tableDescription.Pose.Position + new Vector3(2f, 0.3f, 0), Orientation = BepuUtilities.Quaternion.Identity
                            }
                        };
                        Simulation.Bodies.Add(clampDescription);
                    }
                }
            }

            //Prevent stuff from falling into the infinite void.
            {
                var boxShape          = new Box(100, 1, 100);
                var groundShapeIndex  = Simulation.Shapes.Add(boxShape);
                var groundDescription = new StaticDescription
                {
                    Collidable = new CollidableDescription
                    {
                        Shape             = groundShapeIndex,
                        SpeculativeMargin = 0.1f,
                    },
                    Pose = new RigidPose {
                        Position = new Vector3(0, 0, 0), Orientation = BepuUtilities.Quaternion.Identity
                    }
                };
                Simulation.Statics.Add(groundDescription);
            }
        }
示例#14
0
        /// <summary>
        /// Constructs a simple character controller.
        /// </summary>
        /// <param name="position">Location to initially place the character.</param>
        /// <param name="characterHeight">The height of the character.</param>
        /// <param name="characterWidth">The diameter of the character.</param>
        /// <param name="supportHeight">The distance above the ground that the bottom of the character's body floats.</param>
        /// <param name="mass">Total mass of the character.</param>
        public CharacterController(Vector3 position, float characterHeight, float characterWidth, float supportHeight, float mass)
        {
            Body = new Capsule(position, characterHeight - characterWidth, characterWidth / 2, mass);
            Body.Tag = this;
            Body.PositionUpdateMode = PositionUpdateMode.Continuous;
            collisionPairCollectorPositionOffset = new Vector3(0, -characterHeight / 2 - supportHeight + 0.1f, 0);
            collisionPairCollector = new Box(position + collisionPairCollectorPositionOffset, characterWidth, supportHeight * 2, characterWidth, 1);
            collisionPairCollector.CollisionInformation.CollisionRules.Personal = CollisionRule.NoNarrowPhaseUpdate; //Prevents collision detection/contact generation from being run.
            collisionPairCollector.IsAffectedByGravity = false;
            CollisionRules.AddRule(collisionPairCollector, Body, CollisionRule.NoBroadPhase);//Prevents the creation of any collision pairs between the body and the collector.

            grabPairCollector = new Box(position - (Vector3.UnitZ * 5.0f), characterWidth / 3.0f, characterWidth / 3.0f, characterWidth * 1.5f, 1.0f);
            grabPairCollector.CollisionInformation.CollisionRules.Personal = CollisionRule.NoNarrowPhaseUpdate;
            grabPairCollector.IsAffectedByGravity = false;
            CollisionRules.AddRule(grabPairCollector, Body, CollisionRule.NoBroadPhase);

            rayOriginOffset = new Vector3(0, -characterHeight / 2, 0);
            this.supportHeight = supportHeight;

            Body.LocalInertiaTensorInverse = new Matrix3X3();
            collisionPairCollector.LocalInertiaTensorInverse = new Matrix3X3();
            grabPairCollector.LocalInertiaTensorInverse = new Matrix3X3();
            //Make the body slippery.
            //Note that this will not make all collisions have zero friction;
            //the friction coefficient between a pair of objects is based
            //on a blending of the two objects' materials.
            Body.Material.KineticFriction = 0;
            Body.Material.StaticFriction = 0;
            orientation = Quaternion.Identity;
        }
示例#15
0
文件: Character.cs 项目: whztt07/SDK
        Capsule GetWorldCapsule( CapsuleShape shape )
        {
            Capsule capsule = new Capsule();

            Vec3 pos = shape.Body.Position + shape.Body.Rotation * shape.Position;
            Quat rot = shape.Body.Rotation * shape.Rotation;

            Vec3 diff = rot * new Vec3( 0, 0, shape.Length * .5f );
            capsule.Point1 = pos - diff;
            capsule.Point2 = pos + diff;
            capsule.Radius = shape.Radius;

            return capsule;
        }
示例#16
0
 /// <summary>
 /// Performs a sweep into the scene using a capsule and checks if it has hit anything. This can be significantly more
 /// efficient than other types of cast* calls.
 /// </summary>
 /// <param name="capsule">Capsule to sweep through the scene.</param>
 /// <param name="rotation">Orientation of the capsule.</param>
 /// <param name="unitDir">Unit direction towards which to perform the sweep.</param>
 /// <param name="layer">Layers to consider for the query. This allows you to ignore certain groups of objects.</param>
 /// <param name="max">
 /// Maximum distance at which to perform the query. Hits past this distance will not be detected.
 /// </param>
 /// <returns>True if something was hit, false otherwise.</returns>
 public static bool CapsuleCastAny(Capsule capsule, Quaternion rotation, Vector3 unitDir, ulong layer = 18446744073709551615, float max = 3.40282347E+38f)
 {
     return(Internal_capsuleCastAny(ref capsule, ref rotation, ref unitDir, layer, max));
 }
示例#17
0
 private static extern bool Internal_capsuleCast(ref Capsule capsule, ref Quaternion rotation, ref Vector3 unitDir, out PhysicsQueryHit hit, ulong layer, float max);
示例#18
0
 public void detachRocket(Capsule rocket)
 {
     if (_attachedRockets.Contains(rocket))
         _attachedRockets.Remove(rocket);
 }
示例#19
0
 public void attachRocket(Capsule rocket)
 {
     _attachedRockets.Add(rocket);
 }
示例#20
0
    public void onMaxPeople()
    {
        if (_died) {
            return;
        }
        _died = true;

        //detach people
        for (int i = 0; i < peopleComingToMe.Count; ++i)
        {
            peopleComingToMe[i].setTarget(null);
        }
        peopleComingToMe.Clear();

        //Detatch rockets
        Capsule[] rocketsToDetach = new Capsule[_attachedRockets.Count];
        _attachedRockets.CopyTo(rocketsToDetach);
        for (int j = 0; j < rocketsToDetach.Length; ++j)
        {
            if (rocketsToDetach[j] == null ||rocketsToDetach[j].isDead())
                continue;
            rocketsToDetach[j].startUrgenceEngine();
        }
        _attachedRockets.Clear();

        //instantiate explosion
        Instantiate(explosionFX, transform.position, explosionFX.transform.rotation );
        if (Camera.main.GetComponent<ShakePosition>()!=null)
        {
            Camera.main.GetComponent<ShakePosition>().Shake();
        }
        GameObject.Destroy(this.gameObject);
        aliveCount--;
    }
示例#21
0
        public void Render(Camera camera)
        {
            if (Sphere == null)
            {
                Sphere = new Sphere();
            }

            if (Capsule == null)
            {
                Capsule = new Capsule();
            }

            if (Line == null)
            {
                Line = new Line();
            }

            var sphereShader  = ShaderContainer.GetShader("Sphere");
            var capsuleShader = ShaderContainer.GetShader("Capsule");
            var lineShader    = ShaderContainer.GetShader("Line");

            Matrix4 mvp = camera.MvpMatrix;

            List <Collision> collisions = new List <Collision>();

            collisions.AddRange(Attacks);
            collisions.AddRange(Grabs);

            GL.Disable(EnableCap.DepthTest);
            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);

            for (int i = 0; i < collisions.Count; i++)
            {
                Collision coll = collisions[i];
                if (!coll.Enabled)
                {
                    continue;
                }

                Vector4 collColor = new Vector4(Collision.IDColors[i % Collision.IDColors.Length], 0.5f);

                Matrix4 boneTransform = Skel.GetAnimationSingleBindsTransform(BoneIDs[coll.Bone]);
                Matrix4 boneNoScale   =
                    Matrix4.CreateFromQuaternion(boneTransform.ExtractRotation())
                    * Matrix4.CreateTranslation(boneTransform.ExtractTranslation());

                if (IsSphere(coll))
                {
                    Sphere.Render(sphereShader, coll.Size, coll.Pos, boneNoScale, mvp, collColor);
                }
                else if (coll.ShapeType == Collision.Shape.capsule)
                {
                    Capsule.Render(capsuleShader, coll.Size, coll.Pos, coll.Pos2, boneNoScale, mvp, collColor);
                }

                //angle marker
                if (coll is Attack attack)
                {
                    int     angle      = attack.Angle;
                    Vector4 angleColor = new Vector4(1, 1, 1, 1);
                    GL.LineWidth(2f);

                    if (angle < 361)
                    {
                        float radian = angle * (float)Math.PI / 180f;
                        Line.Render(lineShader, radian, coll.Size, coll.Pos, boneNoScale, mvp, angleColor);
                    }
                    else if (angle == 361)
                    {
                        float radian = (float)Math.PI / 2f;
                        for (int j = 0; j < 4; j++)
                        {
                            Line.Render(lineShader, radian * j, coll.Size / 2, coll.Pos, boneNoScale, mvp, angleColor);
                        }
                    }
                    else if (angle == 368)
                    {
                        //set_vec_target_pos uses a second position to pull opponents toward
                        //this is represented by a line drawn between hitbox center and that point
                        if (attack.VecTargetPos_node != 0)
                        {
                            var attackVecBone        = Skel.GetAnimationSingleBindsTransform(BoneIDs[attack.VecTargetPos_node]);
                            var attackVecBoneNoScale =
                                Matrix4.CreateFromQuaternion(attackVecBone.ExtractRotation())
                                * Matrix4.CreateTranslation(attackVecBone.ExtractTranslation());
                            Line.Render(lineShader,
                                        boneNoScale, attackVecBoneNoScale,
                                        coll.Pos, Vector3.Zero,
                                        Vector3.Zero, new Vector3(attack.VecTargetPos_pos.Z, attack.VecTargetPos_pos.Y, 0),
                                        mvp, angleColor
                                        );
                        }
                    }
                    else
                    {
                        float radian = (float)Math.PI / 2f;
                        float add    = (float)Math.PI / 4f;
                        for (int j = 0; j < 4; j++)
                        {
                            Line.Render(lineShader, radian * j + add, coll.Size / 2, coll.Pos, boneNoScale, mvp, angleColor);
                        }
                    }
                }
            }


            GL.Enable(EnableCap.DepthTest);
            GL.Disable(EnableCap.Blend);
        }
示例#22
0
 private static extern bool Internal_capsuleOverlapAny(ref Capsule capsule, ref Quaternion rotation, ulong layer);
示例#23
0
 private static extern Collider[] Internal_capsuleOverlap(ref Capsule capsule, ref Quaternion rotation, ulong layer);
示例#24
0
 /// <summary>
 /// Sets the target to follow. Called by Capsule.
 /// </summary>
 /// <param name="myTarget"></param>
 public void SetFollowTarget(Capsule myTarget)
 {
     target = myTarget;
 }
示例#25
0
 /// <summary>Returns a list of all colliders in the scene that overlap the provided capsule.</summary>
 /// <param name="capsule">Capsule to check for overlap.</param>
 /// <param name="rotation">Orientation of the capsule.</param>
 /// <param name="layer">Layers to consider for the query. This allows you to ignore certain groups of objects.</param>
 /// <returns>List of all colliders that overlap the capsule.</returns>
 public static Collider[] CapsuleOverlap(Capsule capsule, Quaternion rotation, ulong layer = 18446744073709551615)
 {
     return(Internal_capsuleOverlap(ref capsule, ref rotation, layer));
 }
 public abstract int Deploy(Capsule capsule);
示例#27
0
 // Use this for initialization
 void Start()
 {
     _lineRender = GetComponent<LineRenderer>();
     _lineRender.enabled = false;
     _engine = GetComponent<Engine>();
     _engine.enabled = false;
     _capsule = GetComponent<Capsule>();
 }
 public abstract SquadLogic CapsuleCamperLogic(Capsule capsule);
示例#29
0
文件: Character.cs 项目: whztt07/SDK
        bool VolumeCheckGetFirstNotFreePlace( Capsule[] sourceVolumeCapsules, Vec3 destVector, bool firstIteration, float step,
			out List<Body> collisionBodies, out float collisionDistance, out bool collisionOnFirstCheck )
        {
            collisionBodies = new List<Body>();
            collisionDistance = 0;
            collisionOnFirstCheck = false;

            bool firstCheck = true;

            Vec3 direction = destVector.GetNormalize();
            float totalDistance = destVector.Length();
            int stepCount = (int)( (float)totalDistance / step ) + 2;
            Vec3 previousOffset = Vec3.Zero;

            for( int nStep = 0; nStep < stepCount; nStep++ )
            {
                float distance = (float)nStep * step;
                if( distance > totalDistance )
                    distance = totalDistance;
                Vec3 offset = direction * distance;

                foreach( Capsule sourceVolumeCapsule in sourceVolumeCapsules )
                {
                    Capsule checkCapsule = CapsuleAddOffset( sourceVolumeCapsule, offset );

                    Body[] bodies = PhysicsWorld.Instance.VolumeCast( checkCapsule, (int)ContactGroup.CastOnlyContact );
                    foreach( Body body in bodies )
                    {
                        if( body == mainBody || body == fixRotationJointBody )
                            continue;
                        collisionBodies.Add( body );
                    }
                }

                if( collisionBodies.Count != 0 )
                {
                    //second iteration
                    if( nStep != 0 && firstIteration )
                    {
                        float step2 = step / 10;
                        Capsule[] sourceVolumeCapsules2 = new Capsule[ sourceVolumeCapsules.Length ];
                        for( int n = 0; n < sourceVolumeCapsules2.Length; n++ )
                            sourceVolumeCapsules2[ n ] = CapsuleAddOffset( sourceVolumeCapsules[ n ], previousOffset );
                        Vec3 destVector2 = offset - previousOffset;

                        List<Body> collisionBodies2;
                        float collisionDistance2;
                        bool collisionOnFirstCheck2;
                        if( VolumeCheckGetFirstNotFreePlace( sourceVolumeCapsules2, destVector2, false, step2, out collisionBodies2,
                            out collisionDistance2, out collisionOnFirstCheck2 ) )
                        {
                            collisionBodies = collisionBodies2;
                            collisionDistance = ( previousOffset != Vec3.Zero ? previousOffset.Length() : 0 ) + collisionDistance2;
                            collisionOnFirstCheck = false;
                            return true;
                        }
                    }

                    collisionDistance = distance;
                    collisionOnFirstCheck = firstCheck;
                    return true;
                }

                firstCheck = false;
                previousOffset = offset;
            }

            return false;
        }
示例#30
0
		/// <summary>
		/// Constructs a simple character controller.
		/// </summary>
		/// <param name="position">Location to initially place the character.</param>
		/// <param name="height">The height of the character.</param>
		/// <param name="radius">The diameter of the character.</param>
		/// <param name="supportHeight">The distance above the ground that the bottom of the character's body floats.</param>
		/// <param name="mass">Total mass of the character.</param>
		public Character(Main main, Bindable bindable, Vector3 position, float height = Character.DefaultHeight, float crouchedHeight = Character.DefaultCrouchedHeight, float radius = Character.DefaultRadius, float supportHeight = Character.DefaultSupportHeight, float crouchedSupportHeight = Character.DefaultCrouchedSupportHeight, float mass = Character.DefaultMass)
		{
			this.main = main;
			this.Radius.Value = radius;
			this.Mass.Value = mass;
			this.Body = new Capsule(position, height, radius, mass);
			this.Body.Tag = this;
			this.Body.CollisionInformation.Tag = this;
			this.Body.IgnoreShapeChanges = true;
			this.Body.LinearDamping = 0.0f;
			this.Body.CollisionInformation.CollisionRules.Group = Character.CharacterGroup;
			this.NormalHeight = height;
			this.CrouchedHeight = crouchedHeight;
			this.Body.CollisionInformation.Events.ContactCreated += new BEPUphysics.BroadPhaseEntries.Events.ContactCreatedEventHandler<EntityCollidable>(Events_ContactCreated);
			this.collisionPairCollector = new Box(position + new Vector3(0, (height * -0.5f) - supportHeight, 0), radius * 2, supportHeight * 2, radius, 1);
			this.collisionPairCollector.CollisionInformation.CollisionRules.Personal = CollisionRule.NoNarrowPhaseUpdate; //Prevents collision detection/contact generation from being run.
			this.collisionPairCollector.IsAffectedByGravity = false;
			this.collisionPairCollector.CollisionInformation.CollisionRules.Group = Character.CharacterGroup;
			CollisionRules.AddRule(this.collisionPairCollector, this.Body, CollisionRule.NoBroadPhase); //Prevents the creation of any collision pairs between the body and the collector.
			this.SupportHeight.Value = supportHeight;
			this.NormalSupportHeight = supportHeight;
			this.CrouchedSupportHeight = crouchedSupportHeight;

			this.Body.LocalInertiaTensorInverse = new BEPUutilities.Matrix3x3();
			this.collisionPairCollector.LocalInertiaTensorInverse = new BEPUutilities.Matrix3x3();

			bindable.Add(new ChangeBinding<bool>(this.Crouched, delegate(bool old, bool value)
			{
				if (value && !old)
				{
					this.Body.Position += new Vector3(0, (this.CrouchedSupportHeight - this.NormalSupportHeight) + 0.5f * (this.CrouchedHeight - this.NormalHeight), 0);
					this.Height.Value = this.CrouchedHeight;
					this.Body.Length = this.Height.Value - this.Radius * 2;
					this.SupportHeight.Value = this.CrouchedSupportHeight;
				}
				else if (!value && old)
				{
					this.Height.Value = this.NormalHeight;
					this.Body.Length = this.Height.Value - this.Radius * 2;
					this.Body.Position += new Vector3(0, (this.NormalSupportHeight - this.CrouchedSupportHeight) + 0.5f * (this.NormalHeight - this.CrouchedHeight), 0);
					this.SupportHeight.Value = this.NormalSupportHeight;
				}
				this.collisionPairCollector.Height = this.SupportHeight * 2;
				this.Transform.Value = this.Body.WorldTransform;
			}));

			bindable.Add(new SetBinding<Matrix>(this.Transform, delegate(Matrix m)
			{
				this.Body.WorldTransform = m;
			}));

			bindable.Add(new SetBinding<Vector3>(this.LinearVelocity, delegate(Vector3 v)
			{
				this.Body.LinearVelocity = v;
			}));

			//Make the body slippery.
			//Note that this will not make all collisions have zero friction;
			//the friction coefficient between a pair of objects is based
			//on a blending of the two objects' materials.
			this.Body.Material.KineticFriction = 0.0f;
			this.Body.Material.StaticFriction = 0.0f;
			this.Body.Material.Bounciness = 0.0f;

			const int rayChecks = 4;
			float rayCheckRadius = radius - 0.1f;
			this.rayOffsets = new[] { Vector3.Zero }.Concat(Enumerable.Range(0, rayChecks).Select(
			delegate(int x)
			{
				float angle = x * ((2.0f * (float)Math.PI) / (float)rayChecks);
				return new Vector3((float)Math.Cos(angle) * rayCheckRadius, 0, (float)Math.Sin(angle) * rayCheckRadius);
			})).ToArray();
			this.IsUpdating = false;
		}
        /// <summary>
        /// Detectar colision entre un Ray y una Capsula
        /// Basado en: http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrLine3Capsule3.cpp
        /// </summary>
        /// <param name="ray">Ray</param>
        /// <param name="capsule">Capsula</param>
        /// <param name="t">Menor instante de colision</param>
        /// <returns>True si hay colision</returns>
        private bool intersectRayCapsule(TgcRay.RayStruct ray, Capsule capsule, out float t)
        {
            t = -1;
            Vector3 origin = ray.origin;
            Vector3 dir = ray.direction;

            // Create a coordinate system for the capsule.  In this system, the
            // capsule segment center C is the origin and the capsule axis direction
            // W is the z-axis.  U and V are the other coordinate axis directions.
            // If P = x*U+y*V+z*W, the cylinder containing the capsule wall is
            // x^2 + y^2 = r^2, where r is the capsule radius.  The finite cylinder
            // that makes up the capsule minus its hemispherical end caps has z-values
            // |z| <= e, where e is the extent of the capsule segment.  The top
            // hemisphere cap is x^2+y^2+(z-e)^2 = r^2 for z >= e, and the bottom
            // hemisphere cap is x^2+y^2+(z+e)^2 = r^2 for z <= -e.
            Vector3 U = capsule.segment.dir;
            Vector3 V = U;
            Vector3 W = U;
            generateComplementBasis(ref U, ref V, W);
            float rSqr = capsule.radius * capsule.radius;
            float extent = capsule.segment.extent;

            // Convert incoming line origin to capsule coordinates.
            Vector3 diff = origin - capsule.segment.center;
            Vector3 P = new Vector3(Vector3.Dot(U, diff), Vector3.Dot(V, diff), Vector3.Dot(W, diff));

            // Get the z-value, in capsule coordinates, of the incoming line's unit-length direction.
            float dz = Vector3.Dot(W, dir);
            if (FastMath.Abs(dz) >= 1f - float.Epsilon)
            {
                // The line is parallel to the capsule axis.  Determine whether the line intersects the capsule hemispheres.
                float radialSqrDist = rSqr - P.X * P.X - P.Y * P.Y;
                if (radialSqrDist < 0f)
                {
                    // Line outside the cylinder of the capsule, no intersection.
                    return false;
                }

                // line intersects the hemispherical caps
                float zOffset = FastMath.Sqrt(radialSqrDist) + extent;
                if (dz > 0f)
                {
                    t = -P.Z - zOffset;
                }
                else
                {
                    t = P.Z - zOffset;
                }
                return true;
            }

            // Convert incoming line unit-length direction to capsule coordinates.
            Vector3 D = new Vector3(Vector3.Dot(U, dir), Vector3.Dot(V, dir), dz);

            // Test intersection of line P+t*D with infinite cylinder x^2+y^2 = r^2.
            // This reduces to computing the roots of a quadratic equation.  If
            // P = (px,py,pz) and D = (dx,dy,dz), then the quadratic equation is
            //   (dx^2+dy^2)*t^2 + 2*(px*dx+py*dy)*t + (px^2+py^2-r^2) = 0
            float a0 = P.X * P.X + P.Y * P.Y - rSqr;
            float a1 = P.X * D.X + P.Y * D.Y;
            float a2 = D.X * D.X + D.Y * D.Y;
            float discr = a1 * a1 - a0 * a2;
            if (discr < 0f)
            {
                // Line does not intersect infinite cylinder.
                return false;
            }

            float root, inv, tValue, zValue;
            int quantity = 0;
            if (discr > float.Epsilon)
            {
                // Line intersects infinite cylinder in two places.
                root = FastMath.Sqrt(discr);
                inv = (1f)/a2;
                tValue = (-a1 - root)* inv;
                zValue = P.Z + tValue * D.Z;
                if (FastMath.Abs(zValue) <= extent)
                {
                    quantity++;
                    t = tValue;
                }

                tValue = (-a1 + root) * inv;
                zValue = P.Z + tValue * D.Z;
                if (FastMath.Abs(zValue) <= extent)
                {
                    quantity++;
                    t = TgcCollisionUtils.min(t, tValue);
                }

                if (quantity == 2)
                {
                    // Line intersects capsule wall in two places.
                    return true;
                }
            }
            else
            {
                // Line is tangent to infinite cylinder.
                tValue = -a1 / a2;
                zValue = P.Z + tValue * D.Z;
                if (FastMath.Abs(zValue) <= extent)
                {
                    t = tValue;
                    return true;
                }
            }

            // Test intersection with bottom hemisphere.  The quadratic equation is
            // t^2 + 2*(px*dx+py*dy+(pz+e)*dz)*t + (px^2+py^2+(pz+e)^2-r^2) = 0
            // Use the fact that currently a1 = px*dx+py*dy and a0 = px^2+py^2-r^2.
            // The leading coefficient is a2 = 1, so no need to include in the
            // construction.
            float PZpE = P.Z + extent;
            a1 += PZpE * D.Z;
            a0 += PZpE * PZpE;
            discr = a1 * a1 - a0;
            if (discr > float.Epsilon)
            {
                root = FastMath.Sqrt(discr);
                tValue = -a1 - root;
                zValue = P.Z + tValue * D.Z;
                if (zValue <= -extent)
                {
                    quantity++;
                    t = TgcCollisionUtils.min(t, tValue);
                    if (quantity == 2)
                    {
                        return true;
                    }
                }

                tValue = -a1 + root;
                zValue = P.Z + tValue * D.Z;
                if (zValue <= -extent)
                {
                    quantity++;
                    t = TgcCollisionUtils.min(t, tValue);
                    if (quantity == 2)
                    {
                        return true;
                    }
                }
            }
            else if (FastMath.Abs(discr) <= float.Epsilon)
            {
                tValue = -a1;
                zValue = P.Z + tValue * D.Z;
                if (zValue <= -extent)
                {
                    quantity++;
                    t = TgcCollisionUtils.min(t, tValue);
                    if (quantity == 2)
                    {
                        return true;
                    }
                }
            }

            // Test intersection with top hemisphere.  The quadratic equation is
            // t^2 + 2*(px*dx+py*dy+(pz-e)*dz)*t + (px^2+py^2+(pz-e)^2-r^2) = 0
            // Use the fact that currently a1 = px*dx+py*dy+(pz+e)*dz and
            // a0 = px^2+py^2+(pz+e)^2-r^2.  The leading coefficient is a2 = 1, so
            // no need to include in the construction.
            a1 -= 2f * extent * D.Z;
            a0 -= 4 * extent * P.Z;
            discr = a1*a1 - a0;
            if (discr > float.Epsilon)
            {
                root = FastMath.Sqrt(discr);
                tValue = -a1 - root;
                zValue = P.Z + tValue*D.Z;
                if (zValue >= extent)
                {
                    quantity++;
                    t = TgcCollisionUtils.min(t, tValue);
                    if (quantity == 2)
                    {
                        return true;
                    }
                }

                tValue = -a1 + root;
                zValue = P.Z + tValue * D.Z;
                if (zValue >= extent)
                {
                    quantity++;
                    t = TgcCollisionUtils.min(t, tValue);
                    if (quantity == 2)
                    {
                        return true;
                    }
                }
            }
            else if (FastMath.Abs(discr) <= float.Epsilon)
            {
                tValue = -a1;
                zValue = P.Z + tValue * D.Z;
                if (zValue >= extent)
                {
                    quantity++;
                    t = TgcCollisionUtils.min(t, tValue);
                    if (quantity == 2)
                    {
                        return true;
                    }
                }
            }

            return quantity > 0;
        }
示例#32
0
 public bool TestOverlap(int layerMask, QueryTriggerInteraction query)
 {
     return(Capsule.FromCollider(_controller).TestOverlap(layerMask, query));
 }
示例#33
0
 private static extern bool Internal_capsuleCastAny(ref Capsule capsule, ref Quaternion rotation, ref Vector3 unitDir, ulong layer, float max);
示例#34
0
 public int Overlap(ICollection <Collider> results, int layerMask, QueryTriggerInteraction query)
 {
     return(Capsule.FromCollider(_controller).Overlap(results, layerMask, query));
 }
示例#35
0
    protected virtual IOperation CreateOperationFromEditor(Vector3 start, Vector3 end, TerrainToolEditor editor)
    {
        var voxelType = EditorUtils.GetVoxelTypeFromIndex(VoxelTypeIndex, editor.Terrain.VoxelTypeSet);

        return(Capsule.CreateFromUnityWorld(editor.Terrain, Dig, start, end, Radius, voxelType));
    }
示例#36
0
 public bool Cast(Vector3 direction, out RaycastHit hitinfo, float distance, int layerMask, QueryTriggerInteraction query)
 {
     return(Capsule.FromCollider(_controller).Cast(direction, out hitinfo, distance, layerMask, query));
 }
示例#37
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(0, 10, 40);
            camera.Yaw      = 0;
            camera.Pitch    = 0;
            Simulation      = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)));

            var box     = new Box(2f, 2f, 2f);
            var capsule = new Capsule(1f, 1f);
            var sphere  = new Sphere(1.5f);

            box.ComputeInertia(1, out var boxInertia);
            capsule.ComputeInertia(1, out var capsuleInertia);
            sphere.ComputeInertia(1, out var sphereInertia);
            var       boxIndex     = Simulation.Shapes.Add(box);
            var       capsuleIndex = Simulation.Shapes.Add(capsule);
            var       sphereIndex  = Simulation.Shapes.Add(sphere);
            const int width        = 12;
            const int height       = 3;
            const int length       = 12;

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < height; ++j)
                {
                    for (int k = 0; k < length; ++k)
                    {
                        var location        = new Vector3(5, 5, 5) * new Vector3(i, j, k) + new Vector3(-width * 2.5f, 2.5f, -length * 2.5f);
                        var bodyDescription = new BodyDescription
                        {
                            Activity = new BodyActivityDescription {
                                MinimumTimestepCountUnderThreshold = 32, SleepThreshold = 0.1f
                            },
                            Pose = new RigidPose
                            {
                                Orientation = Quaternion.Identity,
                                Position    = location
                            },
                            Collidable = new CollidableDescription
                            {
                                Continuity = new ContinuousDetectionSettings {
                                    Mode = ContinuousDetectionMode.Discrete
                                },
                                SpeculativeMargin = 0.1f
                            }
                        };
                        switch (j % 3)
                        {
                        case 0:
                            bodyDescription.Collidable.Shape = boxIndex;
                            bodyDescription.LocalInertia     = boxInertia;
                            break;

                        case 1:
                            bodyDescription.Collidable.Shape = capsuleIndex;
                            bodyDescription.LocalInertia     = capsuleInertia;
                            break;

                        case 2:
                            bodyDescription.Collidable.Shape = sphereIndex;
                            bodyDescription.LocalInertia     = sphereInertia;
                            break;
                        }
                        Simulation.Bodies.Add(bodyDescription);
                    }
                }
            }

            //Don't really want to regenerate a convex hull every frame; just cache one out.
            const int pointCount = 32;
            var       points     = new QuickList <Vector3>(pointCount, BufferPool);
            var       random     = new Random(5);

            for (int i = 0; i < pointCount; ++i)
            {
                points.AllocateUnsafely() = new Vector3((float)random.NextDouble() - 0.5f, (float)random.NextDouble() - 0.5f, (float)random.NextDouble() - 0.5f);
            }
            ConvexHullHelper.CreateShape(points.Span.Slice(0, points.Count), BufferPool, out _, out hull);
            points.Dispose(BufferPool);

            //var staticShapeIndex = Simulation.Shapes.Add(new Box(100, 1, 100));
            //var staticDescription = new StaticDescription
            //{
            //    Collidable = new CollidableDescription
            //    {
            //        Continuity = new ContinuousDetectionSettings { Mode = ContinuousDetectionMode.Discrete },
            //        Shape = Simulation.Shapes.Add(new Box(100, 1, 100)),
            //        SpeculativeMargin = 0.1f
            //    },
            //    Pose = new RigidPose { Position = new Vector3(0, -1, 0), Orientation = Quaternion.Identity }
            //};
            //Simulation.Statics.Add(staticDescription);

            const int planeWidth  = 64;
            const int planeHeight = 64;

            DemoMeshHelper.CreateDeformedPlane(planeWidth, planeHeight,
                                               (int x, int y) =>
            {
                return(new Vector3(x, 1 * MathF.Cos(x / 4f) * MathF.Sin(y / 4f), y));
            }, new Vector3(2, 3, 2), BufferPool, out var planeMesh);
            Simulation.Statics.Add(new StaticDescription(new Vector3(-64, -10, -64), new CollidableDescription(Simulation.Shapes.Add(planeMesh), 0.1f)));
        }
示例#38
0
 public int CastAll(Vector3 direction, ICollection <RaycastHit> results, float distance, int layerMask, QueryTriggerInteraction query)
 {
     return(Capsule.FromCollider(_controller).CastAll(direction, results, distance, layerMask, query));
 }
 public void Parse(GameBitBuffer buffer)
 {
     Field0 = buffer.ReadInt(32);
     Field1 = buffer.ReadInt(32);
     Field2 = buffer.ReadInt(32);
     Field3 = buffer.ReadInt(32);
     Field4 = buffer.ReadFloat32();
     Field5 = buffer.ReadFloat32();
     Field6 = buffer.ReadFloat32();
     Field7 = new ConvexHull();
     Field7.Parse(buffer);
     Field8 = new OBB();
     Field8.Parse(buffer);
     Field9 = new Sphere();
     Field9.Parse(buffer);
     Field10 = new Cylinder();
     Field10.Parse(buffer);
     Field11 = new Capsule();
     Field11.Parse(buffer);
 }
示例#40
0
 protected abstract void RecalculateNeededResources(Capsule capsule);
示例#41
0
		public void LinearCapsuleSweepCallback()
		{
			using( CreateCoreAndScene() )
			{
				CreateBoxActor( 0, 0, 20 );

				Capsule capsule = new Capsule( new Vector3( 0, -5, 0 ), new Vector3( 0, 5, 0 ), 10 );

				SweepCallback callback = new SweepCallback();

				this.Scene.LinearCapsuleSweep( capsule, new Vector3( 0, 0, 1000 ), SweepFlags.Dynamics | SweepFlags.Statics, "Dummy Object", callback );

				Assert.IsTrue( callback.NumberOfHits == 1, "The linear capsule sweep should of returned 1 hit. Hits returned: {0}", callback.NumberOfHits );
			}
		}
示例#42
0
 public void HandleCapsuleInsert(Capsule capsule)
 {
     _capsules.Add(capsule);
     capsule.GreenHouse = this;
     RecalculateNeededResourcesForAllCapsules();
 }
示例#43
0
		protected override Body[] OnVolumeCast( Capsule capsule, int contactGroup )
		{
			Vec3 center;
			capsule.GetCenter( out center );
			float length = capsule.GetLength();
			Vec3 direction;
			capsule.GetDirection( out direction );

			dGeomID volumeCastGeomID = Ode.dCreateCapsule( rootSpaceID, capsule.Radius, length );

			Quat rotation = Quat.FromDirectionZAxisUp( direction );

			Mat3 rot;
			rotation.ToMat3( out rot );

			Mat3 rotationMat;
			Mat3.FromRotateByY( MathFunctions.PI / 2, out rotationMat );
			Mat3 mat3;
			Mat3.Multiply( ref rot, ref rotationMat, out mat3 );

			Ode.dMatrix3 odeMat3;
			Convert.ToODE( ref mat3, out odeMat3 );
			Ode.dGeomSetRotation( volumeCastGeomID, ref odeMat3 );
			Ode.dGeomSetPosition( volumeCastGeomID, center.X, center.Y, center.Z );

			Body[] result = DoVolumeCastGeneral( volumeCastGeomID, contactGroup );

			Ode.dGeomDestroy( volumeCastGeomID );

			return result;
		}
示例#44
0
 public void HandleCapsuleGrabbed(Capsule capsule)
 {
     capsule.GreenHouse = null;
     _capsules.Remove(capsule);
     RecalculateNeededResourcesForAllCapsules();
 }
示例#45
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-10, 5, -10);
            //camera.Yaw = MathHelper.Pi ;
            camera.Yaw = MathHelper.Pi * 3f / 4;
            //camera.Pitch = MathHelper.Pi * 0.1f;
            Simulation = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)));

            var shape = new Capsule(.5f, .5f);

            shape.ComputeInertia(1, out var localInertia);
            var       shapeIndex = Simulation.Shapes.Add(shape);
            const int width      = 1;
            const int height     = 1;
            const int length     = 1;

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < height; ++j)
                {
                    for (int k = 0; k < length; ++k)
                    {
                        var location        = new Vector3(1.5f, 1.5f, 4.4f) * new Vector3(i, j, k) + new Vector3(-width * 0.5f, 0.5f, -length * 0.5f);
                        var bodyDescription = new BodyDescription
                        {
                            Activity = new BodyActivityDescription {
                                MinimumTimestepCountUnderThreshold = 32, SleepThreshold = 0.01f
                            },
                            LocalInertia = localInertia,
                            Pose         = new RigidPose
                            {
                                Orientation = BepuUtilities.Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), (float)Math.PI / 2),
                                Position    = location
                            },
                            Collidable = new CollidableDescription {
                                SpeculativeMargin = 50.1f, Shape = shapeIndex
                            }
                        };
                        Simulation.Bodies.Add(bodyDescription);
                    }
                }
            }
            var boxShape = new Box(0.5f, 0.5f, 2.5f);

            boxShape.ComputeInertia(1, out var boxLocalInertia);
            var boxDescription = new BodyDescription
            {
                Activity = new BodyActivityDescription {
                    MinimumTimestepCountUnderThreshold = 32, SleepThreshold = -0.01f
                },
                LocalInertia = boxLocalInertia,
                Pose         = new RigidPose
                {
                    Orientation = BepuUtilities.Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), 0),
                    Position    = new Vector3(1, -0.5f, 0)
                },
                Collidable = new CollidableDescription {
                    SpeculativeMargin = 50.1f, Shape = Simulation.Shapes.Add(boxShape)
                }
            };

            Simulation.Bodies.Add(boxDescription);

            Simulation.Statics.Add(new StaticDescription(new Vector3(0, -3, 0), new CollidableDescription {
                SpeculativeMargin = 0.1f, Shape = Simulation.Shapes.Add(new Box(4, 1, 4))
            }));
        }
示例#46
0
        /// <summary>
        /// Constructs a simple character controller.
        /// </summary>
        /// <param name="position">Location to initially place the character.</param>
        /// <param name="height">The height of the character.</param>
        /// <param name="radius">The diameter of the character.</param>
        /// <param name="supportHeight">The distance above the ground that the bottom of the character's body floats.</param>
        /// <param name="mass">Total mass of the character.</param>
        public Character(Main main, Bindable bindable, Vector3 position, float height = Character.DefaultHeight, float crouchedHeight = Character.DefaultCrouchedHeight, float radius = Character.DefaultRadius, float supportHeight = Character.DefaultSupportHeight, float crouchedSupportHeight = Character.DefaultCrouchedSupportHeight, float mass = Character.DefaultMass)
        {
            this.main         = main;
            this.Radius.Value = radius;
            this.Mass.Value   = mass;
            this.Body         = new Capsule(position, height, radius, mass);
            this.Body.Tag     = this;
            this.Body.CollisionInformation.Tag = this;
            this.Body.IgnoreShapeChanges       = true;
            this.Body.LinearDamping            = 0.0f;
            this.Body.CollisionInformation.CollisionRules.Group = Character.CharacterGroup;
            this.NormalHeight   = height;
            this.CrouchedHeight = crouchedHeight;
            this.Body.CollisionInformation.Events.ContactCreated += new BEPUphysics.BroadPhaseEntries.Events.ContactCreatedEventHandler <EntityCollidable>(Events_ContactCreated);
            this.collisionPairCollector = new Box(position + new Vector3(0, (height * -0.5f) - supportHeight, 0), radius * 2, supportHeight * 2, radius, 1);
            this.collisionPairCollector.CollisionInformation.CollisionRules.Personal = CollisionRule.NoNarrowPhaseUpdate;             //Prevents collision detection/contact generation from being run.
            this.collisionPairCollector.IsAffectedByGravity = false;
            this.collisionPairCollector.CollisionInformation.CollisionRules.Group = Character.CharacterGroup;
            CollisionRules.AddRule(this.collisionPairCollector, this.Body, CollisionRule.NoBroadPhase);             //Prevents the creation of any collision pairs between the body and the collector.
            this.SupportHeight.Value   = supportHeight;
            this.NormalSupportHeight   = supportHeight;
            this.CrouchedSupportHeight = crouchedSupportHeight;

            this.Body.LocalInertiaTensorInverse = new BEPUutilities.Matrix3x3();
            this.collisionPairCollector.LocalInertiaTensorInverse = new BEPUutilities.Matrix3x3();

            bindable.Add(new ChangeBinding <bool>(this.Crouched, delegate(bool old, bool value)
            {
                if (value && !old)
                {
                    this.Body.Position      += new Vector3(0, (this.CrouchedSupportHeight - this.NormalSupportHeight) + 0.5f * (this.CrouchedHeight - this.NormalHeight), 0);
                    this.Height.Value        = this.CrouchedHeight;
                    this.Body.Length         = this.Height.Value - this.Radius * 2;
                    this.SupportHeight.Value = this.CrouchedSupportHeight;
                }
                else if (!value && old)
                {
                    this.Height.Value        = this.NormalHeight;
                    this.Body.Length         = this.Height.Value - this.Radius * 2;
                    this.Body.Position      += new Vector3(0, (this.NormalSupportHeight - this.CrouchedSupportHeight) + 0.5f * (this.NormalHeight - this.CrouchedHeight), 0);
                    this.SupportHeight.Value = this.NormalSupportHeight;
                }
                this.collisionPairCollector.Height = this.SupportHeight * 2;
                this.Transform.Value = this.Body.WorldTransform;
            }));

            bindable.Add(new SetBinding <Matrix>(this.Transform, delegate(Matrix m)
            {
                this.Body.WorldTransform = m;
            }));

            bindable.Add(new SetBinding <Vector3>(this.LinearVelocity, delegate(Vector3 v)
            {
                this.Body.LinearVelocity = v;
            }));

            //Make the body slippery.
            //Note that this will not make all collisions have zero friction;
            //the friction coefficient between a pair of objects is based
            //on a blending of the two objects' materials.
            this.Body.Material.KineticFriction = 0.0f;
            this.Body.Material.StaticFriction  = 0.0f;
            this.Body.Material.Bounciness      = 0.0f;

            const int rayChecks      = 4;
            float     rayCheckRadius = radius - 0.1f;

            this.rayOffsets = new[] { Vector3.Zero }.Concat(Enumerable.Range(0, rayChecks).Select(
                                                                delegate(int x)
            {
                float angle = x * ((2.0f * (float)Math.PI) / (float)rayChecks);
                return(new Vector3((float)Math.Cos(angle) * rayCheckRadius, 0, (float)Math.Sin(angle) * rayCheckRadius));
            })).ToArray();
            this.IsUpdating = false;
        }
示例#47
0
文件: Character.cs 项目: whztt07/SDK
 Capsule[] GetVolumeCapsules()
 {
     Capsule[] volumeCapsules = new Capsule[ mainBody.Shapes.Length ];
     for( int n = 0; n < volumeCapsules.Length; n++ )
         volumeCapsules[ n ] = GetWorldCapsule( (CapsuleShape)mainBody.Shapes[ n ] );
     return volumeCapsules;
 }
        /// <summary>
        /// Constructs a simple character controller.
        /// </summary>
        /// <param name="position">Location to initially place the character.</param>
        /// <param name="characterHeight">The height of the character.</param>
        /// <param name="characterWidth">The diameter of the character.</param>
        /// <param name="supportHeight">The distance above the ground that the bottom of the character's body floats.</param>
        /// <param name="mass">Total mass of the character.</param>
        /// <param name="scale">The scale.</param>
        public CharacterController(Vector3 position, float characterHeight, float characterWidth, float supportHeight, float mass, Vector3 scale)
        {
            IsUpdating = false;
            characterWidth = characterWidth * scale.X;
            this.characterHeight = characterHeight * scale.Y;
            this.scale = scale;
            Body = new Capsule(position, characterHeight - characterWidth, characterWidth / 2, mass);
            collisionPairCollectorPositionOffset = new Vector3(0, -characterHeight / 2 - supportHeight, 0);
            collisionPairCollector = new Box(position + collisionPairCollectorPositionOffset, characterWidth, supportHeight * 2, characterWidth, 1);
           
            
            collisionPairCollector.CollisionInformation.CollisionRules.Personal = CollisionRule.NoNarrowPhaseUpdate; //Prevents collision detection/contact generation from being run.
            collisionPairCollector.IsAffectedByGravity = false;
            CollisionRules.AddRule(collisionPairCollector, Body, CollisionRule.NoBroadPhase);//Prevents the creation of any collision pairs between the body and the collector.
            rayOriginOffset = new Vector3(0, -characterHeight / 2, 0);
            this.supportHeight = supportHeight;

            Body.LocalInertiaTensorInverse = new Matrix3X3();
            collisionPairCollector.LocalInertiaTensorInverse = new Matrix3X3();
            //Make the body slippery.
            //Note that this will not make all collisions have zero friction;
            //the friction coefficient between a pair of objects is based
            //on a blending of the two objects' materials.
            Body.Material.KineticFriction = 0;
            Body.Material.StaticFriction = 0;
        }
示例#49
0
文件: Character.cs 项目: whztt07/SDK
        void TickCrouching()
        {
            if( crouchingSwitchRemainingTime > 0 )
            {
                crouchingSwitchRemainingTime -= TickDelta;
                if( crouchingSwitchRemainingTime < 0 )
                    crouchingSwitchRemainingTime = 0;
            }

            if( Intellect != null && crouchingSwitchRemainingTime == 0 )
            {
                bool needCrouching = Intellect.IsControlKeyPressed( GameControlKeys.Crouching );

                if( crouching != needCrouching )
                {
                    Vec3 newPosition;
                    {
                        float diff = Type.HeightFromPositionToGround - Type.CrouchingHeightFromPositionToGround;
                        if( needCrouching )
                            newPosition = Position + new Vec3( 0, 0, -diff );
                        else
                            newPosition = Position + new Vec3( 0, 0, diff );
                    }

                    bool freePlace = true;
                    {
                        Capsule capsule;
                        {
                            float radius = Type.Radius - .01f;

                            float length;
                            if( needCrouching )
                                length = Type.CrouchingHeight - radius * 2 - Type.CrouchingWalkUpHeight;
                            else
                                length = Type.Height - radius * 2 - Type.WalkUpHeight;

                            capsule = new Capsule(
                                newPosition + new Vec3( 0, 0, -length / 2 ),
                                newPosition + new Vec3( 0, 0, length / 2 ), radius );
                        }

                        Body[] bodies = PhysicsWorld.Instance.VolumeCast( capsule, (int)ContactGroup.CastOnlyContact );
                        foreach( Body body in bodies )
                        {
                            if( body == mainBody )
                                continue;

                            freePlace = false;
                            break;
                        }
                    }

                    if( freePlace )
                    {
                        crouching = needCrouching;
                        crouchingSwitchRemainingTime = .3f;

                        ReCreateMainBody();

                        Position = newPosition;
                        OldPosition = Position;

                        Vec3 addForceOnBigSlope;
                        CalculateMainBodyGroundDistanceAndGroundBody( out addForceOnBigSlope );
                    }
                }
            }
        }
示例#50
0
 public Renderable(ref Capsule c) : this()
 {
     Type        = RenderableType.Capsule;
     CapsuleData = c;
 }
示例#51
0
文件: Character.cs 项目: whztt07/SDK
 Capsule CapsuleAddOffset( Capsule capsule, Vec3 offset )
 {
     return new Capsule( capsule.Point1 + offset, capsule.Point2 + offset, capsule.Radius );
 }
示例#52
0
        /// <summary>
        /// GetLocalSkinWireframe
        /// </summary>
        /// <param name="skin"></param>
        /// <returns>VertexPositionColor[]</returns>
        public static VertexPositionColor[] GetLocalSkinWireframe(this CollisionSkin skin)
        {
            List <VertexPositionColor> wireframe = new List <VertexPositionColor>();

            for (int i = 0; i < skin.NumPrimitives; i++)
            {
                Primitive p     = skin.GetPrimitiveLocal(i);
                Matrix    trans = p.TransformMatrix;

                if (p is Sphere)
                {
                    Sphere np = (Sphere)p;

                    List <Vector3> SpherePoints = calcCirclePoints(np.Radius);

                    AddShapeToWireframe(SpherePoints, wireframe, trans, Color.Blue);
                    AddShapeToWireframe(SpherePoints, wireframe, Matrix.CreateRotationY(MathHelper.PiOver2) * trans, Color.Red);
                    AddShapeToWireframe(SpherePoints, wireframe, Matrix.CreateRotationX(MathHelper.PiOver2) * trans, Color.Green);
                }
                else if (p is Capsule)
                {
                    Capsule np = (Capsule)p;

                    List <Vector3> Ball         = calcCirclePoints(np.Radius);
                    List <Vector3> CylPoints    = new List <Vector3>();
                    List <Vector3> CirclePoints = new List <Vector3>();
                    List <Vector3> SidePoints   = new List <Vector3>();

                    // Create LongWays profile slice
                    foreach (Vector3 v in Ball)
                    {
                        Vector3 t = Vector3.Transform(v, Matrix.CreateRotationX(MathHelper.PiOver2));
                        CylPoints.Add(t);
                    }

                    float len = np.Length;

                    SidePoints.Add(Vector3.Transform(new Vector3(np.Radius, len, 0), Matrix.CreateRotationX(MathHelper.PiOver2)));
                    SidePoints.Add(Vector3.Transform(new Vector3(np.Radius, 0, 0), Matrix.CreateRotationX(MathHelper.PiOver2)));
                    SidePoints.Add(Vector3.Transform(new Vector3(-np.Radius, 0, 0), Matrix.CreateRotationX(MathHelper.PiOver2)));
                    SidePoints.Add(Vector3.Transform(new Vector3(-np.Radius, len, 0), Matrix.CreateRotationX(MathHelper.PiOver2)));

                    // Create Y Rungs
                    AddShapeToWireframe(Ball, wireframe, Matrix.CreateTranslation(new Vector3(0, 0, 0.0f * len)) * trans, Color.Green);
                    AddShapeToWireframe(Ball, wireframe, Matrix.CreateTranslation(new Vector3(0, 0, 0.5f * np.Length)) * trans, Color.Green);
                    AddShapeToWireframe(Ball, wireframe, Matrix.CreateTranslation(new Vector3(0, 0, 1.0f * np.Length)) * trans, Color.Green);

                    // Create Z Profile
                    Matrix Zmat = Matrix.CreateRotationZ(MathHelper.PiOver2);
                    AddShapeToWireframe(CylPoints, wireframe, Matrix.CreateTranslation(new Vector3(0, 0, np.Length)) * Zmat * trans, Color.Blue);
                    AddShapeToWireframe(CylPoints, wireframe, Matrix.CreateTranslation(new Vector3(0, 0, 0)) * Zmat * trans, Color.Blue);
                    AddLineToWireframe(SidePoints[0], SidePoints[1], wireframe, Zmat * trans, Color.Blue);
                    AddLineToWireframe(SidePoints[2], SidePoints[3], wireframe, Zmat * trans, Color.Blue);

                    //// Create X Profile
                    Matrix Xmat = Matrix.Identity;
                    AddShapeToWireframe(CylPoints, wireframe, Matrix.CreateTranslation(new Vector3(0, 0, np.Length)) * Xmat * trans, Color.Red);
                    AddShapeToWireframe(CylPoints, wireframe, Matrix.CreateTranslation(new Vector3(0, 0, 0)) * Xmat * trans, Color.Red);
                    AddLineToWireframe(SidePoints[0], SidePoints[1], wireframe, Xmat * trans, Color.Red);
                    AddLineToWireframe(SidePoints[2], SidePoints[3], wireframe, Xmat * trans, Color.Red);
                }
                else if (p is Box)
                {
                    Box np = (Box)p;

                    List <Vector3> xPoints = new List <Vector3>();
                    List <Vector3> yPoints = new List <Vector3>();
                    List <Vector3> zPoints = new List <Vector3>();

                    Vector3 slen = np.SideLengths;

                    xPoints.Add(new Vector3(slen.X, slen.Y, slen.Z));
                    xPoints.Add(new Vector3(0, slen.Y, slen.Z));
                    xPoints.Add(new Vector3(slen.X, 0, slen.Z));
                    xPoints.Add(new Vector3(0, 0, slen.Z));
                    xPoints.Add(new Vector3(slen.X, slen.Y, 0));
                    xPoints.Add(new Vector3(0, slen.Y, 0));
                    xPoints.Add(new Vector3(slen.X, 0, 0));
                    xPoints.Add(new Vector3(0, 0, 0));

                    yPoints.Add(new Vector3(slen.X, slen.Y, slen.Z));
                    yPoints.Add(new Vector3(slen.X, 0, slen.Z));
                    yPoints.Add(new Vector3(0, slen.Y, slen.Z));
                    yPoints.Add(new Vector3(0, 0, slen.Z));
                    yPoints.Add(new Vector3(slen.X, slen.Y, 0));
                    yPoints.Add(new Vector3(slen.X, 0, 0));
                    yPoints.Add(new Vector3(0, slen.Y, 0));
                    yPoints.Add(new Vector3(0, 0, 0));

                    zPoints.Add(new Vector3(slen.X, slen.Y, slen.Z));
                    zPoints.Add(new Vector3(slen.X, slen.Y, 0));
                    zPoints.Add(new Vector3(0, slen.Y, slen.Z));
                    zPoints.Add(new Vector3(0, slen.Y, 0));
                    zPoints.Add(new Vector3(slen.X, 0, slen.Z));
                    zPoints.Add(new Vector3(slen.X, 0, 0));
                    zPoints.Add(new Vector3(0, 0, slen.Z));
                    zPoints.Add(new Vector3(0, 0, 0));

                    AddLinesToWireframe(xPoints, wireframe, trans, Color.Red);
                    AddLinesToWireframe(yPoints, wireframe, trans, Color.Green);
                    AddLinesToWireframe(zPoints, wireframe, trans, Color.Blue);
                }
                else if (p is AABox)
                {
                }
                else if (p is Heightmap)
                {
                    Heightmap hm = (Heightmap)p;
                    Vector3   point, normal;

                    for (int e = 0; e < hm.Heights.Nx; e += 5)
                    {
                        for (int j = 0; j < hm.Heights.Nz; j += 5)
                        {
                            hm.GetSurfacePosAndNormal(out point, out normal, e, j);
                            AddLineToWireframe(point, point - 0.5f * normal, wireframe, trans, Color.GreenYellow);
                        }
                    }
                }
                else if (p is JigLibX.Geometry.Plane)
                {
                }
                else if (p is TriangleMesh)
                {
                    TriangleMesh np = (TriangleMesh)p;

                    for (int j = 0; j < np.GetNumTriangles(); j++)
                    {
                        IndexedTriangle t = np.GetTriangle(j);

                        Vector3 p1 = np.GetVertex(t.GetVertexIndex(0));
                        Vector3 p2 = np.GetVertex(t.GetVertexIndex(1));
                        Vector3 p3 = np.GetVertex(t.GetVertexIndex(2));

                        List <Vector3> tPoints = new List <Vector3>();

                        tPoints.Add(p1);
                        tPoints.Add(p2);
                        tPoints.Add(p3);
                        tPoints.Add(p1);

                        AddShapeToWireframe(tPoints, wireframe, trans, Color.Red);
                    }
                }
            }

            return(wireframe.ToArray());
        }
示例#53
0
		public CompiledCapsule(Vector3 p1, Vector3 p2, float radius)
		{
			_capsule = new Capsule(p1, p2, radius);
		}
示例#54
0
 public void pickupCapsule(AudioClip sfxPickup, Capsule capsule)
 {
     capsules.Add(capsule);
     audio.PlayOneShot(sfxPickup, 1f);
 }
        /// <summary>
        /// Detectar colision entre un Segmento de recta y una Capsula.
        /// </summary>
        /// <param name="seg">Segmento</param>
        /// <param name="capsule">Capsula</param>
        /// <param name="t">Menor instante de colision</param>
        /// <returns>True si hay colision</returns>
        private bool intersectSegmentCapsule(Segment seg, Capsule capsule, out float t)
        {
            TgcRay.RayStruct ray = new TgcRay.RayStruct();
            ray.origin = seg.a;
            ray.direction = seg.dir;

            if (intersectRayCapsule(ray, capsule, out t))
            {
                if (t >= 0.0f && t <= seg.length)
                {
                    t /= seg.length;
                    return true;
                }
            }

            return false;
        }
示例#56
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-20f, 13, -20f);
            camera.Yaw      = MathHelper.Pi * 3f / 4;
            camera.Pitch    = MathHelper.Pi * 0.1f;
            Simulation      = Simulation.Create(BufferPool, new NoCollisionCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)));

            var       box                 = new Box(0.5f, 1.5f, 1f);
            var       capsule             = new Capsule(0, 0.5f);
            var       sphere              = new Sphere(0.5f);
            var       boxIndex            = Simulation.Shapes.Add(box);
            var       capsuleIndex        = Simulation.Shapes.Add(capsule);
            var       sphereIndex         = Simulation.Shapes.Add(sphere);
            const int width               = 16;
            const int height              = 16;
            const int length              = 16;
            var       spacing             = new Vector3(2.01f);
            var       halfSpacing         = spacing / 2;
            float     randomizationSubset = 0.9f;
            var       randomizationSpan   = (spacing - new Vector3(1)) * randomizationSubset;
            var       randomizationBase   = randomizationSpan * -0.5f;
            var       random              = new Random(5);

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < height; ++j)
                {
                    for (int k = 0; k < length; ++k)
                    {
                        var r        = new Vector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble());
                        var location = spacing * (new Vector3(i, j, k) + new Vector3(-width, -height, -length) * 0.5f) + randomizationBase + r * randomizationSpan;

                        Quaternion orientation;
                        orientation.X = -1 + 2 * (float)random.NextDouble();
                        orientation.Y = -1 + 2 * (float)random.NextDouble();
                        orientation.Z = -1 + 2 * (float)random.NextDouble();
                        orientation.W = 0.01f + (float)random.NextDouble();
                        QuaternionEx.Normalize(ref orientation);

                        TypedIndex shapeIndex;
                        switch ((i + j + k) % 3)
                        {
                        case 0:
                            shapeIndex = boxIndex;
                            break;

                        case 1:
                            shapeIndex = capsuleIndex;
                            break;

                        default:
                            shapeIndex = sphereIndex;
                            break;
                        }

                        if ((i + j + k) % 2 == 1)
                        {
                            var bodyDescription = new BodyDescription
                            {
                                Activity = new BodyActivityDescription {
                                    MinimumTimestepCountUnderThreshold = 32, SleepThreshold = -0.1f
                                },
                                Pose = new RigidPose
                                {
                                    Orientation = orientation,
                                    Position    = location
                                },
                                Collidable = new CollidableDescription
                                {
                                    Continuity = new ContinuousDetectionSettings {
                                        Mode = ContinuousDetectionMode.Discrete
                                    },
                                    SpeculativeMargin = 0.1f,
                                    Shape             = shapeIndex
                                }
                            };
                            Simulation.Bodies.Add(bodyDescription);
                        }
                        else
                        {
                            var staticDescription = new StaticDescription
                            {
                                Pose = new RigidPose
                                {
                                    Orientation = orientation,
                                    Position    = location
                                },
                                Collidable = new CollidableDescription
                                {
                                    Continuity = new ContinuousDetectionSettings {
                                        Mode = ContinuousDetectionMode.Discrete
                                    },
                                    SpeculativeMargin = 0.1f,
                                    Shape             = shapeIndex
                                }
                            };
                            Simulation.Statics.Add(staticDescription);
                        }
                    }
                }
            }

            const int planeWidth  = 128;
            const int planeHeight = 128;

            DemoMeshHelper.CreateDeformedPlane(planeWidth, planeHeight,
                                               (int x, int y) =>
            {
                return(new Vector3(x - planeWidth / 2, 1 * MathF.Cos(x / 4f) * MathF.Sin(y / 4f), y - planeHeight / 2));
            }, new Vector3(1, 3, 1), BufferPool, out var planeMesh);
            Simulation.Statics.Add(new StaticDescription(
                                       new Vector3(0, -10, 0), BepuUtilities.QuaternionEx.CreateFromAxisAngle(new Vector3(0, 1, 0), MathF.PI / 4),
                                       new CollidableDescription(Simulation.Shapes.Add(planeMesh), 0.1f)));

            int raySourceCount = 3;

            raySources       = new QuickList <QuickList <TestRay> >(raySourceCount, BufferPool);
            raySources.Count = raySourceCount;

            //Spew rays all over the place, starting inside the shape cube.
            int     randomRayCount = 1 << 14;
            ref var randomRays     = ref raySources[0];
示例#57
0
 protected override Body[] OnVolumeCast( Capsule capsule, int contactGroup )
 {
     Vec3 origin = capsule.GetCenter();
     Quat rotation = Quat.FromDirectionZAxisUp( capsule.GetDirection() );
     int shapeCount = PhysXNativeScene.OverlapCapsuleShapes( nativeScene, ref origin, ref rotation, capsule.Radius,
         capsule.GetLength() * .5f, GetContactGroupMask( contactGroup ) );
     if( shapeCount == 0 )
         return emptyVolumeCastResult;
     return GetBodiesFromVolumeCastResult( shapeCount );
 }
示例#58
0
 private static extern PhysicsQueryHit[] Internal_capsuleCastAll(ref Capsule capsule, ref Quaternion rotation, ref Vector3 unitDir, ulong layer, float max);