Last Updated: February 25, 2016
·
1.671K
· tjbladez

Ruby OpenGL Walk Bounce

Pretty bouncing effect that gives an illusion that you are walking forward

Normally we would move the camera around and draw the 3D environment relative to the camera position. Here is a trick on how to do it very inexpensively.

  1. Rotate and translate the camera position according to user commands
  2. Rotate the world around the origin in the opposite direction of the camera rotation (giving the illusion that the camera has been rotated)
  3. Translate the world in the opposite manner that the camera has been translated (again, giving the illusion that the camera has moved)

    def update
      @ang_conv = 0.0174532925 # pi / 180
      @y_ang -= 1.5 if button? Button::KbRight
      @y_ang += 1.5 if button? Button::KbLeft
    
      if button?(Button::KbUp)
        @x_pos -= Math.sin(@y_ang * @ang_conv) * 0.05
        @z_diff -= Math.cos(@y_ang * @ang_conv) * 0.05
        @bounce_ang > 359 ? @bounce_ang = 0 : @bounce_ang += 10
        @bouncing = Math.sin(@bounce_ang * @ang_conv) / 20
      end
    
      if button?(Button::KbDown)
        @x_pos += Math.sin(@y_ang * @ang_conv) * 0.05
        @z_diff += Math.cos(@y_ang * @ang_conv) * 0.05
        @bounce_ang <= 1 ? @bounce_ang = 359 : @bounce_ang -= 10
        @bouncing = Math.sin(@bounce_ang * @ang_conv) / 20
      end
    
      @z_diff -= 0.3 if button? Button::KbPageUp
      @z_diff += 0.3 if button? Button::KbPageDown
    
      @y_pos -= 0.05 if button? Button::KbW
      @y_pos += 0.05 if button? Button::KbS
      @x_pos += 0.05 if button? Button::KbD
      @x_pos -= 0.05 if button? Button::KbA
    end
    
    def draw
      x = -@x_pos
      y = -@bouncing - 0.25
      z = -@z_diff
      scene_angle = 360 - @y_ang
      gl 
        glRotatef(@z_diff,1,0,0) #rotate to be able to look up or down
        glRotatef(scene_angle,0,1,0); #rotate on direction user is facing
        glTranslate(x, y, z) #translate the world in opposite of camera
      end
    end