Я работаю над 2D-ролевой игрой с видом сверху и столкнулся с проблемой при обнаружении столкновений. У меня есть два класса: Entity.java и CollisionManager.java.
Класс Entity содержит такие атрибуты, как скорость и BoundingBox (представленный объектом Rectangle). Прежде чем переместить объект, я вызываю метод из класса CollisionManager, чтобы проверить наличие столкновений с плитками.
Проблема в том, что когда я увеличиваю скорость объекта, столкновение обнаруживается слишком рано, за несколько пикселей до того, как объект фактически достигнет плитки.
CollisionManager.java (метод checkTile):
public void checkTile(Entity entity) {
int entityLeftWorldX = entity.worldX + entity.boundingBox.x;
int entityRightWorldX = entityLeftWorldX + entity.boundingBox.width; // Cambiato per maggiore chiarezza
int entityTopWorldY = entity.worldY + entity.boundingBox.y;
int entityBottomWorldY = entityTopWorldY + entity.boundingBox.height; // Cambiato per maggiore chiarezza
int entityLeftColumn = entityLeftWorldX / wm.TILE_SIZE;
int entityRightColumn = entityRightWorldX / wm.TILE_SIZE;
int entityTopRow = entityTopWorldY / wm.TILE_SIZE;
int entityBottomRow = entityBottomWorldY / wm.TILE_SIZE;
switch (entity.currentDirection) {
case UP -> entityTopRow = (entityTopWorldY - entity.speed) / wm.TILE_SIZE;
case DOWN -> entityBottomRow = (entityBottomWorldY + entity.speed) / wm.TILE_SIZE;
case LEFT -> entityLeftColumn = (entityLeftWorldX - entity.speed) / wm.TILE_SIZE;
case RIGHT -> entityRightColumn = (entityRightWorldX + entity.speed) / wm.TILE_SIZE;
}
int[] topTiles = {
wm.firstLayerMap.GAME_MAP[entityLeftColumn][entityTopRow],
wm.firstLayerMap.GAME_MAP[entityRightColumn][entityTopRow]
};
int[] bottomTiles = {
wm.firstLayerMap.GAME_MAP[entityLeftColumn][entityBottomRow],
wm.firstLayerMap.GAME_MAP[entityRightColumn][entityBottomRow]
};
if (isTileColliding(topTiles) || isTileColliding(bottomTiles)) {
entity.isColliding = true;
}
}
private boolean isTileColliding(int... tileNums) {
for (int tileNum : tileNums) {
if (tileNum >= 0 && isTileSolid(tileNum, wm.firstLayerMap)) {
return true;
}
}
return false;
}
private boolean isTileSolid(int tileNum, TileManager layer) {
return layer != null && layer.tileMap.get(tileNum) != null && layer.tileMap.get(tileNum).isSolid;
}
Вызов метода в Entity.java:
private void updatePosition() {
if(currentState == State.WALKING) {
isColliding = false;
cm.checkTile(this);
if(!isColliding) {
switch(currentDirection) {
case UP -> worldY -= speed;
case DOWN -> worldY += speed;
case LEFT -> worldX -= speed;
case RIGHT -> worldX += speed;
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... n-rpg-game
Проблема обнаружения столкновений со скоростью объекта в 2D-ролевой игре с видом сверху ⇐ JAVA
Программисты JAVA общаются здесь
1732086856
Anonymous
Я работаю над 2D-ролевой игрой с видом сверху и столкнулся с проблемой при обнаружении столкновений. У меня есть два класса: Entity.java и CollisionManager.java.
Класс Entity содержит такие атрибуты, как скорость и BoundingBox (представленный объектом Rectangle). Прежде чем переместить объект, я вызываю метод из класса CollisionManager, чтобы проверить наличие столкновений с плитками.
Проблема в том, что когда я увеличиваю скорость объекта, столкновение обнаруживается слишком рано, за несколько пикселей до того, как объект фактически достигнет плитки.
CollisionManager.java (метод checkTile):
public void checkTile(Entity entity) {
int entityLeftWorldX = entity.worldX + entity.boundingBox.x;
int entityRightWorldX = entityLeftWorldX + entity.boundingBox.width; // Cambiato per maggiore chiarezza
int entityTopWorldY = entity.worldY + entity.boundingBox.y;
int entityBottomWorldY = entityTopWorldY + entity.boundingBox.height; // Cambiato per maggiore chiarezza
int entityLeftColumn = entityLeftWorldX / wm.TILE_SIZE;
int entityRightColumn = entityRightWorldX / wm.TILE_SIZE;
int entityTopRow = entityTopWorldY / wm.TILE_SIZE;
int entityBottomRow = entityBottomWorldY / wm.TILE_SIZE;
switch (entity.currentDirection) {
case UP -> entityTopRow = (entityTopWorldY - entity.speed) / wm.TILE_SIZE;
case DOWN -> entityBottomRow = (entityBottomWorldY + entity.speed) / wm.TILE_SIZE;
case LEFT -> entityLeftColumn = (entityLeftWorldX - entity.speed) / wm.TILE_SIZE;
case RIGHT -> entityRightColumn = (entityRightWorldX + entity.speed) / wm.TILE_SIZE;
}
int[] topTiles = {
wm.firstLayerMap.GAME_MAP[entityLeftColumn][entityTopRow],
wm.firstLayerMap.GAME_MAP[entityRightColumn][entityTopRow]
};
int[] bottomTiles = {
wm.firstLayerMap.GAME_MAP[entityLeftColumn][entityBottomRow],
wm.firstLayerMap.GAME_MAP[entityRightColumn][entityBottomRow]
};
if (isTileColliding(topTiles) || isTileColliding(bottomTiles)) {
entity.isColliding = true;
}
}
private boolean isTileColliding(int... tileNums) {
for (int tileNum : tileNums) {
if (tileNum >= 0 && isTileSolid(tileNum, wm.firstLayerMap)) {
return true;
}
}
return false;
}
private boolean isTileSolid(int tileNum, TileManager layer) {
return layer != null && layer.tileMap.get(tileNum) != null && layer.tileMap.get(tileNum).isSolid;
}
Вызов метода в Entity.java:
private void updatePosition() {
if(currentState == State.WALKING) {
isColliding = false;
cm.checkTile(this);
if(!isColliding) {
switch(currentDirection) {
case UP -> worldY -= speed;
case DOWN -> worldY += speed;
case LEFT -> worldX -= speed;
case RIGHT -> worldX += speed;
}
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79200921/collision-detection-issue-with-entity-speed-in-2d-top-down-rpg-game[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия