Godot Version 4
Character movement conflicts with the clamp function.
I am following along and going through the process of making the Dodge the Creeps game. Following this video to be more precise: https://www.youtube.com/watch?v=WEt2JHEe-do
So far I have made the player character move, and this part works fine.
----
extends Area2D
@export var speed = 400 # How fast the player will move (pixels/sec).
var screen_size = Vector2.ZERO
func _ready():
screen_size = get_viewport_rect().size
print(screen_size)
func _process(delta):
var direction = Vector2.ZERO
if Input.is_action_pressed("move_right"):
direction.x += 1
if Input.is_action_pressed("move_left"):
direction.x -= 1
if Input.is_action_pressed("move_down"):
direction.y += 1
if Input.is_action_pressed("move_up"):
direction.y -= 1
position += direction * speed * delta
However, after I add the clamp function, the character responds only to the up and down buttons, and move diagonally (between NW and SE).
position.x = clamp(position.x, 0, screen_size.x)
position.x = clamp(position.y, 0, screen_size.y)
I did, in fact get the clamp function to work at my first try, but after adding animation...
# if direction.length() > 0:
# direction = direction.normalized()
# $AnimatedSprite2D.play()
# else:
# $AnimatedSprite2D.stop()
...ended up with this problem. Also, the animation did work, for all directions. But the character only responded to up and down commands and moving diagonally between NW and SE. When I pressed the left or right key, the character animations worked, but it was not moving.
I am sure the solution is very simple, but I can not figure it out on my own, at least not at the moment. Why would it behave this way? I would appreciate any and all help. :)
Figured it out. I had written position.x on the second clamp row. Should have been position.y. 
1 Like