单向平台
从下面可以穿过蓝色平台,从上面则能落在上面。一个属性就搞定了全部。
上方的编辑器正在运行这个项目。改一行代码,它就会重新加载。
用到的 Godot 类
CharacterBody2DCollisionShape2DStaticBody2D
代码
scripts/main.gd
extends Node
const SPEED: float = 320.0
const JUMP_VELOCITY: float = -900.0
const GRAVITY: float = 1600.0
const BODY_SIZE: Vector2 = Vector2(42, 60)
var player: CharacterBody2D
var start: Vector2
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), false)
_add_platform(Vector2(view.x * 0.5, view.y - 220), Vector2(340, 22), true)
_add_platform(Vector2(view.x * 0.5, view.y - 400), Vector2(240, 22), true)
start = Vector2(view.x * 0.5, view.y - 120)
player = _add_player(start)
print('a and d to move, space to jump, the thin platforms let you pass from below')
func _physics_process(delta: float) -> void:
player.velocity.y += GRAVITY * delta
if player.is_on_floor() and Input.is_key_pressed(KEY_SPACE):
player.velocity.y = JUMP_VELOCITY
player.velocity.x = (float(Input.is_key_pressed(KEY_D)) - float(Input.is_key_pressed(KEY_A))) * SPEED
player.move_and_slide()
if player.position.y > get_viewport().get_visible_rect().size.y + 200:
player.position = start
player.velocity = Vector2.ZERO
func _add_player(at: Vector2) -> CharacterBody2D:
var shape: RectangleShape2D = RectangleShape2D.new()
shape.size = BODY_SIZE
var collision: CollisionShape2D = CollisionShape2D.new()
collision.shape = shape
var body: CharacterBody2D = CharacterBody2D.new()
body.position = at
body.add_child(_make_rect(BODY_SIZE, Color('#8eef97')))
body.add_child(collision)
add_child(body)
return body
func _add_platform(center: Vector2, size: Vector2, one_way: bool) -> void:
var shape: RectangleShape2D = RectangleShape2D.new()
shape.size = size
var collision: CollisionShape2D = CollisionShape2D.new()
collision.shape = shape
collision.one_way_collision = one_way
var platform: StaticBody2D = StaticBody2D.new()
platform.position = center
platform.add_child(_make_rect(size, Color('#8da5f3') if one_way else Color('#2a2f3d')))
platform.add_child(collision)
add_child(platform)
func _make_rect(size: Vector2, color: Color) -> Polygon2D:
var rect: Polygon2D = Polygon2D.new()
rect.polygon = PackedVector2Array([-size * 0.5, Vector2(size.x, -size.y) * 0.5, size * 0.5, Vector2(-size.x, size.y) * 0.5])
rect.color = color
return rect
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)