Monogame - игра в понг - ограничение области мыши

Я пытаюсь сделать простую игру в понг, и у меня есть две проблемы, с которыми я столкнулся и не могу понять.

Для игры в понг я хочу, чтобы ракетка игрока оставалась в пределах половины от Y и ниже, что означает, что он может перемещать ракетку в пределах половины «поля».

Мне удалось заставить весло остановиться в середине, однако оно исчезает после удара по центру. Можно ли остаться в пределах половины оси Y и не исчезнуть?

Другая проблема заключается в том, что ракетка и область игрока находятся в верхней, а не в нижней половине.

Game1.cs

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.IO;

namespace Xong
{
    /// <summary>
    /// This is the main type for your game.
    /// </summary>
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Texture2D redPaddle, bluePaddle, ball, blueBall, greyBall, bg1, bg2, bg3, bg4, elementBlue, elementRed;

        int BluePaddleX = 104;
        int BluePaddleY = 22;

        int RedPaddleX = 104;
        int RedPaddleY = 22;

        int BallX = 22;
        int BallY = 22;


        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }


        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(graphics.GraphicsDevice);

            redPaddle = Content.Load<Texture2D>("paddleRed.png");

            bluePaddle = Content.Load<Texture2D>("paddleBlu.png");

            blueBall = Content.Load<Texture2D>("ballBlue.png");

            greyBall = Content.Load<Texture2D>("ballGrey.png");

            elementBlue = Content.Load<Texture2D>("element_blue_square_glossy.png");

            elementRed = Content.Load<Texture2D>("element_red_square_glossy.png");


            bg1 = Content.Load<Texture2D>("set1_background.png");

            bg2 = Content.Load<Texture2D>("set2_background.png");

            bg3 = Content.Load<Texture2D>("set3_background.png");

            bg4 = Content.Load<Texture2D>("set4_background.png");




            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// game-specific content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <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

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin();

            MouseState mouseState = Mouse.GetState();


            int ScreenX = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
            int ScreenY = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;

            int PlayerBoundaryX = (ScreenX / 2) - (BluePaddleX / 2);
            int PlayerBoundaryY = (ScreenY / 2) - (BluePaddleY / 2);

            spriteBatch.Draw(bg1, new Rectangle(0, 0, ScreenX, ScreenY), Color.White);
            spriteBatch.Draw(redPaddle, new Vector2(ScreenX, ScreenY), Color.White);

            if ((mouseState.Y < (PlayerBoundaryY / 2)) && (mouseState.Y > 0))
            {
                spriteBatch.Draw(bluePaddle, new Vector2(mouseState.X, mouseState.Y), Color.White);
            }
            else
            {
                spriteBatch.Draw(bluePaddle, new Vector2(mouseState.X, PlayerBoundaryY), Color.White);
            }



            spriteBatch.Draw(greyBall, new Vector2(405, 240), Color.White);
            spriteBatch.End();
            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }





    }
}

введите здесь описание изображения


person Brian    schedule 10.06.2016    source источник
comment
Я не вижу вашего кода мыши, но вам нужно следить за движением мыши. Если они переместят его за пределы диапазона, которым вы хотите его ограничить, принудительно установите его в пределах границы. Например, если вы хотите, чтобы максимальное значение было 100, а они переместились на 200, ограничьте положение мыши до 100.   -  person Frecklefoot    schedule 10.06.2016
comment
@Frecklefoot Вот код мыши: if ((mouseState.Y ‹(PlayerBoundaryY / 2)) && (mouseState.Y› 0)) {spriteBatch.Draw (bluePaddle, new Vector2 (mouseState.X, mouseState.Y), Цвет белый); } else {spriteBatch.Draw (bluePaddle, новый Vector2 (mouseState.X, PlayerBoundaryY), Color.White); }   -  person Brian    schedule 11.06.2016
comment
Почему он проверяет PlayerBoundaryY, разделенный на 2? Вы упомянули, что весло появляется в верхней, а не в нижней половине. Вероятно, это как-то связано с этим.   -  person Frecklefoot    schedule 11.06.2016
comment
Логика состоит в том, что он берет общий размер экрана, делит его на два и удаляет половину высоты ракетки, так что она занимает ровно середину.   -  person Brian    schedule 11.06.2016


Ответы (1)


Вероятно, вам потребуется использовать метод Mouse.SetPosition, чтобы вернуть курсор к желаемому прямоугольнику.

Также я рекомендую реализовать вашу собственную «виртуальную мышь в стиле FPS» (каждый тик вы получаете относительные координаты мыши и толкаете реальный курсор мыши обратно в центр окна) над общим классом Mouse. Часто это хороший выбор, если у вас есть ограничения на перемещение курсора.

person Sergey.quixoticaxis.Ivanov    schedule 25.07.2016
comment
Также я предполагаю, что вы создаете Pong как личное упражнение, поэтому реализация вашей собственной виртуальной мыши - хорошее дополнение к нему =) Кстати, я подошел к этой проблеме точно так же, как и вы: я создавал Pong и мне нужно было ограничить движение мыши. - person Sergey.quixoticaxis.Ivanov; 25.07.2016