我是处理的新手,一直在修改某人的代码。除了为什么我的精灵总是随机停止之外,我都明白了。我最终在看似随机的点上失去了运动。有什么帮助吗?
PImage img;
sprite player;
wall[] walls;
void setup() {
size(750, 750);
img = loadImage("sprite.png");
player = new sprite(50,300);
frameRate(60);
smooth();
walls = new wall[3];
walls[0] = new wall(250,0,40,500);
walls[1] = new wall(500,250,40,500);
walls[2] = new wall(300,200,40,500);
}
void draw() {
background(255, 255, 255);
noStroke();
player.draw();
player.move(walls);
for(int i = 0; i < walls.length; i++){
walls[i].draw();
}
}
class sprite {
float x;
float y;
sprite(float _x, float _y){
x = _x;
y = _y;
}
void draw(){
image(img,x,y);
}
void move(wall[] walls){
float possibleX = x;
float possibleY = y;
if (keyPressed==true) {
println(key);
if (key=='a') {
possibleX= possibleX - 2;
}
if (key=='d') {
possibleX = possibleX + 2;
}
if (key=='w') {
possibleY = possibleY - 2;
}
if (key=='s') {
possibleY = possibleY + 2;
}
}
boolean didCollide = false;
for(int i = 0; i < walls.length; i++){
if(possibleX > walls[i].x && possibleX < (walls[i].x + walls[i].w) && possibleY > walls[i].y && possibleY < walls[i].y + walls[i].h){
didCollide = true;
}
}
if(didCollide == false){
x = possibleX;
y = possibleY;
}
}
}
class wall {
float x;
float y;
float w;
float h;
wall(float _x, float _y, float _w, float _h){
x = _x;
y = _y;
w = _w;
h = _h;
}
void draw(){
fill(0);
rect(x,y,w,h);
}
}
问题出在你的mobile()
函数中:
void move(wall [] walls) {
...
boolean didCollide = false;
for (int i = 0; i < walls.length; i++) {
if (possibleX > walls[i].x && possibleX < (walls[i].x + walls[i].w) && ...){
didCollide = true;
}
}
if (didCollide == false) {
x = possibleX;
y = possibleY;
}
}
你在for循环中检查碰撞,这很好!但是,你永远不会解决碰撞(即将人Sprite从墙上移开,使墙不再在其可能的矩形内),因此人不能再移动,因为每次调用此函数时,didCollide最终仍然是true。
您下次可以通过添加以下代码来测试:
if (didCollide == false) {
...
} else {
println("I stopped moving.");
// could also put collision-resolving code here
}
如果你在控制台看到这一点,这意味着你撞到了墙上。
解决碰撞的问题是将精灵移动到离墙最近的边缘之间的距离,再加上一点,这样你就不会碰它了,像这样:
// If sprite to the left of the wall, i.e. went too far to the right...
float diff = walls[i].x - walls[i].w - this.x;
this.x += diff + 1.0
...
// If sprite below the wall, and essentially too high up....
float diff = walls[i].y + wall[i].h - this.y;
this.y += diff + 1.0