Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create jumping effect for an object

Tags:

javascript

here i created a grass object and it has two methods jump and fall.it jumps when user presses the up key on the keyboard.it jumps ,its alright.but i want it to fall back to its previous position..

i have created a keypressed variable which value is either true of false.it will determine the boundary how high the object can jump.

the object should fall back to its previous position after each jump.which i can't manage to do..also jump is not realistic enough...how this problems can be solved

jsfiddle

link to the image

FULL CODE:

<html>
<body>
<canvas id="mycanvas"></canvas>
<script>
var canvas=document.getElementById("mycanvas");
var ctx=canvas.getContext('2d');
canvas.width=500;
canvas.height=500;
canvas.style.border="1px solid black";
var keypressed=true;
var img=new Image();
img.src="grass.jpg";
function grass(x,y){
   this.x=x;
   this.y=y;
   this.image=img;

}

grass.prototype.draw=function(){
     ctx.drawImage(this.image,this.x,this.y);
}
grass.prototype.hop=function(){

   this.y-=200;
 keypressed=false;
}
grass.prototype.fall=function(){
  this.y+=200;
keypressed=true;

}
var grass1=new grass(30,450);
grass1.draw();
document.addEventListener('keydown',function(e){
        ctx.clearRect(0,0,canvas.width,canvas.height);
       if(keypressed && e.keyCode=='38'){

       grass1.hop();


       }
       if(grass1.y<0){
       return false;
       }else{
       grass1.draw(grass1.x,grass1.y);
        }
},false);
</script>
</body>
</html>
like image 577
AL-zami Avatar asked Mar 05 '26 14:03

AL-zami


1 Answers

Here is a simple version of what you want: http://jsfiddle.net/B2SL5/

The key here is to use requestAnimationFrame (alternatively, you could use setInterval). We redraw the grass every frame (about 60 times a second). That way, when the grass moves (we call grass.y-- to move it down), it shows on the screen. Then, we have a velocity variable to keep track of how fast we're going.

like image 193
soktinpk Avatar answered Mar 08 '26 02:03

soktinpk