texts:
I am aiming to achieve a believable engine sound for a car. The vehicles are simplified versions of their real-world counterparts, with simpler steering behaviors and acceleration, etc.

This seems like a fairly complicated topic to me, which I must not take lightly. So, how would I find/capture sounds of a car's engine, properly segmented in a way they can be used inside a game?

Also, what kind of format do I need the sound files in? How do I separate the sounds in multiple files so they can be used by such an algorithm?

I'm not sure this is even the way to go about it, but my wild guess would be to create an algorithm that would take as input the car's shift, current velocity and other engine parameters and output the correct sound at the correct time. How would you do such a thing?


texts:
While compiling the following code. I get a error

float tess = saturate((gMinTessDistance - d) / (gMinTessDistance - gMaxTessDistance));

// Rescale [0,1] --> [gMinTessFactor, gMaxTessFactor].
vout.TessFactor = tess;

if i do this it works.

float tess = saturate((gMinTessDistance - d) / (gMinTessDistance - gMaxTessDistance));

// Rescale [0,1] --> [gMinTessFactor, gMaxTessFactor].
vout.TessFactor = 0.4;

..

struct VertexOut
{
    float3 PosL       : POSITION;
    float3 NormalW    : NORMAL;
    float3 TangentW   : TANGENT;
    float2 Tex        : TEXCOORD;
    float  TessFactor : TESS;
};

Here is code for vertex shader part

VertexOut VS(VertexIn vin)
{
    VertexOut vout;

    // Transform to world space space.
    vout.PosL = mul(float4(vin.PosL, 1.0f), gWorld).xyz;
    vout.NormalW = mul(vin.NormalL, (float3x3)gWorld);
    vout.TangentW = mul(vin.TangentL, (float3x3)gWorld);

    // Output vertex attributes for interpolation across triangle.
    vout.Tex = mul(float4(vin.Tex, 0.0f, 1.0f), gTexTransform).xy;

    float d = distance(vout.PosL, gEyePosW);

    // Normalized tessellation factor.
    // The tessellation is
    //   0 if d >= gMinTessDistance and
    //   1 if d <= gMaxTessDistance.
    float tess = saturate((gMinTessDistance - d) / (gMinTessDistance - gMaxTessDistance));

    // Rescale [0,1] --> [gMinTessFactor, gMaxTessFactor].
    vout.TessFactor = tess;

    return vout;
}

Im in Directx 12 Shader model 5.0


texts: Design of a turn-based game where actions have side-effects

texts:
I am writing a computer version of the game Dominion. It is a turn-based card game where action cards, treasure cards, and victory point cards are accumulated into a player's personal deck. I have the class structure pretty well developed, and I am starting to design the game logic. I'm using python, and I may add a simple GUI with pygame later.

The turn sequence of the players is governed by a very simple state machine. Turns pass clockwise, and a player can't exit the game before it is over. The play of a single turn is also a state machine; in general, players pass through an "action phase", a "buy phase", and a "clean-up phase" (in that order). Based on the answer to the question How to implement turn-based game engine?, the state machine is a standard technique for this situation.

My problem is that during a player's action phase, she can use an action card that has side effects, either on herself, or on one or more of the other players. For example, one action card allows a player to take a second turn immediately following the conclusion of the current turn. Another action card causes all other players to discard two cards from their hands. Yet another action card does nothing for the current turn, but allows a player to draw extra cards on her next turn. To make things even more complicated, there are frequently new expansions to the game that add new cards. It seems to me that hard-coding the results of every action card into the game's state machine would be both ugly and unadaptable. The answer to Turn-based Strategy Loop does not go into a level of detail that addresses designs to solve this problem.

What kind of programming model should I use to encompass the fact that the general pattern for taking turns can be modified by actions that take place within the turn? Should the game object keep track of the effects of every action card? Or, if the cards should implement their own effects (e.g. by implementing an interface), what setup is required to give them enough power? I have thought up a few solutions to this problem, but I am wondering if there is a standard way to solve it. Specifically, I'd like to know what object/class/whatever is responsible for keeping track of the actions that every player must do as a consequence of an action card being played, and also how that relates to temporary changes in the normal sequence of the turn state machine.


texts:
I have an object that has a dynamic body. Currently, I'm setting it's position to follow the sprite when the parallax layer move. After a certain event, the object suppose to fall to the ground. That's when I set it to Awake. But as the object falls and the parallax is moving, how do I control these factor?

When the object falls by right the sprite should be updated to follow the dynamic body position. Let's say I have a character, to avoid the falling object, I move the parallax layer. The sprite is attached to the parallax layer. I'm asking what should I do in this case. Any advice?


texts: Difference between Unity's Renderer.sharedMaterial and Renderer.sharedMaterials

texts: What are the difference between Renderer.sharedMaterial and Renderer.sharedMaterials in Unity?


texts: Unity3d reading profiler binary information

texts:
So I'm using Unity's profiler to help debug some of my code in the standalone. I've got it running smoothly, and writing all it's data to a .data file which I can read.

However, the binary file Unity creates for profiler information gets quite huge very quickly. I'm hoping to get past this by writing the profiler data log to a zip archive. I have dotnetzip installed, and can add files to a zip archive.

What I'm trying to figure out is how I could possibly either write the profiler data log directly to the zip archive, or write the profiler binary data to a variable of some sort which I could store in a stream and write to the zip archive on quit. This way I won't ever have to have the large file on the user's drive.

Another option would be to continuously write the binary data to the log on the drive, then get the binary info from that log, write it to a stream, put it in to a zip archive, then delete the log. However I'd have to do this every few seconds, and that may get slightly process intensive.


texts: Is there a simple C++/.NET game with scripting?

texts: I would like to play around with games that use scripting to see how much easier it makes development. What --simple-- C++ or .NET game may i download and play with using a scripting language. I dont really care which scripting language it is.


texts:
I'm currently porting an old XNA game over to MonoGame and everything (including custom shaders) build fine.

However when i try to load the xnb file using content.Load<Effect>("BaseDraw");
I receive the following error:

An unhandled exception of type 'SharpDX.SharpDXException' occurred in SharpDX.dll

Additional information: HRESULT: [0x80070057], Module: [General],
    ApiCode: [E_INVALIDARG/Invalid Arguments], Message: The parameter is incorrect.

I even tried building the shaders with 2MGFX.exe and loading it manually but that throws the same error.

I have no idea what to so any help would be appreciated!


texts: How to get a good Force Feedback .dll Feedback for Steering Wheels? || How to access Force Feedback without a .dll?

texts:
I want to implement a steering wheel with Force Feedback to my game and I encountered this problem:
I couldnt do it with performance.
I have found a .dll for that online, but it had issues like:

It was not performant
It made my steering wheel react too delayed

Otherwise I was not able to access the steering wheel.
Is it even possible to make a performant steering wheel and force feedback game  with good performance?
How else can I access force feedback ?


texts: Should entities store other other entities that they spawned?

texts:
How should a game entity add another game entity to the game world?

For example, an entity shooting a missile (which is another entity), means the new Missile will need to be added to the entities list in the GameWorld class (so that the next game-loop iteration it will be drawn, moved, etc).

I can think of two approaches:

Approach 1

The entity adds a new Missile to the GameWorld:

class SpaceShip extends Entity{
    // .. stuff omitted
    void shoot(){
        GameWorld.getInstance().add(new Missile(x,y));
    }
}

Approach 2

Have the GameWorld query it's entities every gameloop iteration for their 'stored entities'. For example (pseudocode):

class SpaceShip extends Entity{
    // .. stuff omitted
    List<Missile> missiles;
    void shoot(){
        missiles.add(new Missile(x,y));
    }
}

class MineCreatorThing extends Entity{
    // .. stuff omitted
    List<Mine> mines;
    void putMine(){
        mines.add(new Mine(x,y));
    }
}

class GameWorld{
    // .. stuff omitted
    void gameloop(){
        while(true){
            // .. more stuff omitted
            foreach entity in entities{
                if(entity instanceof MineCreatorThing)
                    foreach mine in entity.getMines() entities.add(mine);
                if(entity instanceof SpaceShip)
                    foreach missile in entity.getMissiles() entities.add(missile);
            }
        }
    }
}

Which approach should I pick?


texts: Creating live wallpaper on Android with libgdx

texts:
I try to create live wallpaper with libgdx framework. Here's my source code: repository

When I run this, black screen with name of the app appears (probably empty android layout). Main game is not called. I think that it is because starting a service not an activity. However how could I start an activity when AndroidTestWallpaper isn't subclass of Activity class? I used this tutorial but I don't think it's complete, in this form my IDE (Intellij IDEA) doesn't let me to run the app because no main Activity class is found.

So what is the proper way to implement and run live wallpaper in libgdx? How should I edit my code?

EDIT: So I made it work now - I run the app and I can see some graphics but how to make live wallpaper from it?

EDIT 2:
I've finally made it work, you can find new version in repository from first post but I still have one problem - when I start the Wallpaper, following exception occurs:

01-05 20:31:53.102: ERROR/AndroidRuntime(3681): FATAL EXCEPTION: main
        java.lang.RuntimeException: Unable to resume activity {com.reinto.wallpaper.test/com.reinto.wallpaper.test.AndroidStarter}: java.lang.NullPointerException
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2823)
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2862)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
        at android.app.ActivityThread.access$600(ActivityThread.java:139)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:156)
        at android.app.ActivityThread.main(ActivityThread.java:4977)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
        at dalvik.system.NativeStart.main(Native Method)
        Caused by: java.lang.NullPointerException
        at com.badlogic.gdx.backends.android.AndroidApplication.onResume(AndroidApplication.java:247)
        at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1236)
        at android.app.Activity.performResume(Activity.java:4620)
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2807)
        ... 12 more

But I can continue with selecting the wallpaper and I can make my wallpaper active. However this error is bothering.

EDIT 3: It's finally working. Solution of previous exception is that AndroidStart should extend Activity class not AndroidApplication.


texts: UI Toolkit, Get the topmost Element under the cursor

texts:
Basically, I'm making a small node system, Just for fun.
And I need to know if I can get the topmost Element under the cursor. I need it to connect nodes.
Thanks!


texts: How can I access a method via a string in Unity?

texts:
I myself am new to unity and I would like to know how it is possible to access a method via a string, something like this:
public string PlayerPrefsName;

public GameObject Button;

public string GadgetForSkin;

private void Start()
{
    GadgetChanged = PlayerPrefs.GetInt(PlayerPrefsName);
    if (GadgetChanged == 0)
    {
        Button.SetActive(false);
    }
    GadgetForSkin = "GadgetForSkin" + GadgetChanged;
}

public void GadgetChecker()
{
    GadgetForSkin();
}

public void GadgetForSkin1()
{

}

If it's not possible, how can I achieve something similar?


texts: Questions before I revamp my rendering engine to use shaders (GLSL)

texts:
I've written a fairly robust rendering engine using OpenGL ES 1.1 (fixed-function.) I've been looking into revamping the engine to use OpenGL ES 2.0, which necessitates that I use shaders. I've been absorbing information all day long and still have some questions.

Firstly, lighting. The fixed-function pipeline is guaranteed to have at least 8 lights available. My current engine finds lights that are "close" to the primitives being drawn and enables them; I don't know how many lights are going to be enabled until I draw a given model. Nothing is dynamically allocated in GLSL, so I have to define in a shader some number of lights to be used, right? So if I want to stick with 8, should I write my general purpose shader to have 8 lights and then use uniforms to tell it how many / which lights to use?

Which brings me to another question: should I be concerned with the amount of data I'm allocating in a shader? Recent video cards have hundreds of "stream processors." If I've got a fragment shader being used on some number of fragments in a given triangle, I assume they must each have their own stack to work on. Are read-only variables copied here, or read when needed?

My initial goal is to rework my code so that it is virtually identical to the current implementation. What I have in mind is to create my own matrix stack so that I can implement something along the lines of push/popMatrix and apply all my translations, rotations, and scales to this matrix, then provide the matrix to the vertex shader so that it can make very quick vertex translations. Is this approach sound?

Edit: My original intention was to ask if there was a tutorial that would explain the bare minimum necessary to jump from fixed-function to using shaders.

Thanks!


texts:
I have a snake game set up in Java and I wanted to be able to toggle between the ability to go through the sides and pop out the opposite side and the classic version where you die when you hit the border. The problem is that my snake keeps going one spot after the border; how do I fix this?

This is one of the parts of my code, that acts when the right arrow key is pressed:

if(right) {
    for(int i = lengthofsnake - 1; i >= 0; i--) {
        snakeylength[i+1] = snakeylength[i];
    }

    for(int i = lengthofsnake; i >= 0; i--) {
        if(i == 0) {
            snakexlength[i] = snakexlength[i] + 25;
        }
        else {
            snakexlength[i] = snakexlength[i-1];
        }

        if(!borderGameplay) {
            if(snakexlength[i] > 850) {
                snakexlength[i] = 25;
            }
        }
        else {
            if(snakexlength[i] > 850) {
                borderDead = true;
            }
        }
    }

    repaint();
}

borderGameplay is the variable that you can toggle to have borders on and off, and borderDead is used in this if statement:

if(borderDead) {
    if(score > highScore) {
        highScore = score;
    }
    playing = false;
    dead();
    deadGraphic(g);
}

This is my deadGraphic(g):
    public void deadGraphic(Graphics g) {
        g.setColor(Color.WHITE);
        g.setFont(new Font("arial", Font.BOLD, 50));
        g.drawString("Game Over", 300, 300);
        g.setFont(new Font("arial", Font.BOLD, 20));
        g.drawString("Press \"Space\" To Restart And \"Enter\" To Toggle Borders", 160, 340);

    if(borderGameplay) {
        g.drawString("Borders ON", 370, 380);
    }
    else {
        g.drawString("Borders OFF", 365, 380);
    }
 }

This is my dead():

public void dead() {
    right = false;
    left = false;
    up = false;
    down = false;
    dead = true;
    score = 0;
    moves = 0;
}

And finally, my JFrame:

JFrame obj = new JFrame("Snake");
gameplay Gameplay = new gameplay();
obj.setBounds(10, 10, 905, 700);
obj.setBackground(Color.DARK_GRAY);
obj.setResizable(false);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.add(Gameplay);
obj.setVisible(true);

If you need to see other parts of my code, please tell me; this question is already really long, and my total code is 550 lines.


texts:
Hi,

this one thing isn't clear to me:
Is it possible, to debug C# of Unity 4.3 with Visual Studio 2013 without any plugin?

If no, what or how else should I debug then?


texts: How to create a simple side scroller game

texts:
Possible Duplicate:
  How to create games with scrolling?

I'm still pretty new to game programming and any tutorial that I have worked with stuck to only games with the initial screen. I want to start creating my own games but there are a few things that I still need to learn. One of them is how to create a game that side-scrolls. For example; Mario... Or ANY type of game like that...

Can anyone give me a small example to create something like that. I'm not asking for any specific language because currently in school I am learning javascript but I know some c++/java/processing/objective-c as well. So any of those languages would be fine and I could probably implement it in any of the others...

I have been searching for some help with this for a while now but could never actually get any help on it.

Thanks in advance!


texts:
Having started learning shaders and experimenting with tools like Shadertoy, I am attempting to make stereoscopic (anaglyph or autostereogram) shaders as an exercise. For this, I need to displace each pixel to the left/right depending on its depth value.

I am trying to generate a double image, based on the original image and the depth map, with each image pixel displaced to the left and right by a value depending on the depth map - so background pixels are displaced more/less (depending on the mode) than foreground pixels.

It would be easy to get the color of the pixel, say, 30 px to the left or right, if I needed a displacement of 30 for this particular pixel. The problem is, this would not actually work: instead, I need to change the color of the pixel 30 px to the left or right, and displace the color of the current pixel there.

One solution would be to use a for loop and check each pixel in the possible displacement range for its depth value. However this has an impact on performance that becomes untenable for large displacement values. With an average eye distance of 65 mm, this can easily require hundreds of pixels of displacement range.

Another solution (as per this answer) would be to generate two viewpoints and combine them, but I want to avoid doing so here. I am searching for a solution based on a single image and its depth map instead.

Is there a another, more efficient way to displace pixels in such a way using shaders?

Note: I am using Shadertoy for ease of use, but if a solution exists but is not usable in it, for example requiring a 3D engine to implement, it is still of interest.


texts: Loading images in XNA 4.0; "Cannot Open File" Problems

texts:
Okay, I'm writing a game in C#/XNA 4.0 and am utterly stumped at my current juncture: Sprite animation.  I understand how it works and have all the code in place, but my ContentLoader won't open my file...

Basically, my directory looks like this:

    //WindowsGame1
      - "Game1.cs"
      - //Classes
          - "NPC.cs"
      - Content Reference
          - //Images
              - "Monster.png"

Inside my NPC class, I have all the essential drawing functions, i.e. LoadContent, Draw, Update.  And I can get the game to find the correct file and attempt to open it, but when it tries, it throws an exception and tells me it can't open the file.  This is how my code in my NPC class looks:

    Texture2D NPCImage;
    Vector2 NPCPosition;
    Animation NPCAnimation = new Animation();

    public void Initialize()
    {
        NPCAnimation.Initialize(NPCPosition, new Vector2(4, 4));
    }

    public void LoadContent(ContentManager Content)
    {
        NPCImage = Content.Load<Texture2D>("_InsertImageFilePathHere_");
        NPCAnimation.AnimationImage = NPCImage;
    }

The rest of the code is irrelevant at this point because I can't even get the image to load.  I think it might have to do with a directory problem, but I also know little to nothing about spriting or working with images or animations in my code.  Any help is appreciated.  Not sure if I provided enough information here, so let me know if more is needed!  Also, what would be the correct way to direct that Content.Load to Monster.png given the current directory situation?  Right now I just have it using the full path from the C:// drive.  Thanks in advance!


texts: Rotating UI element using touch for mobile - Unity 2D

texts:
I want to create the above object that will rotate on z-axis following the direction of a finger. Like a dial. I have written the following code and attached it to that element:

private float rotationRate = 3.0f;

    void Update()
    {
        // get the user touch input
        foreach (Touch touch in Input.touches)
        {
            Debug.Log("Touching at: " + touch.position);

            if (touch.phase == TouchPhase.Began)
            {
                Debug.Log("Touch phase began at: " + touch.position);
            }
            else if (touch.phase == TouchPhase.Moved)
            {
                Debug.Log("Touch phase Moved");
                transform.Rotate(touch.deltaPosition.y * rotationRate,
                                 -touch.deltaPosition.x * rotationRate, 0, Space.World);
            }
            else if (touch.phase == TouchPhase.Ended)
            {
                Debug.Log("Touch phase Ended");
            }
        }
    }

But the element does not move at all. Any ideas?

EDIT:

Here is a gif for better understanding:


texts:
For a 2D overlay in a 3D environment using DirectX, is the 2D overlay still coded as a surface in 3d always positioned in front of the camera?

I haven't tried this yet but I imagine that technique would lead to small jitters as a scene moves, plus lighting weirdness.  It would help me to know the correct way before I struggle in the wrong direction.

I'm very new to DirectX and game programming and I have limited experience with the paradigms of unmanaged APIs.  I'm using C# with SlimDX.  I have a re-organized version of the SlimDX Triangle tutorial working well.

What I read on this site and others regarding DirectX is that DirectX only draws/shades triangles and the rest is up to me.

SlimDX seems to have some stuff in the DirectX2D namespace - RenderTarget, which has a DrawText() method, but I can't figure out how to get such a 2D RenderTarget hooked to my scene to play with it.

Thanks!


texts:
I recently realized Texture2D implements IDisposable, and now (while trying to track down a memory leak) wonder about where and when I should dipose this.

My current architecture is that I have a SpriteComponent instance which encapsulates and hides the Texture2D. Internally, when I switch screens (eg. MainMenuScreen => WorldMapScreen), I call Dispose on the current screen, which calls dispose on the entities, which calls dispose on the textures.

But this results in some wacked-out behaviour, like textures apprearing super zoomed in momentarily, or appearing black, or appearing as garbage image data.

So my question is really, when should I call Dispose on Texture2Ds?

(FYI, I also can switch to a screen, and then later switch back to it, which currently causes me to reload the sprites, and by proxy, the textures.)


texts: How can I scale up sprites but maintain visual quality?

texts:
I am using WebGL. I have an isometric grid which contains tiles. Some have 'tree' sprites on them. If I have my tree sprite loaded from a texture with a fixed resolution, when I zoom into the grid (scale things up), the sprite texture looks poor. How can I render sprites such that quality is maintained when the player zooms in?

Some provisos:

I can't use vector graphics, as the textures are far too detailed.
The scaling needs to be smooth.


texts: CubeRealm OpenGL rotation problems, need help. :\

texts:
I'm totally new to OpenGL and I'm working on a Sandbox game called CubeRealm. My problem you see is rotation. I've got it in my head that to rotate the 'camera' I just rotate all the scene by the negative value of the camera's rotational values. However so far it seems to not be working.

Here's the code snippets:

glPushMatrix();

lighting();
/*
 (640^2)/(64^2)=amount of cubes on one 640x640 plane(409,600,4,096)
 */
//TODO: fix z axis problem for translating
glRotatef(-player.camera.rotation.x,1.0,0.0,0.0);
glRotatef(-player.camera.rotation.y,0.0,1.0,0.0);
glRotatef(-player.camera.rotation.z,0.0,0.0,1.0);
renderGrid();

glPopMatrix();

glutSwapBuffers();

//SNIPPET2...

case LOOK_UP:
    if(player.camera.rotation.y!=-90.0){ //if they are not looking up
        //make them look up
        player.camera.rotation.y-=90.0;
        //TODO: set direction the camera is facing in
    }
    break;
case ROTATE_LEFT:
    if(player.camera.rotation.x!=0.0){
        player.camera.rotation.x-=90.0;
        //TODO: set direction the camera is facing in
    }else{
        player.camera.rotation.x=360.0;
        player.camera.rotation.x-=90.0;
        //TODO: set direction the camera is facing in
    }
    break;
case LOOK_DOWN:
    if(player.camera.rotation.y!=90.0){ //if they are not looking down
        //make them look down
        player.camera.rotation.y+=90.0;
        //TODO: set direction the camera is facing in
    }
    break;
case ROTATE_RIGHT:
    if(player.camera.rotation.x!=360.0){
        player.camera.rotation.x+=90.0;
        //TODO: set direction the camera is facing in
    }else{
        player.camera.rotation.x=0;
        player.camera.rotation.x+=90.0;
        //TODO: set direction the camera is facing in
    }
    break;

When I press the right arrow key(rotate to the right) it doesn't rotate also when I rotate up(up arrow) it goes weird instead of allowing me to see the top of the skybox it still shows me my test cubes.

So guys how do I fix the rotation, what am I doing wrong?

Note the 'TODO: set direction' stuff is for my local axis system. Those TODOs are irrelevant to the question.


texts: How to Sync the Location After Getting Up from Ragdoll?

texts:
I am currently working on multiplayer fighting game and my game will have an anim->ragdoll when the player is knocked out and be able to getting up from it. My problem now is ragdoll is making my character to jitter so I have to disable Replication Movement during ragdoll and enabling it again after getting up from the ragdoll.
My problem now is I am having problem when the character is getting up after ragdoll, as soon I enabling Replication Movement again, the character is snapped back at the initial position before the ragdoll, even though I have set the character location and stuff.

Here is the bp that I set up the location and stuff

This is how I enabling back the replication movement after Getting Up anim is complete and this is where the problem exist.

I tried to set the location back to the current meshlocation that I recorded during the ragdoll mode which is run on tick but still the problem persist. Any ideas or suggestion for another approach to handle this? Thanks!


texts: Need help understanding VkCommandBuffer and VkCommandPool

texts:
I'm creating my first Vulkan project and I'm at the point where I need to send commands to the GPU. Now I need help understanding how and when commands are being executed and what sort of commands can be sent. I have a working example of where I clear the screen using the following.

Creating the Buffer

VkCommandBufferAllocateInfo commandBufferAllocateInfo{};
commandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
commandBufferAllocateInfo.commandPool = engine.pipeline.command_pool;
commandBufferAllocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
commandBufferAllocateInfo.commandBufferCount = 1;

VkCommandBuffer commandBuffer = VK_NULL_HANDLE;

vkAllocateCommandBuffers(
    engine.device.instance,
    &commandBufferAllocateInfo,
    &commandBuffer
);

Clearing the screen

VkCommandBufferBeginInfo commandBufferBeginInfo{};
commandBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;

engine.ErrorCheck(vkBeginCommandBuffer(
    commandBuffer,
    &commandBufferBeginInfo
));

VkRect2D renderArea{};
renderArea.offset.x = 0;
renderArea.offset.y = 0;
renderArea.extent = window->GetVulkanSurfaceSize();

std::array<VkClearValue, 2> clearValues{};
// Depth stencil
clearValues[0].depthStencil.depth = 0.0f;
clearValues[0].depthStencil.stencil = 0;
// Color
clearValues[1].color.float32[0] = 0.0f;
clearValues[1].color.float32[1] = 0.0f;
clearValues[1].color.float32[2] = 1.0f;
clearValues[1].color.float32[3] = 0.0f;

VkRenderPassBeginInfo renderPassBeingInfo{};
renderPassBeingInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassBeingInfo.renderPass = engine.window.renderPass;
renderPassBeingInfo.framebuffer = engine.window.framebuffers[engine.window.activeSwapchainImageId]; // Get current frame buffer
renderPassBeingInfo.renderArea = renderArea;
renderPassBeingInfo.clearValueCount = clearValues.size();
renderPassBeingInfo.pClearValues = clearValues.data();

vkCmdBeginRenderPass(
    commandBuffer,
    &renderPassBeingInfo,
    VK_SUBPASS_CONTENTS_INLINE
);

I'm finding it difficult to understand. I see that when you define a CommandBuffer you point to the pool that it will be submitted to, then when you execute the command it gets added to the queue to be processed asynchronously with the logic that is happening CPU side? I'm not sure if that is right.

Also, can the command buffer be used for other commands? and if so, what commands and how would I find example usage of them.

And what is a command pool in the scheme of things that is happening?


texts: Finding the right directory structure for version control

texts:
Recently I've started thinking about how to layout the directory structure for my game engine. And well, I kinda hit a little snag.

There's going to be 2 people working on this project. Me and one of my friends. The problem is how do I do the layout of the directories so that it works nicely with version control (I'm using Plastic SCM. It has really nice features).

I'm thinking of dividing it up into 3 separate things:

A source code respository for storing all the C++ code
An exported assets repo where my friend can store all his exported data. (Exported as in final version that can be used by the engine).
And a raw assets directory where all my friends raw assets go into. These include stuff like psd files and mb files for easier backup and versioning.

What do you think of this structure? Any comments are welcome. I'm really down in the dirt with this one.


texts: LineRenderer sorting order - lines always in front of everything

texts:
I have 3 cameras and 3 canvases.

Back Camera: depth = -5, Back Canvas: Sorting layer - BackLayer,
Camera: depth = 0, Middle Canvas: Sorting layer - MiddleLayer,
Camera: depth = 10, Front Canvas: Sorting layer - FrontLayer,

Orders in canvases are also set (for SpriteRenderers, images, ui etc.)

Back is for a background image and stars, middle for mountains and front for the UI. Everything is working perfectly with one exception:

No matter where I draw lines with a LineRenderer - they're always at the front of everything (each canvas).

The one situation where the line moves deeper is when I set it's points Z to some huge values like 30000 and then - they're just behind everything.

My goal is to place these lines along with the background image and stars on the BackLayer or BackCanvas.

What I've already tried:

Setting LineRenderer sorting layer and it's order from the code. I read somewhere on Unity forums that lineRenderer has to have a special material for this to work but I tried most of them - not working.
I also tried setting their positions manually, from the inspector, from the code, incrementally in the Update() method - they're always in front or complately hidden (with huge numbers mentioned above).
I tried assigning them to different canvases (back, middle, front) as children  didn't work too.

On Unity forums I also read a post which says that we shouldn't use sorting layers with linerenderer and use only Z positions.

If someone has any experience with this, I would be grateful. I really have no idea if I'm doing something wrong or what.


texts: Can I make a Flash version of an actual game?

texts:
Possible Duplicate:
  Legal issues for a “fangame” of a commercial franchise?

For example, some of you may have seen Portal: The Flash Version. I was wondering what the legal background on this kind of stuff is, for example what legal things I'm supposed to say, give credit to the original's creators and all.

Obviously, I'm presuming that I'm not allowed to make money off of it, but I just want to know what restrictions there are of making a free Flash version.

For example, would I be allowed to make a Yu-Gi-Oh! game based off the Power Of Chaos series? And if so, would I be allowed to use the Yu-Gi-Oh name or would I have to call it something else?


texts: Why does my object "jump" immediately as the game starts?

texts:
I'm having a problem where, when I start my game, my game object (a 3D plane) immediately jumps 300 pixels or so. I suspect this has something to do with my joystick handling code that I've written to move this game object:

 xMin1 += Input.GetAxisRaw("LeftRight");
 yMin1 += Input.GetAxisRaw("UpDown");

 //_targetPlane is my game object
 _targetPlane.transform.position = new Vector3(xMin1, yMin1, 2.5f);

The object jumps even if I don't touch the joystick. Am I doing this wrong?


texts:
For a new game we have do set up a scene with a minimum of 30 bone animated models.(shooter)
The problem is that the update process for the animated models takes too long.

Thats what I do:
Each character has ~30 bones and for every update tick the animation gets calculated and every bone fires a event with the new matrix. The physics receives the event with the new matrix and updates the collision shape for that bone. The time that it takes to build the animation isn't that bad (0.2ms for 30 Bones -> 6ms for 30 models). But the main problem is that the physic engine (Bullet) uses a diffrent matrix for transformation and so its necessary to convert it.

Code for matrix conversion: (~0.005ms)

btTransform CLEAR_PHYSICS_API Mat_to_btTransform( Mat mat )
{
btMatrix3x3 bulletRotation;
btVector3 bulletPosition;

XMFLOAT4X4 matData = mat.GetStorage();

// copy rotation matrix
for ( int row=0; row<3; ++row )
    for ( int column=0; column<3; ++column )
        bulletRotation[row][column] = matData.m[column][row];
for ( int column=0; column<3; ++column )
    bulletPosition[column] = matData.m[3][column];

return btTransform( bulletRotation, bulletPosition );
}

The function for updating the transform(Physic):

void CLEAR_PHYSICS_API BulletPhysics::VKinematicMove(Mat mat, ActorId aid)
{
if ( btRigidBody * const body = FindActorBody( aid ) )
{
    btTransform tmp = Mat_to_btTransform( mat );
    body->setWorldTransform( tmp );
    }
}

The real problem is the function FindActorBody(id):

    ActorIDToBulletActorMap::const_iterator found = m_actorBodies.find( id );
if ( found != m_actorBodies.end() )
    return found->second;

All physic actors are stored in m_actorBodies and thats why the updating process takes to long. But I have no idea how I could avoid this.

Friendly greedings,
Mathias


texts:
I am in a situation where I am writing a framework in XNA and there will be quite a lot of static (ish) content which wont render that often. Now I am trying to take the same sort of approach I would use when doing non game development, where I don't even think about caching until I have finished my application and realise there is a performance problem and then implement a layer of caching over whatever needs it, but wrap it up so nothing is aware its happening.

However in XNA the way we would usually cache would be drawing our objects to a texture and invalidating after a change occurs. So if you assume an interface like so:

public interface IGameComponent
{
    void Update(TimeSpan elapsedTime);
    void Render(GraphicsDevice graphicsDevice);
}

public class ContainerComponent : IGameComponent
{
    public IList<IGameComponent> ChildComponents { get; private set; }

    // Assume constructor

    public void Update(TimeSpan elapsedTime)
    {
        // Update anything that needs it
    }

    public void Render(GraphicsDevice graphicsDevice)
    {
        foreach(var component in ChildComponents)
        {
            // draw every component
        }
    }
}

Then I was under the assumption that we just draw everything directly to the screen, then when performance becomes an issue we just add a new implementation of the above like so:

public class CacheableContainerComponent : IGameComponent
{
    private Texture2D cachedOutput;
    private bool hasChanged;
    public IList<IGameComponent> ChildComponents { get; private set; }

    // Assume constructor

    public void Update(TimeSpan elapsedTime)
    {
        // Update anything that needs it
        // set hasChanged to true if required
    }

    public void Render(GraphicsDevice graphicsDevice)
    {
        if(hasChanged)
        { CacheComponents(graphicsDevice); }
        // Draw cached output
    }

    private void CacheComponents(GraphicsDevice graphicsDevice)
    {
        // Clean up existing cache if needed
        var cachedOutput = new RenderTarget2D(...);
        graphicsDevice.SetRenderTarget(renderTarget);
        foreach(var component in ChildComponents)
        {
            // draw every component
        }
        graphicsDevice.SetRenderTarget(null);
    }
}

Now in this example you could inherit, but your Update may become a bit tricky then without changing your base class to alert you if you had changed, but it is up to each scenario to choose if its inheritance/implementation or composition. Also the above implementation will re-cache within the rendering cycle, which may cause performance stutters but its just an example of the scenario...

Ignoring those facts as you can see that in this example you could use a cache-able component or a non cache-able one, the rest of the framework needs not know. The problem here is that if lets say this component is drawn mid way through the game rendering, other items will already be within the default drawing buffer, so me doing this would discard them, unless I set it to be persisted, which I hear is a big no no on the Xbox. So is there a way to have my cake and eat it here?

One simple solution to this is make an ICacheable interface which exposes a cache method, but then to make any use of this interface you would need the rest of the framework to be cache aware, and check if it can cache, and to then do so. Which then means you are polluting and changing your main implementations to account for and deal with this cache...

I am also employing Dependency Injection for alot of high level components so these new cache-able objects would be spat out from that, meaning no where in the actual game would they know they are caching... if that makes sense. Just incase anyone asked how I expected to keep it cache aware when I would need to new up a cachable entity.


texts: How can I make a level generator script run in Edit Mode?

texts:
Description
I've a script that takes in a PNG bitmap (e.g. 8x8) and, reading from that, populates the grid with cells where alpha > 0.
Problem
The script runs in Awake(), so it can only be seen in Play Mode. I want it to always appear in the scene, even in Edit Mode.
Potential Solutions
I know of the [ExecuteInEditMode] attribute, as well as the OnValidate() callback. I don't know which is better to use, though, or what pitfalls to avoid.
Additionally, in the past, I created a level generator that created a mesh, which I saved as an .asset with a custom editor button. The .asset was then loaded from inside the script. However, if possible, I'd like a more elegant — and automatic — solution.
Other
I'm using Unity 2018.4, and the grid is isometric. (I'm not using Unity's built-in Tilemap.)


texts:
I wanted to test my in-game ads and I forgot to add my device as a Test Device. My game is not yet in Google Play and App Store but I have 12 impressions on AdMob. What I have to do in this situation? I know that Google bans for fake click and impression so what can I do? do I have to inform Google about that?

Thank for help.


texts: GLSL Shader compiles, but source is empty

texts:
I'm trying to compile a GLSL shader, to which I use the following code.

Initialization

SDL_Window* boringInitStuff(){
    SDL_Init(SDL_INIT_VIDEO);
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 );
    SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );

    Uint32 windowFlags = SDL_WINDOW_OPENGL;
    SDL_Window* sdlWindow = SDL_CreateWindow("Boooring", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 400, 400, windowFlags);

    SDL_GL_CreateContext(sdlWindow);

    glewExperimental = GL_TRUE;
    glewInit();

    return sdlWindow;
}

File parser

void readFile(std::string path, std::string& data){
    std::ifstream f(path.c_str(), std::ios::binary);
    data.assign((std::istreambuf_iterator<char>(f)),
                (std::istreambuf_iterator<char>()));
}

Main

int main(int argv, char** args) {
    SDL_Window* sdlWindow = boringInitStuff();

    std::string buffer;
    readFile("./compile_test.vert", buffer);
    const char* cBuffer = buffer.c_str();

    GLuint shaderID = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(shaderID, 1, &cBuffer, nullptr);
    glCompileShader(shaderID);

    while(!SDL_QuitRequested()){
        SDL_GL_SwapWindow(sdlWindow);
    }

    return 0;
}

But when I try to inspect the source code in gDEBugger, the source code is gone. Linking of course doesn't work aswell. The weird thing is, that the compilation error checking works.
EDIT: When I copy & paste the main part into another opengl project, it works.


texts: whats the difference between the two switches in rpg maker mv?

texts: I dont understand what is the difference between the top and bottom set of switches in rpg maker mv. Can someone please explain?


texts: What is going on in this SAT/vector projection code?

texts:
I'm looking at the example XNA SAT collision code presented here:

http://www.xnadevelopment.com/tutorials/rotatedrectanglecollisions/rotatedrectanglecollisions.shtml

See the following code:

private int GenerateScalar(Vector2 theRectangleCorner, Vector2 theAxis)
{
    //Using the formula for Vector projection. Take the corner being passed in
    //and project it onto the given Axis
    float aNumerator = (theRectangleCorner.X * theAxis.X) + (theRectangleCorner.Y * theAxis.Y);
    float aDenominator = (theAxis.X * theAxis.X) + (theAxis.Y * theAxis.Y);
    float aDivisionResult = aNumerator / aDenominator;
    Vector2 aCornerProjected = new Vector2(aDivisionResult * theAxis.X, aDivisionResult * theAxis.Y);

    //Now that we have our projected Vector, calculate a scalar of that projection
    //that can be used to more easily do comparisons
    float aScalar = (theAxis.X * aCornerProjected.X) + (theAxis.Y * aCornerProjected.Y);
    return (int)aScalar;
}

I think the problems I'm having with this come mostly from translating physics concepts into data structures. For example, earlier in the code there is a calculation of the axes to be used, and these are stored as Vector2, and they are found by subtracting one point from another, however these points are also stored as Vector2s. So are the axes being stored as slopes in a single Vector2?

Next, what exactly does the Vector2 produced by the vector projection code represent? That is, I know it represents the projected vector, but as it pertains to a Vector2, what does this represent? A point on a line?

Finally, what does the scalar at the end actually represent? It's fine to tell me that you're getting a scalar value of the projected vector, but none of the information I can find online seems to tell me about a scalar of a vector as it's used in this context. I don't see angles or magnitudes with these vectors so I'm a little disoriented when it comes to thinking in terms of physics. If this final scalar calculation is just a dot product, how is that directly applicable to SAT from here on? Is this what I use to calculate maximum/minimum values for overlap? I guess I'm just having trouble figuring out exactly what the dot product is representing in this particular context.

Clearly I'm not quite up to date on my elementary physics, but any explanations would be greatly appreciated.


texts: Is it legal to record music with a synthesizer and use it in my game?

texts:
I want to make music for game on my own because I don't have professional composer hired. I have found some softwares for making music, but most of them cost some money.
I have an idea to record music on synthesizer, then edit it and use in my game.
My question is:

Is it legal to record music (that I have composed and edited) on synthesizer and use it in my game (the game may be free or charged)?


texts: Frame graph in Vulkan: from theory to implementation

texts:
I've watched the excellent talk from Yuriy[1] and read a blog post[2] multiple times already, but I still cannot find the answers to the questions I have.
I really like the idea of defining a graph of "virtual resources", it gives a lot of flexibility, maintanability, and ease of use (think about synchronization) in the long term. First, I thought that the easier way to solve my problem (described below) is to implement this system so that the graph building and the transformation to the actual graphics API wouldn't be done every frame, only when the conditions (eg. graphics settings) change.
However, extending the "only when the conditions change" statement to include game logic-related decisions, we get to a point where the frame graph must be rebuilt almost every frame. This is also what Yuriy suggested in his talk and I agree with it.
The main problem
In Vulkan the whole pipeline (with the corresponding render pass) must be pre-built. So the rebuilding of the whole graph every frame can be a bottleneck as I can imagine. The pipeline cache could speed up things (in theory) but avoiding sudden frame-rate drops is top priority. However, if a pipeline (especially the shaders) have not yet been built, it could cause a hitch up. And pre-warming the cache(s) with every possible permutations defeat the purpose of the whole system.
The question
So I'm wondering if there is a way to keep the best from both worlds, rebuilding the whole graph every frame while avoiding sudden frame drops from pipeline creation.
If there is no such solution, what would be the closest thing to this kind of dynamic whole frame predefinition? Should I fall back to the rarely rebuild graph, and use another method to skip (sub)passes?
References
[1] FrameGraph: Extensible Rendering Architecture in Frostbite (GDC Vault)
[2] Render graphs and Vulkan — a deep dive (link)


texts:
I have two RGBA integers. What procedure should I perform on them to return the multiplied colour? Do I need to split the RGBA integer into its component integers (R, G, B, A)?

I'm using this for a lighting engine.


texts: Does destroying object at List element make it null?

texts:
I'm using a list in Unity and I'm adding objects to it as they are collected through the game. But they will then be used and destroyed. My first question is do I use Destroy(), or should I just use List.Remove()? I'm not sure what happens to an object once it is removed from a list and not used anymore. Does garbage collection get it? My other question is, when I check the list (I will always be checking the first index), if that object was just destroyed or removed, will that element now be null? I've tried reading about this but it's hard to find an exact answer. Thanks for the help.

For reference, here is the code that I came up with based on my current assumptions about lists:

public List<BasePickUp> pickUpQueue = new List<BasePickUp>();
public bool pickUpActive = false;

void Update ()
{
    if (pickUpQueue[0] != null && !pickUpActive)
    {
        pickUpActive = true;
        pickUpQueue[0].ActivatePickUp();
    }
}

Edit: I have been playing with the if statement conditions, and even if I change pickUpActive to true, it somehow still manages to get inside the if statement to the breakpoint there. How is that possible? The condition says pickUpActive must be false, and yet it blows right by it. When I set the first condition to pickUpQueue != null, I get an error for index out of range once, when it is set to check the first element, as it is in the above code, I get an index out of range every frame. I finally changed it to pickUpQueue.Count != 0, and that finally kept it from getting into the if statement. If anyone can help me understand what is going on with my bool, and to understand exactly how to handle this list, I would greatly appreciate it! Thanks!


texts: Should I pass my resource manager to types that might need it, or make it global?

texts:
Say I have this Cache<typename Resource> class template, which is a resource cache that contains an std::map<std::string, Resource>, mapping strings to resources.

I can many different kinds of resources: sounds, textures, geometry etc. So I need to have something like a container of all of these caches:

struct ResourceManager {
  Cache<Sound*> _soundCache;
  Cache<Mesh*> _meshCache;
  Cache<Texture2D> _textureCache;
};

A Mesh object might need to query Texture objects from the texture cache, so working with these caches is possible in two ways: Either pass a pointer to _textureCache to every Mesh object, perhaps via its constructor (this approach is pretty clumsy), or define a ResourceManager object globally, so every class can use its caches all the time.

Has this issue ever been brought up for discussion? How should I deal with it?

What do most engines do? Where do they store these caches? Is it viable to do something like this? :

~GameEngine.h~

...
#include "ResourceManager.h"

//global object
resourceManager g_resourceManager;

class GameEngine {
  ...
};


texts: How can I generate signed distance fields (2D) in real time, fast?

texts:
In a previous question, it was suggested that signed distance fields can be precomputed, loaded at runtime and then used from there.

For reasons I will explain at the end of this question (for people interested), I need to create the distance fields in real time.

There are some papers out there for different methods which are supposed to be viable in real-time environments, such as methods for Chamfer distance transforms and Voronoi diagram-approximation based transforms (as suggested in this presentation by the Pixeljunk Shooter dev guy), but I (and thus can be assumed a lot of other people) have a very hard time actually putting them to use, since they're usually long, largely bloated with math and not very algorithmic in their explanation.

What algorithm would you suggest for creating the distance fields in real-time (favourably on the GPU) especially considering the resulting quality of the distance fields?

Since I'm looking for an actual explanation/tutorial as opposed to a link to just another paper or slide, this question will receive a bounty once it's eligible for one :-).

Here's why I need to do it in real time:

  If you have to precompute these SDFs for large 2D environments (think of a large Terraria-like map), this would mean that you're accepting a rather large overhead in storage space (and map-generation time) in favour of implementing a more complicated algorithm that is fast enough for real time SDF generation.

  For example, a relatively small map with 1000*256 (width*height) with a tile size of 10*10 pixels and thus total dimensions of 10000*2560 pixels would already cost you around 2 megabytes of size, if you choose a relatively small SDF resolution of 128x128, assuming that you're storing only the distance values from 0 to 255.

  Obviously, this can quickly become too much and is an overhead that I don't want to have.

There's something else:

  SDFs can be used for many things (like collision detection), and some useful applications are potentially not even discovered yet. I think a lot of people are going to look for these things in the future, and if we get a comprehensive answer in here, I think we're going to help a lot of people.


texts: Why doesn't OnCollisionStay execute continuously?

texts:
I'm currently trying to build a simple demo where the player can jump. This is the script I have setup so far.

using UnityEngine;
using System.Collections;

public class PlayerJump : MonoBehaviour
{
    public Vector3 jumpForce;

    void OnCollisionStay (Collision other)
    {
        print("OnCollisionStay");
        if (Input.GetKey (KeyCode.Space) && other.gameObject.tag == "Block")
        {
            rigidbody.velocity += jumpForce;
        }
    }
}

Whenever I check the console, the message "OnCollisionStay" is only printed 21 times. Just for more details the GameObject this script is attached to contains a rigidbody that uses gravity, has the x, y, and z rotation axes frozen, and the z position axis forzen as well. The gameObject I'm trying to collide with has a simple box collider attached to a cube with a scale of (5, 1, 5). What am I doing wrong? I am under the impression that OnCollisionStay continuously executes until the player is no longer colliding with anything, then starts executing again on collision?


texts: How can I generate a 2D mountain landscape procedurally?

texts:
Every level in my game needs to have a different mountain landscape background generated automatically (but the landscape must be the same for each level).

How could I generate such a landscape procedurally? Maybe fractals?

Note: I am using LibGDX and Java on Android


texts: How to spawn collectibles at random positions in Java

texts:
Please i need assistance,
I made a game in Android Studio with Java.
I am almost done with the game just that i'm having an issue where my collectible keeps re-spawning in the same position after the player has collected it.
I would like for it to re-spawn at random positions on the screen, how can i do this?.
The collectible is a fuel can.

Here is the fuel can collectible class

Fuel.java

public class Fuel extends GameObject {

 public Fuel(Bitmap res, int w, int h, int numFrames) {
        x = GamePanel.WIDTH + 5000;
        y = GamePanel.HEIGHT / 2;
        dy =(random.nextInt()*(GamePanel.HEIGHT - (maxBorderHeight* 2)+maxBorderHeight));
        dx = +GamePanel.MOVESPEED;
        height = h;
        width = w;

        Bitmap[] image = new Bitmap[numFrames];
        spritesheet = res;

        for (int i = 0; i < image.length; i++)
        {
            image[i] = Bitmap.createBitmap(spritesheet, 0, i*height, width, height);
        }
        animation.setFrames(image);
        animation.setDelay(100-dx);
        animation.update();
    }

    public void update()
    {
        if (x < 0) {
            reset();
        }
        x += dx;
        dx = dx- 1;

        if (dx <= -15) {
            dx = -15;
        }

    animation.update();
    }

    public void draw(Canvas canvas)
    {
        try {
            canvas.drawBitmap(animation.getImage(),x,y,null);
        }catch (Exception e){}
    }

    public void reset(){
        x = GamePanel.WIDTH + 5000;
        y = GamePanel.HEIGHT/2 ;
        dy = (random.nextInt()*(GamePanel.HEIGHT - (maxBorderHeight* 2)+maxBorderHeight));
        dx = +GamePanel.MOVESPEED;

    }

    public void fuelCollected(){
    reset();
    }

}

Here is my GamePanel.java class

public class GamePanel extends SurfaceView implements SurfaceHolder.Callback
{
  private Fuel fuel;

  @Override
  public void surfaceCreated(SurfaceHolder holder){
   fuel = new Fuel(BitmapFactory.decodeResource(getResources(), R.drawable.fuel),40,40,1);
  }

 public void update()
{
fuel.update();
        if(collectFuel(player,fuel)){
            distance +=100;
        }

public boolean collectFuel(GameObject player, GameObject fuel){
    if(Rect.intersects(player.getRectangle(),fuel.getRectangle()))
    {
        fuelCollected();
        return true;
    }
    return false;
}

public void fuelCollected(){fuel.fuelCollected();}
}
 @Override
public void draw(Canvas canvas){

// draw fuel can

        fuel.draw(canvas);
 }
}


texts: OpenGL ES - render to texture - how to preserve original depth buffer

texts:
I render to texture and attach my own depth buffer that has texture target. However, after I finish rendering I would like to set original depth buffer back.
To start rendering to texture I do:
glGetIntegerv(GL_RENDERBUFFER_BINDING, &bindedDepthBuffer); //returns 0
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &bindedFrameBuffer);  //returns 0

glBindFramebuffer(GL_FRAMEBUFFER, rttFboId);
glBindRenderbuffer(GL_RENDERBUFFER, rttDepthId);
glViewport(0, 0, rttViewPortWidth, rttViewPortHeight);

... render scene

glViewport(0, 0, origWidth, origHeight);
glBindFramebuffer(GL_FRAMEBUFFER, bindedFrameBuffer);

Now after I do:
glBindRenderbuffer(GL_RENDERBUFFER, bindedDepthBuffer);

the original depth buffer stops working and it seems as its content is empty (everything that is rendered after this point behave like the depth buffer has been cleared). This problem occurs only on some OpenGL ES devices with Android and I dont know what can cause this.


texts:
I've been playing around with SDL2 and have made a very nifty little program!
Now, I'm trying to set my window icon - for the SDL Window. I have the following code in the main function of my program, right after SDL initialization stuff.

            SDL_Surface* icon = IMG_Load("assets/system/interface/icon.png");
        SDL_SetWindowIcon(window, icon);

However, the topbar icon and the toolbar icon remain the same, default application icon! What could I be doing wrong???

Thanks!


texts:
I have seen some people using Jenkins CI with Unity, would it be wise to install Jenkins locally and use it with Unity? I've never used Jenkins, so I can't imagine why not. Is this ill-advised?

I would have set up Jenkins on my old laptop, but I don't have windows on it. Is there any harm in using it locally?


texts: Exporting the frames in a Flash CS5.5 animation and possibly creating the spritesheet

texts:
Some time ago, I asked a question here to know what would be the best way to create animations when making an Android game and I got great answers.

I did what people told me there by exporting each frame from a Flash animation manually and creating the spritesheet also manually and it was very tedious.

Now, I changed project and this one is going to contain a lot more animations and I feel like there has to be a better way to to export each frame individually and possibly create my spritesheets in an automated manner.

My designer is using Flash CS5.5 and I was wondering if all of this was possible, as I can't find an option or code examples on how to save each frame individually.

If this is not possible using Flash, please recommend me another program that can be used to create animations without having to create each frame on its own. I'd rather keep Flash as my designer knows how to use it and it's giving great results.


texts: Scrolling Camera in Pygame is not working properly

texts:
I implemented a camera with edges in 2D side scrolling game using Pygame, it is working but sometimes it will scroll for more than it should have, and in case of using different moves that involved movement, sometimes the value will be in float number and it will cause the level to be buggy. I have tried different methods of camera, but none of them worked for me so far. Is there any other way to implement camera, or at least make this one work as intended?

Below is the code for scrolling at x-axis:

   if self.rect.right >= 500 and self.in_level.world_shift_x >= -((self.in_level.total_level_width - (Screen_Width + 32))):
        diff = self.rect.right - 500
        self.rect.right = 500
        self.in_level.shift_world_x(round(-diff, 0))

    if self.rect.left <= 200 and self.in_level.world_shift_x <= -((self.speed / 2)):
        diff = 200 - self.rect.left
        self.rect.left = 200
        self.in_level.shift_world_x(round(diff, 0))


texts:
I'm developing a (scroll) game and i'm getting weird messages in LogCat:

lock_layer() timed out but didn't appear to need to be locked and we recovered(..)
lock_layer timed out (is the CPU pegged?)...
executeScheduledBrodcasts() skipped, contention on the client. We'll try again later.

it looks like the rendering takes too long and causes the warning (i'm drawing ~ 50 images every frame), but is this the emulator fault? When i test it on a device (sony ericsson xperia x8), running 1.6, i don't see any lag or any performance drops (i get ~ 60fps).
I get this warning only in android 1.6.

Should i ignore it? Could it cause the game to crash? Am i doing something horribly wrong or is it a bug?

Run code:

  while(running) {
    try {
       c = holder.lockCanvas(null);
       synchronized(holder) {
           // getElements - returns a Vector of elements to be drawn relative to camera
           elements = collection.getElements(cameraX,cameraY,cameraWidth,cameraHeight);
           for(int i =0 ; i < elements.size(); i++) {
              // draw the element according to camera
              c.drawBitmap(image,elements.get(i).x,elements.get(i).y);
           }
       }

    } finally {
       holder.unloackCanvasAndPost(c);
    }

}


texts: Is Goal-Oriented Action Planning (GOAP) a valid replacement for state machines outside the realm of AI?

texts:
I just learned about Goal-Oriented Action Planning (GOAP, sources below) as used in AI programming. I'm making a state machine for a player-controlled character and was wondering if it can be replaced by a GOAP model? Does this make sense? Or is GOAP only for AI?
Sources:

Goal-Oriented Action Planning (GOAP)
10 Reasons the Age of Finite State Machines is Over
Common Ways to Implement Finite State Machines in Games


texts: is it possible to make a MMO starting with scalable hosting?

texts:
I made a really basic 2D RPG. I want to know whether I can turn it into a free to play MMO.

I cannot afford to rent a server with enough capacity to serve a big number of players but I'm wondering whether I could get a hosting plan that starts cheap but scales enough to eventually handle a big numer of users so I have minimum fixed costs and I can cover expenses on the go with ads or whatever.

Is there such a thing? Thanks


texts: What is the logic behind these design decisions regarding difficulty levels?

texts:
In some games you are unable to play on the harder difficulties before complete it on a lower difficulty. Why?
Achievements are popular. In some games you do not get an achievement for completing the game on the hardest difficulty (e.g. Bethesda RPG's) but for just about everything else, Why?


texts: After sometime increase the speed of Instantiated object

texts:
This may look similar to "increase speed after every N seconds" type question but it's different because objects are being Instantiated and getting destroyed.

In my start() method I'm calling a method called CreateObstacle() after a certain time interval using InvokeRepeating method:

InvokeRepeating("CreateObstacle", 1, 3f);

For those who don't know about the parameters of InvokeRepeating method. The first one is the method name which you want to call. The second is the number of seconds to delay these repeated calls. And the third parameter is the number of seconds between method calls.

In update() method I'm simply storing time per seconds in a float translation:

translation = Time.time;

Then finally in CreateObstacle() method I'm checking that if the seconds are less than 10 then Instantiate ((rocks), new Vector3 (11, -3, 0), Quaternion.identity); else if seconds are greater than 10 do the same Instantiate ((rocks), new Vector3 (11, -3, 0), Quaternion.identity); but with more speed.
So, how to increase speed of the object that is being Instantiated after a certain time interval say 10 seconds. On in which method I should call the InvokeRepeating to decrease it's speed?

but with more speed Explanation:
 Rocks are moving from right to left in the screen. And after every 3 seconds a new rock appears, move right to left and get destroyed. So what I want is that after sometime say 10 seconds the speed of right to left motion increase.


texts: Calculating Linear force required to hit a specific vertex on a parabola

texts:
The idea is a user presses somewhere on the screen and the program will fire an object in a parabola shape from a defined start position that has it's vertex where the user touched the screen.

I have managed to use the two points I have to get the quadratic equation in vertex form, and converted it to standard form ok but I don't know how to get the values required for setLinearVelocity vx and vy in corona sdk.

Current code is:

-- given vertex and another point find the parabola formula in vertex form
-- y=a(x−h)2+k
local y, a, x, h, k, xh
h = event.x
k = event.y
x = xStartPos
y = yStartPos

-- solve for a
xh = (x - h) * (x - h)
y = y + (k * -1)
a = y / xh

-- convert to quadratic formula
-- y = ax^2 + bx + c
local b, c
b = -2 * a * h
c = a * (h * h) + k

local vx, vy = -- calculate something here
proj:setLinearVelocity( vx,vy )


texts: Setting position and look direction of a GameObject

texts:
I'm making a bendable game object comprised of a number of bones. The bones positions are calculated using some joints and some maths and that is all working as expected. But I am struggling to rotate the bones to face the correct direction. I'm settings the bones positions like:

for ( int i = 0; i <= bonesCount; i++ ){
    Vector3 newPosition = someFunction();
    bones[i].transform.position = newPosition;
}

And that works correctly:

But when the bendable object bends the bones retain their original rotation:

I thought I could use Transform.LookAt on the bone at position i to look at the bone at position i + 1 but this gives strange results:

It seems like it's an issue with using the wrong axis (up, right or forward). I see Transform.LookAt accepts a second argument for worldUp but I haven't figured out how that works.

Any suggestions? Is Transform.LookAt the correct method to be using?


texts: How to assign an index to different node clusters? (for pathfinding)

texts:
Hellow~
So for a bit of context: i'm currently working on a RTS (way above may league) which already has a level editor and a node grid which maps the terrain, i previously make a navigation system with A* as explainned by Sebastian Lague in his tutorial series about the topic, but then i run into a problem when running with multiple units (not the point here: but never manage to find each unit cluster within the selection), so i change it into a navmesh mapping which if made dynamic by assigning navmesh obstacles to the unwalkable nodes (the frame after the creation of the node grid)
Now i want to use the node grid basically to check if the target node and the start node share the same node cluster. But here is the thing: i can't assign the needed index to the nodes as i expected.
I've been trying adapting code from this post, but didn't quite make it.
Now i have this one, which i think could achieve something but still gets me a invalid operation exception:
public const int UNWALKABLE_ISLAND = 999;

public static void SetIslands(ref WorldGrid _worldGrid) {
    int width = _worldGrid.nodeGrid.GetLength(0);
    int height = _worldGrid.nodeGrid.GetLength(1);

    bool[,] visited = new bool[width, height];

    int clusterCount = 0;

    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++)
        {
            if (visited[x, y]) { continue; } else {
                List<Node> cluster = new List<Node>() {
                    _worldGrid.nodeGrid[x, y]
                };

                foreach (var node in cluster) {
                    if (node.isWalkable)
                    {
                        visited[node.X, node.Y] = true;
                        node.SetIslandIndex(clusterCount);
                        cluster.AddRange(_worldGrid.GetNeighbours8D(node));
                    }
                    else
                    {
                        cluster.Remove(node);
                    }
                }

                clusterCount++;
            }
        }
    }
}

The error:

InvalidOperationException: Collection was modified; enumeration operation may not execute.
System.ThrowHelper.ThrowInvalidOperationException (System.ExceptionResource resource) (at<437ba245d8404787b9fbab9b439ac908>:0)
System.Collections.Generic.List1+Enumerator[T].MoveNextRare() (at<437ba245d8404787b9fbab9b439ac908>:0) System.Collections.Generic.List1+Enumerator[T].MoveNext() (at<437ba245d8404787b9fbab9b439ac908>:0)
Pathfinding.SetIslands (WorldGrid& _worldGrid) (at Assets/Pathfinding.cs: 25)
WorldGrid.CreateNodeGrid() (at Assets/WorldGrid:80)
WorldGrid+d_12.MoveNext() (at Assets/WorldGrid.cs:42)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, Sustem.IntPtr returnValueAddress) (at<437ba245d8404787b9fbab9b439ac908>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

My node class contains an int that should hold the cluster index, which will be using for the request check. (the code its based from this youtube video)
Right now i'm trying to understand the spectral clustering stuff, i've been told it could help.
I hope you can help an animator in need with some pointers.
Cheers :3
*Oh!, I also tried reading the nav agent path end coordinate for comparison, but it ended up becoming a huge mess for me.


texts: Implementing Dead Reckoning in a Winsock server

texts:
I'm having a little difficulty understanding how I implement Dead Reckoning in my Server-Client Winsock game.

I've been looking on the internet for a decent explanation that explains exactly:

When a message should be sent from the server to the client
How the client should act if it doesn't receive update messages, does it keep using the predicted position as the current position in order to calculate the new predicted position?

Should note I am using Linear Dead Reckoning using the following formula:

path vector = oldPosition - oldestPosition
delta time = oldTime - oldestTime
delta velocity = path vector / delta time
new delta time = current time / oldest time
new prediction = oldPosition + new delta time * delta velocity

Hope this is the correct one! :)

Should also note the connection type is UDP and that the game is played only on the server. The server sents update messages to the client.

Can anyone help please?

Thanks


texts: Choice of open source license for some components, closed source for others

texts:
G'day,

I am working on a set of multiplayer games, where different games play against each other (e.g. you play a Tetris clone, I play an Asteroids clone, but we are both competing against each other). All the games would be based on the same underlying framework written specifically for this project.

I am struggling to comprehend how I would license this so that:

The underlying framework is open source, so other people can create new games based on it.
Some games built on the framework are open source
Other games are closed source

The goal is to have two bundles on something like the Android market:

One free and open source package which has a collection of games
Another "premium" (although I dislike that word) paid package which has a different collection of games.

Usually I am fond of permissive licenses such as MIT/BSD, however I would prefer something more in the vein of the GPL for this. This is because for software such as the snes-9x SNES emulator, which is a great piece of software, there is a ton of poor quality versions being sold, whereas it would be preferable if there was just one authoritative version which was always kept up to date, and distributed for free.

If the underlying framework was GPL'd, would I be able to build closed source games on top of it?

Thanks for your input.

Edit:
@JasonMorales gave me a little more to think about. There are a couple of ways it could be put together:

Main application, handles networking, main menu's, etc, and loads games as plugins.
Games are all separate applications, and the framework will provide a menu, networking, etc.

The first is good because there is guaranteed to be consistency between games. It is not good, however, in the sense that I can't imagine how it would be deployed via the Android market. That is, you go to the market, and download a new game. If it was more akin to a regular package manager, this game would depend on the main application and it would install quietly. I'm not convinced the Android market works like this though.

The second would deploy easier, because each time the user downloads a new game, it does exactly what they expect: downloads a game and gives them a nice icon for them to open it from. There are obviously several downsides to this too though, such as if the framework decides to update its menu or network implementation, the other games will not get this update unless they re-release themselves.

But because I'm ranting, I may create a new question for these matters.


texts: Is it possible to correctly catch up a particle system simulation based on long delta time between many frames?

texts:
I have a particle system with a physics simulation integrator based on delta time (elapsed time between frames) which is implemented on the GPU in a compute shader. I also have a frustum culling system implemented on the GPU. The frustum culling gives me the possibility to cull away draw calls and the dispatch calls for the particle simulation. The culling of draw calls works well, I also don't have a problem with culling the particle simulation when the camera is looking away.
My problem happens when I want to catch up the particle system simulation when the camera looks back at the particle system after looking away for a while. What I do is accumulate the time passed while looking away, then I resume the simulation using all that accumulated time. The problem with this approach is that if the simulation is anything but a simple constant velocity change in one direction, the simulation just doesn't look the same as if the simulation was playing one frame delta at a time.
From what I have read this is a common issue with using time elapsed between frames to simulate physics. What I wonder is if there's a different approach that can actually allow me to correctly play back many seconds of simulation (let's say 20 seconds) the same as if it was played one frame delta at a time?


texts:
I checked the input settings. I added a speed value. I also added Time.deltaTime, but the body is not moving.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    public float speed;
    private Rigidbody rb;

    void Start () {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate () {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
        rb.AddForce(movement * speed);
    }
}


texts: Testing Multiplayer Browser Game on Single Computer

texts:
I am writing a multiplay browser based game and am running into an issue with playtesting simple interactions. When a browser window loses focus is stops running requestAnimationFrame calls. This effectively pauses the state all visuals when focus is lost.

I would like to have two instances of the game running at the same time. I could playtest in one window and observe how a thirdparty would see those actions in another window.

Right now I am only able to toggle between the two windows and see teleportation like behavior as the client state catches up to the new server state.

I am not sure how, without setting up a second computer, I might test this. Anyone have any experience with this or any advice?


texts: Keeping a Character Controller grounded?

texts:
I've got a character that makes use of isGrounded() to determine whether I can jump, whether my air-jump is reset, and the amount of friction to be applied. I've run into a common problem, isGrounded() is fluctuating every frame returning true and false randomly resulting in jagged movement.

The standard suggestion is to constantly apply gravity. Unfortunately, aside from any other more nuanced issues that this could result in, this only works for me if I apply so much gravity that I am no longer able to climb up slopes. I need a way to keep the character grounded without applying large amounts of gravity every frame.


texts: How could I implement destruction of bases in Space Invaders type game?

texts:
What approaches could you use to implement the the gradual destructions of bases/shields in a top down shooter type game similar to Space Invaders?

The simplest approach could be to use a series of sprites that are replaced to show increasing deterioration after each missile hit.

A more advanced approach might be to randomize the deterioration pixel by pixel after each hit, but I'm not sure how to implement an approach like this. Does anyone have any suggestions for how to approach something like this?


texts: Inventory objects not persisting between scenes?

texts:
My Game Manager object has an Inventory script attached to it, which has "Don'tDestroyOnLoad(gameObject)" in its Awake function. During gameplay, items are pushed into a public List in this script. This is done successfully. The trouble comes when changing scenes, where either script instance is being overwritten or the object that was pushed into the list has been destroyed.  How can I prevent this in a way that will scale well?

I am linking to a video you can watch of this problem happening in real time:

https://youtu.be/CLzDJg15VTk

This is the Inventory script, which is attached to my GameManager:

// Inventory.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Inventory : MonoBehaviour
{
    private static Inventory instance = null; // static (class level) variable
    public static Inventory Instance { get { return instance; } } // static getter (only accessing allowed)

    public List<GameObject> itemList;

    private void Awake()
    {
        // if instance is not yet set, set it and make it persistent between scenes
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            // if instance is already set and this is not the same object, destroy it
            if (this != instance) { Destroy(gameObject); }
        }
    }

    // debug only
    public void Debug_PrintItemInventory()
    {
        foreach(GameObject obj in itemList)
        {
            Debug.Log(obj.GetComponent<Item>().itemName);
        }
    }

    public void AddItem(GameObject item)
    {
        itemList.Add(item);
        Debug_PrintItemInventory(); // debug only
    }
}

This is the script that pushes an item into my character's inventory ("gm.GetComponent

// ItemBox.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemBox : MonoBehaviour
{
    bool disabled = false;
    private Animator anim;
    [SerializeField]
    private GameObject[] items = new GameObject[3];
    [SerializeField] private GameObject gm;

    void Start()
    {
        anim = GetComponent<Animator>();
        if (!disabled)
        {
            anim.Play("ItemBoxIdleState");
        }
    }

    void OnTriggerEnter(Collider other)
    {
        if (!disabled && other.gameObject.tag == "Player")
        {
            anim.Play("ItemBoxGetItemState");
            int randInt = Random.Range(0, 3);
            GameObject itemObj = Instantiate(items[randInt].GetComponent<Item>().getPrefab, transform.position + new Vector3(0, 0.375f, 0), Camera.main.transform.rotation);
            gm.GetComponent<Inventory>().AddItem(Instantiate(items[randInt]));
            Destroy(itemObj, 1.6f);
            disabled = true;
        }
    }
}


texts: Ability/Skill Data and Method Structure (C#, Unity3D)

texts:
So I've come to design my game which players will be having a unique set of skill or ability to come with. I can store skill name, mana cost, cooldown, etc in database which each skill have in common, but as we gamer know, a skill is unique not just by its attributes, like the sequence of movement, the object will be instantiate in the world, it's just that very unique.

So the question is, where do I put this "unique", the skill sequences? Do I make skill1.cs, skill2.sc for every single skill? xml for sequence then make script to read and define myXml?

For example, in a game, the effect of each card is very unique for example card1 allow player to deal damage and draw card, card2 just deal damage, card3 deal damage to enemy and then draw a card, and so-on, where and how they store this sequences or method of each card effect?


texts: Efficient way to output/display debugging data in a window

texts:
I'm writing a program in Visual Studio, C++ with OpenGL and for the first time, I think it will be beneficial to see some live data on top of my display/render window.

To give some scope, I'm developing a 3D world with a ball bouncing and it would be nice to see things like the current velocity and y-positions of various objects, amongst other things.

What method is a nice/effective way to display this type of information to a window?
Is there any libraries, vs settings or third-party implementations that can be useful? (please excuse my naivety, I'm used to just cout << some info, on a console).


texts: Unity 5 Distributed Physics in Client Server Model

texts:
I have a server which controls a physics object via buttons, adding force whenever I click them. I want to be able to have a client connect and whenever the physics object has a reaction on the server, the same reaction occurs on the client. But I don't want the client to do any physics calculations. I tried this out as seen below. When a button on the server is hit and the object moves, an RPC is sent to the client with the position, rotation and velocity of the server physics object and then applied to the object on the client.

[ClientRpc]
void RpcSendPhysicsInfo(Vector2 Pos, float Rot, Vector2 Velo)
{
    Debug.Log ("Received");
    moveableBarrel.GetComponent<Rigidbody2D> ().position = Pos;
    moveableBarrel.GetComponent<Rigidbody2D> ().rotation = Rot;
    moveableBarrel.GetComponent<Rigidbody2D> ().velocity = Velo;
}

void OnGUI()
{

    if (isServer)
    {

        if (GUI.Button (new Rect(0,Screen.height/3, 150, 30),"Move Barrel Right"))
        {
            moveableBarrel.GetComponent<Rigidbody2D>().AddForce(new Vector2(50, 0));
            //RpcSendPhysicsInfo(physics info)
            RpcSendPhysicsInfo(moveableBarrel.GetComponent<Rigidbody2D>().position, moveableBarrel.GetComponent<Rigidbody2D>().rotation,
                               moveableBarrel.GetComponent<Rigidbody2D>().velocity);
        }

With this code, whenever the server side button is hit nothing happens on the client side. But when it is hit again the client object moves to the position of the server object, but the speed the object is moving isn't the same as the server object. Obviously this didn't give the reaction that I wanted which was to have the client object copy the server object and in the long run make it seem as though the client carried out the physics when actually it was the server. Is there more data to send? Have I sent the wrong data? Have I went about it all wrong?


texts: Abstraction for player, NPC's, and monsters

texts: I am trying to come up with a good abstract term for my players, NPC's and monsters. They can all have stats and inventory. so they all can function in the same way. But some could be humanoids, some are monsters and whatnot. Are there any standard abstract terms that game devs tend to use.


texts: I would like to make nice games with good architecture that are easy to support and extend. But when i write code it all gets messy and hardcoded, so when I want to add a feature it becomes a huge pain. Is there any book that teaches me how to design my game upfront, so I will know what classes I will want, how to do certain features etc.


texts: How to handle component-based objects in a game loop?

texts:
I've been writing my own game engine and I was wondering the correct way to handle my game objects. Each game object is different. The only thing they have in common is a set of operations to handle their components. With that said, each game object will have different components that do different things. Ex: game object 1 has input, physics and display components; object2 has only a display component.
I was wondering if it was best to

Loop around the list of objects and call an "update" on each of them and then run each "update" for each component the object holds; or
Have a list of components in my game loop and check for each component if they have the current component. If so run it, otherwise move on...

I see benefits and harm to both strategies.

Benefit of 1 is that there isn't a lot of overhead, but things might
get out of sync;
Strategy two is basically the opposite of 1...

For sake of simplicity I'm not putting how I'll handle the gameloop tick and I'm using a generic language.

Example of code for 1:

gameLoop() {
  forloop on each game object as obj {
    obj->update()
  }
}

//obj
update() {
  foreach component as component {
    component->update()
  }
}

Example of code for 2:

gameLoop() {
  input = &event
  forloop on each game object as obj {
    if (obj->canHandleInput())
       obj->handleInput(&event)
  }
  forloop on each game object as obj {
    if (obj->hasPhysics())
       obj->updatePhysics()
  }
  forloop on each game object as obj {
    if (obj->canDraw())
       obj->Draw()
  }
  //audio...
  //other components
}

What is the currently the most accepted way to handle objects in a game loop?


texts:
We have an online game where players sometimes have to wait a while (say 30 minutes) before a process they intiated completes. This encourages them to come back later. An example of this is growing crops in Farmville or basically any action in the Sims Play4Free.

Now, however, there is the idea to let these processes expire, so if the player doesn't 'reap' them in time (e.g. within 4 hours) they are aborted. I'm a bit sceptical about this. How will this make players come back more often? Is not the reward of reaping the process enough for that? Can we expect players to fit their daily schedule around our game, maybe even set the alarm clock at night? Won't this just cause players to give up on starting these processes in the first place?

I realise this may be too subjective for this site, so I'll end with a concrete question: Do (m)any other online free-to-play games employ this technique?


texts: Is Godot's NavMesh viable for dynamic pathfinding (e.g. avoiding moving enemies)?

texts:
I am a novice (read: low-budget) designer looking at moving from Pygame to a real engine, and between Unity and Godot it looks like the latter has a much better 2D engine [1, 2, 3]. I would be happy to support Godot's open-source model except that, as far as I can tell, its built-in navigation mesh is purely static--i.e. it can't update its path to account for dynamic obstacles [4, 5]--while Unity's pathfinding system can [6].

So my question is: Am I "stuck" with Unity? Or is there functionality that I haven't yet been able to find? Or, alternatively, is GDScript significantly faster than Python such that basic algorithms like fixed-grid A* would do the job?

Edit: By "stuck" with Unity I don't mean that it's a bad option or that there aren't good options; I mean, 'if I need good pathfinding, do I have to give up on Godot and use what would otherwise be a second-choice engine?'


texts: Does HLSL implement Shader Model LOD instruction?

texts:
The DX Shader Model 5.0 has a lod instruction. It returns "the LOD (level of detail) that would be used for texture filtering".

Does HLSL have a built-in intrinsic that can do the same? I know I could evaluate the LOD manually, but I'm wondering if there's a better way.


texts: Do I need a Point and a Vector object? Or just using a Vector object to represent a Point is ok?

texts:
Structuring the components of an engine that I am developing along with a friend (learning purposes), I came to this doubt.

Initially we had a Point constructor, like the following:

var Point = function( x, y ) {
    this.x = x;
    this.y = y;
};

But them we started to add some Vector math to it, and them decided to rename it to Vector2d.

But now, some methods are a bit confusing (at least in my opinion), such as the following, which is used to make a line:

//before the renaming of Point to Vector2, the parameters were startingPoint and endingPoint
Geometry.Line = function( startingVector, endingVector ) {
    //...
};

I should make a specific constructor for the Point object, or there are no problems in defining a point as a vector?

I know a vector have magnitude and direction, but I see so many people using a vector to just represent the position of an object.


texts: Control the movement space for an object?

texts:
I want my object not cross the limit of "AiX\AiZ" values. When object cross this limit it faces like walls that block him but not stop him from movement.
public GameObject Player, middleObject;
public float high, upForce, speed;
public float PlayerDistance, AiX, AiZ, PlayerNum;
public Vector3 PlayerPlace,PrediactPlace;

void Update()
{

    Quaternion currentRotation = transform.rotation;
    Quaternion wantedRotation = Quaternion.Euler(0, 90, 0);
    transform.rotation = Quaternion.Lerp(currentRotation, wantedRotation, Time.deltaTime * 10);

    AiX = gameObject.transform.position.x - middleObject.transform.position.x;
    AiZ = gameObject.transform.position.z - middleObject.transform.position.z;

    if (PlayerNum == 0) // control it from inspector
    {
        Player = null;
    }
    else
    {

        Player = GameObject.FindGameObjectWithTag("GPlayer");
        PlayerDistance = Vector3.Distance(gameObject.transform.position, Player.transform.position);
        PrediactPlace = Player.GetComponent<PlayerCtrl>().Point.position;

        if (AiX <= 2 && AiZ >= -2 && AiZ <= 7 && AiZ >= -7)
        {
            transform.position = Vector3.Lerp(transform.position, PrediactPlace, Time.deltaTime * speed);
        }

    }

}


texts: Easy to use cross-platform 3D engines for C++ game development?

texts: I want to try my hand at writing a 3D game. However I don't want to start at such a low level of drawing individual triangles and writing my own 3D object loader and so on. I've heard of things like Irrlicht, Crystal Space 3D, and Cafu, but I don't have any experience with any of them. I'm looking for suggestions from people who have experience with these or other engines on which ones are well written, and are easy to get started using, without having to learn a ton of 3D math theory and how GPUs work internally.


texts: Deleting fewest Navmesh Obstacles when no valid path is found

texts:
So I'm building a Tower Defence, with mazing (i.e. the player can place towers to make the mobs take a longer route to there destination.)

I'm using Unity's Navmesh system. Each Enemy unit has a Navmesh Agent component. And each Tower has a Navmesh Obstacle component.

The Path-finding is working Perfectly. However (as expected) when the play completely blocks off all routes to the Agent's Destination, the agent simply moves to the spot closest to the destination that it can get to and sits there.

What i need, is to detect when that happens... Some kindof NoValidRoute() or something, I haven't been able to dig anything up in the Unity documentation or from google Searches.

Once i have that, I need to determin which Navmesh Obstacles need to be destroyed to open the shortest route possible with the fewest number of Obstacles destroyed. (i.e. if a path can be opened with only 1 tower destroyed which tower would give me the shortest route.)

I'm finding a serious lack of any information on this subject.. as far as i can tell no one has even tried to do this, or asked for help doing something like this. (at least not with Unity's Nevmesh.) I think A* is a little(and by little i Mean LOTS) outside of my skill to implement at present.

Thanks In advance


texts: Copyright laws on famous buildings and monuments in games?

texts:
I am working on a commercial card game based on the middle east. We would like to have famous buildings and monuments in the game, such as the Burj Al-Arab in Dubai.

Are there laws that would prevent us from using pictures or drawings of famous buildings in commercial games?


texts: Box2d too much for Circle/Circle collision detection?

texts:
I'm using cocos2d to program a game and am using box2d for collision detection. Everything in my game is a circle and for some reason I'm having a problem with some times things are not being detected as a collision when they should be.

I'm thinking of rolling up my own collision detection since I don't think it would be too hard.

Questions are:

Would this approach work for collision detection between circles?
      a. get radius of circle A and circle B.
      b. get distance of the center of circle A and circle B
      c. if the distance is greater than or equal to the sum of circle A radius and circle B radius then we have a hit
Should box2d be used for such simple collision detection? There are no physics in this game.


texts:
I'm currently trying to implement my own OBJ Loader for use with FreeGLUT with C++. This is my current OBJ Loader:
    #include "OBJLoader.h"
    #include
    #include
    #include
    #include
    #include

Mesh* OBJLoader::LoadModel(char* path)
{
Mesh* mesh = new Mesh(); //New Mesh

std::vector<Vertex> vertices;
std::vector<TexCoord> textureCoords;
std::vector<Vector3> normals;

//Loads OBJ file from path
std::ifstream file;
file.open(path);
if (!file.good())
{
    std::cout << "Can't open texture file " << path << std::endl;
    return nullptr;
}

std::string text;
while (!file.eof())
{
    file >> text;
    if (text == "v")
    {
        Vertex vertex;

        file >> vertex.X;
        file >> vertex.Y;
        file >> vertex.Z;

        vertices.push_back(vertex);
    }

    if (text == "vt")
    {
        TexCoord texCoord;

        file >> texCoord.U;
        file >> texCoord.V;
        textureCoords.push_back(texCoord);
    }
}

file.close();

mesh->vertexCount = vertices.size();
mesh->vertices = new Vertex[mesh->vertexCount];
for (int i = 0; i < mesh->vertexCount; i++)
{
    mesh->vertices[i].X = vertices[i].X;
    mesh->vertices[i].Y = vertices[i].Y;
    mesh->vertices[i].Z = vertices[i].Z;
}

mesh->texCoordCount = textureCoords.size();
mesh->texCoords = new TexCoord[mesh->texCoordCount];
for (int i = 0; i < mesh->texCoordCount; i++)
{
    mesh->texCoords[i].U = textureCoords[i].U;
    mesh->texCoords[i].V = textureCoords[i].V;
}

return mesh;
}

What I do is create 3 vectors to hold the vertices, texture coords and normals, I then put the data in the corresponding vectors from the OBJ file and then finally loop through these vectors to add them to basically 3 array's which will contain the vertices, texture coordinates and normals so I can use them with "glVertexPointer" and "glTexCoordPointer" (I haven't loaded in normals yet but I will eventually)

The problem is that I'm not sure why my model is displaying really strange. It seems like it should work but the model I'm rendering which is meant to be sonic looks like... this:

Is there something I've done wrong? I imagine it's to do with the faces at the bottom of the OBJ File though I just want to make sure.

EDIT
This is the section of code I'm using to put the values from the vectors into the array's used in glVertexPointer and glTexCoordPointer:

mesh->vertexCount = vertices.size();
mesh->vertices = new Vertex[mesh->vertexCount];
for (int i = 0; i < mesh->vertexCount; i++)
{
    mesh->vertices[i].X = vertices[i].X;
    mesh->vertices[i].Y = vertices[i].Y;
    mesh->vertices[i].Z = vertices[i].Z;
}

mesh->texCoordCount = textureCoords.size();
mesh->texCoords = new TexCoord[mesh->texCoordCount];
for (int i = 0; i < mesh->texCoordCount; i++)
{
    mesh->texCoords[i].U = textureCoords[i].U;
    mesh->texCoords[i].V = textureCoords[i].V;
}