Android Question [Solved] LibGDX - How to Screen Shake?

wonder

Expert
Licensed User
Longtime User
Hi!

How can I shake the screen using the Camera object in LibGDX?
I'm sure the code for this must be really really simple, but I'm not really understanding how to do it, since Camera.Position is a read-only property.

The most simple shake I could come-up with was:
Code: Copy
Camera.Translate(Rnd(0, 3) - 1, Rnd(0, 3) - 1)

The screen does shake indeed, but now I have no idea how to return the Camera to its original position.
If the Position property wasn't read-only I would do it like this:
Code: Copy
Sub LG_Resize(Width As Int, Height As Int)
    'Sets the camera viewport
        Camera.Initialize
        Camera.SetToOrtho2(True, lGdx.graphics.Width, lGdx.Graphics.Height)
        CamReset = Camera.Position 'This is a global variable (lgMathVector2)
End Sub

Sub LG_Render
    ...
    If ScreenShakeActive Then
        'Shake Code Goes Here
    Else
        Camera.Position = cam.Reset 'This is illegal because Camera.Position is read-only! :(
    End If
    Camera.Update
    ...
End Sub
 
Last edited:
SOLVED!

Ok, I figured it out. :)
Turn out that, despite Camera.Position being read-only, Camera.Position.x and Camera.Position.y aren't.

This code is legal:
Code: Copy
Sub LG_Render
    ...
    If ScreenShakeActive Then
        'Shake Code Goes Here
        'For example: http://www.badlogicgames.com/forum/viewtopic.php?f=11&t=18560
    Else
        Camera.Position.x = CamReset.x
        Camera.Position.y = CamReset.y
    End If
    Camera.Update
    ...
End Sub
 
Last edited:
Upvote 0
Back
Top