console
//X,Y是方块的中心点
var playerX=40;
var playerY=40;
var playSpeed=15;
var playerMoveSpeed=7;
var jumpProcess;
var moveProcess;
var canvas = document.getElementById("player");
var ctx=canvas.getContext("2d");
ctx.fillStyle="#2196f3";
var vt=1500
var v0=1500
var g=4000
var s=0
var t=playSpeed/1000;
var angle=0;
var isJumping = false;
var isWin=false;
//////////////////初始变量///////////////
//画出障碍物
function drawObstacle(position,height){
canvas1 = document.getElementById("background");
ctx1=canvas1.getContext("2d");
ctx1.fillStyle="#9b59b6";
ctx1.fillRect(100*position,500-height,100,height);
//位置position,竖直位置,宽度100,高度height
}
function createObstacles(){
drawObstacle(0,1)
drawObstacle(2,1)
drawObstacle(4,1)
drawObstacle(5,230) //500,160 左侧左边,高度
drawObstacle(8,2)
}
//////////////////上面是背景CANVAS相关////
//绘制方块的函数
function drawObj(playerY,angle){
ctx.save();
ctx.translate(playerX, 460-playerY)
ctx.rotate(angle*360/642.5* Math.PI/360)
playerX+=playerMoveSpeed;
ctx.fillRect(-40,-40,80,80);
ctx.restore();
}
//清除canvas方块图形
function clearPlayer(){
ctx.clearRect(0,0,1200,500);
//失败&胜利条件
if(playerX>=canvas.width-40){
ctx.font = "40px Georgia";
ctx.fillStyle = "red";
ctx.fillText("YOU WIN !!!", 500, 150);
isWin=true;
if(jumpProcess!=null) clearInterval(jumpProcess)
if(moveProcess!=null) clearInterval(moveProcess)
}
else if(playerX>=460 && playerX<=640 && playerY<=230){
isWin=true;
reset()
}
else{
}
}
//跳跃
function jump(){
if(!isJumping){
isJumping = true;
if(moveProcess!=null) clearInterval(moveProcess)
jumpProcess = setInterval(jumpUp,playSpeed)
}
}
function jumpUp(){
if(v0>0){
clearPlayer();
s=v0*t-0.5*g*t*t
v0=v0-g*t
playerY+=s
drawObj(playerY,playerY)
}
else{
clearInterval(jumpProcess)
jumpProcess = setInterval(jumpDown,playSpeed)
}
}
function jumpDown(){
if(v0<vt){
clearPlayer();
s=v0*t+0.5*g*t*t
v0=v0+g*t
//先操作坐标,再绘图;先绘图再操作坐标;区别是:后操作有一个延迟,会在RESET后对X,Y产生影响。不知道为什么。
drawObj(playerY,angle)
playerY-=s;
angle += s
}
else{
clearInterval(jumpProcess)
isJumping = false;
playerY=40
angle=0
moveProcess = setInterval(move,playSpeed)
}
}
//移动
function move(){
clearPlayer()
ctx.fillRect(playerX-40,420,80,80);
playerX+=playerMoveSpeed;
}
//重置
function reset(){
if(jumpProcess!=null) clearInterval(jumpProcess)
if(moveProcess!=null) clearInterval(moveProcess)
playerY=40
playerX=40
v0=vt
moveProcess = setInterval(move,playSpeed)
isWin=false;
isJumping = false;
}
//入口
function main(){
drawObj(0,true)
createObstacles()
moveProcess = setInterval(move,playSpeed)
addEventListener("keydown", function(e) {
if(!isWin){
clearInterval(moveProcess)
jump();
}
else{
}
}, false);
}
//初始化
main();
<canvas id="player" width="1200" height="500" style="left:100px;position:absolute;border:1px solid #4caf50;z-index:421;"></canvas>
<canvas id="background" width="1200" height="500" style="left:100px;position:absolute;border:1px solid #4caf50;z-index:331;"></canvas>
body {TEXT-ALIGN: center;margin:0;padding:0}
canvas {
margin-left: auto;
margin-right: auto;