gpt4 book ai didi

javascript - 从更改数组中获取静态值

转载 作者:行者123 更新时间:2023-11-29 10:55:51 25 4
gpt4 key购买 nike

我正在使用 P5.js 和常规 javascript 创建游戏。我有坠落的物体(在一个数组中),当与鼠标碰撞时,它们会返回到屏幕顶部。

我想在碰撞的位置添加一个分数数字。我如何存储该对象的最后一个已知坐标,让得分数字在那里停留一段时间?

可以在这里看到实时原型(prototype):http://www.getelonto.space (按任意键开始游戏)

我搜索了整个互联网,但一无所获。

//The array in the setup

function setup() {
for (var i = 0; i < numberOfMeteors; i++) {
meteors[i] = {
x: random(windowWidth-100),
y: -1* random(windowHeight),

display: function(){
image(meteorimg, this.x, this.y);
},
fall: function(){
this.y += random(1,15);
}
}
}
}

//The array in the draw

function meteor() {
for (var i = 0; i < numberOfMeteors; i++) {
meteors[i].display();
meteors[i].fall();

//Mouse collision
if (meteors[i].x < (mouseX+100) && meteors[i].x > (mouseX-175) &&
meteors[i].y > (750) && meteors[i].y < (850)||
(meteors[i].x < (mouseX+50) && meteors[i].x > (mouseX-100) &&
meteors[i].y > (630) && meteors[i].y <= (750))) {

// Attempt at getting the coordinates at collision
var minScoreIndicatorX = meteors[i].x;
var minScoreIndicatorY = meteors[i].y;


//This is the score text I want to show
text("-3", minScoreIndicatorX, minScoreIndicatorY);

// Actions when collided
score-=3;
Lives = Lives-1;
meteors[i].y = -1* (random(300));
meteors[i].x = (random(windowWidth)-100);
bgY2-=10;
if (start==false) {
meteors[i].y = 0;
}
}

// Meteors returning to the top without collision
if (meteors[i].y>windowHeight) {
meteors[i].y = -1* (random(600));
meteors[i].x = (random(windowWidth)-100);
}
}
}

当我现在运行它时,文本显示为一个框架,然后转到顶部以及它链接到的 meteor 。

最佳答案

就像我在评论中解释的那样,解决方案是创建另一个全局变量 scores 并在碰撞时添加一个条目并安排删除它。在绘制阶段,只需渲染 scores 数组中的任何文本。

我用完整的 javascript 代码做了一个 fiddle here

我检查了该代码,发现第 35 行有一个小错字。它显示 var scoreTTL = 3000; 的地方应该是 var scoresTTL = 3000;(注意缺少的“s”)(更新 fiddle 以反射(reflect)它)

如果您对代码或其背后的逻辑有任何疑问,我很乐意以更详细的方式进行解释。

希望对您有所帮助!

编辑:超时丢失了一些代码(第 223 行)更改了 fiddle 链接

关于javascript - 从更改数组中获取静态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57554625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com