Skip to content

Instantly share code, notes, and snippets.

@belzecue
Last active August 14, 2023 18:36
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 belzecue/e0efe46947a824ac9385ec80f0d7e88b to your computer and use it in GitHub Desktop.
Save belzecue/e0efe46947a824ac9385ec80f0d7e88b to your computer and use it in GitHub Desktop.
The ONLY guaranteed solution to physics body jitter in Godot - separate your physics body from its visual representation. Works with 3D too, but smoothing is now built into Godot for 3D (not yet built in for 2D).
class_name CharRigidBody extends RigidBody2D
# Your visual representation node, e.g. Sprite
export(NodePath) var visual_body_path: NodePath
# For RigidBody tweening
var physics_body_trans_last: Transform
var physics_body_trans_current: Transform
var debug: bool = true
onready var visual_body: Sprite = get_node(visual_body_path)
func _init() -> void:
# Doing our own physics interpolation.
if Engine.get_physics_jitter_fix() != 0.0: Engine.set_physics_jitter_fix(0.0)
func _ready() -> void:
# Config physics tweening
physics_body_trans_current = self.global_transform
physics_body_trans_last = physics_body_trans_current
visual_body.set_as_toplevel(true) # Unparent visual body transform from any parent.
set_process_priority(100) # Process other nodes first.
func _physics_process(delta: float) -> void:
# Store current transform for physics body.
physics_body_trans_last = physics_body_trans_current
physics_body_trans_current = self.global_transform
func _process(delta: float) -> void:
# Interpolate movement for visual body.
visual_body.global_transform = physics_body_trans_last.interpolate_with(
physics_body_trans_current,
Engine.get_physics_interpolation_fraction()
)
@belzecue
Copy link
Author

More on the 3D implementation here: https://github.com/belzecue/godot-physics-fraction

@belzecue
Copy link
Author

belzecue commented Apr 12, 2023

Node composition would look like this:

RigidBody2D
\CollisionShape2D
\Sprite

The Sprite is your visual body/representation.

@yusufberke-py
Copy link

Hi, is this script for the sprite/visual body of the character? If so what should we code in kinematic body? Thanks for code btw..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment