My New Game Project : Jungle Riddle

At present i am working on a 2d side-scrolling platform game. It started as a course project but now i want to extend it and make it large.

I have used java and slick library to make this game project. I have put the game demo on my blog page. The project is still in development process. So you can download and play it. Please give the feedback. I am still new to game development so feedback( both positive and negative ) will be appreciated.

So download the game from http://gaanza.com/games/ and play it

please comment your feedback and suggestions here.

it’ll be great help for developing this game further.

Gracias.

Posted in Slick 2D, games, java | Tagged , , | 5 Comments

Getting started making games with java !!

Okie still there are people who thinks java is slow for making commercial and serious games and java is just for casual games. But here i’l show you that java has lot more potential to make serious games.

So now how to get started ??? What libraries or tools to use for making more efficient games ?? There are two libraries which gives you a lot more features to create real time graphics. You can make amazing cool games using these libraries. And what are these libraries ?? They are LWJGL (light weight java game library) and JOGL (java OpenGL). These two libraries gives you the power of opengl graphics library.

LWJGL

The Lightweight Java Game Library (LWJGL) is a solution aimed directly at professional and amateur Java programmers alike to enable commercial quality games to be written in Java. LWJGL provides developers access to high performance crossplatform libraries such as OpenGL (Open Graphics Library) and OpenAL (Open Audio Library) allowing for state of the art 3D games and 3D sound. Additionally LWJGL provides access to controllers such as Gamepads, Steering wheel and Joysticks.

So Is there any game made using LWJGL ??

Yes there is AAA tiltle that has been made using lwjgl. Its TRIBLE TROUBLE by oddlabs, an amazing cool 3d real time strategy game. You can read my post on this game.

source: http://tribaltrouble.com/screenshots?id=14

source: http://tribaltrouble.com/screenshots?id=14

Okie so now where i can find the lwjgl tutorials:

lwjgl tutorial site 1

lwjgl tutorial site 2

(Note: i’ll keep updating the tutorial sites of lwjgl )

JOGL

Java OpenGL (JOGL) is a wrapper library that allows OpenGl to be used in the Java programming language. JOGL is the Sun supported set of Java class bindings for OpenGL. Using OpenGL through JOGL, you will be able to make cool games or model situations that could be too expensive to create.

So any game made with JOGL ???

Yes. Its called JAKE 2. It is the port of Quake 2 game engine from id Software. Here is the screenshot from their ( bytonic Software) site:

source: http://bytonic.de/html/screenshots_1.html

source: http://bytonic.de/html/screenshots_1.html

Okie now i will tell you about some available good engines to make games. All the low level stuff has been done for you. You have to just use the library and take off.

First i’ll start with 2d game engines:

1) Slick 2D : This is the best java 2d game engine based on LWJGL available now. Its an free and Open Source 2d game engine. Many cool games has been made using this game.

2) Golden T Game Engine (GTGE) : Its an advanced cross-platform game programming library written in java programming language.

3) Stencyl

4) JGame

5) PulpCore

Now 3d java engines:

1) jMonkeyEngine : This is the one of the best and popular java 3d graphics engine available now. Its an free and open source engine. JME (jMonkey Engine) is a high performance scene graph based graphics API. Some videos of game made with jMonkeyEngine.

2) Espresso3D : Its an open source high performance real-time 3D engine for the Java(tm) programming language. It aims to be a complete solution for your application with OpenGL rendering, OpenAL audio, collision detection, input, and rendering support.

3) Xith3D : Xith3D is a Java-based 3D engine, centered on gaming.

4) JCPT : jPCT is a free 3D engine/API for Java. Here is one screenshot of games made with JCPT from there site.

source: http://www.jpct.net/screenshots.html

source: http://www.jpct.net/screenshots.html

Okie so thats it. I hope i have give you enough basic info on starting making games with java. So now you make a choice and get started.

Gracias.

Posted in games, java | Tagged , , | Leave a comment

Is Java too slow for making AAA commercial games ??

In almost every game development forum i have seen people saying that java is too slow for making AAA commercial game titles. So is it true that commercial AAA tiles cannot be made using Java ?????

Here i will tell u about a very amazing  AAA tile that i recently played and has been made using java+lwjgl(java binding for opengl). I downloaded the game demo and i was damn impressed with the game. Its a simple and very fun game. Its an 3D RTS(Real Time Strategy) game. Okie ok ok so whats the name of the game ??? Its called TRIBAL TROUBLE. Tribal Trouble was among GameTunnel’s Top 10 games of the year 2005.  Check the reviews. The game is available for mac, linux and windows platform. The game is developed by oddlabs which is an independent game development studio.

Here is an excerpt from the interview with oddlabs about their using java for making games from gamedev.net:

What do you guys think of java/lwjgl? Why did you choose it? If given the chance to go back in time would have you chosen something else for TT?

Sune: There is no way I would have chosen a language like C or C++ instead. Java is so much more easy/safe to code in. I’m sure it has saved us countless of hours.

Jacob: We settled with lwjgl after trying out a couple of other java opengl/openal bindings.

Sune: I think we have proven that the myth about java being too slow has become invalid and now that it runs fast enough, why not take advantage of the improved development advantages.

Jacob: Whenever there’s a flamewar about java being slow in developer forums, there’s a pretty good chance someone will mention Tribal Trouble :) We have seen this countless times by looking at referrers to oddlabs.com

Nathaniel: Haha, awesome. :)

You can read full interview from here.

Here is one screenshot from their site. You can see all the screenshots here.

tribal

You can see the reviews of this game (please go through it :D )

You can download the demo from here and play it and u decide whether ” Java is Slow ” is myth or not. :) )

So use java.

Gracias. Ciiaao !!!

Posted in games, java | Tagged , , | 1 Comment

Installing or Setting up JOGL on Ubuntu

gl_java_ubuntu1

Here are the detailed steps to set up or install JOGL on your ubuntu. First of all you have to download the jogl library(according to your machine) from here . I am using Ubuntu 8.04 on intel board so i downloaded jogl-1.1.1-linux-i586.zip.

So extract the zip file. Now open the folder that you have just now extracted. Go to lib folder.

STEP 1: Now you have to copy four .so files i.e libjogl.so, libjogl_awt.so, libjogl_cg.so, libgluegen-rt.so to [javainstalation directory]/jre/lib/i386

Open the terminal window and type: sudo cp libjogl.so /usr/lib/java/jdk1.6.0_13/jre/lib/i386

similarly you have to copy other three .so files.

*you have to provide you java installation path*

jogl1

Now you can check the destination if files has been copied.

jogl21

STEP 2: Now copy jogl.jar and gluegen-rt.jar to [java installation di]/jre/lib/ext

run this command to copy: sudo cp jogl.jar /usr/lib/java/jdk1.6.0_13/jre/lib/ext

simillarly copy gluegen-rt.jar

*you have to provide your java installation path*

jogl3

You can check:

jogl4

STEP 3: SO thats it. Now lets test the simple jogl code.

import javax.media.opengl.GLCapabilities;

public class Hello{
public static void main (String args[]) {
try {
System.loadLibrary(“jogl”);
System.out.println(
“Hello World! (The native libraries are installed.)”
);
GLCapabilities caps = new GLCapabilities();
System.out.println(
“Hello JOGL! (The jar appears to be available.)”
);
} catch (Exception e) {
System.out.println(e);
}
}
}

Now compile this Hello.java and the run it. Here is the output:

jogl-final

So thats it. Now your are off to fly and write your jogl apps.

Thanks.

Posted in Tutorials, developer, java | Tagged , , , | 2 Comments

Alpha Blending using OpenGL with SDL

sdl_opengl

Alpha Blending is a convex combination of two colors allowing for transparency effects in computer graphics. Blending is used to combine the color of a given pixel that is about to be drawn with the pixel that is already on the screen. How the colors are combined is based on the alpha value of the colors, and/or the blending function that is being used. Alpha is a 4th color component usually specified at the end.

Alpha Blending in SDL is slow because its not a hardware accelerated. To get a better performance there is OpenGL which is hardware accelerated. So here i’l show you how to use alpha blending using opengl with sdl.

glColor4f(1.0f,1.0f,1.0f,alpha); // full Brightness, Alpha

glBlendFunc(GL_SRC_ALPHA,GL_ONE); // Blending Function for  translucency based on source alpha value>
 

First line set the color to full brightness with alpha value. An alpha value of 0.0 would mean that the material is completely transparent . A value of 1.0 would be totally opaque. The primitive’s opacity is specified using glColor4*(). RGB specifies the color, and the alpha parameter specifies the opacity.

glEnable(GL_BLEND);                      // Turn Blending on

glDisable(GL_DEPTH_TEST);        //Turn Depth Testing off
 

So this is it what you will required to achieve alpha blending.

Below code is a simple FADE IN/FADE OUT program. When UP arow key is pressed then 2d sprite will fade out and when DOWN key is pressed then 2d sprite will fade in.

alpha

Here is the full Source Code:

#include "SDL.h"
#include "SDL_image.h"
#include "SDL_opengl.h"

#include <stdio.h>

GLuint texture=NULL;     //this is a handle to our texture object
GLenum texture_format=NULL;
GLint nofcolors;

SDL_Event event;

float alpha=1.0f;
bool UP=false;         //Up key is pressed/released
bool DOWN=false;       //DOWN key is pressed/released</em>

<em>int loadImage()
{
SDL_Surface *surface; // this surface will tell us the details of the image

if ( (surface = IMG_Load(“flower.png”)) ) {

// Check that the image’s width is a power of 2
if ( (surface-&gt;w &amp; (surface-&gt;w – 1)) != 0 ) {
printf(“warning: image.bmp’s width is not a power of 2\n);
}

// Also check if the height is a power of 2
if ( (surface-&gt;h &amp; (surface-&gt;h – 1)) != 0 ) {
printf(“warning: image.bmp’s height is not a power of 2\n);
}

//get number of channels in the SDL surface
nofcolors=surface-&gt;format-&gt;BytesPerPixel;

//contains an alpha channel
if(nofcolors==4)
{
if(surface-&gt;format-&gt;Rmask==0×000000ff)
texture_format=GL_RGBA;
else
texture_format=GL_BGRA;
}
else if(nofcolors==3) //no alpha channel
{
if(surface-&gt;format-&gt;Rmask==0×000000ff)
texture_format=GL_RGB;
else
texture_format=GL_BGR;
}
else
{
printf(“warning: the image is not truecolor…this will break “);
}

// Have OpenGL generate a texture object handle for us
glGenTextures( 1, &amp;texture );

// Bind the texture object
glBindTexture( GL_TEXTURE_2D, texture );

// Set the texture’s stretching properties
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

glTexImage2D( GL_TEXTURE_2D, 0, nofcolors, surface-&gt;w, surface-&gt;h, 0,
texture_format, GL_UNSIGNED_BYTE, surface-&gt;pixels );
}
else {
printf(“SDL could not load image.bmp: %s\n, SDL_GetError());
SDL_Quit();
return 1;
}

// Free the SDL_Surface only if it was successfully created
if ( surface ) {
SDL_FreeSurface( surface );
}
}

void drawImage()
{
glClear( GL_COLOR_BUFFER_BIT );   // Clear the screen before drawing

glTranslatef(300.0,200.0,0.0);

glBindTexture( GL_TEXTURE_2D, texture );   // Bind the texture to which subsequent calls refer to

glColor4f(1.0f,1.0f,1.0f,alpha);            // Full Brightness, Alpha
glBlendFunc(GL_SRC_ALPHA,GL_ONE);           // // Blending Function For Translucency Based On Source Alpha Value

glBegin( GL_QUADS );
// Top-left vertex (corner)
glTexCoord2i( 0, 0 );
glVertex3f( -64, -64, 0 );

// Bottom-left vertex (corner)
glTexCoord2i( 1, 0 );
glVertex3f( 64, -64, 0 );

// Bottom-right vertex (corner)
glTexCoord2i( 1, 1 );
glVertex3f( 64, 64, 0 );

// Top-right vertex (corner)
glTexCoord2i( 0, 1 );
glVertex3f( -64, 64, 0 );
glEnd();
glLoadIdentity();

SDL_GL_SwapBuffers();
}

int init()
{
SDL_Surface *screen;

// Slightly different SDL initialization
if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
printf(“Unable to initialize SDL: %s\n, SDL_GetError());
return 1;
}

SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

screen = SDL_SetVideoMode( 640, 480, 16, SDL_OPENGL);
if ( !screen ) {
printf(“Unable to set video mode: %s\n, SDL_GetError());
return 1;
}
}

void init_GL()
{
// Set the OpenGL state after creating the context with SDL_SetVideoMode

glClearColor( 0, 0, 0, 0 );

glEnable( GL_TEXTURE_2D );        // Need this to display a texture
glEnable(GL_BLEND);                  // Turn Blending On
glDisable(GL_DEPTH_TEST);         //Turn Depth Testing Off</em>

glViewport( 0, 0, 640, 480 );

glMatrixMode( GL_PROJECTION );
glLoadIdentity();

glOrtho( 0, 640, 480, 0, -1, 1 );

glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
}

void clean_up()
{
glDeleteTextures( 1, &amp;texture );</em>

SDL_Quit();
}

int main(int argc, char *argv[])
{
//Make sure the program waits for a quit
bool quit = false;

init();
init_GL();
loadImage();
drawImage();

while( quit == false )
{
if( SDL_PollEvent( &amp;event ) )
{
//If a key was pressed
if( event.type == SDL_KEYDOWN )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_UP:
UP=true;
break;
case SDLK_DOWN:
DOWN=true;
break;
case SDLK_ESCAPE:
quit=true;
break;
}
}
//If a key was released
else if( event.type == SDL_KEYUP )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_UP:
UP=false;
break;
case SDLK_DOWN:
DOWN=false;
break;
}
}
}

// If UP key is pressed

if(UP==true){
if(alpha&lt;1.0f)         // make sure alpha value is not greater than maximum value 1.0
alpha+=0.01f;       //increase the alpha value, fade out
drawImage();
}

else if(DOWN==true){    //If DOWN key is pressed
if(alpha&gt;0.0f)       // make sure value of alpha is not less than 0.0f
alpha-=0.01f;      // decrease the alpha value, fade in
drawImage();
}

}

clean_up();
return 0;
}

So thats it. Now you are off to fly.

Thanks.

Posted in Opengl with SDL, Tutorials | Tagged , , | 1 Comment

Setting up java classpath on ubuntu

java_ubuntu

When u install sun’s jdk manually on ubuntu, java classpath doesn’t get set automatically unlike in windows. So when you enter command javac in terminal window, it says “javac  command not found”. So here is the very simple way to set up the classpath for java on ubuntu.

STEP 1 : Open the terminal window.

STEP 2: Type sudo gedit /etc/bash.bash.rc. Press enter.

STEP 3: Now gedit editor will open up. Now at the end of file just write:

PATH=$PATH:/usr/lib/java/jdk1.6.0_13/bin

export PATH

**You have to provide the path of bin folder in java installation deirectory.**

screenshot-12

STEP 4: Now save the file and close the editor and terminal. Open new terminal window and type javac and press enter, all the java options and flags will come up.

Thats it.

Thanks.

Posted in Tutorials, developer, java | Tagged | Leave a comment

How to make a exe file of Java Program ?

If you are making a java program for windows operating system only then  wouldn’t it be easy to have a exe file for your java program and distribute it to the users and user would find easy to execute your program. Well i guess yes because exe would definetly make easy for users to execute your java programs. So:

Q. How to make an exe file for your java program ?

A. exe4J.

exe4j is a Java exe maker that helps you integrate your Java applications into the Windows operating environment, whether they are service, GUI or command line applications. If you want your own process name instead of java.exe in the task manager and a user friendly task-bar grouping in Windows XP, exe4j does the job. exe4j helps you with starting your Java applications in a safe way, displaying native splash screens, detecting or distributing suitable JREs and JDKs, startup error handling and much more.

Check out the features of exe4J. Download(i would suggest you to download zip archive) the exe4J from here.

Ok now i’ll show you the steps to use exe4J for making exe. So download the exe4J zip archive and extract it to your preference location. Here i’ll be showing you how to create exe file for your java executable jar file. So lets first write a simple swing frame application which will just create a frame.

import javax.swing.*;

public class Test
{
public Test(){
JFrame frame=new JFrame(“test”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,300);
frame.setVisible(true);
}
public static void main(String[] args){
new Test();
}
}

Ok save Test.java it in some folder ( I have saved it in E:/java_programs).

Now open your  command prompt, navigate to the folder where Test.java file is saved and compile the Test.java using command javac Test.java

Now we’ll create a manifest file which will be needed to make an executable jar file. So this is the way you write your manifest file:

Main-Class: Test

First line on your manifest file will be Main-Class:<space>main-class(class file with the main method). then new line<enter>. You have to provide one new line after first line. Then save it as manifest.txt to the same folder where your Test.class file is saved.

Now we’ll create the executable jar file. Syntax is:  jar -cvmf manifest.txt <name of jar file that you will create> class file/package if used

so open up your command prompt, navigate to the folder where Test.class file and manifest file is saved. Then enter command jar -cvmf manifest.txt test.jar Test.class and press enter. Yout executable jar file is created. You can check and test it(java -jar test.jar).

Now executable jar file is ready. So now i’ll show you the steps to make exe from your executable jar file.

STEP 1: Open the folder that u had extracted. Go to bin folder. Double click exe4j launcher. Now exe4j window will open up. Click next.

1

STEP 2: Choose “JAR in EXE” mode. Click next.

2

STEP 3: Now give the name for your application. I have given “app”. Then give the path of the location where you want to save the exe file. I have given the path of location where my class, manifest and jar file are located i.e E:/java_programs. Click next.

3

STEP 4: Now choose your executable type from list of radio buttons. In our case we will choose GUI application. Then give the name of exe file that we are making.  I have provided test. Now check the boxes as shown in the screenshot. And Click next.

4

STEP 5: Now give the name of your main class. In our case its Test. Don’t put the .class extension, just give the name. Now don’t click next.

5

STEP 6: You can see the the gree plus button on above screenshot. Click that and a window will open up. Check the archive radio button above.Now we have to provide the executable jar file to the Archive, so browse the location where your executable jar file is saved. Add it. Click OK. Click next.

6

STEP 7: Now we have to configure the JRE. So provide the minimum jre version and maximum jre version to be used by the user. Then click next.

7

STEP 8: Now we have to configure splash screen (if you want to). I haven’t provided splash screen so i have chosed no splash screen. You can give your choice. Click next.

8

STEP 9: Now we have to configure messages like if you want to give error message when user does not have JRE installed in his/her machine. Click next.

9

STEP 10: Now the last step of the wizard. If you want to save the configuration then click save as. I haven’t saved the configuration so i clicked EXIT. Then it will ask me if i want to save the configuration. Click NO(if you want to save click yes). So Thats it. Done.

10

Now navigate the output folder where u have saved the exe file. In our case we provided the same folder where our jar and class files are located. In below screenshot you can see that test.exe file has been created.

111

Now double click test.exe and message box(“executable was created using evalustion version of exe4J”) will open. Just click ok. Then application will run. In our program we created a frame so frame will get displayed.

13

So thats it. You are off. Your exe has been created. Now you can distribute this exe to windows user. But i f u want to make a cross-platform distributed file then this methos is not recommended. This is for only windows environment.

Thanks.

Posted in Tools, Tutorials | Tagged , , , | 2 Comments

Setting up Slick 2D with netbeans 6.5.1


Slick2D engine is a high performance 2d game library based on a LWJGL(Lightweight Java Game Library). You can see the current features of Slick2D in their site. Download the library from here.
You can check the games made in Slick2D engine http://www.cokeandcode.com/ and http://slick.cokeandcode.com/gallery.php.

Tutorials : There are good and easy to go tutorials for beginners.

Now download the library. So here i’ll be telling how to setup the library with netbeans 6.5.1 so that u can write compile and run slick games easily and fast. I am using Ubuntu 8.04(Hardy heron), steps are similar for setting up in windows.

STEP 1: Download the library and save it in some appropriate place.
STEP 2: Open your Netbeans 6.5.1.
STEP 3: Go to tool->libraries. Library Manager window will open. Click New Library. Give it a name Slick. Then click OK.

screenshot-11

STEP 4: Now click classpath tab. Click Add Jar/Folder. Browse the folder where u have saved Your slick library. Go to lib folder and add all the jar files except slick.jar. Click OK

screenshot-2

STEP 5: Click JavaDoc tab. Click add/zip floder. Browse ur slick folder and select javadoc folder and add it. So done. Click OK.

screenshot-3

STEP 6: Ok so your slick library has been created. Now few steps remaining to complete the full set up. Create a new java project called SlickTest. Now Right Click SlickTest project, then click properties. Project properties window will open up. At left side, under categories select Libraries. Now at right side click Compile tab. Now Click Add Jar/Folder. Browse ur slick folder, go to lib folder, select slick.jar and add it.

screenshot-4

STEP 7: Now click Run tab. Click Add Library. Add Library window will open up. From there select Slick library that we previously created. Then add it.

screenshot-5

FINAL STEP 8 : Now at left side select Run. At Right side, go to VM Options, there u have to provide the parameter/argument that will link lwjgl libraries to your application. So at VM Options textbox, For Ubuntu users write: -Djava.library.path=lwjgl library path For Windows user write: -Djava.library.path=”lwjgl library path”. And Click Ok

Thats it Windows users have to put the path within double quotes. Here lwjgl library path is the path to the location where .so files for ubuntu linux(liblwjgl.so, liblwjgl64.so, libodejava.so,libopenal.so etc) and .dll for windows(liblwjgl.dll, liblwjgl64.dll, libodejava.dll,libopenal.dll etc) are located.

For windows user .dll files comes with slick library but linux users have to download the native .so lib files.

So now you are done and lets write a simple program for testing. This code will just create a window. Create a class called Test under the project that we had created.

package com.padam.testing;

import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;

/**
*
* @author padam
*/
public class Test extends BasicGame{

public Test(String name){
super(name);
}

public static void main(String[] args){
try {
AppGameContainer container = new AppGameContainer(new Test(“Game”));
container.setDisplayMode(800,600,false);
container.start();
} catch (SlickException e) {
e.printStackTrace();
}
}

@Override
public void init(GameContainer gc) throws SlickException {

}

@Override
public void update(GameContainer gc, int delta) throws SlickException {

}

public void render(GameContainer gc, Graphics g) throws SlickException {

}

}

NOTE: Linux and Mac users must download the lwjgl library. Then browse the folder and go to native folder. There choose your native OS folder. That will be your lwjgl library path thatt will go to VM Options parameter as specified on last step or you can copy the .so/native files to your convenient location and provide that path to VM Options parameter.
Now after this just test the above code. You may get a runtime error saying:

Exception in thread “main” java.lang.LinkageError: Version mismatch: jar version is ‘16′, native libary version is ‘17′
at org.lwjgl.Sys.(Sys.java:105)
at org.lwjgl.opengl.Display.(Display.java:128)
at org.newdawn.slick.AppGameContainer$1.run(AppGameContainer.java:39)
at java.security.AccessController.doPrivileged(Native Method)
at org.newdawn.slick.AppGameContainer.(AppGameContainer.java:36)
at com.padam.testing.Test.main(Test.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)

Linux/Mac/Solaris might face this problem because lwjgl jar files that comes with slick might be of older version which won’t match with the new lwjgl native .so/native files that u have downloaded. This means that the lwjgl jar files and lwjgl native/ .so files doesn’t match. So what u have to do is browse lwjgl folder that u have downloaded and go to jar folder and copy all the jar files and paste/replace the old jar files in the lib folder located in slick folder or location of slick library.

So Thats it. If u face any problem, comment it.

Thanks.

Posted in Tutorials, developer | Tagged , , , , | 8 Comments

2D Sprite Rotation using Opengl with SDL

Rotating 2D Sprite: In my previous post i showed how to move a 2D sprite in two dimensional screen using Opengl with SDL. Now in this post i’l show how to rotate a 2D sprite using Opengl with SDL.

In Opengl, rotation can be made about x axis, y axis and z axis. In different axis rotation occurs differently like:

about X axis: like closing your laptop

about Y axis: like turning a page in a book

about Z axis: like the hands of a clock

So to rotate our 2D sprite we use glRotatef(angle,x,y,z). If you want to rotate about x axis the the value of x will be 1.0, y and z will be 0.0. How much angle do you want to rotate your sprite is determined by the value of angle to glRotatef() parameter.

So here is the drawImage() function to draw and rotate the 2D sprite:

void drawImage()
{
// Clear the screen before drawing
glClear( GL_COLOR_BUFFER_BIT );
glTranslatef(300.0,200.0,0.0);
// Bind the texture to which subsequent calls refer to
glBindTexture( GL_TEXTURE_2D, texture );
glBegin( GL_QUADS );
// Top-left vertex (corner)
glTexCoord2i( 0, 0 );
// Bottom-left vertex (corner)
glTexCoord2i( 1, 0 );

// Bottom-right vertex (corner)
glTexCoord2i( 1, 1 );

// Top-right vertex (corner)
glTexCoord2i( 0, 1 );

glEnd();
glLoadIdentity();
SDL_GL_SwapBuffers();
}

In opengl, rotation happens about origin of the screen i.e(0,0). But we want rotation to happen about the centre of the 2D sprite. So instead of drawing the top left vertex at 0,0 you draw it at -imgWidth / 2, -imgHeight / 2, you draw the bottom right vertex at imgWidth / 2, imgHeight / 2, etc, etc. Our size of the quad is 128*128 as we are mapping the texture of size 128*128 to quad. So we’ll draw our quad as (-64,-64) to (64,64) so that (0,0) is directly at the center of the 2D sprite and when we rotate our sprite then rotation will happen about the center of the 2D sprite.

while( quit == false )
{
if( SDL_PollEvent( &amp;event ) )
{
//If a key was pressed
if( event.type == SDL_KEYDOWN )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_LEFT:
LEFT=true;
break;
case SDLK_RIGHT:
RIGHT=true;
break;
case SDLK_ESCAPE:
quit=true;
break;
}
}
//If a key was released
else if( event.type == SDL_KEYUP )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_LEFT:
LEFT=false;
break;
case SDLK_RIGHT:
RIGHT=false;
break;
}
}
}
if(LEFT==true){
spin=spin+2;
if(spin&gt;360.0)
spin=spin-360.0;
drawImage();
}
else if(RIGHT==true){
spin=spin-2;
if(spin&gt;360.0)
spin=spin-360.0;
drawImage();
}

In while loop inside main function we are handling key event. As user presses left arrow key then we increment the angle and redraw the 2D sprite. I have used the same style as in previous posts i.e i have used two bool state variables(LEFT and RIGHT), when user presses left arrow key then LEFT becomes TRUE then angle is updated and 2D sprite is redrawn with rotation.

In this program, when left arrow key is pressed then sprite rotates towards east and when right arrow key is pressed then sprite rotates towards west.

 2D Sprite after rotation

2D Sprite after rotation

Here is the full source code

#include "SDL.h"
#include "SDL_image.h"
#include "SDL_opengl.h"
 
#include &lt;stdio.h&gt;
 
GLuint texture=NULL; //this is a handle to our texture object
GLenum texture_format=NULL;
GLint nofcolors;
SDL_Event event;
static GLfloat spin=0.0;
float x=100,y=100;
bool LEFT=false;
bool RIGHT=false;

int loadImage()
{
SDL_Surface *surface; // this surface will tell us the details of the image

if ( (surface = IMG_Load(“flower.png”)) ) {

// Check that the image’s width is a power of 2
if ( (surface-&gt;w &amp; (surface-&gt;w – 1)) != 0 ) {
printf(“warning: image.bmp’s width is not a power of 2\n);
}

// Also check if the height is a power of 2
if ( (surface-&gt;h &amp; (surface-&gt;h – 1)) != 0 ) {
printf(“warning: image.bmp’s height is not a power of 2\n);
}

//get number of channels in the SDL surface
nofcolors=surface-&gt;format-&gt;BytesPerPixel;

//contains an alpha channel
if(nofcolors==4)
{
if(surface-&gt;format-&gt;Rmask==0×000000ff)
texture_format=GL_RGBA;
else
texture_format=GL_BGRA;
}
else if(nofcolors==3) //no alpha channel
{
if(surface-&gt;format-&gt;Rmask==0×000000ff)
texture_format=GL_RGB;
else
texture_format=GL_BGR;
}
else
{
printf(“warning: the image is not truecolor…this will break “);
}

// Have OpenGL generate a texture object handle for us
glGenTextures( 1, &amp;texture );

// Bind the texture object
glBindTexture( GL_TEXTURE_2D, texture );

// Set the texture’s stretching properties
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

glTexImage2D( GL_TEXTURE_2D, 0, nofcolors, surface-&gt;w, surface-&gt;h, 0,
texture_format, GL_UNSIGNED_BYTE, surface-&gt;pixels );
}
else {
printf(“SDL could not load image.bmp: %s\n, SDL_GetError());
SDL_Quit();
return 1;
}

// Free the SDL_Surface only if it was successfully created
if ( surface ) {
SDL_FreeSurface( surface );
}
}

void drawImage()
{
// Clear the screen before drawing
glClear( GL_COLOR_BUFFER_BIT );

glTranslatef(300.0,200.0,0.0);
glRotatef( spin, 0.0, 0.0, 1.0 );

// Bind the texture to which subsequent calls refer to
glBindTexture( GL_TEXTURE_2D, texture );

glBegin( GL_QUADS );
// Top-left vertex (corner)
glTexCoord2i( 0, 0 );
glVertex3f( -64, -64, 0 );

// Bottom-left vertex (corner)
glTexCoord2i( 1, 0 );
glVertex3f( 64, -64, 0 );

// Bottom-right vertex (corner)
glTexCoord2i( 1, 1 );
glVertex3f( 64, 64, 0 );

// Top-right vertex (corner)
glTexCoord2i( 0, 1 );
glVertex3f( -64, 64, 0 );
glEnd();
glLoadIdentity();

SDL_GL_SwapBuffers();
}

int init()
{
SDL_Surface *screen;

// Slightly different SDL initialization
if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
printf(“Unable to initialize SDL: %s\n, SDL_GetError());
return 1;
}

SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

screen = SDL_SetVideoMode( 640, 480, 16, SDL_OPENGL|SDL_FULLSCREEN);
if ( !screen ) {
printf(“Unable to set video mode: %s\n, SDL_GetError());
return 1;
}
}

void init_GL()
{
// Set the OpenGL state after creating the context with SDL_SetVideoMode

glClearColor( 0, 0, 0, 0 );

glEnable( GL_TEXTURE_2D ); // Need this to display a texture

glViewport( 0, 0, 640, 480 );

glMatrixMode( GL_PROJECTION );
glLoadIdentity();

glOrtho( 0, 640, 480, 0, -1, 1 );

glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
}

void clean_up()
{
glDeleteTextures( 1, &amp;texture );

SDL_Quit();
}

int main(int argc, char *argv[])
{
//Make sure the program waits for a quit
bool quit = false;

init();
init_GL();
loadImage();
drawImage();

while( quit == false )
{
if( SDL_PollEvent( &amp;event ) )
{
//If a key was pressed
if( event.type == SDL_KEYDOWN )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_LEFT:
LEFT=true;
break;
case SDLK_RIGHT:
RIGHT=true;
break;
case SDLK_ESCAPE:
quit=true;
break;
}
}
//If a key was released
else if( event.type == SDL_KEYUP )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_LEFT:
LEFT=false;
break;
case SDLK_RIGHT:
RIGHT=false;
break;
}
}
}

if(LEFT==true){
spin=spin+2;
if(spin&gt;360.0)
spin=spin-360.0;
drawImage();
}
else if(RIGHT==true){
spin=spin-2;
if(spin&gt;360.0)
spin=spin-360.0;
drawImage();
}

}

clean_up();
return 0;
}

So Thats it. I hope this of any help to you and gives u some idea on rotation of 2D sprite using opengl and sdl.

Thanks.

Posted in Opengl with SDL, Tutorials | Tagged , , , , | 1 Comment

Moving 2D Sprite using Opengl with SDL


Moving 2D Sprite: SO on my previous post i showed you the code to display a 2D sprite using OpenGl with SDL. Now i’ll show how to move a 2D Sprite using opengl with sdl. There will be some minor changes in the code and rest will be the same.

I’ll write the new changes in black and bold and rest are the same as in previous code on my previous post.

Here is the full code:

#include "SDL.h"
 
#include "SDL_image.h"
 
#include "SDL_opengl.h"
 
#include &lt;stdio.h&gt;

GLuint texture=NULL; //this is a handle to our texture object

GLenum texture_format=NULL;

GLint nofcolors;

SDL_Event event;

bool LEFT=false;

bool RIGHT=false;

float x=100.0,y=100.0;

int loadImage()

{

SDL_Surface *surface; // this surface will tell us the details of the image

if ( (surface = IMG_Load(“flower.png”)) ) {

// Check that the image’s width is a power of 2

if ( (surface-&gt;w &amp; (surface-&gt;w – 1)) != 0 ) {

printf(“warning: image.bmp’s width is not a power of 2\n);

}

// Also check if the height is a power of 2

if ( (surface-&gt;h &amp; (surface-&gt;h – 1)) != 0 ) {

printf(“warning: image.bmp’s height is not a power of 2\n);

}

//get number of channels in the SDL surface

nofcolors=surface-&gt;format-&gt;BytesPerPixel;

//contains an alpha channel

if(nofcolors==4)

{

if(surface-&gt;format-&gt;Rmask==0×000000ff)

texture_format=GL_RGBA;

else

texture_format=GL_BGRA;

}

else if(nofcolors==3) //no alpha channel

{

if(surface-&gt;format-&gt;Rmask==0×000000ff)

texture_format=GL_RGB;

else

texture_format=GL_BGR;

}

else

{

printf(“warning: the image is not truecolor…this will break “);

}

// Have OpenGL generate a texture object handle for us

glGenTextures( 1, &amp;texture );

// Bind the texture object

glBindTexture( GL_TEXTURE_2D, texture );

// Set the texture’s stretching properties

glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

glTexImage2D( GL_TEXTURE_2D, 0, nofcolors, surface-&gt;w, surface-&gt;h, 0,

texture_format, GL_UNSIGNED_BYTE, surface-&gt;pixels );

}

else {

printf(“SDL could not load image.bmp: %s\n, SDL_GetError());

SDL_Quit();

return 1;

}

// Free the SDL_Surface only if it was successfully created

if ( surface ) {

SDL_FreeSurface( surface );

}

}

void drawImage()

{

// Clear the screen before drawing

glClear( GL_COLOR_BUFFER_BIT );

glTranslatef( x, y, 0 );

// Bind the texture to which subsequent calls refer to

glBindTexture( GL_TEXTURE_2D, texture );

glBegin( GL_QUADS );

// Top-left vertex (corner)

glTexCoord2i( 0, 0 );

glVertex3f( 100, 100, 0 );

// Bottom-left vertex (corner)

glTexCoord2i( 1, 0 );

glVertex3f( 228, 100, 0 );

// Bottom-right vertex (corner)

glTexCoord2i( 1, 1 );

glVertex3f( 228, 228, 0 );

// Top-right vertex (corner)

glTexCoord2i( 0, 1 );

glVertex3f( 100, 228, 0 );

glEnd();

glLoadIdentity();

SDL_GL_SwapBuffers();

}

int init()

{

SDL_Surface *screen;

// Slightly different SDL initialization

if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {

printf(“Unable to initialize SDL: %s\n, SDL_GetError());

return 1;

}

SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

screen = SDL_SetVideoMode( 640, 480, 16, SDL_OPENGL|SDL_FULLSCREEN);

if ( !screen ) {

printf(“Unable to set video mode: %s\n, SDL_GetError());

return 1;

}

}

void init_GL()

{

// Set the OpenGL state after creating the context with SDL_SetVideoMode

glClearColor( 0, 0, 0, 0 );

glEnable( GL_TEXTURE_2D ); // Need this to display a texture

glViewport( 0, 0, 640, 480 );

glMatrixMode( GL_PROJECTION );

glLoadIdentity();

glOrtho( 0, 640, 480, 0, -1, 1 );

glMatrixMode( GL_MODELVIEW );

glLoadIdentity();

}

void clean_up()

{

glDeleteTextures( 1, &amp;texture );

SDL_Quit();

}

int main(int argc, char *argv[])

{

//Make sure the program waits for a quit

bool quit = false;

init();

init_GL();

loadImage();

drawImage();

while( quit == false )

{

if( SDL_PollEvent( &amp;event ) )

{

//If a key was pressed

if( event.type == SDL_KEYDOWN )

{

switch( event.key.keysym.sym )

{

case SDLK_LEFT:

LEFT=true;

break;

case SDLK_RIGHT:

RIGHT=true;

break;

case SDLK_ESCAPE:

quit=true;

break;

}

}

//If a key was released

else if( event.type == SDL_KEYUP )

{

switch( event.key.keysym.sym )

{

case SDLK_LEFT:

LEFT=false;

break;

case SDLK_RIGHT:

RIGHT=false;

break;

}

}

}

if(LEFT==true){

x-=2;

drawImage();

}

else if(RIGHT==true){

x+=2;

drawImage();

}

}

clean_up();

return 0;

}

In above code i have used two bool variable(LEFT and RIGHT) and two float variables(x and y) to store the position of  sprite. In the main function inside the loop we are taking the key input from the user. So when the user press left arrow key “LEFT bool variable is assigned TRUE” and when user releases the left arrow key ” LEFT bool variable is assigned FALSE”. Same applies for pressing right arrow key. So in this code :

if(LEFT==true){
x-=2;
drawImage();

}

else if(RIGHT==true){

x+=2;

drawImage();

}

when left arrow key is pressed “LEFT bool variable becomes TRUE” and x position of sprite is incremented by 2. Then we draw the sprite again. And when left arrow key is released “LEFT bool variable becomes FALSE” which means x position of sprite should not be updated. Same concept applies for moving right.

Now we have code to update the x and y position of  sprite. But how to render the sprite with updated x and y coordinates. This is done by gTranslatef(x,y,z) function. It translates the position of sprite. So we’ll be updating x and y to move the sprite, and z will be zero. So in this code:

void drawImage()
{
// Clear the screen before drawing

glClear( GL_COLOR_BUFFER_BIT );

glTranslatef( x, y, 0 );

// Bind the texture to which subsequent calls refer to

glBindTexture( GL_TEXTURE_2D, texture );

glBegin( GL_QUADS );

// Top-left vertex (corner)

glTexCoord2i( 0, 0 );

glVertex3f( 100, 100, 0 );

// Bottom-left vertex (corner)

glTexCoord2i( 1, 0 );

glVertex3f( 228, 100, 0 );

// Bottom-right vertex (corner)

glTexCoord2i( 1, 1 );

glVertex3f( 228, 228, 0 );

// Top-right vertex (corner)

glTexCoord2i( 0, 1 );

glVertex3f( 100, 228, 0 );

glEnd();

glLoadIdentity();

SDL_GL_SwapBuffers();

}

when we update the position of x and y then we call the above function where we have included new code glTranslatef(x,y,z) which will make the sprite to be drawn in given x.y and z location.

So thats it. I hope this will give u some pretty basic idea. Now you can write your own code for moving 2d Sprite.

Thanks.

Posted in Opengl with SDL, Tutorials | Tagged , , , , , | Leave a comment
  • Become a GaanZa Fan

    GaanZa on Facebook