当前位置: 首页>>代码示例>>C#>>正文


C# MyPhysicsBody.CreateFromCollisionObject方法代码示例

本文整理汇总了C#中Sandbox.Engine.Physics.MyPhysicsBody.CreateFromCollisionObject方法的典型用法代码示例。如果您正苦于以下问题:C# MyPhysicsBody.CreateFromCollisionObject方法的具体用法?C# MyPhysicsBody.CreateFromCollisionObject怎么用?C# MyPhysicsBody.CreateFromCollisionObject使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Sandbox.Engine.Physics.MyPhysicsBody的用法示例。


在下文中一共展示了MyPhysicsBody.CreateFromCollisionObject方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Init

        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            InitializeSinkComponent();
            base.Init(objectBuilder, cubeGrid);
            if (CubeGrid.CreatePhysics)
            {
            	// Put on my fake, because it does performance issues
                if (MyFakes.ENABLE_GRAVITY_PHANTOM)
                {
                        var shape = CreateFieldShape();
                        Physics = new Sandbox.Engine.Physics.MyPhysicsBody(this, RigidBodyFlag.RBF_KINEMATIC);
                        Physics.IsPhantom = true;
                        Physics.CreateFromCollisionObject(shape, PositionComp.LocalVolume.Center, WorldMatrix, null, Sandbox.Engine.Physics.MyPhysics.CollisionLayers.GravityPhantomLayer);
                        shape.Base.RemoveReference();
                        Physics.Enabled = IsWorking;
                }
                NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME;

                SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;
                ResourceSink.Update();
            }
            m_soundEmitter = new MyEntity3DSoundEmitter(this, true);
            m_baseIdleSound.Init("BlockGravityGen");
			
        }
开发者ID:liiir1985,项目名称:SpaceEngineers,代码行数:25,代码来源:MyGravityGeneratorBase.cs

示例2: Init

        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            ResourceSink = new MyResourceSinkComponent();
            ResourceSink.Init(
                BlockDefinition.ResourceSinkGroup,
                BlockDefinition.RequiredPowerInput,
                this.CalculateRequiredPowerInput);

            base.Init(objectBuilder, cubeGrid);

            ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged;
            ResourceSink.Update();

            if (Physics != null)
            {
                Physics.Close();
            }

            var detectorShape = new HkBoxShape(new Vector3(cubeGrid.GridSize / 3.0f));
            var massProperties = HkInertiaTensorComputer.ComputeBoxVolumeMassProperties(detectorShape.HalfExtents, BlockDefinition.VirtualMass);
            Physics = new Sandbox.Engine.Physics.MyPhysicsBody(this, RigidBodyFlag.RBF_DEFAULT);
            Physics.IsPhantom = false;
            Physics.CreateFromCollisionObject(detectorShape, Vector3.Zero, WorldMatrix, massProperties, MyPhysics.CollisionLayers.VirtualMassLayer);
            Physics.Enabled = IsWorking && cubeGrid.Physics != null && cubeGrid.Physics.Enabled;
            Physics.RigidBody.Activate();
            detectorShape.Base.RemoveReference();

            UpdateText();

            NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME;

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;
        }
开发者ID:ChristianHeinz71,项目名称:SpaceEngineers,代码行数:33,代码来源:MyVirtualMass.cs

示例3: LoadDummies

        private void LoadDummies()
        {
            var finalModel = VRage.Game.Models.MyModels.GetModelOnlyDummies(BlockDefinition.Model);
            foreach (var dummy in finalModel.Dummies)
            {
                if (dummy.Key.ToLower().Contains("merge"))
                {
                    var matrix = dummy.Value.Matrix;
                    Vector3 halfExtents = matrix.Scale / 2.0f;

                    Vector3 projectedPosition = Vector3.DominantAxisProjection(matrix.Translation / halfExtents);
                    projectedPosition.Normalize();
                    m_forward = Base6Directions.GetDirection(projectedPosition);
                    m_right = Base6Directions.GetPerpendicular(m_forward);

                    var world = MatrixD.Normalize(matrix) * this.WorldMatrix;

                    var detectorShape = CreateFieldShape(halfExtents);
                    Physics = new Sandbox.Engine.Physics.MyPhysicsBody(this, RigidBodyFlag.RBF_STATIC);
                    Physics.IsPhantom = true;
                    Physics.CreateFromCollisionObject(detectorShape, matrix.Translation, world, null, MyPhysics.CollisionLayers.ObjectDetectionCollisionLayer);
                    Physics.Enabled = IsWorking;
                    Physics.RigidBody.ContactPointCallbackEnabled = true;
                    detectorShape.Base.RemoveReference();

                    break;
                }
            }
        }
开发者ID:2asoft,项目名称:SpaceEngineers,代码行数:29,代码来源:MyShipMergeBlock.cs

示例4: InitDeadBodyPhysics

        private void InitDeadBodyPhysics()
        {
            Vector3 velocity = Vector3.Zero;

            RadioBroadcaster.BroadcastRadius = 5;

            if (Physics != null)
            {
                velocity = Physics.LinearVelocity;

                Physics.Enabled = false;
                Physics.Close();
                Physics = null;
            }

            //if (Physics == null)
            {
                var massProperties = new HkMassProperties();
                massProperties.Mass = 500;

                HkShape shape;
                // CH: Need to rethink this. It does not belong here, but I don't want to add "DeadCharacterBodyCenterOfMass" to the character definition either...
                // MZ: See ticket "Correct dying for characters", https://app.asana.com/0/64822442925263/75411538582998
                //     dead body shape can now be specified in character's SBC
                if (Definition.DeadBodyShape != null)
                {
                    HkBoxShape bshape = new HkBoxShape(PositionComp.LocalAABB.HalfExtents * Definition.DeadBodyShape.BoxShapeScale);
                    massProperties = HkInertiaTensorComputer.ComputeBoxVolumeMassProperties(bshape.HalfExtents, massProperties.Mass);
                    massProperties.CenterOfMass = bshape.HalfExtents * Definition.DeadBodyShape.RelativeCenterOfMass;
                    shape = bshape;

                    Physics = new MyPhysicsBody(this, RigidBodyFlag.RBF_DEFAULT);
                    Vector3D offset = PositionComp.LocalAABB.HalfExtents * Definition.DeadBodyShape.RelativeShapeTranslation;
                    MatrixD pos = MatrixD.CreateTranslation(offset);
                    Physics.CreateFromCollisionObject(shape, PositionComp.LocalVolume.Center + offset, pos, massProperties, MyPhysics.CollisionLayers.FloatingObjectCollisionLayer);
                    Physics.Friction = Definition.DeadBodyShape.Friction;
                    Physics.RigidBody.MaxAngularVelocity = MathHelper.PiOver2;
                    Physics.LinearVelocity = velocity;
                    shape.RemoveReference();

                    Physics.Enabled = true;
                }
                else // no special definition => use AABB
                {
                    HkBoxShape bshape = new HkBoxShape(PositionComp.LocalAABB.HalfExtents);
                    massProperties = HkInertiaTensorComputer.ComputeBoxVolumeMassProperties(bshape.HalfExtents, massProperties.Mass);
                    massProperties.CenterOfMass = new Vector3(bshape.HalfExtents.X, 0, 0);
                    shape = bshape;

                    Physics = new MyPhysicsBody(this, RigidBodyFlag.RBF_DEFAULT);
                    Physics.CreateFromCollisionObject(shape, PositionComp.LocalVolume.Center, MatrixD.Identity, massProperties, MyPhysics.CollisionLayers.FloatingObjectCollisionLayer);
                    Physics.Friction = 0.5f;
                    Physics.RigidBody.MaxAngularVelocity = MathHelper.PiOver2;
                    Physics.LinearVelocity = velocity;
                    shape.RemoveReference();

                    Physics.Enabled = true;
                }
            }

            NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME;
        }
开发者ID:ChristianHeinz71,项目名称:SpaceEngineers,代码行数:62,代码来源:MyCharacter.cs

示例5: PrepareItemsPhysics

        /// <summary>
        /// Prepares data for renderer and physics. Must be called after all items has been added.
        /// </summary>
      
        private void PrepareItemsPhysics(HkStaticCompoundShape sectorRootShape, ref BoundingBoxD aabbWorld, Dictionary<MyStringHash, HkShape> subtypeIdToShape)
        {
            foreach (var item in m_itemsData)
            {
                if (!item.Value.Enabled)
                    continue;

                int physicsShapeInstanceId;
                MatrixD transform = item.Value.Transform.TransformMatrix;
                if (AddPhysicsShape(item.Value.SubtypeId, item.Value.Model, ref transform, sectorRootShape, subtypeIdToShape, out physicsShapeInstanceId))
                {
                    // Map to data index - note that itemData is added after this to its list!
                    m_physicsShapeInstanceIdToLocalId[physicsShapeInstanceId] = item.Value.Id;
                    m_localIdToPhysicsShapeInstanceId[item.Value.Id] = physicsShapeInstanceId;

                }
            }

            PositionComp.WorldAABB = aabbWorld;

            if (sectorRootShape.InstanceCount > 0)
            {
                Debug.Assert(m_physicsShapeInstanceIdToLocalId.Count > 0);

                Physics = new Sandbox.Engine.Physics.MyPhysicsBody(this, RigidBodyFlag.RBF_STATIC)
                {
                    MaterialType = m_definition.Material,
                    AngularDamping = MyPerGameSettings.DefaultAngularDamping,
                    LinearDamping = MyPerGameSettings.DefaultLinearDamping,
                    IsStaticForCluster = true,
                };

                sectorRootShape.Bake();
                HkMassProperties massProperties = new HkMassProperties();
                MatrixD matrix = MatrixD.CreateTranslation(CellsOffset);
                Physics.CreateFromCollisionObject((HkShape)sectorRootShape, Vector3.Zero, matrix, massProperties);

                Physics.ContactPointCallback += Physics_ContactPointCallback;
                Physics.RigidBody.ContactPointCallbackEnabled = true;

                Physics.Enabled = true;
            }           
        }
开发者ID:fluxit,项目名称:SpaceEngineers,代码行数:47,代码来源:MyEnvironmentItems.cs

示例6: InitInternal

        private void InitInternal()
        {
            base.Init(null, m_definition.Model, null, null);
            Render.ColorMaskHsv = m_definition.ColorHSV;
            Render.Transparency = 0.25f;
            Render.AddRenderObjects();

			List<MyTextureChange> textureChanges = new List<MyTextureChange>();
			textureChanges.Add(new MyTextureChange { TextureName = m_definition.ColorMetalTexture, MaterialSlot = "ColorMetalTexture" });
			textureChanges.Add(new MyTextureChange { TextureName = m_definition.AddMapsTexture, MaterialSlot = "AddMapsTexture" });

            VRageRender.MyRenderProxy.ChangeMaterialTexture(Render.RenderObjectIDs[0], "BotFlag", textureChanges); // TODO: change the material name

            m_localActivationMatrix = MatrixD.CreateScale(this.PositionComp.LocalAABB.HalfExtents * 2.0f) * MatrixD.CreateTranslation(this.PositionComp.LocalAABB.Center);

            var shape = new HkBoxShape(m_localActivationMatrix.Scale);
            Physics = new MyPhysicsBody(this, RigidBodyFlag.RBF_DISABLE_COLLISION_RESPONSE);
            Physics.CreateFromCollisionObject(shape, Vector3.Zero, WorldMatrix, null, MyPhysics.ObjectDetectionCollisionLayer);
            Physics.Enabled = true;

            Components.Add<MyPlaceArea>(new MySpherePlaceArea(10.0f, m_definition.Id.SubtypeId)); // TODO: Add radius to the definition

            MyHud.LocationMarkers.RegisterMarker(this, new MyHudEntityParams() {
                FlagsEnum = MyHudIndicatorFlagsEnum.SHOW_TEXT,
                Text = m_definition.DisplayNameEnum.HasValue ? MyTexts.Get(m_definition.DisplayNameEnum.Value) : new StringBuilder(),
                TargetMode = MyRelationsBetweenPlayerAndBlock.Neutral,
                MaxDistance = 200.0f,
                MustBeDirectlyVisible = true
            } );
        }
开发者ID:caomw,项目名称:SpaceEngineers,代码行数:30,代码来源:MyAreaMarker.cs

示例7: InitInternal

        private void InitInternal()
        {
            // TODO: This will be fixed and made much more simple once ore models are done
            // https://app.asana.com/0/6594565324126/10473934569658

            var physicalItem = MyDefinitionManager.Static.GetPhysicalItemDefinition(Item.Content);

            string model = physicalItem.Model;

            VoxelMaterial = null;
            float scale = 1.0f;

            if (Item.Content is MyObjectBuilder_Ore)
            {
                string oreSubTypeId = physicalItem.Id.SubtypeId.ToString();
                foreach (var mat in MyDefinitionManager.Static.GetVoxelMaterialDefinitions())
                {
                    if (oreSubTypeId == mat.MinedOre)
                    {
                        VoxelMaterial = mat;
                        model = MyDebris.GetRandomDebrisVoxel();
                        scale = (float)Math.Pow((float)Item.Amount * physicalItem.Volume / MyDebris.VoxelDebrisModelVolume, 0.333f);
                        break;
                    }
                }

                scale = (float)Math.Pow((float)Item.Amount * physicalItem.Volume / MyDebris.VoxelDebrisModelVolume, 0.333f);
            }

            if (scale < 0.05f)
                Close();
            else if (scale < 0.15f)
                scale = 0.15f;

            FormatDisplayName(m_displayedText, Item);
            Init(m_displayedText, model, null, null, null);

            PositionComp.Scale = scale; // Must be set after init


            var massProperties = new HkMassProperties();
            HkShape shape = GetPhysicsShape(physicalItem.Mass * (float)Item.Amount, scale, out massProperties);
            var scaleMatrix = Matrix.CreateScale(scale);

            if (Physics != null)
                Physics.Close();
            Physics = new MyPhysicsBody(this, RigidBodyFlag.RBF_DEBRIS);

            if (VoxelMaterial != null)
            {
                HkConvexTransformShape transform = new HkConvexTransformShape((HkConvexShape)shape, ref scaleMatrix, HkReferencePolicy.None);
        
                Physics.CreateFromCollisionObject(transform, Vector3.Zero, MatrixD.Identity, massProperties, MyPhysics.FloatingObjectCollisionLayer);
               
                Physics.Enabled = true;
                transform.Base.RemoveReference();
            }
            else
            {
                Physics.CreateFromCollisionObject(shape, Vector3.Zero, MatrixD.Identity, massProperties, MyPhysics.FloatingObjectCollisionLayer);
                Physics.Enabled = true;
            }

            Physics.MaterialType = VoxelMaterial != null ? MyMaterialType.ROCK : MyMaterialType.METAL;
            Physics.PlayCollisionCueEnabled = true;

            NeedsUpdate = MyEntityUpdateEnum.EACH_FRAME;
        }
开发者ID:martejj,项目名称:SpaceEngineers,代码行数:68,代码来源:MyFloatingObject.cs

示例8: PrepareItemsPhysics

        /// <summary>
        /// Prepares data for renderer and physics. Must be called after all items has been added.
        /// </summary>
        public void PrepareItemsPhysics(HkStaticCompoundShape sectorRootShape, ref BoundingBoxD aabbWorld)
        {
            PositionComp.WorldAABB = aabbWorld;

            if (sectorRootShape.InstanceCount > 0)
            {
                Debug.Assert(m_physicsShapeInstanceIdToLocalId.Count > 0);

                Physics = new Sandbox.Engine.Physics.MyPhysicsBody(this, RigidBodyFlag.RBF_STATIC)
                {
                    MaterialType = m_definition.Material,
                    AngularDamping = MyPerGameSettings.DefaultAngularDamping,
                    LinearDamping = MyPerGameSettings.DefaultLinearDamping,
                    IsStaticForCluster = true,
                };

                sectorRootShape.Bake();
                HkMassProperties massProperties = new HkMassProperties();
                MatrixD matrix = MatrixD.CreateTranslation(CellsOffset);
                Physics.CreateFromCollisionObject((HkShape)sectorRootShape, Vector3.Zero, matrix, massProperties);

                Physics.ContactPointCallback += Physics_ContactPointCallback;
                Physics.RigidBody.ContactPointCallbackEnabled = true;

                sectorRootShape.Base.RemoveReference();

                Physics.Enabled = true;
            }
        }
开发者ID:Krulac,项目名称:SpaceEngineers,代码行数:32,代码来源:MyEnvironmentItems.cs

示例9: RefreshPhysicsBody

        private void RefreshPhysicsBody()
        {
            if (CubeGrid.CreatePhysics)
            {
                if (Physics != null)
                {
                    Physics.Close();
                }

                var detectorShape = new HkSphereShape(CubeGrid.GridSize * 0.5f);
                var massProperties = HkInertiaTensorComputer.ComputeSphereVolumeMassProperties(detectorShape.Radius, VirtualMass != 0 ? VirtualMass : 0.01f);
                Physics = new Sandbox.Engine.Physics.MyPhysicsBody(this, RigidBodyFlag.RBF_KEYFRAMED_REPORTING);
                Physics.IsPhantom = false;
                Physics.CreateFromCollisionObject(detectorShape, Vector3.Zero, WorldMatrix, massProperties, MyPhysics.CollisionLayers.VirtualMassLayer);
                UpdateIsWorking();
                Physics.Enabled = IsWorking && CubeGrid.Physics != null && CubeGrid.Physics.Enabled;

                Physics.RigidBody.Activate();
                detectorShape.Base.RemoveReference();

                if (CubeGrid != null && CubeGrid.Physics != null && !CubeGrid.IsStatic)
                    CubeGrid.Physics.UpdateMass();
            }
        }
开发者ID:liiir1985,项目名称:SpaceEngineers,代码行数:24,代码来源:MySpaceBall.cs

示例10: Init


//.........这里部分代码省略.........
            {
                var child = m_children[i];
                Func<MyObjectBuilder_FracturedPiece.Shape, bool> x = s => s.Name == child.ShapeName;
                var result = m_shapes.Where(x);
                if (result.Count() > 0)
                {
                    var found = result.First();
                    var m = Matrix.CreateFromQuaternion(found.Orientation);
                    if (!offset.HasValue && found.Name == m_shapes[0].Name)
                    {
                        offset = child.GetTransform().Translation;
                        shapeAtZero = m_shapeInfos.Count;
                    }
                    m.Translation = child.GetTransform().Translation;
                    var si = new HkdShapeInstanceInfo(child.Shape.Clone(), m);
                    if(found.Fixed)
                        si.Shape.SetFlagRecursively(HkdBreakableShape.Flags.IS_FIXED);
                    m_shapeInfos.Add(si);
                    m_shapes.Remove(found);
                }
                else
                {
                    child.GetChildren(m_children);
                }
            }

            if (m_shapeInfos.Count == 0)
            {
                List<string> shapesToLoad = new List<string>();
                foreach (var obShape in ob.Shapes)
                    shapesToLoad.Add(obShape.Name);

                var shapesStr = shapesToLoad.Aggregate((str1, str2) => str1 + ", " + str2);
                var blocksStr = OriginalBlocks.Aggregate("", (str, defId) => str + ", " + defId.ToString());
                var failMsg = "No relevant shape was found for fractured piece. It was probably reexported and names changed. Shapes: " + shapesStr + ". Original blocks: " + shapesStr;

                Debug.Fail(failMsg);
                //HkdShapeInstanceInfo si = new HkdShapeInstanceInfo(new HkdBreakableShape((HkShape)new HkBoxShape(Vector3.One)), Matrix.Identity);
                //m_shapeInfos.Add(si);
                throw new Exception(failMsg);
            }

            if (offset.HasValue)
            {
                for (int i = 0; i < m_shapeInfos.Count; i++)
                {
                    var m = m_shapeInfos[i].GetTransform();
                    m.Translation -= offset.Value;
                    m_shapeInfos[i].SetTransform(ref m);
                }
                {
                    var m = m_shapeInfos[shapeAtZero].GetTransform();
                    m.Translation = Vector3.Zero;
                    m_shapeInfos[shapeAtZero].SetTransform(ref m);
                }
            }

            if (m_shapeInfos.Count > 0)
            {
                if (m_shapeInfos.Count == 1)
                    Shape = m_shapeInfos[0].Shape;
                else
                {
                    Shape = new HkdCompoundBreakableShape(null, m_shapeInfos);
                    ((HkdCompoundBreakableShape)Shape).RecalcMassPropsFromChildren();
                }
                Shape.SetStrenght(MyDestructionConstants.STRENGTH);
                var mp = new HkMassProperties();
                Shape.BuildMassProperties(ref mp);
                Shape.SetChildrenParent(Shape);
                Physics = new MyPhysicsBody(this, RigidBodyFlag.RBF_DEBRIS);
                Physics.CanUpdateAccelerations = true;
                Physics.InitialSolverDeactivation = HkSolverDeactivation.High;
                Physics.CreateFromCollisionObject(Shape.GetShape(), Vector3.Zero, PositionComp.WorldMatrix, mp);
                Physics.BreakableBody = new HkdBreakableBody(Shape, Physics.RigidBody, null, (Matrix)PositionComp.WorldMatrix);
                Physics.BreakableBody.AfterReplaceBody += Physics.FracturedBody_AfterReplaceBody;

                if (OriginalBlocks.Count > 0)
                {
                    MyPhysicalModelDefinition def;
                    if (MyDefinitionManager.Static.TryGetDefinition<MyPhysicalModelDefinition>(OriginalBlocks[0], out def))
                        Physics.MaterialType = def.PhysicalMaterial.Id.SubtypeId;
                }


                var rigidBody = Physics.RigidBody;
                bool isFixed = MyDestructionHelper.IsFixed(Physics.BreakableBody.BreakableShape);
                if (isFixed)
                {
                    rigidBody.UpdateMotionType(HkMotionType.Fixed);
                    rigidBody.LinearVelocity = Vector3.Zero;
                    rigidBody.AngularVelocity = Vector3.Zero;
                }


                Physics.Enabled = true;
            }
            m_children.Clear();
            m_shapeInfos.Clear();
        }
开发者ID:2asoft,项目名称:SpaceEngineers,代码行数:101,代码来源:MyFracturedPiece.cs

示例11: InitInternal

        private void InitInternal()
        {
            // TODO: This will be fixed and made much more simple once ore models are done
            // https://app.asana.com/0/6594565324126/10473934569658

            var itemDefinition = MyDefinitionManager.Static.GetPhysicalItemDefinition(Item.Content);

            m_health = itemDefinition.Health;

            // Setting voxel material (if applicable)
            VoxelMaterial = null;
            if (itemDefinition.VoxelMaterial != MyStringHash.NullOrEmpty)
            {
                VoxelMaterial = MyDefinitionManager.Static.GetVoxelMaterialDefinition(itemDefinition.VoxelMaterial.String);
            }
            else if (Item.Content is MyObjectBuilder_Ore)
            {
                string oreSubTypeId = itemDefinition.Id.SubtypeName;
                string materialName = (Item.Content as MyObjectBuilder_Ore).GetMaterialName();
                bool hasMaterialName = (Item.Content as MyObjectBuilder_Ore).HasMaterialName();

                foreach (var mat in MyDefinitionManager.Static.GetVoxelMaterialDefinitions())
                {
                    if ((hasMaterialName && materialName == mat.Id.SubtypeName) || (hasMaterialName == false && oreSubTypeId == mat.MinedOre))
                    {
                        VoxelMaterial = mat;
                        break;
                    }
                }
            }

            // Setting the item's model
            string model = itemDefinition.Model;
            if (itemDefinition.HasModelVariants)
            {
                int modelNum = itemDefinition.Models.Length;
                Debug.Assert(m_modelVariant >= 0 && m_modelVariant < modelNum, "Model variant overflow. This can happen if model variants changed");
                m_modelVariant = m_modelVariant % modelNum;

                model = itemDefinition.Models[m_modelVariant];
            }
            else if (Item.Content is MyObjectBuilder_Ore && VoxelMaterial != null)
            {
                // Only ores without found voxel material use the defined model (otherwise, the scrap metal does not work)
                model = MyDebris.GetRandomDebrisVoxel();
            }

            // Setting the scale
            float scale = this.Item.Scale;
            if (Item.Content is MyObjectBuilder_Ore)
            {
                scale *= (float)Math.Pow((float)Item.Amount * itemDefinition.Volume / MyDebris.VoxelDebrisModelVolume, 0.333f);
            }
            else
            {
                scale *= (float)Math.Pow(itemDefinition.Volume / itemDefinition.ModelVolume, 0.333f);
            }
            if (scale < 0.05f)
                Close();
            else if (scale < 0.15f)
                scale = 0.15f;

            FormatDisplayName(m_displayedText, Item);
            Debug.Assert(model != null, "Floating object model is null");
            Init(m_displayedText, model, null, null, null);

            PositionComp.Scale = scale; // Must be set after init

            var massProperties = new HkMassProperties();
            var mass = MyPerGameSettings.Destruction ? MyDestructionHelper.MassToHavok(itemDefinition.Mass) : itemDefinition.Mass;
            mass = mass * (float)Item.Amount;

            HkShape shape = GetPhysicsShape(mass, scale, out massProperties);
            var scaleMatrix = Matrix.CreateScale(scale);

            if (Physics != null)
                Physics.Close();
            Physics = new MyPhysicsBody(this, RigidBodyFlag.RBF_DEBRIS);

            int layer = mass > MyPerGameSettings.MinimumLargeShipCollidableMass ? MyPhysics.CollisionLayers.FloatingObjectCollisionLayer : MyPhysics.CollisionLayers.LightFloatingObjectCollisionLayer;

            if (VoxelMaterial != null || (shape.IsConvex && scale != 1f))
            {
                HkConvexTransformShape transform = new HkConvexTransformShape((HkConvexShape)shape, ref scaleMatrix, HkReferencePolicy.None);

                Physics.CreateFromCollisionObject(transform, Vector3.Zero, MatrixD.Identity, massProperties, layer);

                Physics.Enabled = true;
                transform.Base.RemoveReference();
            }
            else
            {
                Physics.CreateFromCollisionObject(shape, Vector3.Zero, MatrixD.Identity, massProperties, layer);
                Physics.Enabled = true;
            }

            Physics.MaterialType = this.EvaluatePhysicsMaterial(itemDefinition.PhysicalMaterial);
            Physics.PlayCollisionCueEnabled = true;
            Physics.RigidBody.ContactSoundCallbackEnabled = true;
            m_easeCollisionForce = new HkEasePenetrationAction(Physics.RigidBody, 2f);
//.........这里部分代码省略.........
开发者ID:ChristianHeinz71,项目名称:SpaceEngineers,代码行数:101,代码来源:MyFloatingObject.cs

示例12: InitInternal

        private void InitInternal()
        {
            base.Init(null, m_definition.Model, null, null);
            Render.ColorMaskHsv = m_definition.ColorHSV;
            Render.Transparency = 0.25f;
            Render.AddRenderObjects();

			List<MyTextureChange> textureChanges = new List<MyTextureChange>();
			textureChanges.Add(new MyTextureChange { TextureName = m_definition.ColorMetalTexture, MaterialSlot = "ColorMetalTexture" });
			textureChanges.Add(new MyTextureChange { TextureName = m_definition.AddMapsTexture, MaterialSlot = "AddMapsTexture" });

            VRageRender.MyRenderProxy.ChangeMaterialTexture(Render.RenderObjectIDs[0], "BotFlag", textureChanges); // TODO: change the material name

            m_localActivationMatrix = MatrixD.CreateScale(this.PositionComp.LocalAABB.HalfExtents * 2.0f) * MatrixD.CreateTranslation(this.PositionComp.LocalAABB.Center);

            var shape = new HkBoxShape(m_localActivationMatrix.Scale);
            var physicsBody = new MyPhysicsBody(this, RigidBodyFlag.RBF_DISABLE_COLLISION_RESPONSE);
            Physics = physicsBody;
            physicsBody.CreateFromCollisionObject(shape, Vector3.Zero, WorldMatrix, null, MyPhysics.CollisionLayers.ObjectDetectionCollisionLayer);
            physicsBody.Enabled = true;

            Components.Add<MyPlaceArea>(new MySpherePlaceArea(10.0f, m_definition.Id.SubtypeId)); // TODO: Add radius to the definition

			AddHudMarker();
        }
开发者ID:stanhebben,项目名称:SpaceEngineers,代码行数:25,代码来源:MyAreaMarker.cs

示例13: PrepareItems

        /// <summary>
        /// Prepares data for renderer and physics. Must be called after all items has been added.
        /// </summary>
        public void PrepareItems(HkStaticCompoundShape sectorRootShape, ref BoundingBoxD aabbWorld)
        {
            PositionComp.LocalAABB = (BoundingBox)aabbWorld;

            if (sectorRootShape.InstanceCount > 0)
            {
                Debug.Assert(m_physicsShapeInstanceIdToLocalId.Count > 0);

                Physics = new Sandbox.Engine.Physics.MyPhysicsBody(this, RigidBodyFlag.RBF_STATIC)
                {
                    MaterialType = m_definition.Material,
                    AngularDamping = MyPerGameSettings.DefaultAngularDamping,
                    LinearDamping = MyPerGameSettings.DefaultLinearDamping,
                    IsStaticForCluster = true,
                };

                sectorRootShape.Bake();
                HkMassProperties massProperties = new HkMassProperties();
                Physics.CreateFromCollisionObject((HkShape)sectorRootShape, Vector3.Zero, WorldMatrix, massProperties);
                if (Sandbox.Game.MyPerGameSettings.Destruction)
                {
                    Physics.ContactPointCallback += Physics_ContactPointCallback;
                    Physics.RigidBody.ContactPointCallbackEnabled = true;
                }
                sectorRootShape.Base.RemoveReference();

                Physics.Enabled = true;
            }

            foreach (var pair in m_sectors)
            {
                pair.Value.UpdateRenderInstanceData();
            }

            foreach (var pair in m_sectors)
            {
                pair.Value.UpdateRenderEntitiesData(WorldMatrix, m_subtypeToModel);
            }
        }
开发者ID:caomw,项目名称:SpaceEngineers,代码行数:42,代码来源:MyEnvironmentItems.cs

示例14: InitSubpartsPhysics

        private void InitSubpartsPhysics()
        {
            var subpart = m_subpart1;
            if (subpart == null || CubeGrid.Physics == null)
                return;
            m_subpartPhysics = new MyPhysicsBody(this, CubeGrid.IsStatic ? RigidBodyFlag.RBF_STATIC : (CubeGrid.GridSizeEnum == MyCubeSize.Large ? RigidBodyFlag.RBF_DOUBLED_KINEMATIC : RigidBodyFlag.RBF_DEFAULT));
            const float threshold = 0.11f; // Must be bigger than 2x convex radius
            HkCylinderShape shape = new HkCylinderShape(new Vector3(0, -2, 0), new Vector3(0, 2, 0), CubeGrid.GridSize / 2 - threshold, 0.05f);
            var mass = HkInertiaTensorComputer.ComputeCylinderVolumeMassProperties(new Vector3(0, -2, 0), new Vector3(0, 2, 0), CubeGrid.GridSize / 2, 40.0f * CubeGrid.GridSize);
            mass.Mass = BlockDefinition.Mass;
            m_subpartPhysics.CreateFromCollisionObject(shape, Vector3.Zero, subpart.WorldMatrix, mass);
            m_subpartPhysics.RigidBody.Layer = CubeGrid.Physics.RigidBody.Layer;
            var info = HkGroupFilter.CalcFilterInfo(m_subpartPhysics.RigidBody.Layer, CubeGrid.Physics.HavokCollisionSystemID, 1, 1);
            m_subpartPhysics.RigidBody.SetCollisionFilterInfo(info);
            shape.Base.RemoveReference();
            if (m_subpartPhysics.RigidBody2 != null)
                m_subpartPhysics.RigidBody2.Layer = MyPhysics.CollisionLayers.KinematicDoubledCollisionLayer;

            CreateSubpartsConstraint(subpart);

            m_posChanged = true;
        }
开发者ID:Furt,项目名称:SpaceEngineers,代码行数:22,代码来源:MyPistonBase.cs

示例15: Init


//.........这里部分代码省略.........
                if (MyModels.GetModelOnlyData(model).HavokBreakableShapes == null)
                {
                    MyDestructionData.Static.LoadModelDestruction(mdef, false, Vector3.One);
                }
                var shape = MyModels.GetModelOnlyData(model).HavokBreakableShapes[0];
                var si = new HkdShapeInstanceInfo(shape, null, null);
                m_children.Add(si);
                shape.GetChildren(m_children);
                OriginalBlocks.Add(def);
            }
            m_shapes.AddRange(ob.Shapes);

            Vector3? offset = null;
            int shapeAtZero = 0;
            for (int i = 0; i < m_children.Count; i++)
            {
                var child = m_children[i];
                Func<MyObjectBuilder_FracturedPiece.Shape, bool> x = s => s.Name == child.ShapeName;
                var result = m_shapes.Where(x);
                if (result.Count() > 0)
                {
                    var found = result.First();
                    var m = Matrix.CreateFromQuaternion(found.Orientation);
                    if (!offset.HasValue && found.Name == m_shapes[0].Name)
                    {
                        offset = child.GetTransform().Translation;
                        shapeAtZero = m_shapeInfos.Count;
                    }
                    m.Translation = child.GetTransform().Translation;
                    var si = new HkdShapeInstanceInfo(child.Shape.Clone(), m);
                    if(found.Fixed)
                        si.Shape.SetFlagRecursively(HkdBreakableShape.Flags.IS_FIXED);
                    m_shapeInfos.Add(si);
                    m_shapes.Remove(found);
                }
                else
                {
                    child.GetChildren(m_children);
                }
            }

            if (m_shapeInfos.Count == 0)
            {
                Debug.Fail("No relevant shape was found for fractured piece. It was probably reexported and names changed.");
                //HkdShapeInstanceInfo si = new HkdShapeInstanceInfo(new HkdBreakableShape((HkShape)new HkBoxShape(Vector3.One)), Matrix.Identity);
                //m_shapeInfos.Add(si);
                throw new Exception("No relevant shape was found for fractured piece. It was probably reexported and names changed.");
            }

            if (offset.HasValue)
            {
                for (int i = 0; i < m_shapeInfos.Count; i++)
                {
                    var m = m_shapeInfos[i].GetTransform();
                    m.Translation -= offset.Value;
                    m_shapeInfos[i].SetTransform(ref m);
                }
                {
                    var m = m_shapeInfos[shapeAtZero].GetTransform();
                    m.Translation = Vector3.Zero;
                    m_shapeInfos[shapeAtZero].SetTransform(ref m);
                }
            }

            if (m_shapeInfos.Count > 0)
            {
                if (m_shapeInfos.Count == 1)
                    Shape = m_shapeInfos[0].Shape;
                else
                {
                    Shape = new HkdCompoundBreakableShape(null, m_shapeInfos);
                    ((HkdCompoundBreakableShape)Shape).RecalcMassPropsFromChildren();
                }
                Shape.SetStrenght(MyDestructionConstants.STRENGTH);
                var mp = new HkMassProperties();
                Shape.BuildMassProperties(ref mp);
                Shape.SetChildrenParent(Shape);
                Physics = new MyPhysicsBody(this, RigidBodyFlag.RBF_DEBRIS);
                Physics.InitialSolverDeactivation = HkSolverDeactivation.Medium;
                Physics.CreateFromCollisionObject(Shape.GetShape(), Vector3.Zero, PositionComp.WorldMatrix, mp);
                Physics.BreakableBody = new HkdBreakableBody(Shape, Physics.RigidBody, MyPhysics.SingleWorld.DestructionWorld, (Matrix)PositionComp.WorldMatrix);
                Physics.BreakableBody.AfterReplaceBody += Physics.FracturedBody_AfterReplaceBody;

                var rigidBody = Physics.RigidBody;
                bool isFixed = MyDestructionHelper.IsFixed(Physics.BreakableBody.BreakableShape);
                if (isFixed)
                {
                    rigidBody.UpdateMotionType(HkMotionType.Fixed);
                    rigidBody.LinearVelocity = Vector3.Zero;
                    rigidBody.AngularVelocity = Vector3.Zero;
                }

                //Cannot set keyframed in constructor, because Havok does not allow set CoM on kinematic object..
                if(!Sync.IsServer)
                    Physics.RigidBody.UpdateMotionType(HkMotionType.Keyframed);
                Physics.Enabled = true;
            }
            m_children.Clear();
            m_shapeInfos.Clear();
        }
开发者ID:leandro1129,项目名称:SpaceEngineers,代码行数:101,代码来源:MyFracturedPiece.cs


注:本文中的Sandbox.Engine.Physics.MyPhysicsBody.CreateFromCollisionObject方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。