Reason for this error code?

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

Error parsing expression, misplaced: else

extends Area2D

export var speed = 400
var screen_size

func _ready():
	screen_size = get_viewport_rect().size
	
func _process(delta):
	var velocity = Vector2()  # The player's movement vector.
	if Input.is_action_pressed("ui_right"):
		velocity.x += 1
	if Input.is_action_pressed("ui_left"):
		velocity.x -= 1
	if Input.is_action_pressed("ui_down"):
		velocity.y += 1
	if Input.is_action_pressed("ui_up"):
		velocity.y -= 1
	if velocity.length() > 0:
		velocity = velocity.normalized() * speed
		$AnimatedSprite.play()
	position += velocity * delta
	position.x = clamp(position.x, 0, screen_size.x)
	position.y = clamp(position.y, 0, screen_size.y)
	else:
	$AnimatedSprite.stop()

Your screenshot doesn’t work because apparently you linked to the file on your computer. People on the internet can’t (for obvious reasons) access your computer.

Rather than posting a screenshot, please post the text of the error message and copy and paste the script that is causing it. Note that when you post code here on this forum, there’s a “Code Sample” button just above that will ensure the code is formatted correctly.

kidscancode | 2021-11-26 18:37

:bust_in_silhouette: Reply From: DaddyMonster

If you highlight your code and click the curly braces symbol, it’ll format your code in a readable way.

I assume the issue is that you have something like this:

if velocity.length() > 0:
    velocity = velocity.normalized() * speed
    $AnimatedSprite.play()
    position += velocity * delta
    position.x = clamp(position.x, 0, screensize.x)
    position.y = clamp(position.y, 0, screen_size.y)
    else: # incorrectly tabbed
    $AnimatedSprite.stop()

Instead of the correct:

if velocity.length() > 0:
    velocity = velocity.normalized() * speed
    $AnimatedSprite.play()
    position += velocity * delta
    position.x = clamp(position.x, 0, screen_size.x)
    position.y = clamp(position.y, 0, screen_size.y)
else:
    $AnimatedSprite.stop()

It’s hard to be sure exactly what’s wrong because the tabbing wasn’t preserved but it’ll be something along those lines.

The else needs to be in line horizontally with its corresponding if.

func _process(delta):
    ...
    if velocity.length() > 0:
        velocity = velocity.normalized() * speed
        ...
    else:
        $AnimatedSprite.stop()

(it could be that he has it unindented like func)

timothybrentwood | 2021-11-26 20:52

Thank you both, Looking now, I do believe it to be a indenting issue. I’m still very new to all of this. It’s literally a foreign language to me.

peggels | 2021-11-27 18:57