官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 凌云县| 富川| 古蔺县| 克什克腾旗| 呈贡县| 革吉县| 岳普湖县| 江都市| 阜城县| 阿拉尔市| 皋兰县| 义马市| 阿巴嘎旗| 宝坻区| 时尚| 东明县| 松桃| 从化市| 衡水市| 安龙县| 虹口区| 泸水县| 赤城县| 射阳县| 夏邑县| 钟祥市| 安国市| 丹阳市| 东海县| 开江县| 郓城县| 舒城县| 鹿邑县| 濮阳市| 紫金县| 嘉禾县| 巢湖市| 东山县| 霍州市| 密云县| 中阳县|