XNA Game Component – Custom Mouse Pointer

For a while I have had some basic code to handle mouse functions in XNA Applications,



But as some of these are old and each have some different functions I thought this morning that I would put the simple mouse functions into a Drawable XNA Game Component. The component that I have put together will draw a custom mouse pointer on the screen and restrict the pointer to the current game window, when you leave the window the mouse will return to the normal mouse pointer you use in windows. At the same time the mouse will change color when the mouse buttons are pressed. There are a lot more functions that could be added to this, for example handling the wheel or adding events to the mouse states. One of the functions that I will be adding soon is a shadowed effect to the mouse pointer.


To use this game component add the following code to the top of the game class just under the initialization for the game manager and content manager so that it looks like this…


[code language="C#"]
GraphicsDeviceManager graphics;
ContentManager content;


GameComponents.MousePointer mousePointer;
[/code]


Next change you initialization code to look like this…


[code language="C#"]
protected override void Initialize()
{
    // TODO: Add your initialization logic here
    this.Window.Title = "Virtual Realm - Custom Mouse Pointer Example";


    this.mousePointer = new CustomMouse.GameComponents.MousePointer(this);
    this.mousePointer.DrawOrder = 1000;
    this.mousePointer.RestrictZone = new Rectangle(0, 0,
         this.graphics.GraphicsDevice.Viewport.Width,
         this.graphics.GraphicsDevice.Viewport.Height);
    this.Components.Add(this.mousePointer);


    base.Initialize();
}
[/code]


I have set up a restrictZone that will restrict the mouse to the screen, this makes sure that the icon will stay in the sceens viewport, also changing the draw order to a high number (1000) will make sure that the mouse cursor is drawn above all other items on the screen.


The final stge is to load the content for the pointer, in this example I am using a simple arrow texture, but you could use anything you like to work in with your application.



[code language="C#"]
protected override void LoadGraphicsContent(bool loadAllContent)
    {
        if (loadAllContent)
        {
            // TODO: Load any ResourceManagementMode.Automatic content
            this.mousePointer.PointerTexture = content.Load<Texture2D>(@"Content\Arrow");
        }
        // TODO: Load any ResourceManagementMode.Manual content
    }
[/code]


Now here is the Game Component code, I have created a folder called GameComponents where I put the game components I am working on, this helps to keep the code looking clean. Create the directory and add the following class file to application.


[code language="C#"]
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
#endregion


namespace CustomMouse.GameComponents
{
    /// <summary>
    /// This is a game component that implements IUpdateable.
    /// </summary>
    public class MousePointer : Microsoft.Xna.Framework.DrawableGameComponent
    {
        private SpriteBatch spriteBatch;
        public Vector2 MousePosition;


        private MouseState CurrentMouseState;
        private MouseState PreviousMouseState;


        private Color pointerColor = Color.White;


        private Texture2D pointerTexture;


        public Texture2D PointerTexture
        {
            get { return pointerTexture; }
            set { pointerTexture = value; }
        }


        private Rectangle restrictZone;


        public Rectangle RestrictZone
        {
            get { return restrictZone; }
            set { restrictZone = value; }
        }
 
        public MousePointer(Game game)
            : base(game)
        {
            // TODO: Construct any child components here
        }



        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {
            // TODO: Add your initialization code here


            base.Initialize();
        }


        protected override void LoadGraphicsContent(bool loadAllContent)
        {
            if (loadAllContent)
            {
                // TODO: Load any ResourceManagementMode.Automatic content
                this.spriteBatch = new SpriteBatch(this.GraphicsDevice);
            }


            // TODO: Load any ResourceManagementMode.Manual content
            base.LoadGraphicsContent(loadAllContent);
        }


        protected override void UnloadGraphicsContent(bool unloadAllContent)
        {
            base.UnloadGraphicsContent(unloadAllContent);
        }


        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {
            // TODO: Add your update code here
            this.CurrentMouseState = Mouse.GetState();
            this.MousePosition.X = this.CurrentMouseState.X;
            this.MousePosition.Y = this.CurrentMouseState.Y;


            // Restrict the Mouse so that it stays inside the current display
            if (this.MousePosition.X < 0)
                this.MousePosition.X = 0;
            if (this.MousePosition.X > this.restrictZone.Width)
                this.MousePosition.X = this.restrictZone.Width;
            if (this.MousePosition.Y < 0)
                this.MousePosition.Y = 0;
            if (this.MousePosition.Y > this.restrictZone.Height)
                this.MousePosition.Y = this.restrictZone.Height;


            if (this.CurrentMouseState.LeftButton == ButtonState.Pressed)
            {
                this.pointerColor = Color.Red;
            }
            else
            {
                this.pointerColor = Color.White;
            }


            if (this.CurrentMouseState.RightButton == ButtonState.Pressed)
            {
                this.pointerColor = Color.Red;
            }
            else
            {
                this.pointerColor = Color.White;
            }


            this.PreviousMouseState = this.CurrentMouseState;


            base.Update(gameTime);
        }


        /// <summary>
        /// Allows the game commponent to Draw itself
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values</param>
        public override void Draw(GameTime gameTime)
        {
            this.spriteBatch.Begin(SpriteBlendMode.AlphaBlend);
            this.spriteBatch.Draw(this.pointerTexture, this.MousePosition, this.pointerColor);
            this.spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}
[/code]


I do hope that someone finds this useful, if you have any sugestions please drop me a line.


Cross Post from www.virtualrealm.com.au

Xbox 360 – Rainbow Six Vegas Red and Black for Free

Major Nelson, and the Gamerscoreblog have posted some really good news…


“Tom Clancy’s Rainbow Six Vegas Black Pack Downloadable Content for Xbox 360 Live was originally intended to be free content for the fans of Rainbow Six Vegas. We apologize for the error. All players who purchased the Black Pack will be reimbursed automatically.* The Black Pack will be posted Saturday June 30th and will be free of charge. Also, as a token of our appreciation for the Rainbow Six community, we are making the Red Pack free as of Friday July 6th as well. Thanks for playing and we hope you enjoy this free content.”


I was planning on purchasing both, now it looks like if I just wait a small bit I will get then for free.


Cross Post from www.virtualrealm.com.au

Xbox 360 Games for the summer or winter

IGN Has published a good list of the upcoming titles for this summer, but as most will know in Australia this happens to be our winter. At least with this selection of games it might help us get through the cold months of winter.


BioShock

Publisher: 2K Games
Developer: Irrational Games
Genre: First-Person Shooter
Release Date: August 21

BlackSite: Area 51

Publisher: Midway
Developer: Midway Studios – Austin
Genre: First-Person Shooter
Release Date: September

Blue Dragon

Publisher: Microsoft
Developer: Mistwalker
Genre: RPG
Release Date: August

The Darkness

Publisher: 2K Games
Developer: Starbreeze AB
Genre: First-Person Shooter
Release Date: June 25

Eternal Sonata

Publisher: Namco Bandai
Developer: tri-Crescendo
Genre: RPG
Release Date: September

John Woo Presents Stranglehold

Publisher: Midway
Developer: Midway
Genre: Action
Release Date: August

Madden NFL 08

Publisher: Electronic Arts
Developer: Tiburon
Genre: Sports
Release Date: August 14

Mass Effect

Publisher: Microsoft
Developer: BioWare
Genre: RPG
Release Date: Summer

Medal of Honor: Airborne

Publisher: Electronic Arts
Developer: EA Los Angeles
Genre: First-Person Shooter
Release Date: Late Summer

Overlord

Publisher: Codemasters
Developer: Triumph Studios
Genre: Action
Release Date: June 26

Project Gotham Racing 4

Publisher: Microsoft
Developer: Bizarre Creations
Genre: Racing
Release Date: September

Skate

Publisher: Electronic Arts
Developer: Black Box
Genre: Sports
Release Date: September

TimeShift

Publisher: Vivendi
Developer: Saber Interactive
Genre: First-Person Shooter
Release Date: September

Turok

Publisher: Touchstone
Developer: Propaganda Games
Genre: First-Person Shooter
Release Date: September

Two Worlds

Publisher: SouthPeak Interactive
Developer: TopWare Interactive
Genre: RPG
Release Date: August 7

Virtua Fighter 5

Publisher: SEGA
Developer: AM2
Genre: Fighting
Release Date: Late Summer


It will be interesting o see how many of these games are going to make the release dates and if those dates will be reflected here in Australia.I already know that some of the dates have been past and the Titles not yet released, i.e. Darkness (This date was moved back and from memory this was before this IGN Article).


Cross Post from www.virtualrealm.com.au

XNA – Drawing your first Triangle

I remember when I first started out with MDX, the first thing you did was draw your basic device and then the second was to draw the basic triangle. My first one followed the examples in Tom Millers MDX Kickstart, before that I was mainly 2D. Now as I have not seen an example of this I thought I would start putting one together. In the example to follow I will go through the simple task of drawing a simple triangle and use the basic effect to display it on the screen.


To start with start a Windows Game (Or an Xbox 360 one as this example will work on both), and call it Simple Triangle.


Next set up the varibles that we are going to use through out the project, add the following under the calls to the Grapics and content manager calls.


[code language="C#"]


        VertexBuffer vertexBuffer;
        VertexDeclaration basicEffectVertexDeclaration;


        Matrix worldMatrix;
        Matrix viewMatrix;
        Matrix projectionMatrix;


        BasicEffect basicEffect;
[/code]


The next stage is to set up the Effect and Verttices, I do this buy Setting up a vertex buffer to store the information. Also as I would like to have the triangle colored I use a VertexPositionColor for each point.


[code language="C#"] 


        private void SetUpVertices()
        {
            VertexPositionColor[] vertices = new VertexPositionColor[3];
            vertices[0] = new VertexPositionColor(new Vector3(0, 1, 1), Color.Aqua);
            vertices[1] = new VertexPositionColor(new Vector3(-1, -1, 1), Color.Black);
            vertices[2] = new VertexPositionColor(new Vector3(1, -1, 1), Color.Purple);


            vertexBuffer = new VertexBuffer(this.graphics.GraphicsDevice, VertexPositionColor.SizeInBytes * 3, ResourceUsage.WriteOnly);
            vertexBuffer.SetData(vertices);
        }


        private void InitializeEffect()
        {
            basicEffectVertexDeclaration = new VertexDeclaration(
                graphics.GraphicsDevice, VertexPositionColor.VertexElements);


            basicEffect = new BasicEffect(graphics.GraphicsDevice, null);
            basicEffect.Alpha = 1.0f;
            basicEffect.VertexColorEnabled = true;
        }
[/code]


Once that is all done we now need to set up the view and camera positions, add the following code to the Initialization call for the game just under the base.initialize.


[code language="C#"] 


           // Set up the initial View Matrixes
            viewMatrix = Matrix.CreateLookAt(new Vector3(0, -6, 5), Vector3.Zero, Vector3.Up);


            projectionMatrix = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.ToRadians(45),  // 45 degree angle
                (float)graphics.GraphicsDevice.Viewport.Width / (float)graphics.GraphicsDevice.Viewport.Height,
                1.0f, 100.0f);


[/code]


With every thing setup we can now get down to actually displaying it on the screen, add the following to the load content call.


[code language="C#"] 


                // TODO: Load any ResourceManagementMode.Automatic content
                this.InitializeEffect();
                this.SetUpVertices();


[/code]


Now to the update call add the following section of code. This will fill the world and view settings inside the basic effect so that when the images are drawn we will be able to see them.


[code language="C#"]


            // TODO: Add your update logic here


            worldMatrix = Matrix.Identity;


            basicEffect.World = worldMatrix;
            basicEffect.View = viewMatrix;
            basicEffect.Projection = projectionMatrix;


[/code]


The final stage is to add the following code to the draw call of the application. This is the code that will draw and display the image to the screen so that the end user can see it. when adding the code below make sure that it is above the base.draw call.


[code language="C#"] 


            // TODO: Add your drawing code here


            graphics.GraphicsDevice.RenderState.CullMode = CullMode.None;
            graphics.GraphicsDevice.VertexDeclaration = basicEffectVertexDeclaration;
            graphics.GraphicsDevice.Vertices[0].SetSource(vertexBuffer, 0, VertexPositionColor.SizeInBytes);


            // This code would go between a device
            // BeginScene-EndScene block.
            basicEffect.Begin();
            foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
            {
                pass.Begin();
                graphics.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 12);
                pass.End();
            }
            basicEffect.End();


[/code]


After complete and you have compiled the application you should be presented with the following.


 


With the above sample this is just the beginning, there is a lot more that can be done, this includes adding lights and rotating the object or world. You could also swap the system over so that it does not use the Basic Effect and have it use a custom effect. These are some of the changes that I plan on adding and writing about. Also you will find that as I move forward using 3D with XNA I will be posting examples, these will more then likley be based on this base code or versions of it.


One other thing, as I move forward I plan on explaining some or all of the systems that have been used, I may not of here but as each example grows I will explain what is happening, plan on using this as a base.


I have included the Virtual Realm Simple Triangle in the Downloads section on this site.


Cross Post from www.virtualrealm.com.au

Ireland’s Call on Guitar Hero X-Plorer for the PC and XBox 360

Came across an interesting post this morning, Robert Burke has put together a set of small programs that allow you to use the Guitar Hero X-Plorer controller to play Ireland’s call on the PC or the Xbox 360.


“If you have the Guitar Hero X-Plorer controller for the XBox360, here’s an XNA application that will let you play Ireland’s Call (a.k.a. “The Rugby Song”) on your PC or XBox360. This was my finale at Rob’s Last Stand last week.

This game is a bit more “free form” than the real Guitar Hero, in that you aren’t prompted visually with when you should play each chord. Instead, as you play, fireworks go off in sync with the music that match the colours of the notes you’re playing.”


In the sample Robert uses the Particle sample from the Creators site and he supplies both the PC and Xbox 360 versions of his application.


Here is the link to the Post.


Cross Post from www.virtualrealm.com.au

3D Studio Max Tutorial – Model and Texture a Nokia 6210

The guys over at The 3D Studio have posted a free tutorial that will take you through the process of modeling a Nokia 6210. This tutorial will show you some simple techniques to get the job done, which includes the texturing of the model. All of the skills in this tutorial can be carried across to Game Models.



This tutorial was written exclusively for The3dStudio.com by Martin Kostov (Member Link).

In this tutorial I will show you, in detail, how to model and texture a cell phone. We will create the Nokia 6210, an old phone but it will give you all the basics you need to know. I always start by finding reference pictures on the net or by taking the photos myself.

…download free PDF or XPS file to view entire tutorial…”


Here is the direct Link to the Tutorial.


Cross Post from www.virtualrealm.com.au

Lost Planet Map Pack 3 Announced

Looks like the third map pack for Lost planet has been announced, the pack should be released on June 21st and will be 400 Microsoft points. Included in this pack will be three new maps, Ice Drop, Ruins, and Lost Technologies.


““Lost Technology” is described as “a throw-back to the good ol’ days of pixelated 8-bit gaming”. Ooh, kinky. That should be interesting”, Game Stooge.


At present I don’t have this game, but as this game seems to be getting regular conent updates, I might have to drop down to the local and hire to see what it is like.


Here is the link to the MyGamerCard post on the release.


Cross Post from www.virtualrealm.com.au

Generic Defense Game

Going through my Digg posts for the day I came across another great Office time wasting game “Generic Defense Game“.

“It’s a survival shooter, a turret defence game; it’s so generic it’s unique!

This bad-boy game gives you eight different games in one, with a ton of options to deliver a unique experience every time you play.”

After playing it for about an hour, I game to thinking that this might have some good ideas that could be integrated into another XNA Game.


Cross Post from www.virtualrealm.com.au

Creating a DiggIt Module for Community Server 2007

For a while I have been asking about Scott’s ShareIt Module and wether the system will run inside the Community Server 2007 system, there have been several hints that a new release will soon be coming out. Now with a lot of sites starting to pick up the share it type links and icons on there systems (Link www.digg.com, www.dotnetkicks.com and others) I decided that I needed to throw the same sort of system on my site.

With Scott’s Module not having a CS 2007 Release I thought that I would look into the code and try and get it to work. The good thing is that if you open the source project attach the new community server libraries…. it all works fine. So in the end I just recompiled the Modules under 2007 and off I went.

Digging deeper I found that the ShareIt system that Scott had was good, but I wanted more, I wanted to have the nice little graphic at the bottom. With Scott’s code as a base as well as some other sources I found I started to code my own DiggIt Module, after about 20 minutes of work and some testing I now have a DiggIt module that will add the code to the bottom of each post. The mod also allows the user to click on the graphic and submit the Digg article, at the same time populating some of the fields during the submit.

Anyway here is the code and process that I took to create the module…

Creating the DiggItModule

The first step is to create you base assembly; I have called mine ‘VirtualRealm.CS.Modules’ as I plan on writing more. When the project has finished setting it’s self up add the following Community Server Library references to the project references.

CommunityServer.Blogs

CommunityServer.Components

Next rename the Class.cs file to ‘DiggItModule.cs’ and add the following using statements to the top of the class file.

[code language="C#"]

using System.Xml;

using CommunityServer.Blogs.Components;

using CommunityServer.Components;

[/code]

Change the main definition of the class so it looks like this.

[code language="C#"]

namespace VirtualRealm.CS.Modules

{

public class DiggItModule : ICSModule

{

}

}

[/code]

Add the following code to the class, this will initialize the module and set up the event handler that we will be using. If you are going to be looking into creating more modules you should have a look at the references on the Communityserver.org site for the other types of events that you can use.

[code language="C#"]

public void Init(CSApplication csa, XmlNode node)

{

csa.PreRenderPost += new CSPostEventHandler(csa_PreRenderPost);

}

private void csa_PreRenderPost(IContent content, CSPostEventArgs e)

{

}

[/code]

Next we add the variables that we will be using in the code, just under the init procedure add the following.

[code language="C#"]

private bool _syndicate = true;

private bool _web = true;

private DateTime _dateFilter = DateTime.MinValue;

[/code]

The last stage we need to do is to add the following code section inside the event handler.

[code language="C#"]

if (e.Target == PostTarget.Web)

{

if (!_web)

return;

}

else if (e.Target == PostTarget.Syndication)

{

if (!_syndicate)

return;

}

if (e.ApplicationType == ApplicationType.Weblog)

{

WeblogPost wp = content as WeblogPost;

bool includePost = (e.Target == PostTarget.Web || wp.PostDate >= _dateFilter);

if (wp != null && wp.PostLevel == 1 && includePost)

{

string link = Globals.FullPath(BlogUrls.Instance().Post(wp));

string title = wp.Subject;

string titleUrlEncode = Globals.UrlEncode(wp.Subject);

wp.FormattedBody =

string.Format("{0}\n<script type=\"text/javascript\">digg_url = '{1}';digg_title = '{2}';</script><script src=\"http://digg.com/tools/diggthis.js\" type=\"text/javascript\"></script>",

wp.FormattedBody, link, title);

}

}

[/code]

With all the coding done you should be able to compile the project, for the first time to check that it works compile the code under debug, but remember that when you publish the code and ship it to your web site that you compile it under a release mode.

Once compiled and working to install the module you will need to upload the dll to the bin directory of you web site. Next open your communityserver.config file and add the following reference to the csmodules section. I added mine last in the list.

[code language="C#"]

<add name="DiggIt" type ="VirtualRealm.CS.Modules.DiggItModule, VirtualRealm.CS.Modules" />

[/code]

The last thing is that you should touch you web.config file to make sure that the site recompiles and relinks every thing. Now when you go to your blogs pages you should see the DiggIt graphic and links on the bottom of each post.

This is only my first CSModule and I was surprised at how easy it was to put one together. I admit that a lot of the code in the mod is from Scott’s ShareIt Module, but it helped a lot and could be used as a base for other modules of the same type. I am presently putting together a KickItModule which I will release and post. For more information on CSModules and some templates that you can use you should check out the Community Server Documentation Pages as well as the Community Server MVPs blogs as they all hold valuable information on how to do lots of different tasks with CSModules. You could also do what I have done and look at some of the open source modules that have already been written, as you might find that the task you want to do may be simular to one of those.


Cross Post from www.virtualrealm.com.au