Ruotare un cubo sul suo asse Y usando OpenGL
Vai alla navigazione
Vai alla ricerca
Mostreremo un possibile codice, usando OpenGL, con il quale verrà disegnato un cubo che ruota in 3D attorno al suo asse verticale centrale (asse Y), perpendicolare alla faccia superiore e inferiore.
E' necessario attivare una GLArea, un Timer, il Componente grafico per la compatibilità con OpenGL (ad esempio: gb.gui.qt.opengl), nonché i Componenti:
- gb.opengl
- gb.opengl.glu
Private angle As Float
Public Sub Form_Open()
Me.Center
Me.W = 640
Me.H = 640
With GLArea1
.X = 0
.Y = 0
.W = Me.W
.H = Me.H
End With
Timer1.Delay = 16
Timer1.Start
End
Public Sub Timer1_Timer()
angle += 1
If angle >= 360 Then angle = 0
GLArea1.Refresh
End
Public Sub GLArea1_Resize()
Dim w As Integer = GLArea1.W
Dim h As Integer = GLArea1.H
If h = 0 Then h = 1
GL.Viewport(0, 0, w, h)
GL.MatrixMode(GL.PROJECTION)
GL.LoadIdentity()
GLU.Perspective(45.0, w / h, 1.0, 100.0)
GL.MatrixMode(GL.MODELVIEW)
End
Public Sub GLArea1_Draw()
' Pulisce i buffer colore e profondità:
GL.Clear(GL.COLOR_BUFFER_BIT Or GL.DEPTH_BUFFER_BIT)
' Abilita il test di profondità per corretto disegno 3D:
GL.Enable(GL.DEPTH_TEST)
' Colore di sfondo:
GL.ClearColor(0.1, 0.1, 0.1, 1.0)
' Reset della matrice di trasformazione:
GL.LoadIdentity()
' Allontana la "camera", ossia il punto di vista dell'osservatore:
GL.Translatef(0.0, 0.0, -8.0)
' Rotazione solo intorno all'asse Y (verticale):
GL.Rotatef(angle, 0.0, 1.0, 0.0)
' Disegna il cubo:
DrawCube()
' Finalizza il rendering:
GL.Flush()
End
Private Sub DrawCube()
Dim vertices As Float[][] = [[-1.0, -1.0, -1.0], [1.0, -1.0, -1.0], [1.0, 1.0, -1.0], [-1.0, 1.0, -1.0],
[-1.0, -1.0, 1.0], [1.0, -1.0, 1.0], [1.0, 1.0, 1.0], [-1.0, 1.0, 1.0]]
Dim faces As Integer[][] = [[0, 1, 2, 3], [1, 5, 6, 2], [5, 4, 7, 6],
[4, 0, 3, 7], [3, 2, 6, 7], [0, 4, 5, 1]]
Dim colors As Float[][] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0],
[1.0, 1.0, 0.0], [1.0, 0.0, 1.0], [0.0, 1.0, 1.0]]
For i As Integer = 0 To 5
GL.Color3f(colors[i][0], colors[i][1], colors[i][2])
GL.Begin(GL.QUADS)
For j As Integer = 0 To 3
GL.Vertex3f(vertices[faces[i][j]][0], vertices[faces[i][j]][1], vertices[faces[i][j]][2])
Next
GL.End
Next
End