Godot 3 Tutorial–2D Physics

This video tutorial covers using the 2D physics system built into Godot 3.  We will cover simple collisions using Area2D, then full blown physics simulations using Rigid Bodies, Kinematic Bodies and Static Bodies, showing how to respond to collisions using code.  Finally we look at collision masks and layers to control what physic objects collide with other objects in your simulation.

The Video

Assets and Code Samples

Gravity.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")

KinematicBody2d.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

Back to Tutorial Series Homepage

Scroll to Top