如何在p5.js中让分数固定停在指定数值(如10)?
问题分析与解决方案
你的代码无法让分数停在10的核心原因有两个:
- 碰撞加分的逻辑没有限制分数上限,只要碰撞就会持续累加分数
draw()函数里的return语句无法终止游戏循环,后续的碰撞检测和分数累加仍会执行
修复后的完整代码
/* VARIABLES */ let catcher, fallingObject; let score = 0; let stickFigureVisble = true; let catcherImg; /* PRELOAD LOADS FILES */ function preload(){ catcherImg=loadImage("assets/stickFigure.png"); } /* SETUP RUNS ONCE */ function setup() { createCanvas(400,400); //Create catcher catcher = new Sprite(catcherImg, 200,380,100,20, "k"); catcher.color = color(95,158,160); catcherImg.resize(50,50); //Create falling object fallingObject = new Sprite(100,0,10); fallingObject.color = color(0,128,128); fallingObject.vel.y = 2; } /* DRAW LOOP REPEATS */ function draw() { background(224,224,224); // Draw directions to screen fill(0); textSize(12); text("Move the \ncatcher with the \nleft and right arrow keys to \ncatch the falling \nobjects. Reach \n10 points to \nwin \nthe game." , width-100, 20); // 分数达到10时,显示胜利信息并终止游戏逻辑 if (score === 10) { fill(255, 0, 0); textSize(24); textAlign(CENTER); text("You Win!", width/2, height/2); // 停止下落物体和 catcher 的移动 fallingObject.vel.y = 0; catcher.vel.x = 0; return; // 结束当前draw循环,不再执行后续逻辑 } //If fallingObject reaches bottom, move back to random position at top if (fallingObject.y >= height) { fallingObject.y = 0; fallingObject.x = random(width); fallingObject.vel.y = random(1,5); } // Moving catcher if (kb.pressing("left")) { catcher.vel.x = -3; } else if (kb.pressing("right")) { catcher.vel.x = 3; } else { catcher.vel.x = 0; } // Stop catcher at edges of screen if (catcher.x < 30) { catcher.x = 30; } else if (catcher.x > 370) { catcher.x = 370; } // 只有分数小于10时,碰撞才加分并重置物体位置 if (fallingObject.collides(catcher)) { fallingObject.y = 0; fallingObject.x = random(width); fallingObject.vel.y = random(1,5); fallingObject.direction = "down"; if (score < 10) { // 限制分数上限 score += 1; } } // Score keeper fill(0); textSize(17); textAlign(LEFT); // 重置文本对齐方式,避免影响胜利文本 text("Score: " + score, width-390, 35); }
关键修改点说明
- 限制分数累加:在碰撞加分的逻辑中添加
if (score < 10)判断,确保分数达到10后不再增加 - 终止游戏逻辑:当
score === 10时,先显示胜利信息,然后停止所有物体的移动,最后用return结束当前draw循环,不再执行后续的碰撞检测和移动逻辑 - 修正文本对齐:胜利文本使用
textAlign(CENTER)后,重置为LEFT避免影响分数文本的显示位置 - 修正拼写错误:原文本中的"narrow keys"改为"arrow keys"(箭头键),符合游戏操作描述
内容的提问来源于stack exchange,提问作者red
相关产品推荐
相关产品推荐

