How do you process collisions in DragonRuby Game Toolkit?

Viewed 201

I'm using DragonRuby Game Toolkit to build a game.

How do I detect if one object such as a Sprite is colliding with another Sprite?

Here are two sprites placed on the screen. With a todo of how to check collision:

def tick args
  # create a sprite
  args.state.sprite_one = { x: 100,
                            y: 200,
                            w: 50,
                            h: 50 } 
    
  # create another sprite that definitely collides
  args.state.sprite_two = { x: 101, 
                            y: 201, 
                            w:  1,
                            h:  1 }
  
  sprites_collide = ????? # help
  
  if sprites_collide
    args.gtk.notify! "sprites collide!"
  else
    args.gtk.notify! "sprites do not collide!"
  end
end
1 Answers

Use the intersect_rect? method. This method is available on Array, Hash, and any class that uses the attr_sprite class method. The source for intersect_rect? is here.

For this specific example you would do:

sprites_collide = args.state.sprite_one.intersect_rect? args.state.sprite_two
Related