Inheritance: Sprite
示例#1
0
        public void updatepaddle(Ball ball,Paddle P)
        {
            counter++;
            AIPaddle = P;
            Vector2 PaddleCenter = new Vector2(AIPaddle.Position.X, AIPaddle.Position.Y + (AIPaddle.Height) / 2);
            if (counter != Difficulty)
            {

                if (ball.Location.Y > (PaddleCenter.Y) && ball.Motion.X < 0)
                {
                    AIPaddle.computerinput(10);
                }
                else if (ball.Location.Y < (PaddleCenter.Y) && ball.Motion.X < 0)
                {
                    AIPaddle.computerinput(-10);
                }

                else if (ball.Motion.X < 0 && PaddleCenter.Y < 250)
                {
                    AIPaddle.computerinput(10);
                }
                else if (ball.Motion.X < 0 && PaddleCenter.Y > 250)
                {
                    AIPaddle.computerinput(-10);
                }
            }
            else { counter = 0; }
        }
示例#2
0
        /// <summary>
        /// Initialises Game Engine with given dimensions of game-world
        /// </summary>
        /// <param name="clientSize">dimensions of game-world</param>
        public GameEngine(Size clientSize)
        {
            this.clientSize = clientSize;
            ballStartPosition = new Point(clientSize.Width / 2, clientSize.Height / 2);
            ball = new Ball(BALL_SIZE, Color.Orange, clientSize, ballStartPosition);

            Size paddleSize = new Size(PADDLE_WIDTH, PADDLE_HEIGHT);

            Point paddlePosition = new Point(PADDLE_X, PADDLE_Y);
            leftPaddle = new Paddle(paddleSize, paddlePosition, Color.Red, clientSize, "femaleGrunt.wav");

            paddlePosition = new Point((clientSize.Width - PADDLE_WIDTH) - PADDLE_X, PADDLE_Y);
            rightPaddle = new Paddle(paddleSize, paddlePosition, Color.Red, clientSize, "maleGrunt.wav");

            topCentre = new Point((clientSize.Width / 2), 0);
            bottomCentre = new Point((clientSize.Width / 2), clientSize.Height);
            dashedLinePen = new Pen(Color.White, PENWIDTH);
            dashedLinePen.DashStyle = DashStyle.Dash;

            winConditions = false;

            int x = Convert.ToInt32((clientSize.Width * POSITION_1ST_QUARTER) - FONT_SIZE);
            Point position = new Point(x, (clientSize.Height / POSITION_Y_DIVISOR));
            scoreLeft = new Score(position);

            x = Convert.ToInt32((clientSize.Width * POSITION_3RD_QUARTER) - FONT_SIZE);
            position = new Point (x, (clientSize.Height / POSITION_Y_DIVISOR));
            scoreRight = new Score(position);
        }
示例#3
0
        public void Update(Paddle[] paddles)
        {
            Vector2 surfaceNormal;
            Vector2 orientation = Vector2.Normalize(Velocity);
            var oldEdge = Position + (Radius * orientation);
            var newEdge = oldEdge + Velocity;

            // Check to see if the ball is going to collide with a paddle or with the edges of the playfield
            foreach (var poly in new[] {
                Polygon.FromBounds(paddles[0].Bounds),
                Polygon.FromBounds(paddles[1].Bounds),
                Polygon.FromBounds(Playfield.Bounds),
            }) {
                var intersection = Geometry.LineIntersectPolygon(oldEdge, newEdge, poly, out surfaceNormal);

                if (!intersection.HasValue)
                    continue;

                // The ball is colliding, so we make it bounce off whatever it just hit
                Velocity = Vector2.Reflect(Velocity, surfaceNormal);

                return;
            }

            Position += Velocity;
        }
示例#4
0
 static void BounceX(Paddle p1, Ball b1)
 {
     if ((b1.Pos[1] <= p1.Pos[1] && b1.Pos[1] >= p1.Pos[1] - p1.Size) && (p1.Pos[0] >= b1.Pos[0] - (b1.Vel[0] + 1)   && p1.Pos[0] <= b1.Pos[0] + b1.Vel[0]))
     {
         b1.Vel[0] = -b1.Vel[0];
         b1.Last = p1;
     }
 }
示例#5
0
        public PongGame(Size ScreenDimensions)
        {
            PongBall = new Ball(new Vector2(0.0f, 0.0f), 1.0f);
            LeftPaddle = new Paddle(new Vector2(-19.0f, 0.0f), 3.0f);
            RightPaddle = new Paddle(new Vector2(19.0f, 0.0f), 3.0f);
            Board = new GameBoard(20.0f, 15.0f);

            Score = new int[2] { 0, 0 };
        }
示例#6
0
 protected override void Init()
 {
     base.Init();
     Entities.world2D.Gravity /= 10.0f;
     Entities.Register(new Sprite(new Texture("Background.jpg"), new Size(2.0f, 1.4f)));
     ball = new Ball(new Sprite(new Texture("Ball.png"), Constants.BallSize));
     ResetBall();
     var paddleTexture = new Texture("Paddle.png");
     leftPaddle = new Paddle(new Sprite(paddleTexture, Constants.PaddleSize),
         new Vector2D(Constants.LeftPaddleX, 0));
     rightPaddle = new Paddle(new Sprite(paddleTexture, Constants.PaddleSize),
         new Vector2D(Constants.RightPaddleX, 0));
 }
示例#7
0
        public void Update(Rectangle mainFrame, Paddle p1, Paddle p2)
        {
            if(start)
            {
                width = texture.Width;
                height = texture.Height;

                boundingBox = new Rectangle(((int)position.X), ((int)position.Y), width, height);
                if (boundingBox.Intersects(p1.boundingBox))
                    right = true;
                if (boundingBox.Intersects(p2.boundingBox))
                    right = false;

                if (position.Y <= 5)
                {
                    position.Y = 5;
                    up = true;
                }
                if (position.Y >= mainFrame.Height - 16)
                {
                    position.Y = mainFrame.Height - 16;
                    up = false;
                }
                if (position.X <= 5)
                {
                    position.X = 5;
                    right = true;
                    p2.points++;
                    Reset(mainFrame);
                }
                if (position.X >= mainFrame.Width - 15)
                {
                    position.X = mainFrame.Width - 15;
                    right = false;
                    p1.points++;
                    Reset(mainFrame);
                }

                if (right)
                    position.X += speedX;
                else
                    position.X -= speedX;

                if (up)
                    position.Y += speedY;
                else
                    position.Y -= speedY;
            }
        }
示例#8
0
文件: Game1.cs 项目: rubik951/Pong
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);

            var gameBoundaries = new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height);
            var paddleTexture = Content.Load<Texture2D>("Paddle");

            playerPaddle = new Paddle(paddleTexture, Vector2.Zero, gameBoundaries, PlayerTypes.Human);
            computerPaddle = new Paddle(paddleTexture, new Vector2(gameBoundaries.Width - paddleTexture.Width, 0), gameBoundaries, PlayerTypes.Computer);
            ball = new Ball(Content.Load<Texture2D>("Ball"), Vector2.Zero, gameBoundaries);
            ball.AttachTo(playerPaddle);

            score = new Score(Content.Load<SpriteFont>("GameFont"), gameBoundaries);

            gameObjects = new GameObjects { PlayerPaddle = playerPaddle, ComputerPaddle = computerPaddle, Ball = ball, Score=score };
        }
示例#9
0
        public GameScene()
        {
            this.Camera.SetViewFromViewport();
            _physics = new PongPhysics();

            ball = new Ball(_physics.SceneBodies[(int)PongPhysics.BODIES.Ball]);
            _player = new Paddle(Paddle.PaddleType.PLAYER,
                                 _physics.SceneBodies[(int)PongPhysics.BODIES.Player]);
            _ai = new Paddle(Paddle.PaddleType.AI,
                             _physics.SceneBodies[(int)PongPhysics.BODIES.Ai]);
            _scoreboard = new Scoreboard();

            this.AddChild(_scoreboard);
            this.AddChild(ball);
            this.AddChild(_player);
            this.AddChild(_ai);

            // This is debug routine that will draw the physics bounding box around the players paddle
            if(DEBUG_BOUNDINGBOXS)
            {
                this.AdHocDraw += () => {
                    var bottomLeftPlayer = _physics.SceneBodies[(int)PongPhysics.BODIES.Player].AabbMin;
                    var topRightPlayer = _physics.SceneBodies[(int)PongPhysics.BODIES.Player].AabbMax;
                    Director.Instance.DrawHelpers.DrawBounds2Fill(
                        new Bounds2(bottomLeftPlayer*PongPhysics.PtoM,topRightPlayer*PongPhysics.PtoM));

                    var bottomLeftAi = _physics.SceneBodies[(int)PongPhysics.BODIES.Ai].AabbMin;
                    var topRightAi = _physics.SceneBodies[(int)PongPhysics.BODIES.Ai].AabbMax;
                    Director.Instance.DrawHelpers.DrawBounds2Fill(
                        new Bounds2(bottomLeftAi*PongPhysics.PtoM,topRightAi*PongPhysics.PtoM));

                    var bottomLeftBall = _physics.SceneBodies[(int)PongPhysics.BODIES.Ball].AabbMin;
                    var topRightBall = _physics.SceneBodies[(int)PongPhysics.BODIES.Ball].AabbMax;
                    Director.Instance.DrawHelpers.DrawBounds2Fill(
                        new Bounds2(bottomLeftBall*PongPhysics.PtoM,topRightBall*PongPhysics.PtoM));
                };
            }

            //Now load the sound fx and create a player
            _pongSound = new Sound("/Application/audio/pongblip.wav");
            _pongBlipSoundPlayer = _pongSound.CreatePlayer();

            Scheduler.Instance.ScheduleUpdateForTarget(this,0,false);
        }
示例#10
0
        public void collision(Paddle pad)
        {
            //checks if a bullet has collided with another bullet
            int padx = pad.getX();
            int pady = pad.getY();
            int padw = pad.getWidth();
            int padh = pad.getHeight();
            // Console.WriteLine(padx + " " + pady + " " + ballx + " " + bally + " " + (padx <= ballx) + " " + (ballx <= padx + padw) + " " + (pady <= bally) + " " + (bally <= pady + padh));
            var bx = ballx + ballw / 2f;
            var by = bally + ballh / 2f;
            if (padx <= bx && bx <= padx + padw && pady <= by && by <= pady + padh)
            {
                dx *= -1;
                dy *= -1;
                /*if (pad.getPlayer() == 1)
                {
                    dx *= -1;
                    dy *= randomneg();
                }
                if (pad.getPlayer() == 2)
                {
                    dx *= -1;
                    dy *= randomneg();
                }
                if (pad.getPlayer() == 3)
                {
                    dx *= randomneg();
                    dy *= -1;
                }
                if (pad.getPlayer() == 4)
                {
                    dx *= randomneg();
                    dy *= -1;
                }*/

                //dx += 1;
                //dy += 1; */
            }
        }
示例#11
0
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            menuSprite = new Sprite();
            pointerSprite = new Sprite();
            creditSprite = new Sprite();
            gameOverSprite = new Sprite();

            gameball = new Ball(285, 285, 30, 30, 5, 5);
            paddle1 = new Paddle(1);
            paddle2 = new Paddle(2);
            paddle3 = new Paddle(3);
            paddle4 = new Paddle(4);
            ballsprite = new Sprite(gameball.getx(), gameball.gety());
            paddlesprite1 = new Sprite(paddle1.getX(), paddle1.getY());
            paddlesprite2 = new Sprite(paddle2.getX(), paddle2.getY());
            paddlesprite3 = new Sprite(paddle3.getX(), paddle3.getY());
            paddlesprite4 = new Sprite(paddle4.getX(), paddle4.getY());
            menu = new Menu();
        }
示例#12
0
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Initialize new SpriteBatch object which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            // Ask graphics device about screen bounds we are using.
            var screenBounds = GraphicsDevice.Viewport.Bounds;
            // Load paddle texture using Content.Load static method
            Texture2D paddleTexture = Content.Load<Texture2D>("paddle");
            // Create bottom and top paddles and set their initial position
            PaddleBottom = new Paddle(paddleTexture);
            PaddleTop = new Paddle(paddleTexture);
            // Position both paddles with help screenBounds object
            PaddleBottom.Position = new Vector2(150, screenBounds.Bottom - PaddleBottom.Size.Height);
            PaddleTop.Position = new Vector2(150, screenBounds.Top);
            // Load ball texture
            Texture2D ballTexture = Content.Load<Texture2D>("ball");

            // Create new ball object and set its initial position
            Ball = new Ball(ballTexture);
            Ball.Position = screenBounds.Center.ToVector2();
            // Load background texture and create a new background object.
            Texture2D backgroundTexture = Content.Load<Texture2D>("background");
            Background = new Background(backgroundTexture, screenBounds.Width,
             screenBounds.Height);
            // Load sounds
            HitSound = Content.Load<SoundEffect>("hit");
            Music = Content.Load<Song>("music");
            MediaPlayer.IsRepeating = true;
            // Start playing background music
            MediaPlayer.Play(Music);
            //dodavanje objekata za iscrtati
            SpritesForDrawList.Add(Background);
            SpritesForDrawList.Add(PaddleBottom);
            SpritesForDrawList.Add(PaddleTop);
            SpritesForDrawList.Add(Ball);

        }
示例#13
0
文件: Ball.cs 项目: rubik951/Pong
        public override void Update(GameTime gameTime, GameObjects gameObjects)
        {
            if (attachedToPaddle != null && Mouse.GetState().LeftButton == ButtonState.Pressed && Mouse.GetState().X > (gameBoundaries.Width/2) && Mouse.GetState().X < gameBoundaries.Width)
            {
                var newVelocity = new Vector2(3.5f, attachedToPaddle.Velocity.Y);
                Velocity = newVelocity;
                attachedToPaddle = null;
            }

            if (attachedToPaddle != null)
            {
                Location.X = attachedToPaddle.Location.X + attachedToPaddle.Width + 5;
                Location.Y = attachedToPaddle.Location.Y + attachedToPaddle.Height / 3;
            }
            else
            {
                if(BoundingBox.Intersects(gameObjects.PlayerPaddle.BoundingBox) || BoundingBox.Intersects(gameObjects.ComputerPaddle.BoundingBox))
                {
                    Velocity = new Vector2(-Velocity.X, Velocity.Y);
                }
            }

            base.Update(gameTime, gameObjects);
        }
示例#14
0
文件: Ball.cs 项目: StephGarland/Pong
        /// <summary>
        /// Reverses ball vertical velocity on collision with a paddle
        /// </summary>
        /// <param name="paddle">paddle to check for a collision with</param>
        public void PaddleCollisionY(Paddle paddle)
        {
            Rectangle ballBounds = new Rectangle(ballPosition.X, ballPosition.Y, ballSize, ballSize);
            Rectangle paddleBounds = new Rectangle(paddle.PaddlePosition, paddle.PaddleSize);

            if (ballBounds.IntersectsWith(paddleBounds))
            {
                if (velocity.Y > 0)
                {
                    ballPosition.Y -= (ballBounds.Bottom - paddleBounds.Top);
                }
                else
                {
                    ballPosition.Y -= (ballBounds.Top - paddleBounds.Bottom);
                }

                velocity.Y *= -1;
                paddle.CollisionSound.Play();
            }
        }
示例#15
0
文件: Ball.cs 项目: rubik951/Pong
 public void AttachTo(Paddle paddle)
 {
     attachedToPaddle = paddle;
 }
示例#16
0
 private bool IsTouchingRightOf(Paddle paddle)
 {
     return(this.BoundingBox.Left <= paddle.BoundingBox.Right &&
            this.BoundingBox.Top < paddle.BoundingBox.Bottom &&
            this.BoundingBox.Bottom > paddle.BoundingBox.Top);
 }
示例#17
0
        public override int CompareTo(Sprite obj)
        {
            Paddle obj1 = (Paddle)obj;

            return(this.CompareTo(obj1));
        }
示例#18
0
文件: Game1.cs 项目: ayrc/Pong
 /// <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
     this.IsMouseVisible = true;
     left = new Paddle();
     right = new Paddle();
     mBall = new Ball();
     rightCount = leftCount = 0;// = tickCounter = 0;
     base.Initialize();
 }
示例#19
0
        /// <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(GraphicsDevice);
            contentManager = Content;

            //Add component for accessing save state on xbox
            #if (XBOX)
            Components.Add(new GamerServicesComponent(this));
            #endif

            Texture2D tempTexture = Content.Load<Texture2D>("ball");
            ball = new Ball(this, tempTexture, screenRectangle);
            tempTexture = Content.Load<Texture2D>("paddle");
            player1Paddle = new Paddle(tempTexture, screenRectangle, 1);
            player2Paddle = new Paddle(tempTexture, screenRectangle, 2);
            font = Content.Load<SpriteFont>("font");
            bgcolor = Color.DarkSlateGray;

            SoundEffect music = Content.Load<SoundEffect>("music");
            Music = music.CreateInstance();
            Music.Volume = 0.05f;
            Music.IsLooped = true;
            beep = Content.Load<SoundEffect>("beep");

            // initialize save game data
            highScoreCount = 10;
            saveGameData.highScore = new int[highScoreCount];
            for (int i = 0; i < highScoreCount; i++)
            {
                saveGameData.highScore[i] = 0;
            }
            // Load save game high score into saveGameData struct
            GetDevice();

            StartGame();
        }
示例#20
0
文件: Ball.cs 项目: mayur70/Pong
 public bool Collides(Paddle paddle)
 {
     return(transform.Intersects(paddle.transform));
 }
示例#21
0
        public GameScene(bool localMultiplayer)
        {
            this.Camera.SetViewFromViewport();
            m_physics = new PongPhysics();

            m_ball = new Ball(m_physics.SceneBodies[(int)PongPhysics.BODIES.Ball]);
            if (localMultiplayer == true)
            {
                m_player1 = new Paddle(Paddle.PaddleType.PLAYER1,
                                       m_physics.SceneBodies[(int)PongPhysics.BODIES.Player1]);
                m_player2 = new Paddle(Paddle.PaddleType.PLAYER2,
                                       m_physics.SceneBodies[(int)PongPhysics.BODIES.Player2]);

                this.AddChild(m_player1);
                this.AddChild(m_player2);
            }
            else
            {
                m_player1 = new Paddle(Paddle.PaddleType.PLAYER1,
                                       m_physics.SceneBodies[(int)PongPhysics.BODIES.Player1]);
                m_ai = new Paddle(Paddle.PaddleType.AI,
                                  m_physics.SceneBodies[(int)PongPhysics.BODIES.Ai]);

                this.AddChild(m_player1);
                this.AddChild(m_ai);
            }

            m_scoreboard = new Scoreboard();

            this.AddChild(m_scoreboard);
            this.AddChild(m_ball);


            // This is debug routine that will draw the physics bounding box around the players paddle
            if (DEBUG_BOUNDINGBOXS)
            {
                this.AdHocDraw += () => {
                    var bottomLeftPlayer = m_physics.SceneBodies[(int)PongPhysics.BODIES.Player1].AabbMin;
                    var topRightPlayer   = m_physics.SceneBodies[(int)PongPhysics.BODIES.Player1].AabbMax;
                    Director.Instance.DrawHelpers.DrawBounds2Fill(
                        new Bounds2(bottomLeftPlayer * PongPhysics.PtoM, topRightPlayer * PongPhysics.PtoM));

                    var bottomLeftPlayer2 = m_physics.SceneBodies[(int)PongPhysics.BODIES.Player2].AabbMin;
                    var topRightPlayer2   = m_physics.SceneBodies[(int)PongPhysics.BODIES.Player2].AabbMax;
                    Director.Instance.DrawHelpers.DrawBounds2Fill(
                        new Bounds2(bottomLeftPlayer2 * PongPhysics.PtoM, topRightPlayer2 * PongPhysics.PtoM));


                    var bottomLeftAi = m_physics.SceneBodies[(int)PongPhysics.BODIES.Ai].AabbMin;
                    var topRightAi   = m_physics.SceneBodies[(int)PongPhysics.BODIES.Ai].AabbMax;
                    Director.Instance.DrawHelpers.DrawBounds2Fill(
                        new Bounds2(bottomLeftAi * PongPhysics.PtoM, topRightAi * PongPhysics.PtoM));

                    var bottomLeftBall = m_physics.SceneBodies[(int)PongPhysics.BODIES.Ball].AabbMin;
                    var topRightBall   = m_physics.SceneBodies[(int)PongPhysics.BODIES.Ball].AabbMax;
                    Director.Instance.DrawHelpers.DrawBounds2Fill(
                        new Bounds2(bottomLeftBall * PongPhysics.PtoM, topRightBall * PongPhysics.PtoM));
                };
            }

            //Now load the sound fx and create a player
            m_pongSound           = new Sound("/Application/audio/pongblip.wav");
            m_pongBlipSoundPlayer = m_pongSound.CreatePlayer();

            Scheduler.Instance.ScheduleUpdateForTarget(this, 0, false);
        }
示例#22
0
 public GameState(Rectangle r)
 {
     winRect = r;
     paddle  = new Paddle(r.Width / 2, r.Height - 30);
     ball    = new Ball(0, 0);
 }
示例#23
0
        // I'm using this method so that clips on vertical boundaries behave appropriately
        // simply inverting makes the ball get stuck as it is within the paddle for multiple ticks
        // eg.  Only invert if ball is heading in the opposite direction
        private void SetXVelocity(bool pos, Paddle paddle)
        {
            if (!pos && Velocity.X > 0f || pos && Velocity.X < 0f)
            {
                var centerX = BoundingBox.Center.X;
                var centerY = BoundingBox.Center.Y;

                var paddleYCenter = paddle.BoundingBox.Center.Y;
                var paddleTop     = paddle.BoundingBox.Top;
                var paddleBottom  = paddle.BoundingBox.Bottom;


                float newVelX = GameConstants.BallXSpeed; //Velocity.X;
                float newVelY = Velocity.Y;
                if (Velocity.X < 0)
                {
                    newVelX = -newVelX;
                }

                int yPercent = 50;
                int xPercent = 50;

                if (centerY > paddleYCenter + paddle.BoundingBox.Height / 2 ||
                    centerY < paddleYCenter - paddle.BoundingBox.Height / 2)
                {
                    yPercent = 75;
                    xPercent = 25;
                }

                // at center point, decide to reflect up or down
                if (centerY >= paddleYCenter)
                {
                    // go up
                    newVelY = GameConstants.BallXSpeed;
                }
                else
                {
                    // go down
                    newVelY = -GameConstants.BallXSpeed;
                }

                // enforce mins and max
                if (yPercent > 90)
                {
                    yPercent = 90;
                }
                if (yPercent < 10)
                {
                    yPercent = 10;
                }
                if (xPercent > 90)
                {
                    xPercent = 90;
                }
                if (xPercent < 10)
                {
                    xPercent = 10;
                }


                // apply percent changes to velocities.  Should be no change yet at 50/50
                newVelY = newVelY * yPercent / 100;
                newVelX = newVelX * xPercent / 100;


                var newVelocity = new Vector2(-newVelX, newVelY);
                Velocity = newVelocity;
            }
        }
示例#24
0
 public void AttachTo(Paddle paddle)
 {
     _attachedToPaddle = paddle;
     lastHitWasRight   = false;
 }
示例#25
0
 public AI(Paddle P, int D)
 {
     AIPaddle = P;
     counter = 0;
     Difficulty = D;
 }
示例#26
0
        /// <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
            numPlayers = -1;

            p1 = new Paddle();
            p2 = new Paddle();

            ball = new Ball();

            base.Initialize();
        }
示例#27
0
 protected void gamestart()
 {
     playerleft = new Player(new Vector2(50, 480), font,"Player Left");
     playerright = new Player(new Vector2(600, 480), font,"Player Right");
     Left = new Paddle(0, 213, paddle, Keys.W, Keys.S);
     Right = new Paddle(740, 213, paddle, Keys.Up, Keys.Down);
     upb = new Boundary(0, 0, 750, 20);
     downb = new Boundary(0, 480, 750, 20);
     gameball = new Ball(ball, upb.boundary, downb.boundary, Left.boundary, Right.boundary, font);
     timestart.Start();
     timerstarted = true;
     gameball.keepinposition();
     gamescreen = GameScreens.GameState.Play;
     gametimer.Start();
 }
示例#28
0
        protected override void LoadContent()
        {
            base.LoadContent ();

            paddleOne = new Paddle (game, spriteBatch);
            paddleOne.Direction = new Vector2 (0, 0);
            paddleTwo = new Paddle (game, spriteBatch);
            paddleTwo.Direction = new Vector2 (0, 0);
            ball = new Ball (game, spriteBatch);
            ball.Direction = new Vector2 (0, 0);

            paddleOne.LoadContent (content);
            paddleOne.Position = new Vector2 (20, 20);

            paddleTwo.LoadContent (content);
            paddleTwo.Position = new Vector2 (GraphicsDevice.Viewport.Width - 40, GraphicsDevice.Viewport.Height - 100);

            ball.LoadContent (content);
            ball.Position = new Vector2 (GraphicsDevice.Viewport.Width + 10, 0);
        }
示例#29
0
        /// <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(GraphicsDevice);

            // create ball and paddle objects
            pongBall = new Ball(Content, new Vector2(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2), 10);
            pongBall.GiveRandomVelocity();

            leftPaddle = new Paddle(Content, 100, 20, "left", GraphicsDevice);
            rightPaddle = new Paddle(Content, 100, 20, "right", GraphicsDevice);

            // load audio components
            audioEngine = new AudioEngine(@"Content/Pong.xgs");
            waveBank = new WaveBank(audioEngine, @"Content/Wave Bank.xwb");
            soundBank = new SoundBank(audioEngine, @"Content/Sound Bank.xsb");

            // set the board rectangle to the size of the window, load the board texture
            boardRectangle = new Rectangle(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
            boardTexture = Content.Load<Texture2D>("board");

            playerOneScore = new Score(Content, new Vector2(WINDOW_WIDTH / 4, 25), 39, 75);
            playerTwoScore = new Score (Content, new Vector2 ((3 * (WINDOW_WIDTH / 4)), 25), 39, 75);
        }
示例#30
0
        protected override void SetupScene()
        {
            DefaultKeyBindings = false;

            CamSize = new Vector2(18 * RenderContext.ScreenAspectRatio, 18);
            System.Console.WriteLine(CamSize);

            Player1 = new Paddle(new Vector2((-CamSize.X / 2) + 1f, 0), new Vector2(1, 3))
            {
                Up        = Key.W,
                Down      = Key.S,
                WorldSize = CamSize,
            };

            Player2 = new Paddle(new Vector2((CamSize.X / 2) - 1f, 0), new Vector2(1, 3))
            {
                Up        = Key.Up,
                Down      = Key.Down,
                WorldSize = CamSize,
            };

            Ball = new Ball(0.5f)
            {
                FirstPlayer  = Player1,
                SecondPlayer = Player2,
                WorldSize    = CamSize,
            };

            SceneContext.AddActor(Player1);
            SceneContext.AddActor(Player2);
            SceneContext.AddActor(Ball);
            SceneContext.AddActor(new Actor(new PointLightComponent()
            {
                Name = "StaticLight",
                RelativeTranslation = new Vector3(0, 0, 10),
                Quadric             = 0.0125f,
                //Direction = new Vector3(0, 0, -1), // Let the light come from the direction of the camera
                //Color = new Vector4(1, 1, 0, 1),
            }));
            SceneContext.AddActor(new Actor(new DirectionalLightComponent()
            {
                Name = "StaticLight_",
                RelativeTranslation = new Vector3(0, 0, 10),
                Direction           = new Vector3(0, 0, -1), // Let the light come from the direction of the camera
                //Color = new Vector4(1, 1, 0, 1),
                CastShadow = false,
            }));

#if DEBUG
            //UISlider slider;
            //SceneContext.AddActor(new Actor(slider = new UISlider()
            //{
            //    Size = new Vector2(200, 200),
            //    MinValue = 0,
            //    MaxValue = 1,
            //}));
            //slider.SliderValueChanged += (e) =>
            //{
            //    SceneContext.GetActor("StaticLight").GetComponent<PointLightComponent>().Quadric = e.NewValue;
            //};
#endif

            var gen = new Aximo.Generators.Voronoi.VoronoiGeneratorOptions
            {
                Color1   = new Vector4(0.4f, 0.6f, 0.6f, 1),
                Color2   = new Vector4(0.4f, 0.4f, 0.6f, 1),
                MinDelta = 50,
                Seed     = 100,
                Points   = 8,
                Size     = new Vector2i(320, 240),
            };
            var groundMaterial = new Material()
            {
                DiffuseTexture = Texture.GetFromFile(AssetManager.GetAssetsPath("Textures/Voronoi/.png", gen)),
                //Ambient = 0.3f,
                //Shininess = 32.0f,
                //SpecularStrength = 0.5f,
                CastShadow = false,
            };
            SceneContext.AddActor(new Actor(new CubeComponent
            {
                RelativeScale       = new Vector3(CamSize.X, CamSize.Y, 1),
                RelativeTranslation = new Vector3(0, 0, -1),
                Material            = groundMaterial,
            }));

            SceneContext.AddActor(new Actor(new StatsComponent()));

            RenderContext.Camera = new OrthographicCamera(new Vector3(0, 0, 10))
            {
                Size      = CamSize,
                NearPlane = 0.001f,
                FarPlane  = 1000.0f,
                LookAt    = new Vector3(0, 0, 0),
                Up        = new Vector3(0, 1, 0),
            };
            RenderContext.BackgroundColor = new Vector4(0, 0, 0, 1);
        }
示例#31
0
        // Initialize
        protected override void Initialize()
        {
            Viewport viewport = GraphicsDevice.Viewport;

            // Create a Scene
            scene = new Scene(this);

            // Create a GUI
            gui       = new GUI(this, "heart16");
            gui.color = new Color(190, 147, 255);

            // Create an EventHandler
            eventHandler = new EventHandler(this);

            // Create an empty container GameObject
            GameObject container = new GameObject(this);

            container.name = "container";

            // Create an empty container GameObject
            Sprite background = new Sprite(this);

            background.color            = new Color(24, 24, 24);
            background.transform.Width  = viewport.Width;
            background.transform.Height = viewport.Height;

            // Create a Ball
            Ball ball = new Ball(this, "ball", width: 16, height: 16);

            ball.IgnoreCollision = false;

            // Create player1 player's Paddle
            Paddle player1 = new Paddle(this, width: 8, height: 96);

            player1.name            = "yellow";
            player1.IgnoreCollision = false;

            // Create player2 player's Paddle
            Paddle player2 = new Paddle(this, width: 8, height: 96);

            player2.name            = "red";
            player2.IgnoreCollision = false;

            // Add the game objects to the scene
            scene.rootNode.AddChild(eventHandler);
            scene.rootNode.AddChild(container);
            scene.rootNode.AddChild(gui);
            container.AddChild(background);
            container.AddChild(ball);
            container.AddChild(player1);
            container.AddChild(player2);

            // Add the ball objects to a list
            balls.Add(ball);

            // Add the player objects to a list
            players.Add(player1);
            players.Add(player2);

            eventHandler.CurrentState = EventHandler.State.Inactive;
            eventHandler.SetupGameObjects();

            base.Initialize();
        }
示例#32
0
文件: Ball.cs 项目: thiecrow/Pong
 public void AttachTo(Paddle paddle)
 {
     attachedToPaddle = paddle;
 }
示例#33
0
文件: Program.cs 项目: maciekak/Pong
        static void Main()
        {
            var window = new RenderWindow(new VideoMode(Configuration.WindowWidth, Configuration.WindowHeight), "Pong");

            window.SetKeyRepeatEnabled(false);

            var ball        = new Ball(new Vector2i(200, 200), new Vector2i(5, 5));
            var leftPaddle  = new Paddle(new Vector2i(30, 200));
            var rightPaddle = new Paddle(new Vector2i(Configuration.WindowWidth - 50, 200));
            var paddles     = new List <Paddle> {
                leftPaddle, rightPaddle
            };

            window.KeyPressed += (sender, args) =>
            {
                switch (args.Code)
                {
                case Keyboard.Key.Q:
                    leftPaddle.MoveUp();
                    break;

                case Keyboard.Key.A:
                    leftPaddle.MoveDown();
                    break;
                }

                switch (args.Code)
                {
                case Keyboard.Key.O:
                    rightPaddle.MoveUp();
                    break;

                case Keyboard.Key.L:
                    rightPaddle.MoveDown();
                    break;
                }
            };
            window.KeyReleased += (sender, args) =>
            {
                switch (args.Code)
                {
                case Keyboard.Key.Q:
                    leftPaddle.StopMovingUp();
                    break;

                case Keyboard.Key.A:
                    leftPaddle.StopMovingDown();
                    break;
                }

                switch (args.Code)
                {
                case Keyboard.Key.O:
                    rightPaddle.StopMovingUp();
                    break;

                case Keyboard.Key.L:
                    rightPaddle.StopMovingDown();
                    break;
                }
            };

            window.SetActive();
            while (window.IsOpen)
            {
                window.Closed += (sender, args) =>
                {
                    window.Close();
                };
                window.Clear();

                ball.CheckForCollision(paddles);

                ball.Update();
                paddles.ForEach(p => p.Update());

                window.DispatchEvents();
                window.Draw(ball);
                paddles.ForEach(p => window.Draw(p));
                window.Display();
                Thread.Sleep(1000 / 60);
            }
        }
示例#34
0
        static void Main(string[] args)
        {
            Console.Title = "Pong";
            bool end = true;

            Console.ReadKey();

            Ball[] b1 = new Ball[5];
            b1[0] = new Ball(10, 0, 1, 0);
            b1[1] = new Ball(10, 1, 2, 0);
            b1[2] = new Ball(10, 2, 3, 0);
            b1[3] = new Ball(10, 3, 4, 0);
            b1[4] = new Ball(10, 4, 5, 0);

            Paddle[] p1 = new Paddle[2];
            p1[0] = new Paddle(1, 5, 4, 'w', 's');
            p1[1] = new Paddle(100, 5, 4, 'i', 'k');

            while (end)
            {
                Console.Clear();

                foreach (Ball b in b1)
                {
                    foreach(Paddle p in p1)
                    {
                        DrawP(p);
                        BounceX( p, b);
                    }
                    BounceY(b);
                    MoveB(b);
                    DrawB(b);
                    if (b.score)
                        end = false;
                }

            }
            Console.ReadKey();
        }
示例#35
0
 public static void SendPaddlePosition(Paddle pd1, Paddle pd2)
 {
     Ball._paddle1 = pd1;
     Ball._paddle2 = pd2;
 }
示例#36
0
 static void DrawP(Paddle p1)
 {
     for (int i = 0; i <= p1.Size; i++)
     {
         try
         {
             Console.SetCursorPosition(p1.Pos[0], p1.Pos[1] - i);
             Console.Write(p1.Char);
         }
         catch { }
     }
 }
示例#37
0
        private void movePaddleLeft(Paddle paddle, GameTime gameTime)
        {
            var screenBounds = GraphicsDevice.Viewport.Bounds;

            paddle.X = MathHelper.Clamp(paddle.X - (float)(paddle.Speed * gameTime.ElapsedGameTime.TotalMilliseconds), 0, screenBounds.Width - paddle.Width);
        }
示例#38
0
 void DrawPaddle(Paddle p)
 {
     Raylib.DrawRectanglePro(new Rectangle(p.pos.X, p.pos.Y, p.size.X, p.size.Y), p.size / 2, 0.0f, Color.WHITE);
 }
示例#39
0
 void ResetGame()
 {
     paddle1 = new Paddle(10, 200);
     paddle2 = new Paddle(770, 200);
     ball    = new Ball(385, 285);
 }
示例#40
0
        int getDirection(Paddle paddle)
        {
            float originY = paddle.Position.Y;
            float ballCenter = ball.Position.Y + ball.Size.Height / 2;
            float paddleLocation = ballCenter - originY;
            int direction;

            if (paddleLocation < paddle.Size.Height / 5)
                direction = -2;
            else if (paddleLocation < paddle.Size.Height * 2 / 5)
                direction = -1;
            else if (paddleLocation <= paddle.Size.Height * 3 / 5)
                direction = 0;
            else if (paddleLocation <= paddle.Size.Height * 4 / 5)
                direction = 1;
            else
                direction = 2;

            return direction;
        }
示例#41
0
        /// <summary>
        ///  Update metod som "resettar" spelets state tillbaka till ursprung, kollar också ifall bollen är utanför skärmen(hela tiden)
        ///  Har också timer för att pausa mellan ronderna efter bollen gått bakom respektive sida går denna timer av och varar i 3 sekunder.
        /// </summary>
        #region Update metod
        public void Update(Paddle leftPaddle, Paddle rightPaddle, Ball ball1, GameWindow Window, Bonus box, GameTime gameTime)
        {
            if (ball1.BallPos.X <= 0 || ball1.BallPos.X >= 785)
            {
                newRound = true;
            }

            if (newRound == false)
            {
                startRound = true;
            }

            //ifall bollen gått längre än 785 på x värdet så får spelare 1 poäng och spelet resettas
            if (ball1.BallPos.X >= 785)
            {
                Score_1++;
                box.Intersect = false;

                ball1.BallPos = new Vector2((Window.ClientBounds.Width / 2) - 20, (Window.ClientBounds.Height / 2) - 20);

                leftPaddle.PaddlePos  = new Vector2(0, 340);
                rightPaddle.PaddlePos = new Vector2(779, 340);

                leftPaddle.PaddleHitbox  = new Rectangle((int)leftPaddle.PaddlePos.X, (int)leftPaddle.PaddlePos.Y, 21, 148);
                rightPaddle.PaddleHitbox = new Rectangle((int)rightPaddle.PaddlePos.X, (int)rightPaddle.PaddlePos.Y, 21, 148);

                box.BonusPos = new Vector2(1000, 1000);

                //Kollar ifall paddeln är liten, isåfall gör den stor igen nästa runda
                leftPaddle.Small = false;
                leftPaddle.Big   = true;

                rightPaddle.Small = false;
                rightPaddle.Big   = true;
            }

            //ifall bollen gått mindre än 0 på x värdet så får spelare 2 poäng och spelet resettas
            if (ball1.BallPos.X <= 0)
            {
                Score_2++;

                box.Intersect = false;

                ball1.BallPos = new Vector2((Window.ClientBounds.Width / 2) - 20, (Window.ClientBounds.Height / 2) - 20);

                leftPaddle.PaddlePos  = new Vector2(0, 340);
                rightPaddle.PaddlePos = new Vector2(779, 340);

                leftPaddle.PaddleHitbox  = new Rectangle((int)leftPaddle.PaddlePos.X, (int)leftPaddle.PaddlePos.Y, 21, 148);
                rightPaddle.PaddleHitbox = new Rectangle((int)rightPaddle.PaddlePos.X, (int)rightPaddle.PaddlePos.Y, 21, 148);

                box.BonusPos = new Vector2(1000, 1000);

                //Kollar ifall paddeln är liten, isåfall gör den stor igen nästa runda
                leftPaddle.Small = false;
                leftPaddle.Big   = true;

                rightPaddle.Small = false;
                rightPaddle.Big   = true;
            }

            //Timer som pausar spelet direkt efter en spelare gjort mål, spelet pausas i 3 sekunder
            if (newRound == true)
            {
                timer     += gameTime.ElapsedGameTime.TotalSeconds;
                startRound = false;

                if (timer >= 3)
                {
                    timer      = 0;
                    newRound   = false;
                    startRound = true;
                }
            }
        }
示例#42
0
 public void move(Paddle pad1, Paddle pad2, Paddle pad3, Paddle pad4)
 {
     ballx += dx;
     bally += dy;
     collision(pad1);
     collision(pad2);
     collision(pad3);
     collision(pad4);
 }
示例#43
0
 public Player(IInputHandler inputHandler, Paddle paddle)
 {
     _inputHandler = inputHandler;
     _paddle       = paddle;
 }
示例#44
0
        public static void Main(string[] args)
        {
            VideoMode    vMode   = new VideoMode(640, 480);
            RenderWindow rWindow = new RenderWindow(vMode, "Pong");                 // creamos la ventana de juego

            rWindow.SetFramerateLimit(60);

            HUD hud = new HUD();

            bool playing;


            RectangleShape line = new RectangleShape();

            line.Size      = new Vector2f(2, 480);
            line.Position  = new Vector2f(640 / 2, 0);
            line.FillColor = new Color(Color.White);


            Text player1_Score;
            Text player2_Score;
            Font fuente = new Font("Data/consola.ttf");

            player1_Score          = new Text(hud.GetHudScore(1), fuente, 65);
            player1_Score.Position = new Vector2f(160, 10);
            player2_Score          = new Text(hud.GetHudScore(2), fuente, 65);
            player2_Score.Position = new Vector2f(480, 10);


            Paddle paddle1 = new Paddle(1);
            Paddle paddle2 = new Paddle(2);

            paddle1.FillColor = new Color(Color.White);
            paddle2.FillColor = new Color(Color.White);


            Ball ball = new Ball();

            ball.FillColor = new Color(Color.White);


            playing = true;
            while (playing)
            {
                playing = CheckForEnd(hud);

                player1_Score          = new Text(hud.GetHudScore(1), fuente, 65);
                player1_Score.Position = new Vector2f(160, 10);
                player2_Score          = new Text(hud.GetHudScore(2), fuente, 65);
                player2_Score.Position = new Vector2f(480, 10);

                paddle1.Movement(1);
                paddle2.Movement(2);

                SendPaddlePosition(paddle1, paddle2);
                ball.Movement();

                rWindow.Draw(line);
                rWindow.Draw(ball);
                rWindow.Draw(paddle1);
                rWindow.Draw(paddle2);
                rWindow.Draw(player1_Score);
                rWindow.Draw(player2_Score);

                rWindow.Display();
                rWindow.Clear(Color.Black);
            }

            rWindow.Close();
        }
示例#45
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)
        {
            // Allows the game to exit
            //if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            //    this.Exit();

            // TODO: Add your update logic here
            myKeyboard.Update();
            Random random = new Random();

            x = random.Next(0, 255);
            y = random.Next(0, 255);
            z = random.Next(0, 255);

            if (change == 1)
            {
                a = random.Next(0, 200);
                b = random.Next(0, 200);
                c = random.Next(0, 200);
            }

            if (gameState == GameState.Menu)
            {
                fromMenu = true;
                player1  = new Paddle(vPaddle, Paddle.Player.Player1);
                player2  = new Paddle(vPaddle2, Paddle.Player.Player2);
                ball     = new Ball();
                //check if enter present to set to play game
                if (myKeyboard.IsNewKeyPress(Keys.Enter))
                {
                    gameState = GameState.Play;
                }
                else if (myKeyboard.IsNewKeyPress(Keys.I))
                {
                    gameState = GameState.Instructions;
                }
                //menu to settings
                else if (myKeyboard.IsNewKeyPress(Keys.S))
                {
                    gameState = GameState.Settings;
                }
                else if (myKeyboard.IsNewKeyPress(Keys.Escape))
                {
                    gameState = GameState.Exit;
                }
                //initalize the ball and the player paddles
            }
            if (gameState == GameState.Instructions)
            {
                //instructions to main menu
                if (myKeyboard.IsKeyPress(Keys.M))
                {
                    gameState = GameState.Menu;
                }
            }
            //setting buttons
            if (gameState == GameState.Settings)
            {
                //settings to main menu
                if (myKeyboard.IsNewKeyPress(Keys.M))
                {
                    gameState = GameState.Menu;
                }
                if (myKeyboard.IsNewKeyPress(Keys.E))
                {
                    difficulty = Difficulty.Easy;
                }
                if (myKeyboard.IsNewKeyPress(Keys.H))
                {
                    difficulty = Difficulty.Hard;
                }
                if (myKeyboard.IsNewKeyPress(Keys.G))
                {
                    theme = Theme.Green;
                }
                if (myKeyboard.IsNewKeyPress(Keys.B))
                {
                    theme = Theme.Black;
                }
                if (myKeyboard.IsNewKeyPress(Keys.P))
                {
                    theme = Theme.Pink;
                }
                if (myKeyboard.IsNewKeyPress(Keys.R))
                {
                    theme = Theme.Rave;
                }
                if (myKeyboard.IsNewKeyPress(Keys.C))
                {
                    theme = Theme.Changing;
                }
            }
            //in game buttons
            if (gameState == GameState.Play)
            {
                fromMenu = false;
                //pause game
                if (myKeyboard.IsNewKeyPress(Keys.P))
                {
                    gameState = GameState.Pause;
                }

                //exit game
                if (myKeyboard.IsNewKeyPress(Keys.Escape))
                {
                    gameState = GameState.Exit;
                }
            }

            //pause buttons
            if (gameState == GameState.Pause)
            {
                //pause to resume
                if (myKeyboard.IsNewKeyPress(Keys.Enter))
                {
                    gameState = GameState.Play;
                }

                //pause to escape
                if (myKeyboard.IsNewKeyPress(Keys.Escape))
                {
                    gameState = GameState.Exit;
                }

                //pause to main menu
                if (myKeyboard.IsNewKeyPress(Keys.M))
                {
                    gameState = GameState.Menu;
                }
                if (myKeyboard.IsNewKeyPress(Keys.R))
                {
                    gameState    = GameState.Play;
                    ball.points1 = 0;
                    ball.points2 = 0;
                    player1      = new Paddle(vPaddle, Paddle.Player.Player1);
                    player2      = new Paddle(vPaddle2, Paddle.Player.Player2);
                    ball.Reset();
                }
            }

            //exit buttons
            if (gameState == GameState.Exit)
            {
                //exit
                if (myKeyboard.IsNewKeyPress(Keys.Y))
                {
                    Exit();
                }

                //resume
                if (myKeyboard.IsNewKeyPress(Keys.N))
                {
                    if (fromMenu == false)
                    {
                        gameState = GameState.Play;
                    }
                    else
                    {
                        gameState = GameState.Menu;
                    }
                }
            }

            if (gameState == GameState.Play)
            {
                ball.Update();
                player1.Update(myKeyboard);
                player2.Update(myKeyboard);
            }



            if (ball.Boundary.Intersects(player1.Boundary))
            {
                if (ball.speed < 12)
                {
                    ball.velocity.X *= -1.1f;
                    ball.speed       = (float)ball.velocity.Length();
                    paddle.Play();
                }
                else
                {
                    ball.velocity.X *= -1;
                    paddle.Play();
                }
            }
            //
            if (ball.Boundary.Intersects(player2.Boundary))
            {
                //paddle
                if (ball.speed < 12)
                {
                    ball.velocity.X *= -1.1f;
                    ball.speed       = (float)ball.velocity.Length();
                    paddle.Play();
                }
                else
                {
                    ball.velocity.X *= -1;
                    paddle.Play();
                }
            }


            if (ball.points1 == 10 || ball.points2 == 10)
            {
                gameState = GameState.GameOver;
            }

            if (gameState == GameState.GameOver)
            {
                if (myKeyboard.IsNewKeyPress(Keys.R))
                {
                    gameState    = GameState.Play;
                    ball.points1 = 0;
                    ball.points2 = 0;
                    player1      = new Paddle(vPaddle, Paddle.Player.Player1);
                    player2      = new Paddle(vPaddle2, Paddle.Player.Player2);
                }
                if (myKeyboard.IsNewKeyPress(Keys.M))
                {
                    gameState = GameState.Menu;
                }
                if (myKeyboard.IsNewKeyPress(Keys.Escape))
                {
                    Exit();
                }
            }

            base.Update(gameTime);
        }
示例#46
0
文件: Ball.cs 项目: StephGarland/Pong
        /// <summary>
        /// Reverses ball horizontal velocity on collision with a paddle
        /// </summary>
        /// <param name="paddle">paddle to check for a collision with</param>
        public void PaddleCollisionX(Paddle paddle)
        {
            Rectangle ballBounds = new Rectangle(ballPosition.X, ballPosition.Y, ballSize, ballSize);
            Rectangle paddleBounds = new Rectangle(paddle.PaddlePosition, paddle.PaddleSize);

            if (ballBounds.IntersectsWith(paddleBounds))
            {
                if (velocity.X > 0)
                {
                    ballPosition.X -= (ballBounds.Right - paddleBounds.Left);
                }
                else
                {
                    ballPosition.X -= (ballBounds.Left - paddleBounds.Right);
                }
                velocity.X *= -1;
                paddle.CollisionSound.Play();
            }
        }
示例#47
0
 private bool IsUnderTop(Ball ball, Paddle paddle) => ball.HitBox.Bottom >= paddle.HitBox.Top;
示例#48
0
 private bool IsAboveBottom(Ball ball, Paddle paddle) => ball.HitBox.Top <= paddle.HitBox.Bottom;
示例#49
0
        private void CheckPaddleInput(float delta, ref Paddle paddle)
        {
            KeyboardState keyboard = Keyboard.GetState();

            // Padding at the top and bottom of the screen.
            int padding = 50;

            // Check if the player wants to move upward.
            if (keyboard.IsKeyDown(paddle.MoveUpKey) && paddle.Position.Y > padding)
                paddle.Position.Y -= 300 * delta;

            // Check if the player wants to move downward.
            if (keyboard.IsKeyDown(paddle.MoveDownKey) && paddle.Position.Y < (WINDOW_HEIGHT - padding) - paddle.Texture.Height)
                paddle.Position.Y += 300 * delta;
        }