Este video tutorial cubre el uso del sistema de física 2D integrado en Godot 3. Cubriremos colisiones simples usando Area2D, luego simulaciones físicas completas usando cuerpos rígidos, cuerpos cinemáticos y cuerpos estáticos, mostrando cómo responder a colisiones usando código. Finalmente, observamos las máscaras y capas de colisión para controlar qué objetos físicos chocan con otros objetos en su simulación.
El video
Activos y muestras de código
Gravedad.gd
extends Node func _ready(): pass func _process(delta): #impulsePoint is the position relative to the objects center to apply the impulse var impulsePoint = Vector2(0.0,$RigidBody2D/CollisionShape2D.shape.extents.y/2) #The impulse amount is impulse * mass added directly to the linear velocity if Input.is_mouse_button_pressed(BUTTON_LEFT): $RigidBody2D.apply_impulse(impulsePoint,Vector2(0,-10)) if Input.is_mouse_button_pressed(BUTTON_RIGHT): $RigidBody2D.apply_impulse(impulsePoint,Vector2(0,10)) func _on_RigidBody2D_body_entered(body): print("Collision with " + body.get_name())
CircleShapeController.gd
extends Area2D func _process(delta): if Input.is_key_pressed(KEY_RIGHT): self.move_local_x(5) if Input.is_key_pressed(KEY_LEFT): self.move_local_x(-5) if Input.is_key_pressed(KEY_UP): self.move_local_y(-5) if Input.is_key_pressed(KEY_DOWN): self.move_local_y(5) pass func _on_Area2D_area_entered(area): print("Entered area!") func _on_Area2D_area_exited(area): print("Area exited")
CinemáticaCuerpo2d.gd
extends KinematicBody2D func _physics_process(delta): var moveBy = Vector2(0,0) if Input.is_key_pressed(KEY_LEFT): moveBy = Vector2(-5,0) if Input.is_key_pressed(KEY_RIGHT): moveBy = Vector2(5,0) if Input.is_key_pressed(KEY_UP): moveBy = Vector2(0,-5) if Input.is_key_pressed(KEY_DOWN): moveBy = Vector2(0,5) self.move_and_collide(moveBy)
KinematicBody2dSlide.gd
extends KinematicBody2D var priorFrame = Vector2(0,0) func _physics_process(delta): var moveBy = Vector2(0,0) if Input.is_key_pressed(KEY_LEFT): moveBy = Vector2(-50,0) if Input.is_key_pressed(KEY_RIGHT): moveBy = Vector2(50,0) if Input.is_key_pressed(KEY_UP): moveBy = Vector2(0,-250) if Input.is_key_pressed(KEY_DOWN): moveBy = Vector2(0,50) self.move_and_slide(moveBy,Vector2(0,-1)) if(is_on_floor()): print("Currently on Floor") # If we aren't currently on the floor, lets simulate gravity to pull us downwards else: self.move_and_collide(Vector2(0,1)) if(is_on_ceiling()): print("Currently on Ceiling") if(self.get_slide_count() > 0): var collide = self.get_slide_collision(0).collider print(collide.rotation) if collide.is_class("StaticBody2D"): self.rotation = collide.rotation