Итак, я пишу простую игру в жанре Tower Defense на C++ с использованием SDL. Мои снаряды пролетают некоторое расстояние, а затем меняют направление к цели. Цель передается как ссылка на сущность при создании снаряда. Но иногда снаряды начинают лететь в сторону другого врага, даже если их цель явно мертва.
//Another file:
for (auto& e : manager.getGroup(Game::groupEnemies)) {
//.........
EntityManager::CreateProjectile(Vector2D(A0.x, A0.y), direction, 250, 3, 20, "assets/button1.png", &manager, *e);
//...........
}
//ProjectileComponent file
Entity& target;
//.........
void setAim() {
//Possible to add a mechanism so that the projectile would find a target after its death
//If the targeted enemy is still alive
if (target.isActive() == true) {
//Let the projectile fly some distance without chasing the enemy to look more natural
if (distance > 50) {
//Calculate the vertical and horizontal distances
float dxLength = tools::dx(entity->getComponent().collider, target.getComponent().collider);
float dyLength = tools::dy(entity->getComponent().collider, target.getComponent().collider);
//Define a vector with parameters of direction
Vector2D test(-dxLength, -dyLength);
//Call a normalize function that would set the modulus of vector(length a.k.a. speed in our case) to "speed" variable
test.normalize(speed);
//And change the direction of projectile to the vector pointing at the enemy
transform->velocity = test;
}
}
}
Я пытался проверить, жив ли враг, что должно было решить проблему, но это не помоглоt. Sometimes it still aims at other enemies, despite the fact that the target is dead and the function should not be called. I tried playing with the memory and passing a pointer. The problem Persisted. I tried just passing a copy, couldnне заставлю его работать. Подозреваю, что это действительно проблемы с памятью, но я не настолько хорош, чтобы в этом разобраться
for (auto e : manager.getGroup(Game::groupEnemies)) {
/...
EntityManager::CreateProjectile(Vector2D(A0.x, A0.y), direction, 250, 3, 20, "assets/button1.png", &manager, e);
//...
}
//...
Entity* target;
//...
if (target->isActive() == true) {
//Let the projectile fly some distance without chasing the enemy to look more natural
if (distance > 50) {
//Calculate the vertical and horizontal distances
float dxLength = tools::dx(entity->getComponent().collider, target->getComponent().collider);
float dyLength = tools::dy(entity->getComponent().collider, target->getComponent().collider);
//Define a vector with parameters of direction
Vector2D test(-dxLength, -dyLength);
//Call a normalize function that would set the modulus of vector(length a.k.a. speed in our case) to "speed" variable
test.normalize(speed);
//And change the direction of projectile to the vector pointing at the enemy
transform->velocity = test;
}
}
Подробнее здесь: https://stackoverflow.com/questions/781 ... ne-is-dead
Снаряды находят новую цель после смерти исходной. ⇐ C++
Программы на C++. Форум разработчиков
1710485718
Гость
Итак, я пишу простую игру в жанре Tower Defense на C++ с использованием SDL. Мои снаряды пролетают некоторое расстояние, а затем меняют направление к цели. Цель передается как ссылка на сущность при создании снаряда. Но иногда снаряды начинают лететь в сторону другого врага, даже если их цель явно мертва.
//Another file:
for (auto& e : manager.getGroup(Game::groupEnemies)) {
//.........
EntityManager::CreateProjectile(Vector2D(A0.x, A0.y), direction, 250, 3, 20, "assets/button1.png", &manager, *e);
//...........
}
//ProjectileComponent file
Entity& target;
//.........
void setAim() {
//Possible to add a mechanism so that the projectile would find a target after its death
//If the targeted enemy is still alive
if (target.isActive() == true) {
//Let the projectile fly some distance without chasing the enemy to look more natural
if (distance > 50) {
//Calculate the vertical and horizontal distances
float dxLength = tools::dx(entity->getComponent().collider, target.getComponent().collider);
float dyLength = tools::dy(entity->getComponent().collider, target.getComponent().collider);
//Define a vector with parameters of direction
Vector2D test(-dxLength, -dyLength);
//Call a normalize function that would set the modulus of vector(length a.k.a. speed in our case) to "speed" variable
test.normalize(speed);
//And change the direction of projectile to the vector pointing at the enemy
transform->velocity = test;
}
}
}
Я пытался проверить, жив ли враг, что должно было решить проблему, но это не помоглоt. Sometimes it still aims at other enemies, despite the fact that the target is dead and the function should not be called. I tried playing with the memory and passing a pointer. The problem Persisted. I tried just passing a copy, couldnне заставлю его работать. Подозреваю, что это действительно проблемы с памятью, но я не настолько хорош, чтобы в этом разобраться
for (auto e : manager.getGroup(Game::groupEnemies)) {
/...
EntityManager::CreateProjectile(Vector2D(A0.x, A0.y), direction, 250, 3, 20, "assets/button1.png", &manager, e);
//...
}
//...
Entity* target;
//...
if (target->isActive() == true) {
//Let the projectile fly some distance without chasing the enemy to look more natural
if (distance > 50) {
//Calculate the vertical and horizontal distances
float dxLength = tools::dx(entity->getComponent().collider, target->getComponent().collider);
float dyLength = tools::dy(entity->getComponent().collider, target->getComponent().collider);
//Define a vector with parameters of direction
Vector2D test(-dxLength, -dyLength);
//Call a normalize function that would set the modulus of vector(length a.k.a. speed in our case) to "speed" variable
test.normalize(speed);
//And change the direction of projectile to the vector pointing at the enemy
transform->velocity = test;
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/78165130/projectiles-find-a-new-target-after-the-original-one-is-dead[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия