Animating a Sprite with jQuery

Written by Tony Lea on Mar 2nd, 2012 Views Report Post

Table of contents

Animating a sprite with jQuery is very simple. I have created a simple sprite animation to show you how this is done. I have used a png image of Mario from the SNES 'Super Mario World'. You can see what the image looks like below:

Check out the demo here.

Below is the simple code that I used to create this simple animation:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<title>Mario Sprite Animation Scroll</title>
		<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
		<style type="text/css">
			#mario{
				background:url('mario-walk.gif') no-repeat;
				width:50px;
				height:68px;
				position:fixed;
				left:0;
				background-position:0px 0px;
			}
			
			#mario2{
				background:url('mario-walk.gif') no-repeat;
				width:50px;
				height:68px;
				position:fixed;
				left:0;
				background-position:0px 0px;
			}
			
			.instructions
			{
				font-family:'Helvetica Neue', Helvetica, Arial;
				font-size:14px;
				color:#343434;
			}
			
		</style>
		
		<script type="text/javascript">
			
			$('document').ready(function(){
				$('#mario').css('top', ($(window).height()/2)-($('#mario').height()/2));
				
				$('html').keydown(function(){
					$('#mario').css('top', ($(window).height()/2)-($('#mario').height()/2));
					$('#mario').css('left', parseInt($('#mario').css('left'))+10);
					
					if($('#mario').css('background-position') == '0px 0px'){
						$('#mario').css('background-position', '-50px 0px');
					} else {
						$('#mario').css('background-position', '0px 0px');
					}
					
					if(parseInt($('#mario').css('left')) > $(window).width())
					{
						$('#mario').css('left', -parseInt($('#mario').width()));
					}
				});
			});
			
		</script>
		
	</head>
	<body>
	
		<p class="instructions" readonly="readonly">Hold any key down to animate mario...</p>
		<div id="mario"></div>
	
	</body>
</html>

Pretty simple, right. You can download the files from here.

Comments (0)