Снаряды находят новую цель после смерти исходной.C++

Программы на C++. Форум разработчиков
Ответить Пред. темаСлед. тема
Гость
 Снаряды находят новую цель после смерти исходной.

Сообщение Гость »

Итак, я пишу простую игру в жанре 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
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Мои снаряды бьют, но не правильно [дублировать]
    Anonymous » » в форуме Python
    0 Ответы
    4 Просмотры
    Последнее сообщение Anonymous
  • Kotlin/Android Collectors/ Observers не находят никаких изменений за пределами класса
    Anonymous » » в форуме Android
    0 Ответы
    32 Просмотры
    Последнее сообщение Anonymous
  • Панды группируются и находят разницу между максимальным и минимальным
    Anonymous » » в форуме Python
    0 Ответы
    33 Просмотры
    Последнее сообщение Anonymous
  • Мой XAML и С# больше не находят друг друга
    Anonymous » » в форуме C#
    0 Ответы
    16 Просмотры
    Последнее сообщение Anonymous
  • Панды находят повторяющиеся пары между двумя столбцами данных
    Anonymous » » в форуме Python
    0 Ответы
    10 Просмотры
    Последнее сообщение Anonymous

Вернуться в «C++»