Skip to content

Instantly share code, notes, and snippets.

@Shilo
Last active February 9, 2024 03:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shilo/165fd1be7488d87f66c898807b242fb6 to your computer and use it in GitHub Desktop.
Save Shilo/165fd1be7488d87f66c898807b242fb6 to your computer and use it in GitHub Desktop.
Simple camera shake script in Godot 4.
using Godot;
using System;
public partial class Camera : Camera2D
{
public enum ShakeStrengthType
{
Low,
Medium,
High
}
[Export]
private float _shakeDecay = 0.8f; // How quickly the shaking stops (0-1).
[Export]
private Vector2 _shakeOffsetMax = new(100, 75); // Maximum horizontal/vertical shake in pixels.
[Export]
private float _shakeStrengthLow = 0.1f; // Max shake strength for low intensity.
[Export]
private float _shakeStrengthMed = 0.2f; // Max shake strength for medium intensity.
[Export]
private float _shakeStrengthHigh = 0.3f; // Max shake strength for high intensity.
private float _currentShakeStrength;
public static Camera Last { get; private set; }
public override void _EnterTree()
{
Last = this;
}
public static void ShakeCamera(ShakeStrengthType strengthType)
{
Last?.Shake(strengthType);
}
public void Shake(ShakeStrengthType strengthType)
{
Shake(strengthType switch
{
ShakeStrengthType.Medium => _shakeStrengthMed,
ShakeStrengthType.High => _shakeStrengthHigh,
_ => _shakeStrengthLow
});
}
public void Shake(float? strength = null)
{
strength ??= _shakeStrengthLow;
_currentShakeStrength = Mathf.Max(_currentShakeStrength, strength.Value);
}
public override void _Process(double delta)
{
if (_currentShakeStrength <= 0)
return;
_currentShakeStrength = Mathf.Max(_currentShakeStrength - _shakeDecay * (float)delta, 0);
UpdateShake();
}
private void UpdateShake()
{
float amount = Mathf.Pow(_currentShakeStrength, 2);
float x = _shakeOffsetMax.X * amount * GD.RandRange(-1, 1);
float y = _shakeOffsetMax.Y * amount * GD.RandRange(-1, 1);
Offset = new Vector2(x, y);
}
public override void _ExitTree()
{
if (Last == this)
Last = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment