kidscancode / godot_recipes

Lessons, tutorials, and guides for game development using the Godot game engine.
MIT License
240 stars 37 forks source link

2D Screen Shake potential bug #131

Open WolfgangSenff opened 1 year ago

WolfgangSenff commented 1 year ago

While using the code from the article, I ran into an issue where somewhat regularly, the thing I shake (I have genericized it to not just shake a camera, but anything with an offset), it will blow out the offset values beyond NAN. I have tracked this down to the following code, and fixing this has fixed it, but I am opening this to make sure you agree. I can assert that the bug happens most often for the y-value, which makes sense, since the majority of integers are above 1/3 the max value of the integer type. For the following code:

noise_y += 1
rotation = max_roll * amount * noise.get_noise_2d(noise.seed, noise_y)
offset.x = max_offset.x * amount * noise.get_noise_2d(noise.seed*2, noise_y)
offset.y = max_offset.y * amount * noise.get_noise_2d(noise.seed*3, noise_y)

When multiplying the seed by 2 or 3, you must ensure that noise.seed is less than half or a third (respectively) of the max value of the int type - without that, it seems like it's going above the max value of the int type and resulting in NAN when multiplied. To fix it, I simply divided the original value when it was set, like so:

func _ready():
  randomize()n
  noise.seed = randi() / 3
  noise.period = 4
  noise.octaves = 2

This should still result in a fairly randomized value, and if anyone notices the visual effect, I'd be stunned. Since this is more of a fix of exclusion, i.e. it doesn't seem to happen anymore but can't say it doesn't happen forever, I didn't want to submit a PR yet. If you feel the above fix should work, or if you don't think the bug I found is the problem, let me know!