Membuat benteng atau catur pada pemrograman grafis bisa Anda gunakan untuk tugas kuliah atau untuk belajar. Selain itu, coding dibawah ini masih bisa Anda ubah-ubah.
Contoh coding membuat benteng ini juga bisa digerakkan menggunakan tombol keyboard.
Berikut tombol keyboard untuk menggerakkan objek benteng atau catur :
Tombol W : untuk memindahkan objek ke atas.
Tombol A : untuk memindahkan objek ke kiri.
Tombol S : untuk memindahkan objek ke bawah.
Tombol D : untuk memindahkan objek ke kanan.
Anda juga bisa mengubah atau menambah tombol keyboard yang lain. Tergantung selera Anda mau dipindahkan kemana objek benter atau catur tersebut.
Terdapat 3 buah files java, yaitu : benteng.java, objek.java dan GLRenderer.java. Perhatikan file-file tersebut jangan ada yang tertinggal. Agar tidak terjadi error.
Berikut adalah coding dari Benteng.java :
Berikut adalah coding dari Objek.java :
Berikut adalah coding dari GLRenderer.java :
Contoh coding membuat benteng ini juga bisa digerakkan menggunakan tombol keyboard.
Berikut tombol keyboard untuk menggerakkan objek benteng atau catur :
Tombol W : untuk memindahkan objek ke atas.
Tombol A : untuk memindahkan objek ke kiri.
Tombol S : untuk memindahkan objek ke bawah.
Tombol D : untuk memindahkan objek ke kanan.
Anda juga bisa mengubah atau menambah tombol keyboard yang lain. Tergantung selera Anda mau dipindahkan kemana objek benter atau catur tersebut.
Terdapat 3 buah files java, yaitu : benteng.java, objek.java dan GLRenderer.java. Perhatikan file-file tersebut jangan ada yang tertinggal. Agar tidak terjadi error.
Berikut adalah coding dari Benteng.java :
package org.yourorghere; import com.sun.opengl.util.Animator; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Level; import java.util.logging.Logger; import javax.media.opengl.GLCanvas; import javax.media.opengl.GLCapabilities; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPopupMenu; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.UIManager; import javax.swing.WindowConstants; public class Benteng extends JFrame { static { // When using a GLCanvas, we have to set the Popup-Menues to be HeavyWeight, // so they display properly on top of the GLCanvas JPopupMenu.setDefaultLightWeightPopupEnabled(false); } private Animator animator; /** Creates new form MainFrame */ public Benteng() { initComponents(); final GLRenderer glrender = new GLRenderer(); KeyListener mylisterner = new KeyListener() { public void keyTyped(KeyEvent e) { System.out.println("typed "+e.getKeyCode()); } public void keyPressed(KeyEvent e) { System.out.println("pressed "+e.getKeyCode()); glrender.Key_Pressed(e.getKeyCode()); canvas.repaint(); } public void keyReleased(KeyEvent e) { System.out.println("released "+e.getKeyCode()); } }; canvas.addGLEventListener(glrender); Timer mytimer = new Timer(); TimerTask mytimertask = new TimerTask() { @Override public void run() { //glrender.draw_text(glut, gl); canvas.repaint(); //To change body of generated methods, choose Tools | Templates. } }; mytimer.schedule(mytimertask, 100, 100); addKeyListener(mylisterner); animator = new Animator(canvas); this.setLocationRelativeTo(null); this.setSize(600,400); animator = new Animator(canvas); // This is a workaround for the GLCanvas not adjusting its size, when the frame is resized. canvas.setMinimumSize(new Dimension()); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // Run this on another thread than the AWT event queue to // make sure the call to Animator.stop() completes before // exiting new Thread(new Runnable() { //Modul 8 – Camera and object rotation 8-4 public void run() { animator.stop(); System.exit(0); } }).start(); } }); } @Override public void setVisible(boolean show){ if(!show) animator.stop(); super.setVisible(show); if(!show) animator.start(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { JLabel label = new JLabel(); canvas = new GLCanvas(createGLCapabilites()); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); label.setText("Gunakan Keyboard untuk menggerakkan kamera"); GroupLayout layout = new GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(Alignment.LEADING) .addComponent(canvas, GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE) .addComponent(label)) .addContainerGap()) ); layout.setVerticalGroup( //Modul 8 – Camera and object rotation 8-5 layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(label) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(canvas, GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * Called from within initComponents(). * hint: to customize the generated code choose 'Customize Code' in the contextmenu * of the selected UI Component you wish to cutomize in design mode. * @return Returns customized GLCapabilities. */ private GLCapabilities createGLCapabilites() { GLCapabilities capabilities = new GLCapabilities(); capabilities.setHardwareAccelerated(true); // try to enable 2x anti aliasing - should be supported on most hardware capabilities.setNumSamples(2); capabilities.setSampleBuffers(true); return capabilities; } /** * @param args the command line arguments */ public static void main(String args[]) { // Run this in the AWT event thread to prevent deadlocks and race conditions EventQueue.invokeLater(new Runnable() { public void run() { // switch to system l&f for native font rendering etc. try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch(Exception ex) { //Modul 8 – Camera and object rotation 8-6 Logger.getLogger(getClass().getName()).log(Level.INFO, "can not enable system look and feel", ex); } Benteng frame = new Benteng(); frame.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private GLCanvas canvas; // End of variables declaration//GEN-END:variables }
Berikut adalah coding dari Objek.java :
package org.yourorghere; import com.sun.opengl.util.GLUT; import javax.media.opengl.GL; import javax.media.opengl.glu.GLU; import javax.media.opengl.glu.GLUquadric; public class Objek { static void Tabung(GL gl) { float amb[] = {0.34f, 0.34f, 2.34f, 1}; float diff[] = {2.41f, 0.41f, 1.41f, 1}; float spec[] = {0.11f, 2.11f, 0.11f, 1}; float shine = 200; gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT, amb, 0); gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_DIFFUSE, diff, 0); //Modul 8 – Camera and object rotation 8-14 gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR, spec, 0); gl.glMaterialf(GL.GL_FRONT_AND_BACK, GL.GL_SHININESS, shine); float BODY_LENGTH=5f; float BODY_RADIUS=2.0f; int SLICES=30; int STACKS=30; GLU glu=new GLU(); GLUquadric q=glu.gluNewQuadric(); glu.gluCylinder(q, BODY_RADIUS, BODY_RADIUS, BODY_LENGTH, SLICES, STACKS); glu.gluDisk(q, 0.0f, BODY_RADIUS, SLICES, STACKS); gl.glTranslatef(0.0f, 0.0f, BODY_LENGTH); glu.gluDisk(q, 0.0f, BODY_RADIUS, SLICES, STACKS); } static void TabungAtas(GL gl) { float amb[] = {1.34f, 0.34f, 0.34f, 1}; float diff[] = {0.41f, 0.41f, 0.41f, 1}; float spec[] = {0.11f, 1.11f, 0.11f, 1}; float shine = 200; gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT, amb, 0); gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_DIFFUSE, diff, 0); //Modul 8 – Camera and object rotation 8-14 gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR, spec, 0); gl.glMaterialf(GL.GL_FRONT_AND_BACK, GL.GL_SHININESS, shine); float BODY_LENGTH=1f; float BODY_RADIUS=3f; int SLICES=30; int STACKS=30; GLU glu=new GLU(); GLUquadric q=glu.gluNewQuadric(); glu.gluCylinder(q, BODY_RADIUS, BODY_RADIUS, BODY_LENGTH, SLICES, STACKS); glu.gluDisk(q, 0.0f, BODY_RADIUS, SLICES, STACKS); gl.glTranslatef(0.0f, 0.0f, BODY_LENGTH); glu.gluDisk(q, 0.0f, BODY_RADIUS, SLICES, STACKS); } static void TabungBawahKecil(GL gl) { float amb[] = {0.34f, 0.34f, 0.34f, 1}; float diff[] = {1.41f, 0.41f, 0.41f, 1}; float spec[] = {1.11f, 0.11f, 0.11f, 1}; float shine = 200; gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT, amb, 0); gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_DIFFUSE, diff, 0); //Modul 8 – Camera and object rotation 8-14 gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR, spec, 0); gl.glMaterialf(GL.GL_FRONT_AND_BACK, GL.GL_SHININESS, shine); float BODY_LENGTH=0.5f; float BODY_RADIUS=2.5f; int SLICES=30; int STACKS=30; GLU glu=new GLU(); GLUquadric q=glu.gluNewQuadric(); glu.gluCylinder(q, BODY_RADIUS, BODY_RADIUS, BODY_LENGTH, SLICES, STACKS); glu.gluDisk(q, 0.0f, BODY_RADIUS, SLICES, STACKS); gl.glTranslatef(0.0f, 0.0f, BODY_LENGTH); glu.gluDisk(q, 0.0f, BODY_RADIUS, SLICES, STACKS); } static void TabungBawah(GL gl) { float amb[] = {0.34f, 1.34f, 0.34f, 1}; float diff[] = {0.41f, 1.41f, 1.41f, 1}; float spec[] = {0.11f, .11f, 0.11f, 1}; float shine = 200; gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT, amb, 0); gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_DIFFUSE, diff, 0); //Modul 8 – Camera and object rotation 8-14 gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR, spec, 0); gl.glMaterialf(GL.GL_FRONT_AND_BACK, GL.GL_SHININESS, shine); float BODY_LENGTH=1.5f; float BODY_RADIUS=3f; int SLICES=30; int STACKS=30; GLU glu=new GLU(); GLUquadric q=glu.gluNewQuadric(); glu.gluCylinder(q, BODY_RADIUS, BODY_RADIUS, BODY_LENGTH, SLICES, STACKS); glu.gluDisk(q, 0.0f, BODY_RADIUS, SLICES, STACKS); gl.glTranslatef(0.0f, 0.0f, BODY_LENGTH); glu.gluDisk(q, 0.0f, BODY_RADIUS, SLICES, STACKS); } static void Kerucut(GL gl) { float amb[] = {1.34f, 0.34f, 0.34f, 1}; float diff[] = {2.41f, 0.41f, 2.41f, 1}; float spec[] = {0.11f, 0.11f, 0.11f, 1}; float shine = 200; gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT, amb, 0); gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_DIFFUSE, diff, 0); //Modul 8 – Camera and object rotation 8-14 gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR, spec, 0); gl.glMaterialf(GL.GL_FRONT_AND_BACK, GL.GL_SHININESS, shine); float BODY_LENGTH=1.5f; float BODY_RADIUS=2.5f; int SLICES=15; int STACKS=15; GLU glu=new GLU(); GLUquadric q=glu.gluNewQuadric(); glu.gluCylinder(q, 0, BODY_RADIUS, BODY_LENGTH, SLICES, STACKS); glu.gluDisk(q, 0.0f, 0, SLICES, STACKS); gl.glTranslatef(0.0f, 0.0f, BODY_LENGTH); glu.gluDisk(q, 0.0f, BODY_RADIUS, SLICES, STACKS); } }
Berikut adalah coding dari GLRenderer.java :
package org.yourorghere; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLEventListener; import javax.media.opengl.glu.GLU; public class GLRenderer implements GLEventListener { //class vector untuk memudah vektor-isasi class vector { float x; float y; float z; public vector(float startX, float startY, float startZ){ x = startX; y = startY; z = startZ; } void vectorRotation(vector reference, float angle){ vector temp = reference; float magnitude = (float)Math.sqrt(Math.pow(temp.x, 2)+Math.pow(temp.y, 2)+Math.pow(temp.z, 2)); temp.x = temp.x/magnitude; temp.y = temp.y/magnitude; temp.z = temp.z/magnitude; float dot_product = (x*temp.x)+(y*temp.y)+(z*temp.z); float cross_product_x = (y*temp.z) - (temp.z*z); float cross_product_y = -((x*temp.z) - (z*temp.x)); //Modul 8 – Camera and object rotation 8-7 float cross_product_z = (x*temp.y) - (y*temp.x); float last_factor_rodrigues = (float) (1 - Math.cos(Math.toRadians(angle%360))); x = (float) ((x*Math.cos(Math.toRadians(angle%360))) +(cross_product_x*Math.sin(Math.toRadians(angle%360))) +(dot_product*last_factor_rodrigues*x)); y = (float) ((this.y*Math.cos(Math.toRadians(angle%360))) +(cross_product_y*Math.sin(Math.toRadians(angle%360))) +(dot_product*last_factor_rodrigues*y)); z = (float) ((z*Math.cos(Math.toRadians(angle%360))) +(cross_product_z*Math.sin(Math.toRadians(angle%360))) +(dot_product*last_factor_rodrigues*z)); } } vector depanBelakang = new vector(0f, 0f, -1f);//deklarasi awal vektor untuk maju & mundur vector samping = new vector(1f, 0f, 0f);//deklarasi awal vektor untuk gerakan ke kanan & kiri vector vertikal = new vector(0f, 1f, 0f);//deklarasi awal vetor untuk gerakan naik & turun float Cx = 0, Cy = 2.5f, Cz = 0; float Lx = 0, Ly = 2.5f, Lz = -20f; float angle_depanBelakang = 0f; float angle_depanBelakang2 = 0f; float angle_samping = 0f; float angle_samping2 = 0f; float angle_vertikal = 0f; float angle_vertikal2 = 0f; float silinderAngle = 0f; boolean ori = true, silinder = false, kamera = false, silinderXp = false, silinderYp = false, silinderZp = false; //Modul 8 – Camera and object rotation 8-8 /* ini adalah metod untuk melakukan pergerakan. magnitude adalah besarnya gerakan sedangkan direction digunakan untuk menentukan arah. gunakan -1 untuk arah berlawanan dengan vektor awal */ private void vectorMovement(vector toMove, float magnitude, float direction){ float speedX = toMove.x*magnitude*direction; float speedY = toMove.y*magnitude*direction; float speedZ= toMove.z*magnitude*direction; Cx += speedX; Cy += speedY; Cz += speedZ; Lx += speedX; Ly += speedY; Lz += speedZ; } private void cameraRotation(vector reference, double angle){ float M = (float) (Math.sqrt(Math.pow(reference.x, 2)+ Math.pow(reference.y, 2) + Math.pow(reference.z, 2)));//magnitud float Up_x1 = reference.x/M; //melakukan float Up_y1 = reference.y/M; //normalisasi float Up_z1 = reference.z/M; //vektor patokan float VLx = Lx - Cx; float VLy = Ly - Cy; float VLz = Lz - Cz; float dot_product = (VLx*Up_x1)+(VLy*Up_y1)+(VLz*Up_z1); float cross_product_x = (Up_y1*VLz) - (VLy*Up_z1); float cross_product_y = -((Up_x1*VLz) - (Up_z1*VLx)); float cross_product_z = (Up_x1*VLy) - (Up_y1*VLx); float last_factor_rodriques = (float) (1 - Math.cos(Math.toRadians(angle%360))); float Lx1 = (float) ((VLx*Math.cos(Math.toRadians(angle%360))) +(cross_product_x*Math.sin(Math.toRadians(angle%360))) +(dot_product*last_factor_rodriques*VLx)); float Ly1 = (float) ((VLy*Math.cos(Math.toRadians(angle%360))) //Modul 8 – Camera and object rotation 8-9 +(cross_product_y*Math.sin(Math.toRadians(angle%360))) +(dot_product*last_factor_rodriques*VLy)); float Lz1 = (float) ((VLz*Math.cos(Math.toRadians(angle%360))) +(cross_product_z*Math.sin(Math.toRadians(angle%360))) +(dot_product*last_factor_rodriques*VLz)); Lx = Lx1+Cx; Ly = Ly1+Cy; Lz = Lz1+Cz; } public void init(GLAutoDrawable drawable) { // Use debug pipeline // drawable.setGL(new DebugGL(drawable.getGL())); GL gl = drawable.getGL(); System.err.println("INIT GL IS: " + gl.getClass().getName()); // Enable VSync gl.setSwapInterval(1); float ambient[] = {1.0f,1.0f,1.0f,1.0f }; float diffuse[] = {1.0f,1.0f,1.0f,1.0f }; float position[] = {1.0f,1.0f,1.0f,0.0f }; gl.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, ambient,0); gl.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, diffuse,0); gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, position,0); gl.glEnable(GL.GL_LIGHT0); gl.glEnable(GL.GL_LIGHTING); gl.glEnable(GL.GL_DEPTH_TEST); gl.glClearColor(0f, 0f, 1.0f, 1.0f); gl.glShadeModel(GL.GL_SMOOTH); //gl.glShadeModel(GL.GL_SMOOTH); // try setting this to GL_FLAT and see what happens. } public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { GL gl = drawable.getGL(); GLU glu = new GLU(); //Modul 8 – Camera and object rotation 8-10 if (height <= 0) { // avoid a divide by zero error! height = 1; } final float h = (float) width / (float) height; gl.glViewport(0, 0, width, height); gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); glu.gluPerspective(45.0f, h, 1.0, 50.0); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glLoadIdentity(); } public void display(GLAutoDrawable drawable) { GL gl = drawable.getGL(); GLU glu = new GLU(); // Clear the drawing area gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); // Reset the current matrix to the "identity" gl.glLoadIdentity(); gl.glTranslatef(0f, 0f, -5f); // Move the "drawing cursor" around glu.gluLookAt(Cx, Cy, Cz, Lx, Ly, Lz, vertikal.x, vertikal.y, vertikal.z); gl.glPushMatrix(); gl.glRotatef(silinderAngle, 1f, 0, 0); gl.glPushMatrix(); gl.glTranslatef(0f, 5f, -15f); gl.glRotatef(90, 1f, 0, 0); Objek.Tabung(gl); gl.glPopMatrix(); gl.glPushMatrix(); gl.glTranslatef(0f, 6.5f, -15f); gl.glRotatef(90, 1f, 0, 0); Objek.Kerucut(gl); gl.glPopMatrix(); gl.glPushMatrix(); gl.glTranslatef(0f, 6.7f, -15f); gl.glRotatef(90, 1f, 0, 0); Objek.TabungAtas(gl); gl.glPopMatrix(); gl.glPushMatrix(); gl.glTranslatef(0f, 0f, -15f); gl.glRotatef(90, 1f, 0, 0); Objek.TabungBawahKecil(gl); gl.glPopMatrix(); gl.glPushMatrix(); gl.glTranslatef(0f, -0.5f, -15f); gl.glRotatef(90, 1f, 0, 0); Objek.TabungBawah(gl); gl.glPopMatrix(); gl.glPopMatrix(); if(silinderXp){ silinderAngle +=3f; gl.glRotatef(silinderAngle,0,0,-1); } if(kamera) Key_Pressed(74); gl.glFlush(); } public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { } //Modul 8 – Camera and object rotation 8-11 void Key_Pressed(int keyCode) { //huruf W if(keyCode == 67){ vectorMovement(depanBelakang, 2f, 1f); } //huruf S else if(keyCode == 70){ vectorMovement(depanBelakang, 2f, -1f); if(kamera) kamera = false; else kamera = true; } //huruf A else if(keyCode == 68){ if(kamera) kamera = false; else kamera = true; vectorMovement(samping, 2f, 1f); } //huruf D else if(keyCode == 65){ if(silinderXp) silinderXp = false; else silinderXp = true; vectorMovement(samping, 2f, -1f); } //panah atas else if(keyCode == 69){ if(kamera) kamera = false; else kamera = true; vectorMovement(vertikal, 2f, 1f); } //panah bawah else if(keyCode == 66){ vectorMovement(vertikal, 2f, -1f); } //tombol spasi //else if(keyCode == 32){ //if(silinder) //silinder = false; //else //silinder = true; //} //tombol enter else if(keyCode == 10){ if(kamera) kamera = false; else kamera = true; } else if(keyCode == 72){ angle_vertikal += 15f; samping.vectorRotation(vertikal, angle_vertikal-angle_vertikal2); depanBelakang.vectorRotation(vertikal, angle_vertikal-angle_vertikal2); cameraRotation(vertikal, angle_vertikal-angle_vertikal2); angle_vertikal2 = angle_vertikal; } else if(keyCode == 71){ angle_vertikal -= 15f; samping.vectorRotation(vertikal, angle_vertikal-angle_vertikal2); depanBelakang.vectorRotation(vertikal, angle_vertikal-angle_vertikal2); cameraRotation(vertikal, angle_vertikal-angle_vertikal2); angle_vertikal2 = angle_vertikal; } } }
0 komentar untuk Contoh Coding Membuat Benteng/Catur Pemrograman Grafis pada Java.
Perlihatkan Semua Komentar Tutup Semua Komentar