본문 바로가기

Not Using/game

게임제작


 ppt38

변수
현재 공의 위치
Vector2  ballPosition = new Vector2(0.5f, 0.5f)//가운데놓고자함
102401사이로 정규화함



공의 화면 상의 위치 계산
화면 해상도 : 1024 x 768
X:  (int)( (0.05f +  0.9f * ballPosition.X) * 1024 ) - GameBallRect.Width / 2,

//
실제뿌릴땐 1024곱해줘야함  ''GameBallRect.Width / 2->이미지를 중앙에 놓기위해 공사이즈의 반만큼 빼줌
왼 0.05 오 0.05만큼은 안써줌 따라서 그만큼 더해주고 공은 0.9사이에서 왔다갔다하도록(x.y)

Y:  (int)( (0.02f + 0.96f * ballPosition.Y) * 768  ) - GameBallRect.Height / 2,

//위아래 0.96만큼만 움직일수있음





paddle

 

변수
현재 패들의 Y 위치 (왼쪽/오른쪽 화면 중앙)
float leftPaddlePosition = 0.5f
float rightPaddlePosition = 0.5f

패들의 화면 상의 위치 계산
화면 해상도 : 1024 x 768

X:  (int)(0.05f * 1024) - GameRedPaddleRect.Width / 2,
Y:  (int)((0.06f + 0.88f * leftPaddlePosition) * 768) - GameRedPaddleRect.Height / 2,

//1 - 0.12f




공과패들움직이기


using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace WindowsGame1
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
 
        Vector2 ballSpeedVector = new Vector2(0, 0); // 공 이동 방향
 
 
        delegate void TestDelegate();
        //---------------------------------
        const float BallSpeedMultiplicator = 0.5f;
        const float ComputerPaddleSpeed= 0.5f;
        bool multiplayer =false;
        //--------------------------------
        public static void TestGameSprites()
        {
            StartTest(
            delegate
            {
                testGame.ShowLives();     //생명 표시
                testGame.RenderBall();
                testGame.RenderPaddles();
            });
        }
        Vector2 ballPosition = new Vector2(0.5f, 0.5f);  // 현재 공의 위치
        public void ShowLives()
        {  // Left players lives
            RenderSprite(menuTexture, 2, 2, GameLivesRect);
            for (int num = 0; num < leftPlayerLives; num++)
                RenderSprite(gameTexture,
                        2 + GameLivesRect.Width + GameSmallBallRect.Width * num - 2, 9,
                        GameSmallBallRect);
            // Right players lives
            int rightX = 1024 - GameLivesRect.Width - GameSmallBallRect.Width * 3 - 4;
            RenderSprite(menuTexture, rightX, 2, GameLivesRect);
            for (int num = 0; num < rightPlayerLives; num++)
                RenderSprite(gameTexture,
                               rightX + GameLivesRect.Width + GameSmallBallRect.Width * num - 2, 9, GameSmallBallRect);
        }
        public void RenderBall()
        {
            RenderSprite(gameTexture,
                                    (int)((0.05f + 0.9f * ballPosition.X) * 1024) - GameBallRect.Width / 2,
                                     (int)((0.02f + 0.96f * ballPosition.Y) * 768) - GameBallRect.Height / 2,
                                       GameBallRect);
        }
 
        int leftPlayerLives = 3, rightPlayerLives = 3;   // 목숨 갯수
        float leftPaddlePosition = 0.5f, rightPaddlePosition = 0.5f; // 현재 paddle 위치
        public void RenderPaddles()
        {
            // left Paddles
            RenderSprite(gameTexture,
                        (int)(0.05f * 1024) - GameRedPaddleRect.Width / 2,
                        (int)((0.06f + 0.88f * leftPaddlePosition) * 768) - GameRedPaddleRect.Height / 2,
                        GameRedPaddleRect);
            // Right Paddles
            RenderSprite(gameTexture,
                        (int)(0.95f * 1024) - GameBluePaddleRect.Width / 2,
                        (int)((0.06f + 0.88f * rightPaddlePosition) * 768) - GameBluePaddleRect.Height / 2,
                        GameBluePaddleRect);
        }
 

        class TestPongGame : Game1
        {
            TestDelegate testLoop;
            public TestPongGame(TestDelegate setTestLoop)
            {
                testLoop = setTestLoop;
            } // TestPongGame(setTestLoop)
            protected override void Draw(GameTime gameTime)
            {
                base.Draw(gameTime);
                testLoop();
            } // Draw(gameTime)
        } // class TestPongGame

        static TestPongGame testGame;
        static void StartTest(TestDelegate testLoop)
        {
            using (testGame = new TestPongGame(testLoop))
            {
                testGame.Run();
            }
        }
 
 

        public static void TestBallCollisions()
        {
            StartTest(
                        delegate
                        {
                            // Make sure we are in the game and in singleplayer mode
                            testGame.multiplayer = false;
                            testGame.Window.Title = "Xna Pong - Press 1-5 to start collision tests";//타이틀주기
                            // Start specific collision scene based on the user input.
                            if (testGame.keyboard.IsKeyDown(Keys.D1))//1눌렀을때
                            {
                                // 첫번째로 스크린보더와충돌했는지체크
                                testGame.ballPosition = new Vector2(0.6f, 0.9f);
                                testGame.ballSpeedVector = new Vector2(1, 1);
                            } // if
                            else if (testGame.keyboard.IsKeyDown(Keys.D2))
                            {
                                // Second test, straight on collision with right paddle
                                testGame.ballPosition = new Vector2(0.9f, 0.6f);
                                testGame.ballSpeedVector = new Vector2(1, 1);//1,1방향
                                testGame.rightPaddlePosition = 0.7f;
                            } // if
                            else if (testGame.keyboard.IsKeyDown(Keys.D3))
                            {
                                // Thrid test, straight on collision with left paddle
                                testGame.ballPosition = new Vector2(0.1f, 0.4f);
                                testGame.ballSpeedVector = new Vector2(-1, -0.5f);
                                testGame.leftPaddlePosition = 0.35f;
                            } // if
                            else if (testGame.keyboard.IsKeyDown(Keys.D4))
                            {
                                // Advanced test to check if we hit the edge of the right paddle
                                testGame.ballPosition = new Vector2(0.9f, 0.4f);
                                testGame.ballSpeedVector = new Vector2(1, -0.5f);
                                testGame.rightPaddlePosition = 0.29f;
                            } // if
                            else if (testGame.keyboard.IsKeyDown(Keys.D5))
                            {
                                // Advanced test to check if we hit the edge of the right paddle
                                testGame.ballPosition = new Vector2(0.9f, 0.4f);
                                testGame.ballSpeedVector = new Vector2(1, -0.5f);
                                testGame.rightPaddlePosition = 0.42f;
                            } // if

                            // Show lives
                            testGame.ShowLives();
                            // Ball in center
                            testGame.RenderBall();
                            // Render both paddles
                            testGame.RenderPaddles();
                        }); //End of StartTest
        } // TestBallCollisions()
 
 
 
 
 
 
        public static void TestMenuSprites()
        {
            StartTest(
                delegate
                {
                    testGame.RenderSprite(testGame.menuTexture, 512 - XnaPongLogoRect.Width / 2, 150, XnaPongLogoRect);
                    testGame.RenderSprite(testGame.menuTexture, 512 - MenuSingleplayerRect.Width / 2, 300, MenuSingleplayerRect);
                    testGame.RenderSprite(testGame.menuTexture, 512 - MenuMultiplayerRect.Width / 2, 350, MenuMultiplayerRect);
                    testGame.RenderSprite(testGame.menuTexture, 512 - MenuExitRect.Width / 2, 400, MenuExitRect);
                });
        }

        public class SpriteToRender
        {
            public Texture2D texture;
            public Rectangle rect;
            public Rectangle? sourceRect;
            public Color color;
            public SpriteToRender(Texture2D setTexture, Rectangle setRect,
                Rectangle? setSourceRect, Color setColor)
            {
                texture = setTexture;
                rect = setRect;
                sourceRect = setSourceRect;
                color = setColor;
            }
        }

        List<SpriteToRender> sprites = new List<SpriteToRender>();
 
        public void RenderSprite(Texture2D texture, Rectangle rect, Rectangle? sourceRect, Color color)
        {
            sprites.Add(new SpriteToRender(texture, rect, sourceRect, color));
        }
        void RenderSprite(Texture2D texture, int x, int y, Rectangle sourceRect)//어떤텍스쳐를 어떠위치에 source를 어느부분에서 가져올것인가
        {
            RenderSprite(texture,
                                        new Rectangle(x, y, sourceRect.Width, sourceRect.Height), sourceRect, Color.White);
        }
 
 
        public void DrawSprites()
        {
            if (sprites.Count == 0) return;//등록된 스프라이트가있는가?
            spriteBatch.Begin(SpriteBlendMode.AlphaBlend,
                                        SpriteSortMode.BackToFront,
                                        SaveStateMode.None);
            foreach (SpriteToRender sprite in sprites)//sprite에 모든엘리먼트를 그려라
                spriteBatch.Draw(sprite.texture,
                                        new Rectangle(sprite.rect.X * width / 1024, sprite.rect.Y * height / 768,
                                        sprite.rect.Width * width / 1024, sprite.rect.Height * height / 768),
                                        sprite.sourceRect, sprite.color);
            spriteBatch.End();
            sprites.Clear();
        }
 

        int width;
        int height;
        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>
        ///
        Texture2D backgroundTexture, menuTexture, gameTexture;
        SpriteBatch spritesBatch;
 
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            backgroundTexture = Content.Load<Texture2D>("SpaceBackground");
            menuTexture = Content.Load<Texture2D>("PongMenu");
            gameTexture = Content.Load<Texture2D>("PongGame");
            spritesBatch = new SpriteBatch(graphics.GraphicsDevice);
            width = graphics.GraphicsDevice.Viewport.Width;
            height = graphics.GraphicsDevice.Viewport.Height;
            RenderSprite(menuTexture, 512 - XnaPongLogoRect.Width / 2, 150, XnaPongLogoRect);
            RenderSprite(menuTexture, 512 - MenuSingleplayerRect.Width / 2, 300, MenuSingleplayerRect);
            RenderSprite(menuTexture, 512 - MenuMultiplayerRect.Width / 2, 350, MenuMultiplayerRect);
            RenderSprite(menuTexture, 512 - MenuExitRect.Width / 2, 400, MenuExitRect);
 
            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(GraphicsDevice);
            // TODO: use this.Content to load your game content here
        }
        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all 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>
        ///
        KeyboardState keyboard;
        protected override void Update(GameTime gameTime)
        {
        
 
            keyboard = Keyboard.GetState();
            float moveFactorPerSecond = 0.5f *
                            (float)gameTime.ElapsedRealTime.TotalMilliseconds / 1000.0f;
   if (ballSpeedVector.X == 0 && ballSpeedVector.Y == 0)
                StartNewBall();
            ballPosition += ballSpeedVector * moveFactorPerSecond * BallSpeedMultiplicator;

            if (keyboard.IsKeyDown(Keys.Up))
                rightPaddlePosition -= moveFactorPerSecond;
            if (keyboard.IsKeyDown(Keys.Down))
                rightPaddlePosition += moveFactorPerSecond;
            if (multiplayer)
            {
                // Move up and down if we press the cursor or gamepad keys.
                if (keyboard.IsKeyDown(Keys.W))
                    leftPaddlePosition -= moveFactorPerSecond;
                if (keyboard.IsKeyDown(Keys.S) ||
                    keyboard.IsKeyDown(Keys.O))
                    leftPaddlePosition += moveFactorPerSecond;
            } // if

            else
            {
                // Just let the computer follow the ball position
                float computerChange = ComputerPaddleSpeed * moveFactorPerSecond;
                if (leftPaddlePosition > ballPosition.Y + computerChange)
                    leftPaddlePosition -= computerChange;//bp가 pd낮으면 아래에위치(공을 쫓아가도록)
                else if (leftPaddlePosition < ballPosition.Y - computerChange)
                    leftPaddlePosition += computerChange;
                //bp가 pd보다크면 위에위치
            }
       
           
            if (leftPaddlePosition < 0)
                leftPaddlePosition = 0;
if (leftPaddlePosition > 1)
                leftPaddlePosition = 1;
if (rightPaddlePosition < 0)
                rightPaddlePosition = 0;
if (rightPaddlePosition > 1)
                rightPaddlePosition = 1;

           
            //-------------------
            // TODO: Add your update logic here
            base.Update(gameTime);
        }

        public void StartNewBall()
        {
            ballPosition = new Vector2(0.5f, 0.5f);
            Random rnd = new Random((int)DateTime.Now.Ticks);
            int direction = rnd.Next(4);
            ballSpeedVector = direction == 0 ? new Vector2(1, 0.8f) :
                            direction == 1 ? new Vector2(1, -0.8f) :
                            direction == 2 ? new Vector2(-1, 0.8f) :
                            new Vector2(-1, -0.8f);
        } // StartNewBall()
 
        /// <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)
        {
            spriteBatch.Begin();
            spriteBatch.Draw(backgroundTexture, new Rectangle(0, 0, width, height), Color.LightGray);
            spriteBatch.End();

            DrawSprites();
            /*
           Vector2 spritePosition = Vector2.Zero;
           Rectangle targetRect = new Rectangle(0, 0, width, 375);
           Rectangle sourceRect = new Rectangle(-170, -150, width, 375);
           spriteBatch.Draw(menuTexture, targetRect, sourceRect, Color.White);
           spritesBatch.End();  // TODO: Add your drawing code here
           spriteBatch.End();*/
            base.Draw(gameTime);
        }
        static readonly Rectangle
        XnaPongLogoRect = new Rectangle(0, 0, 512, 110),
        MenuSingleplayerRect = new Rectangle(0, 110, 512, 38),
        MenuMultiplayerRect = new Rectangle(0, 148, 512, 38),
        MenuExitRect = new Rectangle(0, 185, 512, 38),
        GameLivesRect = new Rectangle(0, 222, 100, 34),
        GameRedWonRect = new Rectangle(151, 222, 155, 34),
        GameBlueWonRect = new Rectangle(338, 222, 165, 34),
        GameRedPaddleRect = new Rectangle(23, 0, 22, 92),
        GameBluePaddleRect = new Rectangle(0, 0, 22, 92),
        GameBallRect = new Rectangle(1, 94, 33, 33),
        GameSmallBallRect = new Rectangle(37, 108, 19, 19);//사용시전역변수로 선언(여러번사용하니까)

    }
}

 





program




using System;
namespace WindowsGame1
{
    static class Program
    {
   
        static void Main(string[] args)
        {
            Game1.TestBallCollisions();

            /*using (Game1 game = new Game1())
            {
                game.Run();
            }*/
        }
    }
}





 

'Not Using > game' 카테고리의 다른 글

11.18 beakout  (0) 2009.11.18
esc누르면 메뉴화면으로.. 애니메이션넣기는 미완성;  (0) 2009.11.10
애니메이션넣기  (1) 2009.11.04
과제(live, paddle, ball)  (0) 2009.10.11
10.07 Live, ball, paddle  (0) 2009.09.16