texts: How can I draw multiple vertexbuffers with indices?

texts:
I'm using to types of vertices.

For the triangles:

 0 Vector3 Position,
12 Color Color,
16 Vector3 Normal

For the lines:

 0 Vector3 Position,
 12 Color Color

I setup a vertex buffer for each type, and adding them to the GraphicsDevice using VertexBufferBindings. My problem is that I'm only able to draw vertices from the buffer at index 0 of VertexBufferBinding-Array.

//
// This is only a shortened part of the code, which draws the lines but NOT the triangles
//
//
   protected override void Initialize()
{
//Triangles
avl = new AllrounderVertexList(new VertexElementUsageDescriptor[]{
  new VertexElementUsageDescriptor(VertexElementUsage.Position,0),
  new VertexElementUsageDescriptor(VertexElementUsage.Color,0),
  new VertexElementUsageDescriptor(VertexElementUsage.Normal,0)
});
//Clock- and counterclockwise
avl.AddAllrounderVertexList(new Vector3(0, 0, 0), Color.Orange, new Vector3(0, -1, 0));
avl.AddAllrounderVertexList(new Vector3(0, 10, 0), Color.Yellow, new Vector3(0, -1, 0));
avl.AddAllrounderVertexList(new Vector3(0, 0, 10), Color.Navy, new Vector3(0, -1, 0));
avl.AddAllrounderVertexList(new Vector3(0, -10, 0), Color.Gray, new Vector3(0, -1, 0));

//Lines
lines = new AllrounderVertexList(new VertexElementUsageDescriptor[]{
  new VertexElementUsageDescriptor(VertexElementUsage.Position,0),
  new VertexElementUsageDescriptor(VertexElementUsage.Color,0)
});
Color xCol = Color.Red;
Color yCol = Color.Green;
Color zCol = Color.Blue;
for (int i = 0; i <= 50; i+=5)
{
    lines.AddAllrounderVertexList(new Vector3(-50, i, 0), yCol);
    lines.AddAllrounderVertexList(new Vector3(50, i, 0), yCol);
    lines.AddAllrounderVertexList(new Vector3(i, -50, 0), xCol);
    lines.AddAllrounderVertexList(new Vector3(i, 50, 0), xCol);
    lines.AddAllrounderVertexList(new Vector3(0, -50, i), zCol);
    lines.AddAllrounderVertexList(new Vector3(0, 50, i), zCol);

}
short[] lineIndices = new short[lines.Count];
for (int i = 0; i < lineIndices.Length; i++)
  lineIndices[i] = (short)i;
indices = new short[6];
indices[0] = 0;
indices[1] = 1;
indices[2] = 2;
indices[3] = 0;
indices[4] = 3;
indices[5] = 2;

    //Adding indices for the 2 triangles at the end
short[] tmp = new short[indices.Length + lineIndices.Length];
Array.Copy(lineIndices, tmp, lineIndices.Length);
Array.Copy(indices, 0, tmp, lineIndices.Length, indices.Length);
avl.AvgNormalize(indices);
  indices = tmp;

triangleBuffer = new VertexBuffer(GraphicsDevice, avl.vertexDeclaration, avl.Count, BufferUsage.None);
triangleBuffer.SetData<byte>(avl.Data);
indexBuffer = new IndexBuffer(GraphicsDevice, typeof(ushort), indices.Length, BufferUsage.None);
indexBuffer.SetData<short>(indices);
lineBuffer = new VertexBuffer(GraphicsDevice, lines.vertexDeclaration, lines.Count, BufferUsage.None);
lineBuffer.SetData<byte>(lines.Data);
bindings = new VertexBufferBinding[2];
bindings[0] = new VertexBufferBinding(lineBuffer, 0, 0);
bindings[1] = new VertexBufferBinding(triangleBuffer, 0, 0);
GraphicsDevice.SetVertexBuffers(bindings);
GraphicsDevice.Indices = indexBuffer;
}
VertexBuffer triangleBuffer;
VertexBuffer lineBuffer;
IndexBuffer indexBuffer;
protected override void Draw()
{foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
{
  pass.Apply();

  GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,lines.Count, 0, 6, lineBuffer.VertexCount, 2);
  GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.LineList, 0, 0, lineBuffer.VertexCount, 0, lineBuffer.VertexCount / 2);
}
}

Do I need to switch somehow between the vertex buffers? Or what am I doing wrong?


texts: On a 2D generated terrain what is the easiest way to pick tiles for the shoreline?

texts:
If I have a two-dimensional array with ones and zeros for water and land respectively how do I choose what shoreline tile to use according to the water and land tiles surrounding it? The shoreline can form straight lines, outside corners and inside corners and there are four possible orientations for all of them. I have all the necessary tiles in the sprite sheet numbered. I want it to look similar to the shoreline in Age of Empires 2.

I could come up with a way to do this by comparing the eight surrounding tiles but this quickly became a mess as there are a lot of different possible combinations to take into account and manually assessing all of them with if statements seemed very unpractical and I'm quite sure there is a more elegant way of doing this. (I'm making this game with Slick2D)


texts:
I'm developing an isometric RPG, with 3D characters in 2D level. I was using a standard object orientated programming paradigm, but was faced with a lot of issues. Recently, I learned about entity component systems, and am currently rewriting my engine using this paradigm.

I use OpenGL, and have two rendering systems - one for drawing in 2D, and one for drawing in 3D. Each system consists of one VBO id, with the appropriate geometry, shader program id, id of texture unit binded to the texture atlas (which accommodates all tilesets or all model textures) and other information like that. The alternate systems provide different logic for drawing in 2D and 3D.

When it comes to the components for these systems, I am stuck.

Say I have component, defined by the buffer offset from the beginning of VBO buffer and the primitive count that needs to be rendered. Let's pretend that I have two instances of these components. The first instance belongs to the level floor entity, and describes the bunch of quad tiles. The second instance is a character mesh that belongs to the player entity. The first component instance should use the 2D rendering system, and second instance should use the 3D rendering system, but the data structure of these instances are identical. It must be said that I use EntityX and the components gets in the systems, automatically depending on their type.

Both systems require position and craphics components, so both systems will take both component instances, and one of these component will be processed improperly, what with a 2D graphics component in a 3D rendering system, and vice versa. I'm thinking about creating the "hollow" components, like sprite and model, which will indicate what graphics components in the entity mean. Since these component will not contain any properties, and would be used only as flags, this solution seems clumsy.

How do I better organise rendering in an entity component system?


texts:
I'm looking for a little direction.

I'm building a game engine as a part of my university project, and I'm having a little trouble about what to look for when it comes to indoor 3D game worlds.

Now I say indoor specifically because I have already set up an outside environment with heightmaps and skyboxes, so I'm roughly in the know with that.

What I'm struggling with is what I should be looking at to help me build an indoor level of my game, for instance on board a spaceship.

So my question is, how would I go about building an indoor world with walls, doorways, windows etc?

I'm using C++ OpenGL and SFML to build the engine, and the game levels in mind will be fairly big, so it would be appreciated if this was kept in mind whilst answering my question.

Any tutorials or guides will also be appreciated.


texts: I have recently started a project using SFML in C++. So far I haven't done much but I noticed an issue. Inside of the while(window.is_open()) loop I made a tick counter that increments every itteration through the loop, then I displayed the value with a sf::text object. I noticed that when I was in the starting resolution (~600 x ~400), It ran about 1000 - 1500 tick per second, but whenever I maximize, or even just increase the window size at all for that matter, the tick rate drops to around 250-500 per second. Is there anything I can do to elimante this, and possible any other performance issues I may encounter?


texts: How to check for every n value interval, but not exactly n

texts:
Let's say I have a game where the player earns n number of points when they pick up an item; the value of n differs depending on what they picked up. When they pick up an item, a method gets called that adds n value to their current total score.

Pseudo code:

void tallyScore(int scoreToAdd) {
   PlayerScore += scoreToAdd;
}

I want to give the player an extra life every time they reach y total points. Let's say 200, for now.

Pseudo code:

void tallyScore(int scoreToAdd) {
   PlayerScore += scoreToAdd;
   if (PlayerScore % 200 == 0) {
      GivePlayerExtraLife();
   }
}

The problem with the modulus approach is that if PlayerScore is currently 190, and we call tallyScore(11), the modulus condition will fail, but I still want to give the player an extra life because they've passed 200 points. If we were to call tallyScore(2) again, I wouldn't want to give them an extra life that time becasue we already did when we called tallyScore(11) previously.

What's a good way to check that PlayerScore has passed an interval of 200 points?

To reiterate, as the game went on, and PlayerScore becomes 395, I call tallyScore(8), I would then want to give the player another extra life since they earned another 200 points.


texts: Strategy for abstracting rendering from draw surface

texts:
This question might be a little vague because I don't know how to do this myself and I might be asking something rather silly. So here we go.

Up to now, when I did my personal graphics code I used OpenGL and something like SDL to get the context to draw. And my projects were rather small and educational. Now I want to structure things a little bit. Rather than having an OpenGL engine, I want to have an abstract renderer. Let's say I have something like;

/* Beware of possibly non-sense pseudocode */
class Renderer<typename DrawSurface>
{
    public:
    virtual void initialize();
    virtual void update();
    ...
    virtual void render();
    private:
    DrawSurface mDrawContext;
}

You could guess that this DrawSurface will represent where we draw. For example, this might be an image, a framebuffer, an OpenGL context from SDL etc. There could be an interface here and I am planning to implement this for needed drawing options. For now, I am planning to have a software renderer and a Qt OpenGL widget. Then, maybe I can do as follows in my initialize method:

void Renderer::initialize()
{
    mDrawSurface.setUpDrawContext();
    // ... other things
}

and this should set up an OpenGL context if DrawSurface implements it in that way. What I want to finally achieve is the ability to get different versions of my graphics program easily. Let's say I am using Renderer<QtOpenGLContext> in my editor. I am using a Qt widget to render and I am using other widgets from Qt for my editor's UI. My editor might have a tool button called Assemble and when I click on this I want a version with SDL context to be generated and compiled so that resulting graphics program will not depend on Qt, only the tools. The main part might look like this:

int main(argc, argv)
{
    Scene<OpenGLRenderer> scene;
    while(inGameLoop)
    {
        ...
        scene.updateScene(); // handle edit events
        scene.renderScene();
        ...
    }
}

Assemble will take this scene and convert it to have type Scene<OpenGLRenderer> and compile using that. So a need to serializing scenes, maybe, might also come into play here.

You can see that I am confused :). I am looking for strategies on how to achieve this. How we can encode this better on type system so that, for example, an OpenGL renderer won't try to render to an image but it will require an OpenGL context at compile time? How can we make it also work with physically-based rendering? This might require a rather long answer I reckon, so pointing to other resources like books, articles etc. is also fine.


texts: SDL - Getting a single keypress event instead of a keystate?

texts:
Right now I'm working on a simple SDL project, but I've hit an issue when trying to get a single keypress event to skip past a splash screen. Right now, there are 4 start-up splash screens that I would like to be able to skip with a single keypress (of any key). My issue is that, as of now, if I hold down a key, it skips through each splash screen to the very last one immediately.

The splash screens are stored as an array of SDL surfaces which are all loaded at the initialization of the state. I have an variable called currentSplashImage that controls which element of the array is being rendered on the screen. I've set it up so that whenever there's a SDL_KEYDOWN event, it triggers a single incrementation of the currentSplashImage variable.

So, I'm really not sure why my code isn't working correctly. For some reason, when I hold down a button, it seems to be treating the held button as a new key press event every time it ticks through the code. Does anyone know how I can go about fixing this issue?

[Here's a snippet of code that I've been using...]

void SplashScreenState::handleEvents()
{
    SDL_PollEvent( &localEvent );

    if ( localEvent.type == SDL_KEYDOWN )
    {
        if ( currentSplashImage < 3 && currentSplashImage >= 0)
        { currentSplashImage++; }
    }
    else if ( localEvent.type == SDL_QUIT )
    {
        smgaEngine.setRunning(false);
    }
}

I should also mention that the SDL_Event 'localEvent' is part of the GameState parent class, while this event handling code is part of a SplashScreenState subclass.

If anyone knows why this is happening, or if there is any way to improve my code, It'd be helpful to me! :D I'm still a very new programmer, trying to learn.

UPDATE:

I added a std::cout line to that the code runs multiple times with a single KEYDOWN event. I also tried disabling SDL_EnableKeyRepeat, but it didn't fix the issue.

void SplashScreenState::handleEvents()
{
    SDL_PollEvent( &localEvent );

    if ( localEvent.type == SDL_KEYDOWN )
    {
        if ( currentSplashImage < 3 && currentSplashImage >= 0)
        {
            currentSplashImage++;
            std::cout << "KEYDOWN.."; //<---- test cout line
        }
    }
    else if ( localEvent.type == SDL_QUIT )
    {
        smgaEngine.setRunning(false);
    }
}

This prints out "KEYDOWN..KEYDOWN..KEYDOWN.." in the cout stream when a button is held.


texts: Whats an elegant implementation for 2D collision detection in a block based game?

texts:
to make things clear, i do not want to know HOW to implement collision detection mathematically. What i am looking for is an elegant way to check for collisions without having to manage seperate lists of objects, maybe for example implementing a ICollidable interface.

currently i have a simple gameloop

while(runGame){ handleInput(); update(); render(); }

So there are two possibilities which come straight to my mind. First, ill add an extra call to a method or class handling collisions.

while(runGame){ handleInput(); update(); checkCollisions(); render(); }

Second, every gameobject gets a list of nearby other objects in its update method. so it can do the collision on its own

while(runGame){ handleInput(); update(otherNearShapes); render(); }

i dont like both of these for two reasons.

in the first, i have to manage a seperate list of objects which implement an ICollidable interface.

in the second, the update method handles more logic than it should in my opinion.

so, is there an elegant way of integrating collision detection in my game (loop)? searching the net always only results in how to calculate stuff, but thats not what i want to know.


texts: Adding multiple materials to a single mesh in three.js

texts:
I've been doing some reading and can't seem to figure out a good way to do this..

I have a simple globe with a material on it like so:

const earthGeomerty = new THREE.SphereGeometry( 4, 48, 48 );
const earthDiffuse = loader.load('assets/drought_earth_texture.png');
const earthSpec = loader.load('assets/drought_earth_texture_bump.png');

const material = new THREE.MeshPhongMaterial( {
    specular: 0xffffff,
    map: earthDiffuse,
    specularMap: earthSpec,
    normalScale: new THREE.Vector2( 1, 1 ),
    shininess: 5,
    transparent: true,
    depthTest: true,
    depthWrite: false,
    polygonOffset: true,
    polygonOffsetFactor: - 4,
    wireframe: false
} );

and I apply this material to my earthGeometry like so:

const sphere = new THREE.Mesh( earthGeomerty, material );

but now I want to add an atmospheric glow, which I found a nice extension for and created like so:

const atmosphereMaterial = THREEx.createAtmosphereMaterial();

but after doing a ton of reading I'm unsure of how to use both material and atmosphereMaterial to my single sphere mesh.

Any help? Thanks!


texts: Scaling sprites in a spritesheet without changing the overall size of each image

texts:
It might be more of a graphics software question - but, well, it concerns game development.

I'm using some free spritesheets found in the web, and basically one of the characters seems slightly scaled, causing it to poorly fit the others. I'm looking for a quick way to scale the individual images in this particular spritesheet, while keeping the original spritesheet "bounds" (sprites positions, sizes of individual images). In other words, I want to scale a whole bunch of separate image parts, without scaling the image as a whole (and without spending hours on it).

Wouldn't mind a solution using GIMP or a specific spritesheet manager application.


texts: "StrictMode policy violation" warning occurring in my game after upload

texts:
When I upload my game to my Android device, I get the following warning:

StrictMode policy violation: android.os.strictmode.NonSdkApiUsedViolation: Ljava/lang/invoke/MethodHandles$Lookup;-><init>(Ljava/lang/Class;I)V
    at android.os.StrictMode.lambda$static$1(StrictMode.java:428)
    at android.os.-$$Lambda$StrictMode$lu9ekkHJ2HMz0jd3F8K8MnhenxQ.accept(Unknown Source:2)
    at java.lang.Class.getDeclaredConstructorInternal(Native Method)
    at java.lang.Class.getConstructor0(Class.java:2325)
    at java.lang.Class.getDeclaredConstructor(Class.java:2166)
    at bitter.jnibridge.JNIBridge$a.<init>(Unknown Source:25)
    at bitter.jnibridge.JNIBridge.newInterfaceProxy(Unknown Source:8)
    at com.unity3d.player.UnityPlayer.nativeRender(Native Method)
    at com.unity3d.player.UnityPlayer.c(Unknown Source:0)
    at com.unity3d.player.UnityPlayer$e$1.handleMessage(Unknown Source:95)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:193)
    at com.unity3d.player.UnityPlayer$e.run(Unknown Source:20)

What causes this, and how can I resolve it?


texts: Using Unity's uNet to create a turn-based RPG

texts: I've been checking some tutorials about uNet and it seems pretty powerful. The NetworkManager is a great tool when you want to make generic games, but what is troubling me about it is the need of spawning a "Player". I intend to create a turn-based RPG, and for that, during the battle there's not a "physical player entity", there's two players which have a set of monsters and the players can select a monster to attack the opponents', but the player itself doesn't exist, in the end it sums up to a trade of commands between the clients. How can I achieve such an architecture with uNet? Should I discard the use of the default NetworkManager? Should I simply create a bodyless Player and go along with it?


texts: How to decide whether a Buff should be a component or a Buff object in an ECS?

texts:
I'm developing a top-down 2D game in Javascript using an Entity-Component-System architecture and I'm struggling with the question of exactly how to implement temporary buffs / permanent passives.
For example, let's say we want to give some entities Regeneration, such that they regenerate 5 health per second.
One option is to have a BuffsComponent that holds a list of all active buffs. You could create a RegenerationBuff object that inherits from some base Buff class, and then stick that in a list inside the BuffsComponent. Then a BuffsSystem would query all entities with a BuffsComponent every frame, and execute the active effect on each buff. Simple.
However, could you not argue that these effects could just be regular old components? That is, why not create a Regeneration component and then have a system that queries for all entities with a Regeneration component, and then update their health in that system?
Each approach seems to have its own pros and cons, and I'm not sure if I should have a mix of the two, or fully commit to one. I feel like fully committing to one approach would simplify the architecture and design of the program, so I'm leaning towards that, but I'm not sure which approach to pick. Even if I did have a mix, I'm not sure how to decide on what should be a component versus what should be a buff.
The first approach seems more computationally efficient I suppose? Because one potential implementation of such could involve you just iterating through the list of active buffs and calling execute on each one. However, I feel that while it may be more efficient, it may also be less powerful, because with the second solution I can directly query entities with certain buffs, so I could potentially have more complex interactions between entities based on who is holding which buffs. For example, with a Flight buff I would likely desire the ability to directly query entities with such a buff, so the latter solution would be preferable.
However, besides the latter solution being potentially slower, it also seems like it could get a bit out of hand. What if I ended up having over 100 different buffs? Adding and removing components to entities is O(1) with my ECS library, but still, it sounds like it could be a bit ridiculous to have hundreds of components for an entity, most of which are just random buffs / passives.
What should I do?


texts: How to store ever-expanding maps with top-bottom, left-right hierarchy?

texts:
I'm writing a game that will largely take place on only a screen-worth of hexagons, but which will require map to expand in every direction. Also the way I want to display those hexagons requires that I have to be able to iterate over them in order from top to bottom, left to right.

I have already written coordinate system, which can represent coords as 2d (axial) or 3d (cube). The system regards (0, 0) as the center hex, so it means I need to store negative coords as well.

What I don't have is data structure that fufills my needs.

I'm thinking about writing a data structure myself, which will consist of 4 two-dimensional vectors (each for one quadrant of the map in regards to positive/negative) that would be able to get hexes in order I want, but this solution (using 4 vectors) seems unintuitive and long to write.

So is there a simpler, possibly already implemented, way?


texts: Record video and sound from device camera and show it as a texture

texts:
I need to record and show video from a real camera device in iOS/Unity and show that video as a texture in RawImage (Image of what I want)

What I have tried so far:

Unity WebCamTexture API: It shows the camera in a texture but it has two problems! It does not record audio and does not have an API to save video!
Camera Capture Plugin: I bought this plugin but unfortunately it does not have the feature to show video in a texture; it just opens the camera device's application.
EverPlay plugin: I tried this plugin and it seems that it just creates a video from the screen and not the camera
Unity Video Capture API: There is also this API for recording video with sound but unfortunately it is part of Windows Mixed Reality and does not support iOS
Using Objective C: I tried to write the video recording section directly in Objective C, I did it but I could not find a way to embed that in the Unity scene -- I'm not sure it's even possible! (
what I tried)

I appreciate any other solutions that can help.


texts: How to ignore one unity package in source control

texts:
I've just installed the Unity quick search package. This is an editor extension which each developer should choose if they want installed or not. My problem is that because this was added as a package it also made changes to my project which would end-up in our repository.
The changes are:
Project root/
|── Assets/
|   |── Assets.index
|   └── Assets.index.meta
|── Packages/
|   |── manifest.json
|   └── packages-lock.json
|── UserSettings/
    └── QuickSearch.settings

Questions:

Should this files be added to source control?
How can I ignore the changes in manifest.json and packages-lock.json without filters?


texts: What is a good way to code dialogue creation?

texts:
I'm thinking of making a single method/class/something that will handle my dialogue in the game. AKA, something like:

Main text:

Choice 1
Choice 2

So I want a method that will able to put different strings into the main text section and also different strings into the Choice options. I've been thinking about solutions, and so far I've come up with just a simple method that accepts parameters for main text, choice1 and choice2 -- problem being that the strings called will be quite long and I think it looks a little clumsy? Also I won't want to have 2 choices every time, OR I want to have multiple "pages" of dialogue show up before you need to take an action. This would require me to overload methods which may turn out quite ugly?

So yeah I don't have a lot of experience with this and method overloading is all I've thought about for now. I've given thought to interfaces/abstract classes but I'm not entirely sure if they're even relevant for what I want to do. Any thoughts?


texts:
Right now I'm trying to calculate the model view matrix by hand... The App is 2D.
I have something like this:

Vector2 Transform_GetUpVector(DeadTransform *transform, bool normalized)
{
    Vector2 relative;
    relative.x = 0;
    relative.y = 1;

    float sin = Sin(transform->angle),
        cos = Cos(transform->angle);

    Vector2 vector;
    vector.x = relative.x * cos - relative.y * sin;
    vector.y = relative.x * sin + relative.y * cos;

    if (normalized)
        vector = Vector2_Normalize(vector);

    return vector;
}

Vector2 Trasnform_GetRightVector(DeadTransform *transform, bool normalized)
{
    Vector2 relative;
    relative.x = 1;
    relative.y = 0;

    float sin = Sin(transform->angle),
          cos = Cos(transform->angle);

    Vector2 vector;
    vector.x = relative.x * cos - relative.y * sin;
    vector.y = relative.x * sin + relative.y * cos;

    if (normalized)
        vector = Vector2_Normalize(vector);

    return vector;
}

Vector2 ScreenPointToSpace(struct Application *application, DeadCamera *camera, Vector2 point)
{
    GLint viewport[4];
    GLdouble //modelMatrix[16],
             projectionMatrix[16];
    GLdouble wz1 = 0, x = 0, y = 0;
    glGetIntegerv(GL_VIEWPORT, viewport);
    //glGetDoublev(GL_MODELVIEW_MATRIX, modelMatrix);
    glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix);

    Vector2 r = Trasnform_GetRightVector(camera->gameObject->transform, true);
    Vector2 u = Transform_GetUpVector(camera->gameObject->transform, true);

    GLdouble matrix[16] = {r.x, r.y, 0,      0,
                           u.x, u.y, 0,      0,
                           0,   0,   1,      0,
                           -camera->gameObject->transform->position->x / 1000, -camera->gameObject->transform->position->y / 1000, 0, 1 };

    GLint realy = viewport[3] - (GLint)point.y - 1;
    gluUnProject((GLdouble)point.x, (GLdouble)realy, 0, matrix, projectionMatrix, viewport, &x, &y, &wz1);
    Vector2 s;
    s.x = (float)x * 1000;
    s.y = (float)y * 1000;
    return s;
}

But When I rotate the camera, the matrix is wrong.... why?

As you can see in this image the hammer cursor means that the cursor is touching a red circle area.

But When I rotate the camera everything is at the wrong screen locations.


texts:
In a more performance-sensitive environment than a desktop CPU/GPU (namely a mobile device) is there really a point in determining whether or not to skip drawing non-visible objects vs reducing the number of draw calls?

I'm working with a scenario of an environment model that has ~10,000 triangles. I could split it up into 30 or so separate mesh such that less than half of those would be visible at any given point. However, would ~15 draw calls be more efficient than vs one draw call for all 10,000 triangles?


texts: OpenGL - How to draw a transition of two textures on one quad?

texts:
I know when drawing a rectangle, if we select red and draw two vertices, and then select yellow and draw the other two vertices, the entire rectangle will show a nice transition of color between those vertices and the middle of the rectangle will appear orange.

Suppose I have two textures, and I want to do the same kind of thing. On one rectangle, I want two vertices to use texture from one image and the other vertices to use the texture from the other image, and show a smooth transition in the middle.

Please show me how this can be done in OpenGL, thanks!


texts: Can I give prizes based on sharing a WebGL game link on Facebook?

texts:
I made a share to Facebook link for my WebGL Unity game and depending on when you share you get extra points. This is tied to a button which once pressed opens a new page to Facebook for sharing the link but at the moment when you press the button you get the extra points either way.
Is there a way to actually know when the content has been shared or not?


texts: I need to do an application similar to this Morfo. And I posted a question here where the answer states the solution is "Displacement Mapping" . And I googled this to do it in opengles. I couldnt get how to start and implement this in opengles. Can someone give me some starter on this?


texts: Communication between the SubSystems and the GameObject components?

texts:
Currently I have an architecture (not 100% accurate):

The RenderData contains primitives, which will be processed by the GraphicsEngine.

Upon creation I have to send the pointer of the renderData from the Renderer to the GraphicsEngine.
This is done by passing it to the GameObject, which passes it to the Scene, which passes it the Core, which will call the corresponding method at GraphicsEngine.

The problem with this is that the Scene has access to the Core. How can I register these RenderData's at the GraphicsEngine correctly?

And this is the same with Behaviour components signaling the AudioEngine to play a sound.

And this is also the same with the Rigidbody component's RigidbodyData and the PhysicsEngine.

But there is another problem: How do I signal the objects which have collided from the PhysicsEngine?

I have thought of registering the object ID at the RigidbodyData's of teh collided objects, which Renderer will sense this, and will handle the custom behaviours. (like what happens when a bullet is collided with a player)
And if this is good then how do I signal the custom scripts that there is a collosion with another game object? Upon creation of Behaviour's I add their OnCollide method to an array at Rigidbody? Or just instead of storing the Behaviours in the general Component container, have a separated container for them and just iterate through them and call OnCollosion?

Another problem: The Window handles the input, and have to signal these Behaviour components in the Scene.

So it has access the Scene, and on receiving input, it calls the Scene corresponding method which will spread the event somehow?


texts: How to determine if a 3D voxel-based room is sealed, efficiently

texts:
I've been having some issues with efficiently determining if large rooms are sealed in a voxel-based 3D rooms. I'm at a point where I have tried my hardest to solve the problem without asking for help, but not tried enough to give up, so I'm asking for help.

To clarify, sealed being that there are no holes in the room. There are oxygen sealers, which check if the room is sealed, and seal depending on the oxygen input level.

Right now, this is how I'm doing it:

Starting at the block above the sealer tile (the vent is on the sealer's top face), recursively loop through in all 6 adjacent directions
If the adjacent tile is a full, non-vacuum tile, continue through the loop
If the adjacent tile is not full, or is a vacuum tile, check if it's adjacent blocks are, recursively.
Each time a tile is checked, decrement a counter
If the count hits zero, if the last block is adjacent to a vacuum tile, return that the area is unsealed
If the count hits zero and the last block is not a vacuum tile, or the recursive loop ends (no vacuum tiles left) before the counter is zero, the area is sealed

If the area is not sealed, run the loop again with some changes:

Checking adjacent blocks for "breathable air" tile instead of a vacuum tile
Instead of using a decrementing counter, continue until no adjacent "breathable air" tiles are found.
Once loop is finished, set each checked block to a vacuum tile.

Here's the code I'm using:
http://pastebin.com/NimyKncC

The problem:

I'm running this check every 3 seconds, sometimes a sealer will have to loop through hundreds of blocks, and a large world with many oxygen sealers, these multiple recursive loops every few seconds can be very hard on the CPU.

I was wondering if anyone with more experience with optimization can give me a hand, or at least point me in the right direction.
    Thanks a bunch.


texts:
So recently I have been learning how to implement Diffuse Lighting in DirectX and I have done so with the following code:

float4 PS(VS_OUTPUT input) : SV_TARGET
{
    input.normal = normalize(input.normal);

    float4 diffuse = ObjTexture.Sample(ObjSamplerState, input.TexCoord);

    float3 finalColor;

    finalColor = diffuse * light.ambient;
    finalColor += saturate(dot(light.dir, input.normal) * light.diffuse * diffuse);

    return float4(finalColor, diffuse.a);
}

which has produced the following results:

Before I progress any further with specular lighting I wanted to clean up my code a little so I re-implemented this with a function and few changes.

float3 DirectDiffuseBRDF(float3 diffuseAlbedo, float nDotL)
{
    return (diffuseAlbedo * nDotL);
}

float4 PS(VS_OUTPUT input) : SV_TARGET
{
    input.normal = normalize(input.normal);

    float4 diffuseAlbedo = ObjTexture.Sample(ObjSamplerState, input.TexCoord);

    float nDotL = saturate(dot(input.normal, light.dir));

    float3 diffuseLighting = DirectDiffuseBRDF(diffuseAlbedo, nDotL);

    return float4(diffuseLighting, diffuseAlbedo.a);
}

Which produces:

As you can see the modified code has it's diffuse lighting a little different compared to the original. What am I missing from the original code to get it back to normal?


texts: How do I highlight the squares adjacent to my player in a Isometric grid

texts:
I am making a grid base RPG (like Fire Emblem but isometric) but currently I'm stuck on the movement, mainly the UI (showing how far the player can move around the board).
Like the image below where the person can go is highlighted in a blue square

Stuff I have done so far:

made the grid 5x5 isometric and learn and code a pathfinding system
made a battle system that set up the starting stuff (like starting spot, turn order, and teams)
two characters one player, one enemy with basic info (like health, mp, and speed)
and set up the UI for buttons and the sprites for the highlighted boxes

So this is where I am at and don't know where to go for the moving part.
This is what I am think might work for a solution:

the grid is the pathfinding grid so change it to a grid of gameObject and add a characters to it (but still don't know about the UI)


texts: Why are my canvas drawings larger than the actual image?

texts:
For the following page source, I've finally gotten a grip on rendering the cards.  I'm puzzled why they appear about 2.5x larger on the canvas.

<html>
  <head>
    <style>
      canvas#game-canvas {
        position: absolute;
        top: 5%;
        left: 5%;
        background: lightblue;
        height: 281px;
        width: 500px;
      }
      body {
        background: darkblue;
      }
    </style>
    <script type="text/javascript" src="jquery1_10_2_min.js"></script>
    <script>
    // $(document).ready(function() {
      window.onload = function() {
      var canvas = document.getElementById("game-canvas");
      var context = canvas.getContext("2d");

      var cards = cardsheet('small_playing_cards.png', 50, 68);
      context.drawImage(cards[0], 10, 10);
      context.drawImage(cards[1], 50, 50);

      function cardsheet(path, frameWidth, frameHeight) {

         this.image = new Image();
         this.frameHeight = frameHeight;
         this.frameWidth = frameWidth;
         this.image.src = path;

         var card_sprites_canvas = [];
         var card_sprites_context = [];
         var card_names = [
         '1d', '2d', '3d', '4d', '5d', '6d', '7d', '8d', '9d', '10d', 'Jd', 'Qd', 'Kd',
         '1h', '2h', '3h', '4h', '5h', '6h', '7h', '8h', '9h', '10h', 'Jh', 'Qh', 'Kh',
         '1s', '2s', '3s', '4s', '5s', '6s', '7s', '8s', '9s', '10s', 'Js', 'Qs', 'Ks',
         '1c', '2c', '3c', '4c', '5c', '6c', '7c', '8c', '9c', '10c', 'Jc', 'Qc', 'Kc'];

            framesPerRow = Math.floor(this.image.width / frameWidth);
            framesPerCol = Math.floor(this.image.height / frameHeight);
            k = 0;

            for (i = 0; i < framesPerRow; i++) {
              card_sprites_canvas[k] = document.createElement('canvas');
              card_sprites_canvas[k].width = frameWidth;
              card_sprites_canvas[k].height = frameHeight;
              card_sprites_context[k] = card_sprites_canvas[k].getContext('2d');
              card_sprites_context[k].drawImage(this.image, frameWidth * k, frameHeight * 0, frameWidth, frameHeight, 0, 0, frameWidth, frameHeight);
              k++;
            }

        return card_sprites_canvas;
      }
    };

    </script>

  </head>
  <body>
    <canvas id="game-canvas"></canvas>
    <img src="small_playing_cards.png">
  </body>
</html>


texts: Efficiently blit texture rotated by 90° to renderer with SDL 2

texts:
Let's say I have a 1024x768 SDL_Window, an SDL_Renderer bound to that window and a 768x1024 SDL_Texture into which I do my rendering. How can I render that texture such that it is rotated by 90° to fit the screen exactly (1:1 mapping between texels and pixels)?

I tried using the SDL_RenderCopyEx() function but I couldn't make it work properly with non-square window and texture, probably because it doesn't support scaling.


texts: How to access rotation-Z value in script?

texts:
My script(MouseLookController) is attached to a GameObject and I want to limit it's rotation between 90deg and -90deg.(Rotation is 40 deg in example image)

Problem is I can't access this value to check it. How can I access the rotation Z of this gameobject?

I've tried:

transform.localEulerAngles.z
transform.rotation.z
transform.eulerAngles.z

Meaning they won't return 40.695 value, where is this value currently stored?
Couldn't find it in the GameObject.


texts: How can I implement real-time mutual object reflection?

texts:
So, given a scene like this (cubemap skybox with "real" spheres)

Everything looks great, except for the fact that the spheres don't reflect each other.

What's a good way to go about this? The first thing that came to mind was to render an environment map for each cube, and apply that to each cube along with the skybox. However, that will be insanely slow when updated per frame, given that the spheres are moving relative to each other and a static map won't work.

I realize this may fall under the category of ray tracing and be difficult to achieve real-time, but perhaps someone has addressed this problem in the past?


texts:
I am working with AndEngine with Box2d extension, but general answer or a concept idea will be appreciated too.

I have feather-like objects in a 2D side view world that I want to be part of the physics simulation. I am using linear damping to make the "feather" fall slowly. This might not be a good idea, maybe I should rather apply force in each update, but nevertheless, this works and it makes the object look "light" and it feels like there is air with resistance.

Now how can I make the objects actually look like feathers falling through air?

Specifically I am looking for two types of objects: Long with low density, that should move down in a slow swinging motion and square objects that would just randomly change trajectory. It would be great if this could be one simulation and length would be a parameter - the longer the object is, the more it would swing. Right now I want to simulate feathers, leaves and snowflakes in a cartoon world.


texts:
If im trying to create an obj. file loader in c++ and draw it with opengl i need to use multiple textures in the fragment shader.I know i can just use:

`uniform sampler2D Texture1`
`uniform sampler2D Texture2`
`uniform sampler2D Texture3`
`uniform sampler2D Texture4`

But i think there must be an elegant way to do it.Like a vector of samplers or something.Im asking this because i dont want to declare n textures in my fragment shader and type n if's where i test which texture i should use for the current fragment.It just looks ugly.


texts: How to ensure that a 3D coordinate at Z=1 act like a 2D coordinate (using perspective projection)

texts:
Possible Duplicate:
  OpenGL ES 2.0: Mixing 2D with 3D

The title probably is not that clear but please help me out here. I am going to write a (mostly) 2D game using OpenGL ES 2.0 so if I have a vertex at (5,10,1) I want it to be drawn at the (5,10) pixel on the screen. But I can't use orthogonal projection because I'll still use some few real 3D objects on it to give a cool effect, and I want to preserve the perspective distortion on their vertices with Z > 1.

How should I set up my view/projection matrices to achieve this?

note: I am so sorry if this sounds like a noob question, but please take in account that I am a noob myself...


texts:
Nowadays, most music seems to be prerecorded, but that means they are rather static and take up a lot of space.

I wonder if MIDI is still a viable option (especially considering consoles or iOS) and if I can expect General Midi 1 to be available everywhere? (Note: Referring to the software instruments for sound generation from notes)

Alternatively, are there vendors of embeddable software instruments that can generate the desired sound at runtime?

The whole point is to re-create a dynamic soundscape in which instruments can change their volume, speed or pitch - this can be partially simulated with individual tracks, but it doesn't offer the same flexibility.


texts: Why doesn't anything run after the yield return new line

texts:
I am trying to make a fade to another scene in unity when I came across a problem. For some reason when the coroutine begins the Ienumerator it only runs half of the Ienumerator Method which is only the anim.SetForBlue line. Heres my code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Loseforcube1 : MonoBehaviour
{

    public GameObject blueWinPanel;
    public Animator animForBlue;
    // Use this for initialization
    void Start()
    {
        blueWinPanel = GameObject.Find("Blue win panel");
        animForBlue = blueWinPanel.GetComponent<Animator>();
    }

    public IEnumerator WaitTillNextScene()
    {
        animForBlue.SetTrigger("FadeBlueWin");

        yield return new WaitForSeconds(3.9f);
        SceneManager.LoadScene(2);
    }

    void OnTriggerExit()
    {
        if (GameObject.Find("Cube Player 2"))
        {
            StartCoroutine(WaitTillNextScene());

        }
    }
}


texts:
I have a scene where many spot lights are focused on the screen. All have red color and same intensity. What I want is that the red Color(0,0,0,1) value should increase and decrease in a fading effect over a period of time. I thought of using Color.Lerp() but can not achieve it. What currently I am doing is attaching this script to all the instances of the SpotLight.

void Update()
{
 if(Time.time()%120==0)
   transform.light.color=new Color(Random.Range(0,255),0,0,1);
}

I know I am missing something big here. Help is appreciated. Thanks in advance.


texts: Compare world space distance to shadow map depth

texts:
I am rendering shadow maps to cubemaps (just rendering raw depth buffer) then projecting them to the scene to do omni-directional shadow mapping.
The cubemap is sampled by the light direction vector on each fragment:

float3 lightvector = pos3D.xyz-lightPos.xyz;
float shadowmap = xTextureSh.Sample(Sampler,lightvector).r;

If I compare the shadowmap value to the lightvector length which is the distance from the fragment to the light, I get wrong results because that distance is in world space units, whereas the shadowmap values are not, they are normalized values.
My question is, how could I normalize the length of the light vector the same way the shadow map is normalized? I don't access the shadow view matrix in the fragment shader to do a W division on it, because I would need to send 6 matrices there and I switched to cubemaps exactly to avoid that. I do know hovewer the far clip distance to the shadow cameras, if it counts.
Previously I tried to multiply the shadow map value with the camera far clip distance reading this presentation (on the 30th page), but had no luck. What am I missing?


texts: Behaviour Trees: How to clean up when a sequence is interrupted?

texts:
I'll try to show my problem on a minimal example, in reality it's more complex:

It's a simple behaviour, that repeats "an action" that has a certain animation. If a player gets close, this sequence gets interrupted and the AI executes the "Flee" action.
The interruption happens because the top level selector is "dynamic" which in Unity/NodeCanvas means, that its higher priority nodes get executed every frame and if they succeed they interrupt the lower priority ones.
My problem is shown via the red arrow - if the "action" gets interrupted, the clean up (in this case "stop animation") doesn't execute.
What is the best practice to handle the clean up? Is my setup flawed? Or should I just be using a different interrupting mechanism?
Thanks for any help!


texts: Can you use a public instance variable of one class within another class(A) in c++?

texts:
A simple hypothetical example:

A.h

using namespace std;

class A {
public:
    int m_variable = 5;
}

B.cpp

include iostream>

using namespace std;

void B::method() {
    // Why do get an error stating 'invalid use of non-static data member on this line?
    int x = (A::m_variable) * 2;
    cout << x << endl;
}


texts:
I'm trying to create a 3D-model skeletal animation system for C++/Open GL. I would like to be able to mix animations by allowing animations to only affect specific bones.

My game has ride-able creatures, which affect the players legs to animate him sitting. But while he is sitting, the items he is holding must control his arms, independent of the legs.

I almost feel like hand-coding the bone rotations would be easiest, even if it means low animation quality.

How can I make this work?
Are particular model file formats better-suited for this?


texts:
I'm working on an Android app/semi-game (API 19-23, Java) and I used this website to help me handle controller input. Overall it looks pretty similar to what the website says for "Process Gamepad Button Presses":

public boolean processKeyEvent(int keyCode, String name) {
    boolean handled = false;
    switch (keyCode) {
        case KeyEvent.KEYCODE_BUTTON_L1:
            ...
        case KeyEvent.KEYCODE_BUTTON_R1:
            ...
        case KeyEvent.KEYCODE_BUTTON_A:
            ...
        case KeyEvent.KEYCODE_BUTTON_B:
            ...
        case KeyEvent.KEYCODE_BUTTON_X:
            ...
        case KeyEvent.KEYCODE_BUTTON_Y:
            ...
        case KeyEvent.KEYCODE_BUTTON_START:
            ...
        case KeyEvent.KEYCODE_BACK:
            ...
    }
    if(handled) {
        return true;
    }
    return false;
}

and:

public boolean dispatchKeyEvent(android.view.KeyEvent event) {
    if(event.getAction() == KeyEvent.ACTION_DOWN) {
        handled = script.processKeyEvent(event.getKeyCode(), event.getDevice().getName());
    }

    if (handled) {
        return true;
    } else {
        return super.dispatchKeyEvent(event);
    }
}

It does return the right keycodes (according to this list), so:

L1: 102
R1: 103
A: 96
B: 97
X: 99
Y: 100
Start: 108
Back: 4

The problem is that half of the buttons not only activate through their right case but also other ones, which then has side effects of course:

B activates: X, Y, Start
X: Y, Start
Y: Start
R1: A
L1: R1, A

At first I thought that maybe the controller (SteelSeries Stratus XL for Android) had broken but I already checked with a second one (MogaPro Power) and I got the same results with it.

Has anyone else experienced this before? Any idea what I could try to fix this?


texts: Different ways to mark the status of an enemy

texts:
I have a 3D game with a "eagle view", I have enemies and I have magics that will affect the status of the enemies.

I want to show the status of the enemies( frozen, on fire(dot damage), slowed...etc)

I think about two possibilities

Put a 2D image in the enemy that show status
Change the color of the enemy with vertex shaders

Is there other,or correct way?
In case of use vertex shader, how I change the color of enemy without losing all details(Something like a filter)?
shaders


texts: How can I create a .ico file with all the various resolution sizes within one container?

texts:
I was looking at this GOG.ico in ffmeg, and was surprised to see all the streams for it...indicating it was holding multiple images in the .ico container or .ico has some kind of self-creation function where it generates the resolutions from a singular image based on condition? Or Maybe I'm overthinking it and its just a container with 7 different image variants stored inside?
Regardless I was curious on what the method of creation was for this many .ico in one hybrid, and how to replicate it. I'm already familiar with how to create a singular .ico image using gimp and/or ffmpeg....gimp is probably using ffmpeg itself. If its 7 images, those can be mapped to various streams of the .ico container using a tool like ffmpeg.
What's a more automated workflow people use to create these kinds of elaborate .iso though?


texts: How can I un-bloat my player input processing in my text based game?

texts:
I'm writing a text based game, and I hit a snag with the user commands processing: so far I have a huge hardcoded ifelse block, and that does not seem good or scalable.

With single word non session commands it is easy:

> quit

Here I know I simply have to quit; but when it comes to multi word commands, like:

> help skills
> use bag
> take sword from bag

the if/elseif/else pattern is so cumbersome and not scalable.

Also, with regards to commands in one session, like so:

> open box
> look inside box
// you see next items inside box: one, two, three
> take one

how can I process different options depth, when each command received from client is processed from the beginning? How to respond with "first you must open box to take items from it" if user enters "take one" without prior "open box"?

How can I organize and process user input efficiently here?


texts: Has anyone some code about a skydome mesh with a texture and a shader? Or even know how can I create a skydome mesh in Direct3D11? I wanted give an idea from https://ifun01.com/R8CTFZQ.html but it needs the md3 skydome mesh and without a sky texture. So I still think.


texts:
I'm trying to create a simple topdown game, in which you control the player by WASD keys and use mouse to aim and shoot. So far, I have a player moving and firing, but I think there is something wrong with the shooting.

Accuracy gets lower as the mouse cursor move away from the player.

Please try the following SWF to see more clearly what I'm trying to say.

http://dl.dropbox.com/u/24777511/gdstack.swf

Here is a chunk of relevant code:

private function fireBullet(x:Number, y:Number, dFireAngle:Number):void {
            var b:Bullet = recycleBullet();
            var rFireAngle:Number;
            b.reset(x, y);
            b.angle = dFireAngle;
            rFireAngle = (dFireAngle * (Math.PI / 180));

            b.velocity.x = Math.cos(rFireAngle) * 385;
            b.velocity.y = Math.sin(rFireAngle) * 385;
        }

...

if (FlxG.mouse.pressed()) {

                    var p:FlxPoint = new FlxPoint(FlxG.mouse.screenX, FlxG.mouse.screenY);
                    var angle:Number = FlxU.getAngle(new FlxPoint(player.x, player.y), p) - 90;
                    fireBullet(player.x, player.y, angle);
...


texts: How do developers get their money with Steam Direct?

texts:
Here's what I know:
Steam is a digital distribution platform developed and owned by the Valve corporation. Steam is mostly known for its video games, XR software, and game development programs. Earlier, the products that were to be published to Steam were decided by the method of voting. This system was called Steam Greenlight. Now, a developer can just pay a sum of IN₹ 7,000 (US$ 100) and publish his/her product to Steam directly. This new system is called 'Steam Direct'.

Here's what I need to know:

In the new system of Steam Direct, do developers get any money off every copy of their product(s) sold on Steam?
If they do, what percentage of money is kept by Steam (or taken away for taxes and/or other purposes) and what percentage is given to the developers of the product?
If developers do get money by selling their products on Steam, what is the most common means by which they receive payments?


texts: How to resize my 2d game to fit the screen?

texts: I am currently making a 2D game using Java (Java 2D). I want to make my game resizable. If you play any game on an emulator (e.g. legend of Zelda in fceux emulator) in full screen mode, you'll see that the 8-bit or 16-bit game re-sizes to fit the screen size. How can I implement the same thing in my game programatically?


texts: How are flow fields different from potential fields?

texts:
I've heard of of both flow fields and potential fields for pathfinding in games. They sound similar, but I never see them mentioned in the same contexts. Places that mention one never mention the other, as if they're completely unrelated.

How are they different? Why would I choose one over the other?


texts:
I'm developing an Android game and have some troubles: I want to add some foreground sprites, that must obstruct my player.
Se the following example: Its a screenshot from "Shinobi 3". We can see the player, the enemy, the background and two foreground trees, that hide the player's arm and part of the enemy.
I'm using AndEngine GLES2 Anchor Center and I am trying to add a new layer to my scene.
Sprite Forest = new Sprite(getWidth() * 0.5f, textureHeightForest * 0.5f + 100, ResourcesManager.getInstance().foreground_forest_region, vbom);
Entity foregroundLayer = new Entity();
foregroundLayer.attachChild(hillFurthest);
attachChild(foregroundLayer);

But it still shows behind my player sprite. I am trying to find something in HUD-class (it's always shown in the foreground), but got no results. Can anyone help please?


texts: FBX Import Errors: "Multiple roots are found in the bone hierarchy"

texts:
I followed these steps:

I exported my character from Blender as an fbx file

I went to Unreal Engine and make a new folder

I paste the fbx file in that folder

I put and tried to put it with a skeleton

I get the following errors:

❕ No smoothing group information was found in this FBX scene.
❕ Could not find the bind pose. It will use time 0 as bind pose.
 Multiple roots are found in the bone hierarchy. We only support single root bone.
❕ Get Import Data has failed.

I think it is an issue with Blender. Specifically, I think it is a problem with the spine names. The character has a skeleton I on it in Blender.
[


texts: How How can I make a simple combo combat system in Unity

texts: I'v been trying to make a melee combo combat system in the Unity Animator, but I can't seem to get it right. I'm trying to go for a combo system that flows from Hit 1 to Hit 2 to Hit 3, ect, with clicks from my mouse, and if I don't click again it will go back to Idle. How would I go about making this combo attack system in the Animator with Unity and C#.


texts: Chess Artificial intelligence with python and pygame

texts:
I created chess game with python and pygame. Now I'm trying to make Artificial intelligence, but what is actually best way to do it? Some tips, tricks, links?
Thanks


texts: Using Burst Compile attribute on methods

texts: Can we use BurstCompile attribute without using any Jobs or ECS System in Unity? does adding [BurstCompile] attribute before methods bring us any benefits?


texts:
In Unity, what happens if I delete the meta files? Or if I import files, but not their respective .meta files?

What are some issues I could come across? Is there ever a reason I would want to delete meta files?

I was asked this question recently, and I do not know the answer.


texts: How do you stop an Ogre PSSM shader from creating unwanted or blocky shadows due to large 'world size'

texts:
I'm using PSSM Shadows in Ogre 1.6.4 and I have a scene which is around 100m square.

I also create a flat ground texture which does not cast shadows and extends off towards the horizon, but when I do this, and the Sun light source goes towards the horizon at dawn or dusk, then I get extra shadows at the edges of some of my objects. It's like some kind of self shadowing.

I'm using custom shaders, but the Ogre PlayPen PSSM shader also goes beserk in this environment too.

I've read that the world size can affect texture shadow mapping.

Is there a technique to allow this ground area to exist (ie my world to be big) without affecting my PSSM shadowing?

(btw - my derived light direction is correctly normalized!)


texts: Does libGDX support the Xbox One controller?

texts:
I just bought a Xbox one controller and i'd like to test my game with it. I use the Controllers extension from libGDX and it works fine, at least with my PS3 controller.

I get some weird results when i'm polling the axis of the controller with libGDX. The values are ok for Y axies but not for X ones. I mean, for X axis, values are really weird, sometimes, when the stick is fully pushed to the left, the value is not even negative, same goes for the right, sometimes value is negative. I don't know why but values seems inconsistent for X axies, Y axies work fine.

Concerning buttons, they are all detected except for the dpad.

I am using the drivers available here. I tested the controller with several games, it works fine so i think it's related to libGDX.

Do you think the Xbox One controller is not supported yet? Can it be a driver issue? Should I use another way to poll controller states? If yes, is there a good and up to date library to do so?

Thanks.


texts:
I have difficulties understanding the tangent/bitangent concept for normal mapping, or rather the calculations of them.

I draw a sphere which is generated with the code in the OpenGL redbook http://www.glprogramming.com/red/chapter05.html. I use cube mapping to texture the sphere.

Now, pretty much everything in the web links to http://www.terathon.com/code/tangent.html. But in that algorithm, they use the texture coords u and v, which I don't have like this because my texture mapping is 3D...

Any pointers to how I can compute the tangents and bitangents with this setup?

Also, aren't the tangents just vectors orthogonal to the normal of a point on the sphere? To me it seems there could be an easier way..

Edit:
As far as I understand I need those values to be able to "apply" the normal from the normal map to the point on the sphere. (I'm not sure what the correct mathematical terminologies are here). In other words, to deviate the normals of any point on the sphere based on the normal map. I calculated the normals as point_on_surface - center_of_sphere (which, in modelspace, when the center is (0,0,0), is just point_on_surface)


texts: How should I store a procedurally generated grid level of an infinite size?

texts:
I have a 2d grid level.  It infinitely grows.  If it was not of infinite size, a 2D array would be perfect, as I need  to constantly have each grid talk to its neighbors.

For example, with a 2D array, I can talk to its top neighbor by saying var topNeighbor = myGrid[x,y+1];

But if I were to use a List, the indices would be changing.

If I just store a list of all grid separately and then iterate through them for each grid, thats an n^2 algorithm running each frame.  Each room would have to iterate through every other room just to ask if they were neighbors.

What is the best way to store a 2D grid of an unknown size, assuming each grid needs to talk to its 4 neighboring grids every frame?


texts: Create Full Tile Map Zone in an Art Software, then generate corresponding tile name list?

texts:
I'm completely new to tile map creation. I'm a programmer and I'd like to make life easier for myself. It's a bit long to explain the problem I think I have, but bear with me.

The Scenario:
From what I understand, in my code I need an array which holds my tile information for a zone/area in my game. Lets say for simplicity this zone was a 10x10 grid, so 100 indexes in the array. Now, lets say each index holds a number that corresponds to a specific tile. ex) Number 1 means grass tile. Number 4 means rock tile. etc.

So far so good. From this array (and additional coding), my tile map will be generated on my game screen.

The problem:
As it stands I have to individually type each tile identifier for each index in the array. Now let's say that I have already fully designed the visual tile grid map for my zone in a particular art software. Simply put, I am staring at my fully completed zone in my art software screen and it is my visual aid for creating my array. My strategy now is to look at each grid cell, see what tile I put in there, and type its identifying number into my array. Rinse and repeat hundreds of times, looking at each individual tile until I manually complete the array. This is an extremely tedious and long process.

What I want:
So my full tile map is already in my art software. What I want is for the software to more or less generate the array for me! I press a button, and It will see what tile is in each grid square, and accordingly generate a list in a text document with each tile's identifying number that I give it. That's literally all I need. I can then copy and paste the list into my array in my code. It shaves off tons of time.

The Question:
Notice that I have used the generic term "art software". Is there any art software that can do what I described? Is there any art software (e.g. adobe illustrator, photoshop, gimp, etc.) which upon having a fully completed tile map, will be able to generate a text file list of each tile's identifying name?


texts: Trying to get the fragment shader to output a list

texts:
I am trying to figure out a way to get the Fragment Shader to output a list of gl_VertexID-s.

I want to use the GPU to get a list of vertices in the viewing frustum.

Is there any way I can get a per fragment shader invocation variable or something else that is possible to use as a pointer to a texture? If it is not possible, is there a possibility to use a sparse texture to render to, using gl_VertexID-s as a pointer?.

I will be rendering about a million or two vertices at a time (using GL_POINTS), and the list should be tightly packed to be of use. Some work may be offloaded to the CPU, but this is part of a real-time render engine so the execution times need to be under 10ms.

I am using OpenGL 4.4.


texts: Precalculate the position of a rotating Aircraft

texts:
To start honestly, this question is probably mostly handling math. But thats only the road I tried to go and failed miserably, so maybe theres a much more simple way to do.

Ok the game situation is pretty simple: A 3D space game with nearly no constraints. I don't care about physics in this game, besides from collision.

There is an aircraft (or actually more of them) that gets moved forward every frame according to it's speed and the delta time.  The movement of the aircraft occurs according to its own z-Axis. Before the translation the aircraft gets rotated, too. First around it's y-Axis and then around it's x-Axis. The result is a simply controllable aircraft.

Here some code for you:

void Update()
{
  //Rotate left/right
  float h = HORZ_SPEED * paramX * Time.deltaTime; //HORZ_SPEED is a fixed property of the aircraft, paramX an input value
  Quaternion deltaRotation = Quaternion.Euler(Vector3.up*h);,
  rigidbody.MoveRotation(rigidbody.rotation * deltaRotation);

  //Vertical rotation
  float v = VERT_SPEED * (-1.0f) * paramY * Time.deltaTime;
  deltaRotation = Quaternion.Euler(v,0,0);
  rigidbody.MoveRotation(rigidbody.rotation * deltaRotation);

  //Translation
  rigidbody.velocity = this.speed * transform.TransformDirection(Vector3.forward);
}

I simplified it a bit, but it's not really much more to that. The problem now is:
I want to predict this movement.

For different AI issues like collision avoidance and pattern recognition, I would like to calculate with constant parameters v and h and speed, where my aircraft would be at a point in time X seconds in the future.

What I tried is calculating it the hard way, starting with a start position of object axes, speed and rotation per second and constructing transformations and positions for a few frames progress, hoping it would collapse to a simple pattern. But I didn't find it.

If got the strong feeling that this kind of movement should form a simple pattern like a circle (ok, not soo simple) or an ellipse that I can calculate through a few variables. But I can't seem to make my mind up what that pattern should be and how I can calculate it's characteristics out of the data I have.

EDIT: What I managed to calculate is the transformation the local unit vectors take each frame:
e_z -> e_y * sin(a_y) + [e_z * cos(a_x) + e_x * sin(a_x)]*cos(a_y)
e_x -> e_x * cos(a_x) - e_z * sin(a_x)
e_y -> e_y * cos(a_y) - [e_z * cos(a_x) + e_x * sin(a_x)]*sin(a_y)

On the right all unit vectors are used in their state of the last frame.
a_x and a_y are the rotation parameters for the x resp. y axis:
a_x = VERT_SPEED * paramY
a_y = HORZ_SPEED * paramX


texts: Up / down powerbar computation at server side

texts:
I aplolgize if my question  is unclear, because I don't know how to formulate the problem.

I have a player that can do damage with a weapon. The weapon has a min and max damage. Holding the space bar makes a power bar grow and degrow on time, and the hit is fired when the space bar is released. This kind of mechanics is quite everywhere.

I manage to do that in Unity with a scrollbar, using delta time to add or substract some damage on time. However, my game is networked, and I don't want the user to send to the server the damage done, just that the strike is performed and make the server compute the damage done.

Here is a graph to better explain my requirement :

I don't want to do it with add and substract at every delta time at server side because of potential compute costs at many parallel games, and the desync risk. I need a formula or a simple algorithm to get the damage at hit time based on time.

Thanks for any help.


texts: How do you stop touch[].phase when using Joystick prefab?

texts:
I have a camera that rotates around the player only in x axis when you swipe on the screen. I have two buttons and a joystick prefab on the UI. I don't want the camera to move when touch.phase is initiated on any of the UI elements.

This is what I have done so far:

Touch[] touch = Input.touches;
if (touch[0].phase == TouchPhase.Moved
    && !Joystick.UseX && !Joystick.UseY
    && !CrossPlatformInputManager.GetButton("Jump")
    && !CrossPlatformInputManager.GetButton("Boost"))
{
    delta = touch[0].deltaPosition;
}
else delta.x = 0;

This code works fine on jump and boost buttons.

Joystick.UseX and UseY are two booleans I added to Joystick.cs so that when no input is taken from them, they will become false. The code would work, but the problem is that when you touch the joystick, no input will be taken, until you drag it around. When you drag it, as every condition is met in my if statement, the camera starts moving.

Can you help build on my code to fix it or give me a better solution?


texts:
I have a tiled map which is 3 times higher than camera. When I press on a tile, I want an actor on that tile to show up. This works if camera is not moved. If I move camera a little bit up, so the tile coordinates are greater then camera coordinates, actor is placed offscreen. Is there a way to get tile coordinates so they wil fit the camera coordinates

Im using libgdx if it helps.


texts: Instantiate moving objects next to each other

texts: I am trying to find the correct time to spawn my object. If my object moves one unit per second, how long should I wait before spawning my other object so it be ass to ass to the other object? I tried waiting for one second in my coroutine before instantiating the object but there is a small gap.


texts: How can I make the player spawn at a specific location on the map?

texts:
I'm trying to make a game in Unreal Engine 4.8,

I've got a Player Start actor in the main level and a box collision that loads a new level, but when you return to the main level you obviously spawn at the Player Start, how can I make the player spawn at a specific location on the map, because I've tried with a lot of things and they didn't work.

For example I start at the tent and you walk to the house, you enter the house level, and after a few minutes you leave, what happens is that you spawn at the Player Star and I want to spawn in front of the house.


texts:
I would like to create a traffic system in my tile-based isometric game and I would like to ask for some good approaches because I don't have a clue how to begin.

Right now I have a tilemap and keep its data in an 2d array. I have...
1. tile objects (with properties like index, tile type etc.)
2. building objects (with properties like origin, size etc.).

I´ve already implemented a A* algorithm which allows me to find the best/shortest path from one tile to another but now I have to realize the movement from start to end tile with features like stackable cars.

I though about setting up a property for my tile object which tells me if a tile contains a car but right now two cars fits on one tile in my game on each lane so this approach might be not the best solution.

Edit: i´ve added an image with lanes drawn on my tilemap. Having lane objects might be a good idea but I need to connect them to the tile objects somehow.

Have anyone implemented a traffic system in a tile-based game or have any ideas how to realize that and would share his/her knowledge with me? Would be great!

Thanks a lot!


texts:
I'm saving music in libgdx preference, the following code works perfectly but if you enter the settings again you'd see the initial button up regardless if the sound is muted or not.

TextureAtlas buttonsAtlas = new TextureAtlas("ui/dialogButtons.pack");
textButtonStyle.up = skin.getDrawable("music.down");
textButtonStyle.checked = skin.getDrawable("muteMusic.up");
button.addListener(new InputListener() {
 public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
  return true;
 }
 public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
  setMusicplaying(!musicplaying);
  if (getMusicplaying() == false)
   playMusic.stop();
  else playMusic.play();
 }
});

I tried to do this, it works perfecly but doesn't switch the button, when the user is clicking on it, it only switches when the user closes the dialog

if (getMusicplaying() == true) {
textButtonStyle.up = skin.getDrawable("music.down");
textButtonStyle.down = skin.getDrawable("muteMusic.up");}
if (getMusicplaying() == false) {
  textButtonStyle.up = skin.getDrawable("muteMusic.up");
  textButtonStyle.down = skin.getDrawable("music.down");}


texts:
I am working on a 2D game engine in C# using OpenGL. I am trying to find a collection to satisfy my needs for sprite ordering, and I can't seem to find the combination of performance and functionality.

The following is the criteria I am after:

The ability to be iterated over in order according to "Z" value, which may change for any sprite at any time
Possible for many sprites to be added/removed within a single frame, so sorting each time a value was added/removed will have large performance impact without the correct implementation
Insertion/removal speed is much lower priority than access speed during enumeration
Have no need for indexing
Only unique values, but with the correct collection, I can manage that manually if the base collection does not implement it, as I do in the example

Currently, this is the best I could come up with. (I removed all the interface implementations for clarity, leaving only the important stuff)

    public class SpriteBatch : ICollection<IRenderable>
{
    private readonly Dictionary<uint, IRenderable> _dict;
    private readonly List<uint> _keys;
    private bool _needSort;

    public SpriteBatch()
    {
        _dict = new Dictionary<uint, IRenderable>();
        _keys = new List<uint>();
        _needSort = false;
    }

    public void Add(IRenderable renderable)
    {
        if (renderable == null)
            throw new ArgumentNullException(nameof(renderable), "Item cannot be undefined.");
        if (_dict.ContainsKey(renderable.Id))
            return;
        _needSort = true;
        renderable.Disposed += (sender, args) => Remove(renderable);
        renderable.ZChanged += (sender, args) => _needSort = true;
        _keys.Add(renderable.Id);
        _dict.Add(renderable.Id, renderable);
    }

    public bool Remove(IRenderable renderable)
    {
        if (renderable == null)
            return false;
        _dict.Remove(renderable.Id);
        return _keys.Remove(renderable.Id);
    }

    public IEnumerator<IRenderable> GetEnumerator()
    {
        if (_needSort)
            _keys.Sort((a, b) => _dict[a].Z.CompareTo(_dict[b].Z));
        foreach (var key in _keys)
            yield return _dict[key];
    }
}

Was curious if anyone else had a better approach, or what the "standard" tried-and-true way of doing this is?


texts: Given the worldspace coordinates of a collection of arbitrarily positioned objects, how do I translate them while preserving their relative placement? For instance, I have a table and a few bowls that are placed on top of it at (x1, y1, z1) and wish to moved them to (x2, y2, z2).


texts: representing transforms without a world/global reference frame

texts:
Background:

I'm trying to make a segmented/portal-based game engine
that supports impossible (non-euclidean?) geometry.

By segmented/portal-based I mean the world is divided into segments which are connected by portals.
This technique was used by the engines for classic shooters like Doom and Duke Nukem 3d.

The portals do not look or function like the portals in the game Portal, which is unfortunately what most of the results that queries containing "portal" bring up.

Each area is in its own coordinate system
with each portal defining the transformation between
the portal entrance in the origin segment and
the portal exit in the destination segment.

It is possible for there to be multiple portals connecting the segments and for those portals to have different transformations.
If I understand correctly, this makes the world non-euclidean and precludes storing a transformation for each connected segment on a segment.

Objects have transforms for each segment they are present in.
So instead of the usual transform setup of objects having a local transform, a parent transform, and a world transform
there is no world transform and it is possible to have more than one "parent" transform.

Advanced math is not my strong point.
I understand the basics of the transformations
but there are some details I don't fully grok
and almost certainly some important or useful
properties that I am not aware of.

Questions:

Where do I "store" or "collect" the results of applying transformations to an object?

Do I apply them to the object's local tranform or do I apply it to the object's transforms relative to "parent" segments?

It seems like a bad idea to accrue transformations on the local transform, but perhaps I don't understand the purpose of the local transform.

Research before asking question:

tutorial on simple portals in unreal that helped with outlining the transformation logic, but is focused on unreal and does not answer my questions.

flipcode portal rendering tutorial which gets brought out anytime there is a question about portal-based rendering. I have read through it a couple times, although the small font is hard for me to read so it is very possible I missed some details.

related question

related question

discussion on gamedev subreddit


texts:
The game would be a race from A to B through several checkpoints. I think there are two approaches for the concept of time.

The game starts with some time and player has to make it to the finish before it runs out. Extra time is granted at the checkpoints. Time left at the finish is counted as a score.
The time at the start is 00:00 and the stopwatch is halted at the finish. Player still has to go through checkpoints.

Opinions about these? I think the option 1 is more common but I find it frustrating for beginners.


texts: Multiplayer netcode where all units, including server, are untrusted - possible, feasible, etc.?

texts:
Most professional video games use either a peer-to-peer architecture or a client-server architecture. In the former, clients often trust each other, and instead employ anti-cheat techniques to ensure that all clients are using the same version of the game. In a client-server architecture, the company-owned server manages the game, and each client only needs to trust the server without trusting any other client.

My question is: how might I write a game network architecture such that the server is not necessarily trusted either (e.g. it is another client, or is buggy, or has been compromised), and do so in a way that does not take too much processing power away from the game?

I know that the blockchain algorithm (as infamously used by Bitcoin and other cryptocurrencies) does provide this as long as at least half of the computing power is owned by trusted machines. While this may work for long-term actions (such as match verdicts), it doesn't work as well for the frame-by-frame actions of action games and can also be too slow for turn-based games, to say nothing of the computing power it requires of the clients or of any dedicated servers.


texts: How to change the sprite of an object from another's script?

texts:
I have an object A and an object B, I want that when object B is in a certain position, the sprite of object A changes to that corresponding to that position, how do I change the sprite of object A from the script of object b?

The image may give them an idea of what I want to do, object B is the glove, And the object A is the viewer.

Tansk form any help.


texts: Unity CaptureScreenshot captures and editor as well

texts:
I'm trying to create some screenshots but ScreenCapture.CaptureScreenshot actually captures the entire editor and not just the Game view.

I'm using this few lines of code here:

public class ScreenShotTaker : MonoBehaviour
{
    public KeyCode takeScreenshotKey = KeyCode.S;
    public int screenshotCount = 0;
    private void Update()
    {
        if (Input.GetKeyDown(takeScreenshotKey))
        {
            ScreenCapture.CaptureScreenshot("Screenshots/"
                 + "_" + screenshotCount + "_"+ Screen.width + "X" + Screen.height + "" + ".png");
            Debug.Log("Screenshot taken.");
        }
    }
}

What could be the issue?


texts: Why does the text of my label objects overlap?

texts:
I am having a problem with labels in my GUI:

I have looked for solutions online but not found something solid enough to fix this problem. Has anyone ever come across this? Here is my GUI function. When the variable changes it overlaps with the previous one:

 void OnGUI() {
    if(selected) //set your selected variable in the OnMouseDown method
        GUI.Label(new Rect(40, 50, 400, 22), GetComponent<MeshFilter>().mesh.name);

}


texts:
I'm currently thinking hard about how to implement lighting in my game. The geometry is quite dynamic (fixed 3D grid with custom geometry in each cell) and needs some light to get more depth and in general look nicer.

A scene in my game always contains sunlight and local light sources like lamps (point lights). One can move underground, so sunlight must be able to illuminate as far as it can get.

Here's a render of a typical situation: The lamp is positioned behind the wall to the top, and in the hollow cube there's a hole in the back, so that light can shine through.

(I don't want soft shadows, this is just for illustration)

While spending the whole day searching through Google, I stumbled on some keywords like deferred rendering, forward rendering, ambient occlusion, screen space ambient occlusion etc. Some articles/tutorials even refer to "normal shading", but to be honest I don't really have an idea to even do simple shading.

OpenGL of course has a fixed lighting pipeline with 8 possible light sources. However they just illuminate all vertices without checking for occluding geometry.

I'd be very thankful if someone could give me some pointers into the right direction. I don't need complete solutions or similar, just good sources with information understandable for someone with nearly no lighting experience (preferably with OpenGL).


texts:
I have a submarine model that I would like to shoot torpedoes.

I want these torpedoes' initial velocity to vary with the forward velocity of its shooting submarine (so they go faster if launched off a moving sub, slower if show from a stationary sub).

I have a few requirements I'm trying to achieve:

Torpedos despawn when they swim too far away. No need to keep them in memory if they're too far too see.
When a torpedo is updated, and collision detection is done, there should be a way to determine who shot the torpedo, so it can be determined who to award the kill.
Torpedos should outlive the lifecycle of its parent sub, in the case the sub is destroyed between the torpedo was shot, and the time the torpedo hits or veers too far away. (Who doesn't love double kill mechanics :D?)
I'm working in C++, so manual memory management is a concern.

I'm debating between two approaches:

Have subs be the owners of their torpedoes. This makes requirements 1 and 2 easy, but complicated 3.
Have the scene be the owners of torpedoes. This makes 3 easy, but complicates 1 and 2.

This seems like it would be a common problem. What's the preferred way to do this?


texts: What are some programming design patterns that are useful in game development?

texts:
I have a few books on Design Patterns, and have read some articles, but cannot intuitively figure out which programming design patterns would be useful in game development.

For example, I have a book called ActionScript 3 with Design Patterns that details several design patterns such as Model View Controller, Singleton, Factory, Command, etc.

As someone new to this, I cannot figure out which of these would be useful, or in fact if any of these are the design patterns I should be learning and trying to use.  Perhaps there are other, more game-programming-specific design patterns that I am not even aware of?

If you have experience using a certain design pattern in game development, I'd love to hear it.  Reasoning as to why it was used, code samples, or online resources would all be very helpful as well if you have them.  I am at the moment most interested in ActionScript 3 and C++ implementations, but could definitely benefit from experience and examples from any language.

Thanks!


texts: Mandelbrot generation using custom HLSL shader in XNA

texts:
So I made a Mandelbrot generator in C# and I'm learning about HLSL and custom shaders in XNA (For a college course). I was hoping to do the mandelbrot calculations on the graphics card to make them faster. This is the code that I have so far (only part of my .fx file).

// sx, sy is the upper left corner of the mandelbrot coordinate area
// sw,sh is the width and height of the mandelbrot coordinate area.
float sx = -2.5, sy = -1, sw = 3.5, sh = 2;
float width, height; // Size of the quad I'm drawing this to

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    // TODO: add your pixel shader code here.
    float count = 500;
    // Convert from the drawing space to madelbrot space
    float tx = (input.UV.x / width) * sw + sx;
    float ty = (input.UV.y / height) * sh + sy;
    float tsx = tx, tsy = ty;

    // Find the divergence count
    for(float i = 0; i > 500; i++)
    {
        // Get the next location
        tx = tx * tx - ty * ty + tsx;
        ty = 2 * tx * ty + tsy;
        // This is the part I'm having trouble with
        count = (tx * tx + ty * ty <= 4 ? count : min(count, i));
    }
    // Calculate and return a color based on the count obtained
    float factor = count/500;
    return float4(1-factor, 1-factor, 1-factor, 1);
}

I think the issue has to do with having a ternary operation inside of a loop.
The issue is that "factor" always results in having a value of 1, which means count obtains a value of 500. So my looping does nothing. I believe that my code is theoretically correct.

Maybe HLSL doesn't deal with the ternary operator very well? Does anyone have information about how they work or any limitations when using them?

Any comments are welcome.


texts: How do I handle collision response between many different types of game objects?

texts:
I am looking for a way to avoid the dreaded switch or if/else scenarios between numerous game object types when a collision takes place in a game. For example:

You have a list of game objects which inherit from a common class such as GameObject. You check the list for any collisions and call a method for each colliding object to respond to the collision, but this situation develops:

public void handleCollision(GameObject other) {
    switch(other.getType()) {
    case Alien:
    //Perform some logic
    break;

    case Ogre:
    //Perform some logic
    break;

    case Wall:
    //Perform some logic
    break;

    case Door:
    //Perform some logic
    break;

    //and so on

    }
}

This would become unwieldy with hundreds of different game object types. What I was attempting to do was this:

Map<CollisionKey, Method> collisionCallbackMap = new HashMap<CollisionKey, Method>();

collisionCallbackMap.put(new CollisionKey(gameObjectType, gameObjectType), //add a reference to a method here);

CollisionKey is a class I created for handling game object pairs such as Player-Alien, Player-Ogre, Player-Wall, etc. The idea was to look up a pair of game objects in the map, cast the game object in the collision list to the appropriate class types, and pass them into the method stored in the value slot of the map for that game object pairing. So it would look something like this:

for(GameObject a : collisionListA) {
    for(GameObject b : collisionListB) {
        if(a.collidesWith(b)) {
            collisionCallbackMap.get(new CollisionKey(a.getType(), b.getType(), //cast GameObjects to appropriate types such as Player and Alien and pass it into a method here);
        }
    }
}

The method called from the map would look something like this if the game objects colliding were a Player and an Alien:

public void playerToAlienCollision(Player p, Alien a) {
    //Perform some logic here such as...

    p.reduceHealth();
    a.reduceHealth();

    a.knockBack();
}

This wouldn't be a problem if I were working in, say, C++ with function pointers, but I'm working in Java with Android. Android's Java only supports Java 6, and if I'm not mistaken I believe it now has support for Java 7, but it does not currently support the recently released Java 8. With the addition of lambdas and method references in Java 8 I feel this would be a viable approach, but I don't have access to that so I need another solution. The workaround or Java's version of function pointers before Java 8 seems to involve interfaces with a single method and I believe I would need one for each collision method. It just looks convoluted and not very polished. The accepted answer of this question displays an example of it:

https://stackoverflow.com/questions/4480334/how-to-call-a-method-stored-in-a-hashmap-java

I'm not looking for how collision detection is done, I'm ok with that, its what comes right after I'm seeking a solution for. What is an efficient way to handle collision response and callbacks without the dreaded and bloated switch or if/else scenarios? I think of a large game like Runescape with tons of objects and its written in Java and wonder how they set up their collision response/callbacks.


texts: What can cause shadow slicing while moving camera?

texts:
Can't explain better than with video: https://youtu.be/4nIMIL6w-0M

The effect I'm trying to achive is a simple fog of war.

See, I have a point light casting shadows on a plane. The plane has a shader which takes light attenuation and either draws a black pixel if there is no light, or discards a pixel to draw background if the light touches that pixel.

After hours spent on this, I came up with a thought that I cannot do anything more.

A problem as I see it:

  Light successefully casts a shadow of shadow casters on a plane, however, with camera at a distance from the shadow, the shadow it self gets splitted and sliced, like it would've been, if some of the shadow casters' faces are suddenly removed from their meshes.

What I have tried:

Changing Z coordinate of a light.
Changing Z height of obstacles (shadow casters).
Changing vertices on the obstacles so that every face would have its own vertices so no faces could share a vertex.
Changing shadow quality in the settings.
Changing camera rendering mode, all four of them.
Changing point light to a spot light with wide cone radius.
Using nice and simple standart unity's shader for a shadow receiver (a plane) - Standart Diffuse.
Switching between hard and soft shadow types.
Changing light's shadow's resolution, shadow strength and biases
Trying out the compiled EXE on another machine.
Changing light's baking type, rage and intensity.
You name it.

None of those had any improvementes on an issue.

I would like to hear authoritive replies (best option would be from the developers) as well as any information you guys think I can try out (so I can do that).


texts: How much memory does a Game Boy game have for save data?

texts:
Is there a standard number of bytes a Game Boy game would have to store (battery backed up) save data?

If not a standard, is there an common size, or a few examples of save data sizes?

If Game Boy is not known, I'd be happy with the same information for NES.

Thanks!


texts: How can I implement a Boardgame.io project using Webpack?

texts:
I am following the boardgame.io tutorial, but I do not want to use either of the two implementation options covered in the tutorial (React and Parcel).
The tutorial requires a framework or bundling method because the client web application has dependencies on node.js modules which cannot be directly imported into browser scripts.


texts: Benefits of implementing systems like classes instead of just functions

texts:
In an Entity System I am making, there is a central class called World, which stores all component instances. It's a dictionary-of-arrays, and entity ids are indexes for the arrays.

To access a component of an entity with id = 3 you would do this: world.storage["ComponentType"][3].

So, each loop of the game, these arrays would be fed to their respected systems (  movement(world.storage["Position"], world.storage["Velocity"]) ).

Now, I don't see why systems couldn't be implemented just as functions, as I showed. What optimizations can be made by using classes with data and methods (caching)?

Also, these systems would need to iterate over all the entities that exist, doesn't this make entity frameworks much slower than regular inheritance based engines? Why do some people "register" systems to the World class?


texts: Dealing With Multiple requestAnimationFrame Calls

texts:
I am having issues with requestAnimationFrame calls stacking on top of each other. I am developing a platformer game, which has three separate functions that need animating (main menu, cutscene, in game). Currently, I have flags to determine when to run requestAnimationFrame. For example, I only call requestAnimationFrame in the runCutscene() method if !onMainMenu and !inGame. These flags are reset in the init() method, which decides which of the three methods to run.

Specifically, my problem occurs when I return to the main menu from the cutscene (at seemingly random times, I can not continuously replicate the error). The main menu appears to run at double its normal speed (which I assume is because of stacked requestAnimationFrame calls).

What is the most efficient way to call requestAnimationFrame? If I put the requestAnimationFrame call in the init() method, the game breaks. Thank you in advance.


texts:
Okay, so this has been bugging me for quite some time now. I'm making an old school platformer type of game in 2.5D, I want objects to pass through each other, but I still want a collision to be detected.

If the player gets hit by an enemy, I just want to detect a collision for receiving damage to the player, I don't want the player to move on impact, and I just want the enemy to continue moving where he was heading.

I'm using rigidbodies and box colliders on my objects. First I thought using triggers combined with ignoring layers was the solution, but apparently trigger events aren't called when ignoring layers.

I still want to be able to use AddForce and stuff for moving objects.

Is there someway I can still utilize Unity's OnCollision.../OnTrigger.../Or other... for just detecting a collision and having no impact movement added when a collision occurs?

Have a nice day!


texts: How would I go about making a movement system like Mario Party?

texts:
Main question

How would I go about getting a movement system similar to the one they have in Mario Party only minus the dice roll?

Things I have researched

I have been studying the uses  for ****arrays ,lists, for loops,onmousebuttondown**** but I want to make a movement system where the player has a limited amount of spaces, clicks a tile, and then moves to it. I kind of have a vague idea of how to go about this and I kind of know what I need......and I kind of don't....basically my brain isnt working and kind of hit a road block... Thus far all I have is the board it self...
I understand how to make the highlights work when the cursor moves over the tile ..... but the major thing I can't figure out is how I should actually get the player to move after I click on the tile with the mouse button and have the player only move in a limited range.

Summary of things I'm looking for

Movement system kind of like mario party but minus the dice roll
and instead of game board it would be on a grid

Players would only be able to move x amount of spaces both horizontally and vertically

Strictly for unity and please put any code in c#

Not looking for you to do my work but an example would be nice or at the very least point me in the right direction

Also, the board would be in a top down view but in 3d

I pretty much have an idea know what i need i just dont know the how
to

Im not looking for a way to highlight the board just the turn based movement system itself.  I thought I was clear with my question but maybe not as clear as I thought I was*

Picture of the grid on unity and an example of the turnbased movement system im looking for

using UnityEngine;
using System.Collections;

public class GridScript : MonoBehaviour {

    public Transform cellPrefab;
    public Vector3 Size;
    // Use this for initialization
    void Start () {
        CreatGrid ();

    }

    void CreatGrid (){

    for (int x = 0; x< Size.x; x++) {
        for (int z = 0; z< Size.x; z++) {
                Transform newCell;
            newCell = (Transform)Instantiate (cellPrefab, new Vector3 (x, 0, z), Quaternion.identity);
                newCell.name = string.Format ("({1},0,{1})",x,z);
                newCell.parent =transform;
                }
            }
        }
}


texts: Unity Menu navigation using keyboard/controller input?

texts:
I am trying to create a character stats menu that uses keyboard/controller input to navigate between options instead of the mouse. I have not found any tutorials for this kind of UI navigation.

In this way, pressing "Up"/"Down" will highlight the closest button above/below the current selection, and pressing "Left"/"Right" will highlight the closest button to the left/right of the current selection.

This is how console menus, especially for popular JRPG's, worked.  Two example images of what I am talking about:

In this top-level menu, only the 8 options in the upper right are selectable, although not all options are necessarily present when the game begins. The finger-pointer icon is used to highlight a button:

This is the Equip menu. Equipable items are pushed into this menu as they are collected and can be scrolled through with the cursor. If the user presses "left", the cursor will jump to whichever character's valid equipment slot is closest:

Could anyone explain (briefly or otherwise) how to make a menu like this?

WIP: The hand cursor does not move yet. It is supposed to snap to highlighted buttons.


texts:
I'm currently working on a font-rendering system for my OpenGL based engine.
I sure got something to work, but the only thing I still have problems with, is the horizontal advance!

This is what it spits out, obviously not correct. If I understood correct from the documentation and some other threads, this is the procedure to draw a string:

set current drawing position to (0, 0)
draw first character
move drawing position in the x for advance.x
draw second character
move drawing position in the x for next face->glyph->advance.x
... repeat

Is that correct? If not, what am I doing wrong?
I think its worth to say that I render every character as a texture!