Advertisement
Guest User

Camera2D Screen Shake Extension v1.1

a guest
Mar 5th, 2016
2,441
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1.  
  2. extends Camera2D
  3.  
  4. var _duration = 0.0
  5. var _period_in_ms = 0.0
  6. var _amplitude = 0.0
  7. var _timer = 0.0
  8. var _last_shook_timer = 0
  9. var _previous_x = 0.0
  10. var _previous_y = 0.0
  11. var _last_offset = Vector2(0, 0)
  12.  
  13.  
  14. func _ready():
  15. set_process(true)
  16.  
  17.  
  18. # Shake with decreasing intensity while there's time remaining.
  19. func _process(delta):
  20. # Only shake when there's shake time remaining.
  21. if _timer == 0:
  22. set_offset(Vector2())
  23. set_process(false)
  24. return
  25. # Only shake on certain frames.
  26. _last_shook_timer = _last_shook_timer + delta
  27. # Be mathematically correct in the face of lag; usually only happens once.
  28. while _last_shook_timer >= _period_in_ms:
  29. _last_shook_timer = _last_shook_timer - _period_in_ms
  30. # Lerp between [amplitude] and 0.0 intensity based on remaining shake time.
  31. var intensity = _amplitude * (1 - ((_duration - _timer) / _duration))
  32. # Noise calculation logic from http://jonny.morrill.me/blog/view/14
  33. var new_x = rand_range(-1.0, 1.0)
  34. var x_component = intensity * (_previous_x + (delta * (new_x - _previous_x)))
  35. var new_y = rand_range(-1.0, 1.0)
  36. var y_component = intensity * (_previous_y + (delta * (new_y - _previous_y)))
  37. _previous_x = new_x
  38. _previous_y = new_y
  39. # Track how much we've moved the offset, as opposed to other effects.
  40. var new_offset = Vector2(x_component, y_component)
  41. set_offset(get_offset() - _last_offset + new_offset)
  42. _last_offset = new_offset
  43. # Reset the offset when we're done shaking.
  44. _timer = _timer - delta
  45. if _timer <= 0:
  46. _timer = 0
  47. set_offset(get_offset() - _last_offset)
  48.  
  49.  
  50. # Kick off a new screenshake effect.
  51. func shake(duration, frequency, amplitude):
  52. # Don't interrupt current shake duration
  53. if(_timer != 0):
  54. return
  55.  
  56. # Initialize variables.
  57. _duration = duration
  58. _timer = duration
  59. _period_in_ms = 1.0 / frequency
  60. _amplitude = amplitude
  61. _previous_x = rand_range(-1.0, 1.0)
  62. _previous_y = rand_range(-1.0, 1.0)
  63. # Reset previous offset, if any.
  64. set_offset(get_offset() - _last_offset)
  65. _last_offset = Vector2(0, 0)
  66. set_process(true)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement