Saturday, January 21

Xna Move Ball with arrow keys using c# code


XNA library developed by Microsoft which we use to develop a game with very little effort because it is built with huge classes you only need to use these classes and with very small effort you can develop a very perfect game. This library has solved many problems of a programmer because you do not to be an expert of c# while using this library.



Well this xna brief lecture will focus on how to use xna library and how can we develop game in this. So without any further delay lets come to the main lecture download xna game studio from Microsoft official website make sure it is installed in your pc, open MS visual C# 2010, open a new project choose Window Game (4.0), your project is built with some code provided by the Microsoft, if you just run this code, you will be shown a blue screen. And sometimes you get an error message which is a compile time error, which says could not find high definition graphics, to resolve this issue go to the properties of your project and set the option to use reach graphics, XNA is not an acronym. In the cSharp(.cs) code you will see some protected override methods, which includes
·         Initialize ( )
·         LoadContent ( )
·         Update ( )
·         Draw ( )
·         UnloadContent ( )
·         End ( )
Starting from Initialize method, all of your variables, classes objects will be initialize in the initialize method, you can observe it by its name one more thing in this method you will not be doing any graphical activities. In the LoadContent all your graphics, audio effects will be loaded into it. Both these methods ( Initialize, LoadContent) will be called once when the game is loaded. Update and Draw methods are basically your main methods, Let’s suppose you are playing a car racing game when your car moves forward you see the world detail is coming toward us. And depending upon your graphic adapter you will not see any jerk in the game, this movement is handled by recursive call of Update and Draw methods,Your game main logic will be written inside Update method, and Draw is basically Drawing new objects (Texture) in the game which is running. To understand game working you must know about few things, which are:
·         SpriteBatch
·         Texture
·         Vector
Spritebatch is a class, it uses sprites to draw 2D bitmap graphics directly on to the screen. Texture it may be 2D or 3D it defines the dimensions of images or graphic contents you are using in your game. Vector it may 2,3,4, it defines your game dimensions, Vector2 will have X, Y coordinates, Vector3 will have X,Y and Z coordinates and so on.
Game Tutorial:
Xna Move Ball With arrow keys Game
I have made this game by using another class which is Ball.cs, I have made some Private members which are:
·         Texture
object of Texture class
·         Position
object of Vector2 class
·         VelX
(Velocity x-axis) type Integer initialized with 5
·         VelY
(Velocity y-axis) type Integer initialized with 5
·         WindowWidth
Main Window Width in the game is running type integer, it is initialized in the constructor of Ball class.
·         WindowHeight
Main Window Height of integer type, it is initialized in constructor
To initialize (WindowWidth, WindowHeight, Position, Texture) these variables, you are required to make a constructor which will take four variables of the above class’s objects which are uninitialized. Make a method draw in the Ball class, in which you will begin, end and draw spriteBatch, in the update method of Ball class you will set the logic of your game, let’s say you want to move your ball horizontally you only need to update value of Position.X +=VelX, it means Velocity of x-axis which is initialized with 5, is given to x-axis of Vector Position. This is all what you have done with your ball class. Now open Game1.cs file you will make an object of ball class. In the initialize method you will initialize object of ball class by giving values to its constructor. In the draw method of game1.cs you will call Draw method of ball class. Let’s say we have made an object of Balll class Obj. In Draw method you will write Obj.Draw(Parameters (SpriteBatch) ). I am provide you the source code and screenshot use and provide feedback. Thank you.

Screen Shot:



XNA C# Code:

Game1.cs


namespace WindowsGame3
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Ball gameBall;
        Texture2D rec;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            rec = new Texture2D(graphics.GraphicsDevice, 50, 50);
            gameBall = new Ball(this.Content.Load<Texture2D>("ball"), new Vector2(5, 5), graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight);
            base.Initialize();
        }
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
        }
        protected override void UnloadContent()
        {
        }
        protected override void Update(GameTime gameTime)
        {
            gameBall.Update(gameTime);
            base.Update(gameTime);
        }
        protected override void Draw(GameTime gameTime)
        {
            spriteBatch.Begin();
            spriteBatch.Draw(rec, new Vector2(50,50) , Color.Black);
            GraphicsDevice.Clear(Color.Black);
            gameBall.Draw(spriteBatch);
            spriteBatch.End();
            
            base.Draw(gameTime);
        }
    }
}

Ball.cs


namespace WindowsGame3
{
    class Ball
    {
        Texture2D Texture;
        Vector2 Position;
        int VelX = 5;
        int VelY = 5;
        int WindowWidth;
        int WindowHeight;
        
        public Ball(Texture2D texture, Vector2 position, int windowWidth, int windowHeight)
        {
            
            Texture = texture;
            Position = position;
            WindowWidth = windowWidth;
            WindowHeight = windowHeight;
        }
        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(Texture, Position, Color.White);
        }
        public void Update(GameTime gametime)
        {
            KeyboardState key = Keyboard.GetState();
            if (key.IsKeyDown(Keys.Right))
            {
                if (Position.X + Texture.Width > WindowWidth)
                {
                    Position.X = VelX;
                }
                Position.X += VelX;
            }
            else if (key.IsKeyDown(Keys.Left))
            {
                if (Position.X <= 0)
                {
                    VelX = 5;
                    Position.X = VelX;
                }
                Position.X -= VelX;
            }
            else if (key.IsKeyDown(Keys.Up))
            {
                if (Position.Y <= 0)
                {
                    VelY = 5;
                    Position.Y = VelY;
                }
                Position.Y -= VelY;
            }
            else if (key.IsKeyDown(Keys.Down))
            {
                if (Position.Y + Texture.Height > WindowHeight)
                {
                    Position.Y = VelY;
                }
                Position.Y += VelY;
            }
        
        }
    }
}

1 comment: