Guest User

Basics #4 in Scala

a guest
Jul 11th, 2012
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. import org.lwjgl.LWJGLException
  2. import org.lwjgl.{Sys => LWJGLSys}
  3. import org.lwjgl.input.Keyboard
  4. import org.lwjgl.opengl.{Display, DisplayMode}
  5. import org.lwjgl.opengl.GL11._
  6.  
  7. object TimerExample {
  8.  
  9. var x: Float = 400
  10. var y: Float = 300
  11. var rotation: Float = 0
  12.  
  13. var lastFrame: Long = getTime()
  14.  
  15. var fps: Int = 0
  16. var lastFPS: Long = getTime()
  17.  
  18. def start() : Unit = {
  19. try {
  20. Display.setDisplayMode(new DisplayMode(800,600))
  21. Display.create()
  22. } catch {
  23. case e: LWJGLException => {
  24. e.printStackTrace()
  25. sys.exit(1)
  26. }
  27. }
  28.  
  29. initGL()
  30. getDelta()
  31. lastFPS = getTime()
  32.  
  33. while (!Display.isCloseRequested()) {
  34. val delta = getDelta()
  35.  
  36. update(delta)
  37. renderGL()
  38.  
  39. Display.update()
  40. Display.sync(60)
  41.  
  42. }
  43.  
  44. Display.destroy()
  45.  
  46. }
  47.  
  48. def update(delta: Int) : Unit = {
  49. rotation += 0.15f * delta
  50. if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)) x -= 0.35f * delta
  51. if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) x += 0.35f * delta
  52. if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) y -= 0.35f * delta
  53. if (Keyboard.isKeyDown(Keyboard.KEY_UP)) y += 0.35f * delta
  54.  
  55. if (x < 0) x = 0
  56. if (x > 800) x = 800
  57. if (y < 0) y = 0
  58. if (y > 600) y = 600
  59.  
  60. updateFPS()
  61. }
  62.  
  63. def getDelta() : Int = {
  64. val time = getTime()
  65. val delta = time - lastFrame.toLong
  66. lastFrame = time
  67. delta.toInt
  68. }
  69.  
  70. def getTime() : Long = {
  71. (LWJGLSys.getTime() * 1000) / LWJGLSys.getTimerResolution()
  72. }
  73.  
  74. def updateFPS() : Unit = {
  75. if (getTime() - lastFPS > 1000) {
  76. Display.setTitle("FPS: " + fps)
  77. fps = 0
  78. lastFPS += 1000
  79. }
  80. fps += 1
  81. }
  82.  
  83. def initGL() : Unit = {
  84. glMatrixMode(GL_PROJECTION)
  85. glLoadIdentity()
  86. glOrtho(0, 800, 0, 600, 1, -1)
  87. glMatrixMode(GL_MODELVIEW)
  88. }
  89.  
  90. def renderGL() : Unit = {
  91. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
  92.  
  93. glColor3f(0.5f, 0.5f, 1.0f)
  94.  
  95. glPushMatrix()
  96. glTranslatef(x,y,0)
  97. glRotatef(rotation, 0f, 0f, 1f)
  98. glTranslatef(-x, -y, 0)
  99.  
  100. glBegin(GL_QUADS)
  101. glVertex2f( x - 50, y - 50 )
  102. glVertex2f( x + 50, y - 50 )
  103. glVertex2f( x + 50, y + 50 )
  104. glVertex2f( x - 50, y + 50 )
  105. glEnd()
  106. glPopMatrix()
  107.  
  108. }
  109.  
  110. def main(args: Array[String]): Unit = {
  111. start()
  112. }
  113.  
  114. }
Advertisement
Add Comment
Please, Sign In to add comment