Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

1. Jumping/Gravity in Game

I've been trying to use the set interval in JavaScript, but I can't figure out how to make a jump which gradually decreases the y increase rate then incrementally
increases the decrease rate of y.
Code:
``` if (key == 32) //space
{
setInterval(function(){jump()},1000);
}
function jump()
{
var d=y+100;
document.getElementById('player').style.marginTop=y+'px';
}```

• You need a permanent variable to store the initial vertical velocity.
On each iteration, the velocity is decreased by a fixed amount representing acceleration due to gravity. Eventually the velocity becomes negative.
Continue until the position equals the starting point, below which you must not drop.

I would use setTimeout instead, so you don't have to cancel the interval.

• See the source of this Ball bounce page

• Code:
```<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<title></title>
<style type="text/css">
/*<![CDATA[*/

#tst {
position:absolute;left:200px;top:200px;width:200px;height:100px;background-Color:red;
}

/*]]>*/
</style>
<script type="text/javascript">
/*<![CDATA[*/

function zxcBounce(id,mde,f,to,ms,nu){
var mde=mde=='top'?'top':'left',o=zxcBounce[id+mde],ms=typeof(ms)=='number'&&ms>0?ms:1000,nu=typeof(nu)=='number'&&nu>0?nu:1,obj=document.getElementById(id),z0=0;
if (!o&&obj){
o=zxcBounce[id+mde]=[obj,mde,mde=='top'?'offsetTop':'offsetLeft'];
}
if (o&&typeof(to)=='number'&&typeof(f)=='number'){
o[3]=[];
for (;z0<nu;z0++){
o[3].push(f+(to-f)*(1-Math.sin((z0*90/nu)*Math.PI/180)));
o[3].push(f);
}
animate(o,f,o[3][0],new Date(),ms,'s',Math.PI/(2*ms));
}
}

function animate(a,f,t,srt,mS,s,i){
clearTimeout(a[5]);
var ms=new Date()-srt,n=Math.floor(s=='s'?(t-f)*Math.sin(i*ms)+f:s=='c'?t-(t-f)*Math.cos(i*ms):(t-f)/mS*ms+f);
if (isFinite(n)){
a[0].style[a[1]]=n+'px';
}
if (ms<mS){
a[5]=setTimeout(function(){ animate(a,f,t,srt,mS,s,i); },10);
}
else {
a[3].splice(0,1);
ms/=1.5;
a[3][0]?animate(a,t,a[3][0],new Date(),ms,s=='s'?'c':'s',Math.PI/(2*ms)):null;
}
}

/*]]>*/
</script>

<body>

<input type="button" name="" value="Bounce" onmouseup="zxcBounce('tst','top',200,100,1000,4);" />
<div id="tst" ></div>
</body>

</html>```

•