2D Player Movement - Issues

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Vastra9X

Hi everyone! :slight_smile:

I am a total newbie to GoDot Engine, never done any coding before and never tried to make my own game before. But I thought I’d give it a try, see how it goes.

I’ve watched a bunch of videos on the YouTube channel GD Quest. Watched and followed this video “Code Your First Complete 2D Game with Godot”.

However I have problems. I have followed the code exactly, checked everything. I’m lost.

Now the problem is the movement, the W and S key aren’t doing what they should. My player moves diagonally up and down towards the corners, that’s it. Also somehow it can leave the game area at the bottom. It also flips upwards and downwards when I press the W and S keys. But I just can’t get it to walk in a straight line, up, down, left and right.

So this is my code. Note I kinda stopped around timestamp 13:00 ish, because it wasn’t working for me.
Maybe this is considered old code now and doesn’t work, I don’t know. It seems to work for others, but I don’t know what I’ve missed.

I read somewhere that vector can cause problems, but ehh yah I don’t know anything about that. I just followed the tutorial.

I hope someone can shed some light on this. :slight_smile: Any help is much appreciated!

extends Area2D

export var speed = 400.0
var screen_size = Vector2.ZERO

func _ready():
screen_size = get_viewport_rect().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

if direction.length() > 0:
	direction = direction.normalized()
	$AnimatedSprite.play()
else:
	$AnimatedSprite.stop()

position += direction * speed * delta
position.x = clamp(position.x, 0, screen_size.x)
position.y = clamp(position.x, 0, screen_size.y)

if direction.x != 0:
	$AnimatedSprite.animation = "right"
	$AnimatedSprite.flip_h = direction.x < 0
	$AnimatedSprite.flip_v = false
elif direction.y != 0:
	$AnimatedSprite.animation = "up"
	$AnimatedSprite.flip_v =direction.y > 0
:bust_in_silhouette: Reply From: exuin
position.y = clamp(position.x, 0, screen_size.y)

This line appears to be the issue. It should be:

position.y = clamp(position.y, 0, screen_size.y)

Ahh now I feel so silly, one little letter. Well one incorrect letter can make a huge difference when it comes to coding.

Thanks a lot! :smiley:

Vastra9X | 2022-01-15 17:17