2D 运动概述¶

八向移动¶

```extends KinematicBody2D

export (int) var speed = 200

var velocity = Vector2()

func get_input():
velocity = Vector2()
if Input.is_action_pressed("right"):
velocity.x += 1
if Input.is_action_pressed("left"):
velocity.x -= 1
if Input.is_action_pressed("down"):
velocity.y += 1
if Input.is_action_pressed("up"):
velocity.y -= 1
velocity = velocity.normalized() * speed

func _physics_process(delta):
get_input()
velocity = move_and_slide(velocity)
```

`get_input()` 函数中, 我们检查四个键盘事件并将它们相加以获得速度向量. 这么做的优点是两个相对的键会彼此抵消, 但是由于两个非相对方向被加在一起, 导致对角线方向移动速度更快.

旋转+移动¶

```extends KinematicBody2D

export (int) var speed = 200
export (float) var rotation_speed = 1.5

var velocity = Vector2()
var rotation_dir = 0

func get_input():
rotation_dir = 0
velocity = Vector2()
if Input.is_action_pressed("right"):
rotation_dir += 1
if Input.is_action_pressed("left"):
rotation_dir -= 1
if Input.is_action_pressed("down"):
velocity = Vector2(-speed, 0).rotated(rotation)
if Input.is_action_pressed("up"):
velocity = Vector2(speed, 0).rotated(rotation)

func _physics_process(delta):
get_input()
rotation += rotation_dir * rotation_speed * delta
velocity = move_and_slide(velocity)
```

旋转+移动（鼠标）¶

```extends KinematicBody2D

export (int) var speed = 200

var velocity = Vector2()

func get_input():
look_at(get_global_mouse_position())
velocity = Vector2()
if Input.is_action_pressed("down"):
velocity = Vector2(-speed, 0).rotated(rotation)
if Input.is_action_pressed("up"):
velocity = Vector2(speed, 0).rotated(rotation)

func _physics_process(delta):
get_input()
velocity = move_and_slide(velocity)
```

```rotation = get_global_mouse_position().angle_to_point(position)
```

点击并移动¶

```extends KinematicBody2D

export (int) var speed = 200

var velocity = Vector2()

func _input(event):
if event.is_action_pressed("click"):
target = get_global_mouse_position()

func _physics_process(delta):
velocity = position.direction_to(target) * speed
# look_at(target)
if position.distance_to(target) > 5:
velocity = move_and_slide(velocity)
```