package destr.jogl.main;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import destr.jogl.game2d.Game2DCanvas;
public class PinPongMin extends Game2DCanvas implements MouseMotionListener {
private static final long serialVersionUID = -2012327736229675921L;
private int mouseY = 0;
private float clubX = 10, clubY = 0, clubW = 25, clubH = 100;
private float ballX = 50, ballY = 50, ballW = 25, ballH = 25;
private float ballSX = 2.5f, ballSY = 1.5f;
public PinPongMin(int width, int height) {
super(width, height);
this.addMouseMotionListener(this);
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
mouseY = e.getPoint().y;
}
private void drawRect(GL2 gl2, float x, float y, float w, float h) {
gl2.glPushMatrix();
gl2.glTranslatef(x, y, 0);
gl2.glScalef(w, h, 0f);
gl2.glBegin(GL2.GL_QUADS);
gl2.glColor3f(1.0f, 0.0f, 0.0f);
gl2.glVertex3f(0.0f, 0.0f, 0.0f);
gl2.glColor3f(0.0f, 1.0f, 0.0f);
gl2.glVertex3f(1.0f, 0.0f, 0.0f);
gl2.glColor3f(0.0f, 0.0f, 1.0f);
gl2.glVertex3f(1.0f, 1.0f, 0.0f);
gl2.glColor3f(1.0f, 1.0f, 0.0f);
gl2.glVertex3f(0.0f, 1.0f, 0.0f);
gl2.glEnd();
gl2.glPopMatrix();
}
@Override
public void display(GLAutoDrawable drawable) {
clubY += (mouseY - clubY) / 25;
ballX += ballSX;
ballY += ballSY;
if(ballX < 0.0f){
ballX = width-ballW;
}
if(ballX+ballW > width){
ballSX = -ballSX;
}
if(ballY < 0.0f || ballY+ballH > height){
ballSY = -ballSY;
}
if( ballX < clubX + clubW &&
ballX+ballW > clubX &&
ballY < clubY + clubH &&
ballY+ballH > clubY
){
ballSX = -ballSX;
ballX = clubX + clubW;
}
GL2 gl2 = drawable.getGL().getGL2();
gl2.glClear(GL2.GL_COLOR_BUFFER_BIT);
gl2.glLoadIdentity();
gl2.glTranslatef(-1f, 1f, 0);
gl2.glScalef(2.0f/width, -2.0f/height, 0f);
drawRect(gl2, clubX, clubY, clubW, clubH);
drawRect(gl2, ballX, ballY, ballW, ballH);
}
}
Comments