summaryrefslogtreecommitdiff
path: root/stage/dice_throw/dice.gd
blob: 88fdbb8c4f5828620c9064992239da5132f56f5d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class_name Dice
extends RigidBody3D


var previous_position: Vector3
var previous_rotation: Vector3
var is_moving := false

@export var configuration: DiceConfiguration


func _ready() -> void:
	%DiceFaceFront.configuration = configuration.front_face
	%DiceFaceBack.configuration = configuration.back_face
	%DiceFaceTop.configuration = configuration.top_face
	%DiceFaceBottom.configuration = configuration.bottom_face
	%DiceFaceLeft.configuration = configuration.left_face
	%DiceFaceRight.configuration = configuration.right_face


func roll(direction := Vector3(1.0, 1.0, 1.0), strength: float = 20) -> void:
	var position_impulse := Vector3(
		[-1, 1].pick_random(),
		randf_range(0.5, 1.0),
		[-1, 1].pick_random()
	)
	
	apply_central_impulse(position_impulse.normalized() * direction * strength)
	
	var rotation_impulse := Vector3(
		[-1, 1].pick_random(),
		[-1, 1].pick_random(),
		[-1, 1].pick_random()
	)
	
	apply_torque_impulse(rotation_impulse)


func get_top() -> DiceFace:
	var top := -pow(2, 8)
	var face: DiceFace
	for node: DiceFace in $Faces.get_children():
		if top < node.global_transform.origin.y:
			top = node.global_transform.origin.y
			face = node
	
	return face


func _physics_process(_delta: float) -> void:
	is_moving = not previous_position == global_position and not previous_rotation == rotation
	
	previous_position = global_position
	previous_rotation = rotation