Dartboard prototype with working raycast

This commit is contained in:
Johan Sandoval
2026-06-30 19:18:45 -05:00
parent b3836e266f
commit a237d0c887
55 changed files with 1409 additions and 0 deletions
+156
View File
@@ -0,0 +1,156 @@
extends Control
# DropCatcher.gd (manual-drag version)
# No longer uses Godot's built-in _drop_data. Instead it exposes
# paint_at_screen_pos(), which the trapezoid calls on release.
# This Control no longer needs to catch mouse events at all, so it can be
# tiny/invisible — but keep it in the tree so it can reach the camera & board.
@export var camera: Camera3D
@export var main: Node # the ROOT node (DartboardProto)
const RAY_LENGTH := 1000.0
var dartboard: MeshInstance3D
# Standard dartboard number sequence, clockwise starting from the TOP (12 o'clock).
const DART_NUMBERS := [20, 1, 18, 4, 13, 6, 10, 15, 2, 17,
3, 19, 7, 16, 8, 11, 14, 9, 12, 5]
# Calibration: rotate which sector counts as "top". If the wrong number gets
# hit, bump this by 1 until it lines up. Range 0-19.
@export var sector_offset := 0
# If your board's numbers go counter-clockwise in 3D, flip this.
@export var reverse_direction := false
# --- Radial band boundaries (fractions of outer radius, 0=center 1=rim) ---
# Tune these in the Inspector by reading the norm= prints for each ring.
@export var bull_inner_max := 0.04 # <= this = inner bull (50)
@export var bull_outer_max := 0.09 # <= this = outer bull (25)
@export var inner_max := 0.45 # <= this = inner single
@export var triple_max := 0.55 # <= this = triple ring
@export var outer_max := 0.80 # <= this = outer single; above = double
# Stores which modifier is applied to each surface index: { surface_index: Modifier }
var applied_modifiers: Dictionary = {}
func _ready() -> void:
# Don't block mouse input; the trapezoids handle their own dragging.
mouse_filter = Control.MOUSE_FILTER_IGNORE
print("DropCatcher ready. camera=", camera, " main=", main)
func _get_board() -> MeshInstance3D:
if dartboard == null and main != null and "dartboard" in main:
dartboard = main.dartboard
return dartboard
# Public: try to apply a modifier (paint its texture + store its rule) at a
# screen position. Returns true if it hit the board, false if it missed.
func apply_modifier_at_screen_pos(screen_pos: Vector2, modifier: Resource) -> bool:
var board := _get_board()
if board == null:
push_error("DropCatcher: no dartboard mesh (is 'main' set?).")
return false
if camera == null:
push_error("DropCatcher: camera export not set.")
return false
if modifier == null:
return false
var ray_origin := camera.project_ray_origin(screen_pos)
var ray_dir := camera.project_ray_normal(screen_pos)
var ray_end := ray_origin + ray_dir * RAY_LENGTH
var space_state := get_viewport().world_3d.direct_space_state
var query := PhysicsRayQueryParameters3D.create(ray_origin, ray_end)
query.collide_with_areas = false
query.collide_with_bodies = true
var result := space_state.intersect_ray(query)
if result.is_empty():
print(" drop missed the board")
return false
var surface_index := _surface_from_hit(result, board)
if surface_index < 0:
return false
_paint_surface(board, surface_index, modifier.texture)
applied_modifiers[surface_index] = modifier # remember the scoring rule
print(" applied '", modifier.id, "' to surface ", surface_index)
return true
# Call this when a dart lands on a surface to get the modified score.
func score_for_surface(surface_index: int, base_value: int) -> int:
if applied_modifiers.has(surface_index):
return applied_modifiers[surface_index].apply_score(base_value)
return base_value
func _surface_from_hit(result: Dictionary, board: MeshInstance3D) -> int:
var hit_point: Vector3 = result.get("position", Vector3.ZERO)
var local := board.to_local(hit_point)
var aabb := board.get_aabb()
var center := aabb.position + aabb.size * 0.5
# Board disc lies in the X/Y plane (thin on Z). Measure radius/angle in X/Y.
var dx := local.x - center.x
var dy := local.y - center.y
var radius := Vector2(dx, dy).length()
var outer_radius : float = max(aabb.size.x, aabb.size.y) * 0.5
var norm := radius / outer_radius if outer_radius > 0.0 else 0.0
print(" local=", local, " dx=", "%.3f" % dx, " dy=", "%.3f" % dy, " norm=", "%.3f" % norm)
# --- RADIAL BAND ---
# These thresholds are fractions of the outer radius. TUNE to match your art:
# the real proportions of a dartboard, from center outward.
var seg_name := ""
if norm <= bull_inner_max:
seg_name = "bull_inner" # inner bull (50)
elif norm <= bull_outer_max:
seg_name = "bull_outer" # outer bull (25)
elif norm > 1.0:
print(" outside board")
return -1
else:
# --- ANGULAR SECTOR ---
# atan2 gives angle of the hit point. We map it to one of 20 sectors,
# then index into the dartboard number sequence.
var angle := atan2(dx, dy) # -PI..PI, 0 = straight up (+y = top)
# Convert to 0..1 going clockwise from top. Adjust the rotation so 0 = top.
var t := angle / (2.0 * PI)
t = fposmod(t, 1.0)
if reverse_direction:
t = 1.0 - t
var sector_index := int(floor(t * 20.0 + 0.5)) % 20
sector_index = (sector_index + sector_offset) % 20
var number : int = DART_NUMBERS[sector_index]
# Which ring band within the sector.
var band := ""
if norm <= inner_max:
band = "inner" # inner single
elif norm <= triple_max:
band = "triple" # triple ring
elif norm <= outer_max:
band = "outer" # outer single
else:
band = "double" # double ring
seg_name = "seg_%d_%s" % [number, band]
print(" norm=", "%.3f" % norm, " -> ", seg_name)
return _index_of_surface_named(board, seg_name)
func _index_of_surface_named(board: MeshInstance3D, target_name: String) -> int:
var mesh := board.mesh
for i in mesh.get_surface_count():
var mat := mesh.surface_get_material(i)
if mat and mat.resource_name == target_name:
return i
return -1
func _paint_surface(board: MeshInstance3D, surface_index: int, tex: Texture2D) -> void:
# Always build a fresh StandardMaterial3D so the texture shows as an IMAGE,
# not tinted by the old base color. If the segment looks like a flat color
# instead of the pattern, the mesh is missing proper UVs on that face.
var new_mat := StandardMaterial3D.new()
new_mat.albedo_color = Color.WHITE # white so texture isn't tinted
new_mat.albedo_texture = tex
new_mat.texture_filter = BaseMaterial3D.TEXTURE_FILTER_LINEAR
new_mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
board.set_surface_override_material(surface_index, new_mat)
+1
View File
@@ -0,0 +1 @@
uid://x5kcjofb5pek
+61
View File
@@ -0,0 +1,61 @@
extends Node3D
# Attach to the ROOT node (DartboardProto).
# Leave `dartboard_root` empty to auto-search, or drag the glb node in.
@export var dartboard_root: Node
var dartboard: MeshInstance3D
func _ready() -> void:
dartboard = _find_mesh_instance(dartboard_root if dartboard_root else self)
if dartboard == null:
push_error("Could not find a MeshInstance3D. Check that the glb is in the scene.")
return
print("Found dartboard mesh node: ", dartboard.name)
_print_surfaces()
_ensure_collision()
func _find_mesh_instance(node: Node) -> MeshInstance3D:
if node is MeshInstance3D and node.mesh != null:
return node
for child in node.get_children():
var found := _find_mesh_instance(child)
if found:
return found
return null
func _print_surfaces() -> void:
var mesh := dartboard.mesh
print("=== Dartboard surfaces ===")
for i in mesh.get_surface_count():
var mat := mesh.surface_get_material(i)
var mat_name := mat.resource_name if mat else "(no material)"
print("Surface ", i, " material name: '", mat_name, "'")
print("==========================")
var aabb := dartboard.get_aabb()
print("Board local size (x,y,z): ", aabb.size)
# CHEAP collision: one box that matches the board's bounding box.
# This replaces create_trimesh_collision(), which was making it run at ~3 FPS
# because it built a collision triangle for every face of the board.
func _ensure_collision() -> void:
# Remove any existing auto-added body so we don't stack shapes on re-runs.
for child in dartboard.get_children():
if child is StaticBody3D and child.name == "AutoBoardBody":
child.queue_free()
var body := StaticBody3D.new()
body.name = "AutoBoardBody"
var col := CollisionShape3D.new()
var box := BoxShape3D.new()
# Match the mesh's bounding box. Use the AABB size directly as the box size.
var aabb := dartboard.get_aabb()
box.size = aabb.size
col.shape = box
# Center the box on the mesh's bounding-box center (not always the origin).
col.position = aabb.position + aabb.size * 0.5
body.add_child(col)
dartboard.add_child(body)
print("Created cheap box collision for the dartboard.")
+1
View File
@@ -0,0 +1 @@
uid://d1i0lhibtflvq
+40
View File
@@ -0,0 +1,40 @@
extends Resource
class_name Modifier
# One modifier definition: title + description + texture + scoring rule.
# Create instances of this as .tres files in the editor (right-click in
# FileSystem -> New Resource -> Modifier), OR build them in code in the catalog.
#
# Because a texture always maps to the same modifier, the texture lives HERE.
# A stable unique id (e.g. "stars_x5"). Useful for saving which modifiers are
# applied to which segments, and for lookups. Keep it unique across the catalog.
@export var id: String = ""
# Shown to the player when offered the piece.
@export var title: String = ""
@export_multiline var description: String = ""
# The texture painted onto the segment when this modifier is applied.
@export var texture: Texture2D
# --- Scoring rule ---
# Simple, data-only rules cover most cases without writing code per modifier.
# value = (base_value * mult + add) for the affected segment.
@export var score_mult: float = 1.0
@export var score_add: int = 0
# Optional: rarity weight for random selection (higher = more common).
@export var weight: float = 1.0
# Apply this modifier's rule to a segment's base value.
func apply_score(base_value: int) -> int:
return int(round(base_value * score_mult)) + score_add
# A short human-readable summary of the effect, for tooltips/UI.
func effect_text() -> String:
var parts: Array[String] = []
if score_mult != 1.0:
parts.append("x%s" % str(score_mult))
if score_add != 0:
parts.append(("+%d" % score_add) if score_add > 0 else str(score_add))
return " ".join(parts) if parts.size() > 0 else "no change"
+1
View File
@@ -0,0 +1 @@
uid://duh0lxb7gdimr
+84
View File
@@ -0,0 +1,84 @@
extends Node
# ModifierCatalog.gd
# Holds the master list of every modifier in the game and picks random sets
# for each round. Register this as an AUTOLOAD (Project > Project Settings >
# Autoload) with the name "ModifierCatalog" so any script can reach it globally.
#
# Two ways to fill the catalog:
# A) Drop .tres Modifier files into res://Modifiers/ and they auto-load (below).
# B) Build them in code in _register_builtins() for quick prototyping.
var modifiers: Array[Modifier] = []
var _by_id: Dictionary = {} # id -> Modifier, for fast lookup
func _ready() -> void:
_load_from_folder("res://Modifiers/")
if modifiers.is_empty():
# Fallback so the prototype works before you author .tres files.
_register_builtins()
_reindex()
print("ModifierCatalog loaded ", modifiers.size(), " modifiers.")
# Load every .tres Modifier resource from a folder.
func _load_from_folder(path: String) -> void:
var dir := DirAccess.open(path)
if dir == null:
return
dir.list_dir_begin()
var fname := dir.get_next()
while fname != "":
if not dir.current_is_dir() and fname.ends_with(".tres"):
var res := load(path + fname)
if res is Modifier:
modifiers.append(res)
fname = dir.get_next()
dir.list_dir_end()
# Quick code-defined modifiers for prototyping. Replace texture paths with yours.
func _register_builtins() -> void:
modifiers.append(_make("stars_x5", "Stars", "Multiplies this segment's value by 5.",
"res://Models/Dartboard/Dartboard-Proto_Red.png", 5.0, 0))
modifiers.append(_make("double", "Double", "Doubles this segment's value.",
"res://Models/Dartboard/Dartboard-Proto_Green.png", 2.0, 0))
modifiers.append(_make("plus10", "Bonus +10", "Adds 10 points to this segment.",
"res://Models/Dartboard/Dartboard-Proto_Cork.png", 1.0, 10))
func _make(id: String, title: String, desc: String, tex_path: String,
mult: float, add: int) -> Modifier:
var m := Modifier.new()
m.id = id
m.title = title
m.description = desc
m.texture = load(tex_path)
m.score_mult = mult
m.score_add = add
return m
func _reindex() -> void:
_by_id.clear()
for m in modifiers:
_by_id[m.id] = m
func get_by_id(id: String) -> Modifier:
return _by_id.get(id)
# Pick `count` distinct random modifiers, respecting weight. Returns an Array.
func pick_random(count: int) -> Array[Modifier]:
var pool := modifiers.duplicate()
var chosen: Array[Modifier] = []
count = min(count, pool.size())
for _i in count:
var total := 0.0
for m in pool:
total += max(m.weight, 0.0001)
var r := randf() * total
var acc := 0.0
var picked_index := 0
for j in pool.size():
acc += max(pool[j].weight, 0.0001)
if r <= acc:
picked_index = j
break
chosen.append(pool[picked_index])
pool.remove_at(picked_index) # distinct: don't pick the same one twice
return chosen
+1
View File
@@ -0,0 +1 @@
uid://btm4dwci50xmu
+69
View File
@@ -0,0 +1,69 @@
extends Control
# ModifierTray.gd (catalog-driven)
# Each round, asks ModifierCatalog for 3 random modifiers and spawns a draggable
# trapezoid for each at the bottom-center. Dropping one onto the board applies it
# and consumes the round's pieces.
@export var drop_catcher: Control
@export var pieces_per_round := 3
@export var piece_size := Vector2(90, 110)
@export var spacing := 24.0
@export var bottom_margin := 30.0
const TrapezoidSwatch := preload("res://Scripts/TrapezoidSwatch.gd")
var _pieces: Array[Control] = []
func _ready() -> void:
mouse_filter = Control.MOUSE_FILTER_IGNORE
spawn_round()
# Offer a fresh set of random modifier pieces for a new round.
func spawn_round() -> void:
_clear_pieces()
# ModifierCatalog is an autoload singleton (set it up in Project Settings).
var choices: Array = ModifierCatalog.pick_random(pieces_per_round)
if choices.is_empty():
push_warning("ModifierTray: catalog returned no modifiers.")
return
for mod in choices:
var piece := Control.new()
piece.set_script(TrapezoidSwatch)
piece.custom_minimum_size = piece_size
piece.size = piece_size
piece.modifier = mod # carries the WHOLE modifier
piece.paint_texture = mod.texture # convenience for drawing
piece.drop_catcher = drop_catcher
piece.tray = self
add_child(piece)
_pieces.append(piece)
_layout_pieces()
func _layout_pieces() -> void:
var count := _pieces.size()
if count == 0:
return
var total_w := count * piece_size.x + (count - 1) * spacing
var screen := get_viewport_rect().size
var start_x := (screen.x - total_w) * 0.5
var y := screen.y - piece_size.y - bottom_margin
for i in count:
_pieces[i].position = Vector2(start_x + i * (piece_size.x + spacing), y)
# Called by a piece when successfully used: remove the whole set.
func consume() -> void:
_clear_pieces()
func _clear_pieces() -> void:
for p in _pieces:
if is_instance_valid(p):
p.queue_free()
_pieces.clear()
# TESTING ONLY: press SPACE to roll a new round of pieces.
func _unhandled_input(event: InputEvent) -> void:
if event is InputEventKey and event.pressed and event.keycode == KEY_SPACE:
spawn_round()
+1
View File
@@ -0,0 +1 @@
uid://dnek55fao0l72
+97
View File
@@ -0,0 +1,97 @@
extends Control
# TrapezoidSwatch.gd (manual-drag version)
# The trapezoid node ITSELF follows the cursor while dragging (no ghost).
# On release over the board, it tells DropCatcher to paint the hit segment,
# then asks the tray to consume the round's modifiers.
@export var paint_texture: Texture2D:
set(value):
paint_texture = value
queue_redraw()
@export_range(0.0, 1.0) var top_width_ratio := 0.55
# Set by the tray when it spawns this piece.
var drop_catcher: Control # the DropCatcher node (does the 3D raycast+paint)
var tray: Node # the ModifierTray (so we can consume on use)
# The full modifier this piece carries (texture + title + scoring rule).
var modifier: Resource
var _dragging := false
var _home_position := Vector2.ZERO # where it sits in the tray
var _drag_offset := Vector2.ZERO # cursor-to-corner offset so it doesn't snap
func _ready() -> void:
mouse_filter = Control.MOUSE_FILTER_STOP
if custom_minimum_size == Vector2.ZERO:
custom_minimum_size = Vector2(90, 110)
size = custom_minimum_size
func _draw() -> void:
var w := size.x
var h := size.y
var inset := w * (1.0 - top_width_ratio) * 0.5
var points := PackedVector2Array([
Vector2(inset, 0), Vector2(w - inset, 0),
Vector2(w, h), Vector2(0, h),
])
if paint_texture != null:
var uvs := PackedVector2Array([
Vector2(inset / w, 0), Vector2((w - inset) / w, 0),
Vector2(1, 1), Vector2(0, 1),
])
draw_polygon(points, PackedColorArray([Color.WHITE, Color.WHITE, Color.WHITE, Color.WHITE]), uvs, paint_texture)
else:
draw_colored_polygon(points, Color(0.8, 0.8, 0.8))
var outline := points
outline.append(points[0])
draw_polyline(outline, Color(0, 0, 0, 0.6), 2.0)
func _gui_input(event: InputEvent) -> void:
if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT:
if event.pressed:
_start_drag()
else:
_end_drag()
func _start_drag() -> void:
_dragging = true
_home_position = global_position
_drag_offset = global_position - get_global_mouse_position()
# top_level lets us move by global_position freely, ignoring the container
# layout, WITHOUT reparenting (reparenting mid-drag breaks the release event).
top_level = true
z_index = 100 # float above everything during drag
modulate.a = 0.85
func _end_drag() -> void:
if not _dragging:
return
_dragging = false
modulate.a = 1.0
z_index = 0
# Ask the DropCatcher to try painting wherever we released.
var painted := false
print("PIECE released. drop_catcher=", drop_catcher, " modifier=", modifier)
if drop_catcher == null:
push_error("Piece has no drop_catcher reference! (tray export not set?)")
elif not drop_catcher.has_method("apply_modifier_at_screen_pos"):
push_error("drop_catcher has no apply_modifier_at_screen_pos method.")
else:
painted = drop_catcher.apply_modifier_at_screen_pos(get_global_mouse_position(), modifier)
if painted:
# Used successfully: consume this round's modifier choices.
if tray and tray.has_method("consume"):
tray.consume()
else:
queue_free()
else:
# Missed the board: snap back home.
top_level = false
global_position = _home_position
func _process(_delta: float) -> void:
if _dragging:
global_position = get_global_mouse_position() + _drag_offset
+1
View File
@@ -0,0 +1 @@
uid://d0cdxnymxd6bs