Advertisement
Guest User

Character Interaction with Physics Doors - Godot 4

a guest
Oct 31st, 2022
1,449
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | Source Code | 0 0
  1. extends CharacterBody3D
  2.  
  3.  
  4. const SPEED = 5.0
  5. const JUMP_VELOCITY = 4.5
  6.  
  7. # Get the gravity from the project settings to be synced with RigidBody nodes.
  8. var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")
  9.  
  10. var isHoldingObject = false
  11. var heldObject = null
  12.  
  13. func _ready():
  14. $MeshInstance3D.hide()
  15.  
  16. func _physics_process(delta):
  17. # Add the gravity.
  18. if not is_on_floor():
  19. velocity.y -= gravity * delta
  20.  
  21. # Handle Jump.
  22. if Input.is_action_just_pressed("ui_accept") and is_on_floor():
  23. velocity.y = JUMP_VELOCITY
  24.  
  25. # Get the input direction and handle the movement/deceleration.
  26. # As good practice, you should replace UI actions with custom gameplay actions.
  27. var input_dir = Input.get_vector("left", "right", "forward", "backward")
  28. var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
  29. if direction:
  30. velocity.x = direction.x * SPEED
  31. velocity.z = direction.z * SPEED
  32. else:
  33. velocity.x = move_toward(velocity.x, 0, SPEED)
  34. velocity.z = move_toward(velocity.z, 0, SPEED)
  35.  
  36. move_and_slide()
  37.  
  38. if Input.is_action_just_pressed("interact"):
  39. interactWithDoor()
  40.  
  41. maintainInteraction()
  42.  
  43. func interactWithDoor():
  44.  
  45. if !isHoldingObject:
  46. $OrbitCam/Camera3D/PhysicsRaycast.force_raycast_update()
  47.  
  48. if $OrbitCam/Camera3D/PhysicsRaycast.is_colliding():
  49. var collider = $OrbitCam/Camera3D/PhysicsRaycast.get_collider()
  50. if collider.is_in_group("Door"):
  51. isHoldingObject = true
  52. heldObject = collider
  53.  
  54. elif isHoldingObject:
  55. isHoldingObject = false
  56. heldObject = null
  57.  
  58. func maintainInteraction():
  59. if isHoldingObject and heldObject != null:
  60. var forceDirection = $OrbitCam/Camera3D/InteractPos.global_transform.origin - heldObject.global_transform.origin
  61. forceDirection = forceDirection.normalized()
  62.  
  63. heldObject.apply_central_force(forceDirection * 2)
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement