Basic XNA OOP for Beginners

來源:互聯網
上載者:User
文章目錄
  • The Problem:

Basic XNA OOP for Beginners

by percent20

German Translation

The Problem:

    Often overlooked in development is the beginner to a technology. This is defiantly prevalent in the XNA community as more and more tutorials come out only to show the coolest new thing that we have figured out how to do, and we want to share with everyone else so they can do it too.

    BUT, what about everyone else that wants to learn how to do game development in XNA. As of now the only thing they can really do is goof around with writing all their code in the Game1.cs file in the update draw etc… methods with no real Object Oriented Programming (OOP) to help make things more organized.
很多人都將XNA程式邏輯編寫在Update和Draw裡面,對於一些簡單的執行個體程式是可以接受的,但是對於複雜的程式來說,這種方式意味著混亂的代碼風格。

One of many possible Solutions:

    There are a lot of beginners that may know conceptually how to use OOP, but not able to use it when it comes to actually programming. This tutorial is geared towards those people that just need a nudge in the right direction for things to start making sense with OOP. Since we dont want to get too complex lets just start out with a basic Sprite Class that all Sprites will inherit from.

知道OOP和在實際中應用OOP不能簡單劃等號。

    using System;    using Microsoft.Xna.Framework;    using Microsoft.Xna.Framework.Graphics;     namespace Game    {        public class Sprite        {            private Texture2D _texture;            protected Vector2 _position;            private Color _tint = Color.White;             public Color Tint            {                get { return _tint; }                set { _tint = value; }            }             public Vector2 Position            {                get { return _position; }                set { _position = value; }            }             public Texture2D Texture            {                get { return _texture; }                set { _texture = value; }            }             public virtual void Update(GameTime gt){}             public virtual void Draw(SpriteBatch sb)            {                sb.Draw(this.Texture, this.Position, this.Tint);            }         }    }  

    So basically these are the basics that you need for each sprite that you want to use in your game. Lets run through it real quick.

這是一個sprite的基類。

    First, you have your properties which for a beginner is just enough to draw the sprite to the screen. You don't really need much more usually. There is the Texture2D which is what you will use to give the sprite the texture to load on the screen. You have a Vector2 that is going to be the position you want that sprite to draw on the screen. Then you have the color so you can set the tint of the sprite we have set this default to white so it shows the pure color of the sprite.

sprite的基本屬性:texture+position+color

    Second, you have two virtual methods that can be overridden to allow functionality. As you can see there is the Update method and the Draw method. You will pretty much need both to do something with your sprite. To put it simple form, sort of, you will call the Update method of the Sprite class in the update method of the main game loop, and the Draw method of the Sprite class in the Draw method of the main game loop. I will give examples of both later on so if you didn't catch that don't worry.

兩個需方法,一個負責update,一個負責draw.

    Now that we have your base Sprite class lets look at how it can be used. The following is a class for a ship that extends the Sprite class and has some functionality in it. I am not going to code out everything but it has just enough to give you an idea of what's going on.

然後我們可以從sprite基類中派生我們需要的具體類。

    using System;    using System.Collections.Generic;    using System.Text;     using Microsoft.Xna.Framework.Input;    using Microsoft.Xna.Framework;     namespace Game    {        class Ship : Sprite        {            public override void Update(GameTime gt)            {                // Call the method that moves the sprite                // on the screen by adjusting                 // the position property that was inherited                // from the Sprite base class            }             // No real need yet to override the draw method            // but it is there for you to do so if need be            // for example if you wanted to call a differnt            // overload of the spritebatches draw method.        }    }  

    I left some basic comments in the code above to further explain what and where you can do things in code. Basically though you will spend your time in the Ship class writing your code for the ship class and not having to rewrite code that the sprite itself is needing. This is very useful because you don't want to rewrite the same code in several places then have to go back and change them in several places.
繼承的功能。

    Finally, for our basics of OOP in XNA we will look at what needs to be done to setup these classes we created and how to use them. It is fairly simple and all done in the Game1.cs file. What we are going to do is create a Ship and just a Sprite so that you can see how they work. So lets do that then i'll give a tip on how to streamline the initial setup of these sprites.

    First we will look at creating and initializing objects. We will need 3 things, Sprite object, Ship object and a SpriteBatch Object. So here is the code for initializing those objects.

建立一個sprite,ship,spritebatch

    public class Game1 : Microsoft.Xna.Framework.Game    {        SpriteBatch spriteBatch;        Sprite sprite;        Ship ship;         // skip some code to the initialize method        protected override void Initialize()        {            spriteBatch = new SpriteBatch(graphics.GraphicsDevice);             sprite = new Sprite();            // we will set a position so the sprites don't overlap            // each other when drawn            sprite.Position = new Vector2(100, 100);             ship = new Ship();            ship.Position = Vector2.Zero;             base.Initialize();        }  

    What we have done is created an instance of SpriteBatch, sprite, and ship next step is to load up our sprites into each of the objects. So here is the appropriate code for that. Remember this is JUST going to be the method used to load the textures to the sprites. This should give you an understanding of what to do.

    protected override void LoadGraphicsContent(bool loadAllContent)    {        if (loadAllContent)        {            sprite.Texture = content.Load<Texture2D>(@"sprite");            ship.Texture = content.Load<Texture2D>(@"ship");        }    }  

    Here we have given the sprite and the ship textures to display on the screen. So now we have setup a sprite and a ship, given them positions to draw, and given them the graphics needed to draw on the screen. Next lets do the code to actually draw them on the screen so if you are setting stuff up on the fly while reading this you can actually see something up on the screen. So here is the code you will need to draw your sprites to the XNA window.

    protected override void Draw(GameTime gameTime)    {        graphics.GraphicsDevice.Clear(Color.CornflowerBlue);         spriteBatch.Begin();         sprite.Draw(spriteBatch);        ship.Draw(spriteBatch);         spriteBatch.End();         base.Draw(gameTime);    }  

    In the draw method we are calling the ship and sprite object's Draw method and sending it the SpriteBatch so it may use that to draw to the screen. At this point you should be able to actually see something on the screen. WOOHOO, but next how will you get the sprites to actually do anything? We'll call the update methods of both the ship and the sprite objects. Here is the code to do this.

    protected override void Update(GameTime gameTime)    {        // Allows the game to exit        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)            this.Exit();         sprite.Update(gameTime);        ship.Update(gameTime);         base.Update(gameTime);    }  

    So now you can go in and play with the Update method in ship class and get your ship to move around and do other stuff too. (I suggest not messing with the Update class in the Sprite class itself)

    One quick thing. Back up at the top of the code where we initialized the objects I recommend setting some custom constructors to make that easier so you don't have to call the properties all the time right after initialization. Just a quick tip.

使用構造器比逐一給屬性賦值要好。

    I want to share some closing thoughts on this. This is only one of many ways to do OOP with XNA and is good for beginners doing things such as pong or space invaders or even a basic Super Mario Brothers type game. However, if you want to get more complex I suggest taking the concepts learned here and PLANNING out a better way to do OOP for more complicated games. This is only meant to get started using OOP not to be the end all for OOP in XNA.

在XNA中使用OOP。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.