FORK ME

console 命令行工具 X clear

                    
>
console
var ctx;

var isJumping = false;


var v=1500

var v0=1500
var g=4000
var s=0
var frameSpeed=15
var t=frameSpeed/1000;
var h=0;


//画出障碍物
function drawObj(s){
canvas =  document.getElementById("canvas");
ctx=canvas.getContext("2d");
ctx.fillStyle="#2196f3";
ctx.fillRect(430,430-s,70,70);

}

//创建主主
function createSquare(){
drawObj(0)
}

function clearObj(){
ctx.clearRect(0,0,1000,500);  
}


function jump(){
if(!isJumping){
isJumping = true;
jumpProcess = setInterval(function(){jumpUp()},frameSpeed)
}

}

function jumpUp(){
if(v0>=0){
clearObj()
s=v0*t-0.5*g*t*t
v0=v0-g*t
h+=s
drawObj(h)
}
else{
clearInterval(jumpProcess)
jumpProcess = setInterval(function(){jumpDown()},frameSpeed)
v0=0
}
}

function jumpDown(){
//有效的判断落点方法
if(v0<v){
clearObj()
s=v0*t+0.5*g*t*t
v0=v0+g*t
drawObj(h)
h-=s
}
else{
clearInterval(jumpProcess)
isJumping = false;
v0=v
}
}





//入口
function main(){
createSquare()
}

//初始化
main();
addEventListener("keydown", function (e) {
	jump();
}, false);
<canvas id="canvas" width="1000" height="500" style="border:1px solid #4caf50;"></canvas>
body {TEXT-ALIGN: center;}
canvas {
margin-left: auto;
margin-right: auto;
}