所以我正在学习如何使用类,我已经用P5.JS制作了这段代码(正好有100行长!(,它只应该画三个矩形和三个圆。其中一个圆可以用箭头键移动,另外两个可以跟随那个圆移动。这是不起作用的部分:当跟随者的圆圈在正方形上移动时,应该会让他们在移动时减速。我已经尝试过了。
function setup() {
createCanvas(windowWidth, windowHeight);
noStroke();
character1 = new character(250, 200, 30, 4);
follower1 = new enemy(100, 20, 30, 2);
follower2 = new enemy(200, 20, 30, 2);
obstacle1 = new obstacle(200, 200, 100, 50, follower1.x, follower1.y, follower1.s);
obstacle2 = new obstacle(300, 300, 50, 25, follower1.x, follower1.y, follower1.s);
obstacle3 = new obstacle(200, 400, 25, 50, follower1.x, follower1.y, follower1.s);
}
function draw() {
background(0);
character1.drawCharacter();
follower1.drawEnemy();
follower2.drawEnemy();
obstacle2.drawObstacle();
obstacle1.drawObstacle();
obstacle3.drawObstacle();
}
class character {
constructor(x, y, d, s) {
this.x = x;
this.y = y;
this.d = d;
this.s = s;
}
drawCharacter() {
fill(255);
ellipse(character1.x, character1.y, character1.d);
if (keyIsDown(UP_ARROW)) {
character1.y -= character1.s;
}
if (keyIsDown(DOWN_ARROW)) {
character1.y += character1.s;
}
if (keyIsDown(LEFT_ARROW)) {
character1.x -= character1.s;
}
if (keyIsDown(RIGHT_ARROW)) {
character1.x += character1.s;
}
}
}
class enemy {
constructor(x, y, d, s) {
this.x = x;
this.y = y;
this.d = d;
this.s = s;
}
drawEnemy() {
fill(255, 0, 0);
ellipse(this.x, this.y, this.d);
if (this.x < character1.x - this.d) {
this.x += this.s;
}
if (this.x > character1.x + this.d) {
this.x -= this.s;
}
if (this.y < character1.y - this.d) {
this.y += this.s;
}
if (this.y > character1.y + this.d) {
this.y -= this.s;
}
}
}
class obstacle {
constructor(x, y, w, h, enemyX, enemyY, enemyS) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
enemyX = enemyX;
enemyY = enemyY;
enemyS = enemyS;
}
drawObstacle(enemyX, enemyY, enemyS) {
fill(255);
rectMode(CENTER);
rect(this.x, this.y, this.w, this.h);
if (
this.x - this.w / 2 - 10 < enemyX &&
this.x + this.w / 2 + 10 > enemyX &&
this.y - this.h / 2 - 10 < enemyY &&
this.y + this.h / 2 + 10 > enemyY
) {
enemyS = 0.5;
} else {
enemyS = 2.5;
}
}
}
尽量只设置一个障碍。我的猜测是:
draw调用obstacle.drawObstacle
三次,如果敌人应该被obstacle1
或obstacle2
减速,那也没关系,因为enemy.s
将被obstacle3.drawObstacle
重置
我强烈建议你的每个角色和敌人类都有一个draw
和move
方法,并将敌人如何移动的一切都放在敌人类中。也许障碍类应该有一个draw
,也许有一个由enemy.move
调用的isCollidingWith
方法。
在类中保留类的所有逻辑意味着可以更容易地执行变体。例如,也许以后你会想要一个速度慢得多但根本不受障碍物阻碍的敌人。在类中拥有所有的逻辑使得这很容易。如果你有足够多不同类型的敌人,那么把逻辑放在障碍类中很快就会变成一场噩梦。
此外,您可以有一个game
对象,它包含游戏的所有内容,包括character
、enemies
和obstacles
属性,以及调用角色、敌人和障碍物对象的相应方法的draw
和move
方法,以及清除其属性等的destroy
或quit
方法。(在某些语言中,这一点很重要,因为如果你为游戏中的每一块添加一个game
属性,它们之间就会有句柄,而且由于(在一些语言中(垃圾收集只获取没有引用的对象,它们占用内存的时间会比你想要的要长得多。(