Skip to content

Instantly share code, notes, and snippets.

@shivangrathore
Created November 21, 2024 06:34
Show Gist options
  • Save shivangrathore/db21039c649f2673b33ce67fb7f6fb9f to your computer and use it in GitHub Desktop.
Save shivangrathore/db21039c649f2673b33ce67fb7f6fb9f to your computer and use it in GitHub Desktop.
extends RigidBody3D
@export var torque_impulse: float;
var initial_position: Vector3;
var is_rolling = false;
func _ready() -> void:
randomize()
initial_position = global_position
func roll() -> void:
global_position = initial_position
linear_velocity = Vector3.ZERO
angular_velocity = Vector3.ZERO
is_rolling = true;
sleeping = false;
# Apply random rotation
rotation_degrees = Vector3(
randi_range(0, 359),
randi_range(0, 359),
randi_range(0, 359),
)
apply_torque_impulse(
Vector3(
randf_range(-torque_impulse, torque_impulse),
randf_range(-torque_impulse, torque_impulse),
randf_range(-torque_impulse, torque_impulse)
)
)
func _process(delta: float) -> void:
if Input.is_action_just_pressed("ui_accept"):
roll()
if is_rolling and sleeping:
is_rolling = false
print("Top Face is: ", get_top_face_value())
func get_top_face_value() -> int:
# World up direction
var world_up = Vector3.UP
var max_dot = -1.0 # Initialize to -1.0 for consistent threshold comparison
var threshold = 0.9 # Set a threshold close to 1.0 for "upward" alignment
# Define sides with local cube face mappings
var sides = {
transform.basis.y: 1, # Top
-transform.basis.y: 6, # Bottom
-transform.basis.x: 2, # Left
transform.basis.x: 5, # Right
transform.basis.z: 3, # Forward (screen side)
-transform.basis.z: 4 # Back
}
var value = -1 # Default invalid value
# Compare each face's alignment with the world up direction
for side in sides:
var dot_product = world_up.dot(side.normalized())
# Check if this face is close enough to "up" direction within the threshold
if dot_product > threshold and dot_product > max_dot:
value = sides[side]
max_dot = dot_product
# If no face exceeds the threshold, the object is likely tilted, so default to closest
return value if value != -1 else 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment