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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With