Godot Version
4.5.stable
Question
Hello,
I’m currently developing a small game with a friend to learn Godot and I’m stuck thinking how to implement something.
I’m doing a level selector where there’s a map and the player moves with left mouse clicks. Overall, it’s working almost as expected, but the thing is that I want the player not to be able to pass through certain parts of the map when travelling from one point to another. I’m attaching pictures to illustrate this:
If I click on the upper right icon (orange X), my player moves to the target position, but it exits the area and goes through the darker grey zone (blue arrow). I want him to move alongside the pink arrow.
I’m going to explain my configuration and code. It might be bad, so if it should be reworked, please tell me so.
First of all, the player is a CharacterBody2D set to Floating and it’s not using move_and_slide().
My implementation of movement is:
- WorldMap has an Area2D
- When you click inside the Area2D it makes the player move with these lines:
############## WORLD MAP ##############
func _physics_process(delta: float) -> void:
world_player._flip_movement(world_player.position.x > target_pos.x)
if world_player.position != target_pos:
world_player._start_moving(true)
world_player.position.x = move_toward(world_player.position.x, target_pos.x, MOVEMENT_SPEED * delta)
world_player.position.y = move_toward(world_player.position.y, target_pos.y, MOVEMENT_SPEED * delta)
else:
world_player._start_moving(false)
func _on_input_event(_viewport: Node, event: InputEvent, _shape_idx: int) -> void:
if event is InputEventMouseButton and event.pressed:
if event.button_index == MOUSE_BUTTON_LEFT:
moving = true
target_pos = event.position
print("target_pos is: ", target_pos)
print("Player pos is: ", world_player.position)
print("")
############## PLAYER SCRIPT ##############
func _physics_process(_delta: float) -> void:
if !moving:
player_sprite.animation = "default"
else:
player_sprite.animation = "walking"
func _start_moving(new_state: bool) -> void:
moving = new_state
func _flip_movement(new_state: bool) -> void:
player_sprite.flip_h = new_state
I believe that moving the character with “position.x/y = move_toward” is wrong, but I’m not reaching another solution. On top of that, I’m not being able to find a solution to limit the player inside the WorldMap’s Area2D.
Could you bring me some knowledge?
