Website may be up and down over next few months. I'm currently doing a complete overhaul of everything. Going back to simple individual .htm pages, new overall site theme, sanitizing and cleaning up html of all pages and blog posts, attempting to implement a new tooling and publishing system etc etc.

The code below allows you to scale a GameObject transform to a specific size along the x & z axis by taking into account the GameObjects renderer bounds if a renderer component is attached.

/// <summary>
/// Scales a transform to specific dimensions along the x & z axis.
/// </summary>
/// <param name="transform">
/// Reference to the transform to scale.
/// </param>
/// <param name="width">The width along the x axis that represents the target size.</param>
/// <param name="height">The height along the z axis that represents the target size.</param>
public static void ScaleTransform(Transform transform, float width, float height)
{
    // get bounds of the prefab
    var bounds = new Bounds();
    var encapsulate = false;
    if (!Utilities.Helpers.GetBoundWithChildren(transform, ref bounds, ref encapsulate))
    {
        return;
    }

    // get minimum size from the size dimensions
    var min = Mathf.Min(width, height);

    // get the maximum x or z size of the transform
    var max = Mathf.Max(bounds.size.x, bounds.size.z);

    // calculate the scale factor 
    var scaleFactor = min / max;

    // apply scaling to the transform
    transform.localScale *= scaleFactor;
}

/// <summary>
/// Gets the rendering bounds of the transform.
/// </summary>
/// <param name="transform">The game object to get the bounding box for.</param>
/// <param name="pBound">The bounding box reference that will </param>
/// <param name="encapsulate">Used to determine if the first bounding box to be 
/// calculated should be encapsulated into the <see cref="pBound"/> argument.</param>
/// <returns>Returns true if at least one bounding box was calculated.</returns>
public static bool GetBoundWithChildren(Transform transform, ref Bounds pBound, ref bool encapsulate)
{
    var didOne = false;

    // get 'this' bound
    if (transform.gameObject.renderer != null)
    {
        var bound = transform.gameObject.renderer.bounds;
        if (encapsulate)
        {
            pBound.Encapsulate(bound.min);
            pBound.Encapsulate(bound.max);
        }
        else
        {
            pBound.min = bound.min;
            pBound.max = bound.max;
            encapsulate = true;
        }

        didOne = true;
    }

    // union with bound(s) of any/all children
    foreach (Transform child in transform)
    {
        if (GetBoundWithChildren(child, ref pBound, ref encapsulate))
        {
            didOne = true;
        }
    }

    return didOne;
}

/// <summary>
/// Packs color components into a <see cref="uint"/> type.
/// </summary>
/// <param name="r">The red component.</param>
/// <param name="g">The green component.</param>
/// <param name="b">The blue component.</param>
/// <param name="a">The alpha component.</param>
/// <returns>Returns a uint representing the color.</returns>
public static uint Pack(int r, int g, int b, int a)
{
    return (((uint)r & 0xff)) | (((uint)g & 0xff) << 8) | (((uint)b & 0xff) << 16) | (((uint)a & 0xff) << 24);
}

/// <summary>
/// Unpacks a <see cref="uint"/> type into a color type.
/// </summary>
/// <param name="value">The packed color value to unpack.</param>
/// <returns>Returns a color type from the unpacked values.</returns>
public static Color Unpack(uint value)
{
    var r = (byte)(value);
    var g = (byte)(value >> 8);
    var b = (byte)(value >> 16);
    var a = (byte)(value >> 24);

    return new Color(r, g, b, a);
}

GAH! Google is such phail, Bing is no better either. Been trying to find out how to use EF + SqlCe without having to specify any settings in my web.config.

Finally I found this page on unit testing that pointed be in the right direction.

And here is how to do it in code!

    
    public class testModel
    {
        [Key]
        [Required]
        public int ID { get; set; }
        [Required]
        public int SomeID { get; set; }
    }

    public class MyClass : System.Data.Entity.DbContext
    {
        public MyClass() { }
        public MyClass(string filename) : base(filename) { }
        
        public DbSet TableTest { get; set; }
    }
   
    public class HomeController : Controller
    {

        public ActionResult Index()
        {
            var path = this.Context.Server.MapPath("~/bin/");
            Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0", path, "");
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges());
            var tmp = new MyClass("test.sdf");
            tmp.TableTest.Add(new testModel() { SomeID = 5 });
            tmp.SaveChanges();

            return this.View(); 
        }
    }

The great outdoors await

Published 8/23/2009 by createdbyx in Example | News | Programming | XNA

Well I'm off to go pick mushrooms. I should be back around mid october or so depending on how the season goes. I have turned comment moderation on while i'm away to try and help keep the riff raff from spamming comments while i'm away.

I have added a few Ohsai updates and provided a second download this time with source code. Keep in mind that it is still in the prototyping stages but there is an example project with a few demos that will give you an idea of where the project is heading.

Oh and I'd just like to express just how much I hate Blizzard. "Just when I thought I was out. They ... pull ... me ... back ... in!" Sigh, I just spent a few hours today reading about the new World of Warcraft expansion called Cataclysm, and all of the various changes that will be taking place. I don't know what it is about that game but I compare it to being on crack. I hate even the thought of spending endless hours playing the game just to aquire items and gear etc, but at the same time I have this strong desire to play it.

The problem comes in when I start loosing the ability to manage my time properly between fighting the urge to play the game, and just trying to stay focused on other priorities. I have basically lost a year of work with my programming projects already because of two  previous six month subscriptions. And when I think about it in those terms I think about how much work I could have gotten done on those projects. No other game has even come close the the level of adddiction I have towards this game.

I am not sure what I am trying to say at this point other then before I heard about the new expansion I had 99% garenteed myself that i was never going to renew my subscription to that game. I have always felt a sense of deep loss that I am missing out when I don't have a subscription. Now after reading about the expansion I have almost convinced myself that I am 90% garenteed to renew my subscription in november. It's a vicous cycle.

Also just as a side note, I gotta mention just how blind I am to spotting spelling mistakes on my website. For the longest time there have been glaring and obvious spelling errors and for some reason I just can't seem to spot them. O.o

And OMG Comment spam! I don't even advertise this site and I am getting hit by spammers. I think I may need to leave comment moderation on when I come back. :(


Sigh it can be frustrating sometimes working on my various programming projects. My main solution I work with now consists of  94 projects. View Screenshot

Some of the projects could be considered "Done" but I have yet to upload them to this website and some are still only partially written or working. I have been wanting to create a series of video tutorials that walk through each project but I keep finding myself putting it off, partly because making videos can be very time consuming, and I tend to have too high of standards when making them, "Dam, I should not have said that", "I keep rambling on about off topic stuff", "Forgot to mention this or that feature", "Stupid lispy voice :P" etc etc

It will probably be a while (possible never) before I get around to making any of the videos.

Besides all that I have been doing more work with using xna and winforms and have created a simplfied version of the control then what microsoft has on the xna creators club web site. The reason I created a simplified version of the control is because I needed the control to integrate better with my level editing window. I have provided a preview image below of the control in use in my level editor. The source code can be downloaded here. SimplifiedWinformControl.zip (1.58 mb) (XNA 3.1)

Also something to keep in mind that VS.NET 2008 seems to have issues when the name of the control is the same as the namespace that it resides in. In the example project you may encounter a compile error in the TextForm.Designer.cs file on this line of code "this.xnaControl = new SimplifiedWinformControl.SimplifiedWinformControl();" just delete the namespace off the begining so that it reads like this "this.xnaControl = new SimplifiedWinformControl();". To avoid the error be sure to name your control something other then the namespace that it belongs to. Something else to remember is that if the control is resized larger then the main game windows backbuffer then the control will only display what it can.

public class SimplifiedWinformControl : Control
{
    private Game game;
    public Texture2D Texture { get; set; }
    private SpriteBatch spriteBatch;

    public Game Game
    {
        get { return this.game; }
        set
        {
            // hold onto the game reference
            this.game = value;
            if (this.game == null) return;
            // create the sprite batch
            this.spriteBatch = new SpriteBatch(this.game.GraphicsDevice);
        }
    }

    /// <summary>
    /// Ignores WinForms paint-background messages. The default implementation
    /// would clear the control to the current background color, causing
    /// flickering when our OnPaint implementation then immediately draws some
    /// other color over the top using the XNA Framework GraphicsDevice.
    /// </summary>
    protected override void OnPaintBackground(PaintEventArgs pevent)
    {
        // do nothing here. If this is not overridden the control may have drawing issues O.o 
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        if (this.game == null)
        {
            // draw normal winform way
            e.Graphics.FillRectangle(System.Drawing.SystemBrushes.Control, this.ClientRectangle);
            e.Graphics.DrawString(this.GetType().FullName, this.Font,
                                    System.Drawing.SystemBrushes.ControlText, 0, 0);
        }
        else
        {
            // draw xna way 
            var gr = this.game.GraphicsDevice;
            var oldVP = gr.Viewport;

            // set the graphics viewport to the size the the controls client area
            var newVP = new Viewport()
            {
                Width = this.ClientSize.Width,
                Height = this.ClientSize.Height,
                MinDepth = 0,
                MaxDepth = 1
            };

            gr.Viewport = newVP;

            // clear then draw something onto the control
            gr.Clear(Color.CornflowerBlue);
            this.spriteBatch.Begin();
            this.spriteBatch.Draw(this.Texture, Vector2.Zero, Color.White);
            this.spriteBatch.End();

            // display it onto the control
            try
            {
                var rect = new Rectangle(0, 0, this.ClientSize.Width, this.ClientSize.Height);
                gr.Present(rect, null, this.Handle);
            }
            catch (Exception)
            {
                // Present might throw if the device became lost while we were
                // drawing so we just swallow the exception.
            }

            // restore previous viewport
            gr.Viewport = oldVP;
        }
    }

    protected override void OnCreateControl()
    {
        // check if we are not in design mode and if not hook into the application idle event
        if (!this.DesignMode)
        {
            // just invalidate the control so that it will be redrawn
            // you could also put in some logic to restrict how often the control get invalidated
            Application.Idle += ((sender, e) => { this.Invalidate(); });
        }
        base.OnCreateControl();
    }

    // not really nessary in this simple example to have a dispose here but i put it in anyway
    protected override void Dispose(bool disposing)
    {
        // perform some cleanup
        if (this.spriteBatch != null) this.spriteBatch.Dispose();
        this.spriteBatch = null;
        // we dont need to dispose of the texture here but I did anyway it will be
        // disposed by the content manager. :P But if you have texture(s) you created 
        // your self then this is where they would get disposed
        if (this.Texture != null) this.Texture.Dispose();
        this.Texture = null;
        base.Dispose(disposing);
    }
}

Winforms in XNA

Published 6/1/2009 by createdbyx in Example | News | Programming | XNA

I have created a example project on the XNA page that demonstrates how to add winform controls to your game window in just a few lines of code. I created this project because I recently downloaded the winforms example project found at the XNA creators club website and found it to be rather overkill for what it does.  View Screenshot

Download the example project here. AddingWinformControlsTest.zip (38.58 kb) (XNA 3.0)


New example added

Published 11/20/2008 by createdbyx in Example | News | Programming | XNA
I have added a new xna 3.0 example project that demonstrates stenciling. You can download the example here. View Screenshot

RPG objects

Published 1/28/2008 by createdbyx in Example | News | Programming
Tags:
I have posted a RPG objects example application on the projects page. The example code was written so that I could use it as a thinking tool. It implements a very basic RPG item system. Click here to get more info.

Lots of new content added

Published 4/8/2007 by createdbyx in Example | Games | News | Reviews | XNA
Tags: , , ,
I have ported over some more of my old content from the previous incarnations of the createdbyx.com website.
I have also decided to re upload the numerous incarnations of my old websites. You can find some of them listed here ...
The contact page can now be found by hovering your mouse over the Home link at the top of the site.

Also fixed some minor spelling mistakes and formatting on various pages. A new XNA example project wa added as well called HealthBarProject. HealthBarProject demonstrates one way to display a health bar that floats above a desired object using the Viewport.Project method and 2D sprites rendered with a SpriteBatch object. The health bar also scales itself depending on the distance from the camera's position.
View Screenshot

XNA example code updates

Published 2/4/2007 by createdbyx in Example | News | XNA
Tags: , ,

I just purchased a wired xbox 360 controller so I can test my code using the controller! I also just posted updated code for my two xna example projects ...

The examples now support the xbox 360 controller as an input device.


Created by: X

Just another personal website in this crazy online world

Name of author Dean Lunz (aka Created by: X)
Computer programming nerd, and tech geek.
About Me -- Resume