texts: Problem with scrolling background in one OpenGL loop

texts:
I have 960x3000 map image in png and I'm scrolling it in a loop like this (it's called in 60 FPS loop):

glPushMatrix();
    glBindTexture( GL_TEXTURE_2D, mapTex[iBgImg]);
    glBegin(GL_QUADS);
    double mtstart = 0.0f - fBgVPos/(double)BgSize;
    double mtend = mtstart + mtsize;
    glTexCoord2d(0.0, mtstart); glVertex2f(fBgX, TOP_MARGIN);
    glTexCoord2d(1.0, mtstart); glVertex2f(fBgX + MAP_WIDTH, TOP_MARGIN);
    glTexCoord2d(1.0, mtend); glVertex2f(fBgX + MAP_WIDTH, BOTTOM_MARGIN);
    glTexCoord2d(0.0, mtend); glVertex2f(fBgX, BOTTOM_MARGIN);
    glEnd();
glPopMatrix();

unfortunately it isn't smooth when the game is in windowed mode. However, it is smooth in full screen mode. I'm using GLFW for windows. Maybe there is something wrong with my method? Is there anything better? Or could this be hardware problem?

Edit:
Window is created using

 glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);
 glfwOpenWindowHint(GLFW_REFRESH_RATE, 60);

and main loop is using glfwSwapInterval(1) to ensure 60 FPS;


texts:
I'm relatively new to game development and its terminology and I was wondering how to achieve the effect that is being used on the main character in this game:

http://youtu.be/XK7whzmywno?t=2m38s

To me, it looks like they animated at least 32 directions.
How do they do this? Is it simply creating 2-3 frames for each direction and animation or is there somekind of skewing/distortion technique involved?


texts: How do I optimize searching for the nearest point?

texts:
For a little project of mine I'm trying to implement a space colonization algorithm in order to grow trees.

The current implementation of this algorithm works fine. But I have to optimize the whole thing in order to make it generate faster. I work with 1 to 300K of random attraction points to generate one tree, and it takes a lot of time to compute and compare distances between attraction points and tree node in order to keep only the closest treenode for an attraction point.

So I was wondering if some solutions exist (I know they must exist) in order to avoid the time loss looping on each tree node for each attraction point to find the closest... and so on until the tree is finished.


texts: Is it possible to calculate the next speed of a ball knowing only dx and dy of the ball? For example if x = 120, y = 0, dx = -10, dx = 10, gravity = 0.05. So the next position of a ball (next update) is x = 110, y = 10. But a ball will be fall faster and faster under the influence of gravity. So is it possible to calculate next speed based on current x, y, dx and dy? My equation on next update of a ball x position should be x = x + dx * speed * gravity, but I haven't information about current speed, so I must calculate it every update.


texts:
I have a 2D level that I have built in my map editor, and I was wondering the best way to create a collision map for it.

I have a collision map layer in my map editor, which saves each node (for example, a rectangle would be just 0,0 0,50 50,60 0,60)

I was just wondering how I could take my node locations and convert it to a collision map for Unity.

Thanks!
I feel this has to be able to be done, I can think of how I would do it in flash... but I am not sure how to manipulate it in Unity.

EDIT PICTURE: So I have a node at each one of these red dots (surrounding my terrain lets say)  I want to build a collider from those nodes


texts: How to design 2D collision callback methods?

texts:
In a 2D game where you have a lot of possible combination of collision between objects, such as:

object A vs object B => object B vs A;

object A vs object C => object C vs A;

object A vs object D => object D vs A;

and so on ...

Do we need to create callback methods for all single type of collision? and do we need to create the same method twice? Like, say a bullet hits a wall, now I need a method to penetrate the wall for the wall, and a method to destroy the bullet for the bullet!!

At the same time, a bullet can hit many objects in the game, and hence, more different callback methods!!!

Is there a design pattern for that?


texts: How to move octree data correctly from parent to child?

texts:
This is my first question, so apologies if it is a repeat, I have had a look at the other questions and I still can't seem to find an answer to this.

So I am making a recursive octree in OpenGL. So far I have everything that I think should make up the octree correctly. If I draw all of the partitions (nodes) first (as in, through the constructor of the octree), the octree displays fully and correctly (with a depth level of 3).

However, I am wanting to add partitions only when I need them, I have cubes moving around inside the big root node and they bounce around inside and never leave. The problem I am having is trying to make the partitions appear if the maximum threshold of the nodes' items are exceed. Currently, it only works for the bottom left front node.

Here is where I think the problem is occuring, and also, where I am trying to dynamically add in partitions:

// Inserts data from the main function into here for checks.
void Node::Insert(Data* all_data)
{
    // If there are children.
    if (!nodes_.empty())
    {
        // Check to see if the data collides with the child node.
        Node* child_node = GetChild(all_data);

        // If the data does collide.
        if (child_node != NULL)
        {
            // Recurvisely call the insert function on data and the child node.
            child_node->Insert(all_data);
        }

    // If the amount of data exceeds the limit of the node.
    if (data_.size() >= MAX_ITEMS_)
    {
        // If we have not gone too deep into the octree already.
        if (depth_level_ < MAX_DEPTH_LEVEL)
        {
            // Split the current parent octant up into smaller child octants.
            Partition();

            // THE PROBLEM IS HERE.
            // THIS FOR LOOP DOES NOTHING.
            // Passing in the data from the parent node.
            // Iterate through all of the data in the parent node.
            for (auto node_data = data_.begin(); node_data != data_.end(); node_data++)
            {
                // See if any of the data collides with the NEW child node.
                Node* child_node = GetChild((*node_data));

                // If the data does collide with the NEW child node.
                if (child_node != NULL)
                {
                    // ACTUAL PROBLEM HERE.
                    // Push the data from the parent node into the child node respectively.
                    child_node->data_.push_back((*node_data));
                }
            }

            // Empty the data vector for the parent/this.
            data_.clear();
        }
    }

    // If there are no child nodes.
    // Push the data into the parent/this data vector.
    data_.push_back(all_data);
}

This is all inside of my "Insert(Data* data)" function, this function is called every frame on all of the cubes (data) bouncing around inside. Can anyone see what I am doing wrong? Or point me in the direction of some good material for insertion please? From testing, all I can tell is that the iterator shown above seemingly does nothing to the application.

Thanks.

EDIT: I am using Visual Studio 2013 with C++11.


texts: I accidently changed the cursor image in Unity

texts:
In the Unity Editor I accidently changed the image for the mouse cursor in project settings > player

How can I restore it to the default, preferably not through programming?


texts: Does installing the DirectX SDK add project templates to Visual Studio?

texts: I have Visual Studio 2013 installed on my machine, and I have installed the latest DirectX SDK, but it doesn't seem to have added any DirectX project templates to VS. Should it have? Or do I need to get them separately?


texts: LWJGL True Type Fonts - Calculate width and height of box

texts:
I want to center some text on the screen. At the moment I divide the display height and width by two, and then render. But I also need the height and width of the textbox, so I can subtract it from the box position, making it complete center.

As you can see the text is not in center.

How can I calculate the width and height of some text?

Edit: It's not a solution to multiply the font size by number of chars, as a 'W' is much wider than a '.'.


texts: Algorithm for dividing a 2D grid into organic looking plates

texts:
the title pretty much says it all:
How could one go about segmenting a 2D grid into smaller parts?
My goal here is to create tectonic plates for further procedural world generation

Details to consider:

The amount of parts should be controllable the resulting parts should
look "organic", meaning somewhat irregular, but still clumpy
the parts should wrap on the x and y axes

For now, I am using a random flood fill with as many starting points as I want plates.

Pseudocode would look a bit like this:

For 0 to plateAmount
   create a random seeding point and store point in each plates list of points.

While empty points exist in the grid,
   loop over each plate and add an adjacent, empty point to it.

This gives acceptable results, but takes very long! With 6 plates, a map of 100x100 tiles/points/cells takes 3 seconds, 200x200 takes 50 seconds, 500x500 takes forever. The more plates, the quicker it is.

Is there a quicker way to get a good result? Maybe something with Voronoi?

My result with 60x60 cells, 10 plates, each cell is 10x10 pixels. Ignore the "height" text, it displays not-yet-visualized data from the cell the mousecursor hovers over


texts: How to calculate max region/area of 2d circles?

texts:
I have some 2d circles on a plane, each has its own minRadius and maxRadius. When two circles collides, both of them will shrink their radius, so the actual radius of a circle is in range [minRadius, maxRadius].

I need to calculate the max possible radius of each circle. See below image for an example.

Currently, I use the following algorithm to calculate the radius of each circle.
I try to increase each circle's radius a little each steps, then check and solve if there is any collisions.

foreach c in circles: c.radius = c.minRadius;

for (int i = 0; i < 10000; ++i)
{
  foreach c in circles: c.radius = c.radius + 1
  foreach c in circles: calculate_radius(c)
}

function calculate_radius(c)
  collides = find_all_circles_which_radius_is_overlap_with_c()

  foreach x in collides {
    x.radius -= somevalue;
    c.radius -= somevalue;
  }
end

For now, the result looks fine, but the algorithm costs too much time.

So I wonder if there exists other ways to solve it?

=======================================================

@wondra counterexample(maybe)

The image below illustrates the problem.

From my understanding of your algorithm, the final radius of circle A is 1.6, the calculation sequence is (BC, AB, AD)

But if using my algorithm(increase radius by a small amount each step), the final radius of circle A is 1.5.

I don't think recalculate the dist matrix after each selection will solve the problem, as stated in my question, each circle may have its own minRadius and max Radius.


texts:
I am trying to give an object a velocity spread (e.g. shotgun bullets or particle effect).

//dir is the initial direction
float angle1 = atan(dir.x, dir.z) + spread;
float angle2 = atan(dir.y, abs(dir.z)) + spread;
vec3 xz_dir = vec3(sin(angle1, 0.0, cos(angle2));
vec3 yz_dir = vec3(0.0, sin(angle2), cos(angle2));
vec3 new_dir = vec3(xz_dir.x * yz_dir.z, yz_dir.y, xz_dir.z * yz_dir.z);
new_dir.normalize();

The new_dir spread works fine in the XY and YZ planes but if there is a Y component in the direction, the spread along the XY plane doesn't work.


texts:
I'm developing a portal-based scene manager. Basically all it does is to check the portals against the camera frustum, and render their associated portal zones accordingly.
Is there any way my editor can generate portal zones automatically with the user having to set the portals themselves only? For example, the Max Payne 1/2 engine ("Max-FX") only required to set the portal quads, unlike the C4 engine where you also have to explicitly set the portal zones.


texts: Playing an animation all the way through with one quick keypress with Mechanim Unity

texts:
I have an if statement inside of the Update function that is only called if three other conditions are met. The problem is that right now the function sets a boolean to true which causes the animation to play inside of unity Mechanim. This boolean is only true when I hold down the button, but I would like it to play the whole animation or keep this boolean true for a certain amount of time, thanks and here is my Code.

    //Running and jumping animation
    if (Input.GetKey (KeyCode.W) && (Input.GetKey (KeyCode.Space)) && otherAnimation == false) {
        anim.SetBool ("isRunningAndJumping", true);
    }
    else {
        //anim.SetBool ("isRunningAndJumping", false);
    }


texts:
I'm trying to perform ray triangle intersection on a mesh made of triangles. The below code seems to work fine but only about 50% of the time. The ray often gets into positions where no intersection is detected when there definitely should be. Is there something wrong in my function that isn't checking for intersection under all circumstances.

bool rayTriangleIntersect(Vector3 rayOrigin,
                          Vector3 rayDirection,
                          Vector3 vert0,
                          Vector3 vert1,
                          Vector3 vert2,
                          ref Vector3 intersectionPosition)
{
    // this originally comes from http://www.graphics.cornell.edu/pubs/1997/MT97.pdf

     float u, v, t, det, inv_det;
     Vector3 edge1, edge2, pvec, tvec, qvec;

    Vector3 direction = rayDirection;
    direction.Normalize();
    t = v = u = 0f;
    edge1 = vert1 - vert0;
    edge2 = vert2 - vert0;
    pvec = Vector3.Cross(direction, edge2);
    det = Vector3.Dot(edge1, pvec);

    if (det > -0.00001f)
        return false;

    inv_det = 1.0f / det;
    tvec = rayOrigin - vert0;
    u = Vector3.Dot(tvec, pvec) * inv_det;

    if (u < -0.001f || u > 1.001f)
        return false;

    qvec = Vector3.Cross(tvec, edge1);
    v = Vector3.Dot(direction, qvec) * inv_det;

    if (v < -0.001f || u + v > 1.001f)
        return false;

    t = Vector3.Dot(edge2, qvec) * inv_det;

    float rayMagnitude = rayDirection.magnitude;

    if (t <= 0f || t >= rayMagnitude)
        return false;

    intersectionPosition = rayOrigin + (rayDirection * (t / rayMagnitude)); // percent along ray

    return true;
}

and im calling it with

for (z = 0; z < LENGTH - 1; z++)
{
     for (x = 0; x < WIDTH - 1; x++)
     {
           v0 = verts[(z * WIDTH) + x];
           v1 = verts[((z + 1) * WIDTH) + x];
           v2 = verts[(z * WIDTH) + x + 1];
           v3 = verts[((z + 1) * WIDTH) + x + 1];

           if(rayTriangleIntersect(rayOrigin, rayDirection, v0, v1, v2, ref intersectPosition) ||
              rayTriangleIntersect(rayOrigin, rayDirection, v1, v2, v3, ref intersectPosition))
           {
                 Debug.log(Intersection found at : " intersectPosition);
           }
    }
}

I'm really stuck on this one so any guidance would really be appreciated.

Edit

The triangle are defined like this:

 for (z = 0; z < LENGTH - 1; z++)
   {
        for (x = 0; x < WIDTH - 1; x++)
        {
            triangles[index++] = (z * WIDTH) + x;
            triangles[index++] = ((z + 1) * WIDTH) + x;
            triangles[index++] = (z * WIDTH) + x + 1;

            triangles[index++] = ((z + 1) * WIDTH) + x;
            triangles[index++] = ((z + 1) * WIDTH) + x + 1;
            triangles[index++] = (z * WIDTH) + x + 1;
        }
    }


texts:
I've started to do sth. with SDL/openGL, but I haven't managed to get this tutorial running yet (http://www.sdltutorials.com/sdl-opengl-tutorial-basics).

Since this tutorial, or most tutorials at all, are  written in SDL 1.2, I  changed just this part of the tutorial's code:

instead of:

if((Surf_Display = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE | SDL_GL_DOUBLEBUFFER | SDL_OPENGL)) == NULL)

to:

SDL_Window *window;
if((window = SDL_CreateWindow("SDLWindow", SDL_WINDOWPOS_UNDEFINED,
                              SDL_WINDOWPOS_UNDEFINED,
                              640, 480,
                              SDL_GL_DOUBLEBUFFER | SDL_WINDOW_OPENGL)) == NULL)

Now, all parts of the code seem to be correctly except the last one, this is "SDL_GL_SwapBuffers()";

Xcode says: use of undeclared identifier....

I think it's deprecated in SDL 2.0, but I couldn't find the right function in the migration guide, or is the problem something else?

Can anyone help me with that?


texts: How to extend Tiled and Cocos2d to create an Isometric map that supports elevation

texts:
I've been looking and looking and looking, and I cannot seem to find a solution out there for making a game that uses cocos2d and Tiled to make an isometric map that supports elevation.

I am not looking for anything super complex...

Just maybe 2 or 3 levels of elevation. (Think X-Com UFO Defense, or Final Fantasy Tactics)

I figure that since I've been unable to find a solution, I'll probably have to extend Tiled or something to support this.

For now I'll just stick with level of elevation, but I want to extend the game to support elevation eventually.

Will you share with me any good resources that you know? Where should I read to better understand how to accomplish such a thing?


texts: How can I provide access cheat codes or diagnostics for a tap-only mobile game?

texts:
I'd like to build several cheat-like commands into my game, mainly for debugging problems that could only be reproduced on the end-user's side.

For most games this would be trivial: just listen to a keyboard shortcut or two, but my game is a 'tap-only' mobile game. How can I go about providing access to these sorts of diagnostic commands with such a limited user interface in a way that will remain accessible to end-users but that they'd be unlikely to trigger automatically?


texts:
I've read about this topic on numerous discussion sites, but I can't seem to find a clear definitive (up-to-date) answer, and hopefully this will me some more insight:

I've read the excellent game loop time article on Fix your timestep!, but it dosn't take any consideration of the CPU usage, so it will run at 100%. My question then, is it BAD to run at 100% CPU in your game loop?

If no, why? for example what about gaming on battery-driven devices like laptops? what about computer temperatures/fans/etc, and other windows applications?
If yes, why dosn't the article mention it, because surely that would impact it significantly? what is the best way to fix this on desktops/PC - is there only the unreliable sleep()? How would it affect the game loop suggested by the article?


texts:
I have many sensors(coins) in each level and I want to remove the sensors(coins) when the player rectangle(Mario) touches them. I check in OnCollision if Mario touches a coin, if he touches it, it should be removed. But I don't know how to remove a body.

What is the best way to remove a body?

How can I remove a coin in this example?

bool Player_OnCollision(Fixture fixtureA, Fixture fixtureB, FarseerPhysics.Dynamics.Contacts.Contact contact)
    {
      if (fixtureB.CollisionCategories == Category.Cat10)
        {

        }
        return true;
    }

 coinrect = BodyFactory.CreateRectangle(world, 0.64f, 0.64f, 1.0f);
 coinrect.BodyType = BodyType.Static;
 coinrect.Position = new Vector2(1.60f, 4.16f);
 coinrect.CollisionCategories = Category.Cat10;

 coinrect2 = BodyFactory.CreateRectangle(world, 0.64f, 0.64f, 1.0f);
 coinrect2.BodyType = BodyType.Static;
 coinrect2.Position = new Vector2(2.60f, 3.16f);
 coinrect2.CollisionCategories = Category.Cat10;

 playerrect = BodyFactory.CreateRectangle(world, 0.64f, 0.64f, 1.0f);
 playerrect.BodyType = BodyType.Dynamic;
 playerrect.Position = new Vector2(0.22f, 0f);
 playerrect.FixedRotation = true;

 playerrect.OnCollision += Player_OnCollision;


texts:
I have a model created in Blender for a character with a sprite as a child of the character that I would like to animate. I'm making a turn based strategy game in which I would like to be able to click a character and turn on a "selection circle" beneath the character, much like the way a circle appears underneath a selected unit in games like Star Craft. The selecting of the character(the circle turning on/off) works fine. However, I have a 32 sprite animation that I would like to apply to the selection circle to give it a bit more life. The steps I've take are as follows:

I put my character into the scene

I add the selection circle sprite to the character as a child

I add an animation & animator component to the selection circle

I open the animation window and create a new clip

I drag my 32 sprite sheet to the window

I make sure the "play automatically" check box is selected

When I play the animation in the editor it works fine, but at run time the animation is not present, only a single sprite appears when I select my character. I've noticed that there is warning that appears in the console that says "animation must be marked as legacy" there are about a bazillion questions on here already explaining how to fix this... I.E. Change to debug mode and change animation type to 1(Legacy). I do not see this option anywhere in the inspector when I have the sprite selected. I can change to debug mode but there is nothing under the heading or an component that resembles animation type. I'm using Unity 5. Please, any help would be appreciated.


texts: How should I account for the GC when building games with Unity?

texts:
*As far as I know, Unity3D for iOS is based on the Mono runtime and Mono has only generational mark & sweep GC.

This GC system can't avoid GC time which stops game system. Instance pooling can reduce this but not completely, because we can't control instantiation happens in the CLR's base class library. Those hidden small and frequent instances will raise un-deterministic GC time eventually. Forcing complete GC periodically will degrade performance greatly (can Mono force complete GC, actually?)

So, how can I avoid this GC time when using Unity3D without huge performance degrade?


texts: Lag compensation of projectile shooting game

texts:
I'm thinking about an algorithm for firing projectiles with lag compensation. Now I did find only one descent solution:

Player hits fire button.
Client sends input "fire".
Client waits for server response.
Server generates bullet then sends response to client.
Client recieves response and finally fires projectile.

Is this solution only "trueway"? I find it the only one that can be fair to all of the clients. Valve in this case, doesn't compensate lag from rocket shots. I am feeling that I will not compensate it, too. I think that with today's bandwidth I can close my eyes on this problem, because I don't see any solutions with fair logic. What do you think?


texts: Permanent Adjacency Problem [Gamemaker Studio]

texts:
Situation: I started work on a pet project recently. It's a bit like Puzzlecraft, or Bejewled, but slightly different. You click one gem, as we'll call it, and if it's the first in the link, then it's added to the link.

That works well enough. However, the problem comes in that after that, in order to link, it must be adjacent to the last link... and somehow, something goes wonky. The first time you click something not adjacent, it doesn't get put on the link...or it at least doesn't highlight. It also doesn't run across any of my show_message popups - aside from "second else".

Yet, somehow, it seems to act as though that one you clicked on was the Last_Link, after that point...permanently...which shouldn't even be possible...

So, if you click adjacent to the one that got to "second else", it will still consider that "adjacent", even if it's across the entire board from the last one that actually highlighted.

And this permanent allocation of Last_Link can happen for every gem on the board. At the same time. (Note: It does deallocate once you restart the program.)

This DOESN'T make sense!

I have no step events (yet). This is also the only left click event in the game at the moment. Every other event is a create or game start event, mostly for initialization purposes. So I have no idea what is doing this. Can someone tell me?

Left Click Event for the Gems

if (obj_Handle_Links.Match_Length = 0) //if this would be the first in the link
{
    show_message("first to link");
    obj_Handle_Links.Match_Length +=1; //because we're increasing the length
    image_index = 1; //this should highlight
    //add to link, later
    show_message( Matrix_Location_y );
    obj_Handle_Links.Last_Link = id; //makes it so this is what's seen as last link
    show_message(obj_Handle_Links.Last_Link.Matrix_Location_y);
}
else
{
    // show_message("first else");
    //check if the target is the same type as the last Link's type
    if(obj_Handle_Links.Last_Link.Type = Type &&
        //check if the last link in the chain is adjacent to the target link
        //includes diagonals
         (obj_Handle_Links.Last_Link.Matrix_Location_y = (Matrix_Location_y-1)
         || obj_Handle_Links.Last_Link.Matrix_Location_y = (Matrix_Location_y+1)
         || obj_Handle_Links.Last_Link.Matrix_Location_x = (Matrix_Location_x-1)
         || obj_Handle_Links.Last_Link.Matrix_Location_x = (Matrix_Location_x+1)) )
        {

            show_message( Matrix_Location_y );
            //show_message("third if");
            obj_Handle_Links.Match_Length +=1; //because we're increasing the length
            image_index = 1; //this should highlight
            //add to link, later
            obj_Handle_Links.Last_Link = id; //makes it so this is what's seen as last link
           show_message(obj_Handle_Links.Last_Link.Matrix_Location_y);
         }
    else{

        show_message("second else");
        //play sound that link failed
    }
}


texts: Would A* or Dijkstra be more proper for a grid-based tactics game?

texts:
In a grid-based tactical game (think Fire Emblem), would A* or Dijkstra be more proper for finding a path to use for enemy AI to determine the best place to move?

A* has a better performance that Dijkstra, however Dijkstra may offer me better/smarter looking results for an AI.

If possible, I'd like to have the answer for both a hexagon based grid, and a rectangle based grid, if it'll make a difference.


texts: SpriteKit - How to jump to specific position?

texts:
I'm would like to achieve something like Object A will jump to position A in parabolic way. For example:

I am able to make the object jump but i do not know how to calculate to make the object jump to the precise location.


texts:
I want to make a few simple databases for a sports game using Unity2D(C#).

One is a read-only google sheet where it takes the players from the pool and adds them into the game at the start.

Another one is a read and write database  where all 30 team's players will be saved as well as current stats( a lot of numbers), I don't know if i should make this online or local saves. I want to keep the cost at a minimal.

Generally new to making databases, can someone point me in the right direction?


texts: Aim at moving target (or predicting target's position at time it takes for projectile to hit it)

texts:
I have a game where I know the location and velocity of my target. I know my own location and the speed of my projectile. I want to determine either

the location of the intersection between my projectile fired and the target, or

the time taken for my projectile to intersect the target

All entities are travelling with constant speed and direction which makes life easier. I have been trying to work out the maths for some time but cannot quite get it right. I know that the predicted location of the target intersecting the projectile will be

Pp = Tp + Tv * t

Where Pp is the predicted position, Tp is the current target position, Tv is the target velocity, and t is time.

I also know that

t = |Pp - Sp| / Bs

where Sp is my (source) position and Fs is the projectile (bullet) speed. But I cannot figure out a way to solve this to get either Pp or t.

I know that all speeds are constant. I am free to aim in any direction and I know that the projectile is faster than the target therefore a hit is guaranteed

Can anyone enlighten me? Thanks

I found a website detailing one method but this doesnt seem to work (http://howlingmoonsoftware.com/wordpress/leading-a-target/). My verification method to determine if it worked was to use the predicted position to determine the time for the target to reach it, and for the projectile to reach it. These should be very similar but in my game they are out by almost a factor of 2.


texts: Can't export Blender model for use in jMonkeyEngine SDK

texts: I have a scene rendered in blender called "civ1.blend" which contains multiple materials (for example, I have one called "white"). I want to use this model in jMonkeyEngine, so I used the OGRE exporter to create .scene and .material files. This gives me, for example, a civ1.scene file and a white.material file.However, when I then try to import civ1.scene into the jMonkeyEngine SDK, I get an error along the lines of "Cannot find material file 'civ1.material'". Like I said, I have a white.material file, but I do not have a civ1.material file. Did anyone encounter this problem? How do I fix this?


texts: Generate a 2d mesh terain out of triangles (low details)

texts:
I'd like to learn a good algorithm to generate a 2d mesh made out only of triangles to be used as a terrain.

Its not important to get a high detail terrain. It should just have a triangle looking style.

Also the mesh should be extendable endlessly in all directions because the map will be endless. I thought about to having chunks of meshes saved in a file so they can be loaded during the execution.

Something like this (from Chasing Aurora):


texts: How to handle RTS Click-And-Move in 3D Space?

texts:
How can I handle the click-and-move in a complete 3D space? It is easy to handle on a 2D plane by a simple raycast, but this is not the case in 3D since there is no end-plane for a raycast to get an end-point.

I have two ideas in mind:

Do raycast, then allow player to select distance on the ray by another input (mousewhell, for example).
Instead of complete 3D, have multiple "layers of height", so player can change the height layer before ordering the move.

What are your thoughts?


texts: Is it unethical to make a game AI that is secretly non-competitive?

texts:
In several games the AI is designed to give the player an easy time without their knowledge. This can be having a 0% chance to hit the first time you appear, enemy letting you sneak up on them by not turning around, or the lowering of difficulty when the player is hurt or has restarted several times.

I would be offended if at the end of a board game or sport I was told that a human had not tried their hardest.

Does the same ethics exist for an AI?

edit
As in the title, my main concern was keeping the handicap hidden from the player, for example, when playing a shooter it is reasonable to expect the player knows the AI has an artificial reaction time and poor aim but my question was about games that hide things such as enemies not using the best weapon or lowering their difficulty when the player is inured.


texts: Box2d based tile map game scrolling problem

texts:
I am using a tile based game and also used a joystick. Using joystick sprite body move perfectly but tile map can not scroll.

-(void)setCenterOfScreen:(b2Vec2)position
{
    int x=MAX(position.x*PTM_RATIO, size.width/2);
    int y=MAX(position.y*PTM_RATIO, size.height/2);

    int x1=MIN(x, (theMap.mapSize.width * theMap.tileSize.width-size.width/2));
    int y1=MIN(y, (theMap.mapSize.height * theMap.tileSize.height-size.height/2));

    b2Vec2 goodpoint=b2Vec2(x1,y1);
    NSLog(@"GoodPoint X: %f",goodpoint.x);
    NSLog(@"GoodPoint Y: %f",goodpoint.y);

    b2Vec2 differ=b2Vec2((size.width/2-goodpoint.x),(size.height/2-goodpoint.y));
    position=differ;
}

Is it true logic?
Please help me

Thanks in advance


texts: Why does my character move up forever when he jumps with this code?

texts:
I've been doing some stupid stuff in Slick2D+LWJGL and I've run into a problem.
I press the UP arrow and my character continues to go up until I let go :/
Here's the code:

if (inp.isKeyDown(Input.KEY_UP) && !jumping) {
    jumping = true;
    velY=-0.4f;
} else {
    jumping = false;
    velY=0.2f;
}

No idea what's happening :/ Help?


texts: How to progress an entity-component gamestate in a turn-based game?

texts:
So far the entity component systems I've used have worked mostly like Java's artemis:

All data in components
Stateless independent systems (at least to the degree that they don't require input on initialization) iterating over each entity that contains only the components that particular system is interested in
All systems process their entities one tick, then the whole thing starts over.

Now I'm trying to apply this to a turn based game for the first time, with tons of events and responses that must occur in a set order relative to eachother, before the game can move on. An example:

Player A receives damage from a sword. In response to this, A's armor kicks in and lowers the damage taken. A's movement speed is also lowered as a result of getting weaker.

The damage taken is what sets off the whole interaction
Armor must be computed and applied to the incoming damage before the damage is applied to the player
Movement speed reduction cannot be applied to a unit until after the damage has actually been dealt, since it is dependent on the final damage amount.

Events can also trigger other events. Reducing sword damage using armor can cause the sword to shatter (this must take place before the damage reduction is completed), which in turn can cause additional events in response to it, essentially a recursive evaluation of events.

All in all, this seem to lead to a few problems:

Lots of wasted processing cycles: Most systems (save for things that always run, like rendering) simply doesn't have anything worthwile to do when it's not "their turn" to work, and spend most of the time waiting for the game to enter a valid work-state. This litters every such system with checks that keep growing in size the more states are added to the game.
To find out if a system can process entities that is present in the game, they need some way to monitor other unrelated entity/system states (the systaem responsible for dealing damage needs to know if armor has been applied or not). This either muddles the systems with multiple responsibilities, or creates the need for additional systems with no other purpose but to scan the entity collection after each processing cycle and communicate with a set of listeners by telling them when it's okay to do something.

The above two points assume that the systems work on the same set of entities, that end up changing state using flags in their components.

Another way to solve it would be to add/remove components (or create entirely new entities) as a result of a single systems work to progress the games state. This means that whenever a system actually have a matching entity, it knows that it is allowed to process it.

This however make systems responsible for triggering subsequent systems, making it difficult to reason about the programs behaviour since bugs won't show up as the result of a single system interaction. Adding new systems also gets harder since they can't be implemented without knowing exactly how they affect other systems (and previous systems might have to be modified to trigger the states the new system is interested in), kinda defeating the purpose of having separate systems with a single task.

Is this something I'll have to live with? Every single ECS example I've seen have been real time, and it's really easy to see how this one-iteration-per-game-loop works in such cases. And I still need it for rendering, it just seems really unfit for systems that pause most aspects of itself every time something happens.

Is there some design pattern for moving the game state forward that is suitable for this, or should I just move all logic out of the loop and instead trigger it only when needed?


texts:
I have a Model named cube to which I load in LoadContent(): cube = Content.Load<Model>("untitled");.

In the Draw Method I call DrawModel:

    private void DrawModel(Model m, Matrix world)
    {
        foreach (ModelMesh mesh in m.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.EnableDefaultLighting();
                effect.View = camera.View;
                effect.Projection = camera.Projection;
                effect.World = world;
            }
            mesh.Draw();
        }
    }

camera is of the Camera type, a class I've setup.  Right now it is instantiated in the initialization section with the graphics aspect ratio and the translation (world) vector of the model, and the Draw loop calls the camera.UpdateCamera(); before drawing the models.

class Camera
{
    #region Fields
    private Matrix view; // View Matrix for Camera
    private Matrix projection; // Projection Matrix for Camera
    private Vector3 position; // Position of Camera
    private Vector3 target; // Point camera is "aimed" at
    private float aspectRatio; //Aspect Ratio for projection
    private float speed; //Speed of camera
    private Vector3 camup = Vector3.Up;
    #endregion

    #region Accessors
    /// <summary>
    /// View Matrix of the Camera -- Read Only
    /// </summary>
    public Matrix View
    {
        get { return view; }
    }
    /// <summary>
    /// Projection Matrix of the Camera -- Read Only
    /// </summary>
    public Matrix Projection
    {
        get { return projection; }
    }
    #endregion

    /// <summary>
    /// Creates a new Camera.
    /// </summary>
    /// <param name="AspectRatio">Aspect Ratio to use for the projection.</param>
    /// <param name="Position">Target coord to aim camera at.</param>
    public Camera(float AspectRatio, Vector3 Target)
    {
        target = Target;
        aspectRatio = AspectRatio;
        ResetCamera();
    }

    private void Rotate(Vector3 Axis, float Amount)
    {
        position = Vector3.Transform(position - target, Matrix.CreateFromAxisAngle(Axis, Amount)) + target;
    }

    /// <summary>
    /// Resets Default Values of the Camera
    /// </summary>
    private void ResetCamera()
    {
        speed = 0.05f;
        position = target + new Vector3(0f, 20f, 20f);
        projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, 0.5f, 100f);
        CalculateViewMatrix();
    }

    /// <summary>
    /// Updates the Camera.  Should be first thing done in Draw loop
    /// </summary>
    public void UpdateCamera()
    {
        Rotate(Vector3.Right, speed);
        CalculateViewMatrix();
    }

    /// <summary>
    /// Calculates the View Matrix for the camera
    /// </summary>
    private void CalculateViewMatrix()
    {
        view = Matrix.CreateLookAt(position,target, camup);
    }

I'm trying to create the camera so that it can orbit the center of the model.  For a test I am calling Rotate(Vector3.Right, speed); but it rotates almost right but gets to a point where it "flips."  If I rotate along a different axis Rotate(Vector3.Up, speed); everything seems OK in that direction.

So I guess, can someone tell me what I'm not accounting for in the above code I wrote?  Or point me to an example of an orbiting camera that can be fixed on an arbitrary point?


texts: Why are textures always square powers of two? What if they aren't?

texts:
Why are the resolution of textures in games always a power of two (128x128, 256x256, 512x512, 1024x1024, etc.)? Wouldn't it be smart to save on the game's file size and make the texture exactly fit the UV unwrapped model?

What would happen if there was a texture that was not a power of two?

Would it be incorrect to have a texture be something like 256x512, or 512x1024? Or would this cause the problems that non-power-of-two textures may cause?


texts: how to get the function work without update

texts:
I was working on Lerp on arrays of Vector3, i want this function to work without update function(like using loops) i am not getting how to implement it.

public class MoveTowards : MonoBehaviour {

    int currentStartPoint;
    private Vector3 startMarker, endMarker;
    public float speed = 1.0F;
    private float startTime;
    private float journeyLength;
    public float smooth = 5.0F;
    List<Vector3> tempPositionList = new List<Vector3>();
    List<Vector3> positionList = new List<Vector3>
        {
            new Vector3(4,0,0),
            new Vector3(4,0,2),
            new Vector3(4,0,4),
            new Vector3(2,0,4),
            new Vector3(0,0,4),
            new Vector3(-2,0,4),
            new Vector3(-4,0,4),
            new Vector3(-4,0,2),
            new Vector3(-4,0,0),
            new Vector3(-4,0,-2),
            new Vector3(-4,0,-4),
            new Vector3(-2,-0,-4),
            new Vector3(0,0,-4),
            new Vector3(2,0,-4),
            new Vector3(4,0,-4),
            new Vector3(4,0,-2),
            new Vector3(2,0,-2),
            new Vector3(0,0,-2),
            new Vector3(-2,0,-2),
            new Vector3(-2,0,0),
            new Vector3(-2,0,2),
            new Vector3(0,0,2),
            new Vector3(2,0,2),
            new Vector3(2,0,0),
            new Vector3(0,0,0)
        };
    void Start()
    {
        currentStartPoint = 0;
        SetPoints();
    }
    public void SetPoints()
    {
        startMarker = positionList[currentStartPoint];
        endMarker = positionList[currentStartPoint + 1];
        startTime = Time.time;
        journeyLength = 2;
    }

    void Update()
    {
        Debug.Log(positionList.Count);
        float distCovered = (Time.time - startTime) * speed;
        float fracJourney = distCovered / journeyLength;
        transform.position = Vector3.Lerp(positionList[currentStartPoint], positionList[currentStartPoint + 1], fracJourney);
        if (fracJourney >= 1f && currentStartPoint + 1 < positionList.Count)
        {
            currentStartPoint++;
            SetPoints();
        }
    }
}


texts:
I am using Assimp asset importer (http://assimp.sourceforge.net/lib_html/index.html) to parse 3d models.

So far, I've simply pulled out the normal vectors which are defined for each vertex in my meshes. Yet I have also found various tutorials on normal maps...

As I understand it for normal maps, the normal vectors are stored in each texel of a normal map, and you pull these out of the normal texture in the shader.

Why is there two ways to get the normals, which one is considered best-practice and why?


texts: How to place the origin of an isometric map at the top, not the left

texts:
I have an isometric diamond-shaped map. Currently my map origin is to the far left, instead of the top.

The green circle at the top-center of the map is where I want the origin point to be, however the red circle on the far left is where it currently is now.

Basically when I walk "up" in my game, my x coordinates increase, where I would want them to decrease.

So far in my code I load in a text file with the following format

1 5 5 5 2
8 9 9 9 6
8 9 9 9 6
3 7 7 7 4

It's loaded with infile into a pointer of ints, from left to right, disregarding columns.

The edges and corners of the map above, are sides and corners of tiles - the middle (9) is a grass tile, that is walkable.

Here is how I get map segments of x and y (Terrain codes according to tileset):

int world_map::get_map_segment_x(int code) {
    if (code == 1) return 0;
    if (code == 2) return 64 * 3;
    if (code == 3) return 64 * 0;
    if (code == 4) return 64 * 3;
    if (code == 5) return 64 * 2;
    if (code == 6) return 64 * 1;
    if (code == 7) return 64 * 2;
    if (code == 8) return 64 * 2;
    if (code == 9) return 64 * 1;
    if (code == 10) return 64 * 3;
    if (code == 11) return 64 * 1;
    if (code == 12) return 64 * 2;
    if (code == 13) return 64 * 0;
    if (code == 14) return 64 * 3;
    if (code == 15) return 64 * 2;
    return 0;
}

int world_map::get_map_segment_y(int code) {
    if (code == 1) return 32 * 10;
    if (code == 2) return 32 * 7;
    if (code == 3) return 32 * 9;
    if (code == 4) return 32 * 9;
    if (code == 5) return 32 * 9;
    if (code == 6) return 32 * 8;
    if (code == 7) return 32 * 10;
    if (code == 8) return 32 * 7;
    if (code == 9) return 32 * 6;
    if (code == 10) return 32 * 6;
    if (code == 11) return 32 * 7;
    if (code == 12) return 32 * 6;
    if (code == 13) return 32 * 1;
    if (code == 14) return 32 * 10;
    if (code == 15) return 32 * 8;
    return 0;
}

Here is my world_map::render function

void world_map::render(int screen_width, int screen_height, float x, float y, int sprite_count) {
    int surroundings = 0;
    for (int row = surroundings; row < 20 + surroundings; row++) {
        for (int col = surroundings; col < 20 + surroundings; col++) {

            if (row >= 0 && row < 20 && col >= 0 && col < 20) {
                al_draw_bitmap_region(this->terrain, get_map_segment_x(map[2 * 20 * row + 2 * col]), get_map_segment_y(map[2 * 20 * row + 2 * col]), SPRITE_WIDTH, 32,
                     -32 / 2 + screen_width / 2 + (row - y) * 32 + (col - x) * 32, 64 - SPRITE_HEIGHT / 2 + screen_height / 2 + (row - y) * 16 - (col - x) * 16, get_map_segment_flag(map[40 * row + 2 * col]));
                    //-32 / 2 + width / 2 + (row - y) * 32 + (col - x) * 32, 64 - SPRITE_HEIGHT / 2 + height / 2 + (row - y) * 16 - (col - x) * 16, get_map_segment_flag(map[40 * row + 2 * col]));
            }
            else {
                al_draw_bitmap_region(this->terrain, get_map_segment_x(1), get_map_segment_y(1), SPRITE_WIDTH, SPRITE_HEIGHT,
                    -SPRITE_WIDTH / 2 + screen_width / 2 + (row-y) * 32 + (col-x) * 32, 64-SPRITE_HEIGHT / 2 + screen_height / 2 + (row-y) * 16 - (col-x) * 16, get_map_segment_flag(1));
            }
        }
    }
}

x & y parameters in render function are player x & y coordinates

If any more information is needed, please let me know, this has been bugging me for hours :(


texts: Smooth moving on tile-based map, how to fix simple collisions?

texts:
I've already had some experiences about the work of 2 dimensional square-based playfields and moving a player on them. Though, when a square has multiple pixel sizes, and player moves e.g. 1 pixel per frame, I have some problems. Currently, my program counts the coordinates of tile Player stands on like this:

Tile X coordinate = floor of Player X coordinate divided by the X size of a tile
a.k.a TileX = floor(PlayerX/TileXsize)

and same for Y. However, when I increase the moving speed to bigger px/frame speed, sometimes the player sinks into the tile that should stop it. How can I prevent this problem?

EDIT: codes. Language is Lua, framework is LOVE2D, gamefield is stored in tables. Player has an X, an Y, and Tilex&TileY, count this way on every frames:

Player.TileX = math.floor((Player.X)/TileSize)
Player.TileY = math.floor((Player.Y)/TileSize)

Moving belongs to key actions, they are simply like Player.X = Player.X + 1

There's a Gravity function as well, called on every frames:

function Gravity()
    if not Solidchecker(Field[Player.TileX][Player.TileY+1]) then
        Player.Y = Player.Y +GForce
    end
end

In case of anyGforce (which is a constant) where value is different from the size of the tile (24) the player sinks into the ground. Obviously in that case, everythings the same as if the system would be counted with only tiles, without separated Player.TileX calculations. Otherwise, it can't handle the occuring alignment.

Possibly I forgot showing some code parts, but I can't see now that any other functions would influence these variables.


texts: How to make a Unity3d program/plugin and publish it on Asset Store?

texts: I want to make a plugin for Unity3d, like TornadoTwins's FPS Control. How can I do that? I already have Visual Studio 2010 installed.


texts: How do I rotate an object back and forth?

texts:
I want my object to rotate between two angles in relation to speed and it doesn't need to be a smooth rotation, how can I achieve that?

Thank you in advance.


texts:
I'm already half a year into planning a Turn Based Strategy (4X) game for mobile phones.
Recently I tried to play Civilization 6 and while playing, totally horrified, I realized that my idea and Civ 6 are very, very similar.
So what should I do? Do you recommend that I should change elements that are too similar, or create game I planned, not looking at similarities to Civ 6?
Could there be any legal consequences due to similarity of those two games?


texts: Best depth sorting method for a Top Down 2D game using a 3D physics engine

texts:
I've spent many days googling this and still have issues with my game engine I'd like to ask about, which I haven't seen addressed before.  I think the problem is that my game is an unusual combination of a completely 2D graphical approach using XNA's SpriteBatch, and a completely 3D engine (the amazing BEPU physics engine) with rotation mostly disabled.

In essence, my question is similar to this one (the part about "faux 3D"), but the difference is that in my game, the player as well as every other creature is represented by 3D objects, and they can all jump, pick up other objects, and throw them around.

What this means is that sorting by one value, such as a Z position (how far north/south a character is on the screen) won't work, because as soon as a smaller creature jumps on top of a larger creature, or a box, and walks backwards, the moment its z value is less than that other creature, it will appear to be behind the object it is actually standing on.

I actually originally solved this problem by splitting every object in the game into physics boxes which MUST have a Y height equal to their Z depth.  I then based the depth sorting value on the object's y position (how high it is off the ground) PLUS its z position (how far north or south it is on the screen).

The problem with this approach is that it requires all moving objects in the game to be split graphically into chunks which match up with a physical box which has its y dimension equal to its z dimension.  Which is stupid.

So, I got inspired last night to rewrite with a fresh approach.  My new method is a little more complex, but I think a little more sane: every object which needs to be sorted by depth in the game exposes the interface IDepthDrawable and is added to a list owned by the DepthDrawer object.  IDepthDrawable contains:

public interface IDepthDrawable
{
    Rectangle Bounds { get; } //possibly change this to a class if struct copying of the xna Rectangle type becomes an issue
    DepthDrawShape DepthShape { get; }
    void Draw(SpriteBatch spriteBatch);
}

The Bounds Rectangle of each IDepthDrawable object represents the 2D Axis-Aligned Bounding Box it will take up when drawn to the screen.  Anything that doesn't intersect the screen will be culled at this stage and the remaining on-screen IDepthDrawables will be Bounds tested for intersections with each other.  This is where I get a little less sure of what I'm doing.  Each group of collisions will be added to a list or other collection, and each list will sort itself based on its DepthShape property, which will have access to the object-to-be-drawn's physics information.  For starting out, lets assume everything in the game is an axis aligned 3D Box shape.  Boxes are pretty easy to sort.  Something like:

if (depthShape1.Back > depthShape2.Front) //if depthShape1 is in front of depthShape2.
    //depthShape1 goes on top.
else if (depthShape1.Bottom > depthShape2.Top) //if depthShape1 is above depthShape2.
    //depthShape1 goes on top.

//if neither of these are true, depthShape2 must be in front or above.

So, by sorting draw order by several different factors from the physics engine, I believe I can get a really correct draw order.  My question is, is this a good way of going about this, or is there some tried and true, tested way which is completely different and has somehow completely eluded me on the internets?


texts: How to put virtual hands in front of player?

texts:
I want to have the VR hands always in front of the player. This works while walking forwards/backwards, once I rotate the camera they stay in the same place.

I know that I need to take the camera facing into account, but I am missing the math here.
Here is the code for hand translation/rotation:

    void Update()
{
    if (UnityEngine.XR.XRDevice.isPresent)
    {
        GameObject player = GameObject.Find("PlayerGameObject");
        if (hand == WebVRControllerHand.LEFT)
        {
            transform.position = UnityEngine.XR.InputTracking.GetLocalPosition(UnityEngine.XR.XRNode.LeftHand) + player.transform.position;
            transform.rotation = UnityEngine.XR.InputTracking.GetLocalRotation(UnityEngine.XR.XRNode.LeftHand);
        }

        if (hand == WebVRControllerHand.RIGHT)
        {
            transform.position = UnityEngine.XR.InputTracking.GetLocalPosition(UnityEngine.XR.XRNode.RightHand) + player.transform.position;
            transform.rotation = UnityEngine.XR.InputTracking.GetLocalRotation(UnityEngine.XR.XRNode.RightHand);
        }
    }
}

Update:
Having no movement implemented, looking around will make the hands always appear in front of the camera. If I add this code to the camera object, it will break  so the hands never leave their original space(they still move when I rotate the controller but they stay in the same place):

//Script is attached to the parent of the hands
public class SimpleMovement : MonoBehaviour {
void Update()
    {
        var x = Input.GetAxis("Horizontal") * Time.deltaTime * 150.0f;
        var z = Input.GetAxis("Vertical") * Time.deltaTime * 3.0f;

        transform.Rotate(0, x, 0);
        transform.Translate(0, 0, z);
    }
}

Update 2:
It seems like I got it partially working. At least for translation movement. I set the position only according to what comes out of the XR framework, now I add the player's position on top(previously I did this at the wrong spot).
What is missing now is rotating the camera with the sticks seemns different than rotating the camera with the headset. So the hands still do not respond to rotation movement of the sticks.


texts: Make my Tower continously fire at enemy while inside collider?

texts:
So I've made a Tower script in c# that spawns a projectile that then fires at the enemy gameobject. However, because I'm using the OnTriggerEnter() function it will only fire as many times as gameObjects enters the collider.

How do I make sure that the tower will keep firing untill there is no more enemies within its collider?

public class Tower : MonoBehaviour {

// Public variables
public GameObject ammoPrefab;
public float reloadTime = 1f;

// Private variables
private Transform projectileTarget;
private GameObject projectile;
private float nextFireTime;
private float nextAnimTime;

void Update() {
    if (projectileTarget) {
        Debug.Log("We have target");
        if(Time.time >= nextFireTime){
            Debug.Log("nextFireTime has passed");
            FireProjectile();
        }
    }

}

void OnTriggerEnter(Collider co) {
    // Was it a Monster? Then Shoot it
    if (co.gameObject.tag == "Enemy") {
        Debug.Log("Enemy tag detected");
        nextFireTime = (float)(Time.time+(reloadTime*0.5));
        projectileTarget = FindClosestEnemy().gameObject.transform;
    }
}
void OnTriggerExit(Collider co) {
}
void FireProjectile()  {
    Debug.Log ("Shoot");
    nextFireTime = Time.time + reloadTime;
    projectile = (GameObject)Instantiate (ammoPrefab, transform.position, ammoPrefab.transform.rotation);
    projectile.GetComponent<Projectile> ().target = projectileTarget;
}
GameObject FindClosestEnemy() {
    GameObject[] gos;
    gos = GameObject.FindGameObjectsWithTag("Enemy");
    GameObject closest = null;
    float distance = Mathf.Infinity;
    Vector3 position = transform.position;
    foreach (GameObject go in gos) {
        Vector3 diff = go.transform.position - position;
        float curDistance = diff.sqrMagnitude;
        if (curDistance < distance) {
            closest = go;
            distance = curDistance;
        }
    }
    return closest;
}

}


texts:
I'm making a platform engine with XNA Game Studio, and I've solved almost everything about colliding stuff. But now, I'm searching for good physics for the player, I'm trying to emulate characters from other games like Mario from Super Mario World, or MegaMan X... do you know a website or something, where the physics from that games are revealed? I remember seen a page with something like that.

Or what's the process you think is the best to emulate physics from other games? Just trial and error?

Thank you.


texts: To Unity Rigidbody move like Character Controller on collision

texts:
I want to a blue ball moving like a figure.

in CharacterController, it was possible.

but in Rigidbody, object was stucked.

help me.


texts: Make UI draggable from clicked vertices of UI

texts:
I am able to make my UI panel draggable. Here is the script, it will be helpful:
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class UIElementDragger : EventTrigger
{

    private bool dragging;

    public void Update()
    {
        if (dragging)
        {
            transform.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
        }
    }

    public override void OnPointerDown(PointerEventData eventData)
    {
        dragging = true;
    }

    public override void OnPointerUp(PointerEventData eventData)
    {
        dragging = false;
    }
}

It is working fine but with one issue. Each time I click to drag the panel, my UI panel drag from the center (i have custom panel anchor). Is there any way available to move it with the clicked position of UI? I mean it should be draggable from where i have clicked. Certainly, problem lies in this line
transform.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);

transform.position need to change to clicked position of object?
https://www.youtube.com/watch?v=gayEHaol4Lc


texts:
I have a state machine for a game I am developing. The player can be in four states, depending on button clicks, and some game elements (being in thin air, or standing on the ground). I am just wondering if I should use arrows between all the possible states changes? All states in this diagram need to go through the Idle state, but in the game, you could easily go from Walking to Jumping by pressing the "jump"-button whilst walking. The same applies for the Jump state to the Falling state. After a jump, the player immediately transfers to the Falling state. Is this something I need to put in the finit state machine diagram? The diagram might end up messy with extra arrows, and I would like to avoid it, but if this diagram was meant for a thesis or in lecture I want the diagram to be correct.

I am sorry if this question is too opinion based.


texts: Google Play Services Save Game to store single long?

texts:
I want to implement a Google Leaderboard in my game. The score I will send to the leaderboard is a single long number.

Now I want to make sure that the user's progress won't get lost when reinstalling the app, buying a new mobile, etc.. So I can't store that single long in the Shared Preferences. And I also can't get the user's score back from the leaderboard, since it only supports sending scores (right?).

So I was thinking of implementing a Google SaveGame for that.

What would be the app flow for that?

Thanks in advance!


texts: OpenGL: strange thing with depth and text rendering

texts:
TL;DR I render a scene with M,V,P matrices as always. Than I render something (in this case - text) without any matrices and using separate shaders pair on coordinates with Z = -1. Somehow it's rendered closer to the camera than something on coordinates with Z = 0.9. I can't understand why.

Here is something I can't figure out.

Consider this vertex shader which is used for text rendering:

#version 330 core

layout(location = 0) in vec2 vertexPos;
layout(location = 1) in vec2 vertexUV;

out vec2 fragmentUV;

void main() {
    fragmentUV = vertexUV;

    gl_Position.x = vertexPos.x*2 - 1;
    gl_Position.y = vertexPos.y*2 - 1;
    gl_Position.z = -1.0;
    gl_Position.w =  1.0;
}

When text is rendered with Z  = -1 everything looks fine:

And if I change Z to 0.9 scene looks like this:

According to this tutorial perspective matrix modifies the scene so that all visible objects are in cube where -1 <= {X,Y,Z} <= 1. Also by default camera looks "down" towards Z axis.

So shouldn't it be conversely: larger Z - closer to the camera?

Full source code is on GitHub. Here is a code which renders text. And this code fills corresponding VBO.


texts: What is causing my wheel collider's raycast to fail?

texts:
I'm making custom car suspension(Custom wheelcollider etc), now I encountered a problem where if car gets dropped from a certain height, raycast will fail to detect collision and wheels intersect with terrain.
My raycast starts from the center of a wheel and goes down.
Example of what happens for ~1 frame when car is dropped:

Then it jumps up back to normal state.
I know that Physics.Raycast detection happens every FixedUpdate, which happens rarer than Update(And I update my wheel positions in Update). But since all physics happen every FixedUpdate, doesn't it mean that rigidbodies move every fixed update too?
I don't understand where the conflict happens and why Raycast doesn't detect that ground hit for that one frame.
Wheel collider's code:
void FixedUpdate()
{

 if (Physics.Raycast(transform.position, -transform.up, out hit, springLength))
    {
        // Debug.Log(transform.name + " has hit");
        contactSpeed = (hit.distance - hitDistance) / Time.deltaTime;
        // Debug.Log(contactSpeed);
        hitDistance = Mathf.Clamp(hit.distance, maxCompression, hit.distance);
        // forceDirection = (hit.point - transform.position).normalized;
    }
    else
    {
        //resting position = springlen
        hitDistance = springLength;
    }
}

And code that modifies wheel model's transform.position:
void Update()
    {
        for (int i = 0; i < wheels.Count; i++)
        {
            UpdateWheel(i);
        }
    }

void UpdateWheel(int i)
{
    Transform wheelModel = wheelModels[i];
    PhysicsWheel wheel = wheels[i];

    Vector3 wheelPos = wheelModel.localPosition;
    //springStretch = just hitDistance's getter.
    wheelPos.y = -wheel.springStretch + wheel.radius;
    wheelModel.localPosition = wheelPos;

    Vector3 wheelRot = wheelModel.localRotation.eulerAngles;
    // wheelRot
    wheelModel.Rotate(Vector3.right * wheel.RPM * 6 * Time.deltaTime, Space.Self);

    // wheelModel.transform.localRotation = Quaternion.Euler(wheelRot);
}

Physics settings are default:

Clarifications:
hitDistance is used to find where raycast actually hit the ground(By subtracting radius from it, I can find out where the wheel should be), contactSpeed is delta between two hitDistances, its used to dampen the spring.


texts: Phaser is not loading the same map created in Tiled software


texts: Empty Array of IMotionControllers for Unreal using Oculus Quest

texts:
The typical way of setting up a MotionController in Unreal Engine is through Blueprints, but I'm trying to identify different types of motion controllers for various VR setups and from there apply the orientation and position data. I have no problems getting Oculus Rift and Vive controllers and trackers using C++, but on Oculus Quest the array that's populated with IMotionControllers is empty when debugging over ADB. Why might this be?

The following code will print a length of 0 on Oculus Quest only.

const FName feature = FName(TEXT("MotionController"));
TArray<IMotionController*> controllers = IModularFeatures::Get().GetModularFeatureImplementations<IMotionController>(feature);
UE_LOG(LogGloveController, Warning, TEXT("Number of Controllers: %d"), controllers.Num());


texts: I have been given the task to create an enemy class as well as an enemy manager. I am completely confused as to how I will attempt this. these classes will be added into one group project with my other group members. I need to include things such as enemy health, the sprite itself, animations etc. I am new to using Monogame and c# so it would be appreciated that any help given is in an extremely simple form.


texts: Creating Dialog Trees in Unity with Python?

texts:
I was thinking to create dialog trees with Python in Unity. I was curious if I will using in one project c# scripts and python will not cause problems with compiling scripts. Also I did found few articles about adding Python to unity, but I am not 100% sure if they are actual and they didn't been really detailed enough. Right now I am using the newest version of unity and vs 2017. I already install PythonIron, but also the newest version of it (I lazily just follow where download page leads me).

I was wondering if somebody could enlighten me with how to actually add Python to Unity and how does it work with other scripts (for example, could I have a function in c# script which could be coming from python script?)

Thanks for any kind of help.


texts: ScreenToWorldPoint problems in otherwise awesome Unity demo

texts:
I am using this neat Unity demo I found on Stack Overflow, which demonstrates texture masking via RenderTexture:

Can you erase a texture in real time in Unity

But the mapping from mouse position to world space is wrong. This is the script that does the mapping:

using UnityEngine;
using System.Collections;

public class MaskCamera : MonoBehaviour
{
    public Material EraserMaterial;
    private bool firstFrame;
    private Vector2? newHolePosition;

    private void CutHole(Vector2 imageSize, Vector2 imageLocalPosition)
    {
        Rect textureRect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
        Rect positionRect = new Rect(
            (imageLocalPosition.x - 0.5f * EraserMaterial.mainTexture.width) / imageSize.x,
            (imageLocalPosition.y - 0.5f * EraserMaterial.mainTexture.height) / imageSize.y,
            EraserMaterial.mainTexture.width / imageSize.x,
            EraserMaterial.mainTexture.height / imageSize.y
        );
        GL.PushMatrix();
        GL.LoadOrtho();
        for (int i = 0; i < EraserMaterial.passCount; i++)
        {
            EraserMaterial.SetPass(i);
            GL.Begin(GL.QUADS);
            GL.Color(Color.white);
            GL.TexCoord2(textureRect.xMin, textureRect.yMax);
            GL.Vertex3(positionRect.xMin, positionRect.yMax, 0.0f);
            GL.TexCoord2(textureRect.xMax, textureRect.yMax);
            GL.Vertex3(positionRect.xMax, positionRect.yMax, 0.0f);
            GL.TexCoord2(textureRect.xMax, textureRect.yMin);
            GL.Vertex3(positionRect.xMax, positionRect.yMin, 0.0f);
            GL.TexCoord2(textureRect.xMin, textureRect.yMin);
            GL.Vertex3(positionRect.xMin, positionRect.yMin, 0.0f);
            GL.End();
        }
        GL.PopMatrix();
    }

    public void Start()
    {
        firstFrame = true;
    }

    public void Update()
    {
        newHolePosition = null;
        if (Input.GetMouseButton(0))
        {
            Vector2 v = camera.ScreenToWorldPoint(Input.mousePosition);
            Rect worldRect = new Rect(-8.0f, -6.0f, 16.0f, 12.0f);
            if (worldRect.Contains(v))
                newHolePosition = new Vector2(1600 * (v.x - worldRect.xMin) / worldRect.width, 1200 * (v.y - worldRect.yMin) / worldRect.height);
        }
    }

    public void OnPostRender()
    {
        if (firstFrame)
        {
            firstFrame = false;
            GL.Clear(false, true, new Color(0.0f, 0.0f, 0.0f, 0.0f));
        }
        if (newHolePosition != null)
            CutHole(new Vector2(1600.0f, 1200.0f), newHolePosition.Value);
    }
}

I fixed line 49 and 50 like so:

Vector2 v = GetComponent<Camera>().ScreenToWorldPoint(Input.mousePosition);
Rect worldRect = new Rect(0.0f, 0.0f, 16.0f, 12.0f);

So the script compiles and the worldRect is in the right place now. Through debugging I found that the world coordinates returned on line 49 are off. I also tried setting the z value of mousePosition to 10, even though the cameras are orthographic, like so:

Vector3 mousePos = Input.mousePosition;
mousePos.z = 10;
Vector2 v = GetComponent<Camera>().ScreenToWorldPoint(mousePos);

The mapping from the mouse to worldspace is still wrong though. Mouse coordinates within a small rectangle near the center are mapping to the full width and height of the image in world space.


texts:
I want to implement a basic animation to show clothes being folded. A good example of what I want to do is shown in this game (https://youtu.be/_J-_PAqxtAQ?t=109) at 1:49. You may want to watch it at .25x speed to see the dress fabric’s movement in detail.
I know this kind of animation can be done using bone animations but I think that the cloth will look like an overly stiff and rigid plane. I don’t need to create a very realistic cloth simulation but I would like the cloth to drape a little more naturally as in the link shared above.
I have explored Unity’s cloth simulation component but as far as I can understand, it would simulate cloth’s natural draping but it won’t be able to show the basic cloth folding moves. It also looks a little more realistic than what I need; I’m trying for a more cartoon look as in the game above.
I’d like suggestions for an approach that will both allow the cloth to be folded while maintain a basic level of cloth flexibility (as in the link above). I’m considering using bone animations and have some specific questions:

Using bone animations, can I achieve the effect of a more natural cloth? If yes, will it require a complex bone setup?
Are there other mesh deformation techniques that would be effective to create that effect? If yes, what are those?

I would appreciate any suggestions and thoughts on this topic. Thank you.


texts: How should I manage events in XNA on the Windows Phone 7 without impacting performance?

texts:
It's best-practice to not to create lots of short-lived temporary objects the heap as it'll eventually force a garbage collection during game-play.

It is best to create short lived value objects.

Where does this leave us with event handlers?  My game object fires events quite frequently, so I don't want to create new MyThingDidSomethingEventArgs every time.

What's the alternative.  What do you use?


texts:
The wealth system in d20 Modern always gives me a slight headache at character creation, because I know there's a better way to buy things, but I don't know exactly how, so I'm coming up with an algorithm to automatically buy things in the correct order to minimize losses, sticking it in a program, and just stop thinking about the whole thing. Help if you can, pls.

Algorithm

[Wealth is your Wealth Bonus, and DC is the Purchase DC of the item on the list. > is greater than, < is less than, >= is greater than or equal to, and <= is less than or equal to]

Wealth is a random value generated at the beginning (let's say 1 to 100), and the list of items purchased can contain up to 25 items of equally random purchase DCs. Just in case that's relevant. In the link above, it mentions things like 1d6 and 2d6. In the format xdy, x= number of dice rolled, and y = number of sides each dice have. So 2d6 would generate a number from 2 to 12. 1d6 would generate one from 1 to 6.

-

Run the following through all items in the list first, since if the following conditions are met, the item is free, but might not remain free if you lose wealth:

If DC <15 and (Wealth - DC) > 0
Purchase item

-

Then, determine if there are items on the list that would jump up a tier if you lost 1 wealth (So, if Wealth - DC = -10 or -15) [Don't check for Wealth - DC = 0, because it should have already been bought if it was.]

If there isn't, then purchase an item with DC >=15 and (Wealth - DC) > 0

Repeat that until there are either no more items fitting the conditions, or until you are on the verge of jumping up a tier.

-

(I haven't figured out how to optimize against tier-jumping. I'm inclined to immediately buy anything that might tip over in to -16 territory, and abandon anything that ends up there. If there are none, then prioritize any in the threat of going over a tier, and abandon any that might go in to the -16+ territory.
There's some way to better formulate around these tiers, but it's rather mind-racking, and frustrating that I can't seem to figure it out!.)

-

Repeat the last process (that I actually outlined), but determining if items would jump up a tier if you lost 2 wealth
If there isn't, then purchase an item with DC>=15 and (Wealth - DC) < 0 and (Wealth - DC) > -11
(I have no idea where in the queue I should put this, but I just felt like this would be the lowest priority purchase.)

If an item comes with a restriction of +2 or greater (and you only care about the wealth you have at the end), then, unless the black market adjustment pushes the item over a tier, take the black market because you don't lose as much wealth that way. If it's only +1, then take the license unless you have 9 wealth or less, in which case obey the previous rule on restriction.


texts:
Most DragonBones tutorials I've found seem to have you importing separate files at the start of a project, but the example projects use a single PNG texture containing all the parts of the final armature, along with an accompanying JSON file that says how to chop up the texture to get at each part.

How would you create this pair of files?


texts: Making an AI walk on a NavigationMesh (2D/Top-Down game)

texts:
For some time I have been working on a framework which should make it possible to generate 2D levels based on a set of rules specified by level designers. You can read more about it here as I won't go into details: http://www.jorisdormans.nl/article.php?ref=engineering_emergence

Anyway, I'm now at the point of putting the framework to use and have trouble coming up with a solution for AI.

I decided to implement a NavigationMesh in the generated levels as I already have that information to start with. Consider the following image (borrowed from http://www.david-gouveia.com/pathfinding-on-a-2d-polygonal-map/):

When I run A* on the NavigationMesh, the red path would be suggested when I want to go from point A to B (either direction). However, I don't want my AI to walk that path directly and clipping corners, I'd rather want them to follow the more logical black path.

How would I go about going from the Red path to the Black path, are there any algorithms for this. Which steps do I take? Is A* the proper solution for this at all?

For some additional information: The proof-of-concept game is a 2D top-down game written in C#, but examples/references in any language are welcome!


texts: Artifacts when using SamplerState.LinearClamp in SpriteBatch

texts:
I'm using XNA 4.0 and VS2010 Express for Windows Phone and Windows Phone SDK 7.1.
This is a platform game and I have a map made up of 16x16 textures that is drawn dynamically, tile by tile.
When using SpriteBatch to draw my map with LinearClamp, I get artifacts that looks like blurry thin lines.
They become visible when the camera moves from one pixel to another and when the camera is still, the artifacts disappear.
Here's a small sample of what I mean:

Here's how I draw with the spritebatch:

SBWorld.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullNone, null, camera.View);

When using SamplerState.PointClamp the game just plays horribly (IMHO), so I cannot use that.
Why do these lines appear and how do I get rid of those?


texts: Unity3D Interactive Cloth Basketball Net Falling Apart Though Not Tearable

texts:
I have a basketball net mesh attached to an Interactive Cloth with the following attributes:

The mesh is not segmented and is not marked as tearable but as soon as the game starts the net falls apart into individual ropes like so:

First moment:

A moment later:

I am not great at 3D Modeling and have tried several downloadable nets with similar results. What would you do to keep my net together?


texts: I don't like LWJGL in some cases, so I prefer to use Swing. The thing is that Swing doesn't have OpenGL. I have tried JOGL and it's a mess to install, needs external jars, and I have yet to get it working. So I was wondering if I could just make an OpenGL class that uses opengl32.DLL and put the graphics into a window made with Swing? Also, is opengl32.DLL able to be called with a 64 bit Java program?


texts: How to find resources location regardless of working directory?

texts:
I am working on a resources loader for my personal C++/OpenGL ES engine. My resources are in a resources folder separated trough different sub-folders (shaders, textures, etc).

I am currently giving a path to this folder when I want to load a file. My code looks like this:

texture.load("../../resources/textures/dirt.png");

The problem is - in addition to not be gracious - it depends of the current working directory and of the final binary location when I execute it.

How can I store the complete path to the resource when I call the load function to be able to load it regardless of working directory? I would like to be able to use the following line:

resourcesManager.loadTexture("dirt.png");

Regardless of where I am compiling nor executing my game, as long as I told to the texture manager where is the resources folder.

I tried to find a solution using __FILE__ macro, because I can get the complete path to the compiling file with it, but it would be the path to the source file, not the path to the binary.

I'm trying to make it cross-plateform, so I would prefer a solution not working through an external editor or IDE.


texts: How to not freeze the main thread in Unity?

texts: I have a level generation algorithm that is computationally heavy. As such, calling it always results in the game screen freezing. How can I place the function on a second thread while the game still continues to render a loading screen to indicate the game is not frozen?


texts: In Unity, how to hide objects from specific cameras without using Layers

texts:
The situation is that there are multiple players that can collect items. When a player collects an item, the item will disappear from that player's screen but still be visible to other players. I know I can use LayerMask to achieve this effect. However, what if there are more than 32 players? (Unity Layer has 32 bits). How can I still hold this effect?

I tried using OnWillRender() to check which camera is rendering the object in order to disable its renderer. This does not work because once the renderer has been disabled, OnWillRender() will not be called again for other cameras.


texts: Lerping character moving up and down slope tiles

texts:
So, when interpolating position against a standard 'horizontal' platform, everything works great. What happens is something like this..... (Question continues after graphic)

Now, the question I have is, how do we correctly interpolate the player's sprite (blue circle) against a 45° tile? When I attempt to do this, what happens, is that when the player is going up the slope, it is slightly embedded in the tile and when coming down the slope, it floats slightly above the tile.

In the example above, the sprite effectively 'stops' moving along the Y Axis, so therefore, interpolation along that axis stops, however when interpolating the position against a slope, the sprite moves in an X and Y direction, so never stops.  I think this is causing the issue, if my logic is correct, some more graphics follow to illustrate what I mean....

What am I doing wrong?  How do I interpolate my sprite while making sure it's 'on' the slope at all times?

For moving up a slope

When moving down slope

Summary

When interpolating against a horizontal platform, although the sprite isn't rendered on the platform in the frame straight after collision has been resolved, it is rendered on the platform during subsequent frames because the difference between the old and new positions has become 0 as it is no longer moving. However against a slope, again, the initial frame is incorrect but then the sprite moves again, so the next frame is also wrong etc so it never 'settles'. Note it does move at the slope's angle just not on the slope.

I'm trying to work out how to get my two points along the 45°  slope and interpolate between them (ie, along the slope)....


texts:
I've been working on a wave-based zombie game for the past few months and all of the systems have been working perfectly - until I upgraded to the latest version of Unity. Since then, spawning a zombie onto a nav mesh and then calling SetDesination is throwing the exception:

"SetDestination" can only be called on an active agent that has been placed on a NavMesh.
UnityEngine.AI.NavMeshAgent:SetDestination(Vector3)

The zombies are spawned a random spawn point and their destination set as so:

 GameObject go;
        for (int i = 0; i < SpawnAmount; i++)
        {
            Vector3 location = new Vector3(transform.position.x + i + UnityEngine.Random.Range(-1, 1), transform.position.y, transform.position.z + i + UnityEngine.Random.Range(-1, 1));
            go = Instantiate(enemyPrefab, location, spawnRotation) as GameObject;
            go.GetComponent<NavMeshAgent>().SetDestination(players[0].transform.position);
        }

It is the setdestination line that is causing me issues.

I have a static baked nav area. The player characters (who also use nav agent to move) can move across the nav area perfectly - it is only the zombies which seem to have trouble.

I have spent a long while tweaking settings here and there. Adjusting the location of the zombie and even having a zombie in the game before starting the game. However I can't seem to correct this exception - all while the player characters are moving perfectly.

Any ideas on what I could be missing or areas I should be looking?

EDIT The updated and working code:

GameObject go;
for (int i = 0; i < SpawnAmount; i++)
{
    Vector3 location = new Vector3(transform.position.x + i + UnityEngine.Random.Range(-1, 1), transform.position.y, transform.position.z + i + UnityEngine.Random.Range(-1, 1));
    go = Instantiate(enemyPrefab, location, spawnRotation) as GameObject;
    go.GetComponent<NavMeshAgent>().Warp(location);
    go.GetComponent<NavMeshAgent>().SetDestination(players[0].transform.position);
}


texts:
Is there a way to shufle a group of sprites created with:

pygame.sprite.Group()

I have tried using random.shuffle but it apparently doesn't work on sprite groups.


texts:
I'm obfuscating spritesheets. I've already encrypted the .txt file dictionaries. Now I'd like to perform binary serialization on the image files. Texture2D does not allow for this though, probably because it's coupled to the ContentManager and by extension the Graphicsdevice.

The solution I'd like to go for would be serializing the image files in a single wrapper object in the obfuscation code, and deserializing it when the game is loading. However, Content.Load<Texture2D>() will only take the asset name as parameter. Is there a workaround, or am I looking at this problem the wrong way?


texts:
I have 1000*1000 (1,000,000 tiles) fixed size map composed of 3 layers (3,000,000 tiles) every tile has 4 values X,Y,Z and ID (12,000,000 values). When a client connects and requests map data, server has to send 10x10(100 tiles) tiles in a packet and every time the player moves server sends map buffer which is a row of tiles data (X,Y,Z and ID) in a packet too. All these values needed to be loaded on server startup and that's without mentions other variables. Am i on the right path? Is there is any better method?

Additional info: I'm using C# server, map is made by Tiled exported to XML file with CSV format. Client is supposed to be on GameMaker Studio (not yet made)


texts: Polygon edges visible when using per-fragment lighting (OpenGL)

texts:
I have created a mesh in Blender (just a sphere with a texture over it; it's supposed to look like mars) and I've exported it as OBJ. I've tried it both with exporting with normals in Blender's export settings and also with the aiProcess_GenNormals flag. But for some reason I'm still getting this lighting issue.

There's a lot of C++ code but I'm not sure if any of it is relevant to this issue, so I'll just include the shaders.

The vertex shader:

#version 330 core

layout(location = 0) in vec3 vertexpos_modelspace;
layout(location = 1) in vec2 texcoord_vertex;
layout(location = 2) in vec3 normal_vertex;

uniform mat4 world;
uniform mat4 view;
uniform mat4 projection;

out vec2 texcoord_fragment;
out vec3 normal_fragment;

void main()
{
    texcoord_fragment = texcoord_vertex;

    vec4 transformed_normal;
    transformed_normal = vec4(normal_vertex, 1);
    transformed_normal = world * transformed_normal;
    normal_fragment = transformed_normal.xyz;

    gl_Position.xyzw = projection * view * world * vec4(vertexpos_modelspace, 1);
}

The fragment shader:

#version 330 core

uniform sampler2D texsampler;

uniform vec3 light_direction;

in vec2 texcoord_fragment;
in vec3 normal_fragment;

out vec4 color;

void main()
{
    float lighting = 0;
    lighting = dot(normalize(normal_fragment), normalize(light_direction));
    lighting = clamp(lighting, 0, 1);

    vec4 sample = texture(texsampler, texcoord_fragment).rgba;

    color = sample * lighting;
}

And the result looks like this:

I can't figure out why this is happening. It doesn't appear this way in Blender, just in my application.


texts:
I'm thinking about a future project using MonoGame and it seems there are no level editors that outright support it, though obviously there are those for XNA that may possibly be compatible.  So I suppose this is a two-part question; are there any existing level editors that can be made work with MonoGame, and also is it possible to create levels that are then inbuilt into the codebase and thus work cross-platform (for example, Android or iOS, or does the level editor have to support the platform)?

Thanks in advance.


texts:
Several years ago I overheard a technique that gives the user the illusion of a rotating planet by using a 2D texture. Given that the user isn't able to change its position or viewport.

What's the name of this technique?


texts: How can I show information from a variety of sources in my debug menu?

texts:
I'm creating a debug menu, and I want to be able to show a lot of information (variables) on that menu. This information will come from a lot of classes (instances).

How can I show a lot of information from a lot of classes in my debug menu? How can I get access to all the variables of the instances of the classes that I need information from?


texts:
I'm using Java to learn some movement algorithm. I would like to implement the "wandering" algorithm, but in order to do it, i should understand how to rotate an Object gradually.

Actually, my Player changes its orientation instantly (and too many times!) and it is not so good.

This is my code:

logic update

public void update(float delta) {
    // WANDERING

    // orientation as a vector
    float orientation_x = (float)Math.sin(orientation);
    float orientation_y = (float)Math.cos(orientation);

    // update velocity
    velocity_x = maxSpeed * orientation_x;
    velocity_y = maxSpeed * orientation_y;

    int max = 1;
    int min = 0;
    int random1 = (rand.nextInt((max - min) + 1) + min);
    int random2 = (rand.nextInt((max - min) + 1) + min);
    orientation = (random1 - random2) * maxRotation; // random binomial (i don't know which value i have to assign to maxRotation
    System.out.println(orientation);

    x += (velocity_x * delta);
    if(x >= GamePanel.PWIDTH) {
        x = 0.0f;
    }
    y += (velocity_y * delta);
    if(y >= GamePanel.PHEIGHT) {
        y = 0.0f;
    }
}

draw

public void draw(Graphics dbg) {
    // draws the player
    Graphics2D g2d = (Graphics2D)dbg;
    g2d.setColor(Color.RED);
    AffineTransform old = g2d.getTransform();
    g2d.rotate(orientation, x + SIZE/2, y + SIZE/2);
    g2d.fillRect((int)x, (int)y, SIZE, SIZE);
    g2d.setTransform(old);
}

With this code, the behavior that i get is horrible. The Player changes his direction too many times and instantly.

This is the pseudocode of the algorithm:

# Holds the static data for the character
character

# Holds the maximum speed the character can travel
maxSpeed

# Holds the maximum rotation speed we’d like, probably
# should be smaller than the maximum possible, to allow
# a leisurely change in direction
maxRotation

def getSteering():

# Create the structure for output
steering = new KinematicSteeringOutput()

# Get velocity from the vector form of the orientation
steering.velocity = maxSpeed *
character.orientation.asVector()

# Change our orientation randomly
steering.rotation = randomBinomial() * maxRotation

# Output the steering
return steering


texts: How do you change a Body's origin in Farseer?

texts: In Farseer 3.3.1 for XNA, how do I change the origin of a Body? For example, when I create a Circle Body, instead of it rotating around its center, I want it to rotate around another specified point.


texts:
Seem to have exhausted google looking for an answer to a VERY bullet simple code that should work.

void onCollisionEnter(Collision col) {
    print ("hit " + col.gameObject.name);
    Destroy (gameObject);
    }

Bullet object has the above script, SphereCollider (radius a lot bigger than object), RigidBody, not a trigger, not kinematic, is travelling slow. All checked during runtime.

When it hits a wall (Box collider), it just bounces off but no collisionEnter code is ran.

Debug console bubble is on.


texts:
I'm aware that it usually is a BAD idea to operate separately on GLSL vec's components separately.
For example:

//use instrinsic functions, they do the calculation on 4 components at a time.
float dot = v1.x*v2.x + v1.y * v2.y + v1.z * v2.z; //WRONG
float dot = dot(v1, v2); //RIGHT

//Multiply one by one is bad too, since the ALU can do the 4 components at a time.
vec3 mul = vec3(v1.x * v2.x, v1.y * v2.y, v1.z * v2.z); //WRONG
vec3 mul = v1 * v2; //RIGHT

I've been struggling thinking, are there equivalent operations for branching?

For example:

vec4 Overlay(vec4 v1, vec4 v2, vec4 opacity)
{
    bvec4 less = lessThan(v1, vec4(0.5));
    vec4 blend;
    for(int i = 0; i < 4; ++i)
    {
        if(less[i]) {
            blend[i] = 2.0 * v1[i] * v2[i];
        } else {
            blend[i] = 1.0 - 2.0 * (1.0 - v1[i]) * (1.0 - v2[i]);
        }
    }
    return v1 + (blend - v1) * opacity;
}

This is a Overlay operator that works component wise. I'm not sure if this is the best way to do it, since I'm afraid these for and if can be a bottleneck later.

Tl;dr, Can I branch component wise? If yes, how can I optimize that Overlay function with it?


texts: Unable to use a velocity value when using KeyInput

texts:
Heres the code for the KeyInput

    public void keyPressed(KeyEvent e) {

        int key = e.getKeyCode();

        for(int i = 0; i < handler.object.size(); i++) {
            GameObject tempObject = handler.object.get(i);

            if(tempObject.getId() == ID.Player) {
                //key events for player 1

                if(key == KeyEvent.VK_W) tempObject.setVelY(-5);
                if(key == KeyEvent.VK_A) tempObject.setVelX(-5);
                if(key == KeyEvent.VK_S) tempObject.setVelY(5);
                if(key == KeyEvent.VK_D) tempObject.setVelX(5);
            }

        }

    }

Heres the code for my velocities

        y += velY;

when I launch the program and press any assigned movement keys then my player dissapears entirely, any help?


texts: How can I create a copy of an object in Unity?

texts:
I'm new to unity.

How can I make some copies of my GameObject in Unity by scripting?

I have tried this by the way:

public GameObject stone_3;

void Start ()
{
  for (int i = 0; i < 10; i++)
    Instantiate(stone_3, new Vector3(i * 2.0f, 0, 0), Quaternion.identity);
}

I can't really understand why it's not working.


texts:
Whenever I try to manually call the dispose method in one of my screen my game just crashes.

My dispose looks something like this

@Override
public void dispose() {
    battletheme.dispose();
    renderer.dispose();
    bg.dispose();
    enemy.dispose();
    dialouge.dispose();
    GameTools.fontText.dispose();
}

and I use

this.dispose();

When I switch to another screen, otherwise my memory begins to pile up. Is there any reason for this?

EDIT: My spritebatch called "renderer" seems to crash on dispose, any reason?


texts: Using world coordinates instead of pixels

texts:
I've been told that having a set pixels-per-world unit number is bad practice because it will not look the same at different resolutions. Because of this, I am trying to learn about using abstract world-space coordinates instead, however I am having some trouble understanding.

I've setup a quick test project for learning this: http://pastebin.com/GiUiR2NS
As I understand it, CAM_WIDTH and CAM_HEIGHT should be the dimensions of the world in world units. However, I must be missing something because the end result seems to have made the world 50 pixels by 30 pixels. (My "wall" texture drawn at (0,0) in the bottom left is 16x16 pixels)

I am trying to achieve a view with which I can see 50 walls on the x-axis and 30 on the y-axis. I was able to do this when using direct pixel coordinates and multiplying by 16 (the pixels-per-world-unit number), however as stated before, I don't think I want to use this method anymore because of negative affects at different resolutions.


texts: What is a good way to store tilemap data?

texts:
I'm developing a 2D platformer with some uni friends.  We've based it upon the XNA Platformer Starter Kit which uses .txt files to store the tile map.  While this is simple it does not give us enough control and flexibility with level design. Some examples: for multiple layers of content multiple files are required, each object is fixed onto the grid, doesn't allow for rotation of objects, limited number of characters etc. So I'm doing some research into how to store the level data and map file.

This concerns only the file system storage of the tile maps, not the data structure to be used by the game while it is running.  The tile map is loaded into a 2D array, so this question is about which source to fill the array from.

Reasoning for DB: From my perspective I see less redundancy of data using a database to store the tile data.  Tiles in the same x,y position with the same characteristics can be reused from level to level.  It seems like it would simple enough to write a method to retrieve all the tiles that are used in a particular level from the database.

Reasoning for JSON/XML: Visually editable files, changes can be tracked via SVN a lot easier. But there is repeated content.

Do either have any drawbacks (load times, access times, memory etc) compared to the other?  And what is commonly used in the industry?

Currently the file looks like this:

....................
....................
....................
....................
....................
....................
....................
.........GGG........
.........###........
....................
....GGG.......GGG...
....###.......###...
....................
.1................X.
####################

1 - Player start point, X - Level Exit, . - Empty space, # - Platform, G - Gem


texts:
I'm currently developing a Javascript web game for desktop users. It is a sort of tower-defense game that relies on mouse input only, developed on canvas using EaselJS. In the future, or perhaps simultaneously, I would like to adapt the game for mobile devices.

I can see at least 3 potential areas in shifting from desktop to mobile: 1. resolution size and UI rearrangement, 2. converting mouse events to touch events, 3. distribution as native app wrapper or mobile Web.

What would be the best strategy to facilitate this desktop to mobile conversion? For example, should I try to code the game for both platforms, or port the game UI over to mobile by branching the code base. Should I just publish on the mobile Web or wrap the game in a native app framework? And if I were to code for both platforms using the same codebase, should I register both click and touch events, or remap click events to touch using dispatchEvent?


texts: How to move an object faster through an arc - Unity

texts:
I'm shooting a ball in an arc, but currently it takes too long to move through the arc, so when I increase the force, it doesn't make the ball move faster through the arc, it just launches the ball farther.
Here is my code:
private void Start() {
    rb = GetComponent<Rigidbody>();

    Vector3 direction = new Vector3(0, 1, 1);

    rb.AddForce(direction * 8, ForceMode.Impulse);
}

How can I make the ball move through the arc faster, but not increase the range?


texts: Algorithm to determine all hexagons within an arc from a starting hexagon

texts:
I have a game engine which handles hexagon based war games and things like LOS, etc, for both flat and tip up hexes. A particular game I'm implementing at the moment, Band of Brothers, has facing for vehicles and, optionally, for infantry.

I've searched the web and have not found any algorithm to handle determining the hexagons that fall within an arc expanding out from a hexagon. Here are some pictures to describe what I'm talking about:

I represent the hexagon locations as offset coordinates, and have the values for all the dimensions of each hexagon and the endpoints of the vertices and center in relation to the overall map stored as doubles. I also convert to cube coordinates for determining distance.

Just looking for ideas or pointers on how I might determine these hexagons.

EDIT: I do not have a rep > 10 so I can't add a picture of offset coordinates. There is a good one here on gamedev though. Here's an ASCII art representation of it. The numbers will be a little different depending on which row is indented:

0,0   1,0   2,0   3,0   4,0
   0,1   1.1   2.1   3.1
0,2   1,2   2,2   3,2   4,2