texts:
Hello I am trying to handle some simple box collision (axis-aligned) in my top-down 2d game, but running into a problem.

My game is running at a fixed time step, and checks for player-wall collision on each iteration. It retrieves some collision data (if it collided & what side of the bounding box) and adds some offset (dir) to the players position depending on the overlap amount.

// Check player with walls
        CollisionData col = testBoxCollision(m_player->getCollider(), wall.getCollider());
        if (col.isCollided){
            Vec2f dir(0.0f, 0.0f);
            if (col.left)
                dir.x -= (m_player->getCollider().getPosition().x + m_player->getCollider().getHalfSize().x) - (wall.getPosition().x - wall.getHalfSize().x);
            else if (col.right)
                dir.x += (wall.getPosition().x + wall.getHalfSize().x) - (m_player->getCollider().getPosition().x - m_player->getCollider().getHalfSize().x);
            if (col.top)
                dir.y -= (m_player->getCollider().getPosition().y + m_player->getCollider().getHalfSize().y) - (wall.getPosition().y - wall.getHalfSize().y);
            else if (col.bottom)
                dir.y += (wall.getPosition().y + wall.getHalfSize().y) - (m_player->getCollider().getPosition().y - m_player->getCollider().getHalfSize().y);

            m_player->GameObject::setPosition(m_player->GameObject::getPosition() + dir);
        }

The testBoxCollision function:

CollisionData testBoxCollision(const Collider& a, const Collider& b)

{
    CollisionData c{ false, false, false, false, false };

float w  = a.getHalfSize().x + b.getHalfSize().x;
float h  = a.getHalfSize().y + b.getHalfSize().y;
float dx = a.getPosition().x - b.getPosition().x;
float dy = a.getPosition().y - b.getPosition().y;

if (abs(dx) <= w && abs(dy) <= h)
{
    c.isCollided = true;

    float wy = w * dy;
    float hx = h * dx;

    if (wy > hx)
    {
        if (wy > -hx)
            c.bottom = true;
        else
            c.left = true;
    }
    else
    {
        if (wy > -hx)
            c.right = true;
        else
            c.top = true;
    }
}
return c;

}

The Problem

When two walls produce a corner, and I push my player up to the corner, the player goes through the wall. Not Ideal!

Clearly I've overlooked something and another set of eyes would be very helpful. Thanks.

Below is a snapshot of what's happening.

EDIT: I'm led to believe this is a math error, because it only happens on some corners at a consistent frame rate.


texts: I am a novice programmer and just learned about the concept of saving and loading games. The way I am doing it is to write data into a text file and read it afterward. However, I realize how insecure this method is. What is going to stop someone to just open the text file and edit it? Furthermore, after going through game folders of popular games, I do not seem to find any text file dedicated to saving data at all. So there must be more advanced saving methods than simply writing and reading from a text file. What are they then and how can I do something similar to that? (I mainly use Java and C++)


texts:
I'm working on a game side-project that will be heavily audio-based. One feature I'd like to offer are ambient sound zones which correspond to locations of nearby areas.

Say for instance the player is standing on a beach with waves breaking to the right, and a rainforest to the left. Each of these regions has its distinct ambience. If you continue forward, the breaking waves should still be just as loud on your right. Similarly, if you head into the forest, the sound of the waves should slowly be replaced as you move away from the beach. Many games seem to treat ambient sound as either vaguely positional, or as an environmental sound that comes from everywhere at once. What I'm trying for are different areas with different distinct sounds so you can actually orient yourself to them (I.e. you should be able to return to the beach by listening for the breaking waves, they shouldn't just be omnidirectional and faint.)

I don't want to get too deep into architecture, but my system is simple 2-D tile-based. I've thought of several possible approaches and am wondering a) which is best or b) if I've missed one that is better.

Place distinct, loud ambient sounds in specific locations. This would certainly provide directionality of a sort, but I wonder if the ocean waves might eventually sound ahead or behind and right as you walk down the beach, since all the ambience is coming from a single point. This also wouldn't allow for, say, walking out in the ocean past the breakers and hearing them behind you.
Placing sound sources throughout the area, spaced a reasonable distance apart. So for instance the breakers might be a single row of wave sounds which you could walk along or past. Similarly, the forest would be a grid of scattered nature sounds. This seems like the best approach, but I wonder if I'd quickly hit some limit for number of sounds that can be mixed. I'm using the web audio API, not sure if that intelligently doesn't render sounds that are too soft to hear. While this seems conceptually simpler, a long beach might have hundreds of distinct sound nodes placed along it.
Track the player's nearest intersection with a given zone, and play its ambience at those coordinates. So if you're walking along a beach with breaking waves to your right, I'd project out an invisible circle for as far as you can realistically hear, identify the closest intersection with various audio zones, and play their respective ambience. Maybe limit this to the nearest 2-3, since any more would likely be overwhelming. This seems least demanding in that it'd play fewer sounds, but would likely require more collision checks and thus might be impractical.

Thoughts?


texts: How do i set gravity towards a point in the centre in AndEngine with Box2D?

texts:
I have a scene and i can set gravity in the PhysicsWorld like

this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, -SensorManager.GRAVITY_EARTH),false);

but i would like all bodies to gravitate to a point.

I tried

physicsWorld.setGravity(new Vector2(centerX, centerY));

but that has not worked- i assume because i need to calculate the vector to the centre. But I'm not sure how to do that and where to calculate it so it changes.

I would like the input (of force) to be from the touch handler of the sprite. The sprite at the moment can be moved via

@Override
    public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
            float pTouchAreaLocalX, float pTouchAreaLocalY) {

        //this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);

        if (pSceneTouchEvent.isActionMove() || pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionOutside())
        {
            this.setX(pSceneTouchEvent.getX() - this.getWidth() / 4);
            this.setY(pSceneTouchEvent.getY() - this.getHeight() / 4);
        }

        return true;
    }

I would like to do the calculation in there so as the sprite is dragged, the vector changes, then when it's released it should 'fall' to the centre

EDIT:

Mass can be set as 1 unit since it's not relevant

Thanks for the help.


texts: Bounding box not right rotation XNA blender object (.fbx)

texts:
I am importing .fbx models (a simple cuboid), the model itself displays fine (and is repeated to make a wall) however the bounding box seems to be on the wrong rotation. Below is a screen shoot:

The yellow line is the bounding box for the grey cuboids.

The map walls are loaded from a map object that specifies where walls should be

for (int row = 0; row < map.Rows; row++){
                for (int col = 0; col < map.Columns; col++){
                    if (map.Get(row, col) == 'w') walls.Add(new Wall(content.Load<Model>("models/wallnew"), new Vector3(col, 0, row)));
                }
            }

and a wall is:

public class Wall : Entity {
        BoundingBox boundingBox;

        public Wall(Model model, Vector3 position) : base(model){
            this.translation = Matrix.CreateTranslation(position);
            Vector3 from = Vector3.Transform(new Vector3(0f), World);
            Vector3 to = Vector3.Transform(new Vector3(1f), World);
            boundingBox = new BoundingBox(from, to);
        }

        public BoundingBox GetBoundingBox() {
            return boundingBox;
        }

        public override void Draw(bool textured, Matrix view, Matrix proj) {
            foreach (ModelMesh mesh in model.Meshes) {
                foreach (BasicEffect effect in mesh.Effects) {
                    effect.World = World * mesh.ParentBone.Transform;
                    effect.View = view;
                    effect.Projection = proj;
                    effect.EnableDefaultLighting();
                }
                mesh.Draw();
            }
        }
    }

I cant for the life of me work out why the bounding box is being added wrong, if you need any more info let me know!


texts: Problems with gravity and box colliders in Unity 3D

texts:
I have a game character that can jump or roll in order to avoid obstacles. He is able to roll while on the ground and he can also roll while he is in the air after jumping. Everything was working fine when I made him roll. I want to make it so that when he rolls while he's in the air after jumping, he would fall at a faster pace than if he was just falling normally. So I did this in my c# script:
IEnumerator IncGravAcc()
{
    Physics.gravity = new Vector3(0, -50f, 0);
    yield return new WaitForSeconds(2f);
    Physics.gravity = new Vector3(0, -9.8f, 0);
}

I call this coroutine in the function that runs when the down arrow is clicked. Everything is working fine. When he rolls while in the air, he falls at a faster than normal rate. However he doesn't land properly and he just falls right through the platform like it's not even there. Here's a video to show what I mean:
https://youtu.be/sirc4L3MnqM
I have a box collider, not set to isTrigger, on the player (you can see it, the green box, right underneath him in the video) and the player's also a rigidbody. The platforms don't have rigidbodies on them but they do have box colliders set to trigger. You can see the platform's box collider in the relation to player's box collider in the picture provided (the platform's box collider is the larger one of course)
How do I get it so that the character doesn't fall through? Please let me know if there's anything else you need to know about the project. Thank you for helping me!


texts: VAO and VBO connection and granularity with multiple objects

texts:
How general should vertex array objects be?

I'd like to plan ahead and avoid a major revision down the road. I'm having a hard time wrapping my head around a few (possibly conflicting) pieces of wisdom scattered around the internet.

This answer on VAO best practices: for each batch: generate VAOs and bind buffers
Another describes one should share VAOs with multiple objects
Khronos OpenGL Vertex specification just providing general useful information

This is what I could gather from a half a year of slowly reading specs and docs, building and abstracting away a somewhat structured piece of a game engine.

The more state changes the slower the execution (self evident)
VAO holds state for draw calls (for a simple bind -> draw)
VBOs are bound to a VAO using the attribute location from a shader program (glGetAttribLocation -> glVertexAttribPointer)
These arrays are enabled by location using glEnableVertexAttribArray

So for a single VAO, how many or what kinds of objects should it take care of? Should a single VBO contain many objects' e.g. normals and the program use offsets when drawing, or is having separate VBOs for each a viable option?

Also, since we enable the attribute array by location inside the shader program, are the VAO and the shader in some way connected?

Any pointers would be greatly appreciated!


texts: How to switch career to game engine/graphics programming

texts:
My whole background is related to enterprise applications but I've been thinking of switching my career path from enterprise/business to something that I feel is more challenging and interesting. One of the main fields I've checked is game programming and more specifically engine or graphics programming. One of the requirements I've set is that the new domain requires at least some math/computer science knowledge and have interesting problems to research and solve (hopefully even read some white papers). Graphics programming especially seems to have lot's of that in addition to being interesting in general. I've already started studying the related mathematical background via this book and I believe my general experience in developing and releasing quality software (5+ years) will quickly translate, with the right mentorship, putting me at a level of usefulness of a mid-level game programmer at least.
How should I go about proving this to potential employers? I don't feel like creating small sample games really amounts to anything. Familiarizing myself with an engine like Unity or Unreal seems like a good approach but I'm not sure how to go about it in an engine focused way. I'd potentially like to avoid Gameplay development which is why creating games seems redundant.
I don't want to enter subfields such as server programming or any field that is web-appy but under the umbrella of a game company. I'm also looking to transition relatively quickly which is why I don't want to invest in a game company as a web app developer only to hope to be put into game domain later.
TL;DR: I'm looking for ways to enter the "sciency" side of game programming (graphics/engine programming) with a background in enterprise web apps.


texts: How can I automatically fit elements in libGDX layouts?

texts:
Recently I wanted to use libGDX's Table to show four buttons. But my table doesn't fit on the stage:

Here is the code I used:

table.add(new GameButton("1"));
table.add(new GameButton("2"));
table.add(new GameButton("3"));
table.add(new GameButton("4"));
table.align(Align.bottom);
table.setFillParent(true);
stage.addActor(table);

(GameButton is a TextButton subclass with a special TextButtonStyle.)

When I change table.add(new GameButton("1")); to table.add(new GameButton("1")).width(Gdx.graphics.getWidth() / 4);

I get this result:

Does Table (or another libGDX layout class) have functionality to auto-fit elements like in the second picture? Or I should always add some width/height options after adding element?


texts: Engine and level of detail for maze / labyrinth / dungeon scene?

texts:
My question is similar to these:

Algorithm for generating a 2d maze
To scene graph or not to scene graph?

I.e. in this case should I use jME3 or some other engine (I heard Unreal offers a free engine) for a 3D dungeon game and when I build up the dungeon, should I use an algorithm for a new dungeon every time or should I use a static scene?

I've code to build a small wall that adds it to my scene which is mostly programmaticly achieved with less 3D modelling and more algorithmic solutions:

  /** This loop builds a wall out of individual bricks. */
  public void initWall() {
    float startpt = brickLength / 4;
    float height = 0;
    for (int j = 0; j < 15; j++) {
      for (int i = 0; i < 6; i++) {
        Vector3f vt =
         new Vector3f(i * brickLength * 2 + startpt, brickHeight + height, 10);
        makeBrick(vt);
      }
      startpt = -startpt;
      height += 2 * brickHeight;
    }
  }

  /** This method creates one individual physical brick. */
  public void makeBrick(Vector3f loc) {
    /** Create a brick geometry and attach to scene graph. */
    Geometry brick_geo = new Geometry("brick", box);
    brick_geo.setMaterial(wall_mat);
    rootNode.attachChild(brick_geo);
    /** Position the brick geometry  */
    brick_geo.setLocalTranslation(loc);
    /** Make brick physical with a mass > 0.0f. */
    brick_phy = new RigidBodyControl(2f);
    /** Add physical brick to physics space. */
    brick_geo.addControl(brick_phy);
    bulletAppState.getPhysicsSpace().add(brick_phy);
  }


texts: I'm sure many of you have heard the term host advantage through out your time playing action video games.  However, I was curious if this was a real studied and proven concept in game design, computer science, and network programming?  I tried looking it up on Google, but all I saw was just some gamers ranting back and forth on a forum (none of them even seem to bring up client-server concepts in their babbling...).


texts: Dynamic Hills like Contre Jour in Cocos2d

texts:
I'm interested in maps/environments which are flexible and change at runtime, such as those in Contre Jour.

I have looked for a long time to find out how to make this effect, but I couldn't find an answer. The closest I found was maybe something like this using springs to deform meshes.

Are there better methods for implementing this feature?


texts:
For reasons detailed
here
I need to texture a quad using a bitmap (as in, 1 bit per pixel, not an 8-bit pixmap).

Right now I have a bitmap stored in an on-device buffer, and am mounting it like so:

glBindBuffer(GL_PIXEL_UNPACK_BUFFER, BFR.G[(T+1)%2]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, W, H, 0, GL_COLOR_INDEX, GL_BITMAP, 0);

The OpenGL spec has this to say about glTexImage2D:
"If type is GL_BITMAP, the data is considered as a string of unsigned bytes (and format must be GL_COLOR_INDEX). Each data byte is treated as eight 1-bit elements..."

Judging by the spec, each bit in my buffer should correspond to a single pixel. However, the following experiments show that, for whatever reason, it doesn't work as advertised:

1) When I build my texture, I write to the buffer in 32-bit chunks. From the wording of the spec, it is reasonable to assume that writing 0x00000001 for each value would result in a texture with 1-px-wide vertical bars with 31-wide spaces between them. However, it appears blank.

2) Next, I write with 0x000000FF. By my apparently flawed understanding of the bitmap mode, I would expect that this should produce 8-wide bars with 24-wide spaces between them. Instead, it produces a white 1-px-wide bar.

3) 0x55555555 = 1010101010101010101010101010101, therefore writing this value ought to create 1-wide vertical stripes with 1 pixel spacing. However, it creates a solid gray color.

4) Using my original 8-bit pixmap in GL_BITMAP mode produces the correct animation.

I have reached the conclusion that, even in GL_BITMAP mode, the texturer is still interpreting 8-bits as 1 element, despite what the spec seems to suggest. The fact that I can generate a gray color (while I was expecting that I was working in two-tone), as well as the fact that my original 8-bit pixmap generates the correct picture, support this conclusion.

Questions:

1) Am I missing some kind of prerequisite call (perhaps for setting a stride length or pack alignment or something) that will signal to the texturer to treat each byte as 8-elements, as it suggests in the spec?

2) Or does it simply not work  because modern hardware does not support it? (I have read that GL_BITMAP mode was deprecated in 3.3, I am however forcing a 3.0 context.)

3) Am I better off unpacking the bitmap into a pixmap using a shader? This is a far more roundabout solution than I was hoping for but I suppose there is no such thing as a free lunch.


texts: How could I implement a movement system like Intrusion 2 has?

texts:
Here is a trailer of the game Intrusion 2. The characters seem to move with physics, but look animated as well.

I'd like to know how such a movement system works and how I could go about implementing something similar.


texts:
I'm trying to learn OpenGL ES 2.0 and I'm wondering what is the most common practice to "manage" shaders.
I'm asking this question because in the examples I've found (like the one included in the API Demo provided with the android sdk), I usually see everything inside the GLRenderer class and I'd rather separate things so I can have, for example, a GLImage object that I can reuse whenever I want to draw a textured quad (I'm focusing on 2D only at the moment), just like I had in my OpenGL ES 1.0 code.
In almost every example I've found, shaders are just defined as class attributes. For example:

public class Square {

public final String vertexShader =
        "uniform mat4 uMVPMatrix;\n" +
        "attribute vec4 aPosition;\n" +
        "attribute vec4 aColor;\n" +
        "varying vec4 vColor;\n" +
        "void main() {\n" +
        "  gl_Position = uMVPMatrix * aPosition;\n" +
        "  vColor = aColor;\n" +
        "}\n";

public final String fragmentShader =
        "precision mediump float;\n" +
        "varying vec4 vColor;\n" +
        "void main() {\n" +
        "  gl_FragColor = vColor;\n" +
        "}\n";
// ...
}

I apologize in advance if some of these questions are dumb, but I've never worked with shaders before.

1) Is the above code the common way to define shaders (public final class properties)?
2) Should I have a separate Shader class?
3) If shaders are defined outside the class that uses them, how would I know the names of their attributes (e.g. "aColor" in the following piece of code) so I can bind them?

colorHandle = GLES20.glGetAttribLocation(program, "aColor");


texts: What is the relationship between clipping and the fog of war concept?

texts:
I'm currently developing a 2D top down game and recently implemented clipping.

I understand clipping in a 2D top down game as rectangle or any other geometrical form which defines a viewport for the player of what exactly he sees and what is technically rendered from the engine. As I'm centering the clipping area around the player I recognized that it is similiar to the fog of war concept.
So the player has a limited view perspective depending on his current position.

My questen is what is the concrete difference to the fog of war concept? Is this concept usually using clipping? I often recognized that for example the map is rendered but simply not the objects which are on that map. Are these objects rendered and simply invisible or are they not rendered at all because of the clipping? Could clipping be defined as a way to achieve fog of war?

Would be cool if anyone could shed some light on this topic.


texts: Show 3d object on device live camera in Unity3d for iOS

texts:
Possible Duplicate:
  How to add render able Texture in Unity 3d for iOS

How render a 3d or 2d(.jpg or .png )object at device live camera in Unity3d, and this 3d object shouldn't stuck with camera. It has to show at specific point, like we can set any object in game scene at particular location.


texts:
I am currently trying to develop a small physics engine for my games. I have created bounding volumes for different rigid bodies. However, I am having problems handling collision resolution, more specifically with determining the direction to apply the impulse to the objects and their changes in velocities.

How do I perform collision resolution for rigid bodies of varying volume? Is there a general solution for resolving collision between all rigid bodies like sphere, AABB or OBB, or do I have to specifically arrive at a solution for each scenario?


texts:
Edit: the images below aren't supposed to have whitespace. I am just trying to show you that i am trying to create a rectangle from a 1x64 image, positioned as shown in the second picture

I know how to rotate an image like that in XNA

But how is it possible to draw a sprite in this angle this way ?

I can't seem to be able to find an answer on that and i'm sort on ideas


texts: Is there a testing framework for bounding volume classes?

texts: This may be a long shot, but is there a small framework out there anywhere for testing custom bounding classes and other collision objects? (for example between rays, spheres and AABB's)


texts: Cocos2d background sound not playing a second time C++

texts:
I'm using cocos2d-x on windows10 UWP project. I use the SimpleAudioEngine to load the music:

CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic("level_music1.wav",true);

On the close button handler I use the end method:
CocosDenshion::SimpleAudioEngine::getInstance()->end;

When I run the debugger a second time I get these exceptions:

  Exception thrown at 0x765F3E28 (KernelBase.dll) in MiniGolf.exe: 0x000006BA: The RPC server is unavailable.
  Exception thrown at 0x765F3E28 (KernelBase.dll) in MiniGolf.exe: 0x0000000E: Not enough storage is available to complete this operation.
  Assert failed: getFileSize should be override by platform FileUtils
  Assertion failed!

only if I rename the file to say like "level_music.wav" it works again but failed again the second time so I have to constantly rename it to work.


texts: LibGDX Compare color of Box2D objects on collision

texts:
I have two red balls and two yellow balls, which were created from a class Ball.
The balls are box2d circles, with sprites attached.

Is there a way in which I can check to see if two balls have collided, and if they are the same colour, remove them?

I can access information about the bodies, but am not sure how to test whether they are the same colour.

I have the following code, but am not sure how to continue

@Override
        public void beginContact(Contact contact) {
            Fixture fixtureA = contact.getFixtureA();
            Fixture fixtureB = contact.getFixtureB();

Any ideas on what techniques I can use?

Regards

James


texts: I've seen people who've written in code where the graphics of a scene are rendered in response to WM_PAINT. I only ever rendered the scene once all Windows messages were done translating, and then rendered the scene. Is this the wrong way to go about it, or should I only use DirectX rendering in response to WM_PAINT?


texts: Let both clients know of complete game-state in turn-based game?

texts:
I'm writing a simple turn-based game for mobile, just to test the waters and I'm having doubts about the approach.

Each player has 5 cards on hand.

I want for both players to be able to replay exactly what the other player did. Would it be okay (from a security perspective (and in what degree?)) for both clients to know in-memory what the other player has on hand?

Example:
Game Start > Server sends encrypted data* to both clients > Clients decrypts data in memory

Server sends user action > Client replay action

*where data is Client1's cards and Client2's cards.

The reason for not having the server sending "need to know" stuff, is for code-simplicity and responsiveness.


texts: Solving a recursive problem in the geometry (or any other) shader

texts:
I would like to calculate an effect of an external force on a binary tree (wind on a tree).

It's a recursive function - take a (parent) node and calculate the angle to rotate all of the nodes "younger" than the parent around the parent for the same angle according to the force applied. Then do it for the child nodes and repeat until you reach the leaves. If I'm calculating it right this is a problem of O(k * 2^n) complexity, where n is the depth of the tree and k number of nodes.

Since we rotate a lot of stuff (which is a nice matrix multiplication), it would be really nice to do it on the GPU. The problem is that this code needs to run as many times as the depth of the tree, and not all of it can run in parallel.

For each node (vertex) I have to modify all the nodes (vertices) downstream that vertex. This, however, ruins the parallelism of the GPU, since child nodes cannot be calculated before their parents, but the effect should lessen further up the tree I traverse. How do I make the GPU do this efficiently, if you consider the fact that I'll be having multiple trees in the scene?

Basically, on one hand, I have the same code that needs to execute for every vertex in the same way, but on the other, it needs to be executed in order, only vertices on the same level can run concurrently.

Any idea on how to solve this problem and what to do?

If I were to use Vulkan instead, would that broaden my options?


texts: How to set rotations to 0,0,0 in 3ds max for exporting in unity?

texts:
I'm a modeler in 3ds max and the unity programmer ask me that the object must have:

pivot with Y up
rotations at 0,0,0

but every object that I export in fbx he says don't have rotations at 0,0,0.
I tryed different solutions as:
- reset xform
- freeze rotation
- rotation to zero
- $.rotation = eulerangles 0 0 0

but in unity he have values like this
[4.577637e-05, -1.525879e-05, 0] or [-90, 1.525879e-05, 0] and so on

It's a problem that can I fix in max or the programmer has to fix it in unity?

Thanks


texts: Vertex normals in the geometry shader using directx

texts:
I'm in directx 11 with the geometry shader.

Is is possible to calculate vertex normals? Just one like segment per vertex? In the geometry shader?

I did vertex normals per face, this is what I got,

My exercise in the book wants something like


texts:
I'm in the process of reading up on 3d matrices and trying to following this powerpoint and had a few questions as to how to exactly determine the type of transformation from a matrix.

If I have a matrix such as...

a 0 0
0 b 0
0 0 1

or

1 0 a
0 1 b
0 0 1

...would these be considered a translation by (a, b) vector?

Or a matrix such as...

cos(a) -sin(a)   0
sin(a)  cos(a)   0
  0        0     1

... would this be considered rotation about Z-axis through the angle a?

Is there a better way to visualize these?


texts: Efficient collision detection of sphere with wall

texts:
I'm building a first-person game where up till now the player has been represented as a dimensionless point; this makes collision detection really easy, as I can just cast a ray along their velocity vector, find the distance to the nearest obstacle, and clamp the magnitude of the displacement vector to that maximum distance on every frame.

Unfortunately, though, this runs into occasional glitches where a player can jump through a corner between two walls, especially if there isn't anything on the other side to collide with--if the player is facing exactly into the intersection, then the projected ray passes right through the corner without registering a hit on either adjacent wall.

To fix this, I want to instead model the player as a finite-sized sphere, which cannot fit through floating-point-error-sized gaps. (This will also have the nice side effect of forcing a minimum standoff distance for the camera from the walls, so you can't stick your eyeball right up against the surface and fill the screen with a single texel.)

Now, checking whether or not that sphere currently intersects a wall is easy. However, I find myself stuck on how to check whether the sphere will intersect a wall if translated in a certain direction--and if so, where.

All of my walls are axis-aligned, which I expect should simplify things.

Any tips?


texts:
I have a vertex-fragment shader that use the Unity3D GrabPass functionality (it grabs the screen). And I apply my GrabPass to have a transparent effect.

GrabPass {
    "_GrabTex"
}

sampler2D   _GrabTex;

// float4 grabPassPos : TEXCOORD4 is used to apply the grabbed texture in
// the right place and is calculated in the vertex
half4 transparent = tex2Dproj(_GrabTex, UNITY_PROJ_COORD(IN.grabPassPos));
half4 baseColor = transparent;
return baseColor;

I am searching a simple way of blurring my grabbed texture. I don't know how to apply my blur because it's a tex2Dproj and I don't know where to apply it.
I am searching for a one pass optimized simple blur but I don't know if it's possible.
I know a bit about Gaussian and Box blur which seems to be the simplest but how can I apply them in a tex2Dproj ?

Thanks a lot !


texts:
I am using a texture atlas for my tiles. Of course I need to get the sub-images to draw them on the canvas as separate tiles. Right now I can think of two ways to implement this.

Divide the texture atlas into separate Image instances. Then draw them onto the canvas accordingly.
Use a single image, and just draw part of it by adding extra parameters to CanvasRenderingContext2D's method `drawImage.

I'm not sure which is better. My thoughts were that the first option would be more manageable and flexible, since each tile is separated. What would be better? What are the ups and downs of each?


texts: UVW: better explanation, and how to implement with GLES texture2D()

texts:
UVW texture coordinates, as opposed to UV texture coordinates, do not get very adequate explanation on the web. Many people offer the simple exlanation, "UV is for 2-dimensional textures and UVW are for 3-dimensional textures." I don't buy this.

I have found a small handful of explanations that I find inadequate. This and this seem to be the best I've come across.

The first link talks about an analogy of shining a laser on a wall. At a perpendicular to the wall, the beam will project as a circle. As the angle increases, however, the beam projects increasingly as an elongated ellipse (it skews).

This sounds to me strikingly like the math involved in lighting equations in that the outcome is related to a vector pointing perpendicular to the surface. How can this relationship be adequately described with a single scalar, the W coordinate (assuming my basic understanding is appropriate)? Can you explain the relationship between the UVW coordinates and the current model-view matrix?

More importantly, I have some models that describe texture coords with a non-zero W coordinate (about 1/3 of the tex coords, or so, and most non-zero values are nowhere near zero.) I'm using OpenGL ES 2.0, where my shading language only provides calls to texture2D(). First off, how significant is the effect of the W coordinate for typical models (think something shaped like an airplane)? (I suspect this question is unfair since it should depend equally on the texture itself.) Is the call to texture3D() required for this, and if so, how can I achieve the desired effect with texture2D()?


texts: Pathfinding to unknown destination point

texts:
Usually you need path finding algorithms to find one or the best path between two points. Do you know if path finding algorithm where you don't know the destination point exists?

I have a graph made of thousands of nodes, I'd like to pick one, and tell my path finding algorithm "find a destination node that is at least at N units of distance of my origin point".

Is it a common problem? How would you solve it?

Thanks.


texts: Put objects on a 2D maps using a matrix of distances

texts:
Is that possible to put objects in a 2D map using only a matrix of their relative distance ?

An example would be putting cities on a map using the distances between them. There would be a minimum of 4 cities.

Thanks a lot.


texts: I'm using direct2d and direct3d together and having an issue with gamma correction.  My direct3d backbuffer is using an SRGB format and when I render images from direct2d onto the direct3d surface, they appear washed out.  I can't seem to figure out how to enable SRGB on the direct2d end.  Does anyone know who to do this?


texts: How do I perform interpolation between noise values sampled at a lower resolution?

texts:
I'm doing some experimentation with terrain generating using a method similar to that described in this blog post by Markus Persson, where I use 3D simplex noise as a "density" value. Like him, sampling every single position in a chunk was simply too much of a performance drain, so I sample at a lower resolution. This works perfectly fine if I just use the noise values sampled at a lower resolution as densities, but this obviously leads to very "chunky" terrain, like this:

The relevant code used to generate the noise values and the voxels that make up the above terrain looks like this:

// Initialize the width, height and depth of the noise values map, and initialize
// the noise value map itself.
int noiseValuesMapWidth = (this.ChunkWidth / this.HorizontalNoiseResolutionDivisor) + 2;
int noiseValuesMapHeight = (this.ChunkHeight / this.VerticalNoiseResolutionDivisor) + 2;
int noiseValuesMapDepth = (this.ChunkDepth / this.HorizontalNoiseResolutionDivisor) + 2;
float[,,] noiseValuesMap = new float[noiseValuesMapWidth, noiseValuesMapHeight, noiseValuesMapDepth];

// Fill the noise values map with noise values.
for(int x = 0; x < noiseValuesMapWidth; x++)
{
    for(int y = 0; y < noiseValuesMapHeight; y++)
    {
        for(int z = 0; z < noiseValuesMapDepth; z++)
        {
            float xSeed = Mathf.Abs((x * this.HorizontalNoiseResolutionDivisor) + this.transform.position.x + seed);
            float ySeed = Mathf.Abs((y * this.VerticalNoiseResolutionDivisor) + this.transform.position.y + seed);
            float zSeed = Mathf.Abs((z * this.HorizontalNoiseResolutionDivisor) + this.transform.position.z + seed);

            noiseValuesMap[x, y, z] = Noise.Generate(
                xSeed * this.NoiseScaleX, ySeed * this.NoiseScaleY, zSeed * this.NoiseScaleZ
            ) - NoiseFalloff(
                this.FalloffACoefficient,
                this.FalloffBCoefficient,
                this.FalloffCCoefficient,
                (float)(y * this.VerticalNoiseResolutionDivisor) / (float)this.ChunkHeight
            );
        }
    }
}

// Generate the chunk's terrain itself by iterating over every voxel position
// and generating simplex noise values at a lower resolution.
for(int x = 0; x < this.ChunkWidth; x++)
{
    for(int y = 0; y < this.ChunkHeight; y++)
    {
        for(int z = 0; z < this.ChunkDepth; z++)
        {
            int noiseValuesMapX = (x / this.HorizontalNoiseResolutionDivisor) + 1;
            int noiseValuesMapY = (y / this.VerticalNoiseResolutionDivisor) + 1;
            int noiseValuesMapZ = (z / this.HorizontalNoiseResolutionDivisor) + 1;

            if(noiseValuesMap[noiseValuesMapX, noiseValuesMapY, noiseValuesMapZ] >= 0.0f)
            {
                this.SetVoxel(new Stone(), x, y, z);
            }
        }
    }
}

Obviously, the solution to the "chunky" terrain is to interpolate between each of the sampled noise values, but I have no idea how to perform that interpolation. How is it done?


texts: DevIL image library isn't loading my image

texts:
This is the first time I've had this problem, my code just won't load the images I need it to.

Here is my first function for loading the image into data:

    void C_Resource_Loader::v_Create_Image(std::string filename,int nID)
{
    //create image and bind to it
    ilGenImages(1, &image[nID]);
    ilBindImage(image[nID]);

    //check if DevIL successfully loads the image
    success = ilLoadImage(filename.c_str());
    if(success)
    {
        success = ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
        if (!success)
            SDL_Quit();
        //create texture and bind to it
        glGenTextures(nID,&texture[nID]);
        glBindTexture(GL_TEXTURE_2D,texture[nID]);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

        glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH),
        ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE,
        ilGetData());

        ilDeleteImages(nID, &texture[nID]);
    }
}

and here is my code for putting the image on the screen:

void C_Resource_Loader::v_Apply_Image(int nID, int pn_X, int pn_Y, int pn_Depth)
{
    glPushMatrix();

    //bind the image so it can be textured
    glGenTextures(1,&texture[nID]);
    glBindTexture(GL_TEXTURE_2D,texture[nID]);

    //move the image to the set x and y
    glTranslatef(pn_X,pn_Y,-600);

    glBegin(GL_QUADS);

    glTexCoord2i(0,0);
    glVertex3f(0,0,pn_Depth);
    glTexCoord2i(0,1);
    glVertex3f(0,32,pn_Depth);
    glTexCoord2i(1,1);
    glVertex3f(32,32,pn_Depth);
    glTexCoord2i(1,0);
    glVertex3f(32,0,pn_Depth);

    glEnd();
    glPopMatrix();
}

Is there a major problem with it, because this code should work, I've used it many times before...


texts:
Im trying to create a mobile game that has flat, bright colors and I want every place to be lightened the same. Like this game:

and this is my game's current state:

I don't know what the problem is. It is too dark and not as good-looking as the first image. If i increase the light, it gets bright, not saturated and crispy. Maybe wrong lighting or wrong material usage? First image looks so crispy and it almost like a Vector art. I modeled all of the assets myself in Blender. I tried using Ambient lighting but it didn't work. I also turned off shadows but still the same.
Also there is a distortion in the big red circle i drew and i don't know why is it hapening. And i don't want the shiny light in the little red circle.


texts: Character collision detection on 2D array tileset based map


texts: How to create a new GameObject, without adding it to the scene?

texts:
I'm creating what is essentially my own prefab system. Game objects are defined by a human readable data file. I'd like to create an empty GameObject, load it with the components defined in the data file and have it ready and waiting for an Instantiate() call. However, whenever I use GameObject go = new GameObject() a new game object is added to the scene.

Using Unity built in prefabs, I can load a prefab as a GameObject, and it's not added to the scene. (See example below)

The rationale behind this is I'd like to have one list that contains GameObjects, some generated by loading Unity prefabs and others created by my custom prefab system. This needs to happen at run time, and can't involve the Unity Editor (since ideally end users would be able to define their own data files).

How can I create a new GameObject, without Unity automatically instantiating it for me?

For example, I can make a call like this:

Resources.LoadAll("PrefabsDirectory", typeof(GameObject))

And I'll get a list of GameObjects, none of which are added to the scene when the call is made. Essentially, I'm creating a LoadAll method for my own prefabs, and likewise, I don't want to instantiate the GameObjects when the call is made.


texts: How to work with two layers or more in cocos2d?

texts:
I want to make a game in cocos2d. I don't know too much about it.

My question is related to communication between two layers or more. For instance, let's say I want a layer with a scrolling road and another on top with scrolling clouds.

Is there anything built-in cocos2d for doing that, or any reference link?


texts: Game upgrade launch : Cross-platform release timing

texts:
I just finished doing a major upgrade for a old mobile title, that haven't seen an update in over a year. Lots of new content, things are looking nice.

Sadly, these days it takes an average of 12 days to get the update through the iTunes approval tube, but less than 2 hours to throw it live right away on Google Play.

If i put the version up now, i can hit the autumn vacation period on android at least, and iOS people will have to wait till their version has been approved.

But I hear from other studios that they wait and launch both updates at the same time, to reach a socalled "synergy effect", since (as I understand it) attention to the update spills over to the mirrored platform.

But... I am simply skeptical on this. Is this effect really so strong, that you would postpone launches for weeks ? And googling for a bit, I'm having a hard time finding any numbers that can back this strategy up.

To put it more direct :
Is holding back a app launch till all platforms are in sync really "worth it" ?

Ofcouse I will hold back my PR-horses till the upgrade is ready for both platforms, but is it really that bad to do a "premature" launch of an app on one platform ?

If anyone can back this strategy up with more than just a gut feeling (numbers and charts are always great) I am all ears. I'm not doing anything to my app untill I have some solid intel on these upgrade strategies.

PS: I am aware the same method is being used on initial app launch, where in a way it makes more sense to me. If you have any data on how strong the benefit of this strategy is there, I'm all ears too.


texts: How to find nearest gameobject on one side

texts:
Here is an example:

The left enemy robot is closer than the right enemy robot, but I want the character to attack the robot that is closest to him on his right side. I can't use Physic.SphereCast or anything of that sort because it will just find the closest enemy on both sides. How can I make this happen?


texts:
Civilization IV was a highly moddable game, and many great mods/games were built off it (Fall From Heaven 2 being my personal favorite).

Does Civilization V have the same opportunities for modding that Civilization IV offered?


texts: My sprite walking animation code doesn't work at all

texts:
This is my first time doing code for a game so I followed some online tutorials.

When I got to the walking and the jumping animation I just can't get it to work whatever I do.

I tried multiple codes but it doesn't work.

My animation code right now:

//animation
if (!place_meeting(x,y+1,Owhitetile))
{
    sprite_index = Scute_character_jump_right;
    image_speed = 0;
    if(sign(vspeed)  < 0) image_index = 0;
}
else
{
    image_speed = 1;
    if(hspeed == 0)
    {
        sprite_index = Scute_character_right;
    }
    else
    {
        sprite_index = Scute_character_walk;
    }
}

All my code so far

//player imput
key_left = keyboard_check (vk_left);
key_right = keyboard_check (vk_right);
key_jump = keyboard_check_pressed (vk_space);

//calculate movement
var move = key_right - key_left;

hspeed = move * walksp;
vspeed = vspeed + grv;

if (place_meeting(x,y+1,Owhitetile)) and (key_jump)
{
    vspeed=-7;
}

//horizontal colision
if (place_meeting(x+hspeed,y,Owhitetile))
{
    while (!place_meeting(x+sign(hspeed),y,Owhitetile))
    {
        x = x + sign(hspeed);
    }
    hspeed = 0;
}
x = x + hspeed;

//vertical colision
if (place_meeting(x,y+vspeed,Owhitetile))
{
    while (!place_meeting(x,y+sign(vspeed),Owhitetile))
    {
        y = y + sign(vspeed);
    }
    vspeed = 0;
}
y = y + vspeed;

//player death
if (place_meeting(x,y+vspeed,Ospikes))
{

   instance_destroy()
   game_restart()

}

//animation

if (!place_meeting(x,y+1,Owhitetile))
{
    sprite_index = Scute_character_jump_right;
    image_speed = 0;
    if(sign(vspeed)  < 0) image_index = 0;
}
else
{
    image_speed = 1;
    if(hspeed == 0)
    {
        sprite_index = Scute_character_right;
    }
    else
    {
        sprite_index = Scute_character_walk;
    }
}


texts:
I'm a wanna-be indie developer, and I am working on my first flash game. But, before I even start with the code, I want to know this: When determining the title of my game, how can I decide if it is copyrighted or not?

For example, at first I thought about "Into the Void" for the title. When I Googled it, I found out that it is a name of a song by Black Sabbath. Is it okay if I use this title, or is it copyright infringement?


texts: Smooth interpolation with variable time steps

texts:
My game engine just went through a small overhaul that changed its fixed time step loops into variable time steps ones. Though everything has already been adapted steadily to the new environment, there is still one algorithm that relied heavily on steady ticks: my camera's behavior.

It was pretty much like this (pseudo-code):

    class Camera {
        const float factor = /* value between 0 and 1 */;

        void update() {
            Vector2 distance = player.getPosition() - this.getPosition();
            this.move(distance * factor);
        }
    }

What is generally done for this sort of "pursuing" behavior? This is more than simple speeds and accelerations.

I could go with the following, but it still leaves a feeling of choppiness when in contrast with the rest of the game.

    class Camera {
        const float factor = /* value between 0 and 1 */;
        const float fixedStep = 1.0f / 40.0f; // supposing that it worked under 40FPS before

        float timeAcc = 0.0f;

        void update (float timeElapsed) {
            timeAcc += timeElapsed;

            while (timeAcc >= fixedStep) {
                timeAcc -= fixedStep;

                Vector2 distance = player.getPosition() - this.getPosition();
                this.move(distance * factor);
            }
        }
    }

It is C#-like pseudo-code, but don't be fooled: I'm actually using C++ and SFML, so I don't have many (or any) already-implemented methods at my reach.


texts: Animating child objects via parent object animator in script

texts:
I'm using unity 5

I'm trying to animate multiple child objects via a parent object. The animation worked in the animation view but would not work when I tried to preview the game. In the script I use the code:

ParentObject.GetComponent<Animator>().Play("intro");

to play the animation. A similar line of code worked when playing a singular object, not sure what's going wrong now, any sugestions?


texts:
I'm currently having a problem with lights in Unity. They shine through walls for some reason.

Point, directional, etc. If a light is next to a wall on one side, you can see it on the floor on the other side. I believe this has something to do with culling masks or light culling.

I was wondering how I could go about culling the lights so they no longer shine through walls. Any help is greatly appreciated.

I'm on Unity 4.x Pro, so I have all the features for that.

Here's a picture of a light on one side of the wall:

And here's it shining through to the other side, which it's not supposed to do:


texts: Simplified trajectory equation to identify Time Taken(t) by a protectile to travel Distance(d), under gravity?

texts:
I am building a game, where I have to plot a trajectory of a ball in 3D space, launched with an inital velocity Sx, Sy, Sz. [I am using OpenGL and Android-NDK]

  Lets assume Sz is always 0. And Sx and Sy values are known.

Now, I am able to plot a dotted trajectory properly along the path taken by the ball, under uniform gravity. But, the problem is that the distance between the points are NOT EQUIDISTANT, since I am plotting them at regular time intervals.

So, the next step for me is to plot the trajectory at intervals (tn) such that my distance traveled (d) is always fixed.

  Now, assume I want to plot the "nth" trajectory point for every "d" units of distance. So, I need 'tn' to plot it.

I have tried solving this on white board, but the resulting equation for 'tn' is too complex. And I could get this far :

  d^2 = dx^2 + dy^2;

  dx = Sx * t;  |  t = dx/Sx;

  dy = Sy * t + 1/2 (g) (t^2); | dy = Sy * (dx/Sx) + 1/2 (g) ((dx/Sx)^2);

  So t = 'gives me an equation that has a highest order of 4';

I am hoping there must be a better way. Can anyone please help me derive a better equation for 't'.

  Time (tn) = ?;
     Assume tn = Tn - T(n-1);
     Where 'Tn' is total time to cover 'n' times 'd' units of distance.

  In terms of :
              'd' : is distance interval. (fixed);
              'sx': initial velocity along x axis (horizotal ground);
              'sy': initial velocity along y axis (against gravity 'g');

Hope, I made thing clear enough. Please let me know if you need more information.

I tried this question in 'physics.stackexchange.com', but I was thinking this might be a more appropriate place to discuss, since I want a perspective of a game developers too.


texts: Calculate target angle to a certain Vector

texts:
I'm developing a 3D game in LWJGL.
I have a player class and a monster class and I need the monster class to chase the player when the player is within a certain distance.
For that I have the monster directional vector (let's call it monDirVector) and the directional vector that points from the monster to the player (let's call it dirToPlayer)

So the way my monster class works is that it increments its current rotation to match a target angle (this way I can simulate the walking + turning animation). Given this I need to calculate the target angle so that the monDirVector overlaps the dirToPlayer making the monster walk right towards the player.

How would I go about this?

Here's a diagram for better understanding of what I need.

I pretty much need to get the cº angle and assign it as the target angle for the monster.
The aº is the monster current rotation and the bº is the angle between the two vectors. Both of these are known.
Please notice that the monster can be oriented any way and the player can be in any quadrant relative to the monster. This stands for a problem because I can't simply subtract the angle towards the player to the current rotation of the monster.

I would really apreciate if someone helped me.


texts:
I have a class terrain which create a grid of Quads. I do it like this

for(int z=0; z<_length;z++){
            for(int x=0; x<_width;x++){
                vertices.push_back(vec3((float)x*250, 0.f, (float)z*250));
    }
}
for(int z=0; z<(_length-1);++z){
    for(int x=0; x<(_width-1);++x){
        int index = z*_width+x;
        Vertex _vertices[] = {
            Vertex(vertices.at(index),vec3(0, 0, 0)),
            Vertex(vertices.at(index+1),vec3(0, 0, 0)),
            Vertex(vertices.at(index+_width),vec3(0, 0, 0)),
            Vertex(vertices.at(index+1+_width),vec3(0,0,0))
        };

        unsigned short indices[]= {index,index + 1,index +
            _width,index + 1,index +  _width,index +  _width + 1};
        Quad quad(_vertices, 4, indices, 6);
        squares.push_back(quad);
        i++;
    }
}

The vertices and the logic are correct, but the indices aren't, for some reason. here is the output for this code :

But when I change this indices to this :

            unsigned short indices[]= {0,1,2,1,2,3};

It works great :

The problem is I don't understand why this line

        unsigned short indices[]= {index,index + 1,index +
            _width,index + 1,index +  _width,index +  _width + 1};

doesn't work. And if it worked, my grid would consume a lot less ressources. If someone could explain me why it doesn't work, It would be great, thanks you.
In case you need to know how I draw a Quad, here is the code :

class Quad{
public:
    Quad(Vertex *_vertices, int _n, unsigned short * _indices, unsigned short _numIndices){
        for(int i=0; i < _numIndices; i++){
            indices.push_back(_indices[i]);
        }

        for(int i=0; i<_n; i++){
            vec3 v = vec3(_vertices[i].position, _lengthPower);
            position.push_back(v);
        }
        glGenVertexArrays(1, &mVertexArray);
        glBindVertexArray(mVertexArray);

        glGenBuffers(1, &mPositionBuffer);
        glBindBuffer(GL_ARRAY_BUFFER, mPositionBuffer);
        glBufferData(GL_ARRAY_BUFFER, sizeof(vec3)*position.size(), position.data(), GL_STATIC_DRAW);

        glGenBuffers(1, &mIndicesBuffer);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndicesBuffer);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned short)*indices.size(), indices.data(), GL_STATIC_DRAW);

    }

    void draw(){
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, mPositionBuffer);
        glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndicesBuffer);
        glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_SHORT, 0);
        glDisableVertexAttribArray(0);

    }
    ~Quad(){

    }
private:

    std::vector<unsigned short> indices;
    std::vector<vec3> position;
    GLuint mVertexArray;
    GLuint mPositionBuffer;
    GLuint mIndicesBuffer;
};

I'm using, OpenGL, glm, glfw etc.


texts: I need to use Microsoft.Ink library on XNA. Previously I used ink library on winforms application and drawing on the form screen is very easy and it looks pretty good. However, when I do the same thing on the XNA screen, the ink shows up for a 1 sec then it disappears or sometimes, it shows up but flashes. Is there a solution for that? Thanks for your help.


texts:
Here's something that's been bugging me all day: Controller detection in SDL.

First thing is that it doesn't automatically detect when a controller is connected. Finding out when a controller is disconnected is no problem:

if(joystick.closed > 0) { SendEvent(E_CONTROLLER_DISCONNECTED); //cleanup }

I simply have a little loop to detect for new controllers:

SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
SDL_InitSubSystem(SDL_INIT_JOYSTICK);
joysticks_.Clear();
joysticks_.Resize(SDL_NumJoysticks());

Which works but is very, very slow. Regardless if I have a controller plugged in or not, this step alone takes 10-20ms. Even spacing it apart every few seconds, there are obviously noticable lag spikes whenever I am doing the detection; even with another thread, the lag spikes are still there. However I have not found any better alternative.

This type of behavior is imperitive to proper operation. This is especially so since if a controller gets disconnected, it won't automatically re-open in SDL when I reconnected it. Is there any better way to do this?

Oh, and as another point to make, I don't want to use SDL Events. They do basically what I've listed above, but don't work well with my existing multithreaded approach.


texts:
Looking to create an inventory screen in Unity, and trying to think of the best way to do it.

My current line of thinking is having a few rows of squares for inventory items that are drag and droppable onto a paperdoll, a la Diablo.  When dragging and dropping on the items, it would update a 3D model of your current playable object with the items.

The menu itself would be easy enough to do with a simple square and a hierarchy of game objects for the items, each responding to mouse hovering over.

The problem I am trying to figure out is being able to render the 3D model on the side.  Granted, this is a nice to have, and not necessarily a need, but browsing the documentation, the only way I can think of accomplishing this is using a render to texture which requires Unity Pro with a separate camera completely out of bounds of the current space.

Anyone have suggestions on how to accomplish this?


texts:
I am building an isometric game environemnt and i want to be able to pan the camera around the map by holding the right mouse button, can someone talk me through the logic for this please, i have made an attempt and tried a number ways. I can get the camera to move correctly the first time but when i click and hold the second time the camera resets itself, thanks in advance for any help

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class CameraMovementTest extends JPanel{

private Timer timer;
private int DELAY = 10;
private  CustomMouseListener mouseListener;
private int positionX = 0, positionY = 0;

public CameraMovementTest() {

    mouseListener  = new CustomMouseListener();
    this.addMouseListener(mouseListener);
    this.addMouseMotionListener(mouseListener);
    this.setSize(500,500);
    this.setVisible(true);

    //Swing Timer
    timer = new Timer(DELAY, new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent arg0) {
            update();
            repaint();
            validate();
        }
    });
    timer.start();
}

private void update() {
    if(mouseListener!=null){
        positionX = mouseListener.getX();
        positionY = mouseListener.getY();
    }
}

@Override
public void paint(Graphics g) {
    super.paint(g);
    g.fillRect( positionX,  positionY, 300,300);
}

public class CustomMouseListener implements MouseListener, MouseMotionListener {
    private int positionX = 0, positionY = 0;
    private int mouseClickX, mouseClickY;

    @Override
    public void mousePressed(MouseEvent evt) {

        if(SwingUtilities.isRightMouseButton(evt)) {

            mouseClickX = evt.getX();
            mouseClickY = evt.getY();
        }
    }
    @Override
    public void mouseDragged(MouseEvent evt) {
        if(SwingUtilities.isRightMouseButton(evt)) {
            positionX = mouseClickX - evt.getX();
            positionY = mouseClickY - evt.getY();
        }
    }
    @Override
    public void mouseMoved(MouseEvent arg0) {}
    @Override
    public void mouseClicked(MouseEvent arg0) { }
    @Override
    public void mouseEntered(MouseEvent arg0) { }
    @Override
    public void mouseExited(MouseEvent arg0) {}

    @Override
    public void mouseReleased(MouseEvent arg0) {}
    public int getX(){
        return positionX;
    }
    public int getY(){
        return positionY;
    }
}

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            JFrame f = new JFrame();
            f.setVisible(true);
            f.setSize(new Dimension(500,500));
            f.setContentPane(new CameraMovementTest());
        }
    });
}

}


texts: Art Style Guide - External Image Sources?

texts:
I've been looking into how to structure an art style guide (ASG); it's a document which helps guide artists how a project's visuals should look. They often have sketches and illustrations from artists working on the project, though I am unsure about using external images.

I am working on a commercial videogame project and I have been writing both a game design document (GDD) and currently an art style guide. Is it legal for me to add artwork I came across while browsing the internet into the ASG? I know that most artists can add external images outside of their project into a section talking about inspirations, but could this be done for areas that loosely talk about, say, an overall aesthetic of something, such as creature or environment design?

For example, say I have a section which talks about the design of fantasy monsters in a chapter about characters. Would it be legally viable to use various images I come across to help show artists what I'm looking for in each creature? I'm guessing that it is legally viable because I don't think I'd be profiting off of an ASG. I hope somebody could verify this for me; I don't want to cause any trouble.

I apologize for making this a bit wordy; I wish I knew how to articulate myself better.


texts: How Can I Monetize With Startapp A Libgdx Game Made With Aide

texts:
I have created a libGDX game with the AIDE IDE Android app. The game is working fine so I will be uploading it to the Play Store to make money.

I'd like to use Startapp ads, how would I integrate it?
I Will Using Aide Premium


texts: Libgdx - overlapping stages - textbutton unclickable

texts:
I've created a few TextButtons for a menu that render on top of another stage area, however the textbuttons that i've created for menu aren't clickable or don't provide any events. The MenuComponent class I created is being instantiated/rendered in another class.
The buttons show up, just unable to click anything or get any events from the buttons. Can someone take a look at the code I provided and maybe show me mistakes or something I forgot to implement to make them work?
MenuComponent Class:
   @Override
    public void create() {
        batch = new SpriteBatch();
        this.stage = new Stage();
        setRenderer(new ShapeRenderer());
        Gdx.input.setInputProcessor(stage);
        menuUp = new Texture("assets/ui/disengage.png");
        menuDown = new Texture("assets/ui/disengagePressed.png");

        Table menuWindow = new Table();
        this.menuWindow = menuWindow;
        menuWindow.setPosition(675,160);
        //Button View
        SpriteDrawable upFormat=new SpriteDrawable(new Sprite(createRoundPixMap(Color.BLACK,100, 30,10)));
        SpriteDrawable downFormat=new SpriteDrawable(new Sprite(createRoundPixMap(Color.RED,100, 30,10)));
        SpriteDrawable checkedFormat=new SpriteDrawable(new Sprite(createRoundPixMap(Color.BLACK,100, 30,10)));
        TextButtonStyle buttonStyle=new TextButtonStyle(upFormat, downFormat, checkedFormat, new BitmapFont());
        //Individual Buttons
        lobbyButton = new TextButton("Back to Lobby",buttonStyle);
        mapsButton = new TextButton("List Maps",buttonStyle);
        menuWindow.add(lobbyButton).pad(3,0,3,0).row();
        menuWindow.add(mapsButton).pad(3,0,3,0).row();
        menuWindow.setVisible(false);
        stage.addActor(menuWindow);
        stage.getRoot().setPosition(65,150);
    }

    @Override
    public void update() {
    }

    @Override
    public void render() {
        batch.begin();
        batch.draw((menuButtonIsDown)?menuDown:menuUp, MENU_buttonX, MENU_buttonY);

        batch.end();
        stage.act();
        stage.draw();
    }

Part of the class its being rendered/created in:
    @Override
    public void create() {
        generator = new FreeTypeFontGenerator(Gdx.files.internal("assets/font/Roboto-Regular.ttf"));
        FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
        parameter.size = 10;
        parameter.spaceX = 0;
        parameter.shadowColor = new Color(0, 0, 0, 0.5f);
        parameter.borderColor = Color.BLACK;
        parameter.borderWidth = 1;
        parameter.borderStraight = true;
        parameter.shadowOffsetY = 1;
        parameter.shadowOffsetX = 1;
        font = generator.generateFont(parameter);

        renderer = new ShapeRenderer();
        this.batch = new SpriteBatch();
        sea = context.getManager().get(context.getAssetObject().sea,Texture.class);
        sea.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat);
        camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight() - 200);
        this.mainmenu = new MenuComponent(context, this);
        mainmenu.create();
    }

    @Override
    public void render() {
        batch.setProjectionMatrix(camera.combined);
        batch.begin();

        Gdx.gl.glViewport(0,200, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() - 200);

        mainmenu.render();
    }


texts: What makes a game a game vs something else like a puzzle or a toy?

texts:
Famously the Sims and similar games have been described by some designers as Toys and not "really" games.

I'm curious if there is a good answer to what makes something a game.

For example many companies sell Sudoku games - EA has an iPhone one, IronSudoku offers a great web based one, and there are countless others on most platforms.

Many newspapers publish Sudoku puzzles in their print editions and often online.

What differentiates a game from a puzzle? (or are all Sudoku "games" misnamed?)

I'm not convinced there is a simple or easy answer - but I'd love to be proven wrong. I've seen some definitions and emphasize "rules" as core to something being a game (vs. "real life") but puzzles have rules as well - as do many other things.

I'm open to answers that either focus only on computer games (on any platform) or which expand to include games and gameplay across many platforms. Here to I'm not fully convinced the lines are clear - is a "game" of D&D played over a virtual tabletop with computer dice rollers, video & audio chat a computer game or something else? (I'd lean towards something else - but where do you draw that line?)


texts: I am new to Box2D, I have set gravity to 10. How to make an object fly in space even though the gravity is 10. What are the properties I need to set to make object fly? Is there any different approach?


texts: I have been using a profiler to optimize my game for the Xbox, my aim is as with any optimization to reduce excess CPU and memory usage. I have managed to cut down a lot of the processor time and memory used by my game. However i have a lot of bullets in my game that the player fires and every-time a bullet impacts with something the soundeffect.play() method is called to play the explosion. I would like to know if there is a more efficient way of playing the explosion soundeffect?


texts: How to manually kick players in new Unity Input System

texts:
Using the new Unity PlayerInputManager, I'm trying to create a page in the pause menu of the game where players can remove other players from the game.  It's a split-screen game, and it seems to handle kicking the last player (i.e. if there were three players, kicking the third) just fine.
However, if we have three players and we destroy the gameobject for player two, it seems like the player index and the screen index of player three do not automatically adjust, and the screen remains split three ways.  Here's some of the code I've tried:
public void KickPlayer(int i)
    {

      PlayerInput.Destroy(players[i]);
      players[i] = null;
      for (int j = i; j < 4; j++)
      {
          if (j+1 == 4 || players[j+1] == null)
          {
              players[j] = null;
          } else
          {
              players[j] = players[j + 1];
              players[j + 1] = null;
              PlayerInput pi = players[j].GetComponent<PlayerInput>();
              PlayerInput.Instantiate(players[j], j, pi.currentControlScheme, pi.splitScreenIndex-1, pi.devices.ToArray());
              PlayerInput.Destroy(players[j + 1]);
          }
      }
}

Although this code looks like it should rearrange and re-assign the split-screen, what I end up with when I spawn in three players and try to kick player two is player 0 with split-screen index 0, then there suddenly are three other players, player 1, 2, and a second copy of player 2 all sharing split-screen index 2.
What would be the best way to go about this?  Is there a way to reassign player index and split-screen index?


texts: Finding Game Object with Regular Expressions

texts:
Is there a way to use a Regular expression in the GameObject.Find() method?

I'm making a checkers game and I've got pieces named Red Piece (x,y) and White Piece (x,y) (where x & y are actual integer coordinates). I want to destroy a piece at a certain x,y. So what I'm trying to do is something like

Destroy(GameObject.Find(Regex.Matches("(Red)|(White) Piece (" + x + ","+ y + ")")));

I need it to find any object with a name that contains "Piece (x,y)" whether it's a red piece or a white piece, and destroy it. Any ideas?


texts: How can I get the player coordinates in Minecraft

texts:
I am currently working on a client for Minecraft Java edition and I'm having an issue finding out how I can get my Minecraft character's current coordinates, client side coordinates.

I would just like to know where I can find the file that contains the coordinates, or a way to get the coordinates, without using forge, or anything like that. Just vanilla Minecraft. The Minecraft version I am working with is 1.8.9, but I would like this to work for any version of the game.


texts: WebGL .NETCoreApp 1.1 - UnityLoader.js - SyntaxError: expected expression, got end of script

texts:
After creating a release build of my game using Unity 5.6, I could navigate to the created folder and open the 'index.html' file and my game would load and play normally.
However, when trying to integrate it into my WebApp (.NETCore 1.1), I would continually get this error in Chrome, Firefox, IE, etc..:

UnityLoader.js - SyntaxError: expected expression, got end of script

Invoking error handler due to
TypeError: UnityLoader[r] is not a function


texts: I am creating a windows store game using unity . I want to save the current high score data . I most probably use StreamReader / StreamWriter for saving data but when i build the executable for windows store app , the compiler is giving me a error that StreamReader class is not supported . Is there any alternate way for solving this problem ?


texts: Trying to better understand Unity gameobjects

texts:
New to Unity, but develop in C# normally.  I can't seem to get how / why / where to grab certain elements.  For simplicity, I have a top-level game object, say a cube.  I add a sphere to the scene as child to the cube. The child sphere (actually more complex), has navigation mesh, animation object, collider and finally a script in C#.

Now, my C# class is comprised of an instance of an C# class on the class.  Something like

public class CMyGeneric
{
   public void someMethod()
   {
      // invalid getting to "gameObject" reference
   }
}

public class CMyMainScript
{
   public CMyGeneric myGeneric;

   void Start()
   {
      myGeneric = new CMyGeneric();
   }

   void Update()
   {
      myGeneric.someMethod();
   }
}

So, the parent game object is the cube, the child is the sphere, and the CMyMainScript script is attached to the sphere.  However, when I try to reference "gameObject" via the CMyGeneric (instance), call within the "someMethod", the "someMethod" doesn't appear to see the overall "gameObject".

Now, how/what am I missing as each thing that gets attached, unity adds to these game objects, and I don't know how to get respective hierarchical levels of where things are even though I know where they are from a relative perspective.


texts: How to implement circle clipping in SDL2?

texts:
In SDL2 there's a function to set a rectangular clip mask:

int SDL_RenderSetClipRect(SDL_Renderer* Renderer, SDL_Rect* clip);

If i call this function, copied textures will be displayed in this clip rect but not outside of it.
What I'm wondering is if it's possible to set a circle as a clip?

For example, in Material Design:

There are some buttons with the shape of a circle and when you click on them, it appears a small circle from the cursor and this becomes bigger.
This small circle is not display outside the button but only inside.
And so, i want to do this. I want to renderer a texture that is clipped with a circle.

I don't think SDL_RenderSetClipCircle exists, so how could I emulate this?


texts: Combining Rotation, Jump, and Crouch Animations with 2D Blend Tree

texts:
I have a 2D Freeform Blend Tree that I'm using to animate a character that can currently:

Walk / Sprint Forward
Walk / Sprint Backward
Strafe / Sprint Strafe Left
Strafe / Sprint Strafe Right
Idle

My goal is to add in rotation, jump, crouch, and "firing when walking" animations.
In just dealing with turning or even jumping for now, I understand how to handle and call the animations in the code, but not sure of how it should be set up in the animator.
Do I transition to rotation/jump animations on the base layer? I'm reserved doing it this way because I lose the ability to blend and take advantage of those transitions.
Can I build it into my current 2D blend tree even though the blend tree is only X and Z axis?

public class twoDControllerMovement : MonoBehaviour
{
    Animator animator;
    public CharacterController controller;

    [SerializeField] private float walkSpeed = 12.0f;
    [SerializeField] private float strafeSpeed = 10.0f;
    [SerializeField] private float sprintMultipler = 2.0f;
    [SerializeField] private float rotationSpeed = 120.0f;

    // Start is called before the first frame update
    void Start()
    {
        animator = GetComponent<Animator>();
        controller = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {

        // handle sprint
        float currentWalkSpeed = walkSpeed;
        float currentStrafeSpeed = strafeSpeed;
        bool runPressed = false;

        // handle shift
        if (Input.GetKey(KeyCode.LeftShift))
        {
            currentWalkSpeed = walkSpeed * sprintMultipler;
            currentStrafeSpeed = strafeSpeed * sprintMultipler;
            runPressed = true;
        }

        // calculate movement
        float strafe = Input.GetAxis("Strafe") * currentStrafeSpeed * Time.deltaTime;
        float translation = Input.GetAxis("Vertical") * currentWalkSpeed * Time.deltaTime;
        float rotation = Input.GetAxis("Horizontal") * rotationSpeed * Time.deltaTime;

        // execute movement
        transform.Translate(strafe, 0f, translation);
        transform.Rotate(0, rotation, 0f);

        // handle movement animations
        if (runPressed) {
            animator.SetFloat("VelocityZ", Input.GetAxis("Vertical") * sprintMultipler);
            animator.SetFloat("VelocityX", Input.GetAxis("Strafe") * sprintMultipler);
        } else
        {
            animator.SetFloat("VelocityZ", Input.GetAxis("Vertical"));
            animator.SetFloat("VelocityX", Input.GetAxis("Strafe"));
        }

        // handle roration animations
        if (Input.GetAxis("Horizontal") < 0.1f)
        {
            //Debug.Log(Input.GetAxis("Horizontal"));
        } else if (Input.GetAxis("Horizontal") > 0.1f)
        {
            //Debug.Log(Input.GetAxis("Horizontal"));
        }

    }
}

Also open to any feedback on improving the code above, my goal is as small and clean as possible!  I do have a slight delay in animations starting when switching directions that I have to work out at some point and would eventually.


texts: Unity3d: Rotating a sphere so point lines up with the camera

texts:
I'm trying to make a world map in Unity that contains a rotating globe with landing sites on the perimeter.  What I want is that when a player clicks on the landing site the globe rotates so that the landing site is centered.  I've been trying to find the right way to use the Quaternion class but not much luck.

Here is my latest attempt which doesn't work.  The landing sites are parented to the globe but the camera and globe are separate.

        void Update()
    {
        if (_selectedLandingSite != null)
        {
            var rotation = Quaternion.FromToRotation(_selectedLandingSite.transform.localPosition, MainPlanet.transform.forward);

            var trans = Game.Game.Instance.MainCamera.gameObject.transform;
            var lookDirection = new Vector3(trans.position.x, trans.position.y, trans.position.z);
            lookDirection = rotation * lookDirection;

            var _lookRotation = Quaternion.LookRotation(_selectedLandingSite.transform.localPosition);

            //rotate us over time according to speed until we are in the required rotation
            MainPlanet.transform.rotation = Quaternion.Slerp(transform.rotation, _lookRotation, Time.deltaTime * 1);

            //MainPlanet.transform.rotation =
            //  Quaternion.RotateTowards(MainPlanet.transform.rotation, _targetRotation, 1);
        }
    }


texts: I want to use Ashley but I also want to use actions and listeners with Scene2d. I read that it is not a good idea, but why? Ican create a system with stage.act(); and stage.draw(); in the update method or is it a bad idea? Thanks.


texts:
Context

I have been implementing my own networking for a third person multiplayer game, but controls and physics will be ala old school FPSs. I'm using Unity's transport layer, which allows me to send and recieve raw data between server and client.

I used this model as reference, in order to implement better client response:
http://www.gabrielgambetta.com/client-server-game-architecture.html

Implementing prediction, and interpolation was no problem, but I'm having a problem implementing reconciliation, even though I successfully implemented for normal ground movement.

I do the following each tick:

Client: The client sends the server the delta updates on the player position, and the server validates this movement and updates the player accordingly on the server.
Server: I send a snapshot to all clients with all players' positions. Each client interpolates the rest of the players, and reconciliates it's own position.

Reconciliation

Ground movement seems easy, because each frame the player input determines how the player moves: Each FixedUpdate, the player moves a certain distance.
This makes reconciliation really easy, since knowing which was the last input the server has received, your client just needs to consider the rest of the inputs yet to be processed.

Reconciliating jumping

But I don't know how to deal with jumping. Jumping is an input that has an impact on the player's position over several frames: while it's airborne (and for a few frames, as the placer decelerates in case his air speed was high).

This means I can't just rely on the input "jump" to recalculate my client's position, since depending on the moment I'm present, I could be ascending, or descending. Even more, if I jump and collide with the roof, killing all my vertical speed, the movement would be completelly different.

This lead me to think I should be sending to the server each update on the player's position:
Instead of sending "hey, im jumping here", I could send "I'm moving up 1 unit"..."I'm moving up 0.9 units".... describing the players parabole. But I feel this method is not enterily secure, since the client could be sending "I'm moving up 1" ever single time, allowing the player to just fly away. So the server has to be the one handling the physics on the jump.

Other scenerios

This problem is also present in anything physics related: When the player is pushed away by an external force set up by the server or the client itself. If the client recieves a message saying has been affected by an explosion, I could set the client's speed accordingly, but:
 - If I have any kind of air control (which I want to have), I need to tell the server the change on air speed
 - If the server makes a correction on the physics made, I need to be able to predict and reconciliate the position AND speed. For example: If I collide against a wall in the server, which for some reason, is not present in the client, I also need to kill the player speed or it will keep slamming into an invisible wall.

Posible solutions

There are several solutions I was thinking about, but I'm not really satisfied with any of them:

As said earlier, I could could let the client handle the air movement by sending the position update back to the server, but this feels insecure since th client could technically make himself fly around, and make himself immune to being pushed away.
Besides sending the player positions, I could also send the players' speed, storing this information could make reconciliation easier and more reliable, but it will also increase the size of snapshots and network usage.

Maybe I'm missing a clever alternative, but I don't really see any other option. Any ideas?


texts:
I am creating a Top-View 2D game. However, the only way i can get a good view of the objects, such as houses, trees, is to make the game in orthographic view. The same way games such as Pokemon games in GameBoy Advances used. Until i found out that, GTA 1 and 2 are originally in top-view. Whenever the car (your focus) passes a building, the view of the building changes, specifically, the "Skewness" of the building.

Is it possible to do this using SpriteSheets? or atleast a single image and just dynamically change its attributes? or GTA 2 is already using a 3D game engine.


texts: The children of a Transform are in reverse order

texts:
I am making a simple 4-player turn-based card game.
At one point, a player can "open" his hand on the table. As the player does this, I want cards to be aligned in a way such that left side of each one is visible.

In my hand, the cards look like this.

When I carry them on the table, they look like this

Not only the order is reversed, which I wouldn't mind, but also the cards are not visible now.

This is how the green area looks like in the Inspector

I don't want cards to change shape to fill the area, and I also don't want them to go outside the green area.

When I unselect Control Child Size, the cards are aligned just as I want, but now they are too spread out and outside the green area.

Is there a way to achieve the behavior that I want?


texts: Which game portals support Silverlight games?

texts: I have been looking for strong game portals that support Silverlight.  Which ones are currently available?


texts: Is this technique for stat tracking without a database workable?

texts:
If I wanted to create a chess game, for iOS, that tracked both player moves (for retracing the progression of a game and for player stats), what would be the simplest route to take?

To clarify, I want to track not only the moves a player has made in a particular game, but how often that player has made that move in past games. For example I want to be able to track:

How many times a given player has opened by moving the king pawn up two squares (e4) as white, on move number one.
What is the percentage of time the player responds to white's e4 opening move, with moving his own king pawn to e5?
What percentage of time does he respond by moving his queenside bishop pawn to c5?

And so on. If it's not clear, the stat tracking system should also be able to report how many times this player, as black, move his queen to h1, on move number 30.

I'm using Parse.com for my back-end as a server (BaaS) service. If I were to create a class that

writes strings that identify move number, player color, moved piece, algebraic notation of the square (e.g. "d8") to a file, locally in the file system
saves the file to Parse, and deletes the temporary file from file system
upon opening the same game in my tableview (a la a "With Friends" game), download this file from Parse, parse through it and retrieve all stats/history, assign all relevant values to variables

Is this plan viable, or is there an easier way?


texts: Character permanently disappears when camera zooms in

texts:
I am using ThirdPersonController and FreeLookCameraRig, both from the standard assets package. The camera generally follows the player fine but there is an issue when I move the camera very close to the player. When I do this, the character disappears, though it still behaves as though it is in the scene. For example, the xyz coords still show it as being in the scene and when it jumps, the camera still follows it.

Here's a visual explanation. Notice how the character disappears after about 5-10 seconds and doesn't come back.

(Note: the gif is too large to display here, so please see it on imgur. http://i.imgur.com/PbMDlXD.gifv).

The ThirdPersonController has Transform, Animator, CapsuleCollider, Third Person User Controller, and Third Person Character

The FreeLookCameraRig has Transform, Free Look Cam, and Protect Camera From Wall.

I have tried messing with many of these settings, but nothing has worked.

By the way, some of the course was created in Sketchup.


texts: Handling real projectiles with different FOVs on a first person shooter camera stack

texts:
I'm prototyping out a First Person Shooter and I'll admit I have little work experience in the genre (though I've played many of them). I'm using a traditional weapon camera stack in which the main camera has a user selectable FOV and the weapon camera draws on top of that with a fixed (and lower) FOV. This prevents visible model distortion that would be very apparently with something so close to the camera. Both cameras always maintain the same transform, they just have differing FOVs.
In some instances I want to emit actual physics projectiles not just do hitscan bullet checks. Think a rocket or grenade launcher, you don't want those hitscan.
However, I'm not sure how to overcome the perceived visible offset that happens from the muzzle between the weapon camera's low FOV to the main camera's higher FOV. In this example the weapon FOV is 40 and the main camera is 80. The red ball is the point at which the projectiles will spawn.

As you can see they will visually appear to emit quite a distance away from the muzzle of the gun. The spawn point - and my projectiles - are rendered by the main camera and the high FOV visually moves the ball to the front (despite the world space being actually on the muzzle of the gun). What is the normal approach to overcome this?
Things I've thought of is having the bullets secretly emit behind the gun so then rely on the fact the weapon camera is always on top to mask the fact the bullets are emitting from behind the camera's near clipping plane, or actually calculating the camera projection difference when the view changes and attempting to adjust the emission point.
I appreciate any help, thanks!


texts: What's wrong with this turn to face algorithm?

texts:
I implement a torpedo object that chases a rotating planet. Specifically, it will turn toward the planet each update. Initially my implement was:

void move() {
        vector3<float> to_target = target - get_position();
        to_target.normalize();
        position += (to_target * speed);
}

which works perfectly for torpedo that is a solid sphere. Now my torpedo is actually a model, which has a forward vector, so using this method looks odd because it doesn't actually turn toward but jump toward.
So I revised it a bit to get,

double get_rotation_angle(vector3<float> u, vector3<float> v) const {
    u.normalize();
    v.normalize();
    double cosine_theta = u.dot(v);
    // domain of arccosine is [-1, 1]
    if (cosine_theta > 1) {
        cosine_theta = 1;
    }
    if (cosine_theta < -1) {
        cosine_theta = -1;
    }
    return math3d::to_degree(acos(cosine_theta));
}

vector3<float> get_rotation_axis(vector3<float> u, vector3<float> v) const {
    u.normalize();
    v.normalize();
    // fix linear case
    if (u == v || u == -v) {
        v[0] += 0.05;
        v[1] += 0.0;
        v[2] += 0.05;
        v.normalize();
    }
    vector3<float> axis = u.cross(v);
    return axis.normal();
}

void turn_to_face() {
    vector3<float> to_target = (target - position);
    vector3<float> axis = get_rotation_axis(get_forward(), to_target);
    double angle = get_rotation_angle(get_forward(), to_target);
    double distance = math3d::distance(position, target);
    gl_matrix_mode(GL_MODELVIEW);
        gl_push_matrix(); {
        gl_load_identity();
        gl_translate_f(position.get_x(), position.get_y(), position.get_z());
        gl_rotate_f(angle, axis.get_x(), axis.get_y(), axis.get_z());
        gl_get_float_v(GL_MODELVIEW_MATRIX, OM);
    } gl_pop_matrix();
    move();
}

void move() {
    vector3<float> to_target = target - get_position();
    to_target.normalize();
    position += (get_forward() * speed);
}

The logic is simple, I find the rotation axis by cross product, the angle to rotate by dot product, then turn toward the target position each update. Unfortunately, it looks extremely odds since the rotation happens too fast that it always turns back and forth. The forward vector for torpedo is from the ModelView matrix, the third column A:

        MODELVIEW MATRIX
--------------------------------------------------
R           U           A           T
--------------------------------------------------
1           0           0           0
0           1           0           0
0           0           1           0
0           0           0           1
--------------------------------------------------

Any suggestion or idea would be greatly appreciated.

EDIT
In my current implementation, I don't have forward vector, the only vector I have is position. OM is my orientation matrix. In addition, I have my camera call to glu_look_at before any object update, that's the reason why I have to store all the transformation of object in OM and doing this allow me to check for collision easier. In short,
vector3<float> get_forward() : return the third column.
vector3<float> get_position() : return the forth column.
vector3<float> get_up_vector() : return the 2nd column.

And in my drawing routine,

void draw() {
    gl_push_matrix(); {
        // camera is set here ...
        // ...
        gl_mult_matrix_f(OM);
        // draw
    } gl_pop_matrix();
}


texts: convert world to screen coordinates with camera position and camera angle

texts:
Heyho :)
I'm trying to convert world coordinates to screen coordinates. I have available: fov, screen width, screen height, camera position, camera angle and obviously the position of the object in world space.
This is what I tried:
glm::vec3 world_to_screen(glm::vec3 pos,
                          glm::vec3 cam_angle,
                          glm::vec3 cam_pos) {
    glm::mat4 projection = glm::perspective(
        glm::radians(FOV), (float)SCREEN_W / (float)SCREEN_H, NEAR, FAR);

    glm::mat4 model(1.0);

    model = glm::translate(model, cam_pos);

    model = glm::rotate(model, cam_angle.x, glm::vec3(1.0f, 0.0f, 0.0f));
    model = glm::rotate(model, cam_angle.y, glm::vec3(0.0f, 1.0f, 0.0f));
    model = glm::rotate(model, cam_angle.z, glm::vec3(0.0f, 0.0f, 1.0f));

    glm::mat4 view = glm::inverse(model);

    glm::mat4 modelview = view * model;

    return glm::project(pos, modelview, projection,
                        glm::vec4(0, 0, SCREEN_W, SCREEN_H));
}

However it is not working, the output screen coords are over 30000 (I don't have a 30k monitor...) and I'm not sure what I did wrong.
There is a correlation though, sometimes the screen coords happen to be in my screen (I draw an indicator at the position to see if I did it right) and if the object moves the indicator also moves with (kinda) the same speed etc.
Help is very much appreciated :) Thanks a lot in advance!


texts: Moving a UI element with an object on-screen [Gamemaker]

texts:
I have an oPlayerobject, and an oTutorial object which has a DrawGUI event for displaying text on-screen.

Currently I have the text appearing at the top-left of the screen, but I would like the text to follow the oPlayer object around the room.

I have tried to set the x & y values in the DrawGUI event to the player's , but this does not have the desired effect; I imagine because the DrawGUI event doesn't occur every step.

Can anybody help?


texts:
I'm making a platformer built from mini-levels - and I want to create a sort of a replay of all the player tries that the player did for the level.

My question is - what is the best way to record the player's actions in-game, so that I could replay them later when he finishes the level.

I thought about recording only the player's input and replay them later on, each on a clone of the player.
The problem I have with this is with dynamic obstacles (that could be moved around) - if one clone moves them, it throws the simulation off for the rest of the clones.

So then I thought about recording every frame the X/Y of the player, and then just replay it - but that seems it could cause a major memory leak and very ineffective.

So - does anyone have any ideas? :)

EDIT:
As per the request in the comment, link showing said mechanic


texts:
In my game loop,

m_currentFrameTimestamp = glfwGetTime(); // Get the current timestamp
if ((m_currentFrameTimestamp - m_lastFPSDisplayTimestamp) >= 0.25) { // If 1/4 of a second
                                                         // passed, update the FPS counter
    double renderTime = m_currentFrameTimestamp - m_lastFrameTimestamp; // Frame time
    m_fps = (unsigned int)round(1 / renderTime); // FPS
    std::string title = "MyGame ["s;
    title += std::to_string(m_fps);
    title += " FPS]"s;
    glfwSetWindowTitle(m_window, title.c_str()); // The title
    m_lastFPSDisplayTime = m_currentFrameTime; // Reset the FPS update timer
}
m_lastFrameTime = m_currentFrameTime; // Reset the frame time timer

calculates the FPS from the frame time and displays it in the window title. However, with just this and glClear() above, the FPS displayed in the title is very unstable (with each FPS update, it changes from 46 FPS to 87 FPS and back), even though back in the initialization step, I enabled VSync, and my display's frequency is 60 Hz. Furthermore, using Fraps, I found out that the program actually runs at a stable 60 FPS. So, what's the problem with my FPS calculation code (more specifically, why is glfwGetTime() producing inaccurate results - my code, being way too simple, just can't be wrong, it's a very simple calculation that cannot give errors of any kind)?