![]() |
Attention | Topic was automatically imported from the old Question2Answer platform. |
![]() |
Asked By | trizotti |
I’m currently using a CharacterBody2D with a Camera2D that follows the Player around (the player is always shown at the center of the screen).
I successfully implemented the click and move logic, but I can’t make the player stop at the click destination.
How to do that?
Here is my code:
extends CharacterBody2D
MOVEMENT VARIABLES
@export var MAX_SPEED = 80
@export var ACCELERATION = 1500
@export var FRICTION = 1200
@onready var axis = Vector2.ZERO
ANIMATION VARIABLES
@onready var animations = $AnimationPlayer
func _physics_process(delta):
update_animation()
move(delta)
func update_animation():
if velocity == Vector2.ZERO:
animations.play(“idle”)
else:
var direction = get_direction(axis.normalized())
animations.play(“walk” + direction)
func move(delta):
if axis == Vector2.ZERO:
apply_friction(FRICTION * delta)
else:
apply_movement(axis * ACCELERATION * delta)
move_and_slide()
func apply_friction(amount):
if velocity.length() > amount:
velocity -= velocity.normalized() * amount
else:
velocity = Vector2.ZERO
func apply_movement(accel):
velocity += accel
velocity = velocity.limit_length(MAX_SPEED)
func get_direction(normalized_vec):
var directions = [“Up”, “Down”, “Left”, “Right”]
var dot_products = [normalized_vec.dot(Vector2.UP), normalized_vec.dot(Vector2.DOWN), normalized_vec.dot(Vector2.LEFT), normalized_vec.dot(Vector2.RIGHT)]
var max_index = 0
for i in range(1, 4):
if dot_products[i] > dot_products[max_index]:
max_index = i
return directions[max_index]
func _unhandled_input(event):
if event is InputEventMouseButton:
var target_position = event.position
var viewport_size = get_viewport_rect().size
var center = viewport_size / 2
axis = (target_position - center).normalized()