Example #1
0
        public EntityBeliefs(Beliefs beliefs, Entity ent)
        {
            Beliefs = beliefs;
            Entity = ent;

            Type = ent.HasComponent<Survivor>() ? EntityType.Survivor
                : ent.HasComponent<Zombie>() ? EntityType.Zombie
                : ent.HasComponent<WoodPile>() ? EntityType.PlankPile
                : ent.HasComponent<WoodenBreakable>() ? EntityType.PlankSource
                : EntityType.Other;

            Update();
        }
Example #2
0
 public static void DeleteLocalString(Entity entity, string key)
 {
     if (!entity.HasComponent<LocalData>()) return;
     LocalData data = entity.GetComponent<LocalData>();
     if (data.LocalStrings.ContainsKey(key))
         data.LocalStrings.Remove(key);
 }
        public override void Process(Entity e)
        {
            if (!e.HasComponent<FadingText>())
                return;

            e.GetComponent<FadingText>().Draw(spriteBatch, spriteFont);
        }
 public override void OnAdded(Entity entity)
 {
     if (entity.HasComponent<ShipComponent>())
     {
         entity.AddComponent(new SpatialTokenComponent { Token = Ships.AllocateToken(entity) });
     }
 }
 private void OnRemoveEntity(Entity entity)
 {
     if (entity.HasComponent<ShipComponent>())
     {
         var token = entity.GetComponent<SpatialTokenComponent>().Token;
         token.Dispose();
     }
 }
 public override void OnUse(Entity targetEnt)
 {
     if (targetEnt.HasComponent(ComponentFamily.StatusEffects)) //Use component messages instead.
     {
         var statComp = (StatusEffectComp) targetEnt.GetComponent(ComponentFamily.StatusEffects);
         statComp.AddEffect("Bleeding", 10);
         parent.StartCooldown(this);
     }
 }
Example #7
0
 public override void Process(Entity entity)
 {
     if (!entity.HasComponent<TimeStamp>())
     {
         Int32 unixTimestamp = (Int32)(DateTime.Now.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
         entity.AddComponent(new TimeStamp(unixTimestamp));
         entity.Refresh();
     }
 }
Example #8
0
        public override void Process(Entity e)
        {
            if (!e.HasComponent<AI>())
                return;

            AI ai = e.GetComponent<AI>();

            bool behavior;

            if (ai.Target != null)
            {
                if (World.EntityManager.GetEntity((ai.Target.UserData as Entity).Id) == null)
                    ai.Target = null;
                else if (!(!ai.Recalculate && ai.Calculated) && ai.Target != null && (ai.Target.UserData as Entity) != null && !(behavior = ai.Behavior(ai.Target))) //Run ai behavior, if behavior returns true look for new target.
                {
                    ai.Calculated = true;

                    if (ai.Target == null && e.Group != "Players" && e.Group != "Structures" && !e.Tag.Contains("Cannon"))
                    {
                        if (e.HasComponent<Health>())
                            e.GetComponent<Health>().SetHealth(null, 0);
                        else
                            e.Delete();
                    }

                    return;
                }
            }

            ai.Calculated = true;
            ai.Target = _FindNewTarget(ai, e.GetComponent<Body>());

            if (ai.Target == null && e.Group != "Players" && e.Group != "Structures" && !e.Tag.Contains("Boss"))
            {
                if (e.HasComponent<Health>())
                    e.GetComponent<Health>().SetHealth(null, 0);
                else
                    e.Delete();
            }
            else if (ai.Target == null && e.Group == "Players")
                ai.Behavior(null);

            e.Refresh();
        }
        private void AddTooltipRequestComponent(Entity entity, GameObject tooltipPrefab, long idOfRequestedUser, InteractionSource interactionSource, long sourceId)
        {
            TooltipDataRequestComponent component = !entity.HasComponent <TooltipDataRequestComponent>() ? entity.AddComponentAndGetInstance <TooltipDataRequestComponent>() : entity.GetComponent <TooltipDataRequestComponent>();

            component.MousePosition        = Input.mousePosition;
            component.TooltipPrefab        = tooltipPrefab;
            component.InteractionSource    = interactionSource;
            component.idOfRequestedUser    = idOfRequestedUser;
            component.InteractableSourceId = sourceId;
        }
Example #10
0
        public override bool Matches(Entity entity)
        {
            for (int i = 0, indicesLength = indices.Length; i < indicesLength; i++) {
                if (entity.HasComponent(indices[i])) {
                    return false;
                }
            }

            return true;
        }
Example #11
0
 public void EnslaveMovementAndSprite(Entity master, Entity slave)
 {
     slave.RemoveComponent(ComponentFamily.Mover);
     slave.AddComponent(ComponentFamily.Mover, EntityManager.ComponentFactory.GetComponent <SlaveMoverComponent>());
     slave.GetComponent <SlaveMoverComponent>(ComponentFamily.Mover).Attach(master);
     if (slave.HasComponent(ComponentFamily.Renderable) && master.HasComponent(ComponentFamily.Renderable))
     {
         slave.GetComponent <IRenderableComponent>(ComponentFamily.Renderable).SetMaster(master);
     }
 }
Example #12
0
 public override void Init(MyObjectBuilder_EntityBase objectBuilder)
 {
     NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME;
     if (!Entity.HasComponent <MyModStorageComponent>())
     {
         Entity.Storage = new MyModStorageComponent();
         Entity.Components.Add(Entity.Storage);
         RadarCore.DebugWrite($"{Block.CustomName}.Init()", "Block doesn't have a Storage component!", IsExcessive: false);
     }
 }
 public override void EntityAdded(Entity entityWrapper)
 {
     if (entityWrapper.HasComponent <Monster>())
     {
         lock (LoadedMonstersLock)
         {
             LoadedMonsters.Add(entityWrapper);
         }
     }
 }
Example #14
0
    public void HasComponent_FindsComponent()
    {
      var entity = new Entity(1);
      var component = new ComponentStub(entity);
      entity.AddComponent(component);

      var result = entity.HasComponent<ComponentStub>();

      Assert.IsTrue(result);
    }
Example #15
0
 void HandleBounceCollision(Entity edge, Entity bouncer)
 {
     if (edge.HasComponent <EdgeComponent>())
     {
         if (bouncer.HasComponent <ProjectileComponent>() && bouncer.HasComponent <MovementComponent>())
         {
             EventManager.Instance.TriggerEvent(new ProjectileBouncedEvent(bouncer, bouncer.GetComponent <TransformComponent>().Position));
         }
         if (bouncer != null && bouncer.HasComponent <MovementComponent>())
         {
             Vector2 bounceDirection = bouncer.GetComponent <MovementComponent>().direction;
             bouncer.GetComponent <MovementComponent>().direction = getReflectionVector(
                 bounceDirection,
                 edge.GetComponent <EdgeComponent>().Normal
                 );
             Console.WriteLine("Collision with wall");
         }
     }
 }
        public void SetContainerItemImage(NodeAddedEvent e, GarageListContainerSimpleItemNode listItemNode)
        {
            Entity entity = Flow.Current.EntityRegistry.GetEntity(listItemNode.simpleContainerContentItem.MarketItemId);

            if (entity.HasComponent <ImageItemComponent>())
            {
                listItemNode.garageListItemContent.AddPreview(entity.GetComponent <ImageItemComponent>().SpriteUid);
            }
            listItemNode.garageListItemContent.Header.text = ((listItemNode.simpleContainerContentItem.NameLokalizationKey == null) || !listItemNode.descriptionBundleItem.Names.ContainsKey(listItemNode.simpleContainerContentItem.NameLokalizationKey)) ? entity.GetComponent <DescriptionItemComponent>().Name : listItemNode.descriptionBundleItem.Names[listItemNode.simpleContainerContentItem.NameLokalizationKey];
        }
Example #17
0
        /// <summary>
        /// Returns a local number on an entity.
        /// </summary>
        /// <param name="entity">The entity to retrieve data from.</param>
        /// <param name="key">The key of the data to retrieve.</param>
        /// <returns>The data stored on the entity for the specified key.</returns>
        public float GetLocalNumber(Entity entity, string key)
        {
            if (!entity.HasComponent <LocalData>())
            {
                return(0.0f);
            }
            LocalData data = entity.GetComponent <LocalData>();

            return(data.LocalFloats.ContainsKey(key) ? data.LocalFloats[key] : 0.0f);
        }
Example #18
0
        /// <summary>
        /// Sets a local value on an entity.
        /// </summary>
        /// <param name="entity">The entity to store data on.</param>
        /// <param name="key">The unique key to store the data at.</param>
        /// <param name="value">The data to store on the entity.</param>
        public void SetLocalValue(Entity entity, string key, float value)
        {
            if (!entity.HasComponent <LocalData>())
            {
                return;
            }
            LocalData data = entity.GetComponent <LocalData>();

            data.LocalFloats[key] = value;
        }
Example #19
0
        /// <summary>
        /// Returns a local string on an entity.
        /// </summary>
        /// <param name="entity">The entity to retrieve data from.</param>
        /// <param name="key">The key of the data to retrieve.</param>
        /// <returns>The data stored on the entity for the specified key.</returns>
        public string GetLocalString(Entity entity, string key)
        {
            if (!entity.HasComponent <LocalData>())
            {
                return(string.Empty);
            }
            LocalData data = entity.GetComponent <LocalData>();

            return(data.LocalStrings.ContainsKey(key) ? data.LocalStrings[key] : string.Empty);
        }
Example #20
0
        public void should_return_true_when_entity_has_component()
        {
            var mockEventSystem = Substitute.For <IEventSystem>();
            var entity          = new Entity(1, mockEventSystem);
            var dummyComponent  = new TestComponentOne();

            entity.AddComponent(dummyComponent);

            Assert.That(entity.HasComponent <TestComponentOne>());
        }
        private bool CheckHandleWeaponIntersectionStatus(Entity weapon)
        {
            bool flag = weapon.HasComponent <WeaponUndergroundComponent>();

            if (flag)
            {
                StateUtils.SwitchEntityState <ShaftIdleStateComponent>(weapon, this.weaponStates);
            }
            return(flag);
        }
Example #22
0
        public static void SwitchEntityState(Entity entity, Component component, HashSet <Type> states)
        {
            Type targetState = component.GetType();

            RemoveNonStateComponents(entity, targetState, states);
            if (!entity.HasComponent(targetState))
            {
                entity.AddComponent(component);
            }
        }
Example #23
0
            public override void Update(float dt)
            {
                base.Update(dt);

                if (target != null)
                {
                    if (target.Done)
                    {
                        target = null;
                        return;
                    }

                    var dx = Self.DxTo(target);
                    var dy = Self.DyTo(target);
                    var d  = MathUtils.Distance(dx, dy);

                    if (d <= 32)
                    {
                        if (!target.HasComponent <OrbitGiverComponent>())
                        {
                            target.AddComponent(new OrbitGiverComponent());
                        }

                        target.GetComponent <OrbitGiverComponent>().AddOrbiter(Self);
                        Become <OrbitingState>();

                        return;
                    }

                    var body = Self.GetComponent <SensorBodyComponent>();
                    var s    = dt * 200;

                    body.Velocity += new Vector2(dx / d * s, dy / d * s);
                    return;
                }

                if (!searched)
                {
                    searched = true;
                    target   = Self.GetComponent <RoomComponent>().Room?.FindClosest(Self.Center, Tags.Mob, e => !e.HasComponent <OrbitalComponent>() && !(e is WallWalker || e is Boss));

                    if (target == null)
                    {
                        Self.Kill(Self);
                        // target = Self.GetComponent<RoomComponent>().Room?.FindClosest(Self.Center, Tags.Player);
                    }
                }

                if (T >= 1f && searched)
                {
                    searched = false;
                }

                // fixme: pursue first, make unhittable but autodying (add tag for autodeath)
            }
Example #24
0
        /* TODO
         * this gets us around the "force enable" issue but
         * we still may have a problem of garbage entities
         * because the entity gets added to the pool with or without awake being called
         */
        void Awake()
        {
            if (!Entity.HasComponent <ViewComponent> ())
            {
                var viewComponent = new ViewComponent();
                AddTransformToView(viewComponent);
                Entity.AddComponent(viewComponent);
            }
            else
            {
                AddTransformToView(Entity.GetComponent <ViewComponent> ());
            }

            for (var i = 0; i < ComponentTypes.Count(); i++)
            {
                var type = ComponentTypes[i].GetTypeWithAssembly();
                if (type == null)
                {
                    throw new Exception("Cannot resolve type for [" + ComponentTypes[i] + "]");
                }

                var component = (object)Activator.CreateInstance(type);
                JsonUtility.FromJsonOverwrite(ComponentData[i], component);
                Entity.AddComponent(component);
            }


            //for (var i = 0; i < Components.Count; i++)
            //{
            //             var component = Instantiate(Components[i]);
            //	Entity.AddComponent(component);
            //}

            foreach (var blueprint in Blueprints)
            {
                blueprint.Apply(this.Entity);
            }

            var monoBehaviours = GetComponents <Component>();

            foreach (var mb in monoBehaviours)
            {
                if (mb == null)
                {
                    Debug.LogWarning("Component on " + this.gameObject.name + " is null!");
                }
                else
                {
                    if (mb.GetType() != typeof(Transform) && mb.GetType() != typeof(EntityBehaviour))
                    {
                        Entity.AddComponent(mb);
                    }
                }
            }
        }
Example #25
0
        public CustomItem(ItemsOnGroundLabelElement item)
        {
            CompleteItem = item;
            Entity groundItem = item.ItemOnGround.GetComponent <WorldItem>().ItemEntity;

            GroundItem = groundItem;
            Path       = groundItem.Path;
            BaseItemType baseItemType = BasePlugin.API.GameController.Files.BaseItemTypes.Translate(Path);

            ClassName = baseItemType.ClassName;
            BaseName  = baseItemType.BaseName;
            if (groundItem.HasComponent <Quality>())
            {
                Quality quality = groundItem.GetComponent <Quality>();
                Quality = quality.ItemQuality;
            }

            if (groundItem.HasComponent <Base>())
            {
                Base @base = groundItem.GetComponent <Base>();
                IsElder  = @base.isElder;
                IsShaper = @base.isShaper;
            }

            if (groundItem.HasComponent <Mods>())
            {
                Mods mods = groundItem.GetComponent <Mods>();
                Rarity       = mods.ItemRarity;
                IsIdentified = mods.Identified;
                ItemLevel    = mods.ItemLevel;
            }

            if (groundItem.HasComponent <Sockets>())
            {
                Sockets sockets = groundItem.GetComponent <Sockets>();
                IsRGB       = sockets.IsRGB;
                Sockets     = sockets.NumberOfSockets;
                LargestLink = sockets.LargestLinkSize;
            }

            MapTier = groundItem.HasComponent <Map>() ? groundItem.GetComponent <Map>().Tier : 0;
        }
Example #26
0
 protected override void OnComponentInit(Entity entity)
 {
     // If we have a sprite renderer, we can default to the sprite ;)
     if (entity.HasComponent <SpriteRenderer>())
     {
         var spriteRenderer = entity.GetComponent <SpriteRenderer>();
         var textureSize    = spriteRenderer.Texture.Size.ToFloat();
         CreateRectCollider(new Vector2f(textureSize.X, textureSize.Y)); // Create a collider with the size of the sprite (ish)
         origin = -(textureSize / 2);
     }
 }
Example #27
0
 public PresetItem(string name, int level, string hullName, string turretName, long hullId, long weaponId, Entity presetEntity)
 {
     this.Name         = name;
     this.level        = level;
     this.presetEntity = presetEntity;
     this.hullName     = hullName;
     this.turretName   = turretName;
     this.hullId       = hullId;
     this.weaponId     = weaponId;
     this.isSelected   = presetEntity.HasComponent <SelectedPresetComponent>();
 }
Example #28
0
        public void TestMoveRandom()
        {
            IEntity entity = new Entity(null, Vector2.Zero, Vector2.Zero, false);
            var     moveRandomComponent = new MoveRandomComponent(entity);

            entity.Update();

            Assert.IsTrue(entity.HasComponent <MoveRandomComponent>());
            Assert.AreSame(moveRandomComponent, entity.GetComponent <MoveRandomComponent>());
            Assert.AreSame(entity, entity.GetComponent <MoveRandomComponent>().Parent);
        }
Example #29
0
 public void SetEntity(Entity entity)
 {
     if (entity.HasComponent <PositionComponent>())
     {
         _entity = entity;
     }
     else
     {
         throw new Exception("Tried to set camera's entity to one that doesn't have a PositionComponent");
     }
 }
Example #30
0
 public static Sprite GetIconSprite(Entity entity)
 {
     if(entity.HasComponent(ComponentFamily.Icon))
     {
         var icon = entity.GetComponent<IconComponent>(ComponentFamily.Icon).Icon;
         if (icon == null)
             return IoCManager.Resolve<IResourceManager>().GetNoSprite();
         return icon;
     }
     return IoCManager.Resolve<IResourceManager>().GetNoSprite();
 }
Example #31
0
        public static void RemoveComponent <T>(this Entity entity, bool ignoreNotExists = false) where T : IComponent
        {
            int index = ComponentIndex <T> .FindIn(entity.contextInfo);

            if (ignoreNotExists && !entity.HasComponent(index))
            {
                return;
            }

            entity.RemoveComponent(index);
        }
        public void TestCollision()
        {
            IEntity entity             = new Entity(null, Vector2.Zero, Vector2.Zero, false);
            var     collisionComponent = new CollisionComponent(entity);

            entity.Update();

            Assert.IsTrue(entity.HasComponent <CollisionComponent>());
            Assert.AreSame(collisionComponent, entity.GetComponent <CollisionComponent>());
            Assert.AreSame(entity, entity.GetComponent <CollisionComponent>().Parent);
        }
Example #33
0
        public void Test_NonexistantComponent_GenericHasComponentIsFalse()
        {
            // Arrange
            var entity = new Entity(new World());

            // Act
            var hasComponent = entity.HasComponent <Transform>();

            // Assert
            Assert.False(hasComponent);
        }
Example #34
0
        public static IComponent GetComponentByName(this Entity entity, string name)
        {
            var index = Array.FindIndex(GameComponentsLookup.componentNames,
                                        c => c == name);

            if (index == -1 || !entity.HasComponent(index))
            {
                return(null);
            }
            return(entity.GetComponent(index));
        }
Example #35
0
 void HandleCollisionStart(Entity playerShield, Entity enemy)
 {
     if (playerShield.HasComponent <PlayerShieldComponent>())
     {
         if (enemy.HasComponent <EnemyComponent>() && !enemy.HasComponent <ProjectileComponent>())
         {
             EventManager.Instance.QueueEvent(new CreateExplosionEvent(enemy.GetComponent <TransformComponent>().Position));
             Engine.DestroyEntity(enemy);
         }
     }
 }
Example #36
0
        public override void Process(Entity entity)
        {
            TextureComponent  tc = entity.GetComponent <TextureComponent>();
            PositionComponent pc = entity.GetComponent <PositionComponent>();
            RotationComponent rc = (entity.HasComponent <RotationComponent>()) ? entity.GetComponent <RotationComponent>() : new RotationComponent(0, 0, false);
            ShadowComponent   sc = (entity.HasComponent <ShadowComponent>()) ? entity.GetComponent <ShadowComponent>() : null;

            Rectangle sourceRect = ResourceManager.Instance.GetSpriteSheet(tc.Texture).GetSourceRect(tc.Position.X, tc.Position.Y);
            Rectangle destRect   = new Rectangle((int)pc.Position.X, (int)pc.Position.Y, sourceRect.Width, sourceRect.Height);
            Texture2D texture    = ResourceManager.Instance.GetSpriteSheet(tc.Texture).Texture;

            ScreenManager.Instance.SpriteBatch.Draw(texture, destRect, sourceRect, Color.White, MathHelper.ToRadians(rc.Angle), tc.Origin, SpriteEffects.None, 0f);

            //if (sc != null)
            //{
            //    Rectangle shadowSourceRect = ResourceManager.Instance.GetSpriteSheet(sc.Texture).GetSourceRect(sc.Position.X, sc.Position.Y);
            //    Texture2D shadowTexture = ResourceManager.Instance.GetSpriteSheet(sc.Texture).Texture;
            //    ScreenManager.Instance.SpriteBatch.Draw(shadowTexture, destRect, shadowSourceRect, Color.White, sc.Angle, sc.Origin, SpriteEffects.None, 0f);
            //}
        }
 void onEntityChanged(Entity e, int index, IComponent component)
 {
     if (!e.HasComponent(_debugIndex))
     {
         DestroyBehaviour();
     }
     else
     {
         updateName();
     }
 }
Example #38
0
        public void TestMethod1()
        {
            IEntity entity        = new Entity(null, Vector2.Zero, Vector2.Zero, false);
            var     healComponent = new HealComponent(entity);

            entity.Update();

            Assert.IsTrue(entity.HasComponent <HealComponent>());
            Assert.AreSame(healComponent, entity.GetComponent <HealComponent>());
            Assert.AreSame(entity, entity.GetComponent <HealComponent>().Parent);
        }
Example #39
0
 public static bool GetIsHostile(Entity entity)
 {
     try
     {
         return entity.HasComponent<Hostile>();
     }
     catch (Exception)
     {
         return false;
     }
 }
Example #40
0
 /// <summary>
 /// Returns true if entity is hostile, otherwise returns false.
 /// </summary>
 /// <param name="entity">The entity to check the hostility of</param>
 /// <returns>True if entity is hostile, False otherwise</returns>
 public bool GetIsHostile(Entity entity)
 {
     try
     {
         return(entity.HasComponent <Hostile>());
     }
     catch (Exception)
     {
         return(false);
     }
 }
Example #41
0
        public TComponent AddComponent <TComponent>() where TComponent : IComponent
        {
            if (Entity.HasComponent <TComponent>())
            {
                return(Entity.GetComponent <TComponent>());
            }
            TComponent component = (TComponent)_resolver.Container.Resolve(typeof(TComponent));

            Entity.AddComponent <TComponent>(component);
            return(component);
        }
Example #42
0
 public void HandleCollision(Entity entity, Entity other)
 {
     if (other.HasComponent<CollisionBehaviorComponent> ())
     {
         CollisionDispatcher dispatcher = other.GetComponent<CollisionBehaviorComponent> ()
             .Behavior as CollisionDispatcher;
         if (dispatcher != null)
         {
             dispatcher.DispatchCollision (this, other, entity);
         }
     }
 }
        public void SetMaster(Entity m)
        {
            if (!m.HasComponent(ComponentFamily.Renderable))
                return;
            var mastercompo = m.GetComponent<IRenderableComponent>(ComponentFamily.Renderable);
            //If there's no sprite component, then F**K IT
            if (mastercompo == null)
                return;

            mastercompo.AddSlave(this);
            master = mastercompo;
        }
Example #44
0
 /// <summary>
 /// Add a Modifier script to an Entity, based on a code block (delegate) and a VectorFunction
 /// </summary>
 /// <param name="e">Entity to add modifier script to</param>
 /// <param name="scriptCode">Code block (delegate) that is the script</param>
 /// <param name="func">Function whose value will be passed in ScriptContext.FunctionValue to script</param>
 /// <returns></returns>
 public static VectorModifierScript AddModifier(Entity e, VectorModifierDelegate scriptCode, IVectorFunction func)
 {
     if (!e.HasComponent<ScriptComp>())
     {
         e.AddComponent(new ScriptComp());
         e.Refresh();
     }
     var sc = e.GetComponent<ScriptComp>();
     var script = new VectorModifierScript(scriptCode, func);
     sc.Add(script);
     return script;
 }
        public override void Process(Entity e)
        {
            if (!e.HasComponent<FadingText>())
                return;

            FadingText f = e.GetComponent<FadingText>();

            f.Update(world.Delta);

            if (f.Fraction() <= 0)
            {
                e.Delete();
            }
        }
        public override void Process(Entity e)
        {
            #region Float Effect

            if (e.HasComponent<Body>())
            {
                Body b = e.GetComponent<Body>();

                if (ConvertUnits.ToDisplayUnits(b.Position.Y) >= _MaxH)
                    _Direction = -_Speed;
                if (ConvertUnits.ToDisplayUnits(b.Position.Y) <= 0)
                    _Direction = _Speed;

                b.Position += new Microsoft.Xna.Framework.Vector2(b.Position.X - _X, ConvertUnits.ToSimUnits(_Direction));
            }

            #endregion Float Effect
        }
Example #47
0
        public override void Process(Entity ship)
        {
            var shipComponent = ship.GetComponent<ShipComponent>();
            if (ship.HasComponent<RigidBodyComponent>())
            {
                var rigidBody = ship.GetComponent<RigidBodyComponent>();
                Vector2 linearForce = shipComponent.LinearThrustVector;
                if (linearForce.X > 0) linearForce.X *= shipComponent.Ship.Handling.ForwardForce;
                else linearForce.X *= shipComponent.Ship.Handling.ManeuverForce;
                linearForce.Y *= shipComponent.Ship.Handling.ManeuverForce;
                rigidBody.Body.ApplyForce(rigidBody.Body.GetWorldVector(linearForce), rigidBody.Body.WorldCenter);
                rigidBody.Body.ApplyTorque(shipComponent.AngularTorque * shipComponent.Ship.Handling.AngularTorque);
            }          
            UpdateThrusters(ship);

            shipComponent.AngularTorque = 0;
            shipComponent.LinearThrustVector = Vector2.Zero;
        }
        public override void Process(Entity e)
        {
            try
            {
                if (!e.HasComponent<Bullet>())
                    return;
            }
            catch
            {
                return;
            }

            Particle particle = particleMapper.Get(e);
            Bullet bullet = bulletMapper.Get(e);

            world.RayCast(
                delegate(Fixture fix, Vector2 point, Vector2 normal, float fraction) //On hit
                {
                    ++bullet.collisionChecked;
                    if (fix.Body.UserData is Entity)
                    {
                        if ((fix.Body.UserData as Entity).HasComponent<Health>()
                            && (fix.Body.UserData as Entity).Group == bullet.DamageGroup)
                        { //Do damage
                            (fix.Body.UserData as Entity).GetComponent<Health>().SetHealth(bullet.Firer,
                                (fix.Body.UserData as Entity).GetComponent<Health>().CurrentHealth - bullet.Damage);
                            e.Delete(); //Remove bullet

                            if (bullet.OnBulletHit != null)
                            {
                                //Do bullet effects here........... Maybe a call back?{
                                bullet.OnBulletHit(fix.Body.UserData as Entity);
                            }

                            if (!(fix.Body.UserData as Entity).HasComponent<Health>() || (fix.Body.UserData as Entity).GetComponent<Health>().IsAlive)
                                world.CreateEntity("Explosion", 0f, particle.Position, fix.Body.UserData, 1, fix.Body.LinearVelocity, fix.Body.UserData).Refresh();
                        }
                    }
                    return 0;
                }, particle.Position, particle.Position + particle.LinearVelocity * new Vector2(World.Delta * .001f));
        }
Example #49
0
        public override void Process(Entity entity)
        {
            Placement placement = placementMapper.Get(entity);
            Velocity velocity = velocityMapper.Get(entity);

            if (entity.HasComponent<Acceleration>()) {
                Acceleration acceleration = accelerationMapper.Get(entity);

                if (acceleration.Boost > 0.0f) {
                    velocity.Direction = velocity.Direction * velocity.Speed + acceleration.Direction * acceleration.Boost;

                    Vector2 normalized = Vector2.Normalize(velocity.Direction);
                    velocity.Speed = Math.Min(velocity.Direction.Length() / normalized.Length(), 10.0f);
                    velocity.Direction = normalized;
                }
            }

            placement.Coordinates += velocity.Direction * velocity.Speed;

            placement.X = this.ApplyRange(placement.X, this.graphicsDevice.Viewport.Width);
            placement.Y = this.ApplyRange(placement.Y, this.graphicsDevice.Viewport.Height);
        }
Example #50
0
 public static void SetVelocityY(Entity entity, float y)
 {
     if (entity.HasComponent<Velocity>())
     {
         entity.GetComponent<Velocity>().Y = y;
     }
 }
Example #51
0
 public static void SetVelocityX(Entity entity, float x)
 {
     if (entity.HasComponent<Velocity>())
     {
         entity.GetComponent<Velocity>().X = x;
     }
 }
Example #52
0
 public static void SetLocalValue(Entity entity, string key, float value)
 {
     if (!entity.HasComponent<LocalData>()) return;
     LocalData data = entity.GetComponent<LocalData>();
     data.LocalFloats[key] = value;
 }
Example #53
0
 public static string GetLocalString(Entity entity, string key)
 {
     if (!entity.HasComponent<LocalData>()) return string.Empty;
     LocalData data = entity.GetComponent<LocalData>();
     return data.LocalStrings.ContainsKey(key) ? data.LocalStrings[key] : string.Empty;
 }
Example #54
0
 public static float GetLocalNumber(Entity entity, string key)
 {
     if (!entity.HasComponent<LocalData>()) return 0.0f;
     LocalData data = entity.GetComponent<LocalData>();
     return data.LocalFloats.ContainsKey(key) ? data.LocalFloats[key] : 0.0f;
 }
        public bool PickUpEntity(Entity user, Entity obj)
        {
            HumanHandsComponent userHands = user.GetComponent<HumanHandsComponent>(ComponentFamily.Hands);
            BasicItemComponent objItem = obj.GetComponent<BasicItemComponent>(ComponentFamily.Item);

            if (userHands != null && objItem != null)
            {
                return AddEntity(user, user, obj, userHands.CurrentHand);
            }
            else if (userHands == null && objItem != null && obj.HasComponent(ComponentFamily.Inventory))
            {
                return AddEntity(user, user, obj, InventoryLocation.Inventory);
            }

            return false;
        }
 public void EnslaveMovementAndSprite(Entity master, Entity slave)
 {
     slave.RemoveComponent(ComponentFamily.Mover);
     slave.AddComponent(ComponentFamily.Mover, EntityManager.ComponentFactory.GetComponent<SlaveMoverComponent>());
     slave.GetComponent<SlaveMoverComponent>(ComponentFamily.Mover).Attach(master);
     if (slave.HasComponent(ComponentFamily.Renderable) && master.HasComponent(ComponentFamily.Renderable))
     {
         slave.GetComponent<IRenderableComponent>(ComponentFamily.Renderable).SetMaster(master);
     }
 }
        public void FreeMovementAndSprite(Entity slave)
        {
            var toRemoveSlaveMover = slave.GetComponent<SlaveMoverComponent>(ComponentFamily.Mover);
            if (toRemoveSlaveMover != null)
            {
                toRemoveSlaveMover.Detach();
            }

            if (slave.HasComponent(ComponentFamily.Renderable))
            {
                slave.GetComponent<IRenderableComponent>(ComponentFamily.Renderable).UnsetMaster();
            }
            slave.RemoveComponent(ComponentFamily.Mover);
            slave.AddComponent(ComponentFamily.Mover, EntityManager.ComponentFactory.GetComponent<BasicMoverComponent>());
            slave.GetComponent<BasicItemComponent>(ComponentFamily.Item).HandleDropped();
        }
Example #58
0
 private void RemoveFromOtherComps(Entity entity)
 {
     Entity holder = null;
     if (entity.HasComponent(ComponentFamily.Item))
         holder = ((BasicItemComponent) entity.GetComponent(ComponentFamily.Item)).CurrentHolder;
     if (holder == null && entity.HasComponent(ComponentFamily.Equippable))
         holder = ((EquippableComponent) entity.GetComponent(ComponentFamily.Equippable)).currentWearer;
     if (holder != null) holder.SendMessage(this, ComponentMessageType.DisassociateEntity, entity);
     else Owner.SendMessage(this, ComponentMessageType.DisassociateEntity, entity);
 }
        private void RenderThruster(Entity root, Entity thrusterEntity, ref Matrix parentMatrix)
        {
            var thrusterComponent = thrusterEntity.GetComponent<ThrusterComponent>();
            if (thrusterComponent.ThrustPercentage > 0 || thrusterComponent.Part.IsIdleModeOnZeroThrust)
            {
                var sprite = thrusterEntity.GetComponent<SpriteComponent>();
                var thruster = thrusterComponent.Part;
                var xform = thruster.Transform;
                Vector2 scale = xform.Scale;

                float colorAlpha = 0;

                if (thrusterComponent.Part.IsIdleModeOnZeroThrust)
                {
                    scale *= new Vector2(MathHelper.Clamp(thrusterComponent.ThrustPercentage, 0.3f, 1), 1);
                    colorAlpha = MathHelper.Clamp(thrusterComponent.ThrustPercentage, 0.6f, 1);
                }
                else
                {
                    scale *= new Vector2(MathHelper.Clamp(thrusterComponent.ThrustPercentage, 0, 1), 1);
                    colorAlpha = thrusterComponent.ThrustPercentage;
                }

                if (!thrusterEntity.HasComponent<EditorComponent>())
                {
                    // do thruster graphic wobble
                    var time = MathHelper.ToRadians((float)thrusterComponent.GetHashCode() + _totalTime);
                    var amount = (float)Math.Sin(((time * 1.5f) % MathHelper.Pi) * 1f);
                    scale += new Vector2(amount * 0.05f, amount * 0.03f);
                }

                var matrix = UtilityExtensions.GetMatrix(xform.Position, xform.Rotation, scale, xform.Origin) * parentMatrix;
                _batch.Draw(sprite, ref matrix, thruster.Color * colorAlpha);
                //sprite.Draw(batch: _batch, matrix: tempXform.Matrix * parentMatrix, color: thruster.Color * colorAlpha, effects: fx);
                scale *= 0.8f;
                matrix = UtilityExtensions.GetMatrix(xform.Position, xform.Rotation, scale, xform.Origin) * parentMatrix;
                _batch.Draw(sprite, ref matrix, Color.White * colorAlpha);
                //sprite.Draw(batch: _batch, matrix: tempXform.Matrix * parentMatrix, color: Color.White * colorAlpha, effects: fx);
            }
        }
Example #60
0
 public static void SetFacing(Entity entity, Direction facing)
 {
     if (entity.HasComponent<Position>())
     {
         entity.GetComponent<Position>().Facing = facing;
     }
 }