Skip to content

Instantly share code, notes, and snippets.

@CGArtPython
Created November 18, 2024 05:52
Show Gist options
  • Save CGArtPython/14a349d8db992c964aac5e1e86c26978 to your computer and use it in GitHub Desktop.
Save CGArtPython/14a349d8db992c964aac5e1e86c26978 to your computer and use it in GitHub Desktop.
[Blender Python] Shows how the frame_change_post works (video explanation https://www.skool.com/cgpython/making-deformers?p=5f59f1ff)
import bpy
import bmesh
import mathutils
# Dictionary to store previous object positions and velocities
prev_positions = {}
velocities = {}
velocity_decay = 0.90 # Reduce velocity by 10% each iteration
def update_mesh_inertia(scene):
obj = bpy.context.active_object
if not obj or obj.type != 'MESH':
return
# Get the current location of the object
current_pos = obj.location.copy()
# Get the previous position from the dictionary
prev_pos = prev_positions.get(obj.name, current_pos)
# Calculate the velocity vector
velocity = current_pos - prev_pos
speed = velocity.length
# Store the current position for the next frame
prev_positions[obj.name] = current_pos
# If the object is moving, update its velocity
if speed > 0:
velocities[obj.name] = velocity
else:
# Decay the velocity if the object has stopped moving
if obj.name in velocities:
velocities[obj.name] *= velocity_decay
# Get the current velocity (after possible decay)
current_velocity = velocities.get(obj.name, mathutils.Vector((0, 0, 0)))
print(f"current_velocity {current_velocity.length}")
# Stop updating if the velocity is close to zero
if current_velocity.length < 0.001:
return
mesh = obj.data
bm = bmesh.new()
bm.from_mesh(mesh)
for vert in bm.verts:
offset = current_velocity
vert.co += offset
# Update the mesh with the modified vertex positions
bm.to_mesh(mesh)
bm.free()
# Register the function to run on every frame change
bpy.app.handlers.frame_change_post.clear()
bpy.app.handlers.frame_change_post.append(update_mesh_inertia)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment