如何解决刷新背景后,如何使在函数内运行的代码保留在画布上
我目前正在尝试制作一个以僵尸为主题的游戏,所以我创建了一个函数,用于在画布上绘制一个代表僵尸的椭圆。我无法弄清楚如何让函数运行的代码在背景刷新后保留在画布上。有人对这个问题有答案吗?
var playerI = {
x: width + 500,y: height + 300
};
void setup(){
size(1350,755);
}
//function to spawn zombies
void spawnZombie(let x,let y) {
fill(0,100,0);
ellipse(x,y,50,50);
}
void draw(){
background(0,120,0);
frameRate(60);
//player
fill(250,220,0);
ellipse(playerI.x,playerI.y,50);
//player movement
if (keypressed && key == 'w') {
playerI.y -= 1.5;
}
if (keypressed && key == 's') {
playerI.y += 1.5;
}
if (keypressed && key == 'a') {
playerI.x -= 1.5;
}
if (keypressed && key == 'd') {
playerI.x += 1.5;
}
spawnZombie(random(0,1350),random(0,755));
}
解决方法
类似于你的玩家如何拥有它的 x,y 属性,这些属性被声明一次并在 draw()
中重复使用,你需要将每个僵尸存储在内存中,否则一秒钟内你只是在随机位置重新绘制椭圆很多次.
我建议使用数组来存储所有僵尸。此外,您可能希望减少生成僵尸的频率(例如每 60 帧甚至更少),否则它会很快变得非常拥挤:)
大致如下:
var playerI = {
x:
width + 500,y:
height + 300
};
var zombies = [];
void setup() {
size(1350,755);
}
//function to spawn zombies
void spawnZombie(let x,let y) {
return {
x: x,y: y,draw(): function(){
fill(0,100,0);
ellipse(x,y,50,50);
}
}
}
void draw() {
background(0,120,0);
frameRate(60);
//player
fill(250,220,0);
ellipse(playerI.x,playerI.y,50);
//player movement
if (keyPressed && key == 'w') {
playerI.y -= 1.5;
}
if (keyPressed && key == 's') {
playerI.y += 1.5;
}
if (keyPressed && key == 'a') {
playerI.x -= 1.5;
}
if (keyPressed && key == 'd') {
playerI.x += 1.5;
}
// spawn a new zombie every once in a while and remember it
if(frameRate % 60 == 0){
zombies.push(spawnZombie(random(0,1350),random(0,755)));
}
// draw existing zombies
int numZombies = zombies.length;
for(int i = 0 ; i < numZombies; i++){
zombies[i].draw();
}
}
请注意,上面的代码没有经过测试:目的是为了说明这个想法。
如果我记得 processing.js 支持类,那么你可以这样写。不过,将处理(类 java)语法与 js 混合使用可能会令人困惑。由于 Processing.js 已于 2018 年存档,因此您可能还想查看 p5.js
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。