text:
Is there a better alternative to Timers to increment speed?
I'm making a chaser game in flash, where you would press an arrow key and the player would move in that direction then stop on another point on a grid, as the enemy does the same and chases the player. To make the movement smooth, I have a timer moving the player one pixel each repetition (50 times to stay on the grid points), having the delay get smaller every 30 frames to speed up. But after the delay gets to 0 and can't go any lower, the player can't get faster. What is a better alternative to use to continue going faster?
            var playerTimer:Timer=new Timer(40,50);
            playerTimer.addEventListener(TimerEvent.TIMER,playerMoveTrigger);
            var pStatus:String="";
            stage.addEventListener(KeyboardEvent.KEY_DOWN,playerMove);
            function playerMove(e:KeyboardEvent):void
                {
                if((player.x+15)%50==0&&(player.y+15)%50==0)//ensures player is on grid before moving
                {
                    switch(e.keyCode)
                        {
                            case Keyboard.DOWN:
                            pStatus="down";
                            break;

                            case Keyboard.UP:
                            pStatus="up";
                            break;

                            case Keyboard.LEFT:
                            pStatus="left";
                            break;

                            case Keyboard.RIGHT:
                            pStatus="right";
                            break;
                        }
                }
                playerTimer.start()
                }
                playerTimer.addEventListener(TimerEvent.TIMER_COMPLETE,resetTimerP);
                function resetTimerP(e:TimerEvent){playerTimer.reset();}

            function playerMoveTrigger(e:TimerEvent)
            {blockMove(player,pStatus);}
            var offSet:int=0;
            function blockMove(block:Shape,dir:String)
                {   offSet=(block.height==30)?15:10;
                    switch(dir)
                        {
                            case "down":
                            if(block.y+offSet<150){block.y+=1;}
                            break;

                            case "up":
                            if(block.y+offSet>50){block.y-=1;}
                            break;

                            case "left":
                            if(block.x+offSet>50){block.x-=1;}
                            break;

                            case "right":
                            if(block.x+offSet<150){block.x+=1;}
                            break;
                        }
                }

Increase the distance the player moves per timer iteration
Change your += or -= 1 to a variable [speed].  Your speed starts out at 1 and increases as the game progresses

Assuming I did that, increasing the speed to factors of 50 to stay on the grid, wouldn't it start to get unreasonably fast? (1,2,5,10,25,50) By 25 or 50, the movement would be nearly instant

@user99988 What's the highest level you made it to in Tetris?  "Unreasonably fast" is kind of the point.

But there's literally only 5 increments I can do in that case, isn't there a more gradual way to speed up?

@Malzzzy Two thoughts:  (1) Why can't you increment it gradually?  and (2) You could increase the timer when you jump the speed.  speed = 25; timer.interval += 50; and then decrease the timer again.  But still... (1)?

I guess I should have been a bit more specific in what I was looking for. I chose to use a timer so that the movement looked smooth to the player, instead of looking blocky. At a delay of 0, the timer is moving the player one pixel at a set time, is there any way go faster than that?

@Malzzzy My answer is the same... Move the player more than one pixel at a time.  Once the timer hits zero, start increasing the speed.  It's the only way to make the player move faster.

You can also use floating point numbers instead of purely integers.  Then you can increase speed by 1.3 or such.  You can snap positions to integers when drawing if you want to stay strictly pixel aligned.


text:
Should response be tied to request in a multiplayer game?
I wonder if server responses on client operation requests should be tied by some operation id?
Tied would be when:
1.Client app sends request to server to e.g. buy item X, and sets operation id as ID.
2.Server responds with operation id and true or false.
This would mean that operation with that id was successful or not.
Untied example:
1.Client app sends request to server to e.g. buy item X
2.Server responds with just an updated data of item X, where new item owner would be mentioned.
This way client can check if owner name is equal to it's own name and if true, assume that item was bought successfully. Same response data could be sent to other clients, to let them know that item X was bought by someone.
Which approach is better?
IMHO untied is better and simpler in implementation, but it feels like there can be so many edge cases which I don't see right now.

I have buying implemeted like this: Client sends buy request. Server sends information that it removed you money. Server sends information that you recieved an item. (Both of those are used for another stuff, like looting). Or server sends information message that you cant buy this item (this is used for other stuff too, like telling you that you already looted something). So its more like your approach 2, and it works quite well.

Consider how you can remove ambiguity in your design. A combination of the two choices or the second choice would do that well. For example, you can also send back an enum letting the client know bit more information, something like ErrorItemPurchasedByOtherPlayer or SuccessItemPurchased. Of course enums would be converted into a byte or two to simplify the data transfer. Simply returning true or false is ambiguous because it doesn't really give you much information.
Returning an enum, along with the updated item information would give you all the information you need. I don't think it's necessary to inform other players who purchased the item, but you could push an update on item availability to other players also viewing the store when an item is purchased.
Your untied example is the same as your tied example, it just contains more information (it's trivial to extract true/false from the supplied information). So there aren't edge cases added.

I've intentionally made both examples same.
Problem is not about buying item X. It's about the way client should exchange data with server.

@DenisNarushevich I know they're doing the same task. I'm talking about the information you can get from them. You can get the same information in your untied example that you get in your tied example. You were worried about adding edge cases, I'm saying there won't be any. The tied example data is a subset of the untied example data.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Should I code game logic separately from game engine scripts
I'm developing a game in Unity3d, economic strategy.
I wonder if I should code logic inside unity scripts, or write it as an external module/library?
By game logic I mean game model, which describe game entities, they relation with each other, their methods. And this logic has nothing to do with and doesn't need to know anything about networking, rendering, representation etc.
If I do it inside unity scripts, then logic is tied to unity engine and I don't see a way to implement multiplayer(client-server) without rewriting whole logic for server-side, where unity cannot be used.
I would like to define logic outside of scripts, and later, reference it inside some "main" unity script. This way I could implement multiplayer easily.
Is this a common practice, or should I avoid it, or maybe there is some alternative patterns?

I think that depends on your Game :D Useless Comment!
The bigger the game, the harder it will become to manage

Actually, if I want to implement multiplayer if future then currently I have only one choice - it is to write logic separatelly from engine scripts. I hope someone will lead me to alternatives.

There are definitely some advantages in developing your game logic in an agnostic (non-Unity) environment.
Pros

It forces you to think about game design more purely. I find it is much easier to think about game design, whether on a board or on a computer screen, if I don't also have to think about writing or using an engine.
It is easier to write and run tests, though I hear there are testing frameworks for Unity.
It is easier to simulate your game at faster than real-time. Balance and mechanics in "economic strategy" games are comparatively more chaotic than in other games: the effects of adjusting Ability X are often less localizable and less generalizable than in first-person shooters for instance. Therefore balancing this type of game is a much more time-consuming process. When writing AI or tuning numbers, being able to simulate many games (outcomes) generatively, automatically, at faster-than-real-time, and to finally output statistics, can be incredible useful.
MonoDevelop for Unity is only ok. If you write your game logic in a pure .NET library, you can use Visual Studio which has a more mature debugging environment.
And as you alluded to, to validate game moves on a server you probably want all or some of your game logic to be running in an environment not dependent on Unity.

Cons

If your game model depends on physics, or any other capability already offered by Unity, you must recreate it or use some other library that you can link against or build.
In general you might find yourself rewriting certain basic constructs in your own library, and writing wrappers or converters to go to-and-from yours and Unity's.

Is this answer based on real world experience? Have you developed a game this way before?

You can define your game logic in C#.  There are a number of ways of moving C# to server side.
Alternatively, if you wish to use a different cross-platform scripting language for game logic, there's always LUA (and again, because you're using C#, a brief google search will yield a number of ways you can integrate LUA with Unity).
As previous answers have noted, it depends on the complexity of your game.  In my view, C# is (these days) sufficiently cross-platform as long as you avoid the Unity API.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Android Object get Jagged at the border
I am new to OpenGL ES 1 in android. My 3D Model border getting Jagged. Please help me to look like a smooth border instead of jagged.
Screenshot : https://i.stack.imgur.com/1Gq83.png
private class Renderer implements GLSurfaceView.Renderer {
    public Renderer() {
        setEGLConfigChooser(8, 8, 8, 8, 16, 0);
        getHolder().setFormat(PixelFormat.TRANSLUCENT);
        setZOrderOnTop(true);
    }

    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        gl.glClearColor(0.0f,0.0f,0.0f, 0.0f);
        gl.glDisable(GL10.GL_DITHER);
        gl.glEnable(GL10.GL_DEPTH_TEST);
        gl.glEnable(GL10.GL_BLEND);
        gl.glBlendFunc(GL10.GL_SRC_ALPHA_SATURATE, GL10.GL_ONE);
        gl.glDepthFunc(GL10.GL_LEQUAL);
        gl.glHint(GL10.GL_POLYGON_SMOOTH_HINT, GL10.GL_NICEST);
        gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
        gl.glEnable(GL10.GL_TEXTURE_2D);
        gl.glShadeModel(GL10.GL_SMOOTH);
    }

    public void onSurfaceChanged(GL10 gl, int w, int h) {
        mViewWidth = (float)w;
        mViewHeight = (float)h;
        gl.glViewport(0,0,w,h);

        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();
        GLU.gluPerspective(gl, 45, mViewWidth/mViewHeight, 0.1f, 100f);

        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();
    }

    public void onDrawFrame(GL10 gl) {
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        gl.glPushMatrix();

        gl.glDisable(GL10.GL_DITHER);

        GLU.gluLookAt(gl, 0, 0, 10, 0, 0, 0, 0, 1, 0);

        //draw_model
        gl.glPushMatrix();

        if(mOrigin != null && mRotate != null) {
            gl.glTranslatef(mOrigin.x, mOrigin.y, mOrigin.z);
            gl.glRotatef(mRotate.x, 1f, 0f, 0f);
            gl.glRotatef(mRotate.y, 0f, 1f, 0f);
            gl.glRotatef(mRotate.z, 0f, 0f, 1f);
        }

        if(mModel != null) {
            mModel.draw(gl);
            if(!RendererView.textureFileName.equals(""))
                mModel.bindTextures(mContext, gl);
        }

        gl.glPopMatrix();
        gl.glPopMatrix();

        if(isPictureTake) {

            w = getWidth();
            h = getHeight();
            b = new int[w*(y+h)];
            bt = new int[w*h];

            IntBuffer ib = IntBuffer.wrap(b);
            ib.position(0);
            gl.glReadPixels(0, 0, w, h, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, ib);
            createBitmapFromGLSurface(context);
            isPictureTake = false;
        }
    }
}

Thanks in advance.

why r u using ES 1? ES 1 doesn't support programmable pipe line, is there any specific reason?

@Tofu_Craving_Redish_BlueDragon No reason, When I start to make my app then I mainly found ES 1 examples, you can recommend me to which version should I try

if you were using ES 2.0 you can do something like GL_LINE_SMOOTH then the line will get smoothed out themselves tutorials on that here.

Solution 00 : If you still want o use ES 1.0 still, I recommend what Lasse said in chat; draw anti-aliased texture then render it as your line.

Solution 01 : Another easier way to do so will be preparing "anti-aliased" texture image with alpha value then draw it where you want to have "smooth line" (Prepare blurred square picture. Then resize/draw it where you want to have "smooth line").
 (example of "smooth" texture that can be used for Solution 01)

But really both of them are same in nature; prerender texture for the effect you want, then draw it when you need it.


text:
How can I animate the stretching of a sprite over time?
My goal is to find the function to stretch a sprite like my example below, and then get it to animate during a certain time. It is like an interpolation, where the starting point is the original image, and the final point is the stretched image. Any idea?
Here is an example, hope it is clear.

Your question is a combination of a few simple techniques. Scaling a sprite and changing a value over time. You may find it useful in the future to break apart your problem into smaller problems, that are more generic and easily searchable.

Thanks a lot. I found very useful your links and your suggestion.

The SpriteBatch class's Draw method has an overload that allows you to specify a scale factor.  Thus, to render a sprite in a stretched frame, do something like:
// Scale the sprite 50% along X (like in your example).
var scale = new Vector2(0.5f, 1.0f);

// Draw the sprite with that scale.
spriteBatch.Draw(
  texture,
  position,
  null,
  Color.White,
  0.0f,
  Vector2.Zero,
  scale,
  SpriteEffects.None,
  0
);

To achieve an animation of this effect, store your scale factor somewhere (a member in your Game class would be simple to start with), and update it over time in your game's Update method. The Update method gives you a GameTime object containing the elapsed time since the last update. Every update, adjust your scaling factor by the amount you want to scale per second using the TotalSeconds member of the elapsed time span object.


text:
Gameplay-affecting LOD in a multiplayer UDK environment
There is an idea of developing a proof-of-concept multiplayer environmental exploration game that has varying levels of level of detail in terms of not just how objects are represented, but what objects are presented to each player, depending on the assigned parameters to each player present in the world governed by certain skill-sets. After the initial discussion, it was decided to to give Unreal Development Kit a try for building this concept project. We know that in all major engines LOD settings can affect meshes and textures just fine, but normally it's bound to graphics settings for the whole game.
Example of the implementation: Player A focuses on imagery and and thus sees the world in higher level of detail - there are better textures and better meshes visible, whilst player B focuses on audio clues and thus is enabled to hear more sounds that are triggered by various events.*
Is it possible to implement such a mechanism in a multiplayer Unreal Engine 3 environment?
Since I'm relatively new to both game development and UDK's capabilities, it would be greatly appreciated if I could get advice on any possible show-stoppers for this idea. Thank you.

UDK doesn't have anything built in that does exactly what you say. However, it's certainly possible since you can conditionally play/display sounds/meshes. For example, using Kismet, the conditionals are pretty simple.
It'll certainly be a lot of work, though it's unclear from your requirements if that's a "showstopper". There's nothing that's technically impossible with what you're suggesting.

authors: 末日人生三d动漫抛砖引玉_末日人生第一季三d漫画免费巾帼英雄

authors: 美团24小时人工服务热线周瑜打黄盖_美团定位怎么设置妄自菲薄

authors: 美团24小时外卖称心如意_美团专送app官方下载乘风破浪

authors: 美团收货地址定位不到世态炎凉_美团骑手虚拟定位后会无期


text:
Ways to make my game world bigger without slowing users CPU
I've been developing my first game for a little while now, but I've found that I want to make the game world MUCH bigger. It's currently about 300*300 tiles, but has creatures and bad guys running around the whole thing, so I've got to keep track of all the enemies movement and hostile-finding algorithms.
I'm wondering how I can scale something like this up? It seems (from code profiling) that enemies are the limiting factor, and it's mainly that for each enemy, I need to scan through all the player-units and creatures to see if they're close enough for the enemies to see/attack.
Edit: W,S,A,D,B,Q, if anyone's interested in controls :)
Edit 2: Please tell me if there's any way I could improve the question!

Only update enemies within a certain range and/or use some type of spatial partitioning to reduce the areas you check/update

Thanks wes, I've thought about this - but wouldn't the quadrants need to overlap, since what if an enemy was at the edge of a quadrant? Or I suppose the quadrants could be smaller and I'd check surrounding quadrants as well? Hmmm... Thanks! You've given me something to think about.

Profile the code, that's the best way to know what's slowing it down. Currently, your question it too broad. A discussion with suggestions about how you might improve it, is too open ended a question for this site. You can try chat too.

Ahh, I see. Thanks @Byte56 I'll try to be more specific in furture. While profiling the code, it cam down to the fact that for every frame, every enemy has to scan through every 'attackable' object to see whether its in its sight radius. Do you think wes was on the right track?

Yes, there are a number of questions about such optimizations on the site. Searching for spatial partitioning will reveal a few of them.

Look into quad trees for partitioning groups of units. 2. Loading the current and surrounding quads is pretty standard.

Just ignore any actors which are far away from the player(s). Don't update them and don't allow active actors to interact with them.
Most games divide the game world into zones, and only update the actors in the zones the player is in and the adjacent zones. Many even despawn the actors and respawn them at their initial positions when the zone becomes active again to save memory.
When it is important for your game concept that certain actors do things while the player is away (for most games it is not), you could freeze the action in inactive zones, and when the player comes near calculate the activity in the zone which happened in the meantime using a simplified model. When you have, for example, an RPG with a blacksmith NPC who makes swords by automatically collecting resources and bringing them to his forge, the simplified model would not do the routefinding but just use an estimation how many swords he would have made during the time the player was away, remove the required resources from the surrounding and give him that number of swords.
When you have actors which travel around the whole game world and you want them to keep doing that even when the player isn't close (like in Oblivion or Skyrim), you could strongly simplify the route-finding while the player is away. When you know by experience that traveling from town A to town B takes about 20 minutes, you can treat this as a single step with a cost of 20 minutes in your route-finding system. When the player now suddenly enters the area between town A and town B, and the NPC left town A 15 minutes ago, you would calculate the actual path and spawn the NPC on 3/4 of its way towards town B.

"calculate the activity in the zone which happened in the meantime using a simplified model" YES! Thank you so much, if only stack overflow had a 'tip' feature. Really appreciate the thought you put into that and the great explanation :)

@JoeRocc Actually, there is a tip-feature. But you need more reputation to use it.

You could also do something similar to MineCraft so only the active blocks are loaded. For doing that, you could store each part (e. g. 32x32 tiles) in its own file and load always only the part the player is in and the surrounding. When the player enters another part, save the parts the player is two far away and load the new ones. If you use procedural generated terrain, it wouldn't be too complicated to create endless worlds without using too much CPU (of course, the game may lag short when the new map parts are loaded).

Thanks so much! This infinite world thing is looking so much more feasible now, really appreciate you help - wish I could accept all these answers.

As everyone has already stated, Spatial Partitioning! I think a bare minimal 2D Grid vs. Bounding Sphere will cut it for most browser games.
Since nearly everyone has multiple processors, your game might benefit greatly from Web Workers.
This way you can let the main browser thread focus on providing a perfectly responsive interface at all times. Further, to combat the artifacts caused by updating entities at a lower FPS, you can calculate velocities in your AI update, and then predict positions every render frame.

Oh, that is neat - thanks Mick! Web Workers it is!

authors: 126免费邮箱登陆入口岁寒三友_163邮箱官网注册杯水车薪

authors: 2021年不付费黄台下载--免费完整版片

authors: 2021果冻传媒_2021果冻传媒-免费完整版片

authors: 884aa永久播放地址sxm2cc_亚洲永久免费播放片国产

authors: 一级免费录像_一级免费录像免费在线完整版片

authors: 怏猫全球华人短视频分享平台_快描短视频记录你世界

authors: 永久免费不封视频网站因果报应_sds最新网站2828春暖花开

authors: 江苏卫视电视剧回看网相得益彰_相亲节目非诚勿扰九九归一

authors: 猫快官网入口在线金屋藏娇_怏猫线上体验入口官网心力衰竭

authors: 美容院的特别服为2_美容院的特别服为2-在线观看完整版

authors: 马祖影视免费vip电影_端木影视vip最新版本


text:
Where is linked_portal_door in the Source SDK?
I just made a new mod in the Source SDK. I saw online that there is an entity that allows portals to be created (linked_portal_door). However, I cannot find or create this entity.
Is it included in the base SDK or do you have to have an add-on. If it is not included, is there an alternative?
I am using Source Engine 2007.

Per the documentation, linked_portal_door was added with Portal 2.
It sounds like your version of the SDK and toolset is too old to have it, and there is no alternative that I am aware of (the releated prop_linked_portal_door is also only available in Portal 2).

authors: 天美传媒爱情公寓在线播放--高清播放

authors: 成大本人35分钟大象_成大本人35分钟大象完整版免费播放

authors: 行秋适合什么圣遗物_行秋适合什么圣遗物-高清播放


text:
Parallax scrolling with 2D camera
I'm developing a 2D Platform game, I have a 2D camera, some backgrounds, and everything is working good. Now I want to implement parallax scrolling to give the illusion of depth in my game, but i can't imagine how to make my different layers of background to move (most correctly, be rendered by the camera) with a different speed from each other).
In brief this is my game structure:
I have 3 layers of backgrounds: the first is the road level, where the player runs; the second is the intermediate; the third are some mountains very distant (in my mind). Everyone of these layers is created with seamless textures and organized with the tilemap technique, with every texture positioned one after the other. Of course I make the spritebatch draw only the visible ones.
The camera is a rectangle that follows player movements and goes just horizzontaly.
Since layers aren't moving, but only the camera is moving, I don't know how to make a background scroll with a different speed from another!

Take a look at http://www.jgallant.com/blog/how-to-create-a-parallax-effect-in-monogame/   It says Monogame, but the XNA code is exactly the same.

You just move the backgrounds despite them being meant to be static.

For example, your character (and the camera) move 5 units to the right.
Move the background right behind the character to the right by 1 unit.
Move the background behind the other background by 2 units.
Move the next background by 3 units, etc.
The furthest away background (i.e. the background supposed to be static) is moved with the player/camera (here: 5 units).

Doing this will already create the parallax effect you're looking for.
Simplified:
Move your backgrounds with your camera, where the actual movement is a function based on the camera's movement and the distance to/behind the screen. The further away something is, the more you move it (so it appears static).
This can get a bit tricky drawing wise, but you'll essentially just have to draw your backgrounds twice at most (so it always fills the screen, no matter the offsets).

Actually you'll want the closest things to move faster than the furthest things. IE your furthest away background should only move 1 unit while your layer right behind the character may move 4.

Correct, but if you move the camera, you'll have to move the furthest away back together with the camera (i.e. the fastest). Essentially it appears reversed, but that's correct unless your camera is static (then you'd be right).

Ah, that makes sense. I've always used a static camera.


text:
OpenGL camera translate and rotate on cameras local axis
How can I make rotation and translation on a local camera axis in OpenGL?
I want to make camera like "aeroplane" camera with a pitch yaw and roll.
I want to have good explanation on everything!
Can the solution be with gluLookAt maybe and be without gimbal lock?

Please feel free to tell me if every step is understandable. If it's not i will add more explanation.
Active variables -------------------------------------------------------------------------------------------------

camera_drot={Rotation arou x(right) axe, -\- y(up) axe, -\- z(forward) axe} [radians]
camera_dtra={Translation by x(right) axe, -\- y(up) axe, -\- z(forward) axe}

Code:
float camera_drot[3]={0,0,0};
float camera_dtra[3]={0,0,0};

float camera_place[3]={0,0,0};
float camera_right[3]={1,0,0};
float camera_up[3]={0,1,0};
float camera_forward[3]={0,0,-1};

Algoritem of transformation ------------------------------------------------------------------------------------

I will delete camera_ for better view. :)
If you rotate camera's axis around x axe you must rotate y and z axe (example).
After the rotation its vital to make sure the forward,up,right acis is rectangular and all axis must have length "1"! If we dont make Orthonormality(forward,right,up) the errors in computers computation will sums up really fast! Belive me!
After the Orthonormality we can translate cameras place in local system of cameras axis.
The good old gluLookAt() the simplest thing to comunicate with OpenGL obout cameras properties.

Code:
if(drot[0]!=0){
    MYRotation(right,up,drot[0]);      //#Rotate up axis oround right for drot[0] radians
    MYRotation(right,forward,drot[0]);
    drot[0]=0;}
if(drot[1]!=0){
    MYRotation(up,right,drot[1]);
    MYRotation(up,forward,drot[1]);
    drot[1]=0;}
if(drot[2]!=0){
    MYRotation(forward,right,drot[2]);
    MYRotation(forward,up,drot[2]);
    drot[2]=0;}

Orthonormality(forward,right,up);

if(dtra[0]!=0){
    MYTranslation(right,place,dtra[0]);
    dtra[0]=0;}
if(dtra[1]!=0){
    MYTranslation(up,place,dtra[1]);
    dtra[1]=0;}
if(dtra[2]!=0){
    MYTranslation(forward,place,dtra[2]);
    dtra[2]=0;}

glLoadIdentity();
gluLookAt(place[0],place[1],place[2],
          place[0]+forward[0],place[1]+forward[1],place[2]+forward[2],
          up[0],up[1],up[2]);

MY Functions --------------------------------------------------------------------------------------------------------
Orthonormality

Normalize vec0! If we normalize vec0 we simplify many things!
Projected vec1 on ortogonal space of vec0 vector.orthogonal complement

After a projection we have to normalize new vec1!
And in this step we find vec3 with Gram–Schmidt process
Final step is normalize vec3.

Code:
static void Orthonormality(float vec0[3],float vec1[3],float vec2[3]){
    //1
    float normalize = pow(vec0[0]*vec0[0]+vec0[1]*vec0[1]+vec0[2]*vec0[2],-0.5);
    if(normalize!=1){
        vec0[0]=vec0[0]*normalize;
        vec0[1]=vec0[1]*normalize;
        vec0[2]=vec0[2]*normalize;}

    //2
    float x1=vec1[0];
    float y1=vec1[1];
    float z1=vec1[2];

    vec1[0]=x1*(vec0[1]*vec0[1] + vec0[2]*vec0[2]) - vec0[0]*(vec0[1]*y1 + vec0[2]*z1);
    vec1[1]=-vec0[0]*x1*vec0[1] + vec0[0]*vec0[0]*y1 + vec0[2]*(y1*vec0[2] - vec0[1]*z1);
    vec1[2]=-(vec0[0]*x1 + vec0[1]*y1)*vec0[2] + (vec0[0]*vec0[0] + vec0[1]*vec0[1])*z1;

    //3
    normalize = pow(vec1[0]*vec1[0]+vec1[1]*vec1[1]+vec1[2]*vec1[2],-0.5);
    vec1[0]=vec1[0]*normalize;
    vec1[1]=vec1[1]*normalize;
    vec1[2]=vec1[2]*normalize;

    //4
    float x0x2_y0y2_z0z2=vec0[0]*vec2[0] + vec0[1]*vec2[1] + vec0[2]*vec2[2];
    float x1x2_y1y2_z1z2=vec1[0]*vec2[0] + vec1[1]*vec2[1] + vec1[2]*vec2[2];
    vec2[0] = vec2[0] - vec0[0]*x0x2_y0y2_z0z2 - vec1[0]*x1x2_y1y2_z1z2;
    vec2[1] = vec2[1] - vec0[1]*x0x2_y0y2_z0z2 - vec1[1]*x1x2_y1y2_z1z2;
    vec2[2] = vec2[2] - vec0[2]*x0x2_y0y2_z0z2 - vec1[2]*x1x2_y1y2_z1z2;

    //5
    normalize = pow(vec2[0]*vec2[0]+vec2[1]*vec2[1]+vec2[2]*vec2[2],-0.5);
    vec2[0]=vec2[0]*normalize;
    vec2[1]=vec2[1]*normalize;
    vec2[2]=vec2[2]*normalize;
    }

MYRotation
Rotate vec around line for drot radians.
static void MYRotation(float line[3],float vec[3],float drot){
    float ux=line[0]*vec[0];
    float vy=line[1]*vec[1];
    float wz=line[2]*vec[2];
    float uu=pow(line[0],2);
    float vv=pow(line[1],2);
    float ww=pow(line[2],2);
    float uxvywz=ux+vy+wz;
    float sa=sin(drot);
    float ca=cos(drot);
    vec[0]=line[0]*uxvywz+(vec[0]*(vv+ww)-line[0]*(vy+wz))*ca+(-line[2]*vec[1]+line[1]*vec[2])*sa;
    vec[1]=line[1]*uxvywz+(vec[1]*(uu+ww)-line[1]*(ux+wz))*ca+( line[2]*vec[0]-line[0]*vec[2])*sa;
    vec[2]=line[2]*uxvywz+(vec[2]*(uu+vv)-line[2]*(ux+vy))*ca+(-line[1]*vec[0]+line[0]*vec[1])*sa;
    }

MYTranslation
Translate vec for line*dtra
static void MYTranslation(float line[3],float vec[3],float dtra){
    vec[0]+=line[0]*dtra;
    vec[1]+=line[1]*dtra;
    vec[2]+=line[2]*dtra;}

authors: Любовь Иванова


text:
Tile Map World Background
I am making a 2D top-down game in Java using the Slick2D library. However, this question applies to all ways of making games of this nature.
My question is: How would I do a background for the world. Currently it looks like this:

Obviously, this isn't the best example, as the right side has an area that allows the player to walk into the 'background'. However, I am asking how this is done in other games, such as Pokemon.

Possible duplicate: Stop map from scrolling but let player still move?

It's not a duplicate, but the method defined in that question is a valid way of tackling my problem, thanks. You could make that an answer, just that I could stop scrolling, and I'll mark it as accepted.

If you're working on a plain style map, you can either stop the map from scrolling and make the player move "beyond" the center of the screen OR stop the map from scrolling BEFORE you've reached your limit minus half your screen size.

This is a very good solution, and I have implemented it.

If you don't want to use the method Byte56 linked, another option is to just make a bigger map.  You don't have to put transition points right at the edge of the background.  If you can see up to 20 tiles away, ensure that the "playable area" of the map is within a 20 tile border of the map.  Note that this can be a bit jarring/annoying to players if you don't somehow make it very visually clear where the transition point.
Games like Neverwinter Nights (2002 version) would automatically extend a tiled map out but shade out the extended area.  Thus a pathway that led right up to the "edge" of a map wouldn't just end in darkness but would visually appear to stretch out into the fog.  The darkened shader along with NWN uses a clickable highlight region for transition areas made it clear and obvious where these transitions were but also make the map edges look less like an entire map was inside a box and instead part of an expansive, endless world.

Thanks for your help. I actually was inspired for a 'dark' style game by your answer. I just kept thinking about that. I think I'll use this in that if I bother making it.

There's also approach Heroes of Might and Magic chose - they render a border around the map and fill the abyss with stone texture:


text:
Port a WP7 game to WP8 with Monogame
I have a full working game for WP7, I want to port it to WP8 with Monogame. I have installed Monogame and I have done all tests to see that it is working inside Visual Studio Express 2012 for Windows Phone 8. Now I just don't understand how to rebuild my WP7 version game within a Monogame project to target WP8 devices.
So, if you would have the entire solution of a WP7 game, how would you make it work on WP8 with Monogame?
Thanks!

This is pretty broad. You'll need to be more specific about how it's currently not working. What, specifically, is happening?

Well as far as I have it, it will probably be easiest for you to create a new Windows Phone 8 MonoGame project from the template and then just copy all the code in. MonoGame uses the exact same namespaces, it just has a lot of behind the scenes changes that make it reference different libraries. Applying these changes whilst also applying all the other changes necessary for WP7 to WP8 project manually will be a complicated and messy task which will probably require hours of troubleshooting to get it working.

An even easier option would be to just make a copy of his WP7 project and then simply edit the monogame reference.. As far as i know, it should work straight away unless the win8 solution requires some special initialization in program.cs?


text:
WebGL immediate mode
I know that WebGL is based on OpenGL ES 2.0 and that glBegin and glEnd have been removed and replaced with vertex buffer objects. I understand that VBOs are faster and use less code but is there a library or add-on for JavaScript / WebGL that re-implements these functions?
After more research, I have discovered that this functionality is called immediate mode.

It's unclear what your rationale is for doing this. You might want to ask a new question about the problems you're running into that would inspire you to look for such a utility.
There is a library called LightGL that attempts to do what you're asking. This is just a simulation of immediate mode, since true immediate mode is not supported. It's not really very close to immediate mode either, but it's likely as close as you're going to get.

I was actually looking at light.js on GitHub when I saw your message. What does it mean when it says that it has no fixed function lighting?

As for why I am lookin into this, I built a simple 2d engine in LWJGL using immediate mode and I am looking to port it as easily as possible!

Fixed function lights are immediate mode lights (so you can only do shader level lights). I don't want to start a discussion here about it, you should ask your questions about it in chat if you want further information. If the questions warrant it, you might also ask new questions.


text:
How can I get post-processing effects with pygame?
I'd like to be able to make the screen like blurry and wavy, like when a player enters a portal in Minecraft.
How would I make this with pygame?

My suggestion would be to use surfarrays in conjunction with NumPy.
Assuming you already have an algorithm for the post-processing effects you want, all you'll have to do is port it into NumPy syntax, which will probably just take some tinkering.  Examples of usage can be found here, here, here, and here.
After manipulating the surface, you just have to take whatever is output and blit it back to the screen.
A word of warning: full screen processing in pygame, even with surfarrays and NumPy, can be very slow.  I once tried to create a desaturation post-processing effect for a pygame game, and struggled to get the game to run at 30fps at something like 640x480 resolution.  Of course, if you get speedy results, I'd love to see how you did it :)

Great, I will start doing some work on this. I haven't really done any algorithm for this, but I will start working on it right now. This was a great answer, thanks a lot!


text:
How to march tiles together like in Terraria?
I've been trying to get tile marching to work like in Terraria, and I got something to work. I don't think it's actually very good way of doing this, so I'm wondering what would be really the main way of doing this.
Here's a picture of what I want to accomplish:

As you can see, this really does the thing that I want, but it's so horrible looking and it'd be a pain to extend for different types of tiles.
Here is my code for this. I coded this as a test, so my full game would use tile classes etc.
for x, tile in enumerate(row):
    if tile:
        try:
            air = row[x + 1]
        except Exception:
            pass
        else:
            if not air:
                if not LEVEL[y - 1][x]:
                    tile = 3
                else:
                    tile = 6
        air = row[x - 1]
        if not air:
            if not LEVEL[y - 1][x]:
                if tile == 3:
                    tile = 5
                else:
                    tile = 4
            else:
                if tile == 6:
                    tile = 8
                else:
                    tile = 7
        LEVEL[y][x] = tile
for y, row in enumerate(LEVEL):
    for x, tile in enumerate(row):
        if LEVEL[y - 1][x] in (6, 3, 14):
            try:
            pos = LEVEL[y][x + 1]
        except Exception as e:
            print(e)
        else:
            if pos in (2, 3):
                LEVEL[y][x] = 11
    if LEVEL[y - 1][x] in (7, 4, 15):
        pos = LEVEL[y][x - 1]
        if pos in (2, 4):
            LEVEL[y][x] = 12
    if LEVEL[y - 1][x] in (5, 8):
        if LEVEL[y][x] == 1:
            LEVEL[y][x] = 13
    if LEVEL[y][x] == 6:
        if LEVEL[y][x - 1] in (2, 4):
            LEVEL[y][x] = 14
    if LEVEL[y][x] == 7:
        try:
            tile = LEVEL[y][x + 1]
        except Exception as e:
            print(e)
        if tile in (2, 3):
            LEVEL[y][x] = 15

The basic idea behind this is just to look for some air and dirt, and set the tiles image from those.
Basically then when I'm drawing this I just take the value at a coord and blit the corresponding image to the screen.
So how would I go about making this as readable and easily extendable as possible? Does anyone know how Terraria handles this?

"March"? Typo in title? I think I understand what you are asking. Sadly I don't have an answer as I have the same problem :P

I don't really know what to call this, I'm not a native english speaker and I found something called tile marching that had something to do with this.

You want the terrain to be smoothed? You might be referring to marching cubes (or marching squares in the case of 2D). That's a technique for turning a point cloud into a mesh. Terraria didn't use that.

I just want to add a layer of grass on top of the dirt, and eventually effeciently add a layer on top of other tiles like stone. So basicaly I want to smooth the edges of tiles that are connected to air.

http://gamedev.stackexchange.com/questions/29524/choose-tile-based-on-adjacent-tiles

@Byte56 Yup, an obvious duplicate. I must have missed that back in the days.

It's alright, I just noticed when looking for a recent duplicate. Just making sure it shows up in the linked questions on the right.

Yeah, that was my duplicate flag. Are you sure this question shouldn't be marked duplicate as well?

I smell the development process of GunHero.

Your nose is partially right. I asked this question while working on a different project, but surely what I learned from the awesome answer below helped me implement this terrain pattern to GunHero over two years later.

If I understand right, your map stores whether something is dirt or air, and the simplest thing would be to have dirt and air tiles. However, to make things look better, you have separate images for air above dirt, dirt above air, dirt left of air, and so on. So you're trying to figure out which image to use, given a tile and its neighbors. Is that right?
If so, take a look at one of these articles:

http://www.angryfishstudios.com/2011/04/adventures-in-bitmasking/
http://playtechs.blogspot.se/2007/04/tileset-design-tip.html
http://archive.gamedev.net/archive/reference/articles/article934.html


text:
XNA C# Making the game scaleable for different resolutions
I am currently developing a game in C# and XNA, and I want it to look right at all resolutions. How would I get started with doing that?

You need to define what kind of game you're making, and what "look right" means specifically.

At the moment when I make the resolution bigger, everything in the game stays the same size and gets pushed to the top left hand corner of the screen. On the bottom right there is just the window colour I am drawing. I want it to scale to fill the window at all times.

@Matthew: sounds like you need to scale the positions and sizes of your sprites according to the viewport size.

Thanks for the help. Could you please give me an example on how I would do that?

I probably should have asked specifically - but you should say how you are drawing. I assume SpriteBatch? Can you please edit your question to include all this information - for anyone who comes along later? (And to avoid your question getting closed.)

Yes, spritebatch

First, you have to decide how are you going to actually do the scaling? Do you need to handle aspect ratio? (It sounds like you do.)
If you are using SpriteBatch, you can pass a scaling matrix to Begin. You can also set the Viewport to letterbox or pillarbox off the screen you don't want to render to. Here is an example:
int backbufferWidth = GraphicsDevice.PresentationParameters.BackBufferWidth;
int backbufferHeight = GraphicsDevice.PresentationParameters.BackBufferHeight;

Viewport originalViewport = GraphicsDevice.Viewport;
GraphicsDevice.Viewport = new Viewport((backbufferWidth - viewWidth)/2
        (backbufferHeight - viewHeight)/2, viewWidth, viewHeight);

Matrix scaleMatrix = Matrix.CreateScale(scale, scale, 1);
spriteBatch.Begin(0, null, null, null, null, null, scaleMatrix);

// ... draw your sprites ...

spriteBatch.End();

GraphicsDevice.Viewport = originalViewport;

Note that the above code is untested. Also, I've left the maths for figuring out scale and viewWidth and viewHeight as an exercise - it will depend on how you actually want the scaling to look.
(My answer on that question I linked might give you a starting point. Don't forget to use Math.Floor to set viewWidth/Height, so it doesn't round up and extend outside the backbuffer!)

You can create a menu with an option to change the resolution. Include all the  standard resolutions.
When the user clicks on that option, change the resolution via
graphics.PreferredBackBufferWidth = 1920; //Your width
graphics.PreferredBackBufferWidth = 1080; //Your height
graphics.ApplyChanges(); //When calling this from outside the constructor, apply all the changes.

And if you want to scale up everything, render it into a RenderTarget with fixed size and then render the RenderTarget to the screen (and scale it up).

It would be better to get the available resolutions dynamically from GraphicsAdapter.DefaultAdapter.SupportedDisplayModes, rather than making potentially invalid settings available.

I didn't know something like that existed. But I'd really appreciate if you changed my answer or created your own one.


text:
Obtain rectangle indicating 2D world space camera can see
I have a 2D tile based game in XNA, with a moveable camera that can scroll around and zoom.
I'm trying to obtain a rectangle which indicates the area, in world space, that my camera is looking at, so I can render anything this rectangle intersects with (currently, everything is rendered).
So, I'm drawing the world like this:
  _SpriteBatch.Begin(
                SpriteSortMode.FrontToBack,
                null,
                SamplerState.PointClamp,        // Don't smooth
                null, null, null,
                _Camera.GetTransformation());

The GetTransformation() method on my Camera object does this:
    public Matrix GetTransformation()
    {
        _transform =
           Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
           Matrix.CreateRotationZ(Rotation) *
           Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
           Matrix.CreateTranslation(new Vector3(_viewportWidth * 0.5f,
               _viewportHeight * 0.5f, 0));
        return _transform;
    }

The camera properties in the method above should be self explanatory.
How can I get a rectangle indicating what the camera is looking at in world space?

Do you use rotation?

No, camera has fixed rotation.

You can just create one from the position of the rectangle then, viewport width and height, multiplied by scale.

Sorry, I don't understand that. Surely the camera position has to be involved?

Sorry, by position of rectangle I meant the camera... :)

Ah, that got me thinking. I've having to divide by zoom (something is back to front), but this seems to work: float CameraLeftBound = _Camera.Pos.X - ((Window.ClientBounds.Width / 2) / _Camera.Zoom );

Ok, so here's what seemed to do the trick:
 Rectangle CameraWorldRect = new Rectangle(
                Convert.ToInt32(_Camera.Pos.X - ((Window.ClientBounds.Width / 2) / _Camera.Zoom)),
                Convert.ToInt32(_Camera.Pos.Y - ((Window.ClientBounds.Height / 2) / _Camera.Zoom)),
                Convert.ToInt32(Window.ClientBounds.Width / _Camera.Zoom),
                Convert.ToInt32(Window.ClientBounds.Height / _Camera.Zoom));

Reduced CPU usage 3% by not drawing unnecessary tiles, happy days.

You could use your _viewportWidth(Height) instead of Window.ClientBounds.

Any particular advantage to one over the other?


text:
Android Live Testing
I am making a game for android and in it I am using sensors which are not available in the emulator. At the moment I am connecting my device and transferring the apk, then installing to test but that is a pain to do, and I have gotten to the stage where I need to start logging values for debugging. I have gone into the run configs of my app and set it to prompt me to pick a device, but my device is never in the list when it is connected to my PC and I try to run it. How am I supposed to set it up to work properly?
Thanks for the help.

Doesn't sound like this is specific to game development. General programming questions should be asked on stackoverflow.com.

EDIT: This works fine on it's own. It's only when I implement it into my game that it doesn't work.

This depends on what engine you are using. Are you using a custom engine? You could easily create a method when building your apk to upload it to your phone as well.
If you are using an already made engine then its dependent on that. Unity supports building to the phone, LibGDX does as well.
What are you creating this in?
EDIT: After reading your problem again. If your phone doesn't show up in ADT. You need to make sure you have the USB drivers for your phone installed. Make sure USP debugging is on. And if it's a Nexus device change the connected mode to camera and not media.

Thanks for the help. I had USB debugging on, but I had to download the OEM drivers from the Samsung website. Working well now :)


text:
Best way to do "cutscenes"
I'm curious about the best way to display cutscenes in canvas. When I say cutscene I mean something like a static image fading from one to the other. Would it be best to use a timeout for a certain amount of seconds then go to the next image? Alternatively, would it be better to somehow use the main loop and increment a counter? If anyone has a method they use, post an answer! :D

Do you mean 2D? If so, this is probably a dupe of: http://gamedev.stackexchange.com/questions/31694/what-is-the-best-way-to-display-a-cut-scene?rq=1

"Best" is really subjective.  If it works, it works.  Code something up and see if you run into concrete problems.

Whatever you do, don't use window.setTimeout.  Instead, use requestAnimationFrame.

Don't use setInterval() or so on for animating canvas. There is a requestAnimationFrame() (MDN) function for this. It has better performance and more usefull in general.
Here is a good article about it: http://html5hub.com/request-animation-frame-for-better-performance

Use setTimeout() instead of setInterval(), because setTimeout() will only run after a successful call, while setInterval() would just stack many unhandled calls in case one of the calls takes more time to complete before another call is made. Combine it with requestAnimationFrame() for even better performance plus not trying to render while the browser window is not even being shown.
This is what a standard JavaScript game loop usually looks like:
function getTime() {
    return new Date().getTime();
}

function loop() {
    var startTime = getTime();
    screen.update();
    var elapsedTime = getTime() - startTime;
    var interval = FRAME_DURATION - elapsedTime;
    setTimeout(onTimeout, interval);

    function onTimeout() {
        requestAnimationFrame(loop);
    }
}

function main() {
    loop();
}

main();

You have to issue the first call to loop() from main() (or whatever your main function is called) and then it will keep calling itself indefinitely. In the snippet above, screen.update() is the method for your animation. And yes, you can have a ++tick there to increment whatever property of your animation is required to make the transition.


text:
Making more complicated systems(entity-component-system model question)
I'm using a model where entities are collections of components and components are just data. All the logic goes into systems which operate on components. Making basic systems(for Rendering and handling collision) was easy. But how do I do more compilcated systems? For example, in a CollisionSystem I can check if entity A collides with entity B. I have this code in CollisionSystem for checking if B damages A:
if(collides(a, b)) {
HealthComponent* hc = a->get<HealthComponent();
hc.reduceHealth(b->get<DamageComponent>()->getDamage());

But I feel that this code shouldn't belong to Collision system. Where should code like this be and which additional systems should I create to make this code generic?

Messaging is a common way of handling this. So your health system would subscribe to messages about collision, combat, etc. Then the health system is the only place where health is modified.
Messaging also allows multiple systems to subscribe to the same events. For example, when a collision happens the health system can be notified, sound system and the user notification system. Lots of options and it keeps code localized to the systems where it belongs.
See this question for some details about such systems.

Is there any resources which show how to implement and use those systems? I think OP's solution was too difficult to understand with all those long named classes. Most tutorials I've seen focus only on the aspect of creating simple systems, but I've never seen one where messaging between systems is covered.

This site has a number of questions about it: http://gamedev.stackexchange.com/search?q=messaging+system+is%3Aq. Otherwise, you can ask a specific question about the trouble you're having implementing a messaging system if those questions don't solve your problems.

I'll read this, thanks. My problem definitely will be solved using this.

By the way, which system do you use yourself? Any recommended approaches? Because most of the threads cover lots of themes to choose from.

I rolled my own. It'll probably be specific to your requirements. Start with something simple and keep adding the things you need. Any further discussion about it should be taken to chat. Good luck!


text:
Infinite terrain shadows
I'm creating an infinite terrain engine, which generates the terrain either with fractals or noise. How can I make dynamic shadows for the sun on this terrain, if I don't know in advance what will be rendered in front of the sun.
My terrain:
The sun is the only light, it is directional, my terrain is generated on a plane which is positioned before the camera, frustum culled and fits the size of the viewing frustum.
It is height mapped with generated noise texture, and using tessellation shaders on it.
Video:http://www.youtube.com/watch?v=tk6yFwYusOs
Dynamic shadows with the infinite terrain.

Is the noise texture generated in the shader? Is it randomized in a way that you could theoretically reproduce the exact same texture if the same seed was used for the noise function? If yes, then I think standard shadowing techniques like shadow mapping can be applied here. Just render the plane, height-mapping it using the same random noise that will later be used for the actual terrain rendering, but from the sun's point of view using an orthographic projection to generate a shadow map.

That video doesn't show any shadows being generated for terrain that doesn't exist. If you want to generate shadows for terrain that isn't yet visible, you need to generate the terrain in advance of the camera view distance.

It's important to know if you plan on rotating your sunlight as these would require real dynamic shadows rather than static predefined ones.

Generate shadows as part of your render, this way you render shadows around the camera and as the camera moves your detailed shadows relocate. Many games operate this way and apply lower detailed shadows (e.g. lower resolution shadow textures) the further from the camera a portion of the scene is.


text:
OpenGL camera moves faster than player
I have a side scroller game made in OpenGL, and I'm trying to center the player in the viewport when he moves. I know how to do it:
cameraX = Width / 2 / TileSize - playerPosX
cameraY = Height / 2 / TileSize - playerPosY

However, I have a problem. The player and "camera" move, but the player moves faster than the "camera" scrolls. So, the player can actually move out of the screen.
Some code, this is how I translate the camera:
public Camera(){
}

public void update(Player p){
    glTranslatef(-p.getPos().x - Main.WIDTH / 64 / 2, -p.getPos().y - Main.HEIGHT / 64 / 2, 1);
}

Here's how I move the player:
public void update(){
    if(Keyboard.isKeyDown(Keyboard.KEY_D)){
        this.move(MOVESPEED, 0);
    }

    if(Keyboard.isKeyDown(Keyboard.KEY_A)){
        this.move(-MOVESPEED, 0);
    }
}

The move method:
public void move(float x, float y){
    this.getPos().set(this.getPos().x + x, this.getPos().y + y);
}

And then after I move the player, I update the player's geometry, which shouldn't matter.
What am I doing wrong here, this seems like such a simple problem, yet it doesn't work!

What does glTranslatef do?

Are you translating on the projection matrix?

is your player's coordinates in screen coordinates or does your 'world' use a separate coordinate system? You'll need to convert between world coordinates and screen coordinates to do the calculations for translation.

I already do that, as you can see in my code...

The solution is simple. You just translate the camera to the position in the center of the player. If the stored player position is in the center of the player sprite then cameraPosition = playerPosition. If it is in the left bottom of the player sprite then cameraPosition = playerPosition + playerSize/2.0.  One important thing is to first update the player position and then the camera position, otherwise your camera will lag one update behind.

I understand that, and its what I'm doing right now, but as I said, its scrolling slower than the player. The player can escape the screen.

With the way i suggest, the camera will be fixed on the player position (no scrolling involved). You should check the order of the positions updates. Also, maybe your are doing some transformation to the geometry of the player, other than the translation, that is probably changing the position of the geometry.

As Anastasios said, if your Camera update function is called first and the player Move function after, the camera will follow the previous position of the player, and it will look as the Player go faster than the camera.
And what are Main.Width, 64 and Width? You never use cameraX and cameraY ?
If you want your player to constantly be in the center a easier way is :
glTranslate(playerPos.x, playerPos.y) //Camera translate
//draw your level
glPushMatrix(); //save where you where
glLoadIdentity() //Reset the translate to (0,0) (I'm not sure, but I think it'll affect the camera translate, that would be a big problem)
//Draw your Player
glPopMatrix() // return to the camera translation.

I did not tested this code, but I think that you'll understand what I plan to do.


text:
When storing voxels in chunks, how do I access them at the world level?
I'm not looking for how to store the voxels, data wise; I'm looking for the theory. Currently, my voxel engine has no global list of tiles. Each chunk has its own list, and its "hard to do things" like collision detection or anything that may use tiles that are outside of its own chunk. I want to start using height maps, but I have a problem. If each chunk has its own list, then it will be pretty difficult to implement the height maps.
Should I store a global list of voxels, independent of the chunks? Then, I can just easily perform collision detection and terrain generation. However, it would probably be harder to do things such as frustum culling.
So how should I store voxels?

What do you think makes it hard for heightmap generation? Chunks are just some way to organize the data, just iterate over all chunks as you do with columns/voxels?

I guess, but still. Storing a global list of voxels just seems so much more simple. I took a look at Minecraft's source code when it was still in a very alpha stage, and I believe it had one list of tiles, and not a list per chunk.

How are you planning to remove the voxels from the global list when a chunk is removed? I can pretty much assure you that it will be easier if every chunk has it's own list/array of voxels. One thing you could try is to do something like that chunk.get(-1, 0, 0) basically return chunk.left.get(chunk_width - 1, 0, 0) so that you dont have to write any hacky code in your collision detection/anywhere else.

You don't need a new way of storing them, just just need a new way of accessing them. Storing the data in lists in the chunks is fine. You just need a way to index into them at the world level.
The world should contain a list of chunks currently loaded, and the chunks contain lists of voxels. Each chunk should be the same size (contain the same volume of the world). Now when you want to access a specific voxel in the world, you only need to convert world coordinates into two pieces of data: chunk and chunk coordinates.
Imagine a 2D example. You have a 2D world where each chunk contains 10 x 10 pixels. At the world level you want to access the pixel data for pixel (342,103). First you need to find the chunk that contains the data. You can easily find that because you know each chunk contains 10 x 10 pixels. To get chunk coordinates, just divide by the number of pixels per chunk, (int)342/10 = 34 and (int)103/10 = 10, giving you chunk (34,10).
Now you just need to get the coordinates within the chunk. Those coordinates can easily be found by getting the remainder after the division, i.e. a modulo operation. 342%10 =  2 and 103%10 = 3, giving you pixel (2,3).
That means world position (342,103) can be found in chunk (34,10) at position (2,3).
Think of it like graph paper, where the larger thicker lines show you where the chunks are and the smaller grids are the data each chunk holds.

The system used to access each can be very similar. It's just that one system holds chunks, while the other holds voxels.


text:
LWJGL: Camera distance from image plane?
Let me paste some code before I ask the question...
public static void createWindow(int[] args) {

    try {

        Display.setFullscreen(false);
        DisplayMode d[] = Display.getAvailableDisplayModes();
        for (int i = 0; i < d.length; i++) {
            if (d[i].getWidth() == args[0] && d[i].getHeight() == args[1]
                    && d[i].getBitsPerPixel() == 32) {
                displayMode = d[i];
                break;
            }
        }

        Display.setDisplayMode(displayMode);
        Display.create();

    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }

}

public static void initGL() {
    GL11.glEnable(GL11.GL_TEXTURE_2D);
    GL11.glShadeModel(GL11.GL_SMOOTH);
    GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    GL11.glClearDepth(1.0);
    GL11.glEnable(GL11.GL_DEPTH_TEST);
    GL11.glDepthFunc(GL11.GL_LEQUAL);

    GL11.glMatrixMode(GL11.GL_PROJECTION);
    GL11.glLoadIdentity();

    GLU.gluPerspective(45.0f, (float) displayMode.getWidth()
            / (float) displayMode.getHeight(), 0.1f, 100.0f);

    GL11.glMatrixMode(GL11.GL_MODELVIEW);
    GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST);
}

So, with the camera and screen setup out of the way, I can now ask the actual question: How do I know what the camera distance is from the image plane? I also would like to know what the angle between the image plane's center normal and a line drawn from the middle of one of the edges to the camera position is.
This will be used to consequently draw a vector from the camera's position through the player's click-coordinates to determine the world coordinates they clicked (or could've clicked).
Also, when I set the camera coordinates, do I set the coordinates of the camera or do I set the coordinates of the image plane?
Thank you for your help.
EDIT: So, I managed to solve how to calculate the distance of the camera... Here's the relevant code...
private static float getScreenFOV(int dim) {
    if (dim == 0) {
        float dist = (float) Math.tan((Math.PI / 2 - Math.toRadians(FOV_Y))/2) * 0.5f;
        float FOV_X = 2 * (float) Math.atan(getScreenRatio() * 0.5f / dist);
        return FOV_X;
    } else if (dim == 1) {
        return FOV_Y;
    }
    return 0;
}

FOV_Y is the Field of View that one defines in gluPerspective (float fovy in javadoc). This seems to be (and would logically be) for the height of the screen. Now I just need to figure out how to calculate that vector.

Tge camera's distance from the image plabe is always the near value of the camera and you alwyys move the camera's position, not the plane.

How do I know what the camera distance is from the image plane?

I'm not sure if this is a meaningful question to ask - what is the image plane? A real camera has a plane on which an image is formed, but in OpenGL there is no such thing. If you need this for some physics-based calculation, you could possibly use the near clipping plane distance (third argument to gluPerspective, here it's 0.1 units).

I also would like to know what the angle between the image plane's center normal and a line drawn from the middle of one of the edges to the camera position is.

The angle between the top and bottom edges of the frustum is the "fovy" parameter you passed to Javadoc, so the angle between the top and the normal will be half that.
Since the image isn't square, the horizontal angle will be different from this; you could use some trigonometry to calculate it.
If your screen width and height in pixels is sw and sh, your near plane distance is npd, and your vertical FOV is fovy, then:

The height of the near plane in view is sh pixels, and npd*tan(fovy/2)*2 OpenGL units.
Each pixel must be npd*tan(fovy/2)*2/sh OpenGL units.
The width of the near plane in view is sw pixels, at the same scale, so npd*tan(fovy/2)*2*sw/sh OpenGL units.
The horizontal FOV is atan(width / npd / 2)*2 or atan(npd*tan(fovy/2)*2*sw/sh/npd/2)*2
Simplifying: atan(tan(fovy/2)*sw/sh)*2

That's assuming I didn't make any math mistakes there.
Like before, the angle between the normal and one of the edges will be half the FOV, so remove the *2 at the end to calculate that instead.

Also, when I set the camera coordinates, do I set the coordinates of the camera or do I set the coordinates of the image plane?

OpenGL has no concept of "camera coordinates". If you have a camera in your program, it's a completely made-up concept, and what you're actually doing is moving the entire world the opposite way.

To answer your question about moving the camera, this is what I do at the start of each frame of my program:
/**
 * Looks through the camera, effectively updating how we view the game.
 *
 * @param updateFrustum recalculates the frustum if true
 */
public void lookThrough(boolean updateFrustum) {
    glRotatef(rx, 1.0f, 0.0f, 0.0f);
    glRotatef(ry, 0.0f, 1.0f, 0.0f);
    glRotatef(rz, 0.0f, 0.0f, 1.0f);
    glTranslatef(position.x, position.y, position.z);
    if (updateFrustum) {
        frustum.calculateFrustum();
        }
    }
}

This is called after I handle the inputs from keyboard and mouse, which probably called the move() method (or pitch() or roll() or yaw(), which are equivalent):
/**
 * Moves the camera a specific amount in a specific direction.
 *
 * @param amount
 * @param dir
 */
public void move(float amount, Camera.Direction direction) {
    switch (direction) {
    case BACKWARDS_OR_FORWARDS:
        position.z += amount * Math.sin(Math.toRadians(ry + 90));
        position.x += amount * Math.cos(Math.toRadians(ry + 90));
        position.y += amount * Math.sin(Math.toRadians(rx));
        break;
    case SIDEWAYS:
        position.z += amount * Math.sin(Math.toRadians(ry));
        position.x += amount * Math.cos(Math.toRadians(ry));
        break;
    case UP_OR_DOWN:
        // TODO: implement
    default:
        break;
    }
}

I hope the code is self-sufficient to see what I mean but the most important of course are the glRotatef and glTranslatef commands, which moves the point and direction from where I draw my content each frame.
To answer your second question:
When you want to know where your mouse pointer crosses a plane (the terrain for example), you would need to create a line (or vector) from the position of the camera (you have the position and angle of the camera, so you can create a vector out of that) towards the terrain and calculate the point of intersection.

You've completely managed to misunderstand my second question about the movement of the camera. I am not interested in how to move it. I am interested in which part of it I am actually moving. Also, I have understood that I need to draw a vector from the position of the camera, but I don't know how to make it go through the point where the player clicks, nor do I know how to calculate what the vector intersects with. THAT is my actual question.

"I am interested in which part of it I am actually moving."
The "camera" does not really exist. It represents the point and angle from which you start to draw your scene. When the "camera" moves, you translate and rotate the point of reference from where you draw your 3D elements.

To elaborate: with enough OpenGL magic you can draw a 3D scene that has no relationship to the scene visible through the "camera" without needing a second "camera" including separating movement and input controls.  The camera component is just a helper around this complex OpenGL rendering path that aids the developer in designing the scene.  It's much much easier to Tween.add(...) on a gameobject with a camera than to directly manipulate GL.rotate(...) and GL.translate(...)


text:
Storing attributes in static geometry
I have a Minecraft like world where I statically create one instance of each tile type, and then place it around the world. However, I don't know how to actually change individual attributes for each tile. For instance, I need to change the lighting per tile, but if I do, it'll change the color of ever single tile. I was thinking about storing two arrays per chunk, one for the tiles and one for the light, and when I want to change the lighting, I can just change the value in the lighting array that coincides with the position in the tile array. However, this will mean I'll have to have store twice as much data per chunk, but is it something I have to accept?

Sorry 'bout the silly question, but what do you mean by tiles array? Is it a vertex buffer object? If so, does it store the actual vertices of each voxel of a chunk or you're generating the voxels geometry using geometry shader?

Are you only talking about the light level attribute here? Or do you need an approach that scales to other per-cube attributes as well?

You should check deferred shading system. It implies that you capture the original color of the tiles into a rendertarget and normals and depth of the tiles into other rendertargets (usually done in a single pass with multiple render target technique). You then apply lighting only to those pixels that you store in the rendertargets. So basically your tile data will be completely separated from your lighting and from how you store your tile date in memmory.
Here are some links for deferred shading:
http://en.wikipedia.org/wiki/Deferred_shading
http://ogldev.atspace.co.uk/www/tutorial35/tutorial35.html
You should also study general lighting theory for 3d graphics as it seems to me that you might not completely understand how it works:
http://en.wikipedia.org/wiki/Phong_shading
http://www.opengl.org/sdk/docs/tutorials/ClockworkCoders/lighting.php

Oh sorry, I don't think you understand what I meant. I'm not performing pixel based lighting on my cubes, I'm performing voxel based lighting. That means every voxel has it's own light level, and I color the tile accordingly. I don't need shaders for this besides the standard fragment shader. Also, please don't tell me I don't know what I'm doing, that's just rude. I know what I'm doing, I've been working with 3D for a year now.


text:
Is it possible to achieve a smooth sprite animation with a fixed 60 FPS using Java 2D?
I've seen a lot of different game loops, and before implementing anything complicated I decided to start with a capped 60 FPS. My run method looks like this in my game thread:
/**
 * Fixed Frames Per Second = 60
 */
public void run() {
    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            stage.render();
        }
    }, 0, 17);
}

The stage is a canvas, and the render method looks like this:
public void render() {

    BufferStrategy bufferedStrategy = this.getBufferStrategy();

    if (bufferedStrategy == null) {
        createBufferStrategy(3);
        return;
    }

    Graphics2D graphics2d = (Graphics2D) bufferedStrategy.getDrawGraphics();

    for (Actor actor : actors) {
        graphics2d.setColor(Color.WHITE);
        graphics2d.fillRect(0, 0, 600, 600);
        graphics2d.drawImage(actor.getDrawableImage(), actor.getX(), actor.getY(), 32, 32, this);
    }

    graphics2d.dispose();
    bufferedStrategy.show();
    Toolkit.getDefaultToolkit().sync();
}

The only "actor" sprite is 32x32, is currently moving 1 pixel at a time, and is too slow. So I bumped it to move anywhere from 2-4 pixels at a time across the stage, but now it is chunky. Is this related to my implementation or specific to Java 2D? The movement happens while the user presses one of the arrow keys.

How come you are drawing a white rectangle for each actor? And have you actually tried displaying the fps?

I don't currently have a tile system, so the sprite will ghost if I don't provide some background fill. Are you saying the FPS is not correct?

You need to provide a background, sure, but the code should be outside of the for (Actor actor : actors) loop. If you only have a single actor, it doesn't make a difference, except then you shouldn't have a loop there in the first place? And about the fps, you are capping it, but that's a maximum frame rate, not a minimum. So first things first, actually check the frame rate...

The above example is simply an initial test of the rendering, and is by no means code complete. Eventually the levels and tiles will all be drawn separately, and there will likely be several actors. However, I don't want to get too far into it if I can already pinpoint a problem early on with the rendering strategy. Also, I can check the FPS, but the only way it wouldn't be 60 is if the rendering for a single small sprite took longer than 17ms and the TimerTask run calls bunched up.

I think you should go back to moving 1px at a time, but update the x more often.  How is the x position (actor.getX()) updated?

@nycynik Currently I'm using a custom KeyEventDispatcher, and then with each event (user holding the down arrow) it dispatches and notifies the actors. I didn't think about that, but maybe it isn't dispatching fast enough?

I would try setting it with code, have it move w/o the key as a quick way to know if that is the bottleneck.

It might be related to the way you are setting the new position.  Check this answer for some code related to how to monitor key down events.
https://stackoverflow.com/questions/2702203/keyboard-input-for-a-game-in-java

I'm going to give this a go and report back. I think this will solve the problem. I noticed in the example link that the answer solution detects the keypress and then basically animates synced to a separate adjustable interval until a different keypress.

Good Luck!  Excited to know the outcome.

Hey that was it! It is definitely much smoother and that made a big difference.

Great to hear!! Gl with your game.


text:
Write my own level editor, questions
I just finished to code the most important parts of my game engine (not a tile-map one), such as lights, shadows, objects update/draw, input, ecc. Now I'm making a level editor to simplify the creation of levels. I have a form that does only simple things: place the player, place a block, choose a background, place an enemy... These two components are divided between them (sorry for my bad english).
My question relies on the relation between the form (level editor) and the game engine (the game itself)
These are my thoughts:

For a better explaination, take this example:

My game_engine project holds a Light class, a Player class, a Background class, an Enemy class. My engine (in abstract) is like this:

namespace game_engine
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        enum GameStates { TitleScreen, Playing, PlayerDead, GameOver };
        GameStates gameState = GameStates.Playing;

        Enemy zombie1;
        Enemy zombie2;
        Light sun;
        Light lamp1;
        Player player;
        Background mountains;
    }

     public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void Initialize()
    {
        this.graphics.PreferredBackBufferWidth = 800;
        this.graphics.PreferredBackBufferHeight = 600;
        this.graphics.ApplyChanges();

        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);

        Camera.ViewPortWidth = 800;
        Camera.ViewPortHeight = 600;
        Camera.Position = new Vector2(0, 0);

        mountains = new Background(...);
        zombie1 = new Enemy(...);
        zombie2 = new Enemy(...);
        sun = new Light(...);
        lamp1 = new Light(...);

        enemy_manager.Add(zombie1);
        enemy_manager.Add(zombie2);
        light_manager.Add(sun);
        light_manager.Add(lamp1);
    }

     protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            switch (gameState)
            {
                case GameStates.TitleScreen:
                    //Something
                    break;
                case GameStates.Playing:
                    enemy_manager.Update(gameTime);
                    light_manager.Update(gameTime);
                    mountains.Update(gameTime);
                    player.Update(gameTime);
                    break;
                case GameStates.PlayerDead:
                    //Something
                    break;
                case GameStates.GameOver:
                    //Something
                    break;
            }

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            switch (gameState)
            {
                case GameStates.TitleScreen:
                    //Something
                    break;
                case GameStates.Playing:
                    enemy_manager.Draw(spriteBatch);
                    light_manager.Draw(spriteBatch);
                    mountains.Draw(spriteBatch);
                    player.Draw(spriteBatch);
                    break;
                case GameStates.PlayerDead:
                    //Something
                    break;
                case GameStates.GameOver:
                    //Something
                    break;
            }

            base.Draw(gameTime);
        }

Then I have another project which is a form (Level editor) with some function/tool to help me out not putting manually every entity (enemy, light, ecc ...) when initializing the game:

At this point I have to "link" the form and my game engine. To make my tests I just did copy and paste game engine code into form project. But this is the wrong idea, because I want my code to be written once. Here there are my doubts: is it possible to create a link between them, considering that:

Inside the form there is a PictureBox where I want to render my game for full (With lights, shadows, etc)
I want to write once the game engine so that if I modify something for example inside "Enemy" class, when editing both Level editor and Game itself would run the new code

I miss that logical link between my two entities, I need some hint to go on, something to think about in order to clear things up. I put some code, please give me some code.

My question is really explicit: with the entities described above, I need just one logical idea to implement the connections between level editor and game engine, in order to use modularity. If this answer can't stay here, consider the possibility to move it to another section of this big forum.

The problem is that there are many valid ways to handle that kind of communication and your question doesn't offer enough details about what you have tried or more specific requirements that would allow that huge array of options to be narrowed down.

"Simple and clean" are subjective terms. Please describe what you want in technical and non-subjective language.

I would recommend you to take a look at the model-view-controller concept.
The model would be your map with all the objects on it.
The view would be your graphic engine which visualizes the current state of the model.
The controllers are the parts of the code which implement the game logic or the map editing capabilities.
When your application is in "play mode", the game mechanic controllers would be active. They would cause the objects in your game to behave according to the game rules and manage the user input as commands for the game objects they control.
When your application is in "edit mode", the game mechanic controllers would be inactive. The input controller for the edit mode would interprete the user input as commands to change the model directly.
Your visualization in edit-mode and play-mode will likely also have some difference. The play-mode view might show some HUD information about the game-state (like how much life the player has left), while the edit-mode view shows some help-lines, additional menus and so on and will likely also visualize certain objects which are invisible in play-mode. But the general rendering-engine would likely be the same. When you work object-oriented I would write an abstract base-class GraphicEngine which implements the general rendering engine with two extending classes GameGraphicEngine and EditorGraphicEngine which implement the game-specific or editor-specific graphic engine features.
When you do this well, you might be able to implement seamless switching between play-mode and edit-mode at any time. This would provide you with a very powerful test-tool.


text:
up vector for quaternion
First, I know there's a question exactly like mine, and some ohter really close, but my implementation of the solutions didn't work at all. Ok, now to the question.
I created some forms of camera based on quaternions, however, for my orbit/chase camera every quaternion I create will roll the camera in an uncontrollable manner. What I want is a function like Unity's Quaternion.LookRotation where you can pass an up vector.
This is a simplification current attempt of implementation:
Vector3 target = -Position; //Because we're looking at the origin
target.Normalize();

float cosine = Vector3.Dot(Vector3.Forward, target);
Vector3 axis = Vector3.Cross(Vector3.Forward, target);
Rotation = Quaternion.CreateFromAxisAngle(axis, (float)Math.Acos(cosine));

//Trying to unroll up vector to Vector3.Up
//based on the other answer but results were unchanged
Vector3 rolledUp = Vector3.Transform(Vector3.Up, Rotation);
Vector3 right = Vector3.Cross(target, Vector3.Up);
Vector3 newUp = Vector3.Cross(right, target);

Vector3 axis2 = Vector3.Cross(rolledUp, newUp);
float angle2 = (float) Math.Acos(Vector3.Dot(rolledUp,newUp));

Rotation = Quaternion.CreateFromAxisAngle(axis2, angle2) * Rotation;

return Matrix.CreateLookAt(
    cameraPosition: Position,
    cameraTarget: Vector3.Transform(Vector3.Forward, Rotation),
    cameraUpVector: Vector3.Transform(Vector3.Up, Rotation));

If my sleepiness got in the way of my clarity, here's what I have:

and here's what I want:

you should only need to rotate around the y axis or you can just say to look at the point on the y-axis at the same height of the camera
target.y=0;
target.normalize();

of course then you can start to optimize because axis is (0,1,0) and all the other ups will be the same again (do double check that though)


text:
AABB collision detection not detecting in some cases
I'm using simple AABBs in a tile based world, and for some reason the algorithm does not detect collisions when moving towards the left and then down. I actually upload a video to YouTube to demonstrate the problem because I can't figure out a good way to explain my problem. Here it is:
AABB collision detection problem
As you can see, the little wireframe tile that moves around is the player, and when I move to the left, and then try to move down on the tiles, the player just slips right through. Detection works when moving to the right. Here's my algorithm to detect collisions:
public static boolean isColliding(AABB a, AABB b) {
    if (Math.abs(a.pos.getX() - b.pos.getX()) < a.size + b.size) {
        if (Math.abs(a.pos.getY() - b.pos.getY()) < a.size + b.size) {
            return true;
        }
    }
    return false;
}

The pos variable in the AABB class is the center of the AABB in question, and the size is half the size. Here's how I move the player:
if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
        move(0, 1, 0, MOVESPEED);
    }
    if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
        move(1, 0, MOVESPEED, 0);
    }
    if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
        move(-1, 0, -MOVESPEED, 0);
    }
    if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
        move(0, -1, 0, -MOVESPEED);
    }
    if (Keyboard.isKeyDown(Keyboard.KEY_SPACE) && onGround) {
        onGround = false;
    }

Which references this method:
private void move(float x, float y, float sx, float sy) {
    if (getX() / 32 + x >= 0 && getX() / 32 + x <= world.mx && getY() / 32 + y >= 0 && getY() / 32 + y <= world.my) {
        if (world.tiles[(int) ((int) getX() / 32 + x)][(int) ((int) getY() / 32 + y)] != null) {

            Tile t = world.tiles[(int) ((int) getX() / 32 + x)][(int) ((int) getY() / 32 + y)];
            Vector2f tempPos = new Vector2f((pos.getX() + (pos.getX() + 32)) / 2, (pos.getY() + (pos.getY() + 32)) / 2);
            box.update(new Vector2f(tempPos.getX() + sx, tempPos.getY() + sy), 16);
            t.color = true;

            if (!Collision.isColliding(box, t.getBox())) {
                setPos(getX() + sx, getY() + sy);
            }
        } else {
            setPos(getX() + sx, getY() + sy);
        }
    } else {
        setPos(getX() + sx, getY() + sy);
    }
    glPushMatrix();
    glTranslatef(getX(), getY(), 0);
    glPopMatrix();
}

32 is the tile size and the player size, just for reference. The 'tempPos' vector is just a vector that holds the center of the player's position. AABB is a class that stores a vector and a size variable, and the update method just updates those variables.
I guess my question is either, why is it only working on one axis, or how can I change my move method to be "better"? I've been trying to figure out why this isn't working, and I just can't come up with any ideas because it happens constantly, so it's not that my entities are moving too fast and the algorithm isn't detecting the collisions.

Looks like you are only checking collision with tiles that are to the left of your player. In your move function, you are truncating with your divisions which may be causing this issue.

So should I check if I'm moving to the left and then instead multiply to find my position?

But wait, no that makes no sense because I'm dividing to find my world coordinates. How does that make any sense?

Let's say you are at the position (336, 330), and you are moving the block downwards. According to this line in your code:
if (world.tiles[(int) ((int) getX() / 32 + x)][(int) ((int) getY() / 32 + y)] != null) {

You're going to be checking the point tile (10, 9), which is fine. But your tile is positioned half way between two tiles. That means you should also be checking the tile (11, 9) for a collision. Casting to an (int) rounds down. But you should also have a conditional where you are rounding up.

So if I understand correctly I should be checking for two tiles in every direction I move instead of one and see if I collide with either? For instance, when moving down I should check the two potential tiles under the player? Is this his its normally done? I was always told only to check the tiles directly touching the player.

Very basic collision detection would mean checking all the tiles the player is intersecting with, which would be four tiles in your case (each corner of the player will be in a different tile, except when aligned with the grid). But since you know the direction the player is moving in, you only need to check the tiles in that direction, meaning, yes, two tiles. Personally I'd just check all four tiles each time, regardless of movement direction, to keep things simple.

Ah, I see. I don't know why I didn't think of that. So, just to clarify I should check the eight tiles around the player (since the player is the size of tile), or should I just check the four tiles around the player? I think I should check all eight because like you said, I was stuck in between two tiles.

Four tiles is enough. If the player is aligned to the grid, such as at the position (32, 32), it won't (at that moment) be colliding with any tiles. If, on the other hand, it's at (16, 16), it'll be half way between tiles on the x and y axis. And as such, you'd need to check for collisions at the tiles: (0, 0), (0, 1), (1, 1), and (1, 0). 4 tiles in all. Think about it this way: how many tiles can the player occupy at once?

Right, but with my rounding will it not just do the same thing as it is now? Where it rounds off and picks the incorrect tile? That's why I think I need eight to account for when the player is in between tiles.

Rounding down means you are testing for one of the tiles. Going back to my original example, rounding down checks the tile (10, 9), which it should do, but not (11, 9), which it should also check. There's no reason to be checking eight tiles, since your player cannot be in 8 tiles simultaneously (not unless you make the player bigger).

I'm really confused, I can't seem to get it working no matter what I do. When I try to collide with multiple tiles, I actually get lots of bugs. Can you point me to a link or show me how to implement what I'm trying to do?

let us continue this discussion in chat


text:
Ray picking and bounding boxes in Java
How do I check which bounding boxes (of different types) a ray, sent from the camera through the mouse-click coordinates, intersects with first in Java (and where)? I have arrays (box_X, box_Y, box_Z, box_X2, box_Y2, box_Z2) that store the coordinates and size of each box.
I don't understand very complex math (matrices, definitely nope). I am doing this from scratch so that I can better understand it and because there is a certain priority I want to use when picking objects (UI > Entities > Items > Objects > Terrain).
Thank you for your help!
Edit #1:
So, I finished the code. Pasted it below so you guys can point out obvious errors in it for me. Or possibly, ways to do this easier. I have a feeling that there's something I'm missing, so...
private static int[] getIntersect(Vector3f ray) {
    int coords[] = new int[4];
    boolean planes[] = new boolean[6];
    Vector3f norm = null;

    Vector3f origin = new Vector3f(Disp.camX, Disp.camY, Disp.camZ);

    // Check which direction the ray is going.
    for (int plane = 0; plane < 6; plane++) {
        if (plane == posxy) {
            norm = new Vector3f(0f, 0f, -1f);
        } else if (plane == posxz) {
            norm = new Vector3f(0f, -1f, 0f);
        } else if (plane == posyz) {
            norm = new Vector3f(-1f, 0f, 0f);
        } else if (plane == negxy) {
            norm = new Vector3f(0f, 0f, 1f);
        } else if (plane == negxz) {
            norm = new Vector3f(0f, 1f, 0f);
        } else if (plane == negyz) {
            norm = new Vector3f(1f, 0f, 0f);
        }

        if (Vector3f.dot(ray, norm) < 0) {
            planes[plane] = true;
        }
    }

    norm = null;
    boolean solved;

    // Calculate intersections

    // First, choose the type of object to find collisions with.
    for (int type = 0; type < 5; type++) {
        solved = false;
        // Next, loop through layers.
        for (int dist = 0; dist < 70; dist++) {
            int pos[] = new int[3];
            float t = 0f;

            // Check for intersections on the planes
            for (int plane = 0; plane < 6; dist++) {

                // Skips calculation if the plane is not in the right direction.
                if (planes[plane] == true) {
                    int axis = 0;

                    // Set the normal to be correct.
                    if (plane == posxy ) {
                        norm = new Vector3f(0f, 0f, -1f);
                        axis = 2;
                    } else if (plane == posxz) {
                        norm = new Vector3f(0f, -1f, 0f);
                        axis = 1;
                    } else if (plane == posyz) {
                        norm = new Vector3f(-1f, 0f, 0f);
                        axis = 0;
                    } else if (plane == negxy) {
                        norm = new Vector3f(0f, 0f, 1f);
                        axis = 2;
                    } else if (plane == negxz) {
                        norm = new Vector3f(0f, 1f, 0f);
                        axis = 1;
                    } else if (plane == negyz) {
                        norm = new Vector3f(1f, 0f, 0f);
                        axis = 0;
                    }

                    // Calculate the point of intersection
                    t = ( dist - Vector3f.dot(origin, norm) ) / Vector3f.dot(ray, norm);
                    ray.setX(t * ray.getX());
                    ray.setY(t * ray.getY());
                    ray.setZ(t * ray.getZ());
                    pos[0] = (int) ray.getX();
                    pos[1] = (int) ray.getY();
                    pos[2] = (int) ray.getZ();

                    // Check if there is a collidable item of the type in the coordinates. If is, save the type and coordinates, then break out of the loop.
                    if (isCollidable(pos, type)) {
                        coords[0] = pos[0];
                        coords[1] = pos[1];
                        coords[2] = pos[2];
                        coords[3] = type;
                        solved = true;

                        break;
                    }
                }
            }

            if (solved) {
                break;
            }

        }
        if (solved) {
            break;
        }
    }

    return coords;
}

Edit #2: I actually found something myself. That t needs to be converted to coordinates via p(t)... And it's corrected.

We'll, to do that your going to need a basic understanding of Vectors. I'm not going to be able to provide a decent explanation of those, but there should be sources online for you so I'll leave you to your own devices there.
But first, in the fallowing equations:

Bold face text represents vectors (x, y, z, w)
non-bold face text represents scalars

So, on to the math, first we need to cover the intersection of a plane:
Consider a ray defined as: p(t) = p.origin + t d
where p(t) is a new point given the parametric distance t, p.origin is where the ray starts, d is the vector representing the ray's direction, and t is a parametric distance along the ray.
Now consider a plane defined as: p . n = d
Where p is a point on the plane, n is the planes normal, d is the offset from the origin (much like the c in y = mx + c), and the '.' is a dot product.
Note: The p in the equation of the plane is not the same as the rays p, but they can be substituted.
So, we're looking for the point on the ray is a point on the plane. if an arbitrary point on the ray is p(t), and the p is an arbitrary point on a plane, then we are looking for:
p(t) . n = d
p(t) could be found if we knew what t was. so if we substitute the p(t) for "p.origin + t d", you get:
(p.origin + t d) . n = d
Which becomes:
t = ( d - (p.origin . n) ) / ( d . n )
If there is no intersection, then "d . n" will result in 0. So that's where you check if you want to see if they actually intersect.
so then your intersection point is, p(t), that's it. You can find t with the above equation. And that's how you find the intersecting point of a plane.
So, now we move to box. It's really just 6 different planes, right? Each planes normal goes along one of the axis (x+, y+, z+, x-, y-, z-), and you can find a corner point for each side, so you have the planes all-ready. That mean's, you can test each plane, and wherever t is the smallest is the closest intersection.
Once you have where the ray intersects with the AABB, you can test to see if that "intersection" point on the plane is actually inside or on the AABB. ( eg. p(t).x <= AABB.max.x and p(t).x >= AABB.min.x ) If that checks out for the X, Y, and Z, axis on any given plane, you have an intersection.
So, that's how you find if an cube intersects a ray, and where it intersects. To see if one AABB intersection is closer than another, you can compare 't' in each intersection. The closer t is to zero, the closer the AABB.

This is what I was looking for, thank you. Now I just have to review it again when I'm fully awake. But, for a cube intersection, don't I only need to check the three camera-facing sides of each cube?

If your ray-casting from the camera, then yes. I think d . n would be a good indicator for that. The sides of the cube that are facing the camera should have a normal that goes in the opposite direction of the ray, which will give you a negative result when checking d . n

Question: is the d in p . n = d the shortest distance from the plane to the origin? That is, in this case, the offset along the axis.

Yes. It could also be described as the distance along n to the plane.

I'm trying to find a way to: Given a picture from a camera, translate the X,Y pixel to real world coordinates. Can someone point a direction to me?