Godot Engine Game Development Projects
上QQ阅读APP看书,第一时间看更新

Moving the Player

Next, you'll use the _process() function to define what the player will do. The _process() function is called on every frame, so you'll use it to update elements of your game that you expect to be changing often. You need the player to do three things:

  • Check for keyboard input
  • Move in the given direction
  • Play the appropriate animation

First, you need to check the inputs. For this game, you have four directional inputs to check (the four arrow keys). Input actions are defined in the project settings under the Input Map tab. In this tab, you can define custom events and assign different keys, mouse actions, or other inputs to them. By default, Godot has events assigned to the keyboard arrows, so you can use them for this project.

You can detect whether an input is pressed using Input.is_action_pressed(), which returns true if the key is held down and false if it is not. Combining the states of all four buttons will give you the resultant direction of movement. For example, if you hold right and down at the same time, the resulting velocity vector will be (1, 1). In this case, since we’re adding a horizontal and a vertical movement together, the player would move faster than if they just moved horizontally.

You can prevent that by normalizing the velocity, which means setting its length to 1, then multiplying it by the desired speed:

func get_input():
velocity = Vector2()
if Input.is_action_pressed("ui_left"):
velocity.x -= 1
if Input.is_action_pressed("ui_right"):
velocity.x += 1
if Input.is_action_pressed("ui_up"):
velocity.y -= 1
if Input.is_action_pressed("ui_down"):
velocity.y += 1
if velocity.length() > 0:
velocity = velocity.normalized() * speed

By grouping all of this code together in a get_input() function, you make it easier to change things later. For example, you could decide to change to an analog joystick or other type of controller. Call this function from _process() and then change the player's position by the resulting velocity. To prevent the player from leaving the screen, you can use the clamp() function to limit the position to a minimum and maximum value:

func _process(delta):
get_input()

position += velocity * delta
position.x = clamp(position.x, 0, screensize.x)
position.y = clamp(position.y, 0, screensize.y)

Click Play the Edited Scene (F6) and confirm that you can move the player around the screen in all directions.