Java-Gaming.org Hi !
Featured games (85)
games approved by the League of Dukes
Games in Showcase (612)
Games in Android Showcase (173)
games submitted by our members
Games in WIP (659)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
   Home   Help   Search   Login   Register   
  Show Posts
Pages: [1] 2
1  Game Development / Game Mechanics / Re: Collision between different maps (2d lwjgl) on: 2015-06-14 20:27:49
Quote
I'm gonna stay away from static variables from now on xD.
Fwiw, I use static variables all the time. If you only ever need one at a time, static makes sense. Some people put it in an instance anyway (someone mentioned that here), and I'm sure there are reasons for that, but I have not yet felt the need to do so with stuff where you only need one of it. (Constants like TILE_WIDTH, settings like mouseSensitivity, classes full of utility functions, etc. I don't need to instantiate multiple LibMaths, so I just make everything in it static and go LibMath.thing() instead of lm = new LibMath(); lm.thing().)

But if you want something to have multiple versions of it floating around (like having multiple different levels floating around), you're got the right idea: make instances instead of separate classes with static stuff.
2  Game Development / Game Mechanics / Re: Collision between different maps (2d lwjgl) on: 2015-06-14 15:43:23
Quote from: Phased
If you had an exam question, java is pass by value.

Although it seems to be pass by reference, its not pass by reference, as long as you remember.
I actually did not know this. I had been taught that primitives are by value, everything else is by reference. Maybe they were simplifying? At any rate, if you modify an Object, you can expect it to chance everywhere that object exists because the others are all pointing at the same object. Or at least, that's how it works practically. I guess that's not true on a deep, technical level?

I had not heard that there was some kind of exception with null.

Also with arraylists............ you're saying they are always passed by reference, unlike other data which is passed by value?

...

So really my whole issue was never an issue in the first place because ArrayLists handled the situation anyway?
Err... no, everything that isn't an int, long, float, double, byte, char (am I forgetting anything?) is by value. Everything that starts with a capital letter (is a class) is by reference or might as well be (even if I'm hearing from other posters that this is technically untrue, you can pretend it is). Some things like Strings are designed to not be modified, so you end up getting a new one every time you do a method that changes it or combines it or whatever, so you end up using them more like they're being passed by value, even though I'm pretty sure you're not.

Just pretend any Object is passed by reference, any primitive is not. That's close enough to true that I didn't realize it wasn't until now, hundreds of programming hours later.

Quote
So... should I do collision through an arraylist in the level, or through JBox2D?
...
Lol so ya, ArrayLists vs JBox2d (Collision Library)
I don't think the two are mutually exclusive. Box2d will I assume do your collision checking for you (I've never used it before), and you can give it your entities in whatever form, stored whatever way, that it wants. For your purposes, levels can still have arraylists of entities. You can have different collections (like arraylists) for different things. You could have a list of entities the level uses for "what is alive", a list of entities that are used for "what can collide", etc. Some entities might be in more than one list, and if you modify an entity in one list, it will also be modified in whatever other lists it's in, because it is the same object. Don't imagine that a list has objects inside of it. Imagine that a list has a bunch of wires connecting it to other objects.

Quote
Also regarding the level setup, I guess it just seems like it's 10 time more complicated using data, but once I understood it, everything may be simpler.
It's not, strictly speaking, simpler. But it is much more flexible and reusable.

Quote
So I know this has been explained multiple times, but would i just create separate objects that do stuff on their own, and use an identifier in the "data" for the level to spawn that in? Cause wouldn't I need to hardcode each identifier then? Also if I used data, and let's say I want one block to be 100 x 100, while I want that same block to be 150 x 100 in another place. Every time I would want to change the size, I would need to make a new identifier... which may get kinda sloppy and tedious. Is this correct in what I'm thinking? Or is there a better way of using data for a level. Lol sorry if I sound like I don't know what I'm talking about, but I just wanna ask any possible questions regarding this now so I have a much better understanding.
If you have an entities that needs to appear in multiple levels, you have two choices. 1) Maintain a list of universal entities and, whenever a new level is made, tell the level to add that list to its list so it has both the common objects and the unique-to-itself objects. Again, these are references/pointers/whatever, they still only exist as one thing (in terms of logic), you're just wiring multiple lists to connect to them. 2) When a level is made, include in that level's data file the info you need to recreate the object. You're technically forgetting about the old object (let's say an entity called Foo) and then making a new one (also called Foo) that serves the same purpose. It just depends what makes more sense to you.

As far as differences between levels, here's how you need to approach it.
1) Decide all of the different things a level needs to be able to have. Events of various types, tiles of different sorts, waves that define what shows up when, entities that are always there, whatever. Each of those needs to have a blueprint (probably a class) somewhere in your code so that you can make however many things of that type whenever you need them.
2) Figure out what the level needs to know about each thing in order to create it from that blueprint. For example, for an entity, it may need some kind of keyword that tells you what type of entity it is, some numbers for where it's positioned, maybe a minutes:seconds value for when it needs to show up, etc. An event might need to have a keyword for what sort of event it is (trigger a wave of enemies, play a cutscene, etc.), along with whatever info is unique to that particular event and not shared by all events of that type.
3) The level data file just needs to include that information.
4) When a level loads, it reads that information, then creates all of the objects it needs using that info as a guide. One level might have 5 Wave objects and another might have 1 or 0, but all levels will, when they load, create a wave for each one specified in the data, using the information in the data (start time, list of enemies to create when the wave starts); create a list of waves (maybe sorted by when they're supposed to show up); and add each wave to that list.

Quote
Thank you by the way everyone for the help/advice.
No problem! Feel free to click the appreciate/medal button on anyone's posts that you, well, appreciated.
3  Game Development / Game Mechanics / Re: Collision between different maps (2d lwjgl) on: 2015-06-14 14:31:48
Well, this is a big one. Sorry for the giganto post, but I did see stuff to reply to throughout your post. Smiley

Lol, I think people just don't understand my problem here.

First Question: Yes, a brand new java class file. As of right now I would create an instance of it in my main driver whenever clicked, but that's just how I'm doing it right now.
Ok, thanks for clarifying. I think I agree with those who have been saying you are better off with a single Level class and making a new instance of it for each level, setting that instance up with whatever is unique to the level, which you obtain by reading a file. Someone earlier explained why this can be useful. You have to have the data somewhere (place a foo enemy here, start the player there, mark these tiles to explode when the player touches them, etc.), either in your code or in separate files, and I recommend doing it in separate files. It won't make a ton of difference if you're in a small game and the only person working on it, but it's huge when you're working with other people: now they don't all have to launch an IDE and learn Java and recompile the game every time they want to make a change.

Quote
With by ref and by val... I clearly do understand it. My whole issue is java is by-val, which is why I'm asking for help. I know the way I'm doing it is bad (with the arraylist), but that's why I'm here. I don't know why you all think I don't understand it, as I clearly do.
I think this is where some confusion lies. I'll take your word for it that you know by-val means "copying" and by-ref means "both are still pointing at the same thing", but Java passes the arraylist by reference. If you think that passing an arraylist around makes copies of it and everything in it, I believe you are mistaken. It works better than you think!

Quote
Now what you were saying in the main, you're saying no matter what I do, I'm accessing GameMain. That may actually work. Cause then I could access the updated/live arraylist, and update data in it. After thinking about this more, I get why I would just use a Level class... but I still feel like using a new class file for each level will be 10000 times easier.
Here, when you talk about each entity accessing the same live arraylist, this only works because the objects can get they arraylist by reference. When they access it, they're not getting a copy. This would be the case no matter how you did it unless you were making a new arraylist every time, giving it the items from the old list. Even if you did that, the items in the list would still be the same, so if you have enemy1 in listA and also in listB, any changes to enemy1 will be reflected in both lists, because enemy1 is the same object. However, if you removed enemy1 from listA, it would still be in listB.

If you pass a listEntities around to every entity that asks for it, and an entity makes a change to another entity in that list, the change sticks. The entity in that list has been updated. The next thing to ask for the list will get the exact same list with the exact same objects, and if it asks for the same changed entity, it will get that changed entity. If entityFoo changes entityBar in listA, then entityCow looks at entityBar in listA, entityBar will have the change.

Quote
Second Question: The only issue I'm having personally is updating the arraylist. I tried with an earlier copy of my game passing the arraylist to each creature.... and it worked fine. The issue though was like for each bullet, to actually remove health from an existing creature. The point is, I can access an arraylist just fine, but updating the original one which is being drawn I just don't know how to do. I mean, the point is atm I'm using a static arraylist and hardcoding that in each creature (Player, Enemy).

... I just need a way to both access and update the  arraylist in the level class (for multiple levels, not just the first one). Maybe I'm just being a huge derp, but if I pass the level to each creature, that's just a copy. So... I couldn't really update health that way.

Of course, if this isn't a good idea I'm always open to new ideas for collision.
Alright, let me define the problem here: you need to check if a bullet entity is colliding with a creature entity that is on the same level as the bullet entity. Example fake code:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
//in wherever you handle movement
for(Entity e : GameMain.getCurrentLevel().getEntities()) {
  entity.moveThyself(); //or whatever. if this entity is a bullet, it would move itself based on whatever rules bullets use
}

//in Entity
public Rectangle getCollisionBox() {
  //get or create a rectangle indicating the area that this entity takes up for purposes of collision
}
public void takeDamage(int amount) {
  //modify our hp, check if we're dead, etc.
  //if we are dead, either ask level to remove us (maybe a Level.removeEntity() method)
  //or just wait and have a spot at the end of every game loop where something tells
  //the level to removeDead(). level.removeDead() could then go through and remove
  //any dead entities from its entity list
}

//in Bullet, which extends Entity
public void moveThyself() {
  //blah blah blah, we move around really fast in a direction we decided when we made the bullet
  ArrayList<Entity> collidedWith = GameMain.getCurrentLevel().checkCollisions(this, movementVector); //tell the level that this thing moved a certain amount in a direction
  for(Entity e : collidedWith) { //damage everything the bullet touched
    e.takeDamage(power); //power is a field here on Bullet
  }
  //if you only want to damage the first thing the bullet touched,
  //check that collidedWith.size() > 0, then do collidedWith.get(0).takeDamage(power)
}

//in Level
//assuming we have an arraylist of entities that can be gotten by getEntities()
public ArrayList<Entity> checkCollisions(Entity mover, Vector v) {
  ArrayList<Entity> collidedWith = new ArrayList<>();
  for(Entity e : getEntities()) {
    if(e != mover && mover.getCollisionBox().intersects(e.getCollisionBox())) { //I'll just assume you use rectangles for collision
      collidedWith.add(e);
      //do stuff with the vector info if we care about that
    }
  }
  return collidedWith;
}


Quote
If I did levelOne = new Level("levelOne.lvl") (which wasn't what I was talking about btw), then the only thing unique to that level is the pieces being put into the map. Therefore I can't actually code anything special to that map.. unless you're saying to add it through an object (so like a wave is created, and 3 enemies are added to the arraylist, and the wave could like create invisible walls to stop the user from going further until all 3 enemies are dead).

To me that just seems like it would get sloppy, as I would be making a firstwave.. only for that level. I guess it just seems like using the data driven way takes me on a path I'm not used to, so I don't see how I would do certian things.
Your level file (in my example, "levelOne.lvl") would have info like "enemy here, player starts there", but it can have more than that. If there is such a thing as a "wave" of enemies in your game, it could also have a list of waves, specifying what's in each one. The levelOne file doesn't need to know what that means. It's just tagging stuff and listing things. The game is the part that has to know what it means when levelOne says it has a wave of 3 enemies. When the level is reading it's file, it would say, "Ah, wave: foo, bar, charlie. Ok, make a new wave, make or grab these enemies, put them in the wave, and add the wave to my list of waves, which would be empty if I was a level with no waves." Somewhere in your game programming, you'd check if the current level had any waves, if it was time to start one, if the wave was finished, etc.

Quote
What I will do is try your way through the GameMain, but I still feel like I should make a separate class for each level. I just still don't get why I wouldn't I guess.
I get why this doesn't seem necessary. I thought the same way at first, but as I programmed more, making a single level class and having them vary by data started to make more and more sense. We can talk about this more if you want.
4  Game Development / Game Mechanics / Re: Collision between different maps (2d lwjgl) on: 2015-06-14 04:42:02
I think chrislo27 has offered a good solution. Personally, I might just keep track of the current level in your GameMain class (maybe a variable called currentLevel and a method getCurrentLevel() to retrieve it), and then whenever something needs to look at the list of objects in the current level, you can do GameMain.getCurrentLevel().getEntities(). This would work if you really only need to care at one level at a time. When you switch levels, GameMain makes a new Level(String filePath) and assigns it to currentLevel. All the old stuff goes away, and everything only cares about currentLevel.

But chrislo27's solution is just fine.

Question: when you say you're doing a new class for each level, do you actually mean a new java source code file with a new class definition? Or do you mean you are instantiating the class as a new object, i.e. levelOne = new Level("levelOne.lvl")? If you meant the second one all along, that might be part of the confusion.

Question: for passing the ArrayList around, I'm a little fuzzy on what the problem is there. Are you saying that you want a single object (say, the player) to be able to check its collisions against the other objects in the same level, but you don't want to make a separate player object for each level, and you don't want to have a separate list of objects for each level? Are you trying to figure out how to keep track of where the objects are in each level separately, even though multiple levels sometimes share the same objects? In other words, are you trying to figure out how to make sure you're only getting the objects from the current level instead of the objects from all levels without having to hardcode a bunch of separate lists?

When you were talking about pass-by-ref and pass-by-value, it really sounded like you had something backwards, even though you said you understood it. You can have multiple entities share the same list of objects just by having them all use the same level.getEntities() method that gives them all the same list of the same objects. They could get to level.getEntities() either by chrislo's way (give each entity a reference to the level when you make the entity) or by my way (have a single currentLevel that everything can access).
5  Discussions / Miscellaneous Topics / Re: What I did today on: 2015-05-04 01:07:22

I have no idea if I can actually use FB photos like this.

I made a Spinner widget! Because I was afraid of Swing and whatever AWT uses! I made my own! I also make many other things, like poor decisions!
6  Discussions / Miscellaneous Topics / Re: What I did today on: 2015-04-19 21:31:22
Figured out how to change mouse sensitivity from within the game yesterday. It required grabbing/hiding the native cursor and replacing it with my own, so now I have a hilariously misleading placeholder! But you can control the cursor with a controller now if you want. :O
7  Java Game APIs & Engines / OpenGL Development / Re: LWJGL 3; how's it getting along? on: 2014-12-08 00:21:09
Thanks!

My game is only 2d, and I'm targeting very broad, very old specs. I have, for example, a computer from 2009(!) that only supports OGL 1.4 apparently. Though I'm just going for 2.1 or something so I can use fragment shaders, unless I have it in me to try and mess with extensions to get those working on 1.4, too.

Would I benefit at all from moving to the new LWJGL?
8  Java Game APIs & Engines / OpenGL Development / Re: LWJGL 3; how's it getting along? on: 2014-12-07 17:51:10
Pardon me if this has already been asked, but how does one access the old javadocs? For example, I had this page open, but it has since become a 404: http://www.lwjgl.org/javadoc/index.html?org/lwjgl/input/Mouse.html
9  Discussions / Miscellaneous Topics / Re: A rant on OpenGL's future on: 2014-08-14 12:04:17
I dunnno about that... maybe I'm nuts, but it seems like things have been shifting away from custom rigs. Or maybe that's always been a niche thing, and the niche is swelling along with the overall amount of computer users? But if people start moving away from desktops and laptops... hm.
10  Discussions / Miscellaneous Topics / Re: A rant on OpenGL's future on: 2014-08-14 01:56:43
I have a 2009 computer with an integrated Intel card that may or may not even support fragment shaders. (It's whatever version supports it using an extension. 1.3? 1.4?) It's depressing, but still makes me counterproductively determined to make the game run on it anyway.
11  Game Development / Newbie & Debugging Questions / Re: [Game] How do i make a camera.class? on: 2014-07-27 23:05:22
Glad to help!

I'll let someone else answer your latest question though. Since you're asking multiple questions on one thread, try editing/modifying your original post so you can change the title to reflect your current problem. That way, people know to stop by if they think they can help.

And you can always Appreciate my posts to get me imaginary medals if they've been helpful. Wink
12  Game Development / Newbie & Debugging Questions / Re: [Game] How do i make a camera.class? on: 2014-07-27 21:15:29
I did something similar with my tile grid. (I have the map as a single image, but a bunch of grid outlines placed over it that slowed things down on large maps.)

You need to, before drawing each tile (either in renderMap() or in Tile.render()), calculate whether the tile is on the screen and only draw it if it is.

The information you need:
1. The tile's sides (the x of the left and of the right, the y of the top and of the bottom) or the x,y of a corner and the width and height for you to calculate this from.
2. The width and height of the draw area. I.e., if your window is 1200x800, this might be something like 1192x780. The space that graphics go. This is the cnvW and cnvH (from GameBase.getCnvW() and getCnvH()) in the Camera code I gave you, but you may have it labeled something different or may need to calculate it still by subtracting the frame from the window or something.
3. The position of the Camera. In the Camera code I gave you, I think it's the Camera.getX() and Camera.getY() that give you the top-left corner of the area you want to draw (i.e. the camera location).

Using that, can you figure out how to tell if a Tile is at least partially on-screen before bothering to draw it?
13  Game Development / Newbie & Debugging Questions / Re: [Game] How do i make a camera.class? on: 2014-07-27 19:39:29
Glad to hear you got it working! So, if you centerOnCharacter(), it snaps the camera over to the Player you specify then? Obviously, you had to do a bit of converting to make it work with your classes.

For updating the screen, here's the approach I took:
1. Every time we are ready to update the screen, loop through all things that should be drawn and call their draw() methods.
2. In a draw() method, you do the work of picking the right image and drawing it. I believe you already do this.
3. When everything has drawn, flip the buffer strategy or whatever it is you need to do to put the new drawing on the screen.

For individual animations, here's the approach I took:
1. I made an Animation class.
2. Each thing that should draw has at least one instance of the animation class. Tiles would usually only need one, Players will need one for each pose and direction combination they can have (for example, walking west, idling facing north).
3. When a thing draws, it checks which animation it is currently using (which can be changed when, for example, a Player turns to a different direction or changes poses)...
4. ...then, it tells that animation to draw its next frame, giving it the x and y location minus the Camera's x and y. The animation grabs a BufferedImage, which it then draws.
5. This brings us to Animations themselves:
5a. An animation needs to know several things. First, which images it needs to use (or which directory to automatically load them from).
5b. It needs to know how many frames per second to play and whether it should go back to the first frame when it's finished and loop around, or if it should stay at the last frame when it's done.
5c. If you're allowing the players to pause, it needs to keep track of when it was last paused, last resumed, and be able to take that into account to avoid skipping frames, because...
5d. ...it needs to keep track of when it handed over the last frame to be drawn and what number that frame was...
5e. ...so it can decide what frame to give you when you ask it for the nextFrame(). It compares the current time, the lastFrameTime, and playRate to decide whether to give you the last frame again or move on to the next one. If it's time for a new frame, it needs to make sure that it either loops back to the beginning or gives you the final frame again if it's at the final frame, depending on whether it is a looping animation or not.

I've found this to be a pretty convenient way of doing things, once I got it working.
14  Discussions / Miscellaneous Topics / Re: What I did today on: 2014-07-27 17:37:48
Today (and yesterday), I implemented controller support. A lot of copy-pasting and renaming of copied variables and methods. But now, you should theoretically be able to remap controller buttons and axes just like you can keyboard and mouse buttons, and it should process any input you do correctly.

Not that I've tested it yet. Would anybody find this sort of system for remappable keys, mice, and controller stuff useful?

Screenshots would not be terribly interesting. D:
15  Java Game APIs & Engines / OpenGL Development / Re: LWJGL Controller Advice [Getting false axis events] on: 2014-07-27 13:42:24
Thanks. It hands me events separately for horizontal and vertical movement, and I can compute the angle from those.

The events, as far as I can tell, only trigger when a stick position changes. The right stick gets labeled by LWGLJ as "X Rotation" and "Y Rotation", depending on which direction you push it. If you push it straight to the right, for example, it triggers an X Rotation event with a value of 1.0. All the way to the left is -1.0. If you were to push it, say, to the right and a little bit down, it would give a pair of events, something like X Rotation 1.0 and Y Rotation 0.4253412. And, if you let go of the stick, it fires an event for each axis with values of 0.0. So, on this controller at least, 0.0 is centered. You can set a dead zone where it's not supposed to notice little changes, if I understand correctly.

The weird thing is that, for any other stick movements, it only fires the event once each time you move. It doesn't keep creating events if you hold it still. Yet, the "X Rotation" axis (left-right on the right stick) keeps firing a 0.0 event. It looks as if the computer thinks that the stick keeps getting moved to the center from somewhere else, over and over again, instead of just staying there.
16  Java Game APIs & Engines / OpenGL Development / Re: LWJGL Controller Advice [Getting false axis events] on: 2014-07-27 03:09:08
Current problem, for those interested in helping, or for posterity:

The "X Rotation" axis (moving the right stick side-to-side on the Xbox 360 controller I'm using) is giving constant false positives. I keep getting events where the x- and y-axis values for the event are both 0.0, it's an axis event, and the axis name is "X Rotation". This regardless of what I set the RXDeadZone to (the default is 0.05, I think).

I guess I'll just ignore them for now, as they seem to be doing no real harm?

If anyone knows what's up here, I'd appreciate any advice.
17  Game Development / Newbie & Debugging Questions / Re: [Game] How do i make a camera.class? on: 2014-07-27 01:22:14
Take a look when you've had some sleep; I think you might be able to figure it out. Sorry I won't be analyzing your code or game, but here are some hints on the camera:

The Camera represents where the person who is playing the game is. When that person moves, the things in the game world don't. When the things in the game world move, the person playing does not. But, when you move, it looks like everything else does, because they are being "drawn" through your eyes and in your brain based both on where they are and where you are. So, when we draw something in the game, we should draw it based both on where it is and where the human player is. Thus, g.drawImage(cheapAnimation(), x - Camera.getX(), y - Camera.getY(), width, height, null); . The x and y are where the thing is, and the Camera.getX() and Camera.getY() are where the human player is looking from.

Your Tile.render() should draw its image with its x and y minus the Camera's x and y. This way, if the camera moves to the right, the level gets drawn to the left, for example, making it look like your view has moved to the right.

Anything else that should be part of the game world -- Player, NPC, whatever -- should also draw its images minus the Camera's x and y.

Anything that should be part of the HUD, rather than the game world, such as menus, should not draw minus the Camera's x and y. This way, even if the Camera moves, the menus and stuff will stay in the same spot on the screen.

The principle here is that when something moves (changes its x and y position), that means that it has moved around in the game world. The Player and the Tiles don't move when the Camera does. They stay in the same spot. But, when the Camera moves, while their x and y stay the same, they get drawn with an offset based on where the Camera is. This way, if you move your Camera, you don't have to move all your Players and Tiles, but it's like the person playing the game moves around instead.
18  Game Development / Newbie & Debugging Questions / Re: [Game] How do i make a camera.class? on: 2014-07-27 01:06:05
Looking at your source code, you would want to change this line in your Player.render(Graphics g):
1  
g.drawImage(cheapAnimation(), x, y, width, height, null);

to something like this:
1  
g.drawImage(cheapAnimation(), x - Camera.getX(), y - Camera.getY(), width, height, null);


This would mean that as you move the camera to the right, the player image moves to the left, and vice versa. You can do the same thing to your maps as well, so that as the camera moves, they move. If you want to keep a player or AI at the center of the screen, move the camera to their current position. Mine accomplishes this by Camera.centerOnCharacter(Person subject). If I want it to stay locked on to the player, I use that once each time I'm getting ready to draw everything. You could do the same (or modify my code if you like) by changing Person to Player and giving Player getCenterX() and getCenterY() methods so that the Camera knows where the middle of the player is, so that it can move to it.
19  Game Development / Newbie & Debugging Questions / Re: [Game] How do i make a camera.class? on: 2014-07-27 00:57:51
Ah, I've been typing up an answer for you! Here's how I do the making the screen move:

My game's camera works more or less like Pokémon's, with the player (or whoever we're looking at right now) staying at the center of the screen. The player and everybody else keep track of their own position relative to the level they're on. (My game calls these levels "Boards", but you could call them levels, maps, boards, areas, whatever you want.) If a Person (a character) is at x: 0, y: 0, that means they're at the very top left of the board.

When you update the screen, draw everything with an offset equal to the camera's x and y. Example:
1  
drawThing(thing.getImage(), thing.x - Camera.getX(), thing.y - Camera.getY())
20  Game Development / Newbie & Debugging Questions / Re: [Game] How do i make a camera.class? on: 2014-07-27 00:49:00
For what it's worth, here's my Camera class. If any of it's of use to you (or anyone), feel free to use it for whatever.

It assumes certain things about what a Person is in your game (namely, that it's called Person, and it has getCenterX() and getCenterY() methods that tell you where the middle of the Person's graphic is relative to the game board/level). It also assumes that you have a thing called GameBase that has getCnvW() and getCnvH() to get the width and height of the drawable area of the game window, a variable brd to keep track of the current Board/Level, a variable to keep track of the main player character, and some numbers to symbolize directions (north, south, east, west) which can be sent in to the board/level's getBorder(directionNumber) method to find out where the edges of the level are.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
package GameBase;

import Person.Person;

/**
 *
 * @author jemoore
 */

public class Camera {
    private static double x = 0;
    private static double y = 0;
   
    public static int getX() {
        return (int) x;
    }
    public static int getY() {
        return (int) y;
    }
   
    /*
     * Move Camera's top-left corner a given number of pixels,
     * but only if this wouldn't move the camera past the board edges.
     */

    public static void move(double x, double y) {
            //System.out.print("Camera moves from " + Camera.x + "," + Camera.y + " to ");
        set(Camera.x + x, Camera.y + y);
            //System.out.println(Camera.x + "," + Camera.y);
    }
   
    /*
     * Set Camera to have its top-left corner be a given position,
     * but only if this wouldn't move the camera past the board edges.
     */

    public static void set(double x, double y) {
        Board brd = GameBase.brd;
        int cnvW = GameBase.getCnvW();
        int cnvH = GameBase.getCnvH();
        double marginW = (cnvW - brd.getW())/2; //handle blank margins if canvas wider than board
        double marginH = (cnvH - brd.getH())/2;
            //System.out.print("Camera: cnvW,H="+cnvW+","+cnvH+" marginW,H="+marginW+","+marginH+" input x,y="+x+","+y);
        if(marginW < 0) { marginW = 0; }
        if(marginH < 0) { marginH = 0; }
        if(x + cnvW > brd.getBorder(GameBase.DIR_E) + marginW) { //can't move right
            x = brd.getBorder(GameBase.DIR_E) - cnvW + marginW;
        }
        if(x < brd.getBorder(GameBase.DIR_W) - marginW) { //can't move left
            x = brd.getBorder(GameBase.DIR_W) - marginW;
        }
        if(y < brd.getBorder(GameBase.DIR_N) - marginH) { //can't move up
            y = brd.getBorder(GameBase.DIR_N) - marginH;
        }
        if(y > brd.getBorder(GameBase.DIR_S) - cnvH + marginH) { //can't move down
            y = brd.getBorder(GameBase.DIR_S) - cnvH + marginH;
        }
        Camera.x = x;
        Camera.y = y;
            //System.out.println(" output x,y="+x+","+y);
    }
   
    /*
     * Reset Camera to be centered on subject's position,
     * but only if this wouldn't move the camera past the board edges.
     */

    public static void centerOnCharacter(Person subject) {
        centerOnCharacter(subject, 0, 0);
    }
    public static void centerOnCharacter(Person subject, double offsetX, double offsetY) {
        int cnvW = GameBase.getCnvW();
        int cnvH = GameBase.getCnvH();
        double newX = subject.getCenterX() - cnvW/2 + offsetX;
        double newY = subject.getCenterY() - cnvH/2 + offsetY;
        Camera.set(newX, newY);
        //System.out.println("cam xy: " + Camera.getDrawX() + ", " + Camera.getDrawY());
    }
   
    public static void centerOnMain() {
        centerOnCharacter(GameBase.mainPlayer);
    }
}
21  Java Game APIs & Engines / OpenGL Development / Re: LWJGL Controller Advice on: 2014-07-27 00:10:24
Having trouble getting it to recognize the binaries. It complained they weren't in java.library.path, so I set java.library.path to the same as org.lwjgl.librarypath , all before it ever tries to set up controllers, but it still complains. If I paste the same path into my NetBeans project properties -> run -> VM Options as -Djava.library.path="C:\Users\Joel\Documents\NetBeansProjects\hippo\native\windows" , it works. This, even though printing out java.library.path shows the same path whether I set it in the VM Options or in the program.

I'm trying this, but they call it a hack, which makes me raise an eyebrow about its reliability: http://blog.cedarsoft.com/2010/11/setting-java-library-path-programmatically/

[EDIT: that hack appears to work, and my, it recognizes a lot of controllers. My Xbox 360 controller comes up first, then my keyboard (twice), my microphone (twice, but very interesting), then the driver for my wife's not-connected drawing tablet (also twice), though it claims it failed to initialize said tablet driver (did it fail on both versions that it saw? on one? on a third one that didn't end up in the controllers list?)]
22  Java Game APIs & Engines / OpenGL Development / Re: LWJGL Controller Advice on: 2014-07-26 23:22:35
Good idea. That's what I did for keyboard and mouse -- there are default bindings, but it's basically agnostic to the actual names of the keys or mice, so it should be easy to reconfigure for non-English keyboards and such. I'll be doing something similar for controllers.
23  Java Game APIs & Engines / OpenGL Development / LWJGL Controller Advice [Getting false axis events] on: 2014-07-26 20:49:19
So, I've got Keyboard and Mouse redone to use LWJGL instead of AWT or whatever built-in thing I'd been doing. Remapping works pretty well, and everything. And now, I'm going to try and take this 360 controller we bought and try to make that happen.

Any advice, as I dive in to controller support? Any major differences I should be aware of between how LWJGL treats controllers versus keyboards or mice?

I suppose if I run into any nasty, stumping problems, I'll edit or reply to this topic.
24  Java Game APIs & Engines / OpenGL Development / Re: AWT Frame and Canvas parented to LWJGL Display is resizing on creation on: 2014-05-26 19:30:21
Sorry for all the self-replies. I'm not sure whether to edit or add a new reply in cases like this, where it's new information being added.

As best I can tell, the window is being maximized behind my back somewhere. When the window ends up big instead of the size it's supposed to be, f.getExtendedState() is returning 6 of MAXIMIZED_BOTH instead of the 0 of NORMAL.
25  Java Game APIs & Engines / OpenGL Development / Re: AWT Frame and Canvas parented to LWJGL Display is resizing on creation on: 2014-05-26 18:52:56
*Sigh*

Correction: It works sometimes. Other times, it still resizes the window to take up the whole screen.

EDIT: It also just used the right sized window, but the rendering was stretched, as if it was trying to stretch the correct size to fit a larger window than was there.

EDIT again: Looks like I'd also added an f.setMinimumSize() and f.setSize() after the second f.setVisible(). If I remove those, I get full screen sized window again.
26  Java Game APIs & Engines / OpenGL Development / Re: AWT Frame and Canvas parented to LWJGL Display is resizing on creation on: 2014-05-26 18:44:29
Thaaaaat was weird. If I add another f.setVisible(true) before the f.add(c), it works as it should. The window is the right size, the rendering is the right size and isn't squashed or stretched.

I guess Frames need to be set to validated or made displayable or something before a Canvas is added to them, or the Frame can get resized (and the canvas with it) somewhere behind the scenes later. This even works if I then remove the f.setVisible(true) that came after f.add(c), even though I thought that needed to be called to re-validate stuff after adding a component. Weird.
27  Game Development / Newbie & Debugging Questions / Re: Collision bug in a 2D platfrom game. on: 2014-05-26 18:26:31
Hi,

Not sure if this will help with your specific problem, but it might be a better way to handle collisions during player movement.

You may find it useful to go ahead and move the character 1 pixel at a time until they've moved their whole speed -- but don't draw it yet! Every pixel the character moves, check to see if moving that pixel would make it collide with anything. Then, if it does, simply stop the movement before that pixel.

For simple collision, you can just see if a rectangle you make that surrounds it overlaps with the rectangles of other objects. Here is what you could do for each pixel of movement:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
int moveX = 0;
int moveY = 0;
if(movingLeft) { moveX = -1; }
else if(movingRight) { moveX = 1; }
if(movingUp) { moveY = 1; } //assuming y goes up and not down
else if(movingDown) { moveY = -1; }

//box is the rectangle around your character used for checking collision
//obstacles is an ArrayList of every other rectangle on the level the character can collide with
Rectangle nextSpot = new Rectangle(box.x + moveX, box.y + moveY, box.width, box.height)
boolean collided = false;
for(Rectangle thing : obstacles) {
    if(nextSpot.intersects(thing)) {
        collided = true;
        break; //no need to continue checking obstacles -- we've hit one
    }
}
if(collided == true) {
    //no more movement!
    break;
    //if we're inside another loop that goes until we've moved our whole speed,
    //we can get out of it with break.
} else {
    //move that little bit!
    playerX += moveX;
    playerY += moveY;
}


Then, once the character has moved as far as they can with that collision checking method, update the screen.
28  Java Game APIs & Engines / OpenGL Development / AWT Frame and Canvas parented to LWJGL Display is resizing on creation on: 2014-05-26 18:03:28
This is baffling me. For some reason, the AWT Frame and its child canvas that I'm using with LWJGL's Display.setParent() is resizing itself away from the dimensions I set it as. This used to work fine, and looking through my revision history, I can't figure out how I broke it.

Relevant parts of my code:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
//Frame f is a static final that is initialized when it is declared.

setupFrame(Canvas c) {
        //determine the width and height to use for the game window, put them in resX, resY
        f.setSize(resX, resY);
        f.setResizable(false);
        f.setIgnoreRepaint(true);
        f.add(c);
        f.setVisible(true);
}

setupLWJGL() {
        //locate natives, then...
        try {
            Display.setDisplayMode(new DisplayMode(resX, resY));
            Display.setParent(cnv); //cnv is the same as c from the setupFrame(Canvas c)
            Display.create();
        } catch(LWJGLException ex) {
            Logger.getLogger(GameBase.class.getName()).log(Level.SEVERE, null, ex);
        }
        cnvW = Display.getWidth();
        cnvH = Display.getHeight();
        //...lighting, blending, matrices, etc....
}


Currently, the size of the frame should be 1200x675, and the canvas and Display should be a little less than that (1194x647) because of window borders. However, at some point in the code, the frame and canvas (and thus Display) sizes change from about 1194x647 to 1280x1002.

I've been mucking around in NetBean's debug mode and also with a bunch of print statements to figure out where the canvas and frame end up changing their dimensions. This goes wrong in two different ways and seems to happen at two different spots:

1. Display.setDisplayMode(new DisplayMode(resX, resY)); Before that line, the canvas dimensions are 1194x647, afterward they are 1280x1002. The game renders correctly, but in a window that takes up the whole screen instead of 1200x675.

2. f.setVisible(true); The same dimension change occurs during that line. I tried to follow the source code, and it seems to happen when the Component calls peer.setVisible(true).

Sometimes, the window takes up the full screen (it is still a decorated window, it's not in full screen mode), but only draws on a section of it that looks like it's about the 1200x675 size the window is supposed to be. I can't reliably reproduce this, but it happens sometimes. Also, which spot the frame and canvas change dimensions at is unpredictable, but seems to happen more on f.setVisible() when I'm in debug mode.

I'm guessing this isn't actually due to something within the code I'm using so much as maybe a synchronization issue? Since it seems to change when it happens when I'm using debug mode, the timing seems important.

Any ideas?

EDIT: It looks like if I remove the Display.setDisplayMode(), which I think is supposed to be unnecessary anyway if I give the Display a parent, the resizing changes to during the Display.create() line, and I get the glitch where the window is still big, but the rendering is the right size and takes up only part of the window and is scaled oddly. No, wait... I just ran it again without setDisplayMode(), and it resized at Display.setParent(cnv) and rendered in the whole window. So, this is very inconsistent and seems to not be connected to any particular piece of code I'm writing.
29  Game Development / Newbie & Debugging Questions / Re: Hard to start a project. on: 2014-02-27 04:51:12
I'll pile on to what everyone else is saying.

Just start with what you can do, and do the best you can with that. If it turns out well, you can try to find someone to replace the art and music. Meanwhile, just hack together your own, even if it's bad, or find free stuff online. There is a significant amount of legitimately free resources, though if you use it in a game you release, you should double-check the licenses to make sure you don't have to pay or get permission or release the source code (unless of course you're ok with that!).
30  Game Development / Newbie & Debugging Questions / Re: Framerate cut in half when running by clicking jar vs command line or netbeans on: 2014-01-21 15:09:21
Lol.

It feels inappropriate to reply just to say that. This forum feels too official. Maybe something's wrong with me.
Pages: [1] 2
 
Coldstream24 (11 views)
2015-09-03 00:41:28

Andrew_3ds (23 views)
2015-09-01 19:08:10

afikri (16 views)
2015-08-31 09:30:22

afikri (24 views)
2015-08-31 09:30:07

afikri (12 views)
2015-08-31 09:27:24

afikri (16 views)
2015-08-31 09:26:40

Roquen (23 views)
2015-08-29 11:30:54

GamerC4 (34 views)
2015-08-22 20:38:50

GamerC4 (31 views)
2015-08-22 20:37:18

GamerC4 (37 views)
2015-08-22 20:37:01
HotSpot Options
by Roquen
2015-08-29 11:33:11

Rendering resources
by Roquen
2015-08-17 12:42:29

Rendering resources
by Roquen
2015-08-17 09:36:56

Rendering resources
by Roquen
2015-08-13 07:40:51

Networking Resources
by Roquen
2015-08-13 07:40:43

List of Learning Resources
by gouessej
2015-07-09 11:29:36

How Do I Expand My Game?
by bashfrog
2015-06-14 11:34:43

List of Learning Resources
by PocketCrafter7
2015-05-31 05:37:30
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!