Sorry for the delay, I had things to do, but I was doing a little research on the move_and_collide and test_move methods, but not enough so I decided to postpone these methods and make sure it works first with areas to have the principles of the behavior ready.
However, I have encountered several inconveniences, such as, for example, handling vector 2 in a mathematical operation that requires multiplication/division, if any of its values turns out to be a perfect 0, you will imagine that it does a strange behavior,
The second one that I fixed for the moment but I was a little dissatisfied is that instead of gaining more strength as I get closer to the object, it is the other way around that I leave you the modified code based on the basic_movement project from the documentation tutorial.
https://docs.godotengine.org/en/stable/tutorials/physics/using_character_body_2d.html
extends CharacterBody2D
var speed = 300
var last_vel : Vector2
func get_input():
var input_dir = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
velocity = input_dir * speed
return input_dir * speed
func _physics_process(_delta):
#move_and_collide(velocity * delta)
move_and_slide()
get_input()
func reject_body(BODY_POS:Vector2):
var vector_cero = Vector2(0,0)
if velocity != vector_cero:
last_vel = velocity
var dir : Vector2 = (BODY_POS - global_position)
var dis = dir * dir.normalized()
velocity = get_input() - dir.normalized() * (Vector2(100,100)/dis)
print((Vector2(100,100)/dis) )
Remember to also add an area with this code
extends Area2D
# Called when the node enters the scene tree for the first time.
func _ready():
pass # Replace with function body.
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta):
for bodies in get_overlapping_bodies():
if bodies.has_method("reject_body"):
bodies.reject_body(global_position)