用cursor生成一个平台跳跃游戏DEMO
1、安装cursor:略过
2、登录cursor:略过
3、在右侧chat输入:用JS创建平台跳跃游戏,点击send
4、生成代码,并保存代码
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// 加载玩家图片
const playerImage = new Image();
playerImage.src = 'player.png'; // 请确保在同一目录下有 player.png 文件
// 玩家属性
const player = {
x: 100,
y: 200,
width: 30,
height: 30,
speed: 5,
jumpForce: 12,
gravity: 0.5,
velocityY: 0,
isJumping: false
};
// 平台数组
const platforms = [
{ x: 0, y: 350, width: 800, height: 50 }, // 地面
{ x: 300, y: 250, width: 200, height: 20 }, // 平台1
{ x: 100, y: 150, width: 200, height: 20 }, // 平台2
{ x: 500, y: 200, width: 200, height: 20 } // 平台3
];
// 键盘控制
const keys = {
left: false,
right: false,
up: false
};
// 事件监听
document.addEventListener('keydown', (e) => {
if (e.key === 'ArrowLeft') keys.left = true;
if (e.key === 'ArrowRight') keys.right = true;
if (e.key === 'ArrowUp' && !player.isJumping) {
keys.up = true;
player.isJumping = true;
player.velocityY = -player.jumpForce;
}
});
document.addEventListener('keyup', (e) => {
if (e.key === 'ArrowLeft') keys.left = false;
if (e.key === 'ArrowRight') keys.right = false;
if (e.key === 'ArrowUp') keys.up = false;
});
// 碰撞检测
function checkCollision(rect1, rect2) {
return rect1.x < rect2.x + rect2.width &&
rect1.x + rect1.width > rect2.x &&
rect1.y < rect2.y + rect2.height &&
rect1.y + rect1.height > rect2.y;
}
// 更新游戏状态
function update() {
// 水平移动
if (keys.left) player.x -= player.speed;
if (keys.right) player.x += player.speed;
// 应用重力
player.velocityY += player.gravity;
player.y += player.velocityY;
// 检查与平台的碰撞
player.isJumping = true;
for (let platform of platforms) {
if (checkCollision(player, platform)) {
if (player.velocityY > 0) {
player.y = platform.y - player.height;
player.velocityY = 0;
player.isJumping = false;
}
}
}
// 边界检查
if (player.x < 0) player.x = 0;
if (player.x + player.width > canvas.width) player.x = canvas.width - player.width;
if (player.y + player.height > canvas.height) {
player.y = canvas.height - player.height;
player.velocityY = 0;
player.isJumping = false;
}
}
// 绘制游戏画面
function draw() {
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制玩家
ctx.fillStyle = '#FF0000';
ctx.fillRect(player.x, player.y, player.width, player.height);
// 绘制平台
ctx.fillStyle = '#00FF00';
platforms.forEach(platform => {
ctx.fillRect(platform.x, platform.y, platform.width, platform.height);
});
}
// 游戏主循环
function gameLoop() {
update();
draw();
requestAnimationFrame(gameLoop);
}
// 开始游戏
gameLoop();
5、运行index.html
总结:跳跃反应流畅