Ejemplo n.º 1
0
        /// <summary>
        /// Peek at a temporary native instance or the current (if initialized).
        /// </summary>
        /// <param name="callback">Callback with temporary or already initialized native instance. Callback signature ( nativeRb, isTemporary ).</param>
        /// <remarks>
        /// Always assume the native instance to be temporary. It's never safe to cache an instance to the native object.
        /// </remarks>
        public void PeekTemporaryNativeOrGetNative(Action <agx.RigidBody, bool> callback)
        {
            if (callback == null)
            {
                return;
            }

            if (m_rb != null)
            {
                callback(m_rb, false);
            }
            else
            {
                Shape[] shapes = GetComponentsInChildren <Shape>();

                using (agx.RigidBody rb = new agx.RigidBody()) {
                    foreach (Shape shape in shapes)
                    {
                        agxCollide.Shape nativeShape = shape.CreateTemporaryNative();
                        if (nativeShape != null)
                        {
                            agxCollide.Geometry geometry = new agxCollide.Geometry(nativeShape);

                            geometry.setEnable(shape.IsEnabled);

                            if (shape.Material != null)
                            {
                                geometry.setMaterial(shape.Material.CreateTemporaryNative());
                            }
                            rb.add(geometry, shape.GetNativeRigidBodyOffset(this));
                        }
                    }

                    // For center of mass position/rotation to be correct we have to
                    // synchronize the native transform given current game object transform.
                    SyncNativeTransform(rb);

                    callback(rb, true);

                    // Hitting "Update" (mass or inertia in the Inspector) several times
                    // will crash agx if we don't remove the geometries and shapes.
                    while (rb.getGeometries().Count > 0)
                    {
                        agxCollide.Geometry geometry = rb.getGeometries()[0].get();
                        if (geometry.getShapes().Count > 0)
                        {
                            geometry.remove(geometry.getShapes()[0].get());
                        }
                        rb.remove(geometry);
                    }
                }
            }
        }