平台跳跃

用 CharacterBody2D 实现重力、跳跃和地面检测,平台由代码生成。

上方的编辑器正在运行这个项目。改一行代码,它就会重新加载。

用到的 Godot 类

CharacterBody2DStaticBody2DCollisionShape2D

代码

scripts/main.gd
extends Node


func _ready() -> void:
	_add_background()

	var view: Vector2 = get_viewport().get_visible_rect().size

	_add_platform(Vector2(view.x * 0.5, view.y - 30), Vector2(view.x, 60))
	_add_platform(Vector2(view.x * 0.22, view.y - 200), Vector2(260, 26))
	_add_platform(Vector2(view.x * 0.55, view.y - 330), Vector2(220, 26))
	_add_platform(Vector2(view.x * 0.82, view.y - 190), Vector2(240, 26))

	var player: CharacterBody2D = CharacterBody2D.new()
	player.set_script(Get.script('player'))
	player.position = Vector2(view.x * 0.5, view.y * 0.3)
	add_child(player)

	print('a and d to move, space or w to jump')


func _add_background() -> void:
	var background: ColorRect = ColorRect.new()
	background.color = Color('#12141a')
	add_child(background)
	background.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)


func _add_platform(center: Vector2, size: Vector2) -> void:
	var shape: RectangleShape2D = RectangleShape2D.new()
	shape.size = size

	var collision: CollisionShape2D = CollisionShape2D.new()
	collision.shape = shape

	var visual: Polygon2D = Polygon2D.new()
	visual.polygon = PackedVector2Array(
		[
			-size * 0.5,
			Vector2(size.x, -size.y) * 0.5,
			size * 0.5,
			Vector2(-size.x, size.y) * 0.5,
		]
	)
	visual.color = Color('#2a2f3d')

	var platform: StaticBody2D = StaticBody2D.new()
	platform.position = center
	platform.add_child(visual)
	platform.add_child(collision)
	add_child(platform)
scripts/player.gd
extends CharacterBody2D

const SPEED: float = 340.0
const JUMP_VELOCITY: float = -680.0
const GRAVITY: float = 1500.0
const SIZE: Vector2 = Vector2(44, 64)

var start_position: Vector2


func _ready() -> void:
	start_position = position

	var shape: RectangleShape2D = RectangleShape2D.new()
	shape.size = SIZE

	var collision: CollisionShape2D = CollisionShape2D.new()
	collision.shape = shape
	add_child(collision)

	var visual: Polygon2D = Polygon2D.new()
	visual.polygon = PackedVector2Array(
		[
			-SIZE * 0.5,
			Vector2(SIZE.x, -SIZE.y) * 0.5,
			SIZE * 0.5,
			Vector2(-SIZE.x, SIZE.y) * 0.5,
		]
	)
	visual.color = Color('#8eef97')
	add_child(visual)


func _physics_process(delta: float) -> void:
	velocity.y += GRAVITY * delta

	if is_on_floor() and (Input.is_key_pressed(KEY_SPACE) or Input.is_key_pressed(KEY_W)):
		velocity.y = JUMP_VELOCITY

	velocity.x = (float(Input.is_key_pressed(KEY_D)) - float(Input.is_key_pressed(KEY_A))) * SPEED

	move_and_slide()

	if position.y > get_viewport().get_visible_rect().size.y + 200:
		position = start_position
		velocity = Vector2.ZERO

更多物理示例