texts: How can I rotate an object based on another's offset to it?

texts:
I have a 3D model of a turret that con rotate around the Y-axis. This turret has a cannon that is significantly off the center of the object. I want the cannon, not the turret, to aim at a specified target. I can only rotate the turret, however, and thus I don't know what equation I need to apply in order to accomplish by objective.

The following image illustrates my problem:

If I have the turret "LookAt()" the target, a laser originating from the cannon will completely miss said target.

If this were a completely top-down scenario, and the cannon were exactly parallel to the turret, then my logic tells me that the fake target should be located at a position that's equal to the actual target plus an offset that's equal to that between the turret and the cannon. However, in my actual scenario, my camera is angled 60º, and the cannon has a slight rotation.

The following image illustrates the scenario:

I'm not sure exactly why, but if I apply that same offset, it only seems to work while aiming at certain distances from the turret.

Is my logic flawed? Am I missing something fundamental here?

Final Edit: the solution provided by @JohnHamilton latest update solves this problem with perfect precision. I have now removed the code and images that I used to illustrate my incorrect implementations.


texts: World position reconstruction from depth fails when viewport size does not match window size

texts:
I'm facing very strange issue. My code for world pos reconstruction works correctly when the viewport size is equal to window size (or framebuffer size in other words). Below is the part for reconstruction to view space, later I multiply the result by inversed view matrix:

vec3 posFromDepth(in vec2 Tex, in float depth) {
    vec3 pos = vec3(Tex, depth) * 2.0 - 1.0; // clip-space position

    float z = -projection[3][2] / (pos.z + projection[2][2]);
    float x = pos.x * halfTanFovX * -z;
    float y = pos.y * halfTanFovY * -z;

    return vec3(x, y, z);
}

When I change the viewport light and shadow calculations seems to be incorrect. The shadows for example instead of being "glued" to the object, floats a little bit along with camera movement.

When I switched my deferred renderer to use world pos stored in G-buffer then everything was calculated right. Is there some transformation of texture coordinates which I'm missing? I tried pass fullscreen quad coords in vertex attributes and compute using below formula:

gl_FragCoord.xy * texelSize

but the results were the same.

I'm searching for the issue more than week and slowly running out of ideas what could be wrong. Maybe you'll come up with something useful.


texts:
I've been working a 2D ray versus AABB implementation. I worked it out on paper, then read about a popular "branchless" algorithm. I decied to try the branchless one, but it gives me completely wrong results when one of the components is zero. I used the "naive" version and it's still reporting bad hits. (The difference is the check for a zero component vs simply allowing 1.0-over-0.0 to turn into +/- infinity)
Example: https://tavianator.com/2011/ray_box.html (adapted to C below):
#include <float.h>
#include <math.h>
#include <stdio.h>
typedef struct vec2_s { double x, y; } vec2_t;
typedef struct box_s { vec2_t min, max; } box_t;
typedef struct ray_s { vec2_t x0, n; } ray_t;

int intersection(box_t b, ray_t r) {
    double tmin = -INFINITY, tmax = INFINITY;

    if (r.n.x != 0.0) {
        double tx1 = (b.min.x - r.x0.x)/r.n.x;
        double tx2 = (b.max.x - r.x0.x)/r.n.x;

        tmin = fmax(tmin, fmin(tx1, tx2));
        tmax = fmin(tmax, fmax(tx1, tx2));
    }

    if (r.n.y != 0.0) {
        double ty1 = (b.min.y - r.x0.y)/r.n.y;
        double ty2 = (b.max.y - r.x0.y)/r.n.y;

        tmin = fmax(tmin, fmin(ty1, ty2));
        tmax = fmin(tmax, fmax(ty1, ty2));
    }

    return tmax >= tmin;
}

These don't work at all for me when one of direction components is zero. Consider the example below that used the method. This is an AABB from (-1,2) to (1,4). The ray is at (3,0) and goes up. Standard Cartesian coordinates.
This returns true that there is an intersection. Clearly there is not. It seems to be ignoring the X-axis completely.
int main() {
    box_t b;
    ray_t r;

    b.min.x = -1; b.max.x = 1;
    b.min.y =  2; b.max.y = 4;

    r.x0.x = 3;
    r.x0.y = 0;
    r.n.x = 0;
    r.n.y = 5;

    printf("Intersection? %s\n", intersection(b,r)? "yes" : "no");

}

I've worked it out on paper, and I came to the conclusion that when a component of the ray's direction vector is zero, then the test for that axis is reduced to a simple interval check. However, obviously, this requires quite a bit of "branching". Before I implement what I have on paper, can anyone explain to me what is going wrong here? I've read various implementations of the so-called "branchless" algorithm, and they all seem to do more or less the same thing and even mention that it correctly (?) handles cases when a component is zero -- but it's failing badly in my unit test. What am I missing?


texts: Is Rete an efficient algorithm to implement a system that allows NPCs to make decisions based on their world views and inner state?

texts:
I'm developing an AI "mind" engine, which allows NPCs (non playable characters) to think and make decisions, based on their view on the game world, and their own inner states (in the future I may add the NPCs' memory - long or short term - if necessary).

Given those inputs, they can give a list of possible actions, with possibilities, for example with a rabbit:

World view: a wolf (enemy) is 100m away, the carrot is 40m away.
Inner state: it is hungry, it has big courage and can take risks.

So the expected type of output will be the actions that the rabbit can do:

Runs away: 40%
Bites one bite of carrot then run: 80%
Keep eating and don't give a damn about the wolf: 20%

Based on the desired actions, it will give its decision: which action to take. But that's future works, now I'm concentrating on how to produce that list of actions.

I read the chapter 5, book Artificial Intelligence for Games, Ian Millington and I found the Rete algorithm, which allows match a rule sets to a given database - in my case, the database will be the combination of the NPC's world view and inner state. It seems suit well with my needs, but after making a search, I can see very few (actually, zero) projects that use this algorithm.

Is it so heavy and slow for computer games? Or does it have any more drawbacks that can't be widely used?


texts: I would like to know if you guys know of any libraries, engines, or even simply design patterns that heavily simplify the task of sharing information and sending of messages between networked programs, so one can focus on tweaking gameplay instead of rewriting networking code, while prototyping networked games. Since this is meant for prototypes, ease of use and flexibility is much more important than speed and security.


texts:
This question was already asked a while ago, and I wanted to check the present situation:

Can I control ads frequency from the dashboard? (e.g. frequency
capping in Admob)
Can I control ads frequency through Unity IAP API?
If not, does that mean that I need to implement all that "frequency
control" functionality manually?


texts: I am building a car racing game using the coordinate system in which I have enemies's cars and the player cars. I want to ask that what is the best way to find the the direction of enemies's cars so that they would facing the player's car and move towards the player's car.


texts: I've got a 3D terrain that consists of many heightmap-based tiles. I need to render multiple roads over the tile. By now I simply subdivide road into tile pieces then generate a decal per each tile. But decals are pretty expensive on memory. Is there any better solution than using decals or baking roads into the tile texture? (Target application should work on mobile device with OpenGL ES 2.0 support)


texts: Libgdx: How to rotate a button on main menu

texts:
How to keep rotating a button on main menu screen around its center, here's the code for the button

final ImageButton btnSett=UIFactory.createButton(txtrSettings);
btnSett.setScale(1,1);
btnSett.setPosition(Gdx.graphics.getWidth()/ 2,0.f, Align.center);
stage.addActor(btnSett);


texts:
I'm working with OpenGL and I'm importing from a file coordinates for quads in the following format:

 0.0 1.0 0.0 //normal vector
 20.0 -5.0  20.0 10.0 10.0 //x y z u v
 20.0 -5.0 -20.0 10.0 0.0
-20.0 -5.0 -20.0 0.0 0.0
-20.0 -5.0  20.0 0.0 10.0

I want to tessellate the quad so I'm starting with this:

------------
|          |
|          |
|          |
------------

And I should get this:

-------------
|___|___|___|
|___|___|___|
|   |   |   |
-------------

Can you guys help me creating the subdivide function? I'm struggling with it...


texts: Least expensive way to build a forest in Unity3D?

texts:
I'm a programmer with some experience in Unity. My objective is to make a game (or maybe just a virtual space you can walk around in First Person perspective) featuring a forest and to make it look as good as I can (probably using HDRP to try and exploit all its potential) through the use of lighting and shaders. I will be using assets from the Asset Store to fill my scene.

I have a little bit of experience with the official Unity terrain tools but I have available the Gaia asset, which I have never used but have heard plenty of good things about it. What would be the advantages of using the Gaia terrain generator over Unity official tools?

I think both Unity Terrain Generator as well as Gaia have the ability to instantiate trees, maybe Gaia has more included assets to use and fill the environment? If so, would this assets be part of the terrain or would they be considered GameObjects? All of this I ask with optimization in mind (culling, LODs).

Anyway, I'd appreciate any tips for making (and optimizing) this sort of environment, as well as advice regarding what kind of Terrain tools to use to make it.

Thanks a lot.


texts: Is there any opengl cel shading tutorial out there (without GLAUX)?

texts:
I want to implement cel shading into my opengl game. I have only found a nehe tutorial that uses glaux (old as hell). I'm looking into it, but I wanna avoid the pain of learning how to translate those old glaux functions/variables. Is there any cel shading tutorial out there that uses glut/sdl?

http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=37


texts:
I apologize for the vague title, I'm not sure how else to phrase this problem.
I am using tIDE to assist me in my game's world development. To give a dynamic effect to map layers within tIDE, it has events that can be wired up to draw sprites before or after the draw of layers, to create foreground or background effects during runtime. This all works fine and well, however, the only way that I understand that this works, is by calling tIDE's internal spritebatch to create this effect. This creates a problem for me, because within tIDE's source code, its spritebatch's call block is set to SpriteSortMode.Deferred, and my characters have particle elements that I would like to draw in front of and behind themselves, via a drawdepth value.
I can use a separate instance of spritebatch and call my character's draw method, and set sprite sorting there, but then my character is drawn ontop of all layers in my tIDE map. Which is even worse to me than my particles not being drawn as I want them to be.
So, in summary, I want all of my crap to work, but at the moment the only way I can figure to do that is to ghetto rig the spritebatch within my characters' draw methods by calling a spritebatch.End();, then starting a new call to Begin() with SpriteSortMode.BackToFront, doing all of my characters' draw logic, and then calling another spritebatch.End(); followed once again by a new spritebatch.Begin().
Obviously that is pretty undesirable, but I don't know any other feasible alternatives. Anybody got any wisdom they could impart unto me as to how I could handle this?


texts: Is Phong shading supposed to be so camera-angle dependent?

texts:
I'm not sure if I have a bug in my code or not. It seems like it's a bug, or at least a major shortfall. Here's two images of the same model at slightly different angles (by moving the camera):

As we can see, the diffuse shading is wildly different from moving the camera just a bit. I would expect this effect from the specular, but not the diffuse (and removing the specular component has no noticeable affect on this shading).

The relevant part of the fragment shader (which removing will remove this issue, but also remove all diffuse shading) is:

clamp(dot(normal, lightDir), 0, 1)

Where normal is the normalized normal vector in camera space (found with (VP * M * vec4(vertexNormal_modelspace,0)).xyz) and lightDir is the normalized light direction vector, which is found with:

vec3 vertexPosition_cameraspace = (VP * M * vec4(vertexPosition_modelspace, 1)).xyz;
eyeDirection_cameraspace = vec3(0, 0, 0) - vertexPosition_cameraspace;

vec3 lightPosition_cameraspace = (VP * vec4(lightPos, 1)).xyz;
lightDirection_cameraspace = lightPosition_cameraspace + eyeDirection_cameraspace;

The above clamped dot product is multiplied by the diffuse color and light color. It seems to be exactly what the Wikipedia page describes (they don't clamp it, but describe the need for it in the text).

Most of the Phong shading code is directly or heavily drawn from this site.

Is the Phong model supposed to result in such camera angle dependent diffuse shading? If not, any ideas as to what might be wrong? If so, what alternatives are there that don't have this effect?

What I want to achieve is essentially the diffuse shading, but without it changing on camera angle, which seems very unrealistic to me. Instead, only the angle between the light source and the normal would matter (and these don't change when we move the camera).

This is homework.


texts: How to use the box2d contact listener in android (java port)?

texts: I don't have any idea about the box2d collision detection in android. I googled and got results that suggest to use the contact listener but I don't know how to use it in android java.


texts: What can I do to get audio into my game legally?

texts:
If making a game of my own, what should or what can I do to get audio in game? I understand that just going on the internet, and finding random tracks and putting in my game may raise a whole load of legal issues, but is there any "good" way to get audio in the game?

Basically, if making a game, would it be better to create your own music (regardless of experience) in house, or hire someone outside to do it?

Also, if I want to use music out on the internet, what steps should I take to use that music?


texts: Many sources of movement in an entity system

texts:
I'm fairly new to the idea of entity systems, having read a bunch of stuff (most usefully, this great blog and this answer).

Though I'm having a little trouble understanding how something as simple as being able to manipualate the position of an object by an undefined number of sources.

That is, I have my entity, which has a position component. I then have some event in the game which tells this entity to move a given distance, in a given time.

These events can happen at any time, and will have different values for position and time. The result is that they'd be compounded together.

In a traditional OO solution, I'd have some sort of MoveBy class, that contains the distance/time, and an array of those inside my game object class. Each frame, I'd iterate through all the MoveBy, and apply it to the position. If a MoveBy has reached its finish time, remove it from the array.

With the entity system, I'm a little confused as how I should replicate this sort of behavior.

If there were just one of these at a time, instead of being able to compound them together, it'd be fairly straightforward (I believe) and look something like this:

PositionComponent containing x, y

MoveByComponent containing x, y, time

Entity which has both a PositionComponent and a MoveByComponent

MoveBySystem that looks for an entity with both these components, and adds the value of MoveByComponent to the PositionComponent. When the time is reached, it removes the component from that entity.

I'm a bit confused as to how I'd do the same thing with many move by's.

My initial thoughts are that I would have:

PositionComponent, MoveByComponent the same as above

MoveByCollectionComponent which contains an array of MoveByComponents

MoveByCollectionSystem that looks for an entity with a PositionComponent and a MoveByCollectionComponent, iterating through the MoveByComponents inside it, applying/removing as necessary.

I guess this is a more general problem, of having many of the same component, and wanting a corresponding system to act on each one. My entities contain their components inside a hash of component type -> component, so strictly have only 1 component of a particular type per entity.

Is this the right way to be looking at this?
Should an entity only ever have one component of a given type at all times?


texts:
I need a little help with a formula to calculate the attack range for my turn-based strat game. Since it's a hexagon grid, I'm having trouble coming up with a formula that would pick the character range variable and calculate if an enemy object is in range.
I'm using Game Maker Studio 2.3. My old script used to check like this:
var unity_attack_range = attacker.RNG;

var hex_dist = 90 * unity_attack_range;
with(defender)
{
    if (point_distance(defender.x, defender.y, attacker.x, attacker.y) <= hex_dist)
    {
        //attack code stuff
    }
}

As you can see, it multiplies the attacker range variable by 90 (hexagon width/2), and then it would just point the distance between the attacker and, if inside it, then you can attack. However, I noticed it makes a circle-shaped check after the attacker with the current formula, and it will include enemies from outside the supposed range.
The hexagon shape is 180 x 120, and the distance between each hexagon center is 90 in both axis.
I don't think it will be worth entering all positions to check, since for range = 5, it would be necessary 90 positions to check manually. I need ideas on how to make it work with maths, like Civ 6 does. Any ideas? Also, thanks for the attention!


texts: XNA 4.0 and Lidgren Library, How do I create a server/client hybrid?

texts:
My use of terminology may be off a little bit. I have been playing around with the Lidgren XNA sample for how the library works, and it is simple to implement it looks like.

I am curious on the logic or theory behind making the game client also act as a server? Basically I want a user to open the game client and have the option of "Hosting a Game" which would allow others to connect to that computer and play multiplayer.

It was suggested that I use some sort of thread to kick off the server code in the background for that host client and then connect the two pieces together for full functionality.


texts: Unity Placing a UI on top of Cinemachine

texts:
I have cinemachine set up. I just need to place the UI on top of it. I can easily manage to make the canvas appear when there's only the main camera alone. However with Cinemachine, it appears that the virtual camera prevents the loading screen to be seen. The canvas in my hierarchy is named loadingPanel which is disabled until I trigger an event. Everything in the hierarchy has their layers set to Default, except canvas (UI) and the player (Player)
I can trigger the event and set loadingPanel to active as well as load the next level but I can't see the loading screen. I could only see my tilemap/level before I switch to the next scene. I need to see my canvas / user interface.
This is my hierarchy

Inspector

How do I see the loadingPanel when cinemachine is present?


texts:
The Terrain tool in Unity is great for constructing 3-D landscapes that are open from above. I am working on a game that happens entirely inside tunnels (specifically, blood vessels in a human body. But it can also be tunnels in an ant nest, or sewers below a city). There is nothing "overground" - all movement is inside the tunnels. I am looking for a tool, similar to Terrain, for easily constructing this complex system of tunnels.
One solution I thought of is to construct a terrain with "half tunnels" (i.e., open from above), then duplicate it, rotate 180 degrees, and "glue" on top of the first copy. But it can only handle one layer of tunnels, and in addition, for some reason I could not rotate the terrain.
Is there a way to construct such underground tunnels with the Terrain tool, or with a different tool in Unity?


texts: What is the best way to debug and profile a web application on an iPod in Mobile Safari?

texts: I've built a web app that makes heavy use of JavaScript and HTML5 canvas. It's easy to debug in Chrome, but on a mobile device the developer tools are much less robust. Is there a tool or technique that will enable me to easily debug and profile my application on an iPod in Mobile Safari?


texts: How can I handle markup sequences in a libGDX TypeWriter implementation?

texts:
I've implemented my own TypeWriter for text that looks like this

public static String GetWords(String text, float wordCount)
{
    float words = wordCount;
    // loop through each character in text
    for (int i = 0; i < text.length(); i++)
    {
        if(i == text.length() - 1 && SceneHandler.lineFinished == false){
            SceneHandler.lineFinished = true;
        }
        words--;
        if (words <= 0)
        {
            return text.substring(0, i);
        }
    }
    return text;
}

I decided I wanted to do markup as well, so that means color codes and such. Problem is that the TypeWriter also goes through the color code (The [COLOR] and the [] part) so you get something like this

[
[Y
[YE
[YEL
[YELL
[YELLO
[YELLOW
*nothing*
(Actually yellow) T

Does anybody have any idea how I could fix this or approach this problem?


texts: What is the difference between Unity's Sprite and Texture2D classes?

texts:
Unity has both a Texture2D class and a Sprite (with related SpriteRenderer). What is the difference between these two classes? Both represent an image, for 2D games should I favor one over the other?

Is the main difference between the two that using Sprite I don't need to create the "billboard" quad myself? And that the Sprite is always rendered directly against the camera?


texts: SharpDX (DirectX) - possible to measure Frame time?

texts:
I'm trying to benchmark various ways to draw 2D lines and have a snag. A D3D10Device that I draw with (and flush) doesn't appear to block, so I can't accurately measure frame rate (or time to render 1 frame).

Here's some code

    // Inside my custom render context - at end of setting up draw calls
    public void Dispose()
    {
        {
            _vertexBufferStream.Close();

            _direct3D10Image._d3d10Buffer.Unmap();

            // Vertex buffer contains LineList with 200k vertices
            _direct3D10Image._d3d10Device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_direct3D10Image._d3d10Buffer, 32, 0));

            int targetWidth = _direct3D10Image._renderTargetTexture2D.Description.Width;
            int targetHeight = _direct3D10Image._renderTargetTexture2D.Description.Height;
            _direct3D10Image._d3d10Device.OutputMerger.SetTargets(_direct3D10Image.DepthStencilView, _direct3D10Image.RenderTargetView);
            _direct3D10Image._d3d10Device.Rasterizer.SetViewports(new SharpDX.Direct3D10.Viewport(0, 0, targetWidth, targetHeight, 0.0f, 1.0f));
            _direct3D10Image._d3d10Device.ClearRenderTargetView(_direct3D10Image.RenderTargetView, _direct3D10Image.ClearColor);
            _direct3D10Image._d3d10Device.ClearDepthStencilView(_direct3D10Image.DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);

            // Shader is generating geometry based on line-list to render a 2D plot
            for (int i = 0; i < _direct3D10Image._technique.Description.PassCount; i++)
            {
                _direct3D10Image._pass.Apply();
                _direct3D10Image._d3d10Device.Draw(
                    (int)(_linesCount * 2),
                    0);
            }
        }

        // Flush doesn't appear to block - how to get meaningful time to draw out of SharpDX?
        _direct3D10Image._d3d10Device.Flush();
        _direct3D10Image._dx10ImageSource.InvalidateD3DImage();
    }

Now if I time the setup of draw calls and the Dispose method above, it reports 15ms to draw. However, there appears to be a significant lag between start of draw and the screen actually presenting.

How can I measure the time to present (or is it possible to make D3D10Device.Flush() blocking?)


texts:
In my very, very simple 2D game I'm working on, I'd like there to be moments of slo-mo.

What is the best method of showing the player that the game is currently in slow-motion? As in, what is the most typical and obvious method used by most current games where slow-motion is a feature?

I'm fairly new to game development, and even newer to this site, so am looking for an answer which contains, basically, just bullets of things which should be different between real-time and slow-motion-time.

"Best," to avoid opinionated answers, means established and recognized, common methods of demonstrating slow-mo.


texts: How can I get a direction vector from a an Euler angle?

texts:
Im trying to get a directional vector from an euler angle. But im not getting how to do it. This is what i got so far.

escapeAngle += 90;
var radians = escapeAngle * (Mathf.PI / 180);

var escapeAngleAsDirectionVector = new Vector2 ();
escapeAngleAsDirectionVector.x = Mathf.Cos (radians);
escapeAngleAsDirectionVector.y = Mathf.Sin (radians);

escapeAngleAsDirectionVector = transform.TransformPoint (escapeAngleAsDirectionVector);


texts: Why are coordinates converted to [-1, 1] during mouse picking?

texts:
I am working on my first 3D game, which contains several vehicles placed on a board. I want to implement mouse picking of the vehicles. I found this great tutorial and used its code. But I don't understand part of the math.

Early in the function (listed below), I convert the input mouse coordinates into the -1 to +1 range:

// Create picking ray from camera position and mouse click
void VehiclePicker::SetPickingRay(LONG mouseX, LONG mouseY) {
    float pointX, pointY;

    /* Conversion to -1 to +1 here: */
    // Move the mouse cursor coordinates into the -1 to +1 range.
    pointX = ((2.0f * static_cast<float>(mouseX)) / static_cast<float>(SCREEN_WIDTH)) - 1.0f;
    pointY = (((2.0f * static_cast<float>(mouseY)) / static_cast<float>(SCREEN_HEIGHT)) - 1.0f) * -1.0f;

    ...

I don't understand why this is necessary, could somebody please explain it?

Here's the rest of the function, for context:

    // Adjust the points using the projection matrix to account for the aspect ratio of the viewport.
    XMFLOAT4X4 prMtrx;
    // Convert projectionMatrix from XMMATRIX into XMFLOAT4X4 in order to pick its members
    XMStoreFloat4x4(&prMtrx, _d3d->GetProjectionMatrix());
    pointX = pointX / prMtrx._11;
    pointY = pointY / prMtrx._22;

    // Get the inverse of the view matrix.
    XMFLOAT4X4 invViewMtrx;
    // Convert inverseViewMatrix from XMMATRIX into XMFLOAT4X4 in order to pick its members
    XMStoreFloat4x4(&invViewMtrx, XMMatrixInverse(nullptr, _camera->GetViewMatrix()));
    // Calculate the direction of the picking ray in view space.
    XMFLOAT3 dir;
    dir.x = (pointX * invViewMtrx._11) + (pointY * invViewMtrx._21) + invViewMtrx._31;
    dir.y = (pointX * invViewMtrx._12) + (pointY * invViewMtrx._22) + invViewMtrx._32;
    dir.z = (pointX * invViewMtrx._13) + (pointY * invViewMtrx._23) + invViewMtrx._33;
    _pickingRayDirection = XMLoadFloat3(&dir);

    // Get the origin of the picking ray which is the position of the camera.
    _pickingRayOrigin = _camera->GetPosition();

    // And finally I must normalize the final vector
    _pickingRayDirection = XMVector3Normalize(_pickingRayDirection);
}


texts: Determining if a point is perpendicular to a line

texts:
I am trying to walk a line that is intersecting a mesh, and given the point on the line I need to see what vertices may be perpendicular to it. My initial idea was to attempt a dot product between the line's direction vector and the direction vector from the point on the line to the mesh's vertex, and then only accept values that were near 0. This resulted in a collection of vertices behind the point on my line. Playing with the threshold values for the dot product check do not seem to help either. Any ideas?

Code

//actual_pos = position of the vertex
//trav_in_soace = point along the line
//m_fireDir = normalized direction vector of the line

Vector3 dir_to_point = actual_pos - trav_in_space;
dir_to_point.Normalize();

float dot_accept = DotProduct(m_fireDir, dir_to_point);
if (dot_accept > max_threshold || dot_accept < min_threshold)
    continue;

Picture with threshold values near 0.5

This is best result I can get and it is still really inaccurate. The orange verts are the points on the purple line, the red and blue are what should be the desired vertices.


texts: Unity raycasting not always detecting component

texts:
I am trying to determine what object I am clicking with the help of a raycast, however it doesn't always work
In update I call:
if (Input.GetMouseButtonDown(0))
{
    selectedObject = null;
    selectedUnits = new List<Unit>();
    Select(Input.mousePosition);
    startPos = Input.mousePosition;
}

which calls:
void Select(Vector2 screenPos)
{
    Ray ray = cam.ScreenPointToRay(screenPos);
    RaycastHit hit;
    //Debug.Log("1");
    if (Physics.Raycast(ray, out hit, 100))
    {
        OnClicked(hit.transform.tag);
        //Debug.Log("2");
        if (hit.transform.GetComponent<Unit>())
        {
            //Debug.Log("3");
            if (!selectedUnits.Contains(hit.transform.GetComponent<Unit>()))
            {
                //Debug.Log("4");
                selectedUnits.Add(hit.transform.GetComponent<Unit>());
            }
        }

        if (hit.transform.GetComponent<Building>())
        {
            if (hit.transform.GetComponent<Building>() != selectedObject)
            {
                selectedObject = hit.transform.gameObject;
            }
        }
    }
}

Detecting a "building" always works and is fine, but clicking on a "unit" works anywhere between 0 and 5 times per play session before it returns nothing anymore like the object doesn't exist. I have tried to find where it gets stuck and it gets stuck after the 2nd debug (debug 1 and 2 print but 3 and 4 do not).
This is the Unit in the inspector

and this is it in the hierarchy

When drawing the ray here you can see it hits the cube 3 times before it just passes right through the 4th time.

it seems like after each hit the ray penetrates the collider more and more

But how and why can it only hit it a couple of times before it passes through. After a certain amount of clicks with or without moving my mouse it just doesn't hit it anymore even though in the inspector nothing changes and there are no scripts that alter the box collider.
I hope someone knows what's going wrong, thanks!


texts: Godot: Better Method to setting focus for buttons

texts:
My problem
I am trying to set focus for a group of buttons with a keyboard or controller. Whereby if the user pushes up or down, a particular button will receive focus.
I already know that this can be achieved with arrays. I just want to know if there is anything better out there or even something default that can be set.
Edit:
I have found out that It is indeed automatic. I still do need to set focus for a button at _ready().


texts: Are references between entities in Entitiy Component System allowed?

texts:
I've got a player entiy in my game that can pick up weapons when colliding with item entities. The player can hold and use the weapon in their hand (the weapon sprite is rendered relative to the carrier).

I'm wondering how to design weapons and items in an ECS approach. Should the weapon be an entity the whole time so that the player entity has a weapon-component which holds a reference to the weapon-entity?


texts:
I'm trying to implement a visibility representation in a 2D game ( no plains, no quads - plain 2D )
In the examples below I have calculated what the player can see using raytracing and added all the colliding points as vertices to a polygon 2D collider. What is within the polygon is in view.

I want everything outside this visible area to be darker / faded out / fogged out, so that it is not visible / as visible as what is in the view. Prefably I would want to choose what objects are included in this darkening, so that static enviroment is not affected but enemy players are.

Simply deactivating the object's renderers is not an option. I also though about overlaying a texture and using a cutout alpha mask, but that would not translate well considering that the visible polygon is updated every frame and the mask has to be premade(?).


texts: Four (4) color channel png has black "background"

texts:
I am experimenting with C++ code to load a png file, using libpng.  When I get to the color data in the file, I load it into a std::vector.  I have found that the interface between the C code libpng and my C++ code is straightforward.

I then draw the image using OpenGL.

When the image file is opened in GIMP, it displays as,

When I display the image with my OpenGL code it displays as,

The file I am using is an RGBA image without a backround, i.e., no kBKG chunk.

In looking at the pixel data in my std::vector, it appears that the OpenGL data for the lower right is all RGBA = (0, 0, 0, 0).

I was expecting that the png IDAT chunk would carry and display the transparency information.

In OpenGL I am setting the background to RGBA = (1, 1, 1, 1), i.e., in 8-bit RGBA terms (255, 255, 255, 255), white.

I am obviously missing something, but cannot see what it might be.


texts: How to choose inputs to an artifial neural network?

texts:
I have to implement, as part of an assignment, a learning method that enables minesweepers to avoid colliding with mines. I have been given the choice to choose between a supervised/unsupervised/reinforcement learning algorithm.

I remember in one of my lectures, the lecturer mentioned ALVIN. He was teaching artificial neural networks.

Since the behaviour I'm looking for is more or less similar to ALVINN's, I want to implement an ANN. I've implemented an ANN before for solving the 3-parity xor problem, here's my solution. I've never really understood the intuition behind ANNs.

I was wondering, what could the inputs be to my ANN?
In the case of the 3parity xor problem it was obvious.

[EDIT]

The game is not minesweeper. However, it has bots which look like battleships which we refer to as minesweepers. Please see the screenshot below. The goal is for the battleships aka minesweepers to move in one direction each but should learn to avoid mines over time.


texts: Selective Collision Resolution While Rolling

texts:
I am working on a 2D action platformer in Pygame, though my question is a general one.

The question concerns selective collision resolution. In short, I want certain collisions to be ignored while my player sprite is rolling.

My player sprite has a roll state during which a controlled force is applied, moving the sprite forward until the roll animation finishes and the sprite's state changes to idle.

The sprite's bounding box doesn't change during this animation, since, as a rule, you don't want a sprite's bounding box to change size from frame to frame (see this answer).

My sprite is 64 pixels tall and I want him to be able to roll through 32 pixel gaps. Here's a diagram:

Currently, I do collision resolution during updates to my sprite's position. I first change his y-position according to his y-velocity,  then check if there is rectangular overlap between my sprite and objects of a wall class. If there is, I place him flush with the wall. Then I update his x-position according to his x-velocity and do a similar collision check and resolution.

I was thinking I might be able to achieve my desired goal (rolling under walls)  by flagging certain walls as "passable_while_rolling". The wall under which I'm rolling could be thus flagged. In my collision code, these walls would be ignored if the sprite was in the rolling state.

A problem would occur, however, if the sprite finished rolling while intersecting one of these walls. In that case, the collision code would kick in and resolve the sprite to one side of the wall in an unattractive manner.

Another option would be to just keep the sprite in the rolling state until he no longer intersects any flagged wall (similar to how you can't shift out of morph ball until you have overhead space in Metroid). I don't want to do this since I think looping the roll animation is ugly and unrealistic.

So, my questions are:  What are my other options? How do other games deal with collision while rolling under walls?

I am open to drastically changing my collision resolution system.


texts: How to stop rendering a gameObject that has no rendering component in unity

texts: I want to stop rendering this gameObject. But the all-available renderer.enabled = false is not working. Is it because it has no rendering component attached? If so, how can I see it when it is not rendered?!


texts:
I am wondering what would be a good way to handle enemy crowds generation and simulation.

For example in a hack'n'slash game, how would one go about placing enemies and managing their movement in the world with it feeling at least a bit natural?

What I am looking for is the general approach behind this. I can write (and have written) some code to simulate as best as I can these things, but it feels a bit "hacky", it's just each enemy having a pre-scripted behavior. I am wondering if there are general simulations method to manage enemies walking in the world and chasing players, as it is an element that exists in many games.

In my case, what I have done is to give them random intervals of time in which they can choose a random direction and move for a random duration. Then if the player gets near a certain range they will stop that and chase him (applying pathfinding), but maybe there are more general ways of thinking others than pre-scripting pseudo-random behavior?


texts: Ara matrices calculated on the GPU or on the CPU? Would built-in matrix functions be faster than my custom ones?

texts: If I add a math library (for example containing a Matrix class) and use it in my program drawing with OpenGL, will my be work slower than if I used standard OpenGL functions for matrix calculations? Does the same hold true for DirectX?


texts: Can we use credit card/prepaid voucher payment systems in Android and iOS?

texts:
We already have a credit card gateway with a local bank. We also have a prepaid card voucher in the market.

In our game, a user will create an account within our portal. The user will "recharge" his account via credit or prepaid (voucher) cards. Then the user will buy services and subscriptions.

My question is: can I put our credit and prepaid card gateway in our Android and iOS apps in order to recharge a user account that belongs to our portal?


texts: In XNA 3.1, is it possible to disable texture filtering?

texts: I want to disable texture filtering (since I'm making a retro-style game where it looks bad if a texture gets filtered like that), but since I'm on XNA 3.1 there seems to be no option to set a SamplerState with SpriteBatch.Begin or anything. Is it possible to do this?


texts: Choose your own adventure console program

texts:
I'm new to programming and am writing a choose your own adventure game in C++ and am having trouble with exiting the program.

The way I have it set up is I am using functions as the different pages. So the program jumps around alot say from main to choice 1 to choice 2 to choice 5 to choice 3 and so on. It runs well aslong as I dont choose to go back. I have an int GameOver() function that displays if you die but after that message ends it will jump to another function.

I feel like I am doing this wrong but from all of my searches I can't find the right way to do this.

I have looked at the exit function but I am not sure if that is the right way to go about ending the program so abruptly or if I should end the program so abruptly.

I can post all of my code but really its just a lot of cout's and either a switch statement or if/if else/else loops.

Should my setup be dif.? Should I not jump from functions without returning to main?


texts: Should LOD models be used in mobile games?

texts:
LOD models are widely used in PC and console games, to optimize performance by reducing the vertex count and texture size for distant objects. However, I'm having a harder time finding out if they are typically used to increase performance in mobile games.

I've seen a few people in forums suggest that the CPU overhead for LOD models might actually outweigh the GPU gains on mobile devices. Another consideration is the more limited storage space on mobile, and LOD models/textures necessarily increase the total size of a game. Other than that, I can't find much information on the subject. The Unity documentation on LOD models doesn't mention mobile, and the Unity documentation on optimizing for mobile doesn't mention LOD models.

I know the first answer to any performance question is usually "profile it and find out for yourself"; however, in this case, I am helping to optimize a game that doesn't currently have LOD models, so profiling it would first require commissioning the artists to create enough LOD models that we can realistically profile the performance change.

Does the usage of LOD models typically provide noteworthy performance gains in 3D mobile games, or does the overhead for LOD cancel out any gains?

The specific title in question is a racing game.


texts: How to change mac opengl version back to mesa

texts:
A while ago I wanted to use the functionality of opengl 4.5+ on my mac, so I installed mesa with macports, and it worked. Recently, however, I tried to use my code again and it said that these versions of opengl are not supported.

I tried running glxinfo, and it seems to be telling me that my renderer is the default intel provided renderer.

The last time it worked was a reasonably long time ago, and it is likely that the reason for the switch is that when I restarted my computer at some point it switched back to the old version. I don't know exactly when it stopped working.

What I want to figure out is how to switch to the mesa version. I checked with macports and even looked at the files internally, and mesa is installed and updated to version 17.1.6, which is the latest version supported by macports. I can't find anything anywhere on how to change the renderer used by my computer. I think it has something to do with libGL maybe, but I can't find any information on how to change or even view libGL's environment variables.

How can I switch to the mesa renderer?

This is made especially difficult because I can't trust that the information from glxinfo is correct. Both mesa and the default intel renderers have their own versions of glxinfo, which may give information that is different from what the current opengl actually running on the system is. I'm not sure which one I am actually running when I run glxinfo with terminal, or how to find the executable for the mesa version.

EDIT: I have looked a little more, and it seems like I can control which version is used during context creation and API loading, but that requires manually doing those things, which is not something I really want to do. Currently, I have only tested this with JOGL, and I can't find anything on what it uses to create a context. I don't know if glfw will use the mesa version, but glew did install in the directory for the mesa/X version and not the core version that I think JOGL is using. It did work before with JOGL, so clearly there is some system wide default setting that can change this, and I would like to know what that is.


texts: How do I make bullets in a list intersect with bullets from another list, when both lists are not in the same class?

texts:
I have the initial "Game1" class, with a "Ship" class initiated inside, and within the "Ship" class there's a List, where the "Bullet" class is used.

How can I make a bullet in a list from one of the ship classes intersect with a bullet from the other ship's bullet list?

Do I have to make a list of Rectangles too for their hitboxes?


texts:
Hello,
I get this result when i try to scale and then translate a vec4 in my shader.
I created a mat4x4 class on my own and some functions wich return some matrices for me, everything works, but not the translationfunction.

Currently, I use this Shader Codes:

GLchar* vertexShaderCode = {
"#version 330 core                              \n"
"layout(location=0) in vec3 position;           \n"
"uniform mat4 scale;                            \n"
"uniform mat4 translate;                        \n"
"out vec4 vertexColor;                          \n"
"void main()                                    \n"
"{                                              \n"
"   gl_Position = translate*scale*vec4(position,1.0); \n"
"   vertexColor = vec4(1.0f,0.5f,0.7f,1.0f);    \n"
"}                                              \n"

GLchar* fragmentShaderCode = {
"#version 330 core                              \n"
"in vec4 vertexColor;                           \n"
"out vec4 color;                                \n"
"void main()                                    \n"
"{                                              \n"
"   color = vertexColor;                        \n"
"}                                              \n"

The matrix setup looks like this:

program.use(true);
h3d::mat4x4 mat_scale,
            mat_translate;
mat_scale     = h3d::Math::scale(.5f, .5f, 0.f);
mat_translate = h3d::Math::translate(.5f, .5f, 0.0);

GLint location_scale       = program.Uniform.getLocation("scale");
GLint location_translation = program.Uniform.getLocation("translate");

program.use(true);
glUniformMatrix4fv(location_scale,      1, GL_TRUE,mat_scale.getRowWiseValues());
glUniformMatrix4fv(location_translation,1, GL_TRUE,mat_translate.getRowWiseValues());

So basically, the h3d::Math::scale(X,Y,Z) returns:

X,0,0,0
0,Y,0,0
0,0,Z,0
0,0,0,1

And h3d::Math::translate(X,Y,Z) returns this:

1,0,0,X
0,1,0,Y
0,0,1,Z
0,0,0,1

The vertices are normal:

GLfloat vertices[] = {
    -1.0f, 1.0f, 0.f,
     1.0f, 1.0f, 0.f,
     1.0f,-1.0f, 0.f,
    -1.0f,-1.0f, 0.f,
};

What do I am doing wrong ? I really appreactiate your help !
All the other matrices are working (scale, rotate, perspective).


texts: How to make a map (game world) based on a real world place or city?

texts:
As a disclaimer before my real question, I have little experience in game development, only basic Unity knowledge.

I noticed a lot of games are based on real world places and cities, for example GTA 5 on Los Angeles and Watch Dogs. What is the process of making such a virtual version of a real world place or city? Or at least, what is a good starting point?

I imagine you could get some sort of map data or satellite images and import this in a tool, from which you can start modelling the buildings etc. But if this is the case I don't know how to do that.


texts: How to make an object oscillate left and right?

texts:
I can't seem to make an object move left and right, back and forth, on room start whilst on solid ground.

Codes I used:

Step Event:

if image_index is greater than 5, then physics_apply_force (0,0,100,0) for the right

if image_index is less than 5, then physics_apply_force (0,0,-100,0) for the left


texts:
I was making a game in java and exported it as jar file. Then after that, I opeed jar splice. I added the libaries and exported jar. I added the natives then i made a main class. I created a fat jar and put it on my desktop. I'm using Mac OS X 10.8 Mountain Lion. When I put in the terminal, java -jar System Front.jar it says unable to access System Front.jar Even if i double click on the file, it doesen't show up! Help! I'm using slick.

I added slick and lwjgl as libraries for the jar splice at the jars.


texts: Incorrect lighting results with deferred rendering

texts:
I am trying to render a light-pass to a texture which I will later apply on the scene. But I seem to calculate the light position wrong. I am working on view-space.

In the image above, I am outputting the attenuation of a point light which is currently covering the whole screen. The light is at 0,10,0 position, and I transform it to view-space first:

Vector4 pos;
Vector4 tmp = new Vector4 (light.Position, 1);
// Transform light position for shader
Vector4.Transform (ref tmp, ref Camera.ViewMatrix, out pos);
shader.SendUniform ("LightViewPosition", ref pos);

Now to me that does not look as it should. What I think it should look like is that the white area should be on the center of the scene. The camera is at the corner of the scene, and it seems as if the light would move along with the camera.

Here's the fragment shader code:

void main(){

    // default black color
    vec3 color = vec3(0);

    // Pixel coordinates on screen without depth
    vec2 PixelCoordinates = gl_FragCoord.xy / ScreenSize;

    // Get pixel position using depth from texture
    vec4 depthtexel = texture( DepthTexture, PixelCoordinates );
    float depthSample = unpack_depth(depthtexel);

    // Get pixel coordinates on camera-space by multiplying the
    // coordinate on screen-space by inverse projection matrix
    vec4 world = (ImP * RemapMatrix * vec4(PixelCoordinates, depthSample, 1.0));

    // Undo the perspective calculations
    vec3 pixelPosition = (world.xyz / world.w) * 3;

    // How far the light should reach from it's point of origin
    float lightReach = LightColor.a / 2;

    // Vector in between light and pixel
    vec3 lightDir = (LightViewPosition.xyz - pixelPosition);
    float lightDistance = length(lightDir);
    vec3 lightDirN = normalize(lightDir);

    // Discard pixels too far from light source
    //if(lightReach < lightDistance) discard;

    // Get normal from texture
    vec3 normal = normalize((texture( NormalTexture, PixelCoordinates ).xyz * 2) - 1);

    // Half vector between the light direction and eye, used for specular component
    vec3 halfVector = normalize(lightDirN + normalize(-pixelPosition));

    // Dot product of normal and light direction
    float NdotL = dot(normal, lightDirN);

    float attenuation = pow(lightReach / lightDistance, LightFalloff);

    // If pixel is lit by the light
    if(NdotL > 0) {

        // I have moved stuff from here to above so I can debug them.

        // Diffuse light color
        color += LightColor.rgb * NdotL * attenuation;

        // Specular light color
        color += LightColor.xyz * pow(max(dot(halfVector, normal), 0.0), 4.0) * attenuation;

    }

    RT0 = vec4(color, 1);

    //RT0 = vec4(pixelPosition, 1);
    //RT0 = vec4(depthSample, depthSample, depthSample, 1);
    //RT0 = vec4(NdotL, NdotL, NdotL, 1);
    RT0 = vec4(attenuation, attenuation, attenuation, 1);
    //RT0 = vec4(lightReach, lightReach, lightReach, 1);
    //RT0 = depthtexel;
    //RT0 = 100 / vec4(lightDistance, lightDistance, lightDistance, 1);
    //RT0 = vec4(lightDirN, 1);
    //RT0 = vec4(halfVector, 1);
    //RT0 = vec4(LightColor.xyz,1);
    //RT0 = vec4(LightViewPosition.xyz/100, 1);
    //RT0 = vec4(LightPosition.xyz, 1);
    //RT0 = vec4(normal,1);
}

What am I doing wrong here?


texts: 3Ds Max is exporting model with more normals than vertices

texts:
I made a simple teapot with the "Create Standard Primitives" option and exported it as a collada file, ended up with this:

< float_array id="Teapot001-POSITION-array" count="1590">

< float_array id="Teapot001-Normal0-array" count="9216">

For what I know there should be only one normal per vertex, am I wrong? What am I supposed to do with that much normals? Just put them on the normal buffer all at once normally?


texts:
I have a Visual Studio C++ project. I've just started out with SDL, and I've already rendered images, text, and now I'm trying to play audio. This will be done with the SDL_Mixer extension library.

However, I'm having the following issue. When I run my code with the SDL_Mixer library included, I get the following popup error message:

The procedure entry point SDL_AudioStreamFlush could not be located in the dynamic link library...

What the heck does this mean? Did I do something wrong with the installation? I got SDL mixer from here:
https://www.libsdl.org/projects/SDL_mixer/

Any help would be greatly appreciated!


texts: How to save/persist a GameObject with incremental levels? Dictionary? List?

texts:
I create buildings and they have child Text objects that will reflect the building level.

The Problem:

What can I use to store the buildings a player has built so the data can be persisted?

I've looked at Lists, but when I upgrade a building, how would I update the list so that particular building has its new level reflected?

I'm working on a dictionary so I can update the key with the new value (level) but running into a problem with the keys and names. If I have lets say 10 "Farms" and try to add them to the dictionary, even though they have different properties, I get an error that I have a duplicate.

Currently I am learning how to persist that data through scenes;

GameManager.CS

public class GameManager : MonoBehaviour
{

public static Dictionary<Building, int> playerBuilt = new Dictionary<Building, int>();

public void SaveState()
    {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open(Application.persistentDataPath + "/EmpireGame", FileMode.Open);

        SaveClass sc = new SaveClass()
        {
            food = Player.food.amount,
            buildingList = playerBuilt
        };

        bf.Serialize(file, sc);
        file.Close();
    }
}

[Serializable]
class SaveClass
    {
        public int food, wood, iron, stone;
        public Dictionary<Building, int> buildingList = new Dictionary<Building, int>();
    }

Building.CS

public abstract class Building : MonoBehaviour, IUpgradable {

    public int ID;

    //level this building is
    public Text levelText;
    public int level = 0;

    //starting cost to amplify the upgrade cost
    public int foodBase, woodBase, ironBase, stoneBase;

    //Upgrade cost
    public int foodCost, woodCost, ironCost, stoneCost;
    public float BuildingCostPercentage = 5f;

    public void UpdateDictionary()
    {
        if (GameManager.playerBuilt.ContainsKey(this))
            GameManager.playerBuilt[this] = level;
        else
            GameManager.playerBuilt.Add(this, level);
    }
}

Note: I have not tested the save function so I expect errors.


texts: Algorithm for dynamically calculating a level based on experience points?

texts:
One of the struggles I've always had in game development is deciding how to implement experience points attributed to gaining a level.  There doesn't seem to be a pattern to gaining a level in many of the games I've played, so I assume they have a static dictionary table which contains experience points vs. the level.  e.g.

Experience   Level
0            1
100          2
175          3
280          4
800          5

...There isn't a rhyme or reason why 280 points is equal to level 4, it just is.

I'm not sure how those levels are decided, but it certainly wouldn't be dynamic.  I've also thought about the possibility of exponential levels, as not to have to keep a separate lookup table, e.g.

Experience   Level
0            1
100          2
200          3
400          4
800          5
1600         6
3200         7
6400         8

...but that seems like it would grow out of control rather quickly, as towards the upper levels, the enemies in the game would have to provide a whopping amount of experience to level -- and that would be to difficult to control.  Leveling would become an impossible task.

Does anyone have any pointers, or methods they use to decide how to level a character based on experience?  I want to be fair in leveling and I want to stay ahead of the players as not to worry about constantly adding new experience/level lookups.


texts:
I'm working on a 2d sidescroller in PyGame. For each map we use one texture (this is the actual size of the texture):

Then we load the image with this code:

sprite = pygame.image.load("Maps/MapTesting.png")
sprite.convert()
sprite = pygame.transform.scale(sprite,
              (sprite.get_width()*6, sprite.get_height()*6))

As you can see, the texture gets blown up 6 times to create the actual map texture. On average this texture is about 4500x800. This texture has to be blitted to the screen every frame, because the whole screen is dirty (thanks to the side scrolling). We do that using this code:

screen.blit(sprite, (0, 0),
(cameraposx, cameraposy, windowheight, windowwidth))

And it works. The problem is is that it's quite slow: I get a meager 40 FPS on a low-decent PC, and that's without any of the actual AI/objects going on, while we're aiming for 60 FPS. How can we speed this up?

Note that the above code is sanitized and taken out of context. The full code can be found here: https://github.com/nightcracker/PyGG2

And last but not least, while the above image might look like 8-bit, there are elements in the game which require more bit-depth.


texts: Ward model implementation: specular component too weak

texts:
I'm trying to implement the Ward shading model, the anisotropic, computationally efficient version:

This is how I made it:

float alphaX=0.5, alphaY=0.5; // asinotropic roughness
float minFloat= 1.e-6;

vec4 Ward(vec3 L, vec3 N, vec3 V)
{
    vec3 H= normalize(L+V);
    float NdotL= max(dot(N,L),0.0);
    float NdotV= max(dot(N,V),0.0);

    vec3 e= vec3(1.0,0.0,0.0);
    vec3 T= normalize(cross(N,e));
    vec3 B= normalize(cross(N,T));
    float HdotT= max(dot(H,T),0.0);
    float HdotB= max(dot(H,B),0.0);
    float HdotN= max(dot(H,N),0.0);

    float beta= -2.0 * ( pow(HdotN/alphaX, 2.0) + pow(HdotB/alphaY,2.0) ) / (1.0 + HdotN);
    float den= max(minFloat, 4.0 * pi * alphaX * alphaY * sqrt(NdotL * NdotV) );
    vec4 specular= Ps * 1.0/den * exp(beta);
    return (Pd + specular) * NdotL;
}

But I get a result similar to a lambertian surface or Oren-Nayar model, where the specular component is absent:


texts:
static void BindBuffer(BufferTarget target, GLuint buffer)
{
    if(!glIsBuffer(buffer))
        throw runtime_error("This is not a buffer. WTF?");

    glBindBuffer((GLenum)target,buffer);
    check_gl_error();
}

In my app, this always throws the exception. However, if I remove the glIsBuffer() check, everything works fine. Suggestions?

Update

Okay, turns out that glIsBuffer() returns false if the buffer is not bound. Is this expected behavior? If so, how do I check if a buffer handle is valid before attempting to bind it? calling glBindBuffer() then checking for an error seems like a stupid way to accomplish this.

THE NEW QUESTION

I'd start a new thread, but seems silly since it's directly related to the original post:

Is there a way to determine if a handle refers to a GL object (buffer, program, shader, etc) without trying to bind it first? Is it really recommended practice to bind it, then check for an error?


texts: Is there a way to use the RGB channels of a texture as the alpha channel when applying multitexturing using OpenGL ES 1.1?

texts:
I have been trying to get texture compression using ETC1 (specifically PKM files) working for some time now. I am trying to do this without having to upgrade to OpenGL ES 2 so I have been using multi-texturing.

I have the multi-texturing working now (finally) but the problem is that it is not behaving as one would expect and I think that I have figured out why. When creating the PKMs you end up with PKM with the color components only and one with the alpha component only. Problem is that the alpha PKM seems to be storing the alpha value in the RGB channels. Black seems to represent full transparency and white seems to represent full opaqueness.

My question is: Is there a way to combine and convert these RGB values into an alpha value when using multi-texturing? If not, then I don't see any options for using ETC1 and supporting alphas under OpenGL ES 1.1 (please correct me if I am wrong).


texts: Saving and Loading the Game (Automatically or Manually) via Internal Storage Only (Tablet PC Issues)

texts:
Here is my question. When making a game app for Android, I considered first the device. It's no problem to save progress everything (from levels to records) on a smartphone because it has an SD Card slot. Exception to this, the tablet PC, it can really nothing but on internal only storage.

For example, I'm using this tutorial for audio spectrum (see http://www.youtube.com/watch?v=5cN1VzZXcdo) that involves copying from internal to external in order to detect frequency. It works on the desktop but not on the Android device (Tablets only [i.e. Google Nexus Tablet]).

Is there a way to optimize save/load game problems due to internal/external device issues? Plus, additionally, what's the reason why my device won't work on tablets, except the desktop, while testing the audio spectrum code and why? Also, is it the same with saving/loading game?


texts: How can I add a delay for each moving object?

texts:
The waypoints script :
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class Waypoints : MonoBehaviour
{
    public Transform objectToMovePrefab;
    public int numberOfObjectsToMove = 1;
    //with this approach, you use GameObjects to represent your waypoints
    //(they can be empty if you want the waypoint to be invisible)
    [SerializeField] private List<Transform> waypoints;

    private void Start()
    {
        for (int i = 0; i < numberOfObjectsToMove; i++)
        {
            var parent = GameObject.Find("Moving Object Parent");
            var objectToMove = Instantiate(objectToMovePrefab, parent.transform);
            objectToMove.name = "Platfrom";
        }
    }

    public int Count => waypoints.Count;
    public Vector3 GetWaypoint(int index)
    {
        return waypoints[index].position;
    }
}

Then in the editor I added this script to the prefab :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WaypointsFollower : MonoBehaviour
{
    [SerializeField] private Waypoints waypoints;
    [SerializeField] private float speed = 5f;
    [SerializeField] private bool goBack = false;
    [SerializeField] private float delay;

    private float startTime;
    private int waypointIndex = 0;

    private void Start()
    {
        startTime = Time.time + delay;

        waypoints = GameObject.Find("Waypoints").GetComponent<Waypoints>();
    }

    void Update()
    {
        if (Time.time < startTime) return;

        Vector3 waypoint = waypoints.GetWaypoint(waypointIndex);
        //movement
        float distance = speed * Time.deltaTime;
        transform.position = Vector3.MoveTowards(transform.position, waypoint, distance);

        //check if we've reached the waypoint
        float threshold = .1f; //how close is considered having reached the waypoint
        if (Vector3.Distance(transform.position, waypoint) < threshold)
        {
            //wraps back to 0 when we reach last waypoint
            if (goBack)
            {
                waypointIndex = (waypointIndex + 1) % waypoints.Count;
            }
            else
            {
                if (waypointIndex != waypoints.Count - 1)
                    waypointIndex = waypointIndex + 1;
            }
        }
    }
}

The delay is working but it's delaying all the WaypointsFollower's so they move at the same time after the delay.
I want that even if all the Followers have the same delay value for example 3 so the first one will start moving after 3 seconds then the next follower will start moving after another 3 seconds and so on and not that they all delay for 3 seconds and move together but to make delay so there will be spaces between the followers when they are moving.


texts: How to set root signatures specified in HLSL in my command list?

texts:
From Microsoft Docs, I can specify the root signature of my shader in HLSL. How do I use it though?

Since at the beginning of the command list, root signature is undefined. I need to use ID3D12GraphicsCommandList::SetComputeRootSignature(ID3D12RootSignature*) or ID3D12GraphicsCommandList::SetGraphicsRootSignature(ID3D12RootSignature*) set root signature, but having specified in HLSL instead of C++ code, I do not have a pointer to my root signature objects, how should it be done then?


texts: Converting 2D coordinates from multiple viewpoints into 3D coordinates

texts:
Here's the situation.  I've got a set of 2D coordinates that specify a point on an image.  These 2D coordinates relate to an event that happened in a 3D space (video game).

I have 5 images with the same event point on it, so I have 5 sets of 2D coordinates for a single 3D coordinate.  I've tried everything I can think to translate these 2D coordinates into 3D coordinates, but the math just escapes me.  I have a good estimate of the coordinates from which each image was taken, they're not perfect but they're close.

I tried simplifying this and opening up Cinema 4D, a 3D modeling application.  I placed 5 cameras at the coordinates where the pictures were taken and lined up the pictures with the event points for each one and tried to find a link, but nothing was forthcoming.  I know it's a math question, but like I said, I just can't get it.  I took physics in high school 6 years ago, but we didn't deal with a whole lot of this sort of thing.

Any help will be very much appreciated, I've been thinking on it for quite a while and I just can't come up with anything.


texts: Why is my collision resolution failing on the corners?

texts:
I'm tearing my hair out trying to work out how to handle my collision resolution at the corners of the rectangles that I'm colliding with.

The code that I'm working with is:

class Player(object):
    def move(self):
        # Calculate velocity based on gravity, etc
        # ...

        # Check collisions
        for obj in self.controller.collidable():
            sides = self.get_intersect(obj)

            if sides & TOP:
                self.mover.vy = 0
                self.mover.y = obj.coord.y + obj.size.y
            elif sides & BOTTOM:
                self.mover.vy = 0
                self.mover.y = obj.coord.y - self.size.y
            elif sides & LEFT:
                self.mover.vx = 0
                self.mover.x = obj.coord.x - self.size.x
            elif sides & RIGHT:
                self.mover.vx = 0
                self.mover.x = obj.coord.x + obj.size.x

        self.coord.x = self.mover.x
        self.coord.y = self.mover.y
        self.velocity.x = self.mover.vx
        self.velocity.y = self.mover.vy

    def is_intersecting(self, other):
        return (
            (
                self.coord.x + self.size.x > other.coord.x
                and
                self.coord.x < other.coord.x + other.size.x
            )
            and
            (
                self.coord.y + self.size.y > other.coord.y
                and
                self.coord.y < other.coord.y + other.size.y
            )
        )

    def get_intersect(self, other):
        if not self.is_intersecting(other):
            return 0

        pos = 0

        # Are we overlapping the bottom edge?
        if self.coord.y < other.coord.y < (self.coord.y + self.size.y) > other.coord.y:
            pos |= BOTTOM
        # Are we overlapping the top edge?
        if self.coord.y < (other.coord.y + other.size.y) < (self.coord.y + self.size.y):
            pos |= TOP

        # Are we overlapping the left edge?
        if self.coord.x < other.coord.x < (self.coord.x + self.size.x):
            pos |= LEFT
        # Are we overlapping the right edge?
        if self.coord.x < (other.coord.x + other.size.x) < (self.coord.x + self.size.x):
            pos |= RIGHT

        if pos == 0:
            pos = INSIDE

        return pos

The problem I'm experiencing is during vertical movement. If you push into a wall and jump, as you reach the top corner, it will push you vertically. This is due to the sides & TOP being the first check. Moving the horizontal checks first fixes this when jumping up, but then falling onto a corner moves the player horizontally.

I've tried doing checking based on what the horizontal/vertical velocities are, but this falls apart, since the vertical velocity is always non-zero due to gravity (and is corrected by this check if standing on a platform). Any other answers I've found fail to take this into account.


texts: How can I prevent cheating in a distributed multiplayer game?

texts:
A problem I've been thinking about recently is how it might be possible to create a multiplayer game without a centralised game server.

Is it possible to distribute "server" responsibilities across players? I feel like it would be too easy for modified/hacked clients to change the multiplayer experience, are there any ways around this?


texts: smoothly object transition through lerp and coroutine

texts:
IEnumerator SmoothlyShiftPosition(Vector3 destination, float OverTime) {

    float startTime = 0;
    while (startTime < OverTime)
    {
        Debug.Log(startTime/OverTime + "changing: " + navigationCanvas.transform.position);
        Debug.Log("startTime : " + startTime);
        navigationCanvas.transform.position = Vector3.Lerp(navigationCanvas.transform.position, destination, startTime/OverTime);
        startTime += Time.deltaTime * 2f;
        yield return null;
    }
    navigationCanvas.transform.position = destination;
}

I have this simple code snippet which i am using to lerp my object to specfied position smoothly it work sometime correctly but  not always. I logged different data and found that my startTime variable sometime becomes zero continuously. I am unable to figure why this occuring? what i am doing wrong?

Edit:

I am calling coroutine function like this

 if (SmoothlyShiftPositionIEum != null) {
                            StopCoroutine(SmoothlyShiftPositionIEum);
                        }
                       SmoothlyShiftPositionIEum = StartCoroutine(SmoothlyShiftPosition(navCanvas, smoothPositionTime));


texts: How to match UI background size with text length in Unity?

texts:
I am making an FPS game in which when you are near an item a UI Text appears at the bottom center of the screen indicating the name of the item and the button to pick it up (let's say [E]).

It works fine but since I couldn't get a clear contrast between the text and the game area (like if the player's standing in front of an egg and the color of the text is white, you can't see the text), I decided to add a black background image to the text.

Now since the item names are of different lengths, I need the image length to match the text length. The background image should just be enough to fit the text
How can I go about doing this? Or is there a better way to show a message to the player?


texts:
I have a car with the following aspect:

As you can see, colliders are locally static, because they are separated from the original rigidbody component.

Well, as you can suppose, I have a problem, because MonoBehaviours with an OnTrigger(...) or an OnCollision(...) method won't work. (It needs an rigidbody and a collider on the same object)

I thought about Raycasting:

https://docs.unity3d.com/ScriptReference/Physics.BoxCast.html

https://docs.unity3d.com/ScriptReference/Physics.CapsuleCast.html

https://docs.unity3d.com/ScriptReference/Physics.SphereCast.html

But I have another problem, I have to specify a direction, so, using this: http://answers.unity.com/answers/539155/view.html isn't an option because this is too slow?

What can you suggest me?


texts:
I'm trying to implement atmospheric glow like this. It was a huge pain to get it done, since I'm new to FBO and OpenGL, but I managed to do something similar to what the OP wanted.

I followed his steps and now I'm rendering the resulting texture to my space environment. However, the texture is completely opaque and I only need the glow parts to be visible. How can I make the rest of the texture transparent? I'm using OpenGL ES 2 on Android.


texts: How to generate or smooth really large procedural terrain?

texts:
I'm currently trying to generate a really large procedural terrain in WebGL. I use a quadtree for LOD and plan to generate 1 heightmap for each quadtree node (terrain patch).

The heightmaps are generated on the GPU and with such a large terrain, 32 bits floats don't have enough precision for the smaller terrain patches. This results in terrain becoming "blocky". This article uses bicubic surfaces to smooth things out.

I thought a lot about it and the only other solution I have is to generate the smallest terrain patche on the CPU (with double precision) instead of the GPU, but continue to generate the larger patches on the GPU. But this doesn't seem like the best thing to do. Does someone have an idea for a better solution?

Also, I can't use double precision on the GPU because I'm using WebGL, which doesn't support it.

Thanks a lot :)


texts: What would be a good filter to create 'magnetic deformers' from a depth map?

texts:
In my project, I am creating a system for deforming a highly detailed mesh (clothing) so that it 'fits' a convex mesh.
To do this I use depth maps of the item and the 'hull' to determine at what point in world space the deviation occurs and the extent.

Simply transforming all occluded vertices to the depths as defined by the 'hull' is fairly effective, and has good performance, but it suffers the problem of not preserving the features of the mesh and requires extensive culling to avoid false-positives.

I would like instead to generate from the depth deviation map a set of simple 'deformers' which will 'push'* all vertices of the deformed mesh outwards (in world space). This way, all features of the mesh are preserved and there is no need to have complex heuristics to cull inappropriate vertices.

I am not sure how to go about generating this deformer set however. I am imagining something like an algorithm that attempts to match a spherical surface to each patch of contiguous deviations within a certain range, but do not know where to start doing this.

Can anyone suggest a suitable filter or algorithm for generating deformers? Or to put it another way 'compressing' a depth map?

(*Push because its fitting to a convex 'bulgy' humanoid so transforms are likely to be 'spherical' from the POV of the surface.)

Edit: Here is an image/diagram rightly suggested that illustrates what I am trying to achieve.

Also, I should say since this question was posted I worked a lot more on this problem, and though I never solved how to the get the deformers I did eventually decide that depth maps for this were unsuitable as:

If the deformed mesh is not complete, it is possible to get texels in the map that are meant to be on the other side of the convex mesh (because they are not obscured by those closer to the camera on the correct side).
The efficiency was not as high as I had hoped due to the fact 6 maps were needed per deformation.

Not that these were unsolvable, but the other solution, which involved collision testing in kernels running on the GPU, resulted in higher quality results and was much simpler, even though it may not be as fast.

I still think this questions problem is interesting though and would be interested in any answers as I am sure there are situations where it would be preferred.


texts: Rotating an object to point towards the mouse

texts:
I'm using slick2d for this process and trying to rotate a minigun to face the mouse. My problem is that the minigun in my game is actually rotating but no towards the mouse at all! Also, the minigun goes as far as 180 degrees and stops there.

Here is my minigun class that I have put inside another core class to be updated and rendered.

public class Minigun {

    private Animation Shoot;
    private SpriteSheet sheet;
    private int x = 200, y = 150;
    private double angleToTurn;
    private Input input;

    public Minigun(){
        try {
            sheet = new SpriteSheet(new Image("res/minigun.png"), 130, 34);
            Shoot= new Animation(sheet, 1, 0, 2, 0, true, 1, true);
            Shoot.setLooping(true);
            input = new Input(1);
        } catch (SlickException e) {
            e.printStackTrace();
        }

    }
    public void render(Graphics g){
        g.pushTransform();
        g.rotate(x + Shoot.getWidth() / 2 , y + Shoot.getHeight() /2,   (int) angleToTurn);
        Shoot.draw(x, y);
        g.popTransform();
    }
    public void update(){
        double mX = input.getMouseX();
        double mY = input.getMouseY();
        angleToTurn = Math.toDegrees(Math.atan2(mY - y, mX - x));
        System.out.println(angleToTurn);
    }
}


texts: Structuring game narrative. Handling NPC, Quest, General Dialogue. Is Json/XML the right way to go? Or any other solutions?

texts:
Hello guys I'm try to make some games that have more to it than just simple high score scrolling shooters etc.

I'm trying to design my own systm of handling narrative. I want to be able to place NPC's in the game world, with scripts attached to them. Some of the NPC's would just have n random greetings. Others will be mission givers and will offer you a quest of sorts. (The quest could be go speak to Bob in the pub, or it might be bring me the Holy Grail and Crown Jewels, or something in between).

I've wracked my brain for a long while over this but sadly keep slipping back to the only way I know how, which is to manually code all the strings that people can say and have a horrible web of if statements and other such insanity to give me a rudimental dialogue system. Its not good enough even with just a few characters, but if I had dozens/hundreds of characters it would be even worse.

I've read lots about it already but I'm still very confused when I start trying on my own project. I've read that Json/XML might be the way to go and that I can add custom markups in the Json text to call methods in my code, but I dont even know if this is right and if so how I can do it.

The back of my brain is screaming at me that there is a simpler way to do it, but I've sat here for a very long time without managing to think of ideas.

Here is a diagram I drew which pretty much shows the flow of how I want my NPC to behave. If anyone can see this and then tell me how they might do something like this that would be fantastic!! (note: if Json is the correct advise, please give me a exact example of how exactly to format the Json in order to check the bools I mention in my flowchart - thanks!):

note: The circles denote an output from the data as Text for the dialogue system. The bools will need to be checked against by the data file to see which output to give (hope that makes sense and is possible)


texts:
I'm using a structure, where client sends his inputs every 20ms in one packet and server parses his inputs every update(20ms aswell).
I've got a problem, since player can send me more than one inputs packet per tick(if he uses cheats), so he can move faster than others. The thing is that I don't know how to check if his messages aren't too frequent.
Before, I've been doing like this:
Clients copy his inputs in buffer every 20ms and sends the buffer to server every 100ms. Server parse 1/5 of this buffer every 20ms and sends client's state to client. The problem was the thing that there was a big delay, and client's state on his screen was unstable since he sends message on 100ms and waits for server to parse it(100ms more) and it stacks so delay will be bigger with every client's message. I've been using this since server parses only one input message per 100ms, so even if client tries to cheat his speed will be the same.
My question is, how do other game developers do, how they can be sure that the server won't parse too much client messages and delay will be little?
I'm sure I miss something, since I don't see other questions like this one, it should be easy to fix, so please tell me if I'm wrong.


texts:
I am looking for a collision detection solution for use when 2d screen wrapping.  Specifically, when the image is split between the right and left side I can only detect a collision for a limited area.

For example, the program detects the collision when the rectangle intersects the circle in the first image.  However, it doesn't in the second image.  I am using the Rectangle.Instersects method to check for the collision in both cases.

I used the screen-wrapping solution at the following link:
How to create a 2D region where sprites are automatically wrapped?

However, since I am not using the physics engine, I am not using the related solution at:
How to create a very specific kind of joint in Farseer?

I am aware of the following question:
https://stackoverflow.com/questions/8679304/wrapping-drawn-image-in-xna-4-0, and incorporated part of the code to reset the draw rectangle's position when wrapping for both sprites:

 // reset draw rectangle for wrapping
        if (drawRectangle.X < -sprite.Width)
        {
            drawRectangle.X += parentWindowWidth;
        }
        if (drawRectangle.X > parentWindowWidth)
        {
            drawRectangle.X -= parentWindowWidth;
        }
        if (drawRectangle.Y < -sprite.Height)
        {
            drawRectangle.Y += parentWindowHeight;
        }
        if (drawRectangle.Y > parentWindowHeight)
        {
            drawRectangle.Y -= parentWindowHeight;
        }

This post also says that I have to check for the collision in the two separate positions, but I am having trouble doing so.

Any suggestions?


texts: Easy way to generate colour-per-vertex models for input to Blender

texts:
I procedurally generate 3D planet models that I would like to import into Blender.

I use colour per vertex rendering in my shaders (In practice, I use the same colour for all vertices of a face, but my vertex attributes include RGBA.)

I like generating wavefront .obj files, because the syntax is so easy. But wavefront obj does not let me specify colour per vertex, or colour per face. Instead, the entire object is coloured with a material from the material-library that accompanies the obj geometry file.

I've looked into collada .dae as well, but frankly, that seems like a very complex format, and it still seems to work with material libraries, like the .obj format does.

Is there an easy to generate 3d model format that lets me specify a colour per vert (or face) without material libraries, and can be imported into Blender?


texts: How can I get the borderSize/s of a plane?

texts:
public Texture2D gridImage;
public GameObject floor;

    private int borderSize;

    private void Start()
    {

        GenerateGrid();
    }

    void GenerateGrid()
    {
        Color gridColor = Color.cyan;
        Color borderColor = Color.black;
        Collider floorCollider = floor.GetComponent<Collider>();
        MeshRenderer floorRenderer = floor.GetComponent<MeshRenderer>();
        floorRenderer.material.mainTexture = gridImage;
        floorRenderer.material.mainTextureScale = new Vector2(floorCollider.bounds.size.x, floorCollider.bounds.size.z);
        floorRenderer.material.mainTextureOffset = new Vector2(.5f, .5f);

        Vector3 foorSize = new Vector3(floorCollider.bounds.size.x, floorCollider.bounds.size.z);
        for (int x = 0; x < gridImage.width; x++)
        {
            for (int y = 0; y < gridImage.height; y++)
            {
                if (x < borderSize || x > gridImage.width - borderSize || y < borderSize || y > gridImage.height - borderSize)
                {
                    gridImage.SetPixel(x, y, new Color(borderColor.r, borderColor.g, borderColor.b, 50));
                }
                else gridImage.SetPixel(x, y, new Color(gridColor.r, gridColor.g, gridColor.b, 50));
            }
            gridImage.Apply();
        }
    }

In the end I want to create something like this on a 3D Plane UI :


texts: OpenGL: Avoid geometry shader for cubemap framebuffer

texts:
I want to render an environment map into a cubemap framebuffer but I dislike the fact, that I have to use the geometry shader to set gl_Layer because the geometry shader would be a basic passthrough shader. Additionally a geometry shader could stall the pipeline and decrease performance.

I would rather like to use instanced rendering and set gl_Layer in the vertex shader but
unfortunately this is only possible with the AMD_vertex_shader_layer extension.

Is there any other way to set the layer in the shader?


texts: How do I access a Unity class from an Android Activity?

texts:
I have made my own C# classes in Unity. How can I access them from the Android Activity that starts the UnityPlayer?

Example: I have a C# class called testClass in Unity:

class testClass {
    public static string myString = "test string";
}

From the Android activity in Java, I want to access a member of that class:

string str = testClass.myString;

Is this possible? If so, how? Is there another way to do this? In the end, I basically want to communicate between my Android activity and the UnityPlayer object.

Edit: I found a solution.

I looked at building Android plugins for Unity but this wasn't satisfactory to me.

I ended up building a socket client-server interface in Unity with C# and another one in Java for the Android app: Unity listens on port X and broadcasts on port Y. The Android activity listens on port Y and broadcasts on port X. This is necessary as both interfaces are running on the same host.

So that's how I solved my problem, but I'm open for any suggestions if anyone knows a better way of communicating between the Unityplayer and your app.


texts: What are some good examples of exuberant in-game instructions for telling the player to repeatedly smash a button?

texts:
What are some good examples of exuberant in-game instructions for telling the player to repeatedly and quickly press a button or perform an action? I'm especially interested in examples in retro games (e.g., from the NES, SNES, and 1980-90s arcade eras), and I would love to see examples with text, graphics, or both.

To illustrate, here are a few examples of the type of instructions that I'm thinking of:

Smash the A button to lift something heavy!
Toggle the joystick back and forth to break free!
Quickly press the button to build power in a meter!

I'm working on a 2D iOS game with retro-style pixel art, and there's a point where I want the player to quickly tap on a sprite to complete an action. I have a serviceable starting point -- the word "TAP" flashing with an arrow repeatedly moving downward beneath it:

But it still doesn't feel quite right.

I would love to see some actual examples from the golden days of 2D gaming to use as reference material. I know examples abound, but I'm just struggling to think of any concrete ones at the moment.

Can you think of any examples of this type of thing in old games?


texts:
Is it a bad idea to use hard coded values for things like items (static data) that would change infrequently in an online game? I'm designing an online game in node js, and I'm trying to decide if it would be better to store the data in a database, or hardcoded in a javascript hash (and maybe cache some of the data in a db for filtering). Points I've thought up:

Since javascript is a scripting language, updating it wouldn't be a big deal, it would mean restarting the server, but it would seem most online games go through some sort of restart when introducing new things anyways.

Items in my game are really hard to define in data, as they can have wildly different functions, if its a javascript object, I can define a 'use' function for all of them and don't need to worry about creating a complex item definitions in the database.

If I used a database only, I would have to come up with some sort of way to define every possible item ever, and I don't think its likely I will imagine all of them.

I could use a database for things like name, and description, but still have a hash of functions somewhere.

Maybe having all these items hard coded could increase memory foot print of the web application as they would all always be loaded into memory?

I'm afraid I'm missing something important though? Is there a better answer? Or just preference? Is there a clear right way to do this?


texts: How do I add a delay in a switch statement?

texts:
float distance = Vector3.Distance(transform.position, player.position);
    var State = distance > 10 ? AIState.TowardsPlayer : AIState.Right;
    Debug.Log(distance);

    switch (State)
    {
        case AIState.TowardsPlayer:
            transform.LookAt(player.transform);
            transform.position += transform.forward * approaching * Time.deltaTime;
            break;
        case AIState.Right:
            transform.position += transform.right * 1f * Time.deltaTime;
            Invoke("AIState.TowardsPlayer", 2f);
            break;

I want it to have a slight delay after AIState.Right finishes its execution before moving onto AIState.TowardsPlayer. I put Invoke but it didn't work.


texts: What can I do to render generated 2D terrain in XNA?

texts:
I am working on a smooth terrain generation algorithm in C# and using XNA to display the data.

I am making it so it creates a new point halfway between each point per iteration, at a random height between the two. This works OK, and I am getting the current result, randomly placed points.

Now what I want to do is turn these points into a primitive (I think that is what it is) and display it like a mountain, obviously using a mountain texture. Example below (using different point data, made up in paint)

Any help or tips are greatly appreciated, and look forward to your responses.


texts: How do I make games that interact with desktop windows?

texts:
I want to know how games like desktop pet games like Sheep work, so I can make my own:

In this game, the creatures are being rendered directly to the desktop or over top other windows. How do they accomplish this task? How are they getting the window information? Do they take and process screenshots?


texts:
I just wanted to know if there was a way to find out the size of the window in XNA. I don't want to set it to a specific size; I would like to know what dimensions it currently displays as automatically. Is there a way to find this information out?

I realize I probably should have found this information out (or set it myself manually) before working on the game, but I'm a novice and am now hoping to work within the dimensions I have already become invested in. Thanks!


texts: Pathfinding with direction considerations

texts:
Consider the following road network. The car (orange) needs to get to the red circle. It drives on the right hand side of the road and is initially facing down.

The shortest path is the blue one. But if it follows this path, it reaches the red circle on the wrong side of the road. To actually get to the red circle, it needs to take the green path - much longer. The pink dots represent the nodes - the road network is made up of modular road pieces. Each node also stores all the possible directions a vehicle could take from that piece.

How can I make a pathfinding algorithm that takes this into consideration?


texts: How can I optimize performance when updating tiles?

texts:
So I'm making a side-scrolling adventure type game in Java. The worlds are procedurally generated, so I can't manually place tiles. Therefore, I every 20 ticks (1/3 second) I update every block's tile on the screen. I know this is a terrible solution, and it's causing a bit of lag. I tried only updating the blocks' tiles once when it was created, but it doesn't work well with the way I've programmed my world generation.

Basically, how the ground is generated is the top layer of ground is generated first, then when the player gets close enough, the layers below are created.

public void testForBlocks()
{
        topTaken=false;
        bottomTaken=false;
        rightTaken=false;
        leftTaken=false;

        for(int i=0;i<handler.screenBlocks.size();i++)
        {
                Block b = handler.screenBlocks.get(i);
                if(b.solid)
                {
                        if(b.oneWay==oneWay)
                        {
                                if(b.x==x&&b.y==y+32)
                                        bottomTaken=true;
                                if(b.x==x&&b.y==y-32)
                                        topTaken=true;
                                if(b.y==y&&b.x==x+32)
                                        rightTaken=true;
                                if(b.y==y&&b.x==x-32)
                                        leftTaken=true;
                        }
                }
        }

        setSprite();
}

This means that if I only update the tile's position once, the tile won't recognize that there is a block below it yet(because there isn't), and will be assigned the wrong tile.

Basically, my question is: How can I update tiles, while keeping it efficient?

I feel like I'm missing an obvious solution. Can anyone help me? Thanks in advance. :)


texts:
I am new to game development and I wanted to ask a question.

I am reading the simple game example from here.

1) I want to ask why we define bucket.x = 800 / 2 - 48 / 2 ? How is that?
Why not just set bucket.x=400 ( at the middle position).

...

camera.setToOrtho(false, 800, 480);
...
bucket = new Rectangle();
   bucket.x = 800 / 2 - 48 / 2;
   bucket.y = 20;
   bucket.width = 48;
   bucket.height = 48;

2) The bucket width and height are seet 1/10 of our screen size.Ok.
But what about the real dimensions of bucket object?I mean , the bucket what size must be?32x32 pix?48X48 pix?How we handle that?

3) Also, I am a bit confused about x and y dimensions.
x refers to width and y to height as we see the cell phone in portrait mode?
So , if we are in landscape mode , y is "x"?

Thanks!


texts:
I am using the code below to ask users for their username.

MyTextInputListener listenerz = new MyTextInputListener();
Gdx.input.getTextInput(listenerz, "Create Username", "");

I have knowledge in PHP but beginner in Java LibGdx.
I know that in HTML there is a REQUIRED

<input name='username' required />

That's why I wanted to know the equivalent coding in LibGdx for the REQUIRED input.


texts: Parsing OBJ file having multiple objects

texts:
I am very new to game development and have been following the youtube channel ThinMatrix for its GameEngine tutorials
https://www.youtube.com/playlist?list=PLRIWtICgwaX0u7Rf9zkZhLoLuZVfUksDP
In one of the videos, an OBJ loader is created. However, I noticed that for simplicity purpose, only the bare minimum parameters like faces, textures, normals, and vertices are parsed. (It is the same case for almost all the OBJ Parsers available online).
What I understand is that the assumption of a single object or a group is made.
On reading through the OBJ file format, I realized that there are several other attributes like Sub-objects (-o), Groups (-g) etc.
I am having trouble understanding how to parse these other parameters (if necessary). Should I load the vertices and faces data of every (-o) into separate VAOs?
Also, in that case, how will the rotation of the whole object work? Will all Sub-objects start rotating about their own centers?
How to make the multiple sub-objects rotate in unison like a single object and still have independent control over each whenever necessary?
Kindly pardon me for my verbosity. This is my first post.
Thank you!


texts: Category/genre name for games like: Ogame, Kings of Chaos, and Bitefight.?

texts:
I'm searching for a category name for games like: Ogame, Kings of Chaos, and Bitefight.

When I learned about those, they were just called browser games, but today where we have the technology to create every genre of games in the browser, I miss a box to put these: 'only text, pictures and no fancy animation-games' into.

Do they actually have a name, leading to my Google-Fu being miserable?


texts: Can a set of 3D positions be separated by plane?

texts: I have 3 points in 3D space: A, B and C. I also have another set of 3D points: P, Q, R, S, T and U. What would be the simplest algorithm to figure out if there exists a plane that completely separates the first and second set? I know all the coordinates of all points.


texts:
I have a semi-regularly (15fps to 60fps) sampled source of position and orientation to which I am using dead reckoning to fill in gaps.

However, I would like to smooth it further to eliminate any steps due to dead reckoning error.

The x,y,z can easily be smoothed with a small (3pts?, 5pts?) moving average filter. However, I am unsure of how to approach smoothing the orientation.

I have access to Axis angle representations and a decent Quaternion class that I could possibly build a moving average filter with. It has multiply (operator *) and power (operator ^) which in theory would allow me to effectively average a set of rotations.

Would filtering an axis angle representation work if I simply filtered the 'x','y','z' and 'a' channels and then normalized it?