Jquery Snowfall Plugin 1.3

Plugin has been updated to 1.4 please go here for more up to date information

*Updated* fixed a bug, and added an example file to show how to use the plugin.

Added a few new things to the Jquery snowfall plugin, you now have the ability to clear the snow from elements, chaining is supported, and element matching is supported. Its funny today was the hottest day of the year so far and I decided to work on a script to make it snow.

Download Jquery Snowfall 1.3.1

Invoking the snow

    $(document).snowfall();
    $('#elementid').snowfall({flakeCount : 100, maxSpeed : 10});
    $('.class').snowfall({flakeCount : 100, maxSpeed : 10});

Snowfall Methods

    // stopping the snow
    $(document).snowfall('clear');
    $('#elementid').snowfall('clear');
    $('.class').snowfall('clear');

Options currently supported with default values

options = {
	flakeCount : 35,		// number
	flakeColor : '#ffffff', // string
	flakeIndex: 999999,		// number
	minSize : 1,			// number
	maxSize : 3,			// number
	minSpeed : 2,			// number
	maxSpeed : 3			// number
};

Example

Game Related Snippets I always Forget

When I sit down to prototype something new I always find myself looking up the same snippets to do the same types of things. I figured I might as well record them somewhere so I know an easy place to look when I do forget. All the samples will be in Javascript and should be able to be easily converted to any other language.

Distance Formula

Obviously a pretty important one, used to tell the distance between 2 objects. Can be used for simple radius collisions as well.

var distance = Math.sqrt((x2 - x1) *(x2-x1) + (y2 - y1) * (y2-y1));

Move toward an object (Without rotation) with easing

x += (targetX-x)/speed;
y += (targetY-y)/speed;

Angle Based Movement

I always see myself needing this one, whether its for an Asteroids clone, or a follow the leader type game.

velX = Math.cos((angle * Math.PI / 180) * thrust);
velY = Math.sin((angle * Math.PI / 180) * thrust);

Friction

How do I make something slow down if no force is applied?

velX *= .98; //Any val under 1 is suitable for your needs
velY *= .98

2D Matrix

This is a pretty simple one I know.. but I always seem to forget it. This is how to store a 2d matrix in an array. And how to find a value you need.

// 2d matrix[y * width + x]
var arr = [],
     width = 10;

for(x=0; x<width; x++){
    for(y=0; y<width; y++){
        arr[y * 10 + x] = x + y; //Or whatever value you need to assign
    }
}

//Retrieve a value from x:5, y:2
var val = arr[2 * 10 + 5];

//get the x and y from a 1d array
var index = 12,
    x = index % width, // 2
    y = Math.floor(index / width); // 1

Move towards and object at a constant speed

    var tx = targetX - x,
        ty = targetY - y,
        dist = Math.sqrt(tx*tx+ty*ty),
        rad = Math.atan2(ty,tx),
        angle = rad/Math.PI * 180;;

        velX = (tx/dist)*thrust;
        velY = (ty/dist)*thrust;

Example

Project a point in front of an object

    x + length * Math.cos(angle*Math.PI / 180);
    y + length * Math.sin(angle*Math.PI / 180);

Get the angle between objects

    var x = targetX - this.x,
        y = targetY - this.y;

     return Math.atan2(x,-y);

Plot points around a circle

    var rad = 500,
        total = 50,
        centerX = 250,
        centerY = 250;

    for(var i = 0; i < total; i++){
        ctx.beginPath();
        ctx.moveTo(centerX,centerX);
  
        var x = centerX + rad * Math.cos(2 * Math.PI * i / total),
            y = centerY + rad * Math.sin(2 * Math.PI * i / total);   

        ctx.lineTo(x, y);
        ctx.stroke();
        ctx.closePath();
    }

Quick Sort algorithm comparison

I’ve been trying to do regular programming exercises lately just to stay sharp and recently I decided to take on sorting algorithms. I used my current language of choice (javascript) and set out to implement the quick sort algorithm. Below is the portion of my code that completes this.

sorting.qSort = function (sortItems, _left, _right) {
	var left = _left,
		right = _right,
		pivot = right;

		if(right > left){
			do{
				// From left
				for(var i = left; i < pivot; i+=1){
					left = i;

					if(sortItems[i] > sortItems[pivot]){
						pivot = i;
						break;
					}
				}

				// From right
				for(var i = right; i > pivot; i-=1){
					right = i;

					if(sortItems[i] < sortItems[pivot]){
						// swap
						sortItems.swap(i, pivot);
						pivot = i;
						break;
					}
				}
			}while((right - left) > 1);

			this.qSort(sortItems, _left , pivot - 1);
			this.qSort(sortItems, pivot + 1, _right);

			return true;
		}

	return false;
}

The funny thing is really how much quicker this was than the Bubble sort algorithm. The only benefit I can find to bubble sort is it is much faster to implement

sorting.bubSort = function (sortItems) {
	for(var i = 0; i < sortItems.length; i+=1){
		if(sortItems[i] > sortItems[i+1]){
			//swap change the incrementor to -1
			sortItems.swap(i, i+1);
			i=-1;
		}
	}
}

But like many I recommend you never use it. Using quick sort and sorting 2000 items in random order I get an average of 0.08 with bubble sort this increases to 20 seconds! Also I recommend for javascript using the built in sorting function for arrays the below code beat out my implementation of quick sort everytime with an average speed of 0.01 seconds. Of course its also much easier to implement.

sorting.internalSort = function sortNumber(a,b){
     return a - b;
}

All tests were performed in Chrome. It was a fun exercise overall and helped me brush up on my recursion skills.

How to get the week in a month for a date with Javascript

Working on my calendar application and I needed to get what week in the current month a day occurs on. Unfortunately I couldn’t find anything like this in the JavaScript Date object so this is the function I came up with

Date.prototype.getMonthWeek = function(){
	var firstDay = new Date(this.getFullYear(), this.getMonth(), 1).getDay();
	return Math.ceil((this.getDate() + firstDay)/7);
}

Thanks to mutilator for helping out with the actual math to figure it out.

Javascript Sorting by date time

Im currently working on a web based calendar and I needed to sort my event object by date real quick. So the first thing I did was a quick search  on sorting an object by date time. Google becomes such second nature I immediately think of doing that first sometimes before fleshing out a whole solution in my mind. The first result I was brought to was this page on about.com. While the authors solution will work I thought why do even need this complexity? This is what I came up with when I stepped away from Google realizing this was a very trivial task

/*
* Function : sortDate(Date, Date)
* Description : Sorts an object based on date
*/
function sortDate(a,b)
{
    var a = new Date(a.startDateTime),
        b = new Date(b.startDateTime);
    return (a.getTime() - b.getTime());
}

My object has a property called startDateTime, but this can easily be modified. All I do is a quick comparison of the UNIX time stamp and its sorted. Mainly just hoping this eventually ranks higher than the result I found on Google.

Canvas Lunar Lander update

Game is still coming along, it now supports zooming, which was actually a little bit tricky to figure out. Only a few more things left to add before its a full fledged game.. or clone of a game that is.

Check out the progress  of JSLander

Now supported in any browser that supports the canvas element.

Lunar Lander Canvas Game

Working on a lot of things lately but noticed I haven’t made a post in quite a while. Heres a quick look at one of the random games I’m making using JavaScript and the Canvas element. Its essentially a clone of Lunar Lander.  As it is right now you can’t actually crash, and if you successfully land on one of the pads, your drops from the top again.  I’m not sure yet if I’m going to add the zoom effect when you get close to the landing pads, I think its pretty cool looking as a full page game. I imagine making a bunch of lander automated and having it set as the background to a gaming page.. of course it will only work in modern browsers at this time.

Check it out here