UPBGE camera shake / python parenting

UPBGE camera shake / python parenting

camera_shake_final_2.blend (558.7 KB)

import bge #gives you access to bge data

import math
import mathutils

from mathutils import Vector #get access to vectors

cont = bge.logic.getCurrentController() # this is the python controller brick running the script
own = cont.owner #this is the object the brick is in*
cam = own.scene.active_camera


if 'initalLocalPosition' not in cam:
    cam['initalLocalPosition'] = own.worldOrientation.inverted() @ ( cam.worldPosition - own.worldPosition) 
    #this is where the camera starts off in the world relative to the player
    cam['initalRotation']= Vector(cam.worldOrientation.to_euler()) - Vector(own.worldOrientation.to_euler())


    
mag = 1.5   
elastic = 16 



space = cont.sensors['Space']
if space.positive and 'offset' not in own:
    
    x = -mag + (bge.logic.getRandomFloat() * (2*mag))
    y = -mag + (bge.logic.getRandomFloat() * (2*mag))
    z = -mag + (bge.logic.getRandomFloat() * (2*mag))
    own['t']=0
    own['offset']=Vector([x,y,z]) 
    

newPosition = own.worldTransform @ cam['initalLocalPosition']


if 'offset' in own:
    newPosition += own['offset']*(math.sin(own['t']*elastic)*mag)
    own['offset']*=.9
    if own['offset'].magnitude<.01:
        del own['offset']
        print('finished')
        
#now we rolled our own parenting
        
cam.worldPosition = cam.worldPosition.lerp(newPosition,.9)

r = cam['initalRotation']
rot = mathutils.Euler((r.x, r.y, r.z), 'XYZ')  
cam.worldOrientation = cam.worldOrientation.lerp(own.worldOrientation @ rot.to_matrix(),.9)

here is the same example but designed to be parented to a player

a and d demonstrate feeding it a non random offset (using player Y orientation)

one can also use a weapon raycast vector to feed a offset to ‘hit’ the player

strength = 1
line = (rayStart-rayEnd).normalized()
player.children['Cube']['offset']= line*strength

camera_shake_final_with_demo_left_right.blend (566.7 KB)

May I try to convert this into a Node for Blender Game Logic Nodes (UPBGE-Compatible)? :slight_smile:

1 Like

Sure!

I would have vector, decay, and elastic as inputs

Want me to wip up a rotation offest too?

Why not, I’ll make it triggerable :+1:

camera_shake_with_rot.blend (569.3 KB)
@Iza_Zed

1 Like

camera_shake_with_rot_and_hitExample.blend (647.1 KB)

added a few things

‘Target’ so the rotation is not relative to the cube’s transforms - but any object in the scene

‘elastic’
‘mag’
‘decay’

are all properties in the object used in the system - so outside objects can set it

‘t’ is time, setting it to zero when inputting a new offset is recommended as the elastic jiggle phase is based on it