Christopher
Stoll

HTML5 Space Invaders Clone: iPhone Edition

As a programing experiment I decided to see if I could modify my HTML5 Space Invaders Clone in order to make it work on an iPhone. I was primarily interested in taking advantage of the tilt sensor using JavaScript. It was not too difficult, and the defender in the game moves from side to side based upon the phone's rotation. Below is a link to play the game, and after that is the relevant code (after the jump). It has been optimized for the iPhone and thus does not work as well on a PC.



Space Invaders Clone for iPhone


if(typeof(DeviceOrientationEvent) != 'undefined'){
    window.addEventListener('deviceorientation',
        function(e){
            self.tilt(e.alpha);
        }, false
    )
}

// handle phone tilt
SpaceInvaders.prototype.tilt = function(pVal){
    var tDmp = 0
        tDir = 0;
    
    if(!this.lastOrientation){
        this.lastOrientation = pVal;
    }
    
    tDmp = Math.abs(this.lastOrientation - pVal);
    tDir = this.lastOrientation - pVal;

    if(tDmp > 8){
        if(tDir > 0){
            this.heroMoveRight();
        }else{
            this.heroMoveLeft();
        }
    }
}
Published: 2011-07-02
BloggerJavaScriptGamesiPhoneHTML5Code