Contains() public method

public Contains ( Point value ) : bool
value Point
return bool
Esempio n. 1
0
        public bool HandleEvent(ISkinLayout skin, Rectangle layout, IGameContext context, Event @event)
        {
            var mousePressEvent = @event as MousePressEvent;
            if (mousePressEvent != null)
            {
                if (!layout.Contains(mousePressEvent.MouseState.X, mousePressEvent.MouseState.Y))
                {
                    return false;
                }

                State = LinkState.Clicked;

                Click?.Invoke(this, new EventArgs());

                return true;
            }

            var mouseReleaseEvent = @event as MouseReleaseEvent;
            if (mouseReleaseEvent != null)
            {
                if (!layout.Contains(mouseReleaseEvent.MouseState.X, mouseReleaseEvent.MouseState.Y))
                {
                    return false;
                }

                State = LinkState.None;
            }

            return false;
        }
Esempio n. 2
0
        public void ContainsPoint()
        {
            Rectangle rectangle = new Rectangle(0,0,64,64);

            var p1 = new Point(-1, -1);
            var p2 = new Point(0, 0);
            var p3 = new Point(32, 32);
            var p4 = new Point(63, 63);
            var p5 = new Point(64, 64);

            bool result;

            rectangle.Contains(ref p1, out result);
            Assert.AreEqual(false, result);
            rectangle.Contains(ref p2, out result);
            Assert.AreEqual(true, result);
            rectangle.Contains(ref p3, out result);
            Assert.AreEqual(true, result);
            rectangle.Contains(ref p4, out result);
            Assert.AreEqual(true, result);
            rectangle.Contains(ref p5, out result);
            Assert.AreEqual(false, result);

            Assert.AreEqual(false, rectangle.Contains(p1));
            Assert.AreEqual(true, rectangle.Contains(p2));
            Assert.AreEqual(true, rectangle.Contains(p3));
            Assert.AreEqual(true, rectangle.Contains(p4));
            Assert.AreEqual(false, rectangle.Contains(p5));
        }
 public bool LineIntersectsRect(Vector2 p1, Vector2 p2, Rectangle r)
 {
     return LineIntersectsLine(p1, p2, new Vector2(r.X, r.Y), new Vector2(r.X + r.Width, r.Y)) ||
            LineIntersectsLine(p1, p2, new Vector2(r.X + r.Width, r.Y), new Vector2(r.X + r.Width, r.Y + r.Height)) ||
            LineIntersectsLine(p1, p2, new Vector2(r.X + r.Width, r.Y + r.Height), new Vector2(r.X, r.Y + r.Height)) ||
            LineIntersectsLine(p1, p2, new Vector2(r.X, r.Y + r.Height), new Vector2(r.X, r.Y)) ||
            (r.Contains(p1) && r.Contains(p2));
 }
Esempio n. 4
0
 public static bool LineIntersectsRect(Point p1, Point p2, Rectangle r)
 {
     return LineIntersectsLine(p1, p2, new Point(r.X, r.Y), new Point(r.X + r.Width, r.Y)) ||
            LineIntersectsLine(p1, p2, new Point(r.X + r.Width, r.Y), new Point(r.X + r.Width, r.Y + r.Height)) ||
            LineIntersectsLine(p1, p2, new Point(r.X + r.Width, r.Y + r.Height), new Point(r.X, r.Y + r.Height)) ||
            LineIntersectsLine(p1, p2, new Point(r.X, r.Y + r.Height), new Point(r.X, r.Y)) ||
            (r.Contains(p1) && r.Contains(p2));
 }
Esempio n. 5
0
 //adapted from http://stackoverflow.com/questions/5514366/how-to-know-if-a-line-intersects-a-rectangle
 public static bool LineIntersectsRect(Vector2 p1, Vector2 p2, Rectangle r)
 {
     return LineIntersectsLine(p1, p2, new Vector2(r.X, r.Y), new Vector2(r.X + r.Width, r.Y)) ||
            LineIntersectsLine(p1, p2, new Vector2(r.X + r.Width, r.Y), new Vector2(r.X + r.Width, r.Y + r.Height)) ||
            LineIntersectsLine(p1, p2, new Vector2(r.X + r.Width, r.Y + r.Height), new Vector2(r.X, r.Y + r.Height)) ||
            LineIntersectsLine(p1, p2, new Vector2(r.X, r.Y + r.Height), new Vector2(r.X, r.Y)) ||
            (r.Contains(new Point((int)p1.X, (int)p1.Y)) && r.Contains(new Point((int)p2.X, (int)p2.Y)));
 }
Esempio n. 6
0
        public bool HandleEvent(ISkinLayout skin, Rectangle layout, IGameContext context, Event @event)
        {
            var mousePressEvent = @event as MousePressEvent;
            var touchPressEvent = @event as TouchPressEvent;

            if (mousePressEvent != null && mousePressEvent.Button == MouseButton.Left)
            {
                if (layout.Contains(mousePressEvent.MouseState.X, mousePressEvent.MouseState.Y))
                {
                    this.Focus();

                    return true;
                }
            }

            if (touchPressEvent != null)
            {
                if (layout.Contains((int)touchPressEvent.X, (int)touchPressEvent.Y))
                {
                    this.Focus();

#if PLATFORM_ANDROID
                    var manager = (InputMethodManager)Game.Activity.GetSystemService(Context.InputMethodService);
                    manager.ShowSoftInput(((Microsoft.Xna.Framework.AndroidGameWindow)context.Game.Window).GameViewAsView, ShowFlags.Forced);
#endif

                    return true;
                }
                else
                {
#if PLATFORM_ANDROID
                    var manager = (InputMethodManager)Game.Activity.GetSystemService(Context.InputMethodService);
                    manager.HideSoftInputFromWindow(((Microsoft.Xna.Framework.AndroidGameWindow)context.Game.Window).GameViewAsView.WindowToken, HideSoftInputFlags.None);
#endif
                }
            }

            var keyEvent = @event as KeyboardEvent;

            if (keyEvent != null)
            {
                var keyboard = keyEvent.KeyboardState;
                if (Focused)
                {
                    _keyboardReader.Process(keyboard, context.GameTime, _textBuilder);
                    if (_textBuilder.ToString() != _previousValue)
                    {
                        TextChanged?.Invoke(this, new EventArgs());
                    }

                    _previousValue = _textBuilder.ToString();

                    return true;
                }
            }

            return false;
        }
Esempio n. 7
0
 public static bool LineIntersectsRect(Vector2 pp1, Vector2 pp2, Rectangle r)
 {
     Point p1 = new Point((int)pp1.X, (int)pp1.Y);
     Point p2 = new Point((int)pp2.X, (int)pp2.Y);
     return LineIntersectsLine(p1, p2, new Point(r.X, r.Y), new Point(r.X + r.Width, r.Y)) ||
            LineIntersectsLine(p1, p2, new Point(r.X + r.Width, r.Y), new Point(r.X + r.Width, r.Y + r.Height)) ||
            LineIntersectsLine(p1, p2, new Point(r.X + r.Width, r.Y + r.Height), new Point(r.X, r.Y + r.Height)) ||
            LineIntersectsLine(p1, p2, new Point(r.X, r.Y + r.Height), new Point(r.X, r.Y)) ||
            (r.Contains(p1) && r.Contains(p2));
 }
Esempio n. 8
0
        public void HandleLeftArrow(MouseState mouseState, MouseState PrevMouseState)
        {
            string BoardSize = TilesWidth + "X" + TilesHeight;
            Vector2 BoardSizeLen = StartFont.MeasureString(BoardSize);

            string NumberOfShips = "Ships" + this.NumberOfShips;
            Vector2 NumberOfShipsLen = StartFont.MeasureString(NumberOfShips);
            Vector2 LeftBoardArrowLen = StartFont.MeasureString(LeftArrow);

            Rectangle LeftShipArrowRectangle = new Rectangle(Game.Window.ClientBounds.Width / 2 - (int)NumberOfShipsLen.X / 2 - (int)LeftBoardArrowLen.X * 2, Game.Window.ClientBounds.Height / 2 - (int)NumberOfShipsLen.Y / 2, (int)NumberOfShipsLen.X, (int)NumberOfShipsLen.Y);
            Rectangle LeftBoardArrowRectangle = new Rectangle(Game.Window.ClientBounds.Width / 2 - (int)BoardSizeLen.X / 2 - (int)LeftBoardArrowLen.X * 2, Game.Window.ClientBounds.Height / 2 + (int)BoardSizeLen.Y / 2, (int)LeftBoardArrowLen.X, (int)LeftBoardArrowLen.Y);

            if (mouseState.LeftButton == ButtonState.Released && PrevMouseState.LeftButton == ButtonState.Pressed && LeftBoardArrowRectangle.Contains(mouseState.Position))
            {
                if (TilesWidth > 8 && TilesHeight > 8 && TilesWidth <= 14 && TilesHeight <= 14)
                {
                    TilesWidth--;
                    TilesHeight--;
                }
            }
            if (mouseState.LeftButton == ButtonState.Released && PrevMouseState.LeftButton == ButtonState.Pressed && LeftShipArrowRectangle.Contains(mouseState.Position))
            {
                if (this.NumberOfShips > 4 && this.NumberOfShips > 4 && this.NumberOfShips <= 7 && this.NumberOfShips <= 7)
                {
                    this.NumberOfShips--;
                }
            }
        }
Esempio n. 9
0
        public void Update(EnemyManager director)
        {
            if (!isDisabled)
                {
                    //collision detection between enemy list and bounding box of shield
                    LinkedList<Enemy> removals = new LinkedList<Enemy>();
                    foreach (Enemy test in director.minions)
                    {
                        Rectangle box = new Rectangle(attached.Xpos - 15, attached.Ypos - 30,
                                                      image.Width, image.Height);

                        if (box.Contains((int)test.position.X, (int)test.position.Y))
                        {
                            removals.AddLast(test);
                            isDisabled = true;
                            recharge.set(downtime, true);
                        }
                    }
                    foreach (Enemy curr in removals)
                    {
                        director.minions.Remove(curr);
                    }
                }
                if (isDisabled)
                {
                    recharge.update();
                    if (recharge.ring())
                    {
                        isDisabled = false;
                    }
                }
        }
Esempio n. 10
0
 public void setCameraBounds(Vector2 cameraXBounds, Vector2 cameraYBounds)
 {
     cameraRect = new Rectangle(-1 * (int)cameraXBounds.X, -1 * (int)cameraYBounds.X,
         -1 * ((int)cameraXBounds.Y - (int)cameraXBounds.X), -1 * ((int)cameraYBounds.Y - (int)cameraYBounds.X));
     Console.WriteLine(cameraRect + " CAMERARECT");
     Console.WriteLine(cameraRect.Contains(new Vector2(145, 320)));
 }
Esempio n. 11
0
        public static bool PlaceEmpty(Vector2 position)
        {
            foreach (RoomLayer rl in roomLayers)
            {
                if (rl.Visible)
                {
                    if (rl is ObjectLayer)
                    {
                        ObjectLayer ol = (ObjectLayer)rl;
                        foreach (GameObject g in ol.Objects)
                        {
                            Rectangle r = new Rectangle((int)g.Position.X, (int)g.Position.Y, g.Sprite.ImageRectangle.Width, g.Sprite.ImageRectangle.Height);
                            if (r.Contains(position))
                            {
                                return(false);
                            }

                            if (g == currentObject)
                            {
                                continue;
                            }
                        }
                    }
                }
            }

            return(true);
        }
Esempio n. 12
0
        public static GameObject instance_place(Vector2 vec, Type go)
        {
            //roomLayers.Reverse();
            foreach (RoomLayer rl in roomLayers)
            {
                if (rl.Visible)
                {
                    if (rl is ObjectLayer)
                    {
                        ObjectLayer ol = (ObjectLayer)rl;
                        for (int i = ol.Objects.Count - 1; i >= 0; i--)
                        {
                            RectangleF r = new Rectangle((int)ol.Objects[i].Position.X, (int)ol.Objects[i].Position.Y, ol.Objects[i].Sprite.ImageRectangle.Width, ol.Objects[i].Sprite.ImageRectangle.Height);
                            if (r.Contains(vec))
                            {
                                if (ol.Objects[i].GetType() == go)
                                {
                                    //roomLayers.Reverse();
                                    return(ol.Objects[i]);
                                }
                            }
                        }
                    }
                }
            }

            // roomLayers.Reverse();
            return(null);
        }
Esempio n. 13
0
        private void DrawCharacter(SpriteBatch spriteBatch,
                                   Character character,
                                   Rectangle worldRegion,
                                   Vector2 viewBeginInWorld,
                                   Vector2 drawBeginPosition)
        {
            if (character == null)
            {
                return;
            }

            if (worldRegion.Contains((int)character.PositionInWorld.X, (int)character.PositionInWorld.Y))
            {
                var drawPositon = (character.PositionInWorld - viewBeginInWorld) / 4 + drawBeginPosition;
                if (character.IsEnemy)
                {
                    _enemy.Draw(spriteBatch, drawPositon);
                }
                else if (character.IsPartner)
                {
                    _partner.Draw(spriteBatch, drawPositon);
                }
                else if (character.IsPlayer)
                {
                    _player.Draw(spriteBatch, drawPositon);
                }
                else if (character.Kind == (int)Character.CharacterKind.Normal ||
                         character.Kind == (int)Character.CharacterKind.Fighter ||
                         character.Kind == (int)Character.CharacterKind.Eventer)
                {
                    _neutral.Draw(spriteBatch, drawPositon);
                }
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                Exit();
            }

            // TODO: Add your update logic here
            MouseState mouseState = Mouse.GetState();

            if (mouseState.LeftButton == ButtonState.Pressed)
            {
                //Debug.WriteLine($"Click to X:{mouseState.X}, Y:{mouseState.Y}");

                //GUI.additionalPanel.Drawer.OffsetsVector = new Vector2(
                //    x: mouseState.X - GUI.additionalPanel.Drawer.OffsetsRectangle.Size.X,
                //    y: mouseState.Y - GUI.additionalPanel.Drawer.OffsetsRectangle.Size.Y);
            }



            foreach (Content content in Contents.Content.Contents)
            {
                Rectangle Collider = new Rectangle(content.Drawer.OffsetsVector.ToPoint(), content.Drawer.OffsetsRectangle.Size);
                if (content.Drawer.IsVisible && Collider.Contains(mouseState.X, mouseState.Y))
                {
                    content.MouseHandler(mouseState, LastMouseState);
                }
            }


            LastMouseState = mouseState;
            base.Update(gameTime);
        }
Esempio n. 15
0
        /// <summary>
        /// 鼠标左键是否刚刚按下
        /// </summary>
        public bool IsNewMouseLeftButtonPressed(Rectangle rect)
        {
            if (!rect.Contains(CurrentMouseState.X, CurrentMouseState.Y)) return false;

            return (LastMouseState.LeftButton == ButtonState.Released)
                   && (CurrentMouseState.LeftButton == ButtonState.Pressed);
        }
Esempio n. 16
0
        /// <summary>
        /// 得到鼠标位置的变化量
        /// </summary>
        public Point GetMouseLocationOffset(Rectangle rect)
        {
            if (!rect.Contains(CurrentMouseState.X, CurrentMouseState.Y)) return new Point();

            return new Point(CurrentMouseState.X - LastMouseState.X,
                             CurrentMouseState.Y - LastMouseState.Y);
        }
Esempio n. 17
0
 public void Update(bool isMuteButton, GameTime gameTime)
 {
     MouseState mouse = Mouse.GetState();
     rectangle = new Rectangle((int)(position.X), (int)(position.Y), (int)(Size.X), (int)(Size.Y));
     Point mousePos = new Point(mouse.X, mouse.Y);
     if ((rectangle.Contains(mousePos) && mouse.LeftButton == ButtonState.Pressed && oldMouseState.LeftButton == ButtonState.Released)|| clickDetected)
     {
         clickDetected = true;
         if (normalTimer.CallTimer(gameTime) && !isMuteButton)
         {
             IsClicked = true;
             clickDetected = false;
         }
         else
         {
             if (isMuteButton && muteTimer.CallTimer(gameTime))
             {
                 IsClicked = true;
                 clickDetected = false;
             }
         }
     }
     else IsClicked = false;
     oldMouseState = mouse;
 }
Esempio n. 18
0
 public override void Draw(SpriteBatch spriteBatch, float minDepth, float maxDepth)
 {
     if (maxDepth >= 3.40282347E+38f && minDepth < 3.40282347E+38f)
     {
         spriteBatch.Draw(Main.blackTileTexture, new Rectangle(0, 0, Main.screenWidth, Main.screenHeight), Color.Black * this._fadeOpacity);
         spriteBatch.Draw(this._bgTexture, new Rectangle(0, Math.Max(0, (int)((Main.worldSurface * 16.0 - (double)Main.screenPosition.Y - 2400.0) * 0.10000000149011612)), Main.screenWidth, Main.screenHeight), Color.White * Math.Min(1f, (Main.screenPosition.Y - 800f) / 1000f) * this._fadeOpacity);
         Vector2 value = new Vector2((float)(Main.screenWidth >> 1), (float)(Main.screenHeight >> 1));
         Vector2 value2 = 0.01f * (new Vector2((float)Main.maxTilesX * 8f, (float)Main.worldSurface / 2f) - Main.screenPosition);
         spriteBatch.Draw(this._planetTexture, value + new Vector2(-200f, -200f) + value2, null, Color.White * 0.9f * this._fadeOpacity, 0f, new Vector2((float)(this._planetTexture.Width >> 1), (float)(this._planetTexture.Height >> 1)), 1f, SpriteEffects.None, 1f);
     }
     float scale = Math.Min(1f, (Main.screenPosition.Y - 1000f) / 1000f);
     Vector2 value3 = Main.screenPosition + new Vector2((float)(Main.screenWidth >> 1), (float)(Main.screenHeight >> 1));
     Rectangle rectangle = new Rectangle(-1000, -1000, 4000, 4000);
     for (int i = 0; i < this._bolts.Length; i++)
     {
         if (this._bolts[i].IsAlive && this._bolts[i].Depth > minDepth && this._bolts[i].Depth < maxDepth)
         {
             Vector2 value4 = new Vector2(1f / this._bolts[i].Depth, 0.9f / this._bolts[i].Depth);
             Vector2 position = (this._bolts[i].Position - value3) * value4 + value3 - Main.screenPosition;
             if (rectangle.Contains((int)position.X, (int)position.Y))
             {
                 Texture2D texture = this._boltTexture;
                 int life = this._bolts[i].Life;
                 if (life > 26 && life % 2 == 0)
                 {
                     texture = this._flashTexture;
                 }
                 float scale2 = (float)life / 30f;
                 spriteBatch.Draw(texture, position, null, Color.White * scale * scale2 * this._fadeOpacity, 0f, Vector2.Zero, value4.X * 5f, SpriteEffects.None, 0f);
             }
         }
     }
 }
Esempio n. 19
0
        /// <summary>
        /// Checks to see if a button group's rectangle is big enough to contain the button and if not expands it
        /// </summary>
        /// <param name="lButtonGroupArea">The current rectangle of the button group</param>
        public void AddToButtonGroup(ref Rectangle lButtonGroupArea)
        {
            if (!lButtonGroupArea.Contains(mLocation))
            {
                {
                    int xDist = mLocation.X - lButtonGroupArea.X;
                    if (xDist < 0)
                    {
                        lButtonGroupArea.X = mLocation.X;
                        lButtonGroupArea.Width -= xDist;
                    }

                    xDist = mLocation.Right - lButtonGroupArea.Right;
                    if (xDist > 0)
                    {
                        lButtonGroupArea.Width += xDist;
                    }
                }
                {
                    int yDist = mLocation.Y - lButtonGroupArea.Y;
                    if (yDist < 0)
                    {
                        lButtonGroupArea.Y = mLocation.Y;
                        lButtonGroupArea.Height -= yDist;
                    }

                    yDist = mLocation.Bottom - lButtonGroupArea.Bottom;
                    if (yDist > 0)
                    {
                        lButtonGroupArea.Height += yDist;
                    }
                }
            }
        }
Esempio n. 20
0
        protected override void InternalDraw(YSpriteBatch spritebatch, double frameTime)
        {
            Rectangle area = Model.ScreenArea;
            m_default.Render(spritebatch, area);

            area.X += m_hover.Buffer;

            foreach (MenuElement e in Model.Children)
            {
                bool elementDown = false;
                Vector2 v = Font.MeasureString(e.Label, m_FontSize);

                if (Model.IsMouseOver)
                {
                    Rectangle button = new Rectangle(area.X, area.Y, (int)v.X + m_hover.Buffer * 2, m_MenuHeight);
                    if (e.Enabled && button.Contains(Model.MousePosition))
                        if (Model.IsMouseDown)
                        {
                            m_pressed.Render(spritebatch, button);
                            elementDown = true;
                        }
                        else
                            m_hover.Render(spritebatch, button);
                }
                if (!elementDown)
                    area.Y--;
                Color font_color = e.Enabled ? Color.White : Color.Gray;
                spritebatch.DrawString(Font, e.Label, new Vector2(area.X + m_hover.Buffer, area.Y + (m_MenuHeight - v.Y) / 2f), m_FontSize, color: font_color);
                if (!elementDown)
                    area.Y++;
                area.X += (m_hover.Buffer * 2 + (int)v.X);
                area.Width -= (m_hover.Buffer * 2 + (int)v.X);
            }
        }
Esempio n. 21
0
        public void Draw(SpriteBatch spriteBatch, GraphicsDevice graphics, SpriteFont font)
        {
            // Calculate hand location on screen
            var screenWidth = graphics.PresentationParameters.BackBufferWidth;
            var y = _topHand ? 0 : graphics.PresentationParameters.BackBufferHeight - _cardHeight;
            var initHorizontalOffset = (screenWidth - _hand.Cards.Count * _cardWidth) / 2;

            // Create CardObject for each card in hand
            var cards = new List<CardObject>();
            foreach (var c in _hand.Cards.Select((x,i) => new { Card = x, Index = i }) )
            {
                var location = new Vector2(initHorizontalOffset + _cardWidth * c.Index, y);
                var texture = _cardsDB.LookupTexture(c.Card);

                var m = new Point(_mouseState.X, _mouseState.Y);
                var cardBounds = new Rectangle ((int)location.X, (int)location.Y, _cardWidth, _cardHeight);
                var selected = cardBounds.Contains(m);

                if (DateTime.Now.Millisecond == 0)
                {
                    Debug.WriteLine(cardBounds);
                    Debug.WriteLine(m);
                }

                var card = new CardObject(texture, location, _cardHeight, _cardWidth, 1, c.Card.FaceDown, selected);
                cards.Add(card);
            }

            // Loop through CardObjects and let them draw themselves in the right position
            foreach (var c in cards)
            {
                c.Draw(spriteBatch, graphics, font);
            }
        }
Esempio n. 22
0
        public override void Update(GameTime gameTime)
        {
            if (Selected && Game.KeyboardInput.TypedKey(Keys.Left))
            {
                Game.Audio.Play(Cues.Move02);
                Left();
            }
            if (Selected && Game.KeyboardInput.TypedKey(Keys.Right))
            {
                Game.Audio.Play(Cues.Move01);
                Right();
            }

            if (_rightRegion.Contains(TapLoaction))
            {
                Game.Audio.Play(Cues.Move02);
                Right();
                TapLoaction = Vector2.Zero;
            }
            if (!_leftRegion.Contains(TapLoaction))
            {
                return;
            }
            Game.Audio.Play(Cues.Move01);
            Left();
            TapLoaction = Vector2.Zero;
        }
Esempio n. 23
0
 public static Vector2 LevelBounce(Rectangle EntityCollisionBox, Rectangle LevelCollisionBox, float Bounciness)
 {
     if (!LevelCollisionBox.Contains(EntityCollisionBox))
     {
         if (EntityCollisionBox.Right > LevelCollisionBox.Right)
         {
             return new Vector2(-1, 1) * Bounciness;
         }
         else if (EntityCollisionBox.Left < LevelCollisionBox.Left)
         {
             return new Vector2(-1, 1) * Bounciness;
         }
         else if (EntityCollisionBox.Top < LevelCollisionBox.Top)
         {
             return new Vector2(1, -1) * Bounciness;
         }
         else if (EntityCollisionBox.Bottom > LevelCollisionBox.Bottom)
         {
             return new Vector2(1, -1) * Bounciness;
         }
         else
         {
             return Vector2.One;
         }
     }
     else
     {
         return Vector2.One;
     }
 }
Esempio n. 24
0
        /// <summary>
        /// Generates a grid of <see cref="Rectangle">Rectangles</see>.
        /// </summary>
        /// <param name="bounds">Bricks will be generated inside this rectangle</param>
        /// <param name="rectangleSize">The size for each individual rectangle</param>
        /// <param name="margin">The margin between each brick</param>
        /// <param name="pixel">A <see cref="Texture2D"> defining a single pixel</param>
        /// <returns></returns>
        private List <Rectangle> InitializeBricks(MonoRect bounds, Vector2 rectangleSize, Vector2 margin, Texture2D pixel)
        {
            Debug.Assert(bounds.Contains(new MonoRect(bounds.Location, rectangleSize.ToPoint())));

            var rectangles = new List <Rectangle>();

            Vector2 currentPos = bounds.Location.ToVector2();

            int rows    = (int)Math.Round(bounds.Height / (rectangleSize.Y + margin.Y));
            int columns = (int)Math.Round(bounds.Width / (rectangleSize.X + margin.X));

            for (int y = 0; y < rows; y++)
            {
                for (int x = 0; x < columns; x++)
                {
                    var rectangle = new Rectangle(currentPos, rectangleSize);
                    rectangle.init(pixel);
                    rectangles.Add(rectangle);

                    currentPos.X += rectangleSize.X + margin.X;
                }
                currentPos.X  = bounds.X;
                currentPos.Y += rectangleSize.Y + margin.Y;
            }

            return(rectangles);
        }
 public override bool isCollidingPosition(Microsoft.Xna.Framework.Rectangle position, xTile.Dimensions.Rectangle viewport, bool isFarmer, int damagesFarmer, bool glider, Character character, bool pathfinding, bool projectile = false, bool ignoreCharacterRequirement = false)
 {
     if (!glider)
     {
         foreach (Building building in this.buildings)
         {
             if (building.intersects(position))
             {
                 if (character != null && character.GetType() == typeof(FarmAnimal))
                 {
                     Microsoft.Xna.Framework.Rectangle rectForAnimalDoor = building.getRectForAnimalDoor();
                     rectForAnimalDoor.Height += Game1.tileSize;
                     if (rectForAnimalDoor.Contains(position) && building.buildingType.Contains((character as FarmAnimal).buildingTypeILiveIn))
                     {
                         continue;
                     }
                 }
                 else if (character != null && character is JunimoHarvester)
                 {
                     Microsoft.Xna.Framework.Rectangle rectForAnimalDoor = building.getRectForAnimalDoor();
                     rectForAnimalDoor.Height += Game1.tileSize;
                     if (rectForAnimalDoor.Contains(position))
                     {
                         continue;
                     }
                 }
                 return(true);
             }
         }
     }
     return(base.isCollidingPosition(position, viewport, isFarmer, damagesFarmer, glider, character, pathfinding, projectile, ignoreCharacterRequirement));
 }
Esempio n. 26
0
 public bool ContainsPoint(Point _point)
 {
     Rectangle r = new Rectangle((int)position.X,(int)position.Y,sideLength,sideLength);
        if(r.Contains(_point))
        return true;
        return false;
 }
        public static CollisionResponse CollisionCheck(BoundingCircle c, Rectangle r) {
            CollisionResponse result = new CollisionResponse();

            Vector2 closestPoint = ClosestPointPointRectangle(c.center, r);
	
	        float distanceSquared = Vector2.DistanceSquared(closestPoint,c.center);
            bool contained = r.Contains(c.center);
	        if(distanceSquared < c.radius * c.radius || contained){
		        result.collided = true;
		        result.normal = c.center - closestPoint;
		        result.normal.Normalize();
                //Special case for a circle with center inside the rectangle
                if (contained)
                {
                    result.normal = -result.normal;
                    result.penetrationDepth = c.radius + (float)Math.Sqrt(distanceSquared);
                }
                else {
                    result.penetrationDepth = c.radius - (float)Math.Sqrt(distanceSquared);
                }
                    
	        } else {
		        result.collided = false;
	        }

            return result;
        }
        public override void Update(GameTime gameTime)
        {
            // THIS SHOULD BE HANDLED BY INPUTMANAGER SOMEHOW!!
            MouseState mouseState = Mouse.GetState();

            Rectangle globalControlLoc = new Rectangle((int)GlobalLocation().X, (int)GlobalLocation().Y, (int)this.Size.X, (int)this.Size.Y);

            // hover
            if (globalControlLoc.Contains(mouseState.Position))
            {
                if (Hover != null)
                    Hover(this, EventArgs.Empty);

                // pressed
                if (lastFrameMouseState.LeftButton == ButtonState.Pressed)
                {
                    if (Pressed != null)
                        Pressed(this, EventArgs.Empty);

                    // released / click
                    if (mouseState.LeftButton == ButtonState.Released && Click != null)
                        Click(this, EventArgs.Empty);
                }
            }

            lastFrameMouseState = mouseState;

            base.Update(gameTime);
        }
Esempio n. 29
0
        private void UpdatePlayerView()
        {
            // Find out what the player can see
            map.ComputeFov(player.Position.X, player.Position.Y, 20, true);

            // Mark all render points as visible or not
            for (int i = 0; i < _cellData.CellCount; i++)
            {
                var point       = _cellData.GetPointFromIndex(i);
                var currentCell = map.GetCell(point.X, point.Y);

                if (currentCell.IsInFov)
                {
                    if (_cellData[i].Effect != null)
                    {
                        explored.Clear(_cellData[i]);
                        _cellData[i].Effect = null;
                    }

                    _cellData[i].IsVisible = true;
                    map.SetCellProperties(point.X, point.Y, currentCell.IsTransparent, currentCell.IsWalkable, true);
                }
                else if (currentCell.IsExplored)
                {
                    _cellData[i].IsVisible = true;
                    _cellData[i].Effect    = explored;
                    explored.Apply(_cellData[i]);
                }
                else
                {
                    _cellData[i].IsVisible = false;
                }
            }

            // Calculate the view area and sync it with our player location
            ViewArea = new Microsoft.Xna.Framework.Rectangle(player.Position.X - 15, player.Position.Y - 15, 30, 30);
            player.PositionOffset = this.Position - ViewArea.Location;


            // Check for entities.
            foreach (var entity in entities)
            {
                if (entity != player)
                {
                    entity.IsVisible = map.IsInFov(entity.Position.X, entity.Position.Y);

                    // Entity is in our view, but it may not be within the viewport.
                    if (entity.IsVisible)
                    {
                        entity.PositionOffset = this.Position - ViewArea.Location;

                        // If the entity is not in our view area we don't want to show it.
                        if (!ViewArea.Contains(entity.Position))
                        {
                            entity.IsVisible = false;
                        }
                    }
                }
            }
        }
Esempio n. 30
0
        /// <summary>
        /// This is a collision detection algorithom that tracks collisions between
        /// the mouse and any arbitrary 2D sprite
        /// </summary>
        /// <param name="rect"> Rectangle the sprite is in.</param>
        /// <param name="state">The current mouse state</param>
        /// <returns>bool stating if a collision occured</returns>
        public static bool CollisionWithMouse(Rectangle rect, MouseState state)
        {
            if (!rect.Contains(state.X, state.Y))
                return false;

            return true;
        }
Esempio n. 31
0
 //Update the input during character selection
 public static void UpdateCharacterSelectionInput()
 {
     var mouseState = Mouse.GetState();
     if(mouseState.LeftButton == ButtonState.Pressed)
     {
         mouseClicked = true;
     }
     if(mouseState.LeftButton == ButtonState.Released && mouseClicked)
     {
         mouseClicked = false;
         foreach (var character in OrusTheGame.Instance.GameInformation.AllCharacters)
         {
             Rectangle scaledBoundingBox = new Rectangle(
                 character.BoundingBox.X, character.BoundingBox.Y,
                 (int)(character.BoundingBox.Width * character.IddleAnimation.Scale),
                 (int)(character.BoundingBox.Height * character.IddleAnimation.Scale));
             if (scaledBoundingBox.Contains(mouseState.X, mouseState.Y))
             {
                 character.IddleAnimation.Scale = 1.5f;
             }
             else
             {
                 character.IddleAnimation.Scale = 1f;
             }
         }
     }
 }
Esempio n. 32
0
 public static bool Check(Rectangle rect1, Rectangle rect2, bool full)
 {
     if (full)
         return rect1.Contains(rect2);
     else
         return rect1.Intersects(rect2);
 }
Esempio n. 33
0
 /// <summary>
 /// Funckja sprawdzajaca zwawieranie punktu w obiekcie
 /// </summary>
 /// <param name="_point"></param>
 /// <returns></returns>
 public bool ContainsPoint(Point _point)
 {
     Rectangle r = new Rectangle((int)position.X, (int)position.Y, texture.Width, texture.Height);
     if (r.Contains(_point))
         return true;
     return false;
 }
Esempio n. 34
0
        public bool IsLocationOnBorderOrExit(Vector2 v)
        {
            // No placements on border tiles.
            if (v.X <= 0 || v.Y <= 0 || v.X >= (mapWidth.Value - 2) || v.Y >= (mapHeight.Value - 2))
            {
                return(true);
            }

            // No placements on exits.
            foreach (var exit in this.exits)
            {
                Microsoft.Xna.Framework.Rectangle exitRectangle = new Microsoft.Xna.Framework.Rectangle(exit.Location.X - Settings.Map.ExitRadius, exit.Location.Y - Settings.Map.ExitRadius, Settings.Map.ExitRadius * 2 + 1, Settings.Map.ExitRadius * 2 + 1);
                if (exitRectangle.Contains((int)v.X, (int)v.Y))
                {
                    return(true);
                }
            }

            // No placements on enter location as well.
            Microsoft.Xna.Framework.Rectangle enterRectangle = new Microsoft.Xna.Framework.Rectangle(enterLocation.X - Settings.Map.ExitRadius, enterLocation.Y - Settings.Map.ExitRadius, Settings.Map.ExitRadius * 2 + 1, Settings.Map.ExitRadius * 2 + 1);
            if (enterRectangle.Contains((int)v.X, (int)v.Y))
            {
                return(true);
            }

            return(false);
        }
        public void Draw(SpriteBatch spriteBatch, GraphicsDevice graphics, SpriteFont font)
        {
            // Calculate zone location on screen
            var screenHeight = graphics.PresentationParameters.BackBufferHeight;
            var screenWidth = graphics.PresentationParameters.BackBufferWidth;
            var padding = 5;
            var factoredPadding = padding * _factor;

            var height = (_cardHeight + 2 * factoredPadding);
            var width = ((_cardWidth + factoredPadding) * _battleZone.Capacity + factoredPadding);

            var offset = ((height + padding * 10) * _factor) / 2;
            var top = screenHeight / 2 - (_topZone ? offset : - offset - factoredPadding + height);
            var left = (screenWidth - width) / 2;

            var cardsTop = top + factoredPadding;
            var cardsLeft = left + factoredPadding;

            // Create CardObject for each card in hand
            var cards = new List<CardObject>();

            var m = new Point(_mouseState.X, _mouseState.Y);
            var cardCount = 0;

            // Draw the Zone

            DrawZone(spriteBatch, graphics, Color.Purple, left, top, width, height);

            // Draw the Cards
            foreach (var c in _battleZone.Cards.Select((x,i) => new { Card = x, Index = i }) )
            {
                var location = new Vector2(cardsLeft + (_cardWidth + padding) * _factor, cardsTop);
                var texture = _cardsDB.LookupTexture(c.Card);

                var cardBounds = new Rectangle ((int)location.X, (int)location.Y, _cardWidth, _cardHeight);
                var selected = cardBounds.Contains(m);

                var card = new CardObject(texture, location, _cardHeight, _cardWidth, 1, c.Card.FaceDown, selected);
                cards.Add(card);
                cardCount++;
            }

            // Creates empty Cards to fill in the BattleZone
            for (var i = 0; i < _battleZone.AvailableSlots; i++)
            {
                var location = new Vector2(cardsLeft + cardCount * (_cardWidth + factoredPadding), cardsTop);
                var cardBounds = new Rectangle((int)location.X, (int)location.Y, _cardWidth, _cardHeight);
                var selected = cardBounds.Contains(m);

                cards.Add(new CardObject(null, location, _cardHeight, _cardWidth, 1, false, selected, true));
                cardCount++;
            }

            // Loop through CardObjects and let them draw themselves in the right position
            foreach (var c in cards)
            {
                c.Draw(spriteBatch, graphics, font);
            }
        }
Esempio n. 36
0
 public void Draw(Rectangle rectangle, float dt)
 {
     foreach (var creature in _creatures)
     {
         if(rectangle.Contains(creature.Position))
            creature.Draw(dt);
     }
 }
Esempio n. 37
0
 public override void Update(float dtime)
 {
     Rectangle gameArea = new Rectangle(-100,-100,1400,800);
     if (!gameArea.Contains(AttachedTo.Position.ToPoint()))
     {
         AttachedTo.MarkForDestruction();
     }
 }
Esempio n. 38
0
        }

        public string Update(List<BaseUnit> VecUnits)
        {
            mouseState = Mouse.GetState();
            ClickedOnBuildUnit();
            //Updating for drawing selectedunits on panel
            screenLeftDownX = (int)camera.Pos.X - screenWight / 2;
            screenLeftDownY = (int)camera.Pos.Y + screenHeight;
            panel = new Rectangle(screenLeftDownX, screenLeftDownY - PanelHeight, screenWight, PanelHeight);
            

            //TODO вынести в отдельный метод
            keyboardState = Keyboard.GetState();
            if (mouseState.Position.X < 50 && camera._pos.X > screenWight / 2)    //camera movement
            {                                       //camera movement
                camera._pos += new Vector2(-10, 0); //camera movement
            }                                       //camera movement
            if (mouseState.Position.Y < 50 && camera._pos.Y > screenHeight / 2)    //camera movement
            {                                       //camera movement
                camera._pos += new Vector2(0, -10); //camera movement
            }                                       //camera movement
            if (mouseState.Position.Y > 680 && camera._pos.Y < map.tileHeight * map.height - screenHeight / 2) //camera movement
            {                                       //camera movement
                camera._pos += new Vector2(0, +10); //camera movement
            }                                       //camera movement
            if (mouseState.Position.X > 1230 && camera._pos.X < map.tileWidth * map.width - screenWight / 2)    //camera movement
            {                                       //camera movement
                camera._pos += new Vector2(10, 0);  //camera movement
            }                                       //camera movement

            // I thought thic code is extremely simple
            

            if (isClicded == false && mouseState.LeftButton == ButtonState.Pressed &&
               !panel.Contains( Vector2.Transform(mouseState.Position.ToVector2(), Matrix.Invert(camera.GetTransformation(graphics))))) // If clicked fisrt time
            {
                //Clean list of selecting unit becouse now will select new
                selectedUnits.Clear(); 
                //Transform pixel coords to window coords
                firstLeftClickCoord = Vector2.Transform(mouseState.Position.ToVector2(), Matrix.Invert(camera.GetTransformation(graphics)));
                isClicded = true;
            }
            else if (isClicded == true && mouseState.LeftButton == ButtonState.Pressed) // if moving mouse while selecting units 
            {
                currentMousePos = Vector2.Transform(mouseState.Position.ToVector2(), Matrix.Invert(camera.GetTransformation(graphics)));
                isDrawable = true;
            }
            else if (isClicded == true && mouseState.LeftButton == ButtonState.Released) // if have selected yet
            {
                isClicded = false;
                isDrawable = false;
                SelectUnits(VecUnits);

            }
            else if (mouseState.RightButton == ButtonState.Pressed)
            {
               currentMousePos = Vector2.Transform(mouseState.Position.ToVector2(), Matrix.Invert(camera.GetTransformation(graphics)));
                List<BaseUnit> fighters = new List<BaseUnit>();
                foreach (BaseUnit unit in VecUnits)
                {
                    if (unit is Fighter)
                    {
                        fighters.Add(unit);
                    }
                }
                foreach (Fighter unit in fighters)
                {
                    if (unit.unitBound.Contains(currentMousePos.X, currentMousePos.Y) && selectedUnits.Capacity != 0)
                    {
                        string msg = string.Empty;
                        List<BaseUnit> tmp = new List<BaseUnit>();
                        Attack = true;
                        foreach (BaseUnit fighter in selectedUnits)
                        {
                            if (fighter is Fighter)
                            {
                                tmp.Add(fighter);

                            }
                        }
                        foreach (Fighter fighter in tmp)
                        {
                            if (fighter != unit)
                            {
                                //fighter.setTarget(unit);
                                msg += "2 " + fighter.GN + " " + unit.GN;
                            }
                        }
                        return msg;

                    }
                }
                if (!Attack)
                {
                    if (VecUnits.Count == 0)
                        return null;

                    /* for (int j=0; j < VecUnits.Count; i++)
                         {
                           Вот тут надо сделать такое.
                           1. Метод BaseUnit который возвращает его rect.
                           2. Проверку на то, не перекает ли currentMousePos rect каждого юнита в Vecunits 
                           3 Если есть хоть какой-то юнит, и он вражеский, формируем запрос на атаку, возвращаем строку, и там уже она отошлется
                         } */
                    // Если никакого юнита там нет, формируем запрос на перемещение
                    foreach (Fighter unit in fighters)
                    {
                        unit.isAttacking = false;
                    }
                    return PrepareRequestMoveUnit();
                }
                Attack = false;
            }
            return null;
        }
        private  string PrepareRequestMoveUnit()
        {
            string commands = String.Empty;

            for (int i = 0; i < selectedUnits.Count(); i++)
            {
                 commands += "1" + " " + selectedUnits[i].GN.ToString() + " " +
                           ((int)currentMousePos.X).ToString() + " " + ((int)currentMousePos.Y).ToString() + " " + side.ToString() + "\n";
            }
            if (commands == string.Empty) return null;
            else return commands;
        }

        public void Draw()
        {
Esempio n. 39
0
        public override bool ContainsPoint(Vector2 point)
        {
            if (_boundingRectangle.Contains((int)point.X, (int)point.Y))
            {
                return(intersectPixels(point));
            }

            return(false);
        }
Esempio n. 40
0
        public override void behaviorAtGameTick(GameTime time)
        {
            base.behaviorAtGameTick(time);
            this.isEmoting = false;
            Microsoft.Xna.Framework.Rectangle boundingBox = this.GetBoundingBox();
            if (this.sprite.currentFrame < 4)
            {
                boundingBox.Inflate(Game1.tileSize * 2, Game1.tileSize * 2);
                if (!this.isInvisible || boundingBox.Contains(Game1.player.getStandingX(), Game1.player.getStandingY()))
                {
                    if (this.isInvisible)
                    {
                        if (Game1.currentLocation.map.GetLayer("Back").Tiles[(int)Game1.player.getTileLocation().X, (int)Game1.player.getTileLocation().Y].Properties.ContainsKey("NPCBarrier") || !Game1.currentLocation.map.GetLayer("Back").Tiles[(int)Game1.player.getTileLocation().X, (int)Game1.player.getTileLocation().Y].TileIndexProperties.ContainsKey("Diggable") && Game1.currentLocation.map.GetLayer("Back").Tiles[(int)Game1.player.getTileLocation().X, (int)Game1.player.getTileLocation().Y].TileIndex != 0)
                        {
                            return;
                        }
                        this.position = new Vector2(Game1.player.position.X, Game1.player.position.Y + (float)Game1.player.sprite.spriteHeight - (float)this.sprite.spriteHeight);
                        Game1.playSound(nameof(Duggy));
                        this.sprite.interval = 100f;
                        this.position        = Game1.player.getTileLocation() * (float)Game1.tileSize;
                    }
                    this.isInvisible = false;
                    this.sprite.AnimateDown(time, 0, "");
                }
            }
            if (this.sprite.currentFrame >= 4 && this.sprite.CurrentFrame < 8)
            {
                if (!this.hasDugForTreasure)
                {
                    this.getTileLocation();
                }
                boundingBox.Inflate(-Game1.tileSize * 2, -Game1.tileSize * 2);
                Game1.currentLocation.isCollidingPosition(boundingBox, Game1.viewport, false, 8, false, (Character)this);
                this.sprite.AnimateRight(time, 0, "");
                this.sprite.interval = 220f;
            }
            if (this.sprite.currentFrame >= 8)
            {
                this.sprite.AnimateUp(time, 0, "");
            }
            if (this.sprite.currentFrame < 10)
            {
                return;
            }
            this.isInvisible         = true;
            this.sprite.currentFrame = 0;
            this.hasDugForTreasure   = false;
            int     num           = 0;
            Vector2 tileLocation1 = this.getTileLocation();

            Game1.currentLocation.map.GetLayer("Back").Tiles[(int)tileLocation1.X, (int)tileLocation1.Y].TileIndex = 0;
            Game1.currentLocation.removeEverythingExceptCharactersFromThisTile((int)tileLocation1.X, (int)tileLocation1.Y);
            for (Vector2 tileLocation2 = new Vector2((float)(Game1.player.GetBoundingBox().Center.X / Game1.tileSize + Game1.random.Next(-12, 12)), (float)(Game1.player.GetBoundingBox().Center.Y / Game1.tileSize + Game1.random.Next(-12, 12))); num < 4 && ((double)tileLocation2.X <= 0.0 || (double)tileLocation2.X >= (double)Game1.currentLocation.map.Layers[0].LayerWidth || ((double)tileLocation2.Y <= 0.0 || (double)tileLocation2.Y >= (double)Game1.currentLocation.map.Layers[0].LayerHeight) || (Game1.currentLocation.map.GetLayer("Back").Tiles[(int)tileLocation2.X, (int)tileLocation2.Y] == null || Game1.currentLocation.isTileOccupied(tileLocation2, "") || (!Game1.currentLocation.isTilePassable(new Location((int)tileLocation2.X, (int)tileLocation2.Y), Game1.viewport) || tileLocation2.Equals(new Vector2((float)(Game1.player.getStandingX() / Game1.tileSize), (float)(Game1.player.getStandingY() / Game1.tileSize))))) || (Game1.currentLocation.map.GetLayer("Back").Tiles[(int)tileLocation2.X, (int)tileLocation2.Y].Properties.ContainsKey("NPCBarrier") || !Game1.currentLocation.map.GetLayer("Back").Tiles[(int)tileLocation2.X, (int)tileLocation2.Y].TileIndexProperties.ContainsKey("Diggable") && Game1.currentLocation.map.GetLayer("Back").Tiles[(int)tileLocation2.X, (int)tileLocation2.Y].TileIndex != 0)); ++num)
            {
                tileLocation2 = new Vector2((float)(Game1.player.GetBoundingBox().Center.X / Game1.tileSize + Game1.random.Next(-2, 2)), (float)(Game1.player.GetBoundingBox().Center.Y / Game1.tileSize + Game1.random.Next(-2, 2)));
            }
        }
Esempio n. 41
0
 public virtual bool ContainsPointOnScreen(Point point)
 {
     Rectangle rec = new Rectangle(
             (int)((posicao.X - cena.camaraAtual.Posicao.X + origem.X) * MyGame.instance.GraphicsDevice.Viewport.Width / cena.camaraAtual.Width),
             (int)((posicao.Y - cena.camaraAtual.Posicao.Y + origem.Y) * MyGame.instance.GraphicsDevice.Viewport.Height / cena.camaraAtual.Height),
             (int)(frameSize.X * escala.X) * MyGame.instance.GraphicsDevice.Viewport.Width / cena.camaraAtual.Width,
             (int)(frameSize.Y * escala.Y) * MyGame.instance.GraphicsDevice.Viewport.Height / cena.camaraAtual.Height);
     return rec.Contains(point);
 }
Esempio n. 42
0
        public override bool isTilePlaceable(Vector2 tile_location, Item item = null)
        {
            Point non_tile_position = Utility.Vector2ToPoint((tile_location + new Vector2(0.5f, 0.5f)) * 64f);

            if (!caveOpened && boulderPosition.Contains(non_tile_position))
            {
                return(false);
            }
            return(base.isTilePlaceable(tile_location, item));
        }
        public override void drawWaterTile(SpriteBatch b, int x, int y)
        {
            // Don't draw water on the void "ocean" tiles
            var point = new Point(x, y);

            if (StarPondWater.Contains(point) || CandyPondWater.Contains(point))
            {
                base.drawWaterTile(b, x, y);
            }
        }
Esempio n. 44
0
        private void MovePlayerByClick(MouseState mouseState)
        {
            var bufferRect = new Microsoft.Xna.Framework.Rectangle(0, 0, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight);

            // prevent processing mouse outside the window
            if (bufferRect.Contains(mouseState.X, mouseState.Y))
            {
                var point = viewport.TranslateMouse(mouseState.X, mouseState.Y);
                gameState.MovePlayer(point);
            }
        }
        public static bool Contains(this Microsoft.Xna.Framework.Rectangle rect, System.Drawing.Point p)
        {
            //create MonoGame version of System.Drawing.Point
            Microsoft.Xna.Framework.Point convPoint = new Microsoft.Xna.Framework.Point(p.X, p.Y);
            if (rect.Contains(convPoint))
            {
                return(true);
            }

            return(false);
        }
Esempio n. 46
0
 public void draw_item(SpriteBatch s, Rectangle map_view, Rectangle screen_view)
 {
     //Exilania.display.add_message("@05Try Drawing: map:" + map_view.ToString() + " screen:" + screen_view.ToString() + " loc:" + loc.ToString());
     if (map_view.Contains(loc))
     {
         Point  draw_at     = new Point(screen_view.X, screen_view.Y);
         double percent_map = (double)(loc.X - map_view.X) / (double)map_view.Width;
         draw_at.X  += (int)(percent_map * (double)screen_view.Width);
         percent_map = (double)(loc.Y - map_view.Y) / (double)map_view.Height;
         draw_at.Y  += (int)(percent_map * (double)screen_view.Height);
         s.Draw(Exilania.display.sprites, new Rectangle(draw_at.X - 3, draw_at.Y - 3, 6, 6), MiniMap.item_types[(int)type], Color.White);
     }
 }
Esempio n. 47
0
        public override bool isTilePlaceable(Vector2 tile_location, Item item = null)
        {
            Point non_tile_position = Utility.Vector2ToPoint((tile_location + new Vector2(0.5f, 0.5f)) * 64f);

            if (_exitsBlocked && turtle1Spot.Contains(non_tile_position))
            {
                return(false);
            }
            if (!westernTurtleMoved && turtle2Spot.Contains(non_tile_position))
            {
                return(false);
            }
            return(base.isTilePlaceable(tile_location, item));
        }
Esempio n. 48
0
        public override bool isTilePlaceable(Vector2 tile_location, Item item = null)
        {
            Point non_tile_position = Utility.Vector2ToPoint((tile_location + new Vector2(0.5f, 0.5f)) * 64f);

            if ((bool)landslide && landSlideRect.Contains(non_tile_position))
            {
                return(false);
            }
            if ((bool)railroadAreaBlocked && railroadBlockRect.Contains(non_tile_position))
            {
                return(false);
            }
            return(base.isTilePlaceable(tile_location, item));
        }
Esempio n. 49
0
 private void textureControl_MouseMove(object sender, MouseEventArgs e)
 {
     for (int i = 0; i < this.ExportedTSI.listDDS[this.DDSIndex].ListDDS_element.Count; i++)
     {
         Microsoft.Xna.Framework.Rectangle rect = new Microsoft.Xna.Framework.Rectangle(this.ExportedTSI.listDDS[this.DDSIndex].ListDDS_element[i].X, this.ExportedTSI.listDDS[this.DDSIndex].ListDDS_element[i].Y, this.ExportedTSI.listDDS[this.DDSIndex].ListDDS_element[i].Width, this.ExportedTSI.listDDS[this.DDSIndex].ListDDS_element[i].Height);
         if (rect.Contains(e.X, e.Y))
         {
             Aera aera = new Aera(this.textureControl.GraphicsDevice, rect, Microsoft.Xna.Framework.Graphics.Color.Red);
             this.textureControl.ClearAeras();
             this.textureControl.AddAera(aera);
             this.textBoxClipboard.Text = (this.DDSIndex * 169 + i).ToString();
             this.iconIndex             = i;
         }
     }
 }
Esempio n. 50
0
        private void CheckForStateChange()
        {
            if (_currentState == TransformStates.NotMoving)
            {
                if (_redArrowRect.Contains(_lastMousePosition.ToPoint()))
                {
                    if (InputManager.Instance.CurrentMouseState.LeftButton == ButtonState.Pressed)
                    {
                        _currentState     = TransformStates.MovingX;
                        MouseDownPosition = MousePosition;
                    }
                }

                if (_greenArrowRect.Contains(_lastMousePosition.ToPoint()))
                {
                    if (InputManager.Instance.CurrentMouseState.LeftButton == ButtonState.Pressed)
                    {
                        _currentState = TransformStates.MovingY;
                    }
                }

                if (yellowDotRect.Contains(_lastMousePosition.ToPoint()))
                {
                    if (InputManager.Instance.CurrentMouseState.LeftButton == ButtonState.Pressed)
                    {
                        _currentState = TransformStates.Moving;
                    }
                }

                if (_blueArrowRect.Contains((_lastMousePosition.ToPoint())))
                {
                    if (InputManager.Instance.CurrentMouseState.LeftButton == ButtonState.Pressed)
                    {
                        _currentState = TransformStates.Rotate;
                    }
                }
            }

            if (_currentState == TransformStates.MovingX || _currentState == TransformStates.MovingY || _currentState == TransformStates.Moving ||
                _currentState == TransformStates.Rotate)
            {
                if (InputManager.Instance.CurrentMouseState.LeftButton == ButtonState.Released &&
                    InputManager.Instance.PreviousMouseState.LeftButton == ButtonState.Released)
                {
                    _currentState = TransformStates.NotMoving;
                }
            }
        }
Esempio n. 51
0
        public static bool ClickedEggAtEggFestival(Vector2 clickPoint)
        {
            if (Game1.CurrentEvent is not null && Game1.CurrentEvent.FestivalName == "Egg Festival")
            {
                foreach (Prop prop in Game1.CurrentEvent.festivalProps)
                {
                    Rectangle boundingBox = ClickToMoveHelper.reflection.GetField <Rectangle>(prop, "boundingRect").GetValue();
                    if (boundingBox.Contains((int)clickPoint.X, (int)clickPoint.Y))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
 public static bool DecoratableLocation_IsFloorableOrWallpaperableTile_Prefix(DecoratableLocation __instance, int x, int y, ref bool __result)
 {
     if (!Config.EnableMod || !(__instance is FarmHouse))
     {
         return(true);
     }
     foreach (var room in ModEntry.currentRoomData.Values)
     {
         Rectangle rect = new Rectangle(room.startPos.X + 1, room.startPos.Y + 1, (__instance as FarmHouse).GetSpouseRoomWidth(), (__instance as FarmHouse).GetSpouseRoomHeight());
         if (rect.Contains(x, y))
         {
             __result = true;
             return(false);
         }
     }
     return(true);
 }
Esempio n. 53
0
 public override bool isCollidingPosition(Microsoft.Xna.Framework.Rectangle position, xTile.Dimensions.Rectangle viewport, bool isFarmer, int damagesFarmer, bool glider, Character character, bool pathfinding, bool projectile = false, bool ignoreCharacterRequirement = false)
 {
     if (!glider && buildings.Count > 0)
     {
         Microsoft.Xna.Framework.Rectangle playerBox = Game1.player.GetBoundingBox();
         FarmAnimal animal   = character as FarmAnimal;
         bool       isJunimo = character is JunimoHarvester;
         bool       isNPC    = character is NPC;
         foreach (Building b in buildings)
         {
             if (!b.intersects(position) || (isFarmer && b.intersects(playerBox)))
             {
                 continue;
             }
             if (animal != null)
             {
                 Microsoft.Xna.Framework.Rectangle door = b.getRectForAnimalDoor();
                 door.Height += 64;
                 if (door.Contains(position) && b.buildingType.Value.Contains(animal.buildingTypeILiveIn.Value))
                 {
                     continue;
                 }
             }
             else if (isJunimo)
             {
                 Microsoft.Xna.Framework.Rectangle door2 = b.getRectForAnimalDoor();
                 door2.Height += 64;
                 if (door2.Contains(position))
                 {
                     continue;
                 }
             }
             else if (isNPC)
             {
                 Microsoft.Xna.Framework.Rectangle door3 = b.getRectForHumanDoor();
                 door3.Height += 64;
                 if (door3.Contains(position))
                 {
                     continue;
                 }
             }
             return(true);
         }
     }
     return(base.isCollidingPosition(position, viewport, isFarmer, damagesFarmer, glider, character, pathfinding, projectile, ignoreCharacterRequirement));
 }
Esempio n. 54
0
        public static void EndSetWander()
        {
            int selX = game.selectedX;
            int selY = game.selectedY;

            wanderLoc2 = new Point(selX, selY);

            Microsoft.Xna.Framework.Rectangle wanderArea = new Microsoft.Xna.Framework.Rectangle(
                Math.Min(wanderLoc1.X, wanderLoc2.X),
                Math.Min(wanderLoc1.Y, wanderLoc2.Y),
                Math.Abs(wanderLoc1.X - wanderLoc2.X) + 1,
                Math.Abs(wanderLoc1.Y - wanderLoc2.Y) + 1);

            //if we are editing an NPC then set it's wander area
            if (editor.NPCEditRadio.Checked && editor.activeNPCEdit != null)
            {
                editor.activeNPCEdit.SetWanderArea(wanderArea);

                //if the npc is not in the wander area
                if (!wanderArea.Contains(editor.activeNPCEdit.tileCoords))
                {
                    //set the NPC to the top left corner of the area
                    game.world.currentArea.tile[editor.activeNPCEdit.tileCoords.X, editor.activeNPCEdit.tileCoords.Y].setOccupied(false);
                    for (int y = wanderArea.Y; y < wanderArea.Y + wanderArea.Height; y++)
                    {
                        for (int x = wanderArea.X; x < wanderArea.X + wanderArea.Width; x++)
                        {
                            if (game.world.currentArea.tile[x, y].isClear())
                            {
                                editor.activeNPCEdit.tileCoords = new Microsoft.Xna.Framework.Point(x, y);
                                game.world.currentArea.tile[x, y].setOccupied(true);
                                //exit the loop
                                y = wanderArea.Y + wanderArea.Height;
                                break;
                            }
                        }
                    }
                }
                toolType = NPCToolType.EditNPC;
            }
            else
            {
                toolType = NPCToolType.EditNPC;
            }
        }
Esempio n. 55
0
        /// <summary>Get whether a tile is blocked due to something it contains.</summary>
        /// <param name="location">The current location.</param>
        /// <param name="tile">The tile to check.</param>
        /// <param name="tilePixels">The tile area in pixels.</param>
        /// <remarks>Derived from <see cref="GameLocation.isCollidingPosition(Rectangle,xTile.Dimensions.Rectangle,bool)"/> and <see cref="Farm.isCollidingPosition(Rectangle,xTile.Dimensions.Rectangle,bool,int,bool,Character,bool,bool,bool)"/>.</remarks>
        private bool IsOccupied(GameLocation location, Vector2 tile, Rectangle tilePixels)
        {
            // show open gate as passable
            if (location.objects.TryGetValue(tile, out Object obj) && obj is Fence fence && fence.isGate.Value && fence.gatePosition.Value == Fence.gateOpenedPosition)
            {
                return(false);
            }

            // check for objects, characters, or terrain features
            if (location.isTileOccupiedIgnoreFloors(tile))
            {
                return(true);
            }

            // buildings
            if (location is BuildableGameLocation buildableLocation)
            {
                foreach (Building building in buildableLocation.buildings)
                {
                    Rectangle buildingArea = new Rectangle(building.tileX.Value, building.tileY.Value, building.tilesWide.Value, building.tilesHigh.Value);
                    if (buildingArea.Contains((int)tile.X, (int)tile.Y))
                    {
                        return(true);
                    }
                }
            }

            // large terrain features
            if (location.largeTerrainFeatures.Any(p => p.getBoundingBox().Intersects(tilePixels)))
            {
                return(true);
            }

            // resource clumps
            if (location is Farm farm)
            {
                if (farm.resourceClumps.Any(p => p.getBoundingBox(p.tile.Value).Intersects(tilePixels)))
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 56
0
        /// <inheritdoc/>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="spriteBatch"/> is a null reference.
        /// </exception>
        public void Draw(SpriteBatch spriteBatch)
        {
            if (spriteBatch == null)
            {
                throw new ArgumentNullException("spriteBatch");
            }

            if (this.rasterizerState != null)
            {
                spriteBatch.End();
                spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, this.rasterizerState);
                Microsoft.Xna.Framework.Rectangle preRectangle = spriteBatch.GraphicsDevice.ScissorRectangle;
                if (preRectangle.Contains(this.scissorRectangle))
                {
                    spriteBatch.GraphicsDevice.ScissorRectangle = this.scissorRectangle;
                }

                spriteBatch.DrawString(
                    this.font,
                    this.TextContent,
                    new Vector2(this.bounds.Location.X, this.bounds.Location.Y),
                    this.Color,
                    this.rotation,
                    this.origin,
                    this.textScale,
                    this.effects,
                    0F);
                spriteBatch.GraphicsDevice.ScissorRectangle = preRectangle;
            }
            else
            {
                spriteBatch.DrawString(
                    this.font,
                    this.TextContent,
                    new Vector2(this.bounds.Location.X, this.bounds.Location.Y),
                    this.Color,
                    this.rotation,
                    this.origin,
                    this.textScale,
                    this.effects,
                    0F);
            }
        }
 public override int getFishingLocation(Vector2 tile)
 {
     if (info.DimensionImplementation.CurrentStage() == 6)
     {
         // Maybe there's a better way but if you're standing on each other hopefully you're fishing the same spot
         var who   = farmers.Where(f => f.getTileLocation() == tile).First();
         var point = tile.ToPoint();
         if (who.FacingDirection == FacingDown && StarPondDownFacing.Contains(point) ||
             who.facingDirection == FacingRight && StarPondRightFacing.Contains(point) ||
             StarPondGeneral.Contains(point))
         {
             return(Mountain);
         }
         if (who.facingDirection == FacingLeft && CandyPondLeftFacing.Contains(point) ||
             CandyPondGeneral.Contains(point))
         {
             return(River);
         }
         return(Ocean);
     }
     return(base.getFishingLocation(tile));
 }
Esempio n. 58
0
 protected void addMoonlightJellies(int numTries, Random r, Microsoft.Xna.Framework.Rectangle exclusionRect)
 {
     for (int i = 0; i < numTries; i++)
     {
         Point tile = new Point(r.Next(base.Map.Layers[0].LayerWidth), r.Next(base.Map.Layers[0].LayerHeight));
         if (!isOpenWater(tile.X, tile.Y) || exclusionRect.Contains(tile) || FishingRod.distanceToLand(tile.X, tile.Y, this) < 2)
         {
             continue;
         }
         bool tooClose = false;
         foreach (TemporaryAnimatedSprite t in underwaterSprites)
         {
             Point otherTile = new Point((int)t.position.X / 64, (int)t.position.Y / 64);
             if (Utility.distance(tile.X, otherTile.X, tile.Y, otherTile.Y) <= 2f)
             {
                 tooClose = true;
                 break;
             }
         }
         if (!tooClose)
         {
             underwaterSprites.Add(new TemporaryAnimatedSprite("Maps\\Festivals", new Microsoft.Xna.Framework.Rectangle((r.NextDouble() < 0.2) ? 304 : 256, (r.NextDouble() < 0.01) ? 32 : 16, 16, 16), 250f, 3, 9999, new Vector2(tile.X, tile.Y) * 64f, flicker: false, flipped: false, 0.1f, 0f, Color.White * 0.66f, 4f, 0f, 0f, 0f)
             {
                 yPeriodic         = (Game1.random.NextDouble() < 0.76),
                 yPeriodicRange    = 12f,
                 yPeriodicLoopTime = Game1.random.Next(5500, 8000),
                 xPeriodic         = (Game1.random.NextDouble() < 0.76),
                 xPeriodicLoopTime = Game1.random.Next(5500, 8000),
                 xPeriodicRange    = 16f,
                 light             = true,
                 lightcolor        = Color.Black,
                 lightRadius       = 1f,
                 pingPong          = true
             });
         }
     }
 }
        private void Input_ButtonPressed(object sender, ButtonPressedEventArgs e)
        {
            if (e.Button.IsUseToolButton() || e.Button.IsActionButton())
            {
                Vector2           cursor  = e.Cursor.ScreenPixels;
                Interface.Desktop desktop = Game1.onScreenMenus.FirstOrDefault(menu => menu is Interface.Desktop) as Interface.Desktop;
                if (!desktop.Taskbar.IsExpanded)
                {
                    Microsoft.Xna.Framework.Rectangle area = desktop.Taskbar.ExpandButton.bounds;
                    area.Width  *= 3;
                    area.Height *= 3;
                    if (area.Contains((int)cursor.X, (int)cursor.Y))
                    {
                        desktop.Taskbar.SetActiveState(active: true);
                    }
                }
            }

            if (Config.DebugMode)
            {
                if (e.Button == SButton.I)
                {
                    Log.D("IS-ENTRY: Replacing Desktop");
                    Desktop.exitThisMenu();
                    Game1.activeClickableMenu = null;
                    Game1.onScreenMenus.Remove(Game1.onScreenMenus.FirstOrDefault(menu => menu is Interface.Desktop));
                    Desktop = new Interface.Desktop();
                    Game1.onScreenMenus.Add(Desktop);
                }
                else if (e.Button == SButton.O)
                {
                    Log.D("IS-ENTRY: Realigning Taskbar");
                    Desktop.Taskbar.RealignElements();
                }
            }
        }
Esempio n. 60
0
 public bool Contains(Vector point)
 {
     return(_rectangle.Contains(point.X, point.Y));
 }