【发布时间】:2018-12-08 14:00:04
【问题描述】:
我在使用 p5.js 为视频游戏添加生命时遇到了问题。我正在使用 youtube 上的编码火车演示的代码。我决定为我的代码添加一个计时器和生命值。
由于某种原因,生命减去 5 而不是 1。无论我在生命变量中添加什么数字,它都会减去 5。
这是我的代码:
let bird;
let pipes = [];
let score = 0;
let lives = 10;
let timer = 20;
let hits = false;
function setup() {
createCanvas(400, 600);
bird = new Bird();
pipes.push(new Pipe());
score = new Score();
}
function draw() {
background(0);
// score = score+velocity;
line(800, 150, 800, 650);
textSize(20);
text("LIVES:", 10, 20);
textSize(20);
text(lives, 80, 20)
for (let i = pipes.length-1; i >= 0; i--){
pipes[i].show();
pipes[i].update();
if (pipes[i].hits(bird)) {
print("HIT");
}
if (pipes[i].offscreen()) {
pipes.splice(i, 1);
}
}
bird.update();
bird.show();
if (frameCount % 100 == 0) {
pipes.push(new Pipe());
}
if (frameCount % 60 == 0 && timer > 0) { // if the frameCount is divisible by 60, then a second has passed. it will stop at 0
timer --;
}
if (timer == 0) {
text("You Win", width/2, height*0.7);
noLoop();
}
if (lives <= 0){
noLoop();
}
}
function keyPressed() {
if (key == ' ') {
bird.up();
}
}
function Bird() {
this.y = height/2;
this.x = 64;
this.gravity = 0.5;
this.velocity = 0;
this.lift = -19;
this.show = function() {
fill(255);
ellipse(this.x, this.y, 32, 32);
}
this.up = function() {
this.velocity += this.lift;
}
this.update = function () {
this.velocity += this.gravity;
this.velocity += 0.9;
this.y += this.velocity;
if (this.y > height) {
this.y = height;
this.velocity = 0;
}
if (this.y < 0) {
this.y = height;
this.velocity = 0;
}
}
}
function Pipe () {
this.top = random(height/2);
this.bottom = random(height/2);
this.x = width;
this.w = 17;
this.speed = 3;
this.hits = function(bird){
if(bird.y < this.top || bird.y > height - this.bottom){
if (bird.x > this.x && bird.x < this.x + this.w){
this.highlight = true;
lives = lives - 1;
return true;
}
}
this.highlight = false;
return false;
}
this.show = function() {
fill(255);
if (this.highlight) {
fill (255, 0, 0);
}
rect(this.x, 0, this.w, this.top);
rect(this.x, height-this.bottom, this.w, this.bottom);
}
this.update = function () {
this.x -= this.speed;
}
this.offscreen = function() {
if (this.x < -this.w) {
return true;
}else {
return false;
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.min.js"></script>
更新:
你好,
我添加了一个指向我正在使用的 p5js 编辑器的链接。
【问题讨论】:
-
我唯一能想到的是函数
this.hits = function(bird){...}在命中期间执行了不止一次。 -
我编辑了您的问题,使您的代码列出了一个可运行的 sn-p。您有机会提供
Score的代码吗? sn-p 抱怨它没有定义。 -
如果我们有一个可运行的 sn-p,我们将能够为您提供更好的帮助。
-
我添加了一个链接到我的项目正在运行的编辑器。我还删除了 Score,因为那是我正在处理的一些未完成的代码。
标签: javascript processing p5.js