public class Player {
public Image player;
public double playerX, playerY, dx, dy, nextDirx, nextDiry;
public Object1 object;
public Rectangle playerRect = new Rectangle();
public Rectangle[] rect = new Rectangle[2];
public Player() throws SlickException {
object = new Object1();
player = new Image("Sprites/player/DOWN 0.png");
playerX = 50;
playerY = 50;
dx = 0;
dy = 0;
playerRect.setBounds((int) playerX, (int) playerY, player.getWidth(), player.getHeight());
for(int i = 0; i < object.objectMap.size(); i++) {
rect[i] = new Rectangle(object.objectMap.get(i).rect.x, object.objectMap.get(i).rect.y, object.objectMap.get(i).rect.width, object.objectMap.get(i).rect.height);
}
}
public void setXY(double x, double y) {
playerX = x;
playerY = y;
dy = 0;
dx = 0;
}
public double getX() {
return playerX;
}
public double getY() {
return playerY;
}
public void handleMoving(Input userInput) {
if (userInput.isKeyPressed(Input.KEY_LEFT)) {
dx = -5;
nextDirx = playerX - 5;
nextDiry = playerY;
playerRect.setBounds((int) nextDirx, (int) nextDiry, player.getWidth(), player.getHeight());
for(int i = 0; i < rect.length; i++) {
if (playerRect.getBounds().intersects(rect[i].getBounds())) {
setXY(getX(), getY());
} else {
setXY(getX() + dx, getY() + dy);
}
}
}
if (userInput.isKeyPressed(Input.KEY_RIGHT)) {
dx = 5;
nextDirx = playerX + 5;
nextDiry = playerY;
playerRect.setBounds((int) nextDirx, (int) nextDiry, player.getWidth(), player.getHeight());
for(int i = 0; i < rect.length; i++) {
if (playerRect.getBounds().intersects(rect[i].getBounds())) {
setXY(getX(), getY());
} else {
setXY(getX() + dx, getY() + dy);
}
}
}
if (userInput.isKeyPressed(Input.KEY_UP)) {
dy = -5;
nextDirx = playerX;
nextDiry = playerY-5;
playerRect.setBounds((int) nextDirx, (int) nextDiry, player.getWidth(), player.getHeight());
for(int i = 0; i < rect.length; i++) {
if (playerRect.getBounds().intersects(rect[i].getBounds())) {
setXY(getX(), getY());
} else {
setXY(getX() + dx, getY() + dy);
}
}
}
if (userInput.isKeyPressed(Input.KEY_DOWN)) {
dy = 5;
nextDirx = playerX;
nextDiry = playerY + 5;
playerRect.setBounds((int) nextDirx, (int) nextDiry, player.getWidth(), player.getHeight());
for(int i = 0; i < rect.length; i++) {
if (playerRect.getBounds().intersects(rect[i].getBounds())) {
setXY(getX(), getY());
} else {
setXY(getX() + dx, getY() + dy);
}
}
}
}
}
是我的代码,但它只适用于数组中等于 [0] 的矩形,这是为什么呢?
我知道数组中有对象,因为我可以从其他对象中获取所有信息
for(int i = 0; i < rect.length; i++) {
if (playerRect.getBounds().intersects(rect[i].getBounds())) {
System.out.println("You are inside the object: "+i);
setXY(getX(), getY());//Stop moving
} else {
setXY(getX() + dx, getY() + dy);//move
}
}
是我想要发生的事情,但基本上它会说我在所有对象中,但它只会在我与 rect[0] 相交时阻止我移动,而不是阻止我在所有索引中移动数组。