user20905443
user20905443

Reputation:

2D Player moves Jittery/Laggy in godot 4

So I'm using the PlatformerController2D script from the AssetLib for the movement of my player and when walking and jumping or pretty much moving in general the player looks really jittery. It usually happens every few seconds, the player just lags mid-way.

The code is over 300 lines so I don't think I will be able to provide it, but honestly, I think it is not the code's problem as I tried other codes too ( even the original template ) but the same thing happened.

I tried using both _process and _physics_process and tried changing the default fps in the settings to 30. Also, I tried moving "move_and_slide" separately into _physics but all that didn't help either.

I'm not sure if it has anything to do with my problem, but I'm using a pixel art character and I don't have a camera following my player.

Upvotes: 0

Views: 318

Answers (1)

M. R. M.
M. R. M.

Reputation: 653

The code below uses linear interpolation for the global_position to give a smoothing effect:

extends Sprite2D

@export var parent:Node2D
var parent_prev_position:Vector2
var parent_curr_position:Vector2

func _physics_process(_delta):
    parent_prev_position = parent_curr_position
    parent_curr_position = parent.global_position
func _process(_delta):
    var factor=Engine.get_physics_interpolation_fraction()
    self.global_position.x = parent_prev_position.x + (parent_curr_position.x - parent_prev_position.x) * factor
    self.global_position.y = parent_prev_position.y + (parent_curr_position.y - parent_prev_position.y) * factor
func _ready():
    if(!parent):
        parent=get_parent()
    
    if("global_position" in parent):
        parent_prev_position=parent.global_position
        parent_curr_position=parent.global_position
    else:
        set_process(false)
        set_physics_process(false)

Here's the scene tree:
enter image description here

if you're using AnimatedSprite2D or just about any node which inherits from Node2D you can change the extends as such:

extends <node-type-here>

# for example:
extends AnimatedSprite2D

Upvotes: 0

Related Questions