Invalid operands 'Nil' and 'int' in operator '>' on get_axis assignment

Godot Version

4.3

Question

I’m following a very basic tutorial to begin learning Godot 4.3 2d games. I am not a fluent programmer so my google searches and reading/tested updates haven’t fixed the issue.

I have a basic player script that is erroring out on the player run function call at the very start of the game.

For some reason, the ternary operator in the player_run function is returning null, I guess when the player_run method is initialized? I thought get_axis always returned a value between -1 and 1, with zero meaning nothing is being pressed. I’m missing something easy here but my brain isn’t catching it. if you need the entire code, i can add it in replies.

I think it has something to do with the var direction variable being scoped to the functions and not being passed in the args and not being given a default value but my brain hasn’t really connected these dots yet.

Is anyone able to help me understand this better?

func player_run(delta: float):
	var direction = input_movement()
	
	if direction:
		velocity.x = direction * speed
	else:
		velocity.x = move_toward(velocity.x, 0, speed)
		
	if direction != 0:
		current_state = State.Run
		animated_sprite_2d.flip_h = false if direction > 0 else true
		#above is erroring out on load

func input_movement():
	 var direction = Input.get_axis("move_left", "move_right")

Firstly, you’re not returning anything from your input_movement() function, thus making the code not work, should be fixable by doing:

func input_movement():
	 return Input.get_axis("move_left", "move_right")

and also note on how you are defining variables,
You define each variable in the function, thus it only exists inside that function and never outside of it. You can define the variable outside the functions to make it accesible anywhere.

Though in your case it is just as simple as replacing your input_movement() function with what i sent.

If you have further questions, dont hesitate to ask! We are all here to help each other :3

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.