rigidbody_pick.gd 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. extends RigidBody3D
  2. const MOUSE_DELTA_COEFFICIENT = 0.01
  3. const CAMERA_DISTANCE_COEFFICIENT = 0.2
  4. var _picked = false
  5. var _last_mouse_pos = Vector2.ZERO
  6. var _mouse_pos = Vector2.ZERO
  7. func _ready():
  8. input_ray_pickable = true
  9. func _input(event):
  10. var mouse_event = event as InputEventMouseButton
  11. if mouse_event and not mouse_event.pressed:
  12. if mouse_event.button_index == MOUSE_BUTTON_LEFT:
  13. _picked = false
  14. var mouse_motion = event as InputEventMouseMotion
  15. if mouse_motion:
  16. _mouse_pos = mouse_motion.position
  17. func _input_event(_viewport, event, _click_pos, _click_normal, _shape_idx):
  18. var mouse_event = event as InputEventMouseButton
  19. if mouse_event and mouse_event.pressed:
  20. if mouse_event.button_index == MOUSE_BUTTON_LEFT:
  21. _picked = true
  22. _mouse_pos = mouse_event.position
  23. _last_mouse_pos = _mouse_pos
  24. func _physics_process(delta):
  25. if _picked:
  26. var mouse_delta = _mouse_pos - _last_mouse_pos
  27. var world_delta := Vector3.ZERO
  28. world_delta.x = mouse_delta.x * MOUSE_DELTA_COEFFICIENT
  29. world_delta.y = -mouse_delta.y * MOUSE_DELTA_COEFFICIENT
  30. var camera = get_viewport().get_camera_3d()
  31. if camera:
  32. var camera_basis = camera.global_transform.basis
  33. world_delta = camera_basis * world_delta
  34. var camera_dist = camera.global_transform.origin.distance_to(global_transform.origin)
  35. var fov_coefficient = camera.fov / 70.0
  36. world_delta *= CAMERA_DISTANCE_COEFFICIENT * camera_dist * fov_coefficient
  37. if freeze:
  38. global_transform.origin += world_delta
  39. else:
  40. linear_velocity = world_delta / delta
  41. _last_mouse_pos = _mouse_pos