Skip to main content

Space Engineers: Ore Dispenser Example

Submitted by admin on Tue, 05/10/2016 - 17:33

The official example for an Ore Dispenser is not up to date, so here is a working version of it. Note that it adds functionality to the existing sensor in the game instead of creating a new one.

If you want to see the original tutorial (it's a video), you can find it here: original video. Most of the stuff in it is still correct, though you may want to use Visual Studio 2015 Community Edition instead. Also the DLL VRage.Common.dll no longer exists.

using Sandbox.Common.Components;  
using Sandbox.Common.ObjectBuilders;  
using Sandbox.Common.ObjectBuilders.VRageData;  
using Sandbox.ModAPI;  
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
using VRageMath;

namespace MyTestMod  
{
    [MyEntityComponentDescriptor(typeof(MyObjectBuilder_SensorBlock))]
    public class TestSensor : MyGameLogicComponent
    {

        private IMySensorBlock _sensor;

        public override void Init(MyObjectBuilder_EntityBase objectBuilder)
        {
            _sensor = (IMySensorBlock) Entity;
            _sensor.StateChanged += Sensor_StateChanged;
        }

        public override void Close()
        {
            _sensor.StateChanged -= Sensor_StateChanged;
        }

        private void Sensor_StateChanged(bool obj)
        {
            var floatingBuilder = new MyObjectBuilder_FloatingObject();
            floatingBuilder.PersistentFlags = MyPersistentEntityFlags2.InScene;
            floatingBuilder.Item = new MyObjectBuilder_InventoryItem
            {
                Amount = 100,
                Content = new MyObjectBuilder_Ore { SubtypeName = "Stone" }
            };
            floatingBuilder.PositionAndOrientation = new MyPositionAndOrientation
            {
                Position = _sensor.WorldMatrix.Translation + _sensor.WorldMatrix.Forward * 1.5f,
                Forward = ToSerializeableVector3(_sensor.WorldMatrix.Forward),
                Up = ToSerializeableVector3(_sensor.WorldMatrix.Up),
            };
            var floatingObject = MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(floatingBuilder);

        }

        public static SerializableVector3 ToSerializeableVector3(Vector3D vector3d)
        {
            return new SerializableVector3((float)vector3d.X, (float)vector3d.Y, (float)vector3d.Z);
        }

        public override MyObjectBuilder_EntityBase GetObjectBuilder(bool copy = false)
        {
            return _sensor.GetObjectBuilder();
        }

    }
}