将所有切片加载到ArrayList中。然后,您可以使用for-each循环将碰撞检测应用于您的播放器的所有磁贴。请注意,以下示例可能不会声明工作所需的所有内容,但它应该有助于您了解此碰撞检测方法的工作原理并允许您将其实现到游戏中。
Tile.java
import java.awt.Rectangle;
private int tileWidth = 32;
private int tileHeight = 32;
private int x;
private int y;
public class Tile() {
public Tile(int tx, int ty) {
x = tx * tileWidth;
y = ty * tileHeight;
}
public Rectangle getBounds() {
return new Rectangle(x, y, tileWidth, tileHeight);
}
}CheckCollision.java
import java.awt.Rectangle;
public class CheckCollision {
public boolean isColliding(Player player, Tile tile) {
Rectangle pRect = player.getBounds();
Rectangle tRect = tile.getBounds();
if(pRect.intersects(tRect)) {
return true;
} else {
return false;
}
}
}Player.java
import java.awt.Rectangle;
import java.util.ArrayList;
public class Player {
public void move(ArrayList tiles) {
y -= directionY; //falling
for(Tile t: tiles) { // for all of the Tiles in tiles, do the following
Tile next = t;
if(CheckCollision.isColliding(this, next) {
y += directionY; //stop falling
}
}
x -= dx; // move your x
for(Tile t: tiles) { // for all of the Tiles in tiles, do the following
Tile next = t;
if(CheckCollision.isColliding(this, next) {
x += directionY; //move back if collides }
}
}
public Rectangle getBounds() {
return new Rectangle(playerX, playerY, playerWidth, playerHeight);
}
}Graphics.java(绘制图块和播放器的类)
import java.awt.ActionListener;
import java.util.ArrayList;
public class Graphics extends JPanel implements ActionListener {
public ArrayList tiles = new ArrayList();
Player player = new Player();
public JPanel() {
tiles.add(new Tile(0, 0)); //adds a Tile at X:0 Y:0 to ArrayList tiles
}
@Override
public void ActionPerformed(ActionEvent e) {
player.move(tiles);
}
}
本文介绍了一种游戏开发中常见的碰撞检测方法。通过将地图切片加载到ArrayList,并利用自定义的Tile类和CheckCollision类来判断玩家与地图元素之间的碰撞。玩家类中实现了基于碰撞检测的位置调整逻辑。
755

被折叠的 条评论
为什么被折叠?



