How do I translate this polygon in opengl using fps animator? - java

I'm trying to write a code where my polygon moves from left to right ends of my screen. The main issue I shared is that I'm not able to translate this using fps animator This is my polygon code:
private void drawface(GL2 gl)
{
gl.glBegin(GL2.GL_POLYGON);
gl.glVertex2f(0, 130);
gl.glVertex2f(120, 130);
gl.glVertex2f(120, 140);
gl.glVertex2f(0, 140);
gl.glEnd();
}
Then this is my display function:
public void display(GLAutoDrawable arg0)
{
final GL2 gl = arg0.getGL().getGL2();
gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);
gl.glLoadIdentity();
gl.glPushMatrix();
gl.glColor3f(0.5f, 1f, 0.75f);
gl.glTranslatef(t1x, 1, 1);
drawface(gl);
gl.glPopMatrix();
}
I'm updating the int t1x through a KeyEvent method
public void keyPressed(KeyEvent arg0)
{
int key = arg0.getKeyCode();
if(key == KeyEvent.VK_RIGHT)
{
t1x++;
}
else if(key == KeyEvent.VK_LEFT)
t1x--;
}
But my polygon isn't translating when I click the right arrow key. What should I do ?

Related

Image won't change when key is pressed

I am making my own little copy of Mario that I started today, and I am stuck on a little animation.
When UP is pressed, Mario jumps, but the sprite won't change.
I have tried if-else to set it, but it's not working:
PImage brick1;
PImage bg;
PImage Flag;
float playerX;
float playerY;
float brickX;
float Lives;
float Level;
float Time;
void setup(){
size(1000,800);
smooth();
if (keyPressed){
if (keyCode == UP){
bg = loadImage("Mario3.png");
}
}else{
bg = loadImage("Mario1.png");
}
I expect the image to change while UP is held down, but it says the "Mario1.png" sprite.
You've to implement a draw function.
Load the images in setup:
PImage bg1, bg3;
void setup() {
size(1000, 800);
smooth();
bg1 = loadImage("Mario1.png");
bg3 = loadImage("Mario3.png");
}
And draw the proper image dependent on the state of keyPressed and keyCode.
Use image() to draw an image to the display:
e.g.
void draw() {
background(0);
if (keyPressed && keyCode == UP) {
image(bg3, 0, 0);
} else {
image(bg1, 0, 0);
}
}

How do I add to my snake using Java?

So I am trying to make a snake game for my final project in my programming class. I am trying to add to the snake using an array, since using an array of objects is one of the requirements for the project. But I can't figure out how to make it work. Can anyone tell me what I am doing wrong?
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class FinalApplet extends Applet implements KeyListener {
private Image grass;
private Image mouse;
private Snake[] mySnake = new Snake[100];
private int x;
private int y;
public void init() {
grass = getImage(getCodeBase(), "grass.jpg");
mouse = getImage(getCodeBase(), "mouse.png");
addKeyListener(this);
}
public void update (Graphics g) {
paint(g);
}
public void paint(Graphics g) {
Image buffer = createImage(getWidth(), getHeight());
Graphics z = buffer.getGraphics();
z.drawImage(grass, 0, 0, this);
z.drawImage(mouse, 200, 130, this);
z.setColor(Color.RED);
z.fillRect(x, y, 20, 20);
g.drawImage(buffer, 0, 0, this);
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
y = y + 1;
repaint();
}
else if (e.getKeyCode() == KeyEvent.VK_UP) {
y = y - 1;
repaint();
}
else if(e.getKeyCode() == KeyEvent.VK_LEFT){
x = x - 1;
repaint();
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT){
x = x + 1;
repaint();
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
I suppose your snake starts with at least a length of 1, for it to be shown. That means that your array in its first element has a starting coordinate. All other cells of the array are empty (or null whichever you are using) and hence should not be painted on your canvas, i.e. should not be shown to your user.
A solution could be that every time your snake moves, you update each cell of your array (taking into account that each cell is a section of your snake) with its new position.
When the snake overlaps with the position of a "mouse" then the next available cell on your array should have the last position of your last (now before last) cell, taking into account that it should not move until its previous cell has moved and that only cells that have an actual value should be painted.
I hope this helps, but you should try and post more code so we could help with specific programming problems.

How can I resize my circle in Java using OpenGL

How can I resize my circle shape in Java using OpenGL? I am very new to Java and OpenGL and I don't understand why my circle isn't being resized? I'm calling the function again with different parameters but for some reason my circle stays exactly the same and doesn't change, why is that?
I initially draw the circle calling drawCircle(..,..,..,..) in my display(..) function
You'll notice that when a key is pressed; 'a' , I want to increase the size of the circle
#Override
public void keyTyped(KeyEvent e)
{
// TODO Auto-generated method stub
char key= e.getKeyChar();
System.out.printf("Key typed: %c\n", key);
// Make shape bigger
// increase size of circle
if(key == 'a')
{
drawCircle(test, 10.0f, 10.0f, 10.0f);
}
// move right
if(key == 'f')
{
}
}
For some reason though it just doesn't even change my initial circle drawn whatsoever.
I have:
JoglEventListener.java
package helloOpenGL;
/*************************************************************************************
* IMPORTS
**************************************************************************************/
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import com.jogamp.opengl.*;
import com.jogamp.opengl.glu.GLU;
/*************************************************************************************
* JoglEventListener
**************************************************************************************/
public class JoglEventListener implements GLEventListener, KeyListener
{
float rot;
GL2 gl = null;
GLAutoDrawable test = null;
// Instantiate GLU thing?
private GLU glu = new GLU();
/*************************************************************************************
* displayChanged
* What does this do?
**************************************************************************************/
public void displayChanged(GLAutoDrawable gLDrawable,
boolean modeChanged, boolean deviceChanged)
{
// Function that does nothing?
}
/** Called by the drawable immediately after the OpenGL context is
* initialized for the first time. Can be used to perform one-time OpenGL
* initialization such as setup of lights and display lists.
* #param gLDrawable The GLAutoDrawable object.
*/
/*************************************************************************************
* init
**************************************************************************************/
public void init(GLAutoDrawable gLDrawable)
{
GL2 gl = gLDrawable.getGL().getGL2();
//gl.glShadeModel(GL.GL_LINE_SMOOTH); // Enable Smooth Shading
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
gl.glClearDepth(1.0f); // Depth Buffer Setup
gl.glEnable(GL.GL_DEPTH_TEST); // Enables Depth Testing
gl.glDepthFunc(GL.GL_LEQUAL); // The Type Of Depth Testing To Do
// Really Nice Perspective Calculations
//gl.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST);
}
/*************************************************************************************
* reshape ?
* ?
**************************************************************************************/
public void reshape(GLAutoDrawable gLDrawable, int x, int y, int width,
int height)
{
gl = gLDrawable.getGL().getGL2();
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(GL2.GL_PROJECTION);
gl.glLoadIdentity();
glu.gluPerspective(45.0f, h, 1.0, 200.0);
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(0.0f, 0.0f, -40.0f);
}
public void drawCircle(GLAutoDrawable gLDrawable, float x, float y, float radius)
{
GL2 gl = gLDrawable.getGL().getGL2();
int i;
test = gLDrawable;
//GLfloat radius = 0.8f; //radius
float twicePi = (float) (2.0f * Math.PI);
gl.glBegin(GL.GL_LINE_LOOP);
for(i = 0; i <= 360;i++)
{
gl.glVertex2f(
x + ((float)(radius * Math.cos(i * twicePi / 360))),
y + ((float)(radius* Math.sin(i * twicePi / 360)))
);
}
gl.glEnd();
}
#Override
public void display(GLAutoDrawable gLDrawable)
{
// TODO Auto-generated method stub
final GL2 gl = gLDrawable.getGL().getGL2();
gl.glClearColor(backrgb[0], 0, 1, 1);
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
backrgb[0]+=0.0005;
if (backrgb[0]> 1) backrgb[0] = 0;
// DRAW STUFF IN THIS FUNCTION
drawCircle(gLDrawable, 5.0f, 5.0f, 3.0f);
}
#Override
public void dispose(GLAutoDrawable arg0)
{
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e)
{
// TODO Auto-generated method stub
char key= e.getKeyChar();
System.out.printf("Key typed: %c\n", key);
// Move Horizontally
// move left
if(key == 'a')
{
drawCircle(test, 10.0f, 10.0f, 10.0f);
}
// move right
if(key == 'f')
{
}
}
#Override
public void keyPressed(KeyEvent e)
{
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e)
{
// TODO Auto-generated method stub
}
}
You'll need to give the updated radius in the display function to get it drawn. Otherwise the image gets overwritten by it. So store the radius into a variable, for example under float rot; and don't draw when pressing 'a', only update the variable. Then in the display function use the variable:
drawCircle(gLDrawable, 5.0f, 5.0f, radius);

How to make the camera move in the direction of the rotation?

How can I make the camera move in the direction of the rotation? How do I calculate the position of the camera to follow the rotation?
This is my code:
import javax.media.opengl.*;
import javax.media.opengl.awt.*;
import com.sun.opengl.util.*;
import com.sun.opengl.util.gl2.GLUT;
import javax.media.opengl.glu.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Rotation2 extends JFrame implements GLEventListener, KeyListener
{
GLCanvas canvas = null;
Animator an;
public Rotation2()
{
canvas=new GLCanvas();
an=new Animator(canvas);
add(canvas);
canvas.addGLEventListener(this);
canvas.addKeyListener(this);
setSize(1280,900);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
an.start();
requestFocus();
}
float xPosition = 0;
float zPosition = 0;
float red = 0;
float green = 0;
float blue = 1;
public void init(GLAutoDrawable drawable)
{
GL2 gl = drawable.getGL().getGL2();
GLU glu = new GLU();
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
double w = drawable.getWidth();
double h = drawable.getHeight();
double aspect = w/h;
glu.gluPerspective(60.0, aspect, 2.0, 20.0);
}
double zRot = 0;
double xRot = 0;
public void display(GLAutoDrawable drawable)
{
GL2 gl=drawable.getGL().getGL2();
GLU glu = new GLU();
GLUT glut = new GLUT();
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glClearColor(0f,0f,0f,0f);
//xPosition+=0.005;
//zPosition+=0.005;
gl.glRotated(zRot, 0, 1, 0);
gl.glRotated(xRot, 1, 0, 0);
glu.gluLookAt(xPosition, 0, zPosition,
xPosition, 0, (zPosition+20),
0, 1, 0);
gl.glClear(GL2.GL_COLOR_BUFFER_BIT);
red = 0.0f;
green = 0.0f;
blue = 0.9f;
gl.glColor3f(red, green, blue);
//transforming the place the next shape
//will be drawn.
gl.glTranslated(2, 0, 2);
//We use wire here because default
//lighting is not good enough to
//use when rendering the solid version
glut.glutWireIcosahedron();
//more shapes to navigate through
gl.glTranslated(-4, 0, 0);
glut.glutWireIcosahedron();
red = 0.0f;
green = 0.9f;
blue = 0.1f;
gl.glColor3f(red, green, blue);
gl.glTranslated(4, 0, 4);
glut.glutWireIcosahedron();
gl.glTranslated(-4, 0, 0);
glut.glutWireIcosahedron();
red = 0.9f;
green = 0.0f;
blue = 0.1f;
gl.glColor3f(red, green, blue);
gl.glTranslated(4, 0, 4);
glut.glutWireIcosahedron();
gl.glTranslated(-4, 0, 0);
glut.glutWireIcosahedron();
red = 0.9f;
green = 0.0f;
blue = 0.9f;
gl.glColor3f(red, green, blue);
gl.glTranslated(4, 0, 4);
glut.glutWireIcosahedron();
gl.glTranslated(-4, 0, 0);
glut.glutWireIcosahedron();
}
public void reshape(GLAutoDrawable drawable,int x,int y,int width,int height)
{}
public void dispose(GLAutoDrawable drawable)
{}
public static void main(String[] ar)
{
new Rotation2();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_W) {
zPosition++;
}
else if (e.getKeyCode() == KeyEvent.VK_S) {
zPosition--;
}
else if(e.getKeyCode() == KeyEvent.VK_A) {
xPosition++;
}
else if (e.getKeyCode() == KeyEvent.VK_D) {
xPosition--;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
zRot+=5;
}
else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
zRot-=5;
}
else if (e.getKeyCode() == KeyEvent.VK_UP) {
xRot-=5;
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
xRot+=5;
}
canvas.repaint();
}
#Override
public void keyReleased(KeyEvent e) {
}
}
p.s. You have to click the canvas for things to start working.
elect is right, you have to understand the basic concepts, you can't just tinker with no understanding of the notions on computer graphics. You can read the OpenGL Red Book, its code examples have been ported to JOGL and are available on Github here.
Those classes of my own first person shooter's very oldest alpha version show how to implement a camera except that you cannot look up or down:
GameGLView
GameController
GameModel
P.S: I have to update it soon to make it work with JOGL 2.3.2 and later. It works with JOGL 2.3.1.
P.P.S: I updated the source code above to make it work with JOGL 2.3.2 yesterday (February, 4th, 2016).

LibGDX Desktop flicker

This question has been posted before, but i have problems with flickering sprites in libGdx.
I have looked everywhere on stackoverflow, google, etc but nothing helped me.
The sprites only flicker when they move. It flickers less when i move them slower, but it flickers a lot when a little bit faster. This is very annoying and ofcourse unplayable.
This is my code:
package com.wouter.DuelArena;
import com.badlogic.gdx.Game;
import ...
public class DuelArena extends Game {
Sprite player;
float playerX;
float playerY;
boolean fireBool;
Sprite fireSprite;
Texture fireText;
OrthographicCamera cam;
Texture playerTexture;
SpriteBatch batch;
#Override
public void create() {
fireBool = false;
fireText = new Texture("data/droplet.png");
fireText.setFilter(TextureFilter.Linear, TextureFilter.Linear);
fireSprite = new Sprite(fireText);
playerTexture = new Texture("data/bucket.png");
playerTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
player = new Sprite(playerTexture);
player.setSize(70, 128);
playerX = 0f;
playerY = 0f;
cam = new OrthographicCamera();
cam.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch = new SpriteBatch();
}
#Override
public void dispose() {
super.dispose();
}
#Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(Gdx.gl10.GL_COLOR_BUFFER_BIT);
cam.update();
batch.setProjectionMatrix(cam.combined);
batch.begin();
player.draw(batch);
input();
update();
batch.end();
super.render();
}
private void update()
{
player.setPosition(playerX, playerY);
if (fireBool)
{
fireSprite.setX(fireSprite.getX() + 300 * Gdx.graphics.getDeltaTime());
fireSprite.draw(batch);
if (fireSprite.getX() > 1280)
fireBool = false;
}
}
private void input()
{
if (Gdx.input.isKeyPressed(Keys.LEFT) && player.getX() > 0)
{
playerX -= 200f * Gdx.graphics.getDeltaTime();
}
if (Gdx.input.isKeyPressed(Keys.RIGHT) && player.getX() < 1280)
{
playerX += 200f * Gdx.graphics.getDeltaTime();
}
if (Gdx.input.isKeyPressed(Keys.SPACE) && !fireBool)
{
fireBool = true;
fireSprite.setPosition(playerX, playerY + 35f * Gdx.graphics.getDeltaTime());
}
}
#Override
public void resize(int width, int height) {
super.resize(width, height);
}
#Override
public void pause() {
super.pause();
}
#Override
public void resume() {
super.resume();
}
}
Thanks beforehand!
The problem is the position of the call to the super.render:
super.render();
In a Game class, the super.render needs to be the first line in the code, not the last, like this:
#Override
public void render(){
super.render(); //<-----
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(Gdx.gl10.GL_COLOR_BUFFER_BIT);
cam.update();
batch.setProjectionMatrix(cam.combined);
batch.begin();
player.draw(batch);
input();
update();
batch.end();
}
It is actually very important to put it there if you override the render method in Game, because thats the one that calls the render of the current Screen. You aren't using Screens in this example, but if you are using Game you probably should (will :p).

Categories