Rebote y fricción
Tres pelotas soltadas desde la misma altura con tres ajustes de PhysicsMaterial. El valor de bounce es toda la diferencia.
El editor de arriba está ejecutando este proyecto. Cambia una línea y se recarga.
Clases de Godot usadas
PhysicsMaterialRigidBody2DStaticBody2D
El código
scripts/main.gd
extends Node
const RADIUS: float = 34.0
const MATERIALS: Array = [
{bounce = 0.0, friction = 1.0, label = 'bounce 0.0', color = '#fc7f7f'},
{bounce = 0.5, friction = 0.5, label = 'bounce 0.5', color = '#8da5f3'},
{bounce = 0.95, friction = 0.1, label = 'bounce 0.95', color = '#8eef97'},
]
func _ready() -> void:
_add_background()
var view: Vector2 = get_viewport().get_visible_rect().size
_add_floor(Vector2(view.x * 0.5, view.y - 30), Vector2(view.x, 60))
for i in MATERIALS.size():
var entry: Dictionary = MATERIALS[i]
var at: Vector2 = Vector2(view.x * (i + 1) / (MATERIALS.size() + 1), view.y * 0.15)
_add_ball(at, entry)
_add_label(entry.label, at + Vector2(-46, -70))
print('same drop height, three PhysicsMaterial values')
func _add_ball(at: Vector2, entry: Dictionary) -> void:
var material: PhysicsMaterial = PhysicsMaterial.new()
material.bounce = entry.bounce
material.friction = entry.friction
var circle: CircleShape2D = CircleShape2D.new()
circle.radius = RADIUS
var collision: CollisionShape2D = CollisionShape2D.new()
collision.shape = circle
var ball: RigidBody2D = RigidBody2D.new()
ball.position = at
ball.physics_material_override = material
ball.add_child(_make_circle(RADIUS, Color(entry.color)))
ball.add_child(collision)
add_child(ball)
func _add_floor(center: Vector2, size: Vector2) -> void:
var material: PhysicsMaterial = PhysicsMaterial.new()
material.bounce = 0.4
var shape: RectangleShape2D = RectangleShape2D.new()
shape.size = size
var collision: CollisionShape2D = CollisionShape2D.new()
collision.shape = shape
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('#2a2f3d')
var body: StaticBody2D = StaticBody2D.new()
body.position = center
body.physics_material_override = material
body.add_child(rect)
body.add_child(collision)
add_child(body)
func _add_label(text: String, at: Vector2) -> void:
var label: Label = Label.new()
label.text = text
label.position = at
label.add_theme_color_override('font_color', Color('#999999'))
add_child(label)
func _make_circle(radius: float, color: Color) -> Polygon2D:
var points: PackedVector2Array = PackedVector2Array()
for i in 24:
points.append(Vector2(cos(TAU * i / 24.0), sin(TAU * i / 24.0)) * radius)
var circle: Polygon2D = Polygon2D.new()
circle.polygon = points
circle.color = color
return circle
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)