Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (497)
Games in Android Showcase (114)
games submitted by our members
Games in WIP (563)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Int & Float, Design questions.  (Read 1221 times)
0 Members and 1 Guest are viewing this topic.
Offline Kryel

Senior Newbie





« Posted 2012-11-04 17:04:18 »

So, I've been making my own tools to help me programming my game, and strangely I've stumbled upon a LOT more (interesting) questions than I imagined, mostly about engine design if such a term exist, and good practices (and evil optimizations, which I'm definitely NOT doing).

Anyway, here's something that's been buggering me.
Most of the time, at least for a 2D game, the x,y coordinates are integers, while the velocity is a float.
After lots of reading again, I think I understand the whole choice behind it, but still, let me show you an example :

Let say that I have a character with a vx=0.6 speed :
Step 1: x = 0
Step 2: x = 0.6 -> rounded to 1
Step 3: x = 1.6 -> rounded to 2
And so on.
Basically, when we'll have 0.5 < vx <= 1.5, the character will just move 1 pixel per step.

From there, I wonder if it wouldn't be easier to just use an integer as well for the velocity? At least I'll be able to forget about good-timing cast and such.
I also did think about using float (cash) for everything, but then I heard that casts may act different on others spec? (Even though my assumptions are that it's safe for us, java user, thanks to the JVM..?)

----------

Second question :

I've been using the "school" way of creating my classes so far, but i'm getting a bit annoyed at the overload of get()/set() methods.
To be honest, I somewhat found them boring confusing and I'd rather use public attributes for my classes (even though it's BAAAAAAD for encapsulation and people might actually really want to kill me for that).
For example, i'd rather use (already done it actually):
Character.sprite.speed.acceleration.x
than :
Character.getSprite().getSpeed().getAcceleration().getX()

Since "get/set are god-send!" in the left part of internet and "get/set are EVIL" in the right part, I just figured I might ask directly for opinions here.


----------
Oh right... princec, I demand a keyboard configuration for Ultratron because I have an AZERTY one !!!  Grin [size=6pt](and I'm lazy to change the settings myself)[/size]
Offline KittenKoder

Senior Member


Medals: 7



« Reply #1 - Posted 2012-11-04 17:11:23 »

To your get/set notion, I base it on how volatile the the data is and what would happen if something changed it unexpectedly. If you have to control changes made then protected/private is the best method, so when a change happens the class can do the other work. But if it's just a data holding class for something where if the contents change unexpectedly you won't get an exception, then do what's comfortable. Some classes in Java I think over use the private/protected members, things like Color should be a bit more transparent than they are, but meh.

I am no one else.
Offline sproingie

JGO Kernel


Medals: 202



« Reply #2 - Posted 2012-11-04 17:20:43 »

Velocity is often a float because it has more precision than an int in the lower part of the range.  Most libraries doing the calculations involved are happier with floats (or actually, doubles).  You could always use an int if you scaled everything up to whatever precision you demanded, sure, but it likely won't save you much on modern CPUs.  Float casts are going to behave exactly the same everywhere, the java language spec demands it.  You might get slightly different float behaviors on other float operations on different platforms unless you use 'strictfp', but the differences are incredibly subtle, and nothing likely to have any real-world impact in anything but the most precise scientific programs.

As for getters/setters, they may be evil, but they're a necessary one.  For classes that do nothing but hold mutable data, like a Vector3f for example, I do use public fields (as does even Sun's own Java3D API).  Everything else, I just generate the accessors in my IDE and forget about it.  If you really can't stand the boilerplate code of accessors, you can always use Lombok to generate them for you and keep them out of your source.  Lombok is really nifty (and does other things), though it does look a little weird to call accessors that don't exist anywhere in the source.  The IDE is just fine with it though, since Lombok is also an IDE plugin.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Kryel

Senior Newbie





« Reply #3 - Posted 2012-11-04 17:30:17 »

Hum.. I did want to use float for everything (double might be a bit overkill for a 2D game), I guess i'll just go the "way I like" and see what happens.

For the get/set, as KittenKoder mentioned for the Color example, sometimes I just feel like they are just overkill, if not useless. Saying that I have a hard time generating them would be lying since i'm using mehclipse. Then again, I'm talking mostly about common values, like x,y coordinates etc...  I'm still using them when the attributes are not primitives mainly, but otherwise I just feel that it's useless and add unnecessary lines + text when coding.

Edit : deleted the empty quote. Sorry, bad habit from my MMORPG period.
Online Agro
« Reply #4 - Posted 2012-11-04 17:36:27 »

I use doubles(floats) when I calculate velocity for a game entity. Even though the position of the entity on the screen must be an integer, you can keep on adding a decimal value to the position to advance it at that speed. Its always worked for me and its pretty neat too.

Offline sproingie

JGO Kernel


Medals: 202



« Reply #5 - Posted 2012-11-04 17:38:37 »

Your sig reminds me of this engineering joke:

If time is money, and knowledge is power, it follows:

W = PT       Work = Power * Time
P = W/T      Power = Work/Time
K = W/M      Knowledge = Work/Money
M = W/K      Money = Work/Knowledge

Therefore the more you know, the less you make, and as knowledge approaches zero, money approaches infinity.  This explains postdoc and manager salaries.


Offline Kryel

Senior Newbie





« Reply #6 - Posted 2012-11-04 17:41:31 »

And you decided to post that just when I was thinking of changing my sig.  Grin
Now THAT is some sort of big coincidence.
Offline 65K
« Reply #7 - Posted 2012-11-04 18:31:25 »

Character.sprite.speed.acceleration.x
than :
Character.getSprite().getSpeed().getAcceleration().getX()
Hmm, I can't see anything boring or confusing here. I only see some hopefully IDE-generated accessors to class internals.

Except for the mentioned special cases, encapsulation is an absolutely necessity for anything half decent designed.
More interesting are the questions, why acceleration is an attribute of speed and not of sprite, and why sprite is static.

Not making every member public by default has also the nice effect to start a thinking process about who needs, why and when access to internal stuff of other fellow objects.

Offline Best Username Ever

Junior Member





« Reply #8 - Posted 2012-11-04 18:37:31 »

That combination of floats and ints may make sense under some circumstances. For example, in a 2D racing game I might give characters a speed and an angle direction instead of an x and a y velocity. In that case I might accelerate/decelerate relatively quickly in small increments. A whole number position may be more than enough for positioning a character anywhere in the game, but whole number velocity might not be realistic enough. Rounding to the nearest integer for instantaneous velocity probably would be fairly accurate over a longer period of time for such a situation.

If more precise movement was needed, you could still uses ints by subdividing space into even smaller units than a single pixel or by accumulating someFloat % 1.0 and saving it between updates.



If you know a variable can be assigned virtually any value without interfering with the rest of the object's state and those variables are always going to be used the same way, then you can make those variables public for game programming. The implementation of methods relying on those values won't change and if they did, the changes would spill over to virtually every class in your project and force you to rewrite major parts of it. If the variable represents a simple property, doesn't change meaning if the class is overridden, and is important to the implementation of the entire project instead of just the class it is part of, then there is no reason to add getters/setters.

It still makes sense to have code like this either way:
1  
2  
3  
gameObject.setVelocity(newVx, newVy);
// or...
setSpeedAndDirection(gameObject, speed, angle);


You may need to take higher level classes before deciding what is the "correct" way to do something. Beginner classes are sometimes so basic that they give people a false impression of good programming practices. Sometimes the rules and feature set they give you are so limited that you pick up bad habits if you try to use them outside of class. Some rules are only there to guide people for the sake of teaching a lesson, making grading simpler, or keeping people from making errors in more complicated areas that students haven't had formal education in yet. (Getter/setter behavior isn't one of those rules, though. It will never cause problems if you always used that pattern, but somewhat experienced programmers can identify when getters/setters would have identical behavior to using a public variable.)

(One of the things they probably don't teach you, for example, simply due to a lack of time, is that you can set the value of final variables in constructors. Using a public final variable is often much better than using private variables and only providing a get method for it. Similar to array.length. You could also have string.length instead of string.length(), but not arrayList.size instead arrayList.size().)

Also, your OOP is flawed. Sprites should not have speeds, only characters should have speeds. Acceleration is not a property of speed. (And in most cases you only care about velocity and position in games.) Using vector objects for speeds/positions/accelerations isn't really bad, but it's easier to treat them as separate variables and not nest objects within objects. Consider this:

1  
2  
3  
4  
5  
6  
7  
8  
9  
Character character = /* ... */;
character.x = 100;
character.y = 200;
character.vx = 3.0;
character.vy = -4.0;
System.out.println(character.getSpeed()); // ~ 5
character.update();
System.out.println(character.x + " " + character.y); // 103 196
character.vy += gravity;
Offline Kryel

Senior Newbie





« Reply #9 - Posted 2012-11-04 19:29:14 »

( ... )
Meh, sorry typed it too fast. Actually if you want to know I have (instance of the Character class):
- character.sprite.speedX.acceleration.value
- character.sprite.speedY.velocity.timer
I've just made a middle object that contains more parameters (game engine specifics) and methods for redundant operations.

Well, just personal preference I guess. I grew used to access values like that in any of my previous programs/engines. The 'get' or 'set' before these simplistic values are just...  ,like, useless (for me). But then again, it's not like I plan to make an official API and distribute it to the world, I'm just making them to simplify my tasks.

---
( ... )
Wow ! Oh well, might as well talk about what I've done.

Actually, I'm currently coding my sprite editor (or more like spritesheet editor). The idea is to open any spritesheet I've made, create a set of sprites dynamically with an interface and them save the whole result in an XML file. In the end, I'll have 2 files : imagename.png & imagename.xml, which I'll be able to read for the engine. Fact is, since i'm coding a sort of fighting game, I thought of linking to a sprite all of its hitboxes (boundHitbox, damageHitbox and attackHitbox), though the word 'Sprite' may be a bad choice I admit.
So Basically I've created several GameObject, which are objects specifics to my engine. For example :

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
package gameengine.common;//Once done, I do not plan to change anything from this package

public GameBox{
//Lower denominator between all objects of the engine
//For example any HitBoxes from the xml file mentionned earlier are actually GameBox objects
public int x, int y, int width, int height;
//more attributes
};

public GameVisualBox extends GameBox implements someInterface{
//These ones can be displayed on the screen by the engine
public int h;
public float scaleX, scaleY;
public GameEntitySpeed speedX, speedY, speedH;
//GameEntitySpeed objects contain the velocity and others linked variables (such as a timer, active state etc...)
//I've done it that way to be able to automate vacuum effects that can be localized only on x, or y, or both, etc... (speedH = gravity but meh)
//This is a simplistic way, otherwise I'd have something more appropriate like vectors.

//more attributes + common automatic methods, such as refreshing/activating/desactivating speed values etc...
};


1  
2  
3  
4  
5  
6  
7  
8  
9  
package gameengine.specific;//Classes might change slightly depending on the library I'll use

public GameSprite extends GameVisualBox{
//Previous classes manage ONLY primitives values in the end.
//Since the GameSprite will managed images, its attributes may changed depending on the library I'll use later (still not sure)
public BufferedImage image;//May change to Texture if I use libgdx for example
public float r, g, b, a;
//more attributes + specifics methods
};


And there, you have it. Since I'm the only one doing this and don't really plan to distribute something that lame, this is why I just thought of dropping the 'get/set' because it's faster for me to read something.x instead of something.getX when it comes to simplistic values only of course.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 799
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #10 - Posted 2012-11-04 19:30:18 »

Please don't quote like that. persecutioncomplex

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline Kryel

Senior Newbie





« Reply #11 - Posted 2012-11-04 19:32:00 »

Well, it avoids adding X more lines to my reply... :/
Sorry bad habit, I have to get rid of it, somehow... (see? That's 6 more lines !)
Offline sproingie

JGO Kernel


Medals: 202



« Reply #12 - Posted 2012-11-05 00:32:41 »


Why not?   Grin
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 799
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #13 - Posted 2012-11-05 00:37:26 »

(...)
(because it indicates providing context while providing none...)

Who ever came up with this quote style on some odd MMORPG forum, should be have their contextual ass kicked. Period. (Period. Period.)

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline Best Username Ever

Junior Member





« Reply #14 - Posted 2012-11-05 00:40:51 »

You can use @Kryel. Or @Kryel (Reply #3) if there are multiple posts by the same person since your last post...
Offline ReBirth
« Reply #15 - Posted 2012-11-05 05:46:47 »

In the past I even use double for x,y persecutioncomplex

Offline GabrielBailey74
« Reply #16 - Posted 2012-11-05 06:41:23 »

o,O
Is it common for people to add a semicolon like so?:
1  
2  
public int x, int y, int width, int height;
}; <---- Right Thurr


Offline KittenKoder

Senior Member


Medals: 7



« Reply #17 - Posted 2012-11-05 07:16:43 »

o,O
Is it common for people to add a semicolon like so?:
1  
2  
public int x, int y, int width, int height;
}; <---- Right Thurr



It's a non-issue, one of those old throwbacks that's not really important anymore. For some of us it's just an old habit, I do it sometimes without thinking.

I am no one else.
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

UprightPath (20 views)
2014-09-20 20:14:06

BurntPizza (26 views)
2014-09-19 03:14:18

Dwinin (40 views)
2014-09-12 09:08:26

Norakomi (70 views)
2014-09-10 13:57:51

TehJavaDev (95 views)
2014-09-10 06:39:09

Tekkerue (49 views)
2014-09-09 02:24:56

mitcheeb (70 views)
2014-09-08 06:06:29

BurntPizza (52 views)
2014-09-07 01:13:42

Longarmx (39 views)
2014-09-07 01:12:14

Longarmx (45 views)
2014-09-07 01:11:22
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
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!