physics_body_2d.cpp 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601
  1. /**************************************************************************/
  2. /* physics_body_2d.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "physics_body_2d.h"
  31. #include "core/core_string_names.h"
  32. #include "core/engine.h"
  33. #include "core/list.h"
  34. #include "core/math/math_funcs.h"
  35. #include "core/method_bind_ext.gen.inc"
  36. #include "core/object.h"
  37. #include "core/rid.h"
  38. #include "scene/scene_string_names.h"
  39. void PhysicsBody2D::_notification(int p_what) {
  40. }
  41. void PhysicsBody2D::_set_layers(uint32_t p_mask) {
  42. set_collision_layer(p_mask);
  43. set_collision_mask(p_mask);
  44. }
  45. uint32_t PhysicsBody2D::_get_layers() const {
  46. return get_collision_layer();
  47. }
  48. void PhysicsBody2D::_bind_methods() {
  49. ClassDB::bind_method(D_METHOD("_set_layers", "mask"), &PhysicsBody2D::_set_layers);
  50. ClassDB::bind_method(D_METHOD("_get_layers"), &PhysicsBody2D::_get_layers);
  51. ClassDB::bind_method(D_METHOD("get_collision_exceptions"), &PhysicsBody2D::get_collision_exceptions);
  52. ClassDB::bind_method(D_METHOD("add_collision_exception_with", "body"), &PhysicsBody2D::add_collision_exception_with);
  53. ClassDB::bind_method(D_METHOD("remove_collision_exception_with", "body"), &PhysicsBody2D::remove_collision_exception_with);
  54. ADD_PROPERTY(PropertyInfo(Variant::INT, "layers", PROPERTY_HINT_LAYERS_2D_PHYSICS, "", 0), "_set_layers", "_get_layers"); //for backwards compat
  55. }
  56. PhysicsBody2D::PhysicsBody2D(Physics2DServer::BodyMode p_mode) :
  57. CollisionObject2D(RID_PRIME(Physics2DServer::get_singleton()->body_create()), false) {
  58. Physics2DServer::get_singleton()->body_set_mode(get_rid(), p_mode);
  59. set_pickable(false);
  60. }
  61. Array PhysicsBody2D::get_collision_exceptions() {
  62. List<RID> exceptions;
  63. Physics2DServer::get_singleton()->body_get_collision_exceptions(get_rid(), &exceptions);
  64. Array ret;
  65. for (List<RID>::Element *E = exceptions.front(); E; E = E->next()) {
  66. RID body = E->get();
  67. ObjectID instance_id = Physics2DServer::get_singleton()->body_get_object_instance_id(body);
  68. Object *obj = ObjectDB::get_instance(instance_id);
  69. PhysicsBody2D *physics_body = Object::cast_to<PhysicsBody2D>(obj);
  70. ret.append(physics_body);
  71. }
  72. return ret;
  73. }
  74. void PhysicsBody2D::add_collision_exception_with(Node *p_node) {
  75. ERR_FAIL_NULL(p_node);
  76. PhysicsBody2D *physics_body = Object::cast_to<PhysicsBody2D>(p_node);
  77. ERR_FAIL_COND_MSG(!physics_body, "Collision exception only works between two objects of PhysicsBody type.");
  78. Physics2DServer::get_singleton()->body_add_collision_exception(get_rid(), physics_body->get_rid());
  79. }
  80. void PhysicsBody2D::remove_collision_exception_with(Node *p_node) {
  81. ERR_FAIL_NULL(p_node);
  82. PhysicsBody2D *physics_body = Object::cast_to<PhysicsBody2D>(p_node);
  83. ERR_FAIL_COND_MSG(!physics_body, "Collision exception only works between two objects of PhysicsBody type.");
  84. Physics2DServer::get_singleton()->body_remove_collision_exception(get_rid(), physics_body->get_rid());
  85. }
  86. void StaticBody2D::set_constant_linear_velocity(const Vector2 &p_vel) {
  87. constant_linear_velocity = p_vel;
  88. Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_LINEAR_VELOCITY, constant_linear_velocity);
  89. }
  90. void StaticBody2D::set_constant_angular_velocity(real_t p_vel) {
  91. constant_angular_velocity = p_vel;
  92. Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_ANGULAR_VELOCITY, constant_angular_velocity);
  93. }
  94. Vector2 StaticBody2D::get_constant_linear_velocity() const {
  95. return constant_linear_velocity;
  96. }
  97. real_t StaticBody2D::get_constant_angular_velocity() const {
  98. return constant_angular_velocity;
  99. }
  100. #ifndef DISABLE_DEPRECATED
  101. void StaticBody2D::set_friction(real_t p_friction) {
  102. if (p_friction == 1.0 && physics_material_override.is_null()) { // default value, don't create an override for that
  103. return;
  104. }
  105. WARN_DEPRECATED_MSG("The method set_friction has been deprecated and will be removed in the future, use physics material instead.");
  106. ERR_FAIL_COND_MSG(p_friction < 0 || p_friction > 1, "Friction must be between 0 and 1.");
  107. if (physics_material_override.is_null()) {
  108. physics_material_override.instance();
  109. set_physics_material_override(physics_material_override);
  110. }
  111. physics_material_override->set_friction(p_friction);
  112. }
  113. real_t StaticBody2D::get_friction() const {
  114. WARN_DEPRECATED_MSG("The method get_friction has been deprecated and will be removed in the future, use physics material instead.");
  115. if (physics_material_override.is_null()) {
  116. return 1;
  117. }
  118. return physics_material_override->get_friction();
  119. }
  120. void StaticBody2D::set_bounce(real_t p_bounce) {
  121. if (p_bounce == 0.0 && physics_material_override.is_null()) { // default value, don't create an override for that
  122. return;
  123. }
  124. WARN_DEPRECATED_MSG("The method set_bounce has been deprecated and will be removed in the future, use physics material instead.");
  125. ERR_FAIL_COND_MSG(p_bounce < 0 || p_bounce > 1, "Bounce must be between 0 and 1.");
  126. if (physics_material_override.is_null()) {
  127. physics_material_override.instance();
  128. set_physics_material_override(physics_material_override);
  129. }
  130. physics_material_override->set_bounce(p_bounce);
  131. }
  132. real_t StaticBody2D::get_bounce() const {
  133. WARN_DEPRECATED_MSG("The method get_bounce has been deprecated and will be removed in the future, use physics material instead.");
  134. if (physics_material_override.is_null()) {
  135. return 0;
  136. }
  137. return physics_material_override->get_bounce();
  138. }
  139. #endif // DISABLE_DEPRECATED
  140. void StaticBody2D::set_physics_material_override(const Ref<PhysicsMaterial> &p_physics_material_override) {
  141. if (physics_material_override.is_valid()) {
  142. if (physics_material_override->is_connected(CoreStringNames::get_singleton()->changed, this, "_reload_physics_characteristics")) {
  143. physics_material_override->disconnect(CoreStringNames::get_singleton()->changed, this, "_reload_physics_characteristics");
  144. }
  145. }
  146. physics_material_override = p_physics_material_override;
  147. if (physics_material_override.is_valid()) {
  148. physics_material_override->connect(CoreStringNames::get_singleton()->changed, this, "_reload_physics_characteristics");
  149. }
  150. _reload_physics_characteristics();
  151. }
  152. Ref<PhysicsMaterial> StaticBody2D::get_physics_material_override() const {
  153. return physics_material_override;
  154. }
  155. void StaticBody2D::_bind_methods() {
  156. ClassDB::bind_method(D_METHOD("set_constant_linear_velocity", "vel"), &StaticBody2D::set_constant_linear_velocity);
  157. ClassDB::bind_method(D_METHOD("set_constant_angular_velocity", "vel"), &StaticBody2D::set_constant_angular_velocity);
  158. ClassDB::bind_method(D_METHOD("get_constant_linear_velocity"), &StaticBody2D::get_constant_linear_velocity);
  159. ClassDB::bind_method(D_METHOD("get_constant_angular_velocity"), &StaticBody2D::get_constant_angular_velocity);
  160. #ifndef DISABLE_DEPRECATED
  161. ClassDB::bind_method(D_METHOD("set_friction", "friction"), &StaticBody2D::set_friction);
  162. ClassDB::bind_method(D_METHOD("get_friction"), &StaticBody2D::get_friction);
  163. ClassDB::bind_method(D_METHOD("set_bounce", "bounce"), &StaticBody2D::set_bounce);
  164. ClassDB::bind_method(D_METHOD("get_bounce"), &StaticBody2D::get_bounce);
  165. #endif // DISABLE_DEPRECATED
  166. ClassDB::bind_method(D_METHOD("set_physics_material_override", "physics_material_override"), &StaticBody2D::set_physics_material_override);
  167. ClassDB::bind_method(D_METHOD("get_physics_material_override"), &StaticBody2D::get_physics_material_override);
  168. ClassDB::bind_method(D_METHOD("_reload_physics_characteristics"), &StaticBody2D::_reload_physics_characteristics);
  169. ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "constant_linear_velocity"), "set_constant_linear_velocity", "get_constant_linear_velocity");
  170. ADD_PROPERTY(PropertyInfo(Variant::REAL, "constant_angular_velocity"), "set_constant_angular_velocity", "get_constant_angular_velocity");
  171. #ifndef DISABLE_DEPRECATED
  172. ADD_PROPERTY(PropertyInfo(Variant::REAL, "friction", PROPERTY_HINT_RANGE, "0,1,0.01", 0), "set_friction", "get_friction");
  173. ADD_PROPERTY(PropertyInfo(Variant::REAL, "bounce", PROPERTY_HINT_RANGE, "0,1,0.01", 0), "set_bounce", "get_bounce");
  174. #endif // DISABLE_DEPRECATED
  175. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "physics_material_override", PROPERTY_HINT_RESOURCE_TYPE, "PhysicsMaterial"), "set_physics_material_override", "get_physics_material_override");
  176. }
  177. StaticBody2D::StaticBody2D() :
  178. PhysicsBody2D(Physics2DServer::BODY_MODE_STATIC) {
  179. constant_angular_velocity = 0;
  180. }
  181. StaticBody2D::~StaticBody2D() {
  182. }
  183. void StaticBody2D::_reload_physics_characteristics() {
  184. if (physics_material_override.is_null()) {
  185. Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_BOUNCE, 0);
  186. Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_FRICTION, 1);
  187. } else {
  188. Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_BOUNCE, physics_material_override->computed_bounce());
  189. Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_FRICTION, physics_material_override->computed_friction());
  190. }
  191. }
  192. void RigidBody2D::_body_enter_tree(ObjectID p_id) {
  193. Object *obj = ObjectDB::get_instance(p_id);
  194. Node *node = Object::cast_to<Node>(obj);
  195. ERR_FAIL_COND(!node);
  196. ERR_FAIL_COND(!contact_monitor);
  197. Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.find(p_id);
  198. ERR_FAIL_COND(!E);
  199. ERR_FAIL_COND(E->get().in_scene);
  200. contact_monitor->locked = true;
  201. E->get().in_scene = true;
  202. emit_signal(SceneStringNames::get_singleton()->body_entered, node);
  203. for (int i = 0; i < E->get().shapes.size(); i++) {
  204. emit_signal(SceneStringNames::get_singleton()->body_shape_entered, E->get().rid, node, E->get().shapes[i].body_shape, E->get().shapes[i].local_shape);
  205. }
  206. contact_monitor->locked = false;
  207. }
  208. void RigidBody2D::_body_exit_tree(ObjectID p_id) {
  209. Object *obj = ObjectDB::get_instance(p_id);
  210. Node *node = Object::cast_to<Node>(obj);
  211. ERR_FAIL_COND(!node);
  212. ERR_FAIL_COND(!contact_monitor);
  213. Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.find(p_id);
  214. ERR_FAIL_COND(!E);
  215. ERR_FAIL_COND(!E->get().in_scene);
  216. E->get().in_scene = false;
  217. contact_monitor->locked = true;
  218. emit_signal(SceneStringNames::get_singleton()->body_exited, node);
  219. for (int i = 0; i < E->get().shapes.size(); i++) {
  220. emit_signal(SceneStringNames::get_singleton()->body_shape_exited, E->get().rid, node, E->get().shapes[i].body_shape, E->get().shapes[i].local_shape);
  221. }
  222. contact_monitor->locked = false;
  223. }
  224. void RigidBody2D::_body_inout(int p_status, const RID &p_body, ObjectID p_instance, int p_body_shape, int p_local_shape) {
  225. bool body_in = p_status == 1;
  226. ObjectID objid = p_instance;
  227. Object *obj = ObjectDB::get_instance(objid);
  228. Node *node = Object::cast_to<Node>(obj);
  229. ERR_FAIL_COND(!contact_monitor);
  230. Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.find(objid);
  231. ERR_FAIL_COND(!body_in && !E);
  232. if (body_in) {
  233. if (!E) {
  234. E = contact_monitor->body_map.insert(objid, BodyState());
  235. E->get().rid = p_body;
  236. //E->get().rc=0;
  237. E->get().in_scene = node && node->is_inside_tree();
  238. if (node) {
  239. node->connect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree, make_binds(objid));
  240. node->connect(SceneStringNames::get_singleton()->tree_exiting, this, SceneStringNames::get_singleton()->_body_exit_tree, make_binds(objid));
  241. if (E->get().in_scene) {
  242. emit_signal(SceneStringNames::get_singleton()->body_entered, node);
  243. }
  244. }
  245. //E->get().rc++;
  246. }
  247. if (node) {
  248. E->get().shapes.insert(ShapePair(p_body_shape, p_local_shape));
  249. }
  250. if (E->get().in_scene) {
  251. emit_signal(SceneStringNames::get_singleton()->body_shape_entered, p_body, node, p_body_shape, p_local_shape);
  252. }
  253. } else {
  254. //E->get().rc--;
  255. if (node) {
  256. E->get().shapes.erase(ShapePair(p_body_shape, p_local_shape));
  257. }
  258. bool in_scene = E->get().in_scene;
  259. if (E->get().shapes.empty()) {
  260. if (node) {
  261. node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree);
  262. node->disconnect(SceneStringNames::get_singleton()->tree_exiting, this, SceneStringNames::get_singleton()->_body_exit_tree);
  263. if (in_scene) {
  264. emit_signal(SceneStringNames::get_singleton()->body_exited, node);
  265. }
  266. }
  267. contact_monitor->body_map.erase(E);
  268. }
  269. if (node && in_scene) {
  270. emit_signal(SceneStringNames::get_singleton()->body_shape_exited, p_body, node, p_body_shape, p_local_shape);
  271. }
  272. }
  273. }
  274. struct _RigidBody2DInOut {
  275. RID rid;
  276. ObjectID id;
  277. int shape;
  278. int local_shape;
  279. };
  280. bool RigidBody2D::_test_motion(const Vector2 &p_motion, bool p_infinite_inertia, float p_margin, const Ref<Physics2DTestMotionResult> &p_result) {
  281. Physics2DServer::MotionResult *r = nullptr;
  282. Physics2DServer::MotionResult temp_result;
  283. if (p_result.is_valid()) {
  284. r = p_result->get_result_ptr();
  285. } else {
  286. r = &temp_result;
  287. }
  288. bool colliding = Physics2DServer::get_singleton()->body_test_motion(get_rid(), get_global_transform(), p_motion, p_infinite_inertia, p_margin, r);
  289. if (colliding) {
  290. // Don't report collision when the whole motion is done.
  291. return (r->collision_safe_fraction < 1.0);
  292. } else {
  293. return false;
  294. }
  295. }
  296. void RigidBody2D::_direct_state_changed(Object *p_state) {
  297. state = Object::cast_to<Physics2DDirectBodyState>(p_state);
  298. ERR_FAIL_COND_MSG(!state, "Method '_direct_state_changed' must receive a valid Physics2DDirectBodyState object as argument");
  299. set_block_transform_notify(true); // don't want notify (would feedback loop)
  300. if (mode != MODE_KINEMATIC) {
  301. set_global_transform(state->get_transform());
  302. }
  303. linear_velocity = state->get_linear_velocity();
  304. angular_velocity = state->get_angular_velocity();
  305. if (sleeping != state->is_sleeping()) {
  306. sleeping = state->is_sleeping();
  307. emit_signal(SceneStringNames::get_singleton()->sleeping_state_changed);
  308. }
  309. if (get_script_instance()) {
  310. get_script_instance()->call("_integrate_forces", state);
  311. }
  312. set_block_transform_notify(false); // want it back
  313. if (contact_monitor) {
  314. contact_monitor->locked = true;
  315. //untag all
  316. int rc = 0;
  317. for (Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.front(); E; E = E->next()) {
  318. for (int i = 0; i < E->get().shapes.size(); i++) {
  319. E->get().shapes[i].tagged = false;
  320. rc++;
  321. }
  322. }
  323. _RigidBody2DInOut *toadd = (_RigidBody2DInOut *)alloca(state->get_contact_count() * sizeof(_RigidBody2DInOut));
  324. int toadd_count = 0; //state->get_contact_count();
  325. RigidBody2D_RemoveAction *toremove = (RigidBody2D_RemoveAction *)alloca(rc * sizeof(RigidBody2D_RemoveAction));
  326. int toremove_count = 0;
  327. //put the ones to add
  328. for (int i = 0; i < state->get_contact_count(); i++) {
  329. RID rid = state->get_contact_collider(i);
  330. ObjectID obj = state->get_contact_collider_id(i);
  331. int local_shape = state->get_contact_local_shape(i);
  332. int shape = state->get_contact_collider_shape(i);
  333. //bool found=false;
  334. Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.find(obj);
  335. if (!E) {
  336. toadd[toadd_count].rid = rid;
  337. toadd[toadd_count].local_shape = local_shape;
  338. toadd[toadd_count].id = obj;
  339. toadd[toadd_count].shape = shape;
  340. toadd_count++;
  341. continue;
  342. }
  343. ShapePair sp(shape, local_shape);
  344. int idx = E->get().shapes.find(sp);
  345. if (idx == -1) {
  346. toadd[toadd_count].rid = rid;
  347. toadd[toadd_count].local_shape = local_shape;
  348. toadd[toadd_count].id = obj;
  349. toadd[toadd_count].shape = shape;
  350. toadd_count++;
  351. continue;
  352. }
  353. E->get().shapes[idx].tagged = true;
  354. }
  355. //put the ones to remove
  356. for (Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.front(); E; E = E->next()) {
  357. for (int i = 0; i < E->get().shapes.size(); i++) {
  358. if (!E->get().shapes[i].tagged) {
  359. toremove[toremove_count].rid = E->get().rid;
  360. toremove[toremove_count].body_id = E->key();
  361. toremove[toremove_count].pair = E->get().shapes[i];
  362. toremove_count++;
  363. }
  364. }
  365. }
  366. //process remotions
  367. for (int i = 0; i < toremove_count; i++) {
  368. _body_inout(0, toremove[i].rid, toremove[i].body_id, toremove[i].pair.body_shape, toremove[i].pair.local_shape);
  369. }
  370. //process aditions
  371. for (int i = 0; i < toadd_count; i++) {
  372. _body_inout(1, toadd[i].rid, toadd[i].id, toadd[i].shape, toadd[i].local_shape);
  373. }
  374. contact_monitor->locked = false;
  375. }
  376. state = nullptr;
  377. }
  378. void RigidBody2D::set_mode(Mode p_mode) {
  379. mode = p_mode;
  380. switch (p_mode) {
  381. case MODE_RIGID: {
  382. Physics2DServer::get_singleton()->body_set_mode(get_rid(), Physics2DServer::BODY_MODE_RIGID);
  383. } break;
  384. case MODE_STATIC: {
  385. Physics2DServer::get_singleton()->body_set_mode(get_rid(), Physics2DServer::BODY_MODE_STATIC);
  386. } break;
  387. case MODE_KINEMATIC: {
  388. Physics2DServer::get_singleton()->body_set_mode(get_rid(), Physics2DServer::BODY_MODE_KINEMATIC);
  389. } break;
  390. case MODE_CHARACTER: {
  391. Physics2DServer::get_singleton()->body_set_mode(get_rid(), Physics2DServer::BODY_MODE_CHARACTER);
  392. } break;
  393. }
  394. }
  395. RigidBody2D::Mode RigidBody2D::get_mode() const {
  396. return mode;
  397. }
  398. void RigidBody2D::set_mass(real_t p_mass) {
  399. ERR_FAIL_COND(p_mass <= 0);
  400. mass = p_mass;
  401. _change_notify("mass");
  402. _change_notify("weight");
  403. Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_MASS, mass);
  404. }
  405. real_t RigidBody2D::get_mass() const {
  406. return mass;
  407. }
  408. void RigidBody2D::set_inertia(real_t p_inertia) {
  409. ERR_FAIL_COND(p_inertia < 0);
  410. Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_INERTIA, p_inertia);
  411. }
  412. real_t RigidBody2D::get_inertia() const {
  413. return Physics2DServer::get_singleton()->body_get_param(get_rid(), Physics2DServer::BODY_PARAM_INERTIA);
  414. }
  415. void RigidBody2D::set_weight(real_t p_weight) {
  416. set_mass(p_weight / (real_t(GLOBAL_DEF("physics/2d/default_gravity", 98)) / 10));
  417. }
  418. real_t RigidBody2D::get_weight() const {
  419. return mass * (real_t(GLOBAL_DEF("physics/2d/default_gravity", 98)) / 10);
  420. }
  421. #ifndef DISABLE_DEPRECATED
  422. void RigidBody2D::set_friction(real_t p_friction) {
  423. if (p_friction == 1.0 && physics_material_override.is_null()) { // default value, don't create an override for that
  424. return;
  425. }
  426. WARN_DEPRECATED_MSG("The method set_friction has been deprecated and will be removed in the future, use physics material instead.");
  427. ERR_FAIL_COND_MSG(p_friction < 0 || p_friction > 1, "Friction must be between 0 and 1.");
  428. if (physics_material_override.is_null()) {
  429. physics_material_override.instance();
  430. set_physics_material_override(physics_material_override);
  431. }
  432. physics_material_override->set_friction(p_friction);
  433. }
  434. real_t RigidBody2D::get_friction() const {
  435. WARN_DEPRECATED_MSG("The method get_friction has been deprecated and will be removed in the future, use physics material instead.");
  436. if (physics_material_override.is_null()) {
  437. return 1;
  438. }
  439. return physics_material_override->get_friction();
  440. }
  441. void RigidBody2D::set_bounce(real_t p_bounce) {
  442. if (p_bounce == 0.0 && physics_material_override.is_null()) { // default value, don't create an override for that
  443. return;
  444. }
  445. WARN_DEPRECATED_MSG("The method set_bounce has been deprecated and will be removed in the future, use physics material instead.");
  446. ERR_FAIL_COND(p_bounce < 0 || p_bounce > 1);
  447. if (physics_material_override.is_null()) {
  448. physics_material_override.instance();
  449. set_physics_material_override(physics_material_override);
  450. }
  451. physics_material_override->set_bounce(p_bounce);
  452. }
  453. real_t RigidBody2D::get_bounce() const {
  454. WARN_DEPRECATED_MSG("The method get_bounce has been deprecated and will be removed in the future, use physics material instead.");
  455. if (physics_material_override.is_null()) {
  456. return 0;
  457. }
  458. return physics_material_override->get_bounce();
  459. }
  460. #endif // DISABLE_DEPRECATED
  461. void RigidBody2D::set_physics_material_override(const Ref<PhysicsMaterial> &p_physics_material_override) {
  462. if (physics_material_override.is_valid()) {
  463. if (physics_material_override->is_connected(CoreStringNames::get_singleton()->changed, this, "_reload_physics_characteristics")) {
  464. physics_material_override->disconnect(CoreStringNames::get_singleton()->changed, this, "_reload_physics_characteristics");
  465. }
  466. }
  467. physics_material_override = p_physics_material_override;
  468. if (physics_material_override.is_valid()) {
  469. physics_material_override->connect(CoreStringNames::get_singleton()->changed, this, "_reload_physics_characteristics");
  470. }
  471. _reload_physics_characteristics();
  472. }
  473. Ref<PhysicsMaterial> RigidBody2D::get_physics_material_override() const {
  474. return physics_material_override;
  475. }
  476. void RigidBody2D::set_gravity_scale(real_t p_gravity_scale) {
  477. gravity_scale = p_gravity_scale;
  478. Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_GRAVITY_SCALE, gravity_scale);
  479. }
  480. real_t RigidBody2D::get_gravity_scale() const {
  481. return gravity_scale;
  482. }
  483. void RigidBody2D::set_linear_damp(real_t p_linear_damp) {
  484. ERR_FAIL_COND(p_linear_damp < -1);
  485. linear_damp = p_linear_damp;
  486. Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_LINEAR_DAMP, linear_damp);
  487. }
  488. real_t RigidBody2D::get_linear_damp() const {
  489. return linear_damp;
  490. }
  491. void RigidBody2D::set_angular_damp(real_t p_angular_damp) {
  492. ERR_FAIL_COND(p_angular_damp < -1);
  493. angular_damp = p_angular_damp;
  494. Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_ANGULAR_DAMP, angular_damp);
  495. }
  496. real_t RigidBody2D::get_angular_damp() const {
  497. return angular_damp;
  498. }
  499. void RigidBody2D::set_axis_velocity(const Vector2 &p_axis) {
  500. Vector2 v = state ? state->get_linear_velocity() : linear_velocity;
  501. Vector2 axis = p_axis.normalized();
  502. v -= axis * axis.dot(v);
  503. v += p_axis;
  504. if (state) {
  505. set_linear_velocity(v);
  506. } else {
  507. Physics2DServer::get_singleton()->body_set_axis_velocity(get_rid(), p_axis);
  508. linear_velocity = v;
  509. }
  510. }
  511. void RigidBody2D::set_linear_velocity(const Vector2 &p_velocity) {
  512. linear_velocity = p_velocity;
  513. if (state) {
  514. state->set_linear_velocity(linear_velocity);
  515. } else {
  516. Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_LINEAR_VELOCITY, linear_velocity);
  517. }
  518. }
  519. Vector2 RigidBody2D::get_linear_velocity() const {
  520. return linear_velocity;
  521. }
  522. void RigidBody2D::set_angular_velocity(real_t p_velocity) {
  523. angular_velocity = p_velocity;
  524. if (state) {
  525. state->set_angular_velocity(angular_velocity);
  526. } else {
  527. Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_ANGULAR_VELOCITY, angular_velocity);
  528. }
  529. }
  530. real_t RigidBody2D::get_angular_velocity() const {
  531. return angular_velocity;
  532. }
  533. void RigidBody2D::set_use_custom_integrator(bool p_enable) {
  534. if (custom_integrator == p_enable) {
  535. return;
  536. }
  537. custom_integrator = p_enable;
  538. Physics2DServer::get_singleton()->body_set_omit_force_integration(get_rid(), p_enable);
  539. }
  540. bool RigidBody2D::is_using_custom_integrator() {
  541. return custom_integrator;
  542. }
  543. void RigidBody2D::set_sleeping(bool p_sleeping) {
  544. sleeping = p_sleeping;
  545. Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_SLEEPING, sleeping);
  546. }
  547. void RigidBody2D::set_can_sleep(bool p_active) {
  548. can_sleep = p_active;
  549. Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_CAN_SLEEP, p_active);
  550. }
  551. bool RigidBody2D::is_able_to_sleep() const {
  552. return can_sleep;
  553. }
  554. bool RigidBody2D::is_sleeping() const {
  555. return sleeping;
  556. }
  557. void RigidBody2D::set_max_contacts_reported(int p_amount) {
  558. max_contacts_reported = p_amount;
  559. Physics2DServer::get_singleton()->body_set_max_contacts_reported(get_rid(), p_amount);
  560. }
  561. int RigidBody2D::get_max_contacts_reported() const {
  562. return max_contacts_reported;
  563. }
  564. void RigidBody2D::apply_central_impulse(const Vector2 &p_impulse) {
  565. Physics2DServer::get_singleton()->body_apply_central_impulse(get_rid(), p_impulse);
  566. }
  567. void RigidBody2D::apply_impulse(const Vector2 &p_offset, const Vector2 &p_impulse) {
  568. Physics2DServer::get_singleton()->body_apply_impulse(get_rid(), p_offset, p_impulse);
  569. }
  570. void RigidBody2D::apply_torque_impulse(float p_torque) {
  571. Physics2DServer::get_singleton()->body_apply_torque_impulse(get_rid(), p_torque);
  572. }
  573. void RigidBody2D::set_applied_force(const Vector2 &p_force) {
  574. Physics2DServer::get_singleton()->body_set_applied_force(get_rid(), p_force);
  575. };
  576. Vector2 RigidBody2D::get_applied_force() const {
  577. return Physics2DServer::get_singleton()->body_get_applied_force(get_rid());
  578. };
  579. void RigidBody2D::set_applied_torque(const float p_torque) {
  580. Physics2DServer::get_singleton()->body_set_applied_torque(get_rid(), p_torque);
  581. };
  582. float RigidBody2D::get_applied_torque() const {
  583. return Physics2DServer::get_singleton()->body_get_applied_torque(get_rid());
  584. };
  585. void RigidBody2D::add_central_force(const Vector2 &p_force) {
  586. Physics2DServer::get_singleton()->body_add_central_force(get_rid(), p_force);
  587. }
  588. void RigidBody2D::add_force(const Vector2 &p_offset, const Vector2 &p_force) {
  589. Physics2DServer::get_singleton()->body_add_force(get_rid(), p_offset, p_force);
  590. }
  591. void RigidBody2D::add_torque(const float p_torque) {
  592. Physics2DServer::get_singleton()->body_add_torque(get_rid(), p_torque);
  593. }
  594. void RigidBody2D::set_continuous_collision_detection_mode(CCDMode p_mode) {
  595. ccd_mode = p_mode;
  596. Physics2DServer::get_singleton()->body_set_continuous_collision_detection_mode(get_rid(), Physics2DServer::CCDMode(p_mode));
  597. }
  598. RigidBody2D::CCDMode RigidBody2D::get_continuous_collision_detection_mode() const {
  599. return ccd_mode;
  600. }
  601. Array RigidBody2D::get_colliding_bodies() const {
  602. ERR_FAIL_COND_V(!contact_monitor, Array());
  603. Array ret;
  604. ret.resize(contact_monitor->body_map.size());
  605. int idx = 0;
  606. for (const Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.front(); E; E = E->next()) {
  607. Object *obj = ObjectDB::get_instance(E->key());
  608. if (!obj) {
  609. ret.resize(ret.size() - 1); //ops
  610. } else {
  611. ret[idx++] = obj;
  612. }
  613. }
  614. return ret;
  615. }
  616. void RigidBody2D::set_contact_monitor(bool p_enabled) {
  617. if (p_enabled == is_contact_monitor_enabled()) {
  618. return;
  619. }
  620. if (!p_enabled) {
  621. ERR_FAIL_COND_MSG(contact_monitor->locked, "Can't disable contact monitoring during in/out callback. Use call_deferred(\"set_contact_monitor\", false) instead.");
  622. for (Map<ObjectID, BodyState>::Element *E = contact_monitor->body_map.front(); E; E = E->next()) {
  623. //clean up mess
  624. Object *obj = ObjectDB::get_instance(E->key());
  625. Node *node = Object::cast_to<Node>(obj);
  626. if (node) {
  627. node->disconnect(SceneStringNames::get_singleton()->tree_entered, this, SceneStringNames::get_singleton()->_body_enter_tree);
  628. node->disconnect(SceneStringNames::get_singleton()->tree_exiting, this, SceneStringNames::get_singleton()->_body_exit_tree);
  629. }
  630. }
  631. memdelete(contact_monitor);
  632. contact_monitor = nullptr;
  633. } else {
  634. contact_monitor = memnew(ContactMonitor);
  635. contact_monitor->locked = false;
  636. }
  637. }
  638. bool RigidBody2D::is_contact_monitor_enabled() const {
  639. return contact_monitor != nullptr;
  640. }
  641. void RigidBody2D::_notification(int p_what) {
  642. #ifdef TOOLS_ENABLED
  643. if (p_what == NOTIFICATION_ENTER_TREE) {
  644. if (Engine::get_singleton()->is_editor_hint()) {
  645. set_notify_local_transform(true); //used for warnings and only in editor
  646. }
  647. }
  648. if (p_what == NOTIFICATION_LOCAL_TRANSFORM_CHANGED) {
  649. if (Engine::get_singleton()->is_editor_hint()) {
  650. update_configuration_warning();
  651. }
  652. }
  653. #endif
  654. }
  655. String RigidBody2D::get_configuration_warning() const {
  656. Transform2D t = get_transform();
  657. String warning = CollisionObject2D::get_configuration_warning();
  658. if ((get_mode() == MODE_RIGID || get_mode() == MODE_CHARACTER) && (ABS(t.elements[0].length() - 1.0) > 0.05 || ABS(t.elements[1].length() - 1.0) > 0.05)) {
  659. if (warning != String()) {
  660. warning += "\n\n";
  661. }
  662. warning += TTR("Size changes to RigidBody2D (in character or rigid modes) will be overridden by the physics engine when running.\nChange the size in children collision shapes instead.");
  663. }
  664. return warning;
  665. }
  666. void RigidBody2D::_bind_methods() {
  667. ClassDB::bind_method(D_METHOD("set_mode", "mode"), &RigidBody2D::set_mode);
  668. ClassDB::bind_method(D_METHOD("get_mode"), &RigidBody2D::get_mode);
  669. ClassDB::bind_method(D_METHOD("set_mass", "mass"), &RigidBody2D::set_mass);
  670. ClassDB::bind_method(D_METHOD("get_mass"), &RigidBody2D::get_mass);
  671. ClassDB::bind_method(D_METHOD("get_inertia"), &RigidBody2D::get_inertia);
  672. ClassDB::bind_method(D_METHOD("set_inertia", "inertia"), &RigidBody2D::set_inertia);
  673. ClassDB::bind_method(D_METHOD("set_weight", "weight"), &RigidBody2D::set_weight);
  674. ClassDB::bind_method(D_METHOD("get_weight"), &RigidBody2D::get_weight);
  675. #ifndef DISABLE_DEPRECATED
  676. ClassDB::bind_method(D_METHOD("set_friction", "friction"), &RigidBody2D::set_friction);
  677. ClassDB::bind_method(D_METHOD("get_friction"), &RigidBody2D::get_friction);
  678. ClassDB::bind_method(D_METHOD("set_bounce", "bounce"), &RigidBody2D::set_bounce);
  679. ClassDB::bind_method(D_METHOD("get_bounce"), &RigidBody2D::get_bounce);
  680. #endif // DISABLE_DEPRECATED
  681. ClassDB::bind_method(D_METHOD("set_physics_material_override", "physics_material_override"), &RigidBody2D::set_physics_material_override);
  682. ClassDB::bind_method(D_METHOD("get_physics_material_override"), &RigidBody2D::get_physics_material_override);
  683. ClassDB::bind_method(D_METHOD("_reload_physics_characteristics"), &RigidBody2D::_reload_physics_characteristics);
  684. ClassDB::bind_method(D_METHOD("set_gravity_scale", "gravity_scale"), &RigidBody2D::set_gravity_scale);
  685. ClassDB::bind_method(D_METHOD("get_gravity_scale"), &RigidBody2D::get_gravity_scale);
  686. ClassDB::bind_method(D_METHOD("set_linear_damp", "linear_damp"), &RigidBody2D::set_linear_damp);
  687. ClassDB::bind_method(D_METHOD("get_linear_damp"), &RigidBody2D::get_linear_damp);
  688. ClassDB::bind_method(D_METHOD("set_angular_damp", "angular_damp"), &RigidBody2D::set_angular_damp);
  689. ClassDB::bind_method(D_METHOD("get_angular_damp"), &RigidBody2D::get_angular_damp);
  690. ClassDB::bind_method(D_METHOD("set_linear_velocity", "linear_velocity"), &RigidBody2D::set_linear_velocity);
  691. ClassDB::bind_method(D_METHOD("get_linear_velocity"), &RigidBody2D::get_linear_velocity);
  692. ClassDB::bind_method(D_METHOD("set_angular_velocity", "angular_velocity"), &RigidBody2D::set_angular_velocity);
  693. ClassDB::bind_method(D_METHOD("get_angular_velocity"), &RigidBody2D::get_angular_velocity);
  694. ClassDB::bind_method(D_METHOD("set_max_contacts_reported", "amount"), &RigidBody2D::set_max_contacts_reported);
  695. ClassDB::bind_method(D_METHOD("get_max_contacts_reported"), &RigidBody2D::get_max_contacts_reported);
  696. ClassDB::bind_method(D_METHOD("set_use_custom_integrator", "enable"), &RigidBody2D::set_use_custom_integrator);
  697. ClassDB::bind_method(D_METHOD("is_using_custom_integrator"), &RigidBody2D::is_using_custom_integrator);
  698. ClassDB::bind_method(D_METHOD("set_contact_monitor", "enabled"), &RigidBody2D::set_contact_monitor);
  699. ClassDB::bind_method(D_METHOD("is_contact_monitor_enabled"), &RigidBody2D::is_contact_monitor_enabled);
  700. ClassDB::bind_method(D_METHOD("set_continuous_collision_detection_mode", "mode"), &RigidBody2D::set_continuous_collision_detection_mode);
  701. ClassDB::bind_method(D_METHOD("get_continuous_collision_detection_mode"), &RigidBody2D::get_continuous_collision_detection_mode);
  702. ClassDB::bind_method(D_METHOD("set_axis_velocity", "axis_velocity"), &RigidBody2D::set_axis_velocity);
  703. ClassDB::bind_method(D_METHOD("apply_central_impulse", "impulse"), &RigidBody2D::apply_central_impulse);
  704. ClassDB::bind_method(D_METHOD("apply_impulse", "offset", "impulse"), &RigidBody2D::apply_impulse);
  705. ClassDB::bind_method(D_METHOD("apply_torque_impulse", "torque"), &RigidBody2D::apply_torque_impulse);
  706. ClassDB::bind_method(D_METHOD("set_applied_force", "force"), &RigidBody2D::set_applied_force);
  707. ClassDB::bind_method(D_METHOD("get_applied_force"), &RigidBody2D::get_applied_force);
  708. ClassDB::bind_method(D_METHOD("set_applied_torque", "torque"), &RigidBody2D::set_applied_torque);
  709. ClassDB::bind_method(D_METHOD("get_applied_torque"), &RigidBody2D::get_applied_torque);
  710. ClassDB::bind_method(D_METHOD("add_central_force", "force"), &RigidBody2D::add_central_force);
  711. ClassDB::bind_method(D_METHOD("add_force", "offset", "force"), &RigidBody2D::add_force);
  712. ClassDB::bind_method(D_METHOD("add_torque", "torque"), &RigidBody2D::add_torque);
  713. ClassDB::bind_method(D_METHOD("set_sleeping", "sleeping"), &RigidBody2D::set_sleeping);
  714. ClassDB::bind_method(D_METHOD("is_sleeping"), &RigidBody2D::is_sleeping);
  715. ClassDB::bind_method(D_METHOD("set_can_sleep", "able_to_sleep"), &RigidBody2D::set_can_sleep);
  716. ClassDB::bind_method(D_METHOD("is_able_to_sleep"), &RigidBody2D::is_able_to_sleep);
  717. ClassDB::bind_method(D_METHOD("test_motion", "motion", "infinite_inertia", "margin", "result"), &RigidBody2D::_test_motion, DEFVAL(true), DEFVAL(0.08), DEFVAL(Variant()));
  718. ClassDB::bind_method(D_METHOD("_direct_state_changed"), &RigidBody2D::_direct_state_changed);
  719. ClassDB::bind_method(D_METHOD("_body_enter_tree"), &RigidBody2D::_body_enter_tree);
  720. ClassDB::bind_method(D_METHOD("_body_exit_tree"), &RigidBody2D::_body_exit_tree);
  721. ClassDB::bind_method(D_METHOD("get_colliding_bodies"), &RigidBody2D::get_colliding_bodies);
  722. BIND_VMETHOD(MethodInfo("_integrate_forces", PropertyInfo(Variant::OBJECT, "state", PROPERTY_HINT_RESOURCE_TYPE, "Physics2DDirectBodyState")));
  723. ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Rigid,Static,Character,Kinematic"), "set_mode", "get_mode");
  724. ADD_PROPERTY(PropertyInfo(Variant::REAL, "mass", PROPERTY_HINT_EXP_RANGE, "0.01,65535,0.01,or_greater"), "set_mass", "get_mass");
  725. ADD_PROPERTY(PropertyInfo(Variant::REAL, "inertia", PROPERTY_HINT_EXP_RANGE, "0.01,65535,0.01,or_greater", 0), "set_inertia", "get_inertia");
  726. ADD_PROPERTY(PropertyInfo(Variant::REAL, "weight", PROPERTY_HINT_EXP_RANGE, "0.01,65535,0.01,or_greater", PROPERTY_USAGE_EDITOR), "set_weight", "get_weight");
  727. #ifndef DISABLE_DEPRECATED
  728. ADD_PROPERTY(PropertyInfo(Variant::REAL, "friction", PROPERTY_HINT_RANGE, "0,1,0.01", 0), "set_friction", "get_friction");
  729. ADD_PROPERTY(PropertyInfo(Variant::REAL, "bounce", PROPERTY_HINT_RANGE, "0,1,0.01", 0), "set_bounce", "get_bounce");
  730. #endif // DISABLE_DEPRECATED
  731. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "physics_material_override", PROPERTY_HINT_RESOURCE_TYPE, "PhysicsMaterial"), "set_physics_material_override", "get_physics_material_override");
  732. ADD_PROPERTY(PropertyInfo(Variant::REAL, "gravity_scale", PROPERTY_HINT_RANGE, "-128,128,0.01"), "set_gravity_scale", "get_gravity_scale");
  733. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "custom_integrator"), "set_use_custom_integrator", "is_using_custom_integrator");
  734. ADD_PROPERTY(PropertyInfo(Variant::INT, "continuous_cd", PROPERTY_HINT_ENUM, "Disabled,Cast Ray,Cast Shape"), "set_continuous_collision_detection_mode", "get_continuous_collision_detection_mode");
  735. ADD_PROPERTY(PropertyInfo(Variant::INT, "contacts_reported", PROPERTY_HINT_RANGE, "0,64,1,or_greater"), "set_max_contacts_reported", "get_max_contacts_reported");
  736. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "contact_monitor"), "set_contact_monitor", "is_contact_monitor_enabled");
  737. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "sleeping"), "set_sleeping", "is_sleeping");
  738. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "can_sleep"), "set_can_sleep", "is_able_to_sleep");
  739. ADD_GROUP("Linear", "linear_");
  740. ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "linear_velocity"), "set_linear_velocity", "get_linear_velocity");
  741. ADD_PROPERTY(PropertyInfo(Variant::REAL, "linear_damp", PROPERTY_HINT_RANGE, "-1,100,0.001,or_greater"), "set_linear_damp", "get_linear_damp");
  742. ADD_GROUP("Angular", "angular_");
  743. ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_velocity"), "set_angular_velocity", "get_angular_velocity");
  744. ADD_PROPERTY(PropertyInfo(Variant::REAL, "angular_damp", PROPERTY_HINT_RANGE, "-1,100,0.001,or_greater"), "set_angular_damp", "get_angular_damp");
  745. ADD_GROUP("Applied Forces", "applied_");
  746. ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "applied_force"), "set_applied_force", "get_applied_force");
  747. ADD_PROPERTY(PropertyInfo(Variant::REAL, "applied_torque"), "set_applied_torque", "get_applied_torque");
  748. ADD_SIGNAL(MethodInfo("body_shape_entered", PropertyInfo(Variant::_RID, "body_rid"), PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node"), PropertyInfo(Variant::INT, "body_shape_index"), PropertyInfo(Variant::INT, "local_shape_index")));
  749. ADD_SIGNAL(MethodInfo("body_shape_exited", PropertyInfo(Variant::_RID, "body_rid"), PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node"), PropertyInfo(Variant::INT, "body_shape_index"), PropertyInfo(Variant::INT, "local_shape_index")));
  750. ADD_SIGNAL(MethodInfo("body_entered", PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
  751. ADD_SIGNAL(MethodInfo("body_exited", PropertyInfo(Variant::OBJECT, "body", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
  752. ADD_SIGNAL(MethodInfo("sleeping_state_changed"));
  753. BIND_ENUM_CONSTANT(MODE_RIGID);
  754. BIND_ENUM_CONSTANT(MODE_STATIC);
  755. BIND_ENUM_CONSTANT(MODE_CHARACTER);
  756. BIND_ENUM_CONSTANT(MODE_KINEMATIC);
  757. BIND_ENUM_CONSTANT(CCD_MODE_DISABLED);
  758. BIND_ENUM_CONSTANT(CCD_MODE_CAST_RAY);
  759. BIND_ENUM_CONSTANT(CCD_MODE_CAST_SHAPE);
  760. }
  761. RigidBody2D::RigidBody2D() :
  762. PhysicsBody2D(Physics2DServer::BODY_MODE_RIGID) {
  763. mode = MODE_RIGID;
  764. mass = 1;
  765. gravity_scale = 1;
  766. linear_damp = -1;
  767. angular_damp = -1;
  768. max_contacts_reported = 0;
  769. state = nullptr;
  770. angular_velocity = 0;
  771. sleeping = false;
  772. ccd_mode = CCD_MODE_DISABLED;
  773. custom_integrator = false;
  774. contact_monitor = nullptr;
  775. can_sleep = true;
  776. Physics2DServer::get_singleton()->body_set_force_integration_callback(get_rid(), this, "_direct_state_changed");
  777. }
  778. RigidBody2D::~RigidBody2D() {
  779. if (contact_monitor) {
  780. memdelete(contact_monitor);
  781. }
  782. }
  783. void RigidBody2D::_reload_physics_characteristics() {
  784. if (physics_material_override.is_null()) {
  785. Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_BOUNCE, 0);
  786. Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_FRICTION, 1);
  787. } else {
  788. Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_BOUNCE, physics_material_override->computed_bounce());
  789. Physics2DServer::get_singleton()->body_set_param(get_rid(), Physics2DServer::BODY_PARAM_FRICTION, physics_material_override->computed_friction());
  790. }
  791. }
  792. //////////////////////////
  793. Ref<KinematicCollision2D> KinematicBody2D::_move(const Vector2 &p_motion, bool p_infinite_inertia, bool p_exclude_raycast_shapes, bool p_test_only) {
  794. Collision col;
  795. bool collided = move_and_collide(p_motion, p_infinite_inertia, col, p_exclude_raycast_shapes, p_test_only);
  796. // Don't report collision when the whole motion is done.
  797. if (collided && col.collision_safe_fraction < 1) {
  798. // Create a new instance when the cached reference is invalid or still in use in script.
  799. if (motion_cache.is_null() || motion_cache->reference_get_count() > 1) {
  800. motion_cache.instance();
  801. motion_cache->owner = this;
  802. }
  803. motion_cache->collision = col;
  804. return motion_cache;
  805. }
  806. return Ref<KinematicCollision2D>();
  807. }
  808. bool KinematicBody2D::separate_raycast_shapes(bool p_infinite_inertia, Collision &r_collision) {
  809. Physics2DServer::SeparationResult sep_res[8]; //max 8 rays
  810. Transform2D gt = get_global_transform();
  811. Vector2 recover;
  812. int hits = Physics2DServer::get_singleton()->body_test_ray_separation(get_rid(), gt, p_infinite_inertia, recover, sep_res, 8, margin);
  813. int deepest = -1;
  814. float deepest_depth;
  815. for (int i = 0; i < hits; i++) {
  816. if (deepest == -1 || sep_res[i].collision_depth > deepest_depth) {
  817. deepest = i;
  818. deepest_depth = sep_res[i].collision_depth;
  819. }
  820. }
  821. gt.elements[2] += recover;
  822. set_global_transform(gt);
  823. if (deepest != -1) {
  824. r_collision.collider = sep_res[deepest].collider_id;
  825. r_collision.collider_rid = sep_res[deepest].collider;
  826. r_collision.collider_metadata = sep_res[deepest].collider_metadata;
  827. r_collision.collider_shape = sep_res[deepest].collider_shape;
  828. r_collision.collider_vel = sep_res[deepest].collider_velocity;
  829. r_collision.collision = sep_res[deepest].collision_point;
  830. r_collision.normal = sep_res[deepest].collision_normal;
  831. r_collision.local_shape = sep_res[deepest].collision_local_shape;
  832. r_collision.travel = recover;
  833. r_collision.remainder = Vector2();
  834. return true;
  835. } else {
  836. return false;
  837. }
  838. }
  839. bool KinematicBody2D::move_and_collide(const Vector2 &p_motion, bool p_infinite_inertia, Collision &r_collision, bool p_exclude_raycast_shapes, bool p_test_only, bool p_cancel_sliding, const Set<RID> &p_exclude) {
  840. if (sync_to_physics) {
  841. ERR_PRINT("Functions move_and_slide and move_and_collide do not work together with 'sync to physics' option. Please read the documentation.");
  842. }
  843. Transform2D gt = get_global_transform();
  844. Physics2DServer::MotionResult result;
  845. bool colliding = Physics2DServer::get_singleton()->body_test_motion(get_rid(), gt, p_motion, p_infinite_inertia, margin, &result, p_exclude_raycast_shapes, p_exclude);
  846. // Restore direction of motion to be along original motion,
  847. // in order to avoid sliding due to recovery,
  848. // but only if collision depth is low enough to avoid tunneling.
  849. if (p_cancel_sliding) {
  850. real_t motion_length = p_motion.length();
  851. real_t precision = 0.001;
  852. if (colliding) {
  853. // Can't just use margin as a threshold because collision depth is calculated on unsafe motion,
  854. // so even in normal resting cases the depth can be a bit more than the margin.
  855. precision += motion_length * (result.collision_unsafe_fraction - result.collision_safe_fraction);
  856. if (result.collision_depth > (real_t)margin + precision) {
  857. p_cancel_sliding = false;
  858. }
  859. }
  860. if (p_cancel_sliding) {
  861. // When motion is null, recovery is the resulting motion.
  862. Vector2 motion_normal;
  863. if (motion_length > CMP_EPSILON) {
  864. motion_normal = p_motion / motion_length;
  865. }
  866. // Check depth of recovery.
  867. real_t projected_length = result.motion.dot(motion_normal);
  868. Vector2 recovery = result.motion - motion_normal * projected_length;
  869. real_t recovery_length = recovery.length();
  870. // Fixes cases where canceling slide causes the motion to go too deep into the ground,
  871. // because we're only taking rest information into account and not general recovery.
  872. if (recovery_length < (real_t)margin + precision) {
  873. // Apply adjustment to motion.
  874. result.motion = motion_normal * projected_length;
  875. result.remainder = p_motion - result.motion;
  876. }
  877. }
  878. }
  879. if (colliding) {
  880. r_collision.collider_metadata = result.collider_metadata;
  881. r_collision.collider_shape = result.collider_shape;
  882. r_collision.collider_vel = result.collider_velocity;
  883. r_collision.collision = result.collision_point;
  884. r_collision.normal = result.collision_normal;
  885. r_collision.collider = result.collider_id;
  886. r_collision.collider_rid = result.collider;
  887. r_collision.travel = result.motion;
  888. r_collision.remainder = result.remainder;
  889. r_collision.local_shape = result.collision_local_shape;
  890. r_collision.collision_safe_fraction = result.collision_safe_fraction;
  891. }
  892. if (!p_test_only) {
  893. gt.elements[2] += result.motion;
  894. set_global_transform(gt);
  895. }
  896. return colliding;
  897. }
  898. //so, if you pass 45 as limit, avoid numerical precision errors when angle is 45.
  899. #define FLOOR_ANGLE_THRESHOLD 0.01
  900. Vector2 KinematicBody2D::_move_and_slide_internal(const Vector2 &p_linear_velocity, const Vector2 &p_snap, const Vector2 &p_up_direction, bool p_stop_on_slope, int p_max_slides, float p_floor_max_angle, bool p_infinite_inertia) {
  901. Vector2 body_velocity = p_linear_velocity;
  902. Vector2 body_velocity_normal = body_velocity.normalized();
  903. Vector2 up_direction = p_up_direction.normalized();
  904. bool was_on_floor = on_floor;
  905. // Hack in order to work with calling from _process as well as from _physics_process; calling from thread is risky
  906. float delta = Engine::get_singleton()->is_in_physics_frame() ? get_physics_process_delta_time() : get_process_delta_time();
  907. Vector2 current_floor_velocity = floor_velocity;
  908. if (on_floor && on_floor_body.is_valid()) {
  909. //this approach makes sure there is less delay between the actual body velocity and the one we saved
  910. Physics2DDirectBodyState *bs = Physics2DServer::get_singleton()->body_get_direct_state(on_floor_body);
  911. if (bs) {
  912. Transform2D gt = get_global_transform();
  913. Vector2 local_position = gt.elements[2] - bs->get_transform().elements[2];
  914. current_floor_velocity = bs->get_velocity_at_local_position(local_position);
  915. } else {
  916. // Body is removed or destroyed, invalidate floor.
  917. current_floor_velocity = Vector2();
  918. on_floor_body = RID();
  919. }
  920. }
  921. colliders.clear();
  922. on_floor = false;
  923. on_ceiling = false;
  924. on_wall = false;
  925. floor_normal = Vector2();
  926. floor_velocity = Vector2();
  927. if (current_floor_velocity != Vector2() && on_floor_body.is_valid()) {
  928. Collision floor_collision;
  929. Set<RID> exclude;
  930. exclude.insert(on_floor_body);
  931. if (move_and_collide(current_floor_velocity * delta, p_infinite_inertia, floor_collision, true, false, false, exclude)) {
  932. colliders.push_back(floor_collision);
  933. _set_collision_direction(floor_collision, up_direction, p_floor_max_angle);
  934. }
  935. }
  936. on_floor_body = RID();
  937. Vector2 motion = body_velocity * delta;
  938. // No sliding on first attempt to keep floor motion stable when possible,
  939. // when stop on slope is enabled.
  940. bool sliding_enabled = !p_stop_on_slope;
  941. for (int iteration = 0; iteration < p_max_slides; ++iteration) {
  942. Collision collision;
  943. bool found_collision = false;
  944. for (int i = 0; i < 2; ++i) {
  945. bool collided;
  946. if (i == 0) { //collide
  947. collided = move_and_collide(motion, p_infinite_inertia, collision, true, false, !sliding_enabled);
  948. if (!collided) {
  949. motion = Vector2(); //clear because no collision happened and motion completed
  950. }
  951. } else { //separate raycasts (if any)
  952. collided = separate_raycast_shapes(p_infinite_inertia, collision);
  953. if (collided) {
  954. collision.remainder = motion; //keep
  955. collision.travel = Vector2();
  956. }
  957. }
  958. if (collided) {
  959. found_collision = true;
  960. colliders.push_back(collision);
  961. _set_collision_direction(collision, up_direction, p_floor_max_angle);
  962. if (on_floor && p_stop_on_slope) {
  963. if ((body_velocity_normal + up_direction).length() < 0.01) {
  964. Transform2D gt = get_global_transform();
  965. if (collision.travel.length() > margin) {
  966. gt.elements[2] -= collision.travel.slide(up_direction);
  967. } else {
  968. gt.elements[2] -= collision.travel;
  969. }
  970. set_global_transform(gt);
  971. return Vector2();
  972. }
  973. }
  974. if (sliding_enabled || !on_floor) {
  975. motion = collision.remainder.slide(collision.normal);
  976. body_velocity = body_velocity.slide(collision.normal);
  977. } else {
  978. motion = collision.remainder;
  979. }
  980. }
  981. sliding_enabled = true;
  982. }
  983. if (!found_collision || motion == Vector2()) {
  984. break;
  985. }
  986. }
  987. if (was_on_floor && p_snap != Vector2() && !on_floor) {
  988. // Apply snap.
  989. Collision col;
  990. Transform2D gt = get_global_transform();
  991. if (move_and_collide(p_snap, p_infinite_inertia, col, false, true, false)) {
  992. bool apply = true;
  993. if (up_direction != Vector2()) {
  994. if (Math::acos(col.normal.dot(up_direction)) <= p_floor_max_angle + FLOOR_ANGLE_THRESHOLD) {
  995. on_floor = true;
  996. floor_normal = col.normal;
  997. on_floor_body = col.collider_rid;
  998. floor_velocity = col.collider_vel;
  999. if (p_stop_on_slope) {
  1000. // move and collide may stray the object a bit because of pre un-stucking,
  1001. // so only ensure that motion happens on floor direction in this case.
  1002. if (col.travel.length() > margin) {
  1003. col.travel = up_direction * up_direction.dot(col.travel);
  1004. } else {
  1005. col.travel = Vector2();
  1006. }
  1007. }
  1008. } else {
  1009. apply = false;
  1010. }
  1011. }
  1012. if (apply) {
  1013. gt.elements[2] += col.travel;
  1014. set_global_transform(gt);
  1015. }
  1016. }
  1017. }
  1018. if (moving_platform_apply_velocity_on_leave != PLATFORM_VEL_ON_LEAVE_NEVER) {
  1019. // Add last platform velocity when just left a moving platform.
  1020. if (!on_floor) {
  1021. if (moving_platform_apply_velocity_on_leave == PLATFORM_VEL_ON_LEAVE_UPWARD_ONLY && current_floor_velocity.dot(up_direction) < 0) {
  1022. current_floor_velocity = current_floor_velocity.slide(up_direction);
  1023. }
  1024. return body_velocity + current_floor_velocity;
  1025. }
  1026. }
  1027. return body_velocity;
  1028. }
  1029. Vector2 KinematicBody2D::move_and_slide(const Vector2 &p_linear_velocity, const Vector2 &p_up_direction, bool p_stop_on_slope, int p_max_slides, float p_floor_max_angle, bool p_infinite_inertia) {
  1030. return _move_and_slide_internal(p_linear_velocity, Vector2(), p_up_direction, p_stop_on_slope, p_max_slides, p_floor_max_angle, p_infinite_inertia);
  1031. }
  1032. Vector2 KinematicBody2D::move_and_slide_with_snap(const Vector2 &p_linear_velocity, const Vector2 &p_snap, const Vector2 &p_up_direction, bool p_stop_on_slope, int p_max_slides, float p_floor_max_angle, bool p_infinite_inertia) {
  1033. return _move_and_slide_internal(p_linear_velocity, p_snap, p_up_direction, p_stop_on_slope, p_max_slides, p_floor_max_angle, p_infinite_inertia);
  1034. }
  1035. void KinematicBody2D::_set_collision_direction(const Collision &p_collision, const Vector2 &p_up_direction, float p_floor_max_angle) {
  1036. if (p_up_direction == Vector2()) {
  1037. //all is a wall
  1038. on_wall = true;
  1039. } else {
  1040. if (Math::acos(p_collision.normal.dot(p_up_direction)) <= p_floor_max_angle + FLOOR_ANGLE_THRESHOLD) { //floor
  1041. on_floor = true;
  1042. floor_normal = p_collision.normal;
  1043. on_floor_body = p_collision.collider_rid;
  1044. floor_velocity = p_collision.collider_vel;
  1045. } else if (Math::acos(p_collision.normal.dot(-p_up_direction)) <= p_floor_max_angle + FLOOR_ANGLE_THRESHOLD) { //ceiling
  1046. on_ceiling = true;
  1047. } else {
  1048. on_wall = true;
  1049. }
  1050. }
  1051. }
  1052. bool KinematicBody2D::is_on_floor() const {
  1053. return on_floor;
  1054. }
  1055. bool KinematicBody2D::is_on_wall() const {
  1056. return on_wall;
  1057. }
  1058. bool KinematicBody2D::is_on_ceiling() const {
  1059. return on_ceiling;
  1060. }
  1061. Vector2 KinematicBody2D::get_floor_normal() const {
  1062. return floor_normal;
  1063. }
  1064. real_t KinematicBody2D::get_floor_angle(const Vector2 &p_up_direction) const {
  1065. ERR_FAIL_COND_V(p_up_direction == Vector2(), 0);
  1066. return Math::acos(floor_normal.dot(p_up_direction));
  1067. }
  1068. Vector2 KinematicBody2D::get_floor_velocity() const {
  1069. return floor_velocity;
  1070. }
  1071. void KinematicBody2D::set_moving_platform_apply_velocity_on_leave(MovingPlatformApplyVelocityOnLeave p_on_leave_apply_velocity) {
  1072. moving_platform_apply_velocity_on_leave = p_on_leave_apply_velocity;
  1073. }
  1074. KinematicBody2D::MovingPlatformApplyVelocityOnLeave KinematicBody2D::get_moving_platform_apply_velocity_on_leave() const {
  1075. return moving_platform_apply_velocity_on_leave;
  1076. }
  1077. bool KinematicBody2D::test_move(const Transform2D &p_from, const Vector2 &p_motion, bool p_infinite_inertia) {
  1078. ERR_FAIL_COND_V(!is_inside_tree(), false);
  1079. Physics2DServer::MotionResult result;
  1080. bool colliding = Physics2DServer::get_singleton()->body_test_motion(get_rid(), p_from, p_motion, p_infinite_inertia, margin, &result);
  1081. if (colliding) {
  1082. // Don't report collision when the whole motion is done.
  1083. return (result.collision_safe_fraction < 1.0);
  1084. } else {
  1085. return false;
  1086. }
  1087. }
  1088. void KinematicBody2D::set_safe_margin(float p_margin) {
  1089. margin = p_margin;
  1090. }
  1091. float KinematicBody2D::get_safe_margin() const {
  1092. return margin;
  1093. }
  1094. int KinematicBody2D::get_slide_count() const {
  1095. return colliders.size();
  1096. }
  1097. KinematicBody2D::Collision KinematicBody2D::get_slide_collision(int p_bounce) const {
  1098. ERR_FAIL_INDEX_V(p_bounce, colliders.size(), Collision());
  1099. return colliders[p_bounce];
  1100. }
  1101. Ref<KinematicCollision2D> KinematicBody2D::_get_slide_collision(int p_bounce) {
  1102. ERR_FAIL_INDEX_V(p_bounce, colliders.size(), Ref<KinematicCollision2D>());
  1103. if (p_bounce >= slide_colliders.size()) {
  1104. slide_colliders.resize(p_bounce + 1);
  1105. }
  1106. // Create a new instance when the cached reference is invalid or still in use in script.
  1107. if (slide_colliders[p_bounce].is_null() || slide_colliders[p_bounce]->reference_get_count() > 1) {
  1108. slide_colliders.write[p_bounce].instance();
  1109. slide_colliders.write[p_bounce]->owner = this;
  1110. }
  1111. slide_colliders.write[p_bounce]->collision = colliders[p_bounce];
  1112. return slide_colliders[p_bounce];
  1113. }
  1114. Ref<KinematicCollision2D> KinematicBody2D::_get_last_slide_collision() {
  1115. if (colliders.size() == 0) {
  1116. return Ref<KinematicCollision2D>();
  1117. }
  1118. return _get_slide_collision(colliders.size() - 1);
  1119. }
  1120. void KinematicBody2D::set_sync_to_physics(bool p_enable) {
  1121. if (sync_to_physics == p_enable) {
  1122. return;
  1123. }
  1124. sync_to_physics = p_enable;
  1125. if (Engine::get_singleton()->is_editor_hint()) {
  1126. return;
  1127. }
  1128. if (p_enable) {
  1129. Physics2DServer::get_singleton()->body_set_force_integration_callback(get_rid(), this, "_direct_state_changed");
  1130. set_only_update_transform_changes(true);
  1131. set_notify_local_transform(true);
  1132. } else {
  1133. Physics2DServer::get_singleton()->body_set_force_integration_callback(get_rid(), nullptr, "");
  1134. set_only_update_transform_changes(false);
  1135. set_notify_local_transform(false);
  1136. }
  1137. }
  1138. bool KinematicBody2D::is_sync_to_physics_enabled() const {
  1139. return sync_to_physics;
  1140. }
  1141. void KinematicBody2D::_direct_state_changed(Object *p_state) {
  1142. if (!sync_to_physics) {
  1143. return;
  1144. }
  1145. Physics2DDirectBodyState *state = Object::cast_to<Physics2DDirectBodyState>(p_state);
  1146. ERR_FAIL_COND_MSG(!state, "Method '_direct_state_changed' must receive a valid Physics2DDirectBodyState object as argument");
  1147. last_valid_transform = state->get_transform();
  1148. set_notify_local_transform(false);
  1149. set_global_transform(last_valid_transform);
  1150. set_notify_local_transform(true);
  1151. }
  1152. void KinematicBody2D::_notification(int p_what) {
  1153. if (p_what == NOTIFICATION_ENTER_TREE) {
  1154. last_valid_transform = get_global_transform();
  1155. // Reset move_and_slide() data.
  1156. on_floor = false;
  1157. on_floor_body = RID();
  1158. on_ceiling = false;
  1159. on_wall = false;
  1160. colliders.clear();
  1161. floor_velocity = Vector2();
  1162. }
  1163. if (p_what == NOTIFICATION_LOCAL_TRANSFORM_CHANGED) {
  1164. //used by sync to physics, send the new transform to the physics
  1165. Transform2D new_transform = get_global_transform();
  1166. Physics2DServer::get_singleton()->body_set_state(get_rid(), Physics2DServer::BODY_STATE_TRANSFORM, new_transform);
  1167. //but then revert changes
  1168. set_notify_local_transform(false);
  1169. set_global_transform(last_valid_transform);
  1170. set_notify_local_transform(true);
  1171. }
  1172. }
  1173. void KinematicBody2D::_bind_methods() {
  1174. ClassDB::bind_method(D_METHOD("move_and_collide", "rel_vec", "infinite_inertia", "exclude_raycast_shapes", "test_only"), &KinematicBody2D::_move, DEFVAL(true), DEFVAL(true), DEFVAL(false));
  1175. ClassDB::bind_method(D_METHOD("move_and_slide", "linear_velocity", "up_direction", "stop_on_slope", "max_slides", "floor_max_angle", "infinite_inertia"), &KinematicBody2D::move_and_slide, DEFVAL(Vector2(0, 0)), DEFVAL(false), DEFVAL(4), DEFVAL(Math::deg2rad((float)45)), DEFVAL(true));
  1176. ClassDB::bind_method(D_METHOD("move_and_slide_with_snap", "linear_velocity", "snap", "up_direction", "stop_on_slope", "max_slides", "floor_max_angle", "infinite_inertia"), &KinematicBody2D::move_and_slide_with_snap, DEFVAL(Vector2(0, 0)), DEFVAL(false), DEFVAL(4), DEFVAL(Math::deg2rad((float)45)), DEFVAL(true));
  1177. ClassDB::bind_method(D_METHOD("test_move", "from", "rel_vec", "infinite_inertia"), &KinematicBody2D::test_move, DEFVAL(true));
  1178. ClassDB::bind_method(D_METHOD("is_on_floor"), &KinematicBody2D::is_on_floor);
  1179. ClassDB::bind_method(D_METHOD("is_on_ceiling"), &KinematicBody2D::is_on_ceiling);
  1180. ClassDB::bind_method(D_METHOD("is_on_wall"), &KinematicBody2D::is_on_wall);
  1181. ClassDB::bind_method(D_METHOD("get_floor_normal"), &KinematicBody2D::get_floor_normal);
  1182. ClassDB::bind_method(D_METHOD("get_floor_angle", "up_direction"), &KinematicBody2D::get_floor_angle, DEFVAL(Vector2(0.0, -1.0)));
  1183. ClassDB::bind_method(D_METHOD("get_floor_velocity"), &KinematicBody2D::get_floor_velocity);
  1184. ClassDB::bind_method(D_METHOD("set_safe_margin", "pixels"), &KinematicBody2D::set_safe_margin);
  1185. ClassDB::bind_method(D_METHOD("get_safe_margin"), &KinematicBody2D::get_safe_margin);
  1186. ClassDB::bind_method(D_METHOD("set_moving_platform_apply_velocity_on_leave", "on_leave_apply_velocity"), &KinematicBody2D::set_moving_platform_apply_velocity_on_leave);
  1187. ClassDB::bind_method(D_METHOD("get_moving_platform_apply_velocity_on_leave"), &KinematicBody2D::get_moving_platform_apply_velocity_on_leave);
  1188. ClassDB::bind_method(D_METHOD("get_slide_count"), &KinematicBody2D::get_slide_count);
  1189. ClassDB::bind_method(D_METHOD("get_slide_collision", "slide_idx"), &KinematicBody2D::_get_slide_collision);
  1190. ClassDB::bind_method(D_METHOD("get_last_slide_collision"), &KinematicBody2D::_get_last_slide_collision);
  1191. ClassDB::bind_method(D_METHOD("set_sync_to_physics", "enable"), &KinematicBody2D::set_sync_to_physics);
  1192. ClassDB::bind_method(D_METHOD("is_sync_to_physics_enabled"), &KinematicBody2D::is_sync_to_physics_enabled);
  1193. ClassDB::bind_method(D_METHOD("_direct_state_changed"), &KinematicBody2D::_direct_state_changed);
  1194. ADD_PROPERTY(PropertyInfo(Variant::REAL, "collision/safe_margin", PROPERTY_HINT_RANGE, "0.001,256,0.001"), "set_safe_margin", "get_safe_margin");
  1195. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "motion/sync_to_physics"), "set_sync_to_physics", "is_sync_to_physics_enabled");
  1196. ADD_GROUP("Moving Platform", "moving_platform");
  1197. ADD_PROPERTY(PropertyInfo(Variant::INT, "moving_platform_apply_velocity_on_leave", PROPERTY_HINT_ENUM, "Always,Upward Only,Never", PROPERTY_USAGE_DEFAULT), "set_moving_platform_apply_velocity_on_leave", "get_moving_platform_apply_velocity_on_leave");
  1198. BIND_ENUM_CONSTANT(PLATFORM_VEL_ON_LEAVE_ALWAYS);
  1199. BIND_ENUM_CONSTANT(PLATFORM_VEL_ON_LEAVE_UPWARD_ONLY);
  1200. BIND_ENUM_CONSTANT(PLATFORM_VEL_ON_LEAVE_NEVER);
  1201. }
  1202. KinematicBody2D::KinematicBody2D() :
  1203. PhysicsBody2D(Physics2DServer::BODY_MODE_KINEMATIC) {
  1204. margin = 0.08;
  1205. on_floor = false;
  1206. on_ceiling = false;
  1207. on_wall = false;
  1208. sync_to_physics = false;
  1209. }
  1210. KinematicBody2D::~KinematicBody2D() {
  1211. if (motion_cache.is_valid()) {
  1212. motion_cache->owner = nullptr;
  1213. }
  1214. for (int i = 0; i < slide_colliders.size(); i++) {
  1215. if (slide_colliders[i].is_valid()) {
  1216. slide_colliders.write[i]->owner = nullptr;
  1217. }
  1218. }
  1219. }
  1220. ////////////////////////
  1221. Vector2 KinematicCollision2D::get_position() const {
  1222. return collision.collision;
  1223. }
  1224. Vector2 KinematicCollision2D::get_normal() const {
  1225. return collision.normal;
  1226. }
  1227. Vector2 KinematicCollision2D::get_travel() const {
  1228. return collision.travel;
  1229. }
  1230. Vector2 KinematicCollision2D::get_remainder() const {
  1231. return collision.remainder;
  1232. }
  1233. real_t KinematicCollision2D::get_angle(const Vector2 &p_up_direction) const {
  1234. ERR_FAIL_COND_V(p_up_direction == Vector2(), 0);
  1235. return collision.get_angle(p_up_direction);
  1236. }
  1237. Object *KinematicCollision2D::get_local_shape() const {
  1238. if (!owner) {
  1239. return nullptr;
  1240. }
  1241. uint32_t ownerid = owner->shape_find_owner(collision.local_shape);
  1242. return owner->shape_owner_get_owner(ownerid);
  1243. }
  1244. Object *KinematicCollision2D::get_collider() const {
  1245. if (collision.collider) {
  1246. return ObjectDB::get_instance(collision.collider);
  1247. }
  1248. return nullptr;
  1249. }
  1250. ObjectID KinematicCollision2D::get_collider_id() const {
  1251. return collision.collider;
  1252. }
  1253. RID KinematicCollision2D::get_collider_rid() const {
  1254. return collision.collider_rid;
  1255. }
  1256. Object *KinematicCollision2D::get_collider_shape() const {
  1257. Object *collider = get_collider();
  1258. if (collider) {
  1259. CollisionObject2D *obj2d = Object::cast_to<CollisionObject2D>(collider);
  1260. if (obj2d) {
  1261. uint32_t ownerid = obj2d->shape_find_owner(collision.collider_shape);
  1262. return obj2d->shape_owner_get_owner(ownerid);
  1263. }
  1264. }
  1265. return nullptr;
  1266. }
  1267. int KinematicCollision2D::get_collider_shape_index() const {
  1268. return collision.collider_shape;
  1269. }
  1270. Vector2 KinematicCollision2D::get_collider_velocity() const {
  1271. return collision.collider_vel;
  1272. }
  1273. Variant KinematicCollision2D::get_collider_metadata() const {
  1274. return Variant();
  1275. }
  1276. void KinematicCollision2D::_bind_methods() {
  1277. ClassDB::bind_method(D_METHOD("get_position"), &KinematicCollision2D::get_position);
  1278. ClassDB::bind_method(D_METHOD("get_normal"), &KinematicCollision2D::get_normal);
  1279. ClassDB::bind_method(D_METHOD("get_travel"), &KinematicCollision2D::get_travel);
  1280. ClassDB::bind_method(D_METHOD("get_remainder"), &KinematicCollision2D::get_remainder);
  1281. ClassDB::bind_method(D_METHOD("get_angle", "up_direction"), &KinematicCollision2D::get_angle, DEFVAL(Vector2(0.0, -1.0)));
  1282. ClassDB::bind_method(D_METHOD("get_local_shape"), &KinematicCollision2D::get_local_shape);
  1283. ClassDB::bind_method(D_METHOD("get_collider"), &KinematicCollision2D::get_collider);
  1284. ClassDB::bind_method(D_METHOD("get_collider_id"), &KinematicCollision2D::get_collider_id);
  1285. ClassDB::bind_method(D_METHOD("get_collider_rid"), &KinematicCollision2D::get_collider_rid);
  1286. ClassDB::bind_method(D_METHOD("get_collider_shape"), &KinematicCollision2D::get_collider_shape);
  1287. ClassDB::bind_method(D_METHOD("get_collider_shape_index"), &KinematicCollision2D::get_collider_shape_index);
  1288. ClassDB::bind_method(D_METHOD("get_collider_velocity"), &KinematicCollision2D::get_collider_velocity);
  1289. ClassDB::bind_method(D_METHOD("get_collider_metadata"), &KinematicCollision2D::get_collider_metadata);
  1290. ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "position"), "", "get_position");
  1291. ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "normal"), "", "get_normal");
  1292. ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "travel"), "", "get_travel");
  1293. ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "remainder"), "", "get_remainder");
  1294. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "local_shape"), "", "get_local_shape");
  1295. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "collider"), "", "get_collider");
  1296. ADD_PROPERTY(PropertyInfo(Variant::INT, "collider_id"), "", "get_collider_id");
  1297. ADD_PROPERTY(PropertyInfo(Variant::_RID, "collider_rid"), "", "get_collider_rid");
  1298. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "collider_shape"), "", "get_collider_shape");
  1299. ADD_PROPERTY(PropertyInfo(Variant::INT, "collider_shape_index"), "", "get_collider_shape_index");
  1300. ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "collider_velocity"), "", "get_collider_velocity");
  1301. ADD_PROPERTY(PropertyInfo(Variant::NIL, "collider_metadata", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NIL_IS_VARIANT), "", "get_collider_metadata");
  1302. }
  1303. KinematicCollision2D::KinematicCollision2D() {
  1304. collision.collider = 0;
  1305. collision.collider_shape = 0;
  1306. collision.local_shape = 0;
  1307. owner = nullptr;
  1308. }