Tiled有java版本吗_使用TILED映射的Java碰撞检测

本文介绍了一种游戏开发中常见的碰撞检测方法。通过将地图切片加载到ArrayList,并利用自定义的Tile类和CheckCollision类来判断玩家与地图元素之间的碰撞。玩家类中实现了基于碰撞检测的位置调整逻辑。

将所有切片加载到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);

}

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值