1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Loading and Displaying Your Sprite

By

4 of 5

The Sprite Class

A basic sprite can be created with a very simple class that loads the image and sets up the rect variable in the constructor. The rect variable can be obtained from the image itself by calling make_rect on the image, which will return a rect position at 0,0 and have the same width and height as the image. The rect can then be positioned in the world by using its center method.

class Player
  include Sprites::Sprite
  def initialize
    @image = Surface['player.png']
    @rect = @image.make_rect
    @rect.center = [320, 450]
  end
end
 

This class is dead-simple. The include method is used to extend the class with the Sprites::Sprite mixin. This mixin provides the draw method, which, among other things, makes this class a "sprite" instead of some abstract player class. Next, in the initialize method, the @image is loaded and the @rect is constructed using the image and positioned using the center method.

  1. About.com
  2. Technology
  3. Ruby
  4. Tutorials
  5. Game Programming
  6. The Sprite Class

©2014 About.com. All rights reserved.