Advertisement
Guest User

Untitled

a guest
Mar 27th, 2022
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. extends Node2D
  2.  
  3. var _body:RID
  4. var _invalid_rid:RID #default RID
  5.  
  6. func _enter_tree() -> void:
  7.     _body = Physics2DServer.body_create() #first a body is made so physics can be applied to it
  8.     Physics2DServer.body_set_space(_body, get_world_2d().space) #the body is placed in the 2D world
  9.     _update_shape() #shape is added so that physics can be applied according to the shape of the body
  10.    
  11.     Physics2DServer.body_set_state(_body, Physics2DServer.BODY_STATE_TRANSFORM, self.global_transform) #???
  12.     Physics2DServer.body_set_force_integration_callback(_body, self, "_body_moved", 0) #Once the forces are applied, the _body_moved function is called to change the transform (position) according to the forces
  13.  
  14.     set_notify_transform(true) #setting it true will draw the changes onto the screen once some property is changed in script
  15.  
  16. func _exit_tree() -> void:
  17.     Physics2DServer.free_rid(_body) #removes RID so that physicsServer no longer has to check for that RID
  18.     _body = _invalid_rid #default RID
  19.  
  20. export var shape:Shape2D setget set_shape
  21. export var disabled:bool setget set_disabled
  22. var _shape:RID
  23.  
  24. func _update_shape() -> void:
  25.     var new_shape = _invalid_rid if shape == null else shape.get_rid() #if no shape is assign give _shape default RID
  26.     if new_shape == _shape: #if shape is the same as before then skip
  27.         return
  28.  
  29.     if _shape.get_id() != 0: #???
  30.         Physics2DServer.body_remove_shape(_body, 0) #removes shape to make sure there arn't multiple shapes
  31.  
  32.     _shape = new_shape
  33.  
  34.     if _shape.get_id() != 0:  #???
  35.         Physics2DServer.body_add_shape(_body, _shape, Transform2D.IDENTITY, disabled)
  36.  
  37. func set_shape(new_value:Shape2D) -> void:
  38.     if shape == new_value: #skips if new_shape is same
  39.         return
  40.  
  41.     shape = new_value
  42.  
  43.     if _body.get_id() == 0: #???
  44.         return
  45.  
  46.     _update_shape()
  47.  
  48. func set_disabled(new_value:bool) -> void:
  49.     if disabled == new_value:
  50.         return
  51.  
  52.     disabled = new_value
  53.     if _body.get_id() == 0: #???
  54.         return
  55.  
  56.     if _shape.get_id() != 0: #???
  57.         Physics2DServer.body_set_shape_disabled(_body, 0, disabled) #disables shape at index 0, if shape is disabled the body won't collide
  58.  
  59.  
  60. func _body_moved(state:Physics2DDirectBodyState, _user_data) -> void:
  61.     self.global_transform = state.transform #takes the transformations made by the physics server and applies them onto the body
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement