Ruby/Gosu getting a bouncing image

239 Views Asked by At

I'm following the book "Learn game programming with ruby" one of the exercises is loading an image with gosu and making it bounce off the edges of the screen. I followed the exercise and the image bounces fine off the top and left corners but will sink past the edge of the screen for awhile before bouncing off the bottom and right sides.

require 'gosu'

class Window < Gosu::Window
def initialize
super(800, 600)
self.caption = 'First Game' 
 @blueheart = Gosu::Image.new('blueheart.png')
 @x = 200
@y = 200
@width = 50
@height = 43
@velocity_x = 2
@velocity_y = 2
@direction = 1 
end

def update

@x += @velocity_x
@y += @velocity_y
@velocity_x*= -1 if @x + @width /2 > 800 || @x - @width / 2 < 0
@velocity_y*= -1 if @y + @height /2 > 600 || @y - @height / 2 < 0


end



def draw
@blueheart.draw(@x - @width/2, @y - @height/2, 1)
end

end
window = Window.new

window.show 

I think it has something to do with how ruby uses the top right corner of the image as the coordinates for an image but I thought

@blueheart.draw(@x - @width/2, @y - @height/2, 1)

was supposed to fix that, How can I make it work like I want? Thanks in advance

1

There are 1 best solutions below

0
On

The Problem came from me creating my own sprites and not realizing the height and width values would be different.

changing the code to @width = @blueheart.width gave me a crash but I just changed the values to the proper width and height and fixed the problem. the values @width = 50 and @height = 43 were referring to different sprite sizes in the book.