Apress / Devel-2D-Games-Unity

Source Code for 'Developing 2D Games with Unity: Independent Game Programming with C#' by Jared Halpern
https://www.apress.com/us/book/9781484237717
Other
215 stars 53 forks source link

Chapter 8 - Ammo 'teleport' fix #18

Open gabeux opened 4 years ago

gabeux commented 4 years ago

Hello there!

I bumped into a rather rare issue while shooting - ammo would teleport instead of travelling (with the Arc class) properly. This would only happen if:

  1. An enemy had been hit
  2. Player fired again in under ~0.7ms or less

ezgif com-optimize

I've noticed that once a collision is detected on Ammo OnTriggerEnter2D, Ammo gameObject is disabled. As such, it's free to be reused by the Weapon FireAmmo, as on the SpawnAmmo method it checks the ammoPool for the first disabled Ammo object it can find for reuse. My suspicion is that since the Arc TravelArc method is ran as a Coroutine, when the Ammo is disabled through a collision, the TravelArc Coroutine is likely paused/temporarily stopped, rather than removed/destroyed/truly stopped. So it resumes with the re-enabled Ammo object alongside the new TravelArc coroutine, and the two coroutines cause erratic behavior. My knowledge and experience with Unity is too limited to know for sure when it comes to such Coroutine stuff, though.

In any case, my quick fix was to just add an extra condition on the Travel Arc while loop, to only perform the Arc animation if the object is still active. It seemed to stop the wrong behavior from happening.

PS: Although I added a few things to the project, nothing was added/removed/changed from the Weapon, Ammo and Arc code (until this change) that would affect their original behavior.