Unity 4.x – Mecanim working on your own projects

Hey, as usual its been a while. This time Im switching technologies and solving an issue I had today. Ive started to play around with Unity and since I have some background on game programming I decide to go to the bone and start with the hard stuff.

My ideal starting point was simple: a square room scenario where I could move an avatar and add some monsters (possibly zombies) to shoot. I did some reading (up to chapter 5 of the book Unity 3.x Game Development Essentials) while I was traveling the pasts weeks which was the perfect introduction to the technology.

Continue reading “Unity 4.x – Mecanim working on your own projects”


XNA MD2Model with Normal calculation

Ive been playing around with the excellent MD2Model class RCade provides on his blog(http://www.varcade.com/blog/).

I did some experiments (nothing too fancy) but I wanted to use dynamic lighting on some old doom 1 models I found on the internet. Unfortunately  I was not able to do so because I did not have access to the Normals on the mesh.

I did a little Google search (my math skills are a little rusty) and I refresh my mind on how normals are calculated so I patched the code to support them.

Continue reading “XNA MD2Model with Normal calculation”


Android: simple sync manager using Observer Pattern

I have a new blog post with an updated example an explanation about Android and RESTful web services. You should take a look here:

For my current project I have to create a sort of synchronization mechanism to upload some data to a web service (I’ve covered web services before on the blog). I’m going to complete that article by showing how to create a very simple synchronization manager that will let you communicate to your web service and the upper layers of your application using the Observer pattern.

It’s important to mention this is not a fully featured sync mechanisms because I will only show you how to do the upload process. Nevertheless with the bases presented on this article you will be able to easily implement these.

Continue reading “Android: simple sync manager using Observer Pattern”

android, Uncategorized

Android WCF REST requests made simple (using JSON)

I have a new blog post with an updated example an explanation about Android and RESTful web services. You should take a look here:

I’ve been struggling for some time trying to get my Android phone to talk with a WCF REST web service. Finally I was able to do it and I decided to share the knowledge.

A few things to consider first:

Continue reading “Android WCF REST requests made simple (using JSON)”


Windows Phone 7 – hacer web requests de forma simple

La célula de Mendoza esta intento buscar gente para hacer desarrollos en Windows Phone 7 y por mi cuenta (Angel) he estado haciendo algunas investigaciones.

Por naturaleza de aplicación para celular, lo mas conveniente es hacer aplicaciones que consuman datos de algún web service. A veces es difícil encontrar como hacer esto, mas cuando la plataforma es tan nueva. Acá les voy a pasar un ejemplo de como hacerlo correctamente y de forma fácil:

        public void GetXML(string url)
            HttpWebRequest request = 
(HttpWebRequest)HttpWebRequest.Create(new Uri(url)); request.Headers["user-agent"] = "MSIE 7.0"; request.BeginGetResponse(new AsyncCallback(ReadCallback), request); } private void ReadCallback(IAsyncResult asynchronousResult) { HttpWebRequest request =
(HttpWebRequest)asynchronousResult.AsyncState; HttpWebResponse response =
(HttpWebResponse)request.EndGetResponse(asynchronousResult); using (StreamReader streamReader =
new StreamReader(response.GetResponseStream())) { XDocument xmlDocument = XDocument.Load(streamReader); }

El código hace un pedido a una url especificada y cuando obtiene la respuesta va al metodo ReadCallback (si van a actualizar algún control tengan en cuenta que están trabajando en hilos diferentes). Yo en el ejemplo cree un XDocument (es la version de XmlDocument en WP7), pero pueden usar un string o lo que deseen.

Como les decia, si van a actualizar un metodo, lo mejor es usar un delegado y un evento (estos son ejemplos, no le presten atencion a los metodos y argumentos)

1) Declaramos en nuestra clase ambos:

public delegate void CharacterReceivedHandler(object sender, CharacterReceivedEventArgs e);
public event CharacterReceivedHandler CharacterReceived;

2) Disparamos el evento cuando armamos el XDocument ( o lo que recibamos):

 if(CharacterReceived != null)
new CharacterReceivedEventArgs() { Character = currentCharacter });

3)En la clase que enganchamos el metodo hacemos lo siguiente:

connector.CharacterReceived +=
new ArmoryConnector.CharacterReceivedHandler(connector_CharacterReceived);

void connector_CharacterReceived(object sender, CharacterReceivedEventArgs e) {   this.Dispatcher.BeginInvoke(delegate() {         // Update controls here
}); }

Ojala les sirva 🙂

phone7, xna

XNA – Your first Phone 7 Game in 3D !!!

Heiya guys ! I’ll post a small tutorial on how to compile your first 3d game on windows phone 7 (using the emulator).

First, you’ll need the developer tools WHICH ARE FREE !!! Get them RIGHT now:


Now, lets get this started. First open VS2010 and create a new Windows Game.


I’ve prepared a 3d camera suitable for a shooter. This means the camera is looking from upside down. You can feel free to use it in your projects. Here is the code:

   public static class Camera
       public static Matrix World { get; private set; }
       public static Matrix View { get; set; }
       public static Matrix Projection { get; private set; }

       public static BoundingFrustum BoundingFrustum { get; private set; }

       public static Vector3 Position { get; set; }

       // needed attributes
       private static float nearClip = 1.0f;
       private static float farClip = 1000.0f;

       private static float aspectRatio = 800 / 600; // default aspect ratio
       public static float AspectRatio
           get { return aspectRatio; }

               aspectRatio = value;


       public static void Update()

       public static void UpdateMatrices()

           Matrix rotationMatrix = Matrix.CreateRotationX(MathHelper.ToRadians(90));
           Vector3 transformedReference = Vector3.Transform(Vector3.Forward, rotationMatrix);

           View = Matrix.CreateLookAt(Position, new Vector3(0, 0, 0), Vector3.Forward);
           Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, nearClip, farClip);
           World = Matrix.Identity;

           World = Matrix.Identity;

           BoundingFrustum = new BoundingFrustum(View * Projection);

The code is quite simple. The UpdateMatrices does all the work.  Notice I’ll I’m doing is transform the Forward vector with a 90 degrees angle. I know this is lame but I’ve choose this way to make it more graphical: In a normal FPS game you are pointing forward, if I rotate 90 degrees… well I know you get it 🙂

Note this:

Before we load the graphical device, we don’t know the viewport’s aspect ratio, so I’ve done it in a dynamic fashion, once you change the Camera’s ratio, it’ll recalculate the projection Matrix; this means you have to manually set the aspect ratio of the camera:

        /// <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
            Camera.AspectRatio = GraphicsDevice.Viewport.AspectRatio;

Also ! remember to update the camera !!


Here is the great part. Nothing has changed ! You can draw your models just the way you did it in the XNA 3.1 versions.

In a few steps:

  1. Declare your model
  2. Load it (notice the changes in the Content directory)
  3. Transform it
  4. Draw it

The declaration is easy, but the process to add it to the project is a little bit different. Here is a screenshoot:


To load it, we use the same procedure as before:

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
    Camera.AspectRatio = GraphicsDevice.Viewport.AspectRatio;
    model = Content.Load<Model>("raptorxxi");

Here is our code to draw it (you can see the rest in the project).

/// <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)

            // TODO: Add your drawing code here

            // Copy any parent transforms.
            Matrix[] transforms = new Matrix[model.Bones.Count];

            // Draw the model. A model can have multiple meshes, so loop.
            foreach (ModelMesh mesh in model.Meshes)
                // This is where the mesh orientation is set, as well 
                // as our camera and projection.
                foreach (BasicEffect effect in mesh.Effects)
                    effect.View = Camera.View;
                    effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateTranslation(Vector3.Zero);
                    effect.Projection = Camera.Projection;
                // Draw the mesh, using the effects set above.



And there you go:


Download the solution from HERE !!!!!


Multiple textures (or materials) on models

Hi, this time I’ll play a little with effects (don’t worry, I’m awful at HLSL so this won’t be complicate).

Generally, the problem in multi texture effects is to decide “how much” of each material apply. There are hundreds of approaches and different algorithms. I’ll use a very simple one: We have two textures, a base texture (for example a base skin texture for a character) and a brush texture (lets say, a piece of cloth). The second texture is a transparent texture with some areas painted.

What we are going to do is, take the base texture, and remove the areas that are not transparent on the second one. Although this sound complicated, this is super easy to do. I’ll post some code of the .fx file now:

First, notice I’ll be using two samplers. One for each texture I’ll be using.

texture TextureMap;
sampler2D TextureMapSampler = sampler_state
    texture = (TextureMap);
    AddressU = WRAP;
    AddressV = WRAP;
    MinFilter = LINEAR;
    MipFilter = LINEAR;
    MagFilter = LINEAR;

texture Brush0;
sampler2D Brush0Sampler = sampler_state
    texture = (Brush0);
    AddressU = WRAP;
    AddressV = WRAP;
    MinFilter = LINEAR;
    MipFilter = LINEAR;
    MagFilter = LINEAR;

I’ll skip the vertex shader since it’s very simple. I’ll go straight to the algorithm:

  // this will remove part of the base texture in order to apply the second material
    float amount = 1 – tex2D(Brush0Sampler, input.UV).a;
   output = (tex2D(TextureMapSampler, input.UV)) * amount;
   output += (tex2D(Brush0Sampler, input.UV));  

As you see, it’s really simple. 1 means full color without transparency. I’m removing the amount of color of the second texture. Piece of cake !

Now some XNA – C# code. First I’m loading an effect and applying to the model. Since a lot of people don’t know how to do this I’ll pos it.

model = Content.Load<Model>("cube");
effect = Content.Load<Effect>("MultiTexture");

// apply the effect
foreach (ModelMesh mesh in model.Meshes)
    foreach (ModelMeshPart meshPart in mesh.MeshParts)
        meshPart.Effect = effect;

And now, the drawing part where we assign the textures:

Matrix View = Matrix.CreateLookAt(new Vector3(0, 2, -6), Vector3.Zero, Vector3.UnitX);

Matrix Projection = 
    Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 1, 100);

Matrix[] container = new Matrix[model.Bones.Count];

foreach (ModelMesh mesh in model.Meshes)
    foreach (Effect effect in mesh.Effects)
            * Matrix.CreateRotationY(MathHelper.ToRadians(rotation)));


And of course, here is the solution to download !



Per Mesh Bounding Box tutorial

This article will show you how to build a dictionary of bounding boxes and link them in the code.

Why ? Because many times, the model you want to use in your game is quite complex and it’s build upon many meshes. And you may need to know, for example, if a certain part is clicked. If you have axis oriented objects (maybe walls, floors, etc) this solution can help you.

Solution: It’s quite simple. Since I don’t have much time for posting I’ll just post both, the processor and the code needed to access the boxes. Also, I’ll leave some tips.

First, this is the code for the processor:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;

namespace PerMeshBoundingBox
    [ContentProcessor(DisplayName = "CustomModelProcessor")]
    public class CustomModelProcessor :
        public override ModelContent Process(NodeContent input, ContentProcessorContext context)
            ModelContent output = base.Process(input, context);

            // stores a bounding box per mesh inside the model - we link the bounding box to the mesh using it's name
            Dictionary<string, BoundingBox> boundingBoxes = new Dictionary<string, BoundingBox>();

            foreach (NodeContent currentNodeContent in input.Children)
                // data needed to build a bounding box
                float minX = float.MaxValue;
                float minY = float.MaxValue;
                float minZ = float.MaxValue;
                float maxX = float.MinValue;
                float maxY = float.MinValue;
                float maxZ = float.MinValue;

                if (currentNodeContent is MeshContent)
                    MeshContent meshContent = (MeshContent)currentNodeContent;

                    foreach (Vector3 basev in meshContent.Positions)
                        Vector3 v = basev;
                        if (v.X < minX)
                            minX = v.X;

                        if (v.Y < minY)
                            minY = v.Y;

                        if (v.Z < minZ)
                            minZ = v.Z;

                        if (v.X > maxX)
                            maxX = v.X;

                        if (v.Y > maxY)
                            maxY = v.Y;

                        if (v.Z > maxZ)
                            maxZ = v.Z;

                    // creates a new bounding box associated to the mesh name
                    string meshName = currentNodeContent.Name;
                    BoundingBox boundingBox = 
                        new BoundingBox(new Vector3((float)minX, (float)minY, -(float)minZ),
                            new Vector3((float)maxX, (float)maxY, -(float)maxZ));

                    boundingBoxes.Add(meshName, boundingBox);
            // stores the bounding box inside the tag property
            output.Tag = boundingBoxes;

            return output;

This processor will store a dictionary of bounding boxes inside the Tag property of a model. What’s important here is that each bounding box is linked to the mesh using the mesh name.

The code needed to grab the boxes can be something like this:

Dictionary<string, BoundingBox> sceneBoundingBoxes = 
                (Dictionary<string, BoundingBox>)model.Tag;            

And what’s most important. You have to transform each box according to the mesh bones.

Matrix transforms = Matrix.CreateTranslation(position);

Matrix[] bones = new Matrix[model.Bones.Count];

foreach (ModelMesh mesh in model.Meshes)
    BoundingBox currentBoundingBox = sceneBoundingBoxes[mesh.Name];
    currentBoundingBox.Max = 
        Vector3.Transform(currentBoundingBox.Max, bones[mesh.ParentBone.Index] * transforms);
    currentBoundingBox.Min = 
        Vector3.Transform(currentBoundingBox.Min, bones[mesh.ParentBone.Index] * transforms);

The code above this line just transform the bounding box according some position (for example, some place where you are placing a model). Note you can add any transform you want.


Just as I pointed in the last tutorial, This WONT WORK if you are not applying the transformations to the model in your design program. In blender, before exporting, you have to select the models you are exporting and click CONTROL + A + 1 (what the tutorial on how to export models to blender).


Blender to XNA (fbx) – understanding the model

I’ll apologize for my English since it’s not my native language, but I’ll try to make myself as clear as possible.

Many people don’t understand very well the process (or at least the basics) of exporting a mesh to XNA from Blender. There are a few basic concepts that the user should know.

First, I’ll describe a scenario and then, I’ll enumerate what you should know: Suppose we have our game and we need a 3d object to be displayed. We all have done this in the past, but sometimes we just don’t understand why our object is not behaving the way it should we we apply a transformation. Even worse, some times we don’t even know where to place a camera because we don’t understand the “size” of the model.

I’ll try to explain those points here, I cannot assure I’ll be able to do it in a simple way, maybe because of my rusty english or maybe because it’s just a little hard (I’,m sure it’s because of my enlgish).

Object’s center position:

In blender, we you are creating or editing a model, you will notice a pink dot; This dot is used as reference to apply transforms. When you export the model to XNA, this little dot is also exported as a parent bone, and we apply a transformation this bone is also used as reference.


For example, we have a scenario with a plane as a the floor placed in Y = 0 and we want to add a cube in some position, so we go to blender to create our cube:

In blender we add a cube to an empty project (as shown in the picture above) and we export it (without ANY modification), the reference point will be in the center of the volume. (Notice the pink dot in the screenshot above).

As I said before, our floor is at Y = 0, and we want the cube to be placed above the floor (the bottom face should be at Y = 0 too). To achieve this, we translate our cube to (2,0,1) . This position, should be above the floor, since our Y component is 0.

If we do such transformation, we’ll notice our cube is half above, half under the floor: this is because we have tell XNA to move THE PINK DOT to (2,0,1). If you understood all this, you already know how to fix this: We have to change the position of the pink dot in blender.

How to do this:

Create a cube in blender and be sure it’s on the 0,0,0 position. You can do this by selecting the cube and open the transform properties dialog (N shortcut). You’ll notice 3 fields: LocX, LocY and LocZ. Set them with 0 and you’ll have it centered.

Go to edit mode (TAB key) and  choose face as selection mode (Ctrl + Tab –> faces). Now select the bottom face:


Nothing strange so far, we have just added a new object (in this case a cube), we have centered it  and now we have selected a face we want as reference in our game.

Now, we are going to move that little dot from the center of the volume to the center of the bottom face: With the bottom face selected,  press SHIFT + S; this will bring the “align dialog” popup, Choose “Cursor –> Active”. You’ll notice that the cursor (not the pink dot) will be placed in the center of the bottom face.

Now, to translate the pink dot, exit edit mode (TAB key) and in the buttons window choose, in the Mesh tab choose “Center Cursor”. Now, you should have your reference centered in the bottom face.



Important !!!

Many people doesn’t know this, but when you modify a model, the transformations are not directly mapped to XNA. If you are noticing different units or scales ALWAYS apply all transformation to the model: Select the model and press Ctrl + A  + 1. You can also achieve this by selecting the model and from the menu go to:

Object –> Clear/Apply –> Apply Scale/rotation to Obj Data

About the size:

There seems to be a bug or something with the fbx exporter and objects are scaled 10 times from blender to XNA. To solve this, in the export window change the Scale to 0.01.


Please notice that this can be applied to several type of objects. Characters and trees may have the reference under their feet but maybe planets or stars will be OK with their reference point in the center.