Help with physics!

Godot Version

4.2.2

Question

I’m trying to get an NPC in my game to move or simulate the movement of a turtle. To do this I think I need to apply a force or an impulse in the direction I want it to move, but I’ve been reading and I haven’t found a method with which I can do this to a CharacterBody2D, am I forced to use a RigidBody2D? Any help would be greatly appreciated!

I don’t think you need to use forces for this. For a character body 2d you can set velocity then use move_and_slide() inside a _physics_process function override.

Could you share any code you have so far?

I don’t know why, but I have the idea that when I use move and slide it will either keep moving or it won’t stop fast enough, I don’t know if I can explain myself. The movement of a turtle starts when it is at rest, then it has an acceleration, it moves, until it loses its speed and falls back to rest.

You would have to manually adjust the velocity of a CharacterBody2D. If you do want physics-like behavior then a rigid body 2d will help and you can use apply_central_impulse(direction * speed) to give it a kick.

1 Like


The movement I want it to make I try to describe in that drawing, the green line represents the speed, at first it increases and then decreases, until it reaches zero. Anyway I will try to do it with the move_and_slide() method

You can control “damping” on a rigid body, but the speed will increase faster than that curve. If you want exact control I would recommend a CharacterBody2D, you could even draw this as a Curve and use sample_baked to deduce speed and multiply direction.

Something along these lines lets you draw a curve as an exported property.

extends CharacterBody2D

@export var speed_curve: Curve
@export var speed_curve_duration: float = 2.0
@export var maximum_speed: float = 200
var speed_sample_position: float = 0.0


func start_movement() -> void:
	var tween := create_tween()
	tween.tween_property(self, "speed_sample_position", 1.0, speed_curve_duration).from(0.0)


var direction: Vector2
func _physics_process(delta: float) -> void:

	if direction:
		var speed: float = speed_curve.sample_baked(speed_sample_position) * maximum_speed
		velocity = speed * direction
	else:
		velocity = velocity.move_toward(Vector2.ZERO, maximum_speed * delta)
	
	move_and_slide()
1 Like

This worked for me, it looks pretty much like what I want, thanks a lot

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.