Implemented scren shake in the Camera2D class

This commit is contained in:
jme9
2025-03-19 18:59:13 -07:00
parent 0e60bb4207
commit 1c5f4b1b12
4 changed files with 102 additions and 23 deletions
+48 -4
View File
@@ -12,6 +12,15 @@ namespace LunaLightXMG
private float rotation;
private Vector2 position;
private Rectangle levelBounds;
private readonly float camSpeed = 0.1f;
// Screen Shake
private float shakeTimeRemaining = 0f;
private float shakeMagnitudeCurrent = 0f;
private bool shaking = false;
// Util
Utilities util;
// Getters and setters
public Vector2 Position
@@ -33,11 +42,12 @@ namespace LunaLightXMG
// constructor
public Camera2D(int width, int height)
{
this.viewport = new Viewport(0, 0, width, height);
viewport = new Viewport(0, 0, width, height);
levelBounds = new Rectangle(0, 0, 320, 180); // Default
zoom = 1f;
rotation = 0f;
position = Vector2.Zero;
util = new Utilities();
}
public Matrix GetViewMatrix()
@@ -56,11 +66,45 @@ namespace LunaLightXMG
public void Follow(Vector2 targetPostion)
{
// temp code
Vector2 smoothPosition = Vector2.Lerp(position, targetPostion, 0.1f);
position = smoothPosition;
position += (targetPostion - position) * camSpeed;
if (Math.Abs(position.X - targetPostion.X) < 0.1f)
{
position.X = targetPostion.X;
}
if (Math.Abs(position.Y - targetPostion.Y) < 0.1f)
{
position.Y = targetPostion.Y;
}
ClampToBounds();
}
public void ScreenShake(float shakeTime, float shakeMagnitude)
{
shakeTimeRemaining = shakeTime;
shakeMagnitudeCurrent = shakeMagnitude;
shaking = true;
}
public void UpdateScreenShake(GameTime gameTime)
{
if (!shaking) return;
if (shakeTimeRemaining > 0)
{
float shakeX = util.ChooseFromRange(-shakeMagnitudeCurrent, shakeMagnitudeCurrent);
float shakeY = util.ChooseFromRange(-shakeMagnitudeCurrent, shakeMagnitudeCurrent);
position.X += shakeX;
position.Y += shakeY;
shakeTimeRemaining -= (float)gameTime.ElapsedGameTime.TotalSeconds;
shakeMagnitudeCurrent *= 0.9f;
}
else
{
shaking = false;
shakeTimeRemaining = 0f;
shakeMagnitudeCurrent = 0f;
}
}
private void ClampToBounds()
{