Skip to content

Instantly share code, notes, and snippets.

@nanchu
Created September 30, 2012 00:09
Show Gist options
  • Save nanchu/3805456 to your computer and use it in GitHub Desktop.
Save nanchu/3805456 to your computer and use it in GitHub Desktop.
Forward animated walk cycle
#walkingdude.keyframe0 //start him off on frame 0 of our sprite
.walkdemo
overflow-x: scroll
overflow-y: hidden
width: 8000px //indicate width of your page
$sprite-width: 334px //indicate width of each sprite keyframe
#walkingdude
display: block
position: fixed
top: 50px
left: 20%
background-image: url('/images/walkcycle.png') //walk cycle sprite
width: $sprite-width
height: 500px
z-index: 4
//create classes for each frame using background position to find the keyframe on your sprite.
.keyframe0
background-position: left bottom //this is your default resting position frame
.keyframe1
background-position: 0px 0px
.keyframe2
background-position: 2000 - $sprite-width 0px
.keyframe3
background-position: 2000 - $sprite-width*2 0px
.keyframe4
background-position: 2000 - $sprite-width*3 0px
.keyframe5
background-position: 2000 - $sprite-width*4 0px
.keyframe6
background-position: 2000 - $sprite-width*5 0px
$(document).ready(function() {
//bind your animation function to the scroll listener
$(window).bind('scroll',function(e){
walkanimation();
});
var walkRate=[]; //create an array for the rate you want to switch frames
var switchKeyFrame=[]; //create an array to store your keyframe classes
var walkcycle = 24000 //how far do you want to walk in pixels?
for(var i=0, j=5 ;i<walkcycle;i++, j+=200){
walkRate.push(j);
switchKeyFrame.push("keyframe" + ((i%6)+1)); //keyframe1 - keyframe6
}
function walkanimation(){
var scrollPosition = $(window).scrollLeft();
for(var i = 0; i<walkRate.length; i++) {
//if you are at position 0, show default standing still frame
if (scrollPosition == 0) {
$('#walkingdude').attr('class', 'keyframe0');
//depending on how far you've scrolled, swap out keyframe classes
}else if(scrollPosition > walkRate[i] && scrollPosition < walkRate[i+1]){
$('#walkingdude').attr('class', switchKeyFrame[i]);
}
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment