Archive for December, 2008

Modifying the URL Hash without affecting the browser history

Dec 29 2008 Published by Eneko Alonso under uncategorized

Although this is not very common, some times you would like to modify the URL hash (this is the value after the # on the URL) without affecting the browser history. Let’s say you have multiple sets of tabs on your page or simply that your hash is going to change very often. But still want the user to be able to grab a permanent link to that page configuration.

The trick is to use the replace function, instead of directly assigning the value.

  1. // Direct assignment will add a new step to the history on browsers like Firefox 3
  2. window.location.hash = newHash;
  3. // Using the replace function changes the hash without affecting the browser history.
  4. window.location.replace(window.location.href.split('#')[0] + '#' +newHash);

Nice.

No responses yet

Adding specific code for production only

Dec 26 2008 Published by Eneko Alonso under uncategorized

When you are developing a website you want to get as close as production as possible, to guarantee the final result will be appropriate and to make sure everything is going to work fine. But there are special cases when you want to add some code only on production, like stats code for example.

One easy way to do this is to check the server HTTP variables, the HTTP_HOST to be exact. This will contain your server host name, without the “http://” and the page URL. In my case, the value is “dev.enekoalonso.com”.

In PHP:

  1. <?php if ($_SERVER['HTTP_HOST'] == 'dev.enekoalonso.com'): ?>
  2. [Google Analytics code here]
  3. <?php endif; ?>

That way I don’t mess up my stats while spending hours creating a demo in my development environment.

2 responses so far

Forest demo (was Grass)

Dec 26 2008 Published by Eneko Alonso under uncategorized

I have updated the Grass demo and renamed it to Forest, which I think is a more appropriate environment for the sounds I used. I have done some fixes to the rain loop and I have added some light animations.
Magic Forest demo

No responses yet

Splitting a vector into two vectors 90 degrees apart

Dec 25 2008 Published by Eneko Alonso under uncategorized

I wanted to add something special to the Particle-Balls demo I made. At first, the idea seemed pretty simple: When clicking on a moving ball, split it in two with a 90° angle between them (π/2 in radians). To keep it simple, both balls will have the same size as the original and the same speed.

Vector split

Moving objects

So far, the way I have always animated objects is by storing a 2D position (x, y) and a 2D speed (horizontal speed and vertical speed). If the vertical speed is zero the object will be moving horizontally. If the vertical speed and horizontal are the same, the object will be moving at 45 degrees (π/4) and so on. It is very easy to update the position on every step of the animation according to the speed:

  1. // Speed is the number of pixels per second.
  2. // Interval is the time between calls in milliseconds.
  3. this.position.x += this.speed.x * (interval/1000);
  4. this.position.y += this.speed.y * (interval/1000);

Calculating the moving vector

When I started writing the code to split the ball in two, soon I realized my math was way deep in my memory where I couldn’t find it. Yes, trigonometry had to be involved, since I needed to calculate the angle of a moving ball based on the vertical and horizontal velocity. Then I would add 45 degrees (π/4) to the existing ball and create a clone of it, but subtracting 45 degrees (π/4) from the original angle. Easy, uh?

Let’s see. First we need to get the angle of the vector the object is moving on. This vector is determined by the vertical and horizontal speed, which form a right triangle:

\theta=arctan(\frac{opposite}{adjacent})

Or in Javascript:

  1. var angle = Math.atan2(ball.speed.y, ball.speed.x);

Angle of new vectors

Once we have the angle, we can calculate the angle of the new vectors:

  1. var V1angle = angle + Math.PI/4; // Add 90 degrees
  2. var V2angle = angle – Math.PI/4; // Subtract 90 degrees

2D speeds of new vectors

Once we have the final angles we can calculate the new horizontal and vertical speeds of the new vectors. But first we need Pitagoras to calculate the actual speed of the original vector:

speed=\sqrt{adjacent^2+opposite^2}

In Javascript:

  1. var speed = Math.sqrt(Math.pow(ball.speed.x,2)+Math.pow(ball.speed.y,2));

Given the hypotenuse (speed) and the angle, we can calculate the sides:

opposite=speed*sin(\theta)

adjacent=speed*cos(\theta)

In Javascript:

  1. ball1.speed.x = speed * Math.cos(V1angle);
  2. ball1.speed.y = speed * Math.sin(V1angle);
  3.  
  4. ball2.speed.x = speed * Math.cos(V2angle);
  5. ball2.speed.y = speed * Math.sin(V2angle);

And that is it! At the end, the math is not that complicated, as you can see. But if you haven’t used trigonometry in years, it kind of hurts a little bit when you have to figure it out.

PS: Thanks to my German sister Sarah for your help (we figured it out while having dinner)

One response so far

Grass demo: background sounds

Dec 23 2008 Published by Eneko Alonso under uncategorized

Grass is an example of how to create an environment with multiple sounds playing in the background at random intervals.
Grass Demo
See the demo:
http://dev.enekoalonso.com/research/grass.php

No responses yet

Particle Balls demo, now with sound!

Dec 20 2008 Published by Eneko Alonso under uncategorized

Last week I read about the SoundManager2 javascript/flash library to manage sounds on websites (I found SoundManager2 while reading about MooSound, a sound management library based in Mootools that I haven’t tried yet.). The library looks very nice. It is pretty small but at the same time it gives you a lot of control on sound playing. You can change the position of the sound while playing, adjust the stereo pan from left to right and much more.

Today I wanted to test this library and I decided to add some sounds to my Particle-Balls demo. Every time a ball hits a wall, a sound plays. To make it more fun, I use the X coordinate of the ball to adjust the pan, so if the ball is closest to he left border the sound will play on the left speaker and same with the right border/speaker. The pan can be adjusted gradually from -100 to 100 (left to right).

Particle Balls
Check the demo here:
http://dev.enekoalonso.com/research/particle-balls.php

3 responses so far

sIFR Lite

Dec 20 2008 Published by Eneko Alonso under uncategorized

sIFR is a script that allows using any font on websites by embedding them on a flash object. The first release was back in 2005 and although is not the only solution for using non-standard fonts on the web, is widely used because its server independent and doesn’t require any graphic processing on the server like the DTR techniques do.

Now, sIFR Lite has been released and it looks pretty good.

Seen here.

No responses yet

Wordpress Comment API & WPNotifier

Dec 20 2008 Published by Eneko Alonso under uncategorized

I didn’t know Wordpress had an API (I just decided to start using WordPress a few weeks ago). Apparently now is event better, since the 2.7 API has support for comments too. Well, I promise I’ll play with it as soon as I have some time. Others are already having fun with it and applications like WPNotifier are a good example of what this API can do.

No responses yet

Gravity in the DOM

Dec 18 2008 Published by Eneko Alonso under uncategorized

A couple of days ago I created a demo to simulate planets on a 2D universe interacting each other like Gravity does in our lives. To compute the movements every planet had to be evaluated with each other on every step. Their position will be affected by the other planet position and in proportion to their respective mass. This means the speed of the planets doesn’t impact the attraction between them.

Today I decided to extend this demo a little bit more and I added a few things:

  • Mass parameter to make mass independent from size.
  • Collision detector to merge planets when they meet each other with color effect.
  • Orbit trails

Gravity

The result is very nice. The first option make it possible to create bigger planets with more mass but with a size that fits appropiately on the screen. The second option merged planets that collide, making it more like a real world. Finally, the orbit trails are just some sugar to see the trajectory followed by the plantes. To avoid the screen getting very messy, the trails clean up themselves after 25 seconds.

As you can see, the universe controller uses the Thread class I was talking about few days ago.

See both demos here:
http://dev.enekoalonso.com/research/gravity.php
http://dev.enekoalonso.com/research/gravity-2.php

PS: Please note there is no Canvas involved here. All objects on screen are DOM elements. Of course this is not the best way to do graphic animations on the web, but it is fun!

No responses yet

Keyboard shortcuts in Drupal: Navigating through comments

Dec 14 2008 Published by Eneko Alonso under uncategorized

It was one of the best features of Google Reader and Google GMail: the keyboard shortcuts, specially the ones to navigate through messages or posts (n = next, p = previous).

I decided it was time to implement it on spaniards.es, so here is the code I used. So far it only navigates through comments back and forth on the same page (does not go to next page or so). I am planning to add other shortcuts soon.

  1. $(document).keyup(function(event) {
  2.  
  3.   if (event.target.tagName == "INPUT" ||
  4.       event.target.tagName == "TEXTAREA")
  5.     return;
  6.  
  7.   var selected = $('.comment-selected');
  8.  
  9.   // Next comment
  10.   if (event.keyCode == 78) {
  11.     if (selected.length) {
  12.       selected.removeClass('comment-selected');
  13.       selected = selected.nextAll('.comment:first');
  14.       selected.addClass('comment-selected');
  15.     } else {
  16.       selected = $('.comment:first').addClass('comment-selected');
  17.     }
  18.     if (selected.length) {
  19.       window.scrollTo(0, selected.offset().top);
  20.     }
  21.     return;
  22.   }
  23.  
  24.   // Previous comment
  25.   if (event.keyCode == 80) {
  26.     if (selected.length) {
  27.       selected.removeClass('comment-selected');
  28.       selected = selected.prevAll('.comment:first');
  29.       selected.addClass('comment-selected');
  30.     } else {
  31.       selected = $('.comment:last').addClass('comment-selected');
  32.     }
  33.     if (selected.length) {
  34.       window.scrollTo(0, selected.offset().top);
  35.     }
  36.     return;
  37.   }
  38. });

As you can see, it is important to leave the input and textarea fields alone, so the keyboard shortcuts don’t interfere with the user typing some text. With a little bit of CSS the selected comment can be displayed with a different border color or background. And that’s it!

Check an example topic at www.spaniards.es

2 responses so far

Next »