Adding Multiple GameObjects LWJGL - java

I am looking at making pong using LWJGL.
Well I was doing the LWJGL tutorials, by thebennybox, and had it working, I then wrote it out again when my old hard drive died (R.I.P). What I am trying to do is add multiple GameObjects and have them show up, I worked out that they are being added to the GameObject objects list. Here is the code in my dropbox: https://www.dropbox.com/s/ccs37jqm1b5oi84/lwjglGame.zip
It is a little too big to have on here but here is a main part:
This is from Game.java:
private ArrayList<GameObject> objects;
public Game() {
objects = new ArrayList<GameObject>();
GOplayer player = new GOplayer(0, Display.getDisplayMode().getHeight()/2);
GOball ball = new GOball(Display.getDisplayMode().getWidth()/2-GOball.SIZE-2, Display.getDisplayMode().getHeight()/2);
objects.add(player);
objects.add(ball);
}

Your problem occur because of two problems.
1: Within the GameObject class your float variables x and y are static. Which they should not be!
2: Within the Draw class you call glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); this should not be there as well, because what that does is clearing the depth and color buffer, which results in each time your render a "rect" using you Draw.rect that clears the screen, so in the end, only the last rendered "rect" will be shown!
Also you don't really need to clear the GL_DEPTH_BUFFER_BIT, since within the initGL() you disable it using glDisable(GL_DEPTH_TEST); (though GL_DEPTH_TEST is disabled by default). And since your only working in 2D space then there are no actual depth, unless you're using the GL_DEPTH_TEST to sort the 2D space, while still using Z values.
Advice
Here is just some advice from me, if you don't 100% know all the main/basic keywords within Java, or just don't know how to use them correctly then starting off by creating a Game with OpenGL using LWJGL, will become extremly hard for you at some point. I suggest you start with something a lot easier or start off by reading or watching multiple tutorials about the basics of Java.
The reason I'm saying this is that you create a new instance of the class GameObject through GOball, GOplayer and GObox though inside the GameObject you have the float variables x and y those variables you've set as static, which mean that variables are shared and will always be the same. So when you create an GOball and set the x and y that sets the x and y though when you then create the GOplayer and set it's x and y to something else, that will affect the GOball as well so then they will have equally the same x and y always, since the variables are shared!

Related

Java & Slick2d - Object Interaction

In a game I am creating with slick2d to learn Java, I have multiple levels each with one Footballer and multiple other units I want the footballer to be able to interact with. I also want the other units to interact with each other (for example multiple Balls colliding with eachother) (note, some of these units are sometimes of the same class as one another e/g multiple Defenders). I am unsure, however how to detect these interactions and update the units appropriately. For example, I have my Footballer:
public class Footballer extends Unit {
public Footballer(float x, float y){
super("res/ballerpicture", x, y)
}
}
And within this class I have an update function which overrides the update function in the Unit class (allowing me to move the one Footballer according to my input - this is working without issue other than collision detection).
I could then, for example, have loaded on my map 5 balls:
public class Ball extends Unit {
public Ball(float x, float y){
super("res/ballpicture", x, y)
}
}
For an example, I would like to know how to update any one of the balls upon collision with the Footballer, moving them one tile away from the player each time they collide.
My Unit class includes a move method which moves the unit based on an integer direction (left = 1, right = 2 etc...).
Apologies if I have oversaturated this question or haven't included enough information - I'm relatively new to java.
What you are looking for is collision detection.
All objects which are able to interact with each other can have a hitbox, that's in the easiest way one geometrical shape which represents the body of an object. We could for example assume that your ball has a circle as hitbox with the radius of 8 px and your footballer has a hitbox of a rectangle with width 32 px and height 32 px.
When both objects are now moving you have to check whether the boundaries of your hitbox are intersecting with each other, if so: do something, if not keep moving.
In Slick2D all shapes have a method called intersects(Shape s), it returns true if the boundaries of two shapes are intersecting. So basically you just have to implement hitboxes for your objects (make sure to update the hitbox when your object is moving) and then check for intersecting. There are a lot of different ways of implementing collision detection and the internet is providing a lot of ressourcing regarding that topic. I also recommend to take a look at the Shape documentation of Slick2D. It's hard to write a solution for you since I don't know your code but I'm sure you will figure it out and Slick2D provides an easy preimplemented solution for your problem with the intersecting method.
It could look somewhat like the following:
Edit, for multiple balls:
//in your update method
for(Ball ball : allBalls){
if(footballer.getHitbox().intersects(ball.getHitbox()){
//get direction of footballer
ball.move(...)
}
}

Android 2d game collision detection

I developed a 2d game in android studio using SurfaceView,
it's not complex in context of collision, just need to check collision between a moving-point and some static circles, for detect collision for one circle, I simply check if X of the point is between circle minX and maxX && point Y is between minY and maxY of circle.
So for checking collision in whole of the game, I repeat to check above code for all circles in each frame.
Game work so good when I have for example 10 circles, but if I add 30 circles, its FPS decrease so much and I face so much lag!
What should I do for this problem? should I use Box 2d physics ? what does it do for collision detection that games doesn't face lag problem even if there is so much objects which collide together?
Please help me with more detail, because I was wonder how a game engine work and decided to make a simple one, not only wanted to make and release a game(otherwise I could use a ready game engine).
Thanks in advance
As for how game engines do it, it is probably easiest to look at their source code directly, as at least one version of Unity can do it - you can find the source code of Unity here.
In your case, you could potentially trade off increased memory consumption by your app to make collision detections essentially constant-time regardless of the number of circles, as suggested by #SagarGautam in his comment.
What you can do to achieve this is store a 2D array of booleans indicating all map pixels, setting each element to true if it is inside a circle (as per your previous code) or false otherwise. Doing this during the loading phase of the level/map should be fine, because now during rendering you can just look up the pixel coordinates in the array and see if it is inside a circle or not.
In 3d game i use Colliders so check if there is any collider(mesh,box,etc.)
give tag to that objects.and identify them by tag
Example:
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "Enemy")
coll.gameObject.SendMessage("collided", 10);
}
}

J2ME game thread

I'm trying to make a game for J2ME something like the game Zuma, the structure of classes that you need to know is as follow :
-Level class which holds info about a level such as a vector of points (class I made called Point, the path that the balls will follow), vector of balls (class I made called Ball) to hold different balls object, speed (the speed of the balls in that specific level).. (There're more fields but nothing that you need to worry about)
-Frog class (just so you'd know it exists) if you're not familiar wit the game zuma it serves as a controllable turret that can shoot balls.). (No need to worry about the fields in that class)
-MyGameCanvas which obviously extends GameCanvas and implement runnable, holds instance of frog and a level (the currently played level).. (There're more fields but nothing that you need to worry about). The run method serve as a listener for user input if user pressed right rotate the frog (essentially a sprite) by X amount if pressed left rotate by -X amount, pressed OK shoot a ball. Beside taking care of input the thread calls a render method which renders what going on, on the screen and updates balls position from the balls vector (by using the current level instance) using the vector of points (from the level instance aswell), now the problem is that I wanted each level to have different speed, by speed I mean that balls will "roll" (=move) on screen slower, so I can do it with just using the speed value in the Thread.sleep method and increase the sleep time because the run method is taking input from user making the frog movements and input reaction to be slowed down aswell, I thought maybe doing each ball a seperate thread but thats not really good in my opinion because there'll be alot of threads + when I update each ball location on the screen I actually use the WHOLE ball vector from the level instance for things like if a ball need to gove backwards if there's a gap between the ball and the one behind him, or when to render the ball depending if the ball after him is already rendered and on the "track" (the points vector), so I don't really know how I should do it, any advices guidance would be highly appriciated ! Thanks in advance and hopefully you could understand what I wrote.. Also I don't think I need to give code examples really because I don't wanna use what I want to CHANGE what I wrote so it wouldn't really help providing the run/render methods, all you need to know is the structure of the classes I gave you and the fields they have that I told you about.
Various developers use various methods for controlling the speed of sprite-movement.
JavaME is one of the many platforms that requires you to also consider different resolutions and CPU speed. So it's never as simple as just incrementing the x value 1 pixel in each cycle of the main game loop.
Assuming 2 devices with different screen resolution, but otherwise running the same speed. Incremending x value by 1 in the cycle of the game loop, would obviously result in the sprite reaching the end of the screen faster on the small resolution.
Assuming 2 device with the same screen resolkution, but with different CPU's. Incrementing x value by 1 in the cycle of the game loop, would obviously result in the sprite reaching the end of the screen faster on the device with the fastest CPU.
Here is one way of working around that:
Create a variable, call it itemWait (where "item" is the name of the object you want to control the speed for).
The itemWait variable holds a value that tells the game loop how long should pass before next movement.
For example, say that the sprite should wait 40 milliseconds for each pixel it moves. The code would look somewhat like this:
// Variables defined outside the game loop
long lastTime, thisTime;
int cyclems;
int itemTime; // Replace "item" with the name of the object, like e.g. ballTime.
int itemWait = 40; // Wait 40 ms for each movement
int itemPixelsToMove = 1;
while (running == true) { // Game loop
lastTime = thisTime; // Set lastTime to the time-stamp of the previous cycle
thisTime = System.currentTimeMillis(); // Get the current time-stamp
cyclems = (int) (thisTime - lastTime); // How long did it take to execute previous loop
itemTime += cyclems; // How long has passed since last move
while (itemTime > itemWait) { // If it's time to move
itemTime -= itemWait;
moveItem(itemPixelsToMove);
}
// Do other game logic
// Draw everything
// Handle input, unless you handle it with keyPressed()
}
Using that method, the code doesn't care how fast the device is. And if you want to port the game to a different screen resolution, you can simply change either itemPixelsToMove or itemWait.
For example, say you set itemWait = 40; for 240x320 resolutions. Then you would set it to 40/240*480 = 80 for 480x640 resolutions. (This requires of course, that you also scale the graphics).
We've used this approach in www.PirateDiamonds.com - in case you're curious. The same code runs on whatever screen resolution you want.

How to make a simple mini map for a Java rpg game

I have an array that holds the names and then displays the appropriate graphics using:
public void paintComponent(Graphics g){
for(int i = 0; i<20; i++)
{
for(int j = 0; j<20; j++)
{
if(testMap.getData(i+(rowX-7), j+(columnY-7)).indexOf("rock") >= 0)
{
g.drawImage(image3, j*50 + 5*add, i*50 + 5*add2, 50, 50, this);
}
}
}
This works well displaying the actual graphics of my game. However, for my minimap, I do the same thing, with different values and increased numbers in the 'i' and 'j' in the for loop. This creates a smaller version of the map with a bigger scope, which leaves me with this. (Note, I only included one of the drawImage() methods, I removed the rest here to make the code more readable):
This is pretty much my desired effect (aside from the positioning, which I can change easily), however, this only shows a smaller version of what I already see on the screen. Any larger than about 20 x20, though, and the game begins to lag heavily -- probably something to do with the terrible way that I coded it.
I have tried replacing the images with squares using fillRect, but it does not help the issue.
Here is the code of my main class if anybody would like to take a look: http://pastebin.com/eEQWs2DS
The for loop within the paintComponent method begins at around line 3160, the loop for the main display is around 2678. I set up the Jframe at around 1260.
So, with all that said, basically my question is this:
Is there a better, more efficient way to create my minimap? My idea was to generate an image at the beginning of the program so that the game wouldn't have to recalculate every time the frame refreshes. I could create the map in advance, but I would have to manually update that every time I changed the map, which is definitely a hassle. I am having trouble researching how to do the former. My other idea is to slow the refresh rate of the minimap only, but I also do not know how to do that.
Other than that, if there are any simple fixes to the lag issue, please enlighten me. I apologize for the very, very messy code -- This is my first time programming anything with a display so I sort of just...hacked at it until it worked.
I don't know how easy this would be with your implementation, but instead of drawing an image, perhaps you could draw a square of a certain color based on what type of tile it should be?
For instance if you're looping through your list of tiles and you find a grass tile, you would first draw the grass tile at its proper location, then draw a smaller green square on the minimap.
The downside to this is that first you'd have to define what colors to use for the tiles, or perhaps when you load the tiles you can compute an average color for each one, and then just use that. Another issue is that the houses may not translate well on to the minimap, since the tiles have much more detail. You could draw some kind of house icon on the minimap instead of actually drawing any of the house tiles, though.
Basically, you want to use simpler representations of the objects in your map on the minimap, since it's smaller and less detail can be drawn anyway.
Have a look at how I do it in Tyrant (a Java roguelike):
https://github.com/mikera/tyrant/blob/master/src/main/java/mikera/tyrant/LevelMapPanel.java
Key tricks:
Use an offscreen BufferedImage. Cache this to avoid recreating it each time you paint.
Use an int[] array to setup up a single colour for each tile
Use setRGB with the array to draw all the map at once
Draw the mini-map at x2 zoom to get 2x2 pixel blocks for each tile.
If you want to be even more efficient, keep a changed flag and only update the mini-map BufferedImage when something visible on the mini-map changes. I didn't think it was worth it as the above is already very efficient, but YMMV.

How to animate Rectangle on a Path2D object in Graphics2D context

I have just started learning basics about Graphics2D class, So far I am able to draw different objects and implements ActionListener to actually move them on screen by onKeyPress. So far so good, While I thought of doing something more complicated. I want to give a path to my object and animate it on that particular path only.
Something like, I will draw a line on sky and a plane should stick with that drawn line and keep it self to fly on that particular line. Now is it possible?
I don't need any sort of code, But few different method or ideas will let me get started working on this. A visualise elaboration of my idea is as below.
Start Point :
End Point :
Now as shown above, my yellow box(in future plane) should stick with given path while animating(path grey line)
My research so far,
I have searched my buzz words such as path in java, and found Path2D and GeneralPath classes, Does anyone know if I can use that to solve this.
Thanks
Great !
It reminds me of my first steps in IT. How much I enjoyed all this simple math stuff but that make things move on screen. :)
What you need is actually a linear interpolation . There are other sorts of interpolation and some api offer a nice encapsulation for the concept but here is the main idea, and you will quite often need this stuff :
you must rewrite your path
y = f (x )
as a function of time :
at time 0 the item will be on start position, at time 1 it will reach the end. And then you increment time (t) as you wish (0.001 every ms for instance).
So here is the formula for a simple linear path :
x = xstart + (xend-xstart) * t
y = ystart + (yend-ystart) * t
when t varies, you object will just move linearly along the path, linearly has speed will be constant on all the path. You could imagine some kind of gravtity attraction at end for instance, this would be modeled by a quadratic acceleration (t^2 instead of t) ...
Regards,
Stephane
First, make the ability to move from point a to point b. This is done with simple algebra.
Second, make the ability to take a path and translate it into points. Then when you're going to do curves, you're really just moving from point to point to point along that curve.
This is the most elementary way to do it and works for most instances.
What your talking about is simple 2D graphics and sprites. If that is all you need then for Java take a look at Java 2D Sprites If your leaning more towards or will eventually go with camera perspectives and wanting to view the animation from diferent angles the go with Java 3D from the OpenSource Java 3D.org. Either way what you want is a simple translating of the object along a line, pretty simple in either 2D or 3D.
You can try going trough the code of my open source college project - LANSim. It's code is available in Code menu. It does similar to what you are trying to do.

Categories

Resources