Example #1
0
        public static void AttachObjects(PositionedObject child, PositionedObject parent)
        {
            if (parent == null || parent == child)
            {
                return;
            }

            if (child.Parent != null)
            {
                child.Detach();
            }

            if (child.IsParentOf(parent))
            {
                // A parent is trying to attach to its child.  Not allowed!
                System.Windows.Forms.MessageBox.Show("The current object is a parent of " + parent.Name + ". This operation is not allowed");
                return;
            }

            child.AttachTo(parent, true);

            GuiData.ToolsWindow.attachSprite.Unpress();
            GuiData.ToolsWindow.detachSpriteButton.Enabled    = true;
            GuiData.ToolsWindow.setRootAsControlPoint.Enabled = true;
        }
Example #2
0
        private static void ApplyPropertiesTo(PositionedObject entity, MapDrawableBatch layer, int tileIndex, List <NamedValue> propertiesToAssign)
        {
            int vertexIndex = tileIndex * 4;
            var dimension   =
                (layer.Vertices[vertexIndex + 1].Position - layer.Vertices[vertexIndex].Position).Length();

            float dimensionHalf = dimension / 2.0f;


            float left;
            float bottom;

            layer.GetBottomLeftWorldCoordinateForOrderedTile(tileIndex, out left, out bottom);
            Microsoft.Xna.Framework.Vector3 position = new Microsoft.Xna.Framework.Vector3(left, bottom, 0);

            var bottomRight = layer.Vertices[tileIndex * 4 + 1].Position;

            float xDifference = bottomRight.X - left;
            float yDifference = bottomRight.Y - bottom;

            if (yDifference != 0 || xDifference < 0)
            {
                float angle = (float)System.Math.Atan2(yDifference, xDifference);

                entity.RotationZ = angle;
            }

            position += entity.RotationMatrix.Right * dimensionHalf;
            position += entity.RotationMatrix.Up * dimensionHalf;

            position += layer.Position;

            ApplyPropertiesTo(entity, propertiesToAssign, position);
        }
        public void SortAlongForwardVectorDescending(PositionedObject positionedObjectRelativeTo)
        {
            Dictionary <PositionedObject, Vector3> oldPositions = new Dictionary <PositionedObject, Vector3>(this.Count);

            Matrix inverseRotationMatrix = positionedObjectRelativeTo.RotationMatrix;

            Matrix.Invert(ref inverseRotationMatrix, out inverseRotationMatrix);

            int temporaryCount = this.Count;

            for (int i = 0; i < temporaryCount; i++)
            {
                oldPositions.Add(this[i], this[i].Position);

                this[i].Position -= positionedObjectRelativeTo.Position;

                Vector3.Transform(ref this[i].Position,
                                  ref inverseRotationMatrix, out this[i].Position);
            }

            this.SortZInsertionAscending();

            foreach (KeyValuePair <PositionedObject, Vector3> kvp in oldPositions)
            {
                kvp.Key.Position = kvp.Value;
            }
        }
Example #4
0
        private void ApplyHandleChange(float xChange, float yChange)
        {
            float xChangeMultiplier;
            float yChangeMultiplier;
            float scaleXMultiplier;
            float scaleYMultiplier;

            GetChangeAndScaleMultipliers(out xChangeMultiplier, out yChangeMultiplier, out scaleXMultiplier, out scaleYMultiplier);


            IStaticPositionable positionable = SelectedObject as IStaticPositionable;

            PositionedObject positionedObject = SelectedObject as PositionedObject;

            if (positionedObject != null && positionedObject.Parent != null && positionedObject.IgnoreParentPosition == false)
            {
                positionedObject.RelativeX += xChangeMultiplier * xChange;
                positionedObject.RelativeY += yChangeMultiplier * yChange;
            }
            else
            {
                positionable.X += xChangeMultiplier * xChange;
                positionable.Y += yChangeMultiplier * yChange;
            }

            ApplyScale(xChange, yChange, scaleXMultiplier, scaleYMultiplier);
        }
 public void AttachTo(PositionedObject newParent, bool changeRelative)
 {
     for (int i = 0; i < Count; i++)
     {
         this[i].AttachTo(newParent, changeRelative);
     }
 }
Example #6
0
        public void RemoveFromManagers(bool clearThis)
        {
            if (!clearThis)
            {
                this.MakeOneWay();
            }

            // reverse list this
            for (int i = this.Count - 1; i > -1; i--)
            {
                Emitter emitter = this[i];

                PositionedObject oldParent = emitter.Parent;

                SpriteManager.RemoveEmitter(this[i]);

                if (!clearThis && oldParent != null)
                {
                    emitter.AttachTo(oldParent, false);
                }
            }

            if (clearThis)
            {
                Clear();
            }
            else
            {
                MakeTwoWay();
            }
        }
Example #7
0
        public void ControlPositionedObjectDPad(PositionedObject positionedObject, float velocity)
        {
            if (ButtonDown(Button.DPadLeft))
            {
                positionedObject.XVelocity = -velocity;
            }
            else if (ButtonDown(Button.DPadRight))
            {
                positionedObject.XVelocity = velocity;
            }
            else
            {
                positionedObject.XVelocity = 0;
            }

            if (ButtonDown(Button.DPadUp))
            {
                positionedObject.YVelocity = velocity;
            }
            else if (ButtonDown(Button.DPadDown))
            {
                positionedObject.YVelocity = -velocity;
            }
            else
            {
                positionedObject.YVelocity = 0;
            }
        }
Example #8
0
        public static float Distance2D(this PositionedObject t, PositionedObject p)
        {
            Vector3 v3 = t.Position - p.Position;

            v3.Z = 0;
            return(v3.Length());
        }
Example #9
0
        private void DoShootingActivity(PositionedObject target)
        {
            if (CurrentBehavior == Behavior.Shooting &&
                FlatRedBall.Screens.ScreenManager.CurrentScreen.PauseAdjustedSecondsSince(lastFireShotTime) >
                (1 / FireShotsPerSecond)
                )
            {
                // Rotate the aiming vector to the farthest angle counterclockwise. (Positive)
                // For each increment rotate clockwise. (Negative)
                Vector3 currentAimingVector = RotateVector(aimingVector, BulletSpreadHalfAngle);
                float   spreadIncremet      = -(BulletSpreadHalfAngle * 2) / Math.Max((BulletsToFire - 1), 1);

                for (int i = 0; i < BulletsToFire; i++)
                {
                    var bullet = Factories.BulletFactory.CreateNew(this.X, this.Y);
                    bullet.Z = this.Z - 1;
                    bullet.CurrentDataCategoryState = Bullet.DataCategory.EnemyBullet;
                    bullet.Velocity = bullet.BulletSpeed * currentAimingVector;
                    //bullet.SetAnimationChainFromVelocity(TopDownDirectionExtensions.FromDirection(currentAimingVector, PossibleDirections), Weapon.ShootingFire);

                    currentAimingVector = RotateVector(currentAimingVector, spreadIncremet);
                }
                shootingAnimationLayer.PlayOnce(GetChainName(PrimaryActions.shoot, SecondaryActions.Shooting));
                lastFireShotTime = FlatRedBall.Screens.ScreenManager.CurrentScreen.PauseAdjustedCurrentTime;
                PlayWeaponShotSound();
                shotsLeftInClip--;
            }
        }
Example #10
0
        private void DoTargetDecision(PositionedObjectList <Player> players, PlayerBase playerBase)
        {
            if (forcedTarget != null)
            {
                target = forcedTarget;

                var timeSinceSet =
                    FlatRedBall.Screens.ScreenManager.CurrentScreen.PauseAdjustedSecondsSince(timeForcedTargetSet);

                if (timeSinceSet > AggroDuration)
                {
                    forcedTarget = null;
                }
            }
            else if (target == null)
            {
                PositionedObject closest = GetClosest(players, playerBase);

                target = closest;
            }
            else
            {
                if (CurrentBehavior == Behavior.Chasing)
                {
                    // see if there is anything closer
                    target = GetClosest(players, playerBase);
                }
                // else if shooting/reloading, chase that same target so long as in chasing mode
            }
        }
Example #11
0
        private PositionedObject GetClosest(PositionedObjectList <Player> players, PlayerBase playerBase)
        {
            PositionedObject closest = null;
            // get closest:
            float closestDistance = float.PositiveInfinity;

            foreach (var player in players)
            {
                var distanceToPlayer = (player.Position - this.Position).Length();
                if (distanceToPlayer < closestDistance)
                {
                    closestDistance = distanceToPlayer;
                    closest         = player;
                }
            }

            var distancetoBase = (playerBase.Position - this.Position).Length();

            if (distancetoBase < closestDistance)
            {
                closestDistance = distancetoBase;
                closest         = playerBase;
            }

            return(closest);
        }
Example #12
0
        public void SetIndividualVariablesFromStoredVariables <T>(T s) where T : PositionedObject, ISpriteEditorObject
        {
            PositionedObject asPositionedObject = s as PositionedObject;

            if (EditAxes.changeVector.X != 0 ||
                EditAxes.changeVector.Y != 0 ||
                EditAxes.changeVector.Z != 0)
            {
                #region has a parent
                if (asPositionedObject.Parent != null && GuiData.ToolsWindow.groupHierarchyControlButton.IsPressed)
                {
                    Matrix rotMat = asPositionedObject.Parent.RotationMatrix;
                    rotMat.Invert();

                    mAxes.changeVector.TransformCoordinate(rotMat);

                    s.TopParent.X += EditAxes.changeVector.X;
                    s.TopParent.Y += EditAxes.changeVector.Y;
                    s.TopParent.Z += EditAxes.changeVector.Z;
                }
                else
                {
                    ((ISpriteEditorObject)(s.TopParent)).X += EditAxes.changeVector.X;
                    ((ISpriteEditorObject)(s.TopParent)).Y += EditAxes.changeVector.Y;
                    ((ISpriteEditorObject)(s.TopParent)).Z += EditAxes.changeVector.Z;
                }
                #endregion
            }
        }
        public void Register(PositionedObject item)
        {
            UpdateRegion(item);
            try
            {
                registeredItems.Add(item, new SubscriptionMatrix(item));

            }
            catch (Exception ex)
            {
                // Can't add duplicate items.

                return;
            }

            try
            {
                regionItems[item.Region].Add(item);
            }
            catch (Exception ex)
            {
                // Cna't add duplicate items
                return;
            }
            FindNewItems(item);
            item.Changed += new EventHandler<PositionedObjectChangedEventArgs>(RegisteredItemChanged);
        }
Example #14
0
        private float ModifyDamageToTake(PositionedObject damageDealer, float weaponLevelModifier, float baseDamage)
        {
            float toReturn = baseDamage;

            if (ShieldHalfAngle != 0)
            {
                Vector3 directionOfDamage = damageDealer.Position - Position;
                directionOfDamage.Normalize();
                var     directionFacing = TopDownDirectionExtensions.FromDirection(new Vector2(aimingVector.X, aimingVector.Y), PossibleDirections.EightWay);
                Vector3 forwardVector   = directionFacing.ToVector();

                var dotProd = directionOfDamage.X * forwardVector.X + directionOfDamage.Y * forwardVector.Y;

                var angleDegrees = Math.Acos(dotProd) * (180 / Math.PI);

                toReturn = baseDamage;

                if (angleDegrees < ShieldHalfAngle)
                {
                    toReturn /= 2;
                }
            }

            toReturn = toReturn * weaponLevelModifier;

            return(toReturn);
        }
        public bool CollideAgainstBounce(AxisAlignedRectangle rectangle, float thisMass, float otherMass, float elasticity)
        {
#if DEBUG
            if (thisMass == 0 && otherMass == 0)
            {
                throw new ArgumentException("Both masses cannot be 0.  For equal masses pick a non-zero value");
            }
#endif
            if (CollideAgainstMove(rectangle, thisMass, otherMass))
            {
                if (YVelocity + 103.6 < .01f)
                {
                    int m = 3;
                }

                PositionedObject thisTopParent  = this.TopParent;
                PositionedObject otherTopParent = rectangle.TopParent;

                Vector2 collisionNormal = LastMoveCollisionReposition;

                if (otherMass == 0)
                {
                    collisionNormal = new Vector2(-rectangle.LastMoveCollisionReposition.X, -rectangle.LastMoveCollisionReposition.Y);
                }

                ShapeManager.ApplyBounce(thisTopParent, otherTopParent, thisMass, otherMass, elasticity, ref collisionNormal);
                return(true);
            }

            return(false);
        }
Example #16
0
        public void Update()
        {
            PositionedObject selectedObject = null;

            if (EditorData.EditorLogic.CurrentSprites.Count != 0)
            {
                selectedObject = EditorData.EditorLogic.CurrentSprites[0];
            }
            else if (EditorData.EditorLogic.CurrentTexts.Count != 0)
            {
                selectedObject = EditorData.EditorLogic.CurrentTexts[0];
            }


            mCurrentObjectHighlight.Visible = selectedObject != null;

            if (selectedObject != null)
            {
                mCurrentObjectHighlight.Position       = selectedObject.Position;
                mCurrentObjectHighlight.RotationMatrix = selectedObject.RotationMatrix;

                if (selectedObject is IReadOnlyScalable)
                {
                    IReadOnlyScalable asIScalable = selectedObject as IReadOnlyScalable;

                    float scaleX = asIScalable.ScaleX;
                    float scaleY = asIScalable.ScaleY;

                    mCurrentObjectHighlight.ScaleBy(
                        scaleX / mCurrentObjectHighlight.Points[0].X,
                        scaleY / mCurrentObjectHighlight.Points[0].Y);
                }
            }
        }
Example #17
0
        public void AttachTo(PositionedObject newParent, bool changeRelative)
        {
            mSprites.AttachTo(newParent, changeRelative);

            mSpriteFrames.AttachTo(newParent, changeRelative);
            mTexts.AttachTo(newParent, changeRelative);
        }
        public void TestFluentInterface()
        {
            PositionedObject positionedObject = new PositionedObject();

            // Make sure it doesn't crash:
            positionedObject.Set("XVelocity").To(4.3f).After(1.1f);
        }
Example #19
0
        /// <summary>
        /// Adjusts the calling Circle's position (or its parent if attached) so that the circle is fully-contained
        /// in the argument AxisAlignedRectangle.
        /// </summary>
        /// <param name="otherAxisAlignedRectangle">The rectangle to keep the circle inside of.</param>
        public void KeepThisInsideOf(AxisAlignedRectangle otherAxisAlignedRectangle)
        {
            Vector2 repositionVector;

            repositionVector.X = 0;
            repositionVector.Y = 0;

            this.ForceUpdateDependencies();

            if (this.X - this.Radius < otherAxisAlignedRectangle.X - otherAxisAlignedRectangle.ScaleX)
            {
                repositionVector.X = (otherAxisAlignedRectangle.X - otherAxisAlignedRectangle.ScaleX + this.Radius) - this.X;
            }

            if (this.X + this.Radius > otherAxisAlignedRectangle.X + otherAxisAlignedRectangle.ScaleX)
            {
                repositionVector.X = (otherAxisAlignedRectangle.X + otherAxisAlignedRectangle.ScaleX - this.Radius) - this.X;
            }

            if (this.Y - this.Radius < otherAxisAlignedRectangle.Y - otherAxisAlignedRectangle.ScaleY)
            {
                repositionVector.Y = (otherAxisAlignedRectangle.Y - otherAxisAlignedRectangle.ScaleY + this.Radius) - this.Y;
            }

            if (this.Y + this.Radius > otherAxisAlignedRectangle.Y + otherAxisAlignedRectangle.ScaleY)
            {
                repositionVector.Y = (otherAxisAlignedRectangle.Y + otherAxisAlignedRectangle.ScaleY - this.Radius) - this.Y;
            }

            PositionedObject topParent = this.TopParent;

            topParent.Position.X += repositionVector.X;
            topParent.Position.Y += repositionVector.Y;
        }
Example #20
0
        private static void GetWhatToAttachToForNewNos(PositionedObject parentElementRuntime, NamedObjectSave n, Object newObject, out PositionedObject attachTo, out float parentZToSet)
        {
            attachTo     = null;
            parentZToSet = 0;
            if (n.AttachToCamera &&
                // AttachToCamera is not allowed on objects within an Entity
                // This can lead to confusing behavior.  Technically the NOS itself
                // could have AttachToCamera set to true if Glue has messed up somehow
                // or if the user has manually edited the .glux.  However, even if this
                // is the case, we don't want to perform an attachment.
                (parentElementRuntime is ElementRuntime == false ||
                 ((ElementRuntime)parentElementRuntime).mAssociatedIElement is EntitySave == false))
            {
                parentZToSet = 40;
                attachTo     = SpriteManager.Camera;
            }
            else if (n.AttachToContainer)
            {
                if (parentElementRuntime is ElementRuntime == false ||
                    ((ElementRuntime)parentElementRuntime).mAssociatedIElement is ScreenSave == false)
                {
                    attachTo = parentElementRuntime;
                }

                if (newObject is PositionedObject)
                {
                    // It's already attached to something else in its files
                    if (((PositionedObject)newObject).Parent != null)
                    {
                        attachTo = null;
                    }
                }
            }
        }
Example #21
0
        public bool TakeDamage(PositionedObject damageDealer, float damageToTake, Player owner)
        {
            bool tookDamage = false;

            if (canTakeDamage)
            {
                tookDamage = true;
                var modifedDamage = ModifyDamageToTake(damageDealer, owner.WeaponDamageModifier, damageToTake);
                CurrentHP -= modifedDamage;

                if (CurrentHP <= 0)
                {
                    System.Diagnostics.Debug.WriteLine(
                        $"Took {modifedDamage} damage and died");
                    playerThatDealtKillingBlow = owner;
                    PerformDeath();
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine(
                        $"Took {modifedDamage} damage and has {CurrentHP} left");
                    FlashWhite();
                    PlayDamageSound();
                    SetForcedTarget(owner);
                }
            }

            return(tookDamage);
        }
        public bool CollideAgainstBounce(Polygon polygon, float thisMass, float otherMass, float elasticity)
        {
#if DEBUG
            if (thisMass == 0 && otherMass == 0)
            {
                throw new ArgumentException("Both masses cannot be 0.  For equal masses pick a non-zero value");
            }
#endif
            if (CollideAgainstMove(polygon, thisMass, otherMass))
            {
                PositionedObject thisTopParent  = this.TopParent;
                PositionedObject otherTopParent = polygon.TopParent;


                Vector2 collisionNormal = LastMoveCollisionReposition;

                if (otherMass == 0)
                {
                    collisionNormal = new Vector2(-polygon.LastMoveCollisionReposition.X, -polygon.LastMoveCollisionReposition.Y);
                }

                ShapeManager.ApplyBounce(thisTopParent, otherTopParent, thisMass, otherMass, elasticity, ref collisionNormal);


                return(true);
            }

            return(false);
        }
Example #23
0
        public object UpdateInstanceValuesFromRuntime(ElementRuntime runtime)
        {
            object instance =
                RelationshipManager.Self.InstanceForElementRuntime(runtime);

            object whatToPullValuesFrom = runtime;

            if (runtime.DirectObjectReference != null)
            {
                whatToPullValuesFrom = runtime.DirectObjectReference;
            }
            PositionedObject whatToPullFromAsPo = whatToPullValuesFrom as PositionedObject;

            if (instance is CircleSave)
            {
                CircleSave save = (instance as CircleSave);
                save.SetFrom(whatToPullValuesFrom as Circle);
                SetSavePositionsFromRelativeValues(whatToPullFromAsPo, save);
            }
            else if (instance is SpriteSave)
            {
                SpriteSave save = (instance as SpriteSave);
                save.SetFrom(whatToPullValuesFrom as Sprite);
                SetSavePositionsFromRelativeValues(whatToPullFromAsPo, save);
            }
            else if (instance is AxisAlignedRectangleSave)
            {
                AxisAlignedRectangleSave save = (instance as AxisAlignedRectangleSave);
                save.SetFrom(whatToPullValuesFrom as AxisAlignedRectangle);
                SetSavePositionsFromRelativeValues(whatToPullFromAsPo, save);
            }
            else if (instance is ArrowElementInstance)
            {
                ArrowElementInstance save = (instance as ArrowElementInstance);

                if (whatToPullFromAsPo != null)
                {
                    if (whatToPullFromAsPo.Parent == null)
                    {
                        save.SetVariable("X", whatToPullFromAsPo.X);
                        save.SetVariable("Y", whatToPullFromAsPo.Y);
                    }
                    else
                    {
                        save.SetVariable("X", whatToPullFromAsPo.RelativeX);
                        save.SetVariable("Y", whatToPullFromAsPo.RelativeY);
                    }
                }

                // We can't do this because this object technically doesn't have X and Y properties
                //SetSavePositionsFromRelativeValues(whatToPullFromAsPo, save);
            }
            else
            {
                throw new Exception("Saving of type " + instance.GetType() + " is not supported");
            }

            return(instance);
        }
Example #24
0
        public static void FollowPath(PositionedObject objectFollowingPath, List <Vector3> pointsToFollow,
                                      float velocity, float pointReachedDistance, bool ignoreZ)
        {
            if (pointsToFollow.Count == 0)
            {
                // DESTINATION REACHED!
                return;
            }

            Vector3 vectorToMoveAlong;

            vectorToMoveAlong.X = 0;
            vectorToMoveAlong.Y = 0;
            vectorToMoveAlong.Z = 0;

            while (true)
            {
                vectorToMoveAlong = pointsToFollow[0] - objectFollowingPath.Position;

                if (ignoreZ)
                {
                    vectorToMoveAlong.Z = 0;
                }

                // See if objectFollowingPath has reached the point
                float length = vectorToMoveAlong.Length();

                if (length < pointReachedDistance)
                {
                    pointsToFollow.RemoveAt(0);

                    if (pointsToFollow.Count == 0)
                    {
                        // DESTINATION REACHED!
                        return;
                    }

                    vectorToMoveAlong = pointsToFollow[0] - objectFollowingPath.Position;
                }
                else
                {
#if FRB_MDX
                    vectorToMoveAlong.Scale(1 / length);
#else
                    vectorToMoveAlong /= length;
#endif
                    break;
                }
            }

            vectorToMoveAlong *= velocity;

            if (ignoreZ)
            {
                // This makes it so that setting of velocity doesn't overwrite the old Z value
                vectorToMoveAlong.Z = objectFollowingPath.ZVelocity;
            }
            objectFollowingPath.Velocity = vectorToMoveAlong;
        }
Example #25
0
 public void ReactToPlayerDeath(PositionedObject killedPlayer)
 {
     if (target == killedPlayer)
     {
         // Null out the target if the player is destroyed.
         target = null;
     }
 }
Example #26
0
        public static TweenerHolder Tween(this PositionedObject positionedObject, string memberToSet)
        {
            TweenerHolder toReturn = new TweenerHolder();

            toReturn.Caller = positionedObject;
            toReturn.Tween(memberToSet);
            return(toReturn);
        }
Example #27
0
        protected void PositionNewObstacle(PositionedObject newObstacle)
        {
            // Set the entire position...
            newObstacle.Position = this.Position;
            // ...then overwrite the X:
            var width = Camera.Main.OrthogonalWidth;

            newObstacle.X = -width / 2.0f + (float)FlatRedBallServices.Random.NextDouble() * width;
        }
Example #28
0
        public void ControlPositionedObjectAcceleration(PositionedObject positionedObject, float acceleration)
        {
            if (KeyDown(Keys.Up))
            {
                positionedObject.YAcceleration = acceleration;
            }
            else if (KeyDown(Keys.Down))
            {
                positionedObject.YAcceleration = -acceleration;
            }
            else
            {
                positionedObject.YAcceleration = 0;
            }

            if (KeyDown(Keys.Right))
            {
                positionedObject.XAcceleration = acceleration;
            }
            else if (KeyDown(Keys.Left))
            {
                positionedObject.XAcceleration = -acceleration;
            }
            else
            {
                positionedObject.XAcceleration = 0;
            }

#if FRB_MDX
            // Remember, FRB MDX is left handed, FRB XNA is right handed.
            if (KeyDown(Keys.Minus))
            {
                positionedObject.ZVelocity = -acceleration;
            }
            else if (KeyDown(Keys.Equals))
            {
                positionedObject.ZVelocity = acceleration;
            }
            else
            {
                positionedObject.ZVelocity = 0;
            }
#else
            if (KeyDown(Keys.OemMinus))
            {
                positionedObject.ZAcceleration = acceleration;
            }
            else if (KeyDown(Keys.OemPlus))
            {
                positionedObject.ZAcceleration = -acceleration;
            }
            else
            {
                positionedObject.ZAcceleration = 0;
            }
#endif
        }
 public bool outRange(PositionedObject sub, PositionedObject target)
 {
     int outR = (int)(sub.ViewRadius * rangeBoxMultiplier);
     if (Math.Abs(sub.Position.X - target.Position.X) > outR || Math.Abs(sub.Position.Y - target.Position.Y) > outR)
     {
         return true;
     }
     return false;
 }
Example #30
0
        public static TweenerHolder Tween(this PositionedObject positionedObject, string property, float to,
                                          float during, InterpolationType interpolation, Easing easing)
        {
            TweenerHolder toReturn = new TweenerHolder();

            toReturn.Caller = positionedObject;
            toReturn.Tween(property, to, during, interpolation, easing);
            return(toReturn);
        }
Example #31
0
        private static void ApplyPropertiesTo(PositionedObject entity, List <NamedValue> propertiesToAssign, Microsoft.Xna.Framework.Vector3 position)
        {
            if (entity != null)
            {
                entity.Position = position;
            }

            var entityType = entity.GetType();
            var lateBinder = Instructions.Reflection.LateBinder.GetInstance(entityType);

            foreach (var property in propertiesToAssign)
            {
                // If name is EntityName, skip it:
                string propertyName = property.Name;

                bool shouldSet = propertyName != "EntityName";

                if (shouldSet)
                {
                    if (propertyName == "name")
                    {
                        propertyName = "Name";
                    }

                    var valueToSet = property.Value;
                    valueToSet = SetValueAccordingToType(valueToSet, propertyName, property.Type, entityType);
                    try
                    {
                        lateBinder.SetValue(entity, propertyName, valueToSet);
                    }
                    catch (InvalidCastException e)
                    {
                        string assignedType = valueToSet.GetType().ToString() ?? "unknown type";
                        assignedType = GetFriendlyNameForType(assignedType);

                        string expectedType = "unknown type";
                        object outValue;
                        if (lateBinder.TryGetValue(entity, propertyName, out outValue) && outValue != null)
                        {
                            expectedType = outValue.GetType().ToString();
                            expectedType = GetFriendlyNameForType(expectedType);
                        }

                        // This means that the property exists but is of a different type.
                        string message = $"Attempted to assign the property {propertyName} " +
                                         $"to a value of type {assignedType} but expected {expectedType}. " +
                                         $"Check the property type in your TMX and make sure it matches the type on the entity.";
                        throw new Exception(message, e);
                    }
                    catch (Exception e)
                    {
                        // Since this code indiscriminately tries to set properties, it may set properties which don't
                        // actually exist. Therefore, we tolerate failures.
                    }
                }
            }
        }
Example #32
0
        public void ControlPositionedObject(PositionedObject positionedObject, float velocity)
        {
            if (KeyDown(Keys.Up))
            {
                positionedObject.Velocity.Y = velocity;
            }
            else if (KeyDown(Keys.Down))
            {
                positionedObject.Velocity.Y = -velocity;
            }
            else
            {
                positionedObject.Velocity.Y = 0;
            }

            if (KeyDown(Keys.Right))
            {
                positionedObject.Velocity.X = velocity;
            }
            else if (KeyDown(Keys.Left))
            {
                positionedObject.Velocity.X = -velocity;
            }
            else
            {
                positionedObject.Velocity.X = 0;
            }

#if FRB_MDX
            // Remember, FRB MDX is left handed, FRB XNA is right handed.
            if (KeyDown(Keys.Minus))
            {
                positionedObject.ZVelocity = -velocity;
            }
            else if (KeyDown(Keys.Equals))
            {
                positionedObject.ZVelocity = velocity;
            }
            else
            {
                positionedObject.ZVelocity = 0;
            }
#else
            if (KeyDown(Keys.OemMinus))
            {
                positionedObject.ZVelocity = velocity;
            }
            else if (KeyDown(Keys.OemPlus))
            {
                positionedObject.ZVelocity = -velocity;
            }
            else
            {
                positionedObject.ZVelocity = 0;
            }
#endif
        }
 public bool inRange(PositionedObject sub, PositionedObject target)
 {
     if (sub.ViewRadius != int.MinValue && sub != target)
     {
         if (Math.Abs(sub.Position.X - target.Position.X) <= sub.ViewRadius && Math.Abs(sub.Position.Y - target.Position.Y) <= sub.ViewRadius)
         {
             return true;
         }
     }
     return false;
 }
Example #34
0
        public static Attachment FromAttachment(PositionedObject child)
        {
            if (child.Parent == null)
            {
                throw new ArgumentException("The argument child must have a parent to create an Attachment instance.");
            }

            Attachment attachment = new Attachment();
            attachment.Parent = child.Parent;
            attachment.RelativePosition = child.RelativePosition;
            attachment.RelativeRotationMatrix = child.RelativeRotationMatrix;

            return attachment;
        }
        private static void ApplyPropertiesTo(PositionedObject entity, MapDrawableBatch layer, int tileIndex, List<NamedValue> propertiesToAssign)
        {

            int vertexIndex = tileIndex * 4;
            var dimension = layer.Vertices[vertexIndex + 1].Position.X - layer.Vertices[vertexIndex].Position.X;

            float dimensionHalf = dimension / 2.0f;


            float left;
            float bottom;
            layer.GetBottomLeftWorldCoordinateForOrderedTile(tileIndex, out left, out bottom);

            if (entity != null)
            {
                entity.X = left + dimensionHalf;
                entity.Y = bottom + dimensionHalf;
                entity.Z = layer.Z;
            }

            var entityType = entity.GetType();
            var lateBinder = Instructions.Reflection.LateBinder.GetInstance(entityType);

            foreach (var property in propertiesToAssign)
            {
                try
                {
                    var valueToSet = property.Value;

                    valueToSet = SetValueAccordingToType(valueToSet, property.Name, property.Type, entityType);

                    lateBinder.SetValue(entity, property.Name, valueToSet);
                }
                catch (Exception e)
                {
                    // Since this code indiscriminately tries to set properties, it may set properties which don't
                    // actually exist. Therefore, we tolerate failures.

                }
            }
        }
Example #36
0
        private void GetObjectToSetOnAndParent(ElementRuntime sourceElement, out object objectToSetOn, out PositionedObject parent)
        {
            objectToSetOn = null;

            parent = this;

            #region Get the objectToSetOn

            if (sourceElement.mDirectObjectReference == null)
            {
                objectToSetOn = sourceElement;
            }
            else
            {
                objectToSetOn = sourceElement.mDirectObjectReference;
            }

            if (objectToSetOn == this)
            {
                parent = this.Parent;
            }


            #endregion
        }
Example #37
0
        public void ControlPositionedObjectFpsStyle(PositionedObject positionedObject, Vector3 up)
        {
            positionedObject.Velocity = new Vector3();

            positionedObject.Velocity += positionedObject.RotationMatrix.Forward * LeftStick.Position.Y * 7;
            positionedObject.Velocity += positionedObject.RotationMatrix.Right * LeftStick.Position.X * 7;

            positionedObject.RotationMatrix *= Matrix.CreateFromAxisAngle(positionedObject.RotationMatrix.Right, TimeManager.SecondDifference * RightStick.Position.Y);
            positionedObject.RotationMatrix *= Matrix.CreateFromAxisAngle(up, -TimeManager.SecondDifference * RightStick.Position.X);
        }
Example #38
0
        private PositionedObject SetFieldOrPropertyCustomVariable(CustomVariable cv, object valueToSetTo, bool attachAndUnattach, IElement container, ElementRuntime sourceElement, object objectToSetOn, PositionedObject parent, PropertyInfo property, FieldInfo field)
        {
            if (objectToSetOn != sourceElement && sourceElement.mAssociatedNamedObjectSave.SourceType == SourceType.FlatRedBallType &&
                objectToSetOn is PositionedObject && attachAndUnattach)
            {
                parent = sourceElement;
            }

            // Not sure if this is the best place to put this, but let's replace "\\n" with "\n"
            if (valueToSetTo is string && ((string)valueToSetTo).Contains("\\n"))
            {
                valueToSetTo = ((string)valueToSetTo).Replace("\\n", "\n");
            }

            VariableSetArgs vse = new VariableSetArgs();
            vse.Value = valueToSetTo;
            vse.VariableName = cv.Name;

            if (BeforeVariableApply != null)
            {
                BeforeVariableApply(this, vse);
            }

            if (property != null)
            {
                //try
                //{
                    if (cv.GetIsFile())
                    {
                        object fileRuntime = null;

                        if (valueToSetTo is string)
                        {
                            ReferencedFileSave rfs = GetReferencedFileFromName(valueToSetTo);

                            if (rfs == null)
                            {
                                fileRuntime = null;
                            }
                            else
                            {
                                fileRuntime = LoadReferencedFileSave(rfs, true, container);
                            }
                        }
                        else
                        {
                            fileRuntime = valueToSetTo;
                        }

                        property.SetValue(objectToSetOn, fileRuntime, null);
                    }
                    else
                    {
                        object convertedValue = valueToSetTo;
                        if (property.PropertyType == typeof(Microsoft.Xna.Framework.Color) && valueToSetTo is string)
                        {
                            convertedValue = PropertyValuePair.ConvertStringToType((string)valueToSetTo, property.PropertyType);
                        }
                        if(property.PropertyType == typeof(IList<FlatRedBall.Math.Geometry.Point>))
                        {
                            // We may be storing vectors, so if so we need to convert
                            if (valueToSetTo != null && valueToSetTo is List<Vector2>)
                            {
                                List<FlatRedBall.Math.Geometry.Point> converted = new List<FlatRedBall.Math.Geometry.Point>();
                                foreach(var item in valueToSetTo as List<Vector2>)
                                {
                                    converted.Add(new Math.Geometry.Point(item.X, item.Y));
                                }
                                convertedValue = converted;
                            }
                        }
                        bool shouldSet = true;

                        if (convertedValue is string &&
                            (string.IsNullOrEmpty((string)convertedValue)) &&
                            (
                            property.PropertyType == typeof(float) ||
                            property.PropertyType == typeof(bool) ||
                            property.PropertyType == typeof(long) ||
                            property.PropertyType == typeof(double) ||
                            property.PropertyType == typeof(int)))
                        {
                            shouldSet = false;
                        }
                        if (shouldSet)
                        {
                            // It's possible that GlueView
                            // can set a bad value like float.NaN
                            // on an X which ultimately makes the engine
                            // crash hard!  If an exception occurs on a property
                            // set, then we need to catch it and undo the set, then
                            // throw an exception so that whoever set it can deal with
                            // the problem.
                            object oldValue = null;
                            if(property.CanRead)
                            {
                                oldValue = property.GetValue(objectToSetOn, null);
                            }
                            try
                            {
                                bool wasCustomSet = false;

                                if (objectToSetOn is PositionedObject)
                                {

                                }
                                else
                                {

                                }
                                property.SetValue(objectToSetOn, convertedValue, null);
                            }
                            catch (Exception e)
                            {
                                if (property.CanRead)
                                {
                                    // We failed, so let's set the value back (if we can)
                                    try
                                    {
                                        property.SetValue(objectToSetOn, oldValue, null);
                                    }
                                    catch
                                    {
                                        // do nothing
                                    }
                                }
                                //throw new Exception("Error setting " + property.Name + " on " + objectToSetOn + ":\n" + e.ToString());
                            }
                        }
                    }
                //}
                //catch
                //{
                //    // do nothing for now
                //}
            }
            else if (field != null)
            {
                field.SetValue(objectToSetOn, valueToSetTo);
            }

            if (objectToSetOn is PositionedObject)
            {
                ((PositionedObject)objectToSetOn).ForceUpdateDependencies();
            }

            // If we changed the position of this, we want to make sure to update any 
            // children before we continue to eliminate errors from repositioning
            foreach (PositionedObject childObject in this.Children)
            {
                childObject.ForceUpdateDependenciesDeep();
            }
            foreach (ElementRuntime er in this.ContainedElements)
            {
                er.ForceUpdateDependenciesDeep();
            }

            if (AfterVariableApply != null)
            {
                AfterVariableApply(this, vse);
            }

            return parent;
        }
Example #39
0
        private static void DetachAndMoveParentToOrigin(PositionedObject asPositionedObject, PositionedObject parent, ref Vector3 oldParentPosition, ref Matrix oldParentRotation)
        {
            if (parent != null)
            {
                asPositionedObject.Detach();

                oldParentPosition = parent.Position;
                oldParentRotation = parent.RotationMatrix;

                parent.Position = new Vector3();

                if (parent is Camera)
                {
                    parent.Z = 40;
                }
                parent.RotationMatrix = Matrix.Identity;
            }
        }
Example #40
0
 public void ControlPositionedObject(PositionedObject positionedObject)
 {
     ControlPositionedObject(positionedObject, 10);
 }
        private static void GetWhatToAttachToForNewNos(PositionedObject parentElementRuntime, NamedObjectSave n, Object newObject, out PositionedObject attachTo, out float parentZToSet)
        {
            attachTo = null;
            parentZToSet = 0;
            if (n.AttachToCamera &&
                // AttachToCamera is not allowed on objects within an Entity
                // This can lead to confusing behavior.  Technically the NOS itself
                // could have AttachToCamera set to true if Glue has messed up somehow
                // or if the user has manually edited the .glux.  However, even if this
                // is the case, we don't want to perform an attachment.
                (parentElementRuntime is ElementRuntime == false ||
                    ((ElementRuntime)parentElementRuntime).mAssociatedIElement is EntitySave == false))
            {
                parentZToSet = 40;
                attachTo = SpriteManager.Camera;
            }
            else if (n.AttachToContainer)
            {
                if (parentElementRuntime is ElementRuntime == false ||
                    ((ElementRuntime)parentElementRuntime).mAssociatedIElement is ScreenSave == false)
                {
                    attachTo = parentElementRuntime;
                }

                if (newObject is PositionedObject)
                {
                    // It's already attached to something else in its files
                    if (((PositionedObject)newObject).Parent != null)
                    {
                        attachTo = null;
                    }
                }
            }
        }
Example #42
0
        public void ControlPositionedObject(PositionedObject positionedObject, float velocity)
        {
            positionedObject.XVelocity = this.LeftStick.Position.X * velocity;
            positionedObject.YVelocity = this.LeftStick.Position.Y * velocity;

            if (ButtonDown(Button.LeftShoulder))
                positionedObject.ZVelocity = velocity;
            else if (ButtonDown(Button.RightShoulder))
                positionedObject.ZVelocity = -velocity;
            else
                positionedObject.ZVelocity = 0;
        }
Example #43
0
 public void SetHead(PositionedObject headPO, Texture2D texture, float placementFrequency, float minimumPlacementDistance)
 {
     this.head = headPO;
     this.placementFrequency = placementFrequency;
     this.minimumPlacementDistance = minimumPlacementDistance;
     this.minimumPlacementDistanceSquared = minimumPlacementDistance * minimumPlacementDistance;
     this.texture = texture;
     if (this.mPoints.Count < 2)
     {
         this.AddPoint(this.head.X, this.head.Y, this.head.Z, texture);
         this.lastPlacement = TimeManager.CurrentTime;
     }
 }
        private void CreateNamedObjectElementRuntime(IElement elementSave, Layer layerProvidedByContainer, List<NamedObjectSave> namedObjectSaveList,
            PositionedObjectList<ElementRuntime> listToPopulate, PositionedObject parentElementRuntime)
        {



            foreach (NamedObjectSave n in namedObjectSaveList)
            {
                Object newObject = null;

                if (ShouldElementRuntimeBeCreatedForNos(n, elementSave))
                {
                    Layer layerToPutOn = GetLayerForNos(layerProvidedByContainer, n);

                    switch (n.SourceType)
                    {

                        case SourceType.File:

                            newObject = LoadFileObject(n, elementSave, layerToPutOn, listToPopulate);
                            
                            break;


                        case SourceType.Entity:

                            newObject = LoadEntityObject(n, layerToPutOn, listToPopulate);

                            break;


                        case SourceType.FlatRedBallType:
                            newObject = CreateFlatRedBallTypeNos(n, listToPopulate, layerToPutOn);
                            break;
                    }
                }
                if (newObject != null && newObject is PositionedObject)
                {
                    PositionedObject attachTo;
                    float parentZToSet;
                    GetWhatToAttachToForNewNos(parentElementRuntime, n, newObject, out attachTo, out parentZToSet);

                    if (attachTo != null)
                    {
                        Vector3 oldPosition = attachTo.Position;
                        Matrix oldRotationMatrix = attachTo.RotationMatrix;

                        attachTo.Position = new Vector3();



                        attachTo.Z = parentZToSet;
                        attachTo.RotationMatrix = Matrix.Identity;

                        ((PositionedObject)newObject).AttachTo(attachTo, true);

                        attachTo.Position = oldPosition;
                        attachTo.RotationMatrix = oldRotationMatrix;
                    }
                }
            }
        }
 public void UpdateRegion(PositionedObject po)
 {
     int rX = (int)po.Position.X / world.Scale;
     int rY = (int)po.Position.Y / world.Scale;
     Region r = world.Regions.FirstOrDefault(e => e.XOrigin == rX && e.YOrigin == rY);
     if (r != po.Region)
     {
         po.Region = r;
         regionItems[po.Region].Remove(po);
         regionItems[r].Add(po);
     }
 }
        private void FindNewItems(PositionedObject subscriber)
        {
            Region[] borderRegions = getBorderRegions(subscriber);
            foreach (Region r in borderRegions)
            {
                // Check what I can see.

                var items = regionItems[r].Where(e => inRange(subscriber, e));
                foreach (PositionedObject item in items)
                {
                    registeredItems[subscriber].AddSubscribed(item);
                    registeredItems[item].AddSubscriber(subscriber);
                }

                // Check what can see me!
                var revItems = regionItems[r].Where(e => inRange(e, subscriber));
                foreach (PositionedObject item in revItems)
                {
                    registeredItems[item].AddSubscribed(subscriber);
                    registeredItems[subscriber].AddSubscriber(item);
                }
            }
        }
 private Region[] getBorderRegions(PositionedObject i)
 {
     List<Region> list = new List<Region>();
     for (int x = -1; x < 2; x++)
     {
         for (int y = -1; y < 2; y++)
         {
             if (i.Region.XOrigin + x >= 0 && i.Region.YOrigin + y >= 0 && i.Region.XOrigin + x < world.RegionWidth - 1 && i.Region.YOrigin + y < world.RegionHeight - 1)  // TODO:  Need to check for past the other edge.
             {
                 list.Add(world.Regions.First(e => e.XOrigin == i.Region.XOrigin + x && e.YOrigin == i.Region.YOrigin + y));
             }
         }
     }
     return list.ToArray();
 }
 private void PurgeDistantItems(PositionedObject subscriber)
 {
     List<PositionedObject> tooDistant = registeredItems[subscriber].Subscribed.Where(e => outRange(subscriber, e)).ToList();
     foreach (PositionedObject po in tooDistant)
     {
         registeredItems[subscriber].RemoveSubscribed(po);
         registeredItems[po].RemoveSubscriber(subscriber);
     }
 }
Example #49
0
 public void ApplyTo(PositionedObject positionedObject)
 {
     positionedObject.AttachTo(Parent, false);
     positionedObject.RelativeRotationMatrix = RelativeRotationMatrix;
     positionedObject.RelativePosition = RelativePosition;
 }
Example #50
0
 public void ControlPositionedObjectAcceleration(PositionedObject positionedObject, float acceleration)
 {
     positionedObject.Acceleration.X = this.LeftStick.Position.X * acceleration;
     positionedObject.Acceleration.Y = this.LeftStick.Position.Y * acceleration;
 }
 private static void AssignCustomPropertyTo(PositionedObject entity, NamedValue property)
 {
     throw new NotImplementedException();
 }
Example #52
0
        public void ControlPositionedObjectDPad(PositionedObject positionedObject, float velocity)
        {
            if (ButtonDown(Button.DPadLeft))
                positionedObject.XVelocity = -velocity;
            else if (ButtonDown(Button.DPadRight))
                positionedObject.XVelocity = velocity;
            else
                positionedObject.XVelocity = 0;

            if (ButtonDown(Button.DPadUp))
                positionedObject.YVelocity = velocity;
            else if (ButtonDown(Button.DPadDown))
                positionedObject.YVelocity = -velocity;
            else
                positionedObject.YVelocity = 0;
        }