texts: Android game loop's effect on cpu/battery usage - unexpected results

texts:
I will try to keep this question as concise and as readable as I can.

I recently came across an odd problem with my Android game that I'm developing.

It's an openGL ES 2.0 game and initially I was using RENDERMODE_CONTINUOUSLY, my gameloop was running on the OpenGL provided rendering thread and I was basically limiting the logic updates (to say, 30 times per second), while letting the rendering run as fast as the device could handle.

Please note that I'm not using thread.sleep() and do not want to as I've read various articles advising against it

Everything works well, but when I ran the game on an old Galaxy Ace phone it was rendering at 85+ Frames Per Second which got me thinking that it could be using more battery than it needed to (because it was rendering frames which didn't need to be rendered as there were no logic updates in-between them).

So what I did was this:

I set RENDERMODE_WHEN_DIRTY, started another thread myself, put my game loop into that thread and from this loop, called update() (For logic updates) and requestRender() (for drawing). I altered the gameloop so that it would only render when there was an update.

Now, the way it stands, If I limit my loop to say, 30 ticks per seconds, then all is good, both rendering and logic run at a smooth 30 tics per seconds.  If things get too much and the device can't handle the rendering, and the frame rate drops (lets say, to 12FPS), then the logic will carry on at 30 times per second which is exactly what I'm after.

Howevever, I've used the CPU Meter in Jellybean and it would appear that the first option (2 threads, rendering flat out) is more CPU (and therefore, I assume battery) efficient that the 2nd method (3 threads, but with rendering limited).

I'm trying to figure out why this would be?

Please note that I can't test the CPU usage on the Galaxy Ace phone as it doesn't run jelly bean, but certainly on my Nexus 10 tablet, the CPU usage is more when using the 3 threaded approach.

I understand that now, my loop still 'loops', even when it has no updates or rendering to do (never sleeping), but this was the case in the first loop too (well, when it had no updates, it would carry on rendering regardless).

So what gives here?

Note: I haven't posted code as it's not really relevant to the question. But if you want to see the loop, please ask and I will post - thanks

With OpenGL, am I best to just leave the device to render as fast as it can?  That certainly seems to be the way it's been set up (at least when using RENDERMODE_CONTINUOUSLY)


texts: Where to cast light/shadows in a 2.5D view?

texts:
I'm working on a tile-based 2D pseudo top-down/side-on game very much in the graphical style of Prison Archiect. More specifically, I'm referencing their style of drawing wall tiles where you can see the south, east and west sides of the wall at once. Here's an example from my engine:

I'm also working on a pixel-based (i.e. not tile-based) lighting and shadows implementation. I'm currently struggling with trying to decide how/where to project from a light source on intersections with these wall tiles.

I can't decide where on these tiles should occlude light cast out by light sources. If the red highlighted areas are the "top" of the wall, and the blue highlighted areas are the "side" of the wall, I believe I have two options:

A) Only occlude light from the "top" of the wall

It's worth mentioning that I also plan to use UV-mapping so that only the walls facing the light source will be illuminated, rather than the pre-shaded tiles I'm using as an example. However, that would mean that the tiles adjacent to a wall in shadow may be lit and I don't think this would look quite right. Alternatively...

B) Occlude light from the entirety of the wall tile

This seems more realistic for the ground tiles but does not let me easily illuminate the wall "sides".

I'm not really happy with either solution so my question is: is there another alternative which will give more realistic shadow-casting in a 2.5D view? I'd also rather keep the sides of the walls visible rather than use a top-down only perspective as I feel this would force the rest of the art into a top-down perspective, rather than pseudo side-on.


texts: Unity's StartCoroutine funtionality inside a .NET Library and outside a MonoBehaviour

texts:
This code is used in a MonoBehaviour script in my current code:

    // a simple WWW post
    WWW www = new WWW(this.Url, bytes);
    StartCoroutine(WaitForRequest(www));
}

// simple handler for the WWW error/return data.
private IEnumerator WaitForRequest(WWW www)

The problem is that I want to move this into a dll, that will be used by other dlls, not just monobehaviours, which as far as I can tell, means that StartCoroutine will no longer be available.

In .NET, Async and Await sounds similar, but I don't know how to use them.  Is there a way to duplicate the Coroutine functionality?  I do have access to UnityEngine.dll.

(If it is possible to use Coroutine without inheriting MonoBehaviour, that can work as well)

Thanks.


texts: Zobrist Hashing equivalent for Simple Knights Game with only 1 unique piece

texts:
I looked over the Zobrist hashing function used for getting a unique hash id of the board state in a chess game. https://en.wikipedia.org/wiki/Zobrist_hashing

Martin Fierz explains it very well in his post:

  Assume you have a board with S squares and P different types of
  pieces. You allocate an array:

int zobristnumbers[S][2*P];

  and fill it with random numbers. The hash number is now calculated as
  an XOR over the occupied squares of the entire board:

key = 0;
for(i=0; i<S; i++) {    if(board[i] != EMPTY)
  key ^= zobristnumbers[i][piece[i]];
}

Now this works very well for chess because you have 6 unique pieces and 64 squares - so the probability of getting a clash in the keys is very small.

I am trying to find a variant of this hashing function or another one, which would work smoothly in a more simple zero-sum game called Knights: 49 squares, and only one kind of piece - a knight from chess - which moves exactly like a knight in chess.

I want to use it as a transposition table key, for storing best moves and game states.

Any ideas or hints of how could this be achieved?

Thanks!


texts:
I'm making a game which the user can use the arrow keys to scroll left and right to view the map.  I had an issue with the health bars of my enemies being drawn way off even though I set them to be drawn at the x and y position of the enemy.

I tried to debug using the following line to draw something at mouse_x and mouse_y:

draw_text(mouse_x, mouse_y, "X");

The X on screen would be at the correct position (the mouse position) when the mouse was at 0, 0, BUT as the mouse was moved farther right or down, the respective x or y offset became bigger and bigger, almost like I said to draw the X at mouse_x * 1.5, mouse_y * 1.5.

I'm using a view (view[0]) to allow the user to scroll through the map, and I thought this might be the source of the issue.  This is the code I used to allow the user to scroll left and right:

if (view_xview[0] < room_width - view_wview[0]){
    view_xview += clamp(room_width - view_xview[0], 0, 10);
}else{
    view_xview[0] = room_width - view_wview[0];
}

The same code was used for moving left, but reversed.


texts: How would I create a shadowy "Fog of War" effect in Game Maker Studio 2?

texts:
You know if you ever played "StarCraft," as you explore the map it's dark until you go to that area. I am trying to replicate this effect in Gamemaker studio 2.

I want to create a shadowed area effect on the map, so that when a "obj_player" moves to a darkened area it reveals that part of the map.

Here is a picture to help describe the effect i'm trying to achieve:


texts: How to get the previous value from string array c#(Unity)

texts:
I have this example data

Data: P  ,B  ,B  ,T  ,P

This must be something like this

But what is happening to me is this

here's my code
string[,] table = new string[104, 6];
string newPreviousValue = "placeholder";
int xIndex = -1;
int yIndex = 0;
if (result.Equals(newPreviousValue) &&  yIndex < table.GetLength(1) - 1)
{
    yIndex += 1;
    table[xIndex, yIndex] = result;
}

else
{
     xIndex += 1;
     yIndex = 0;
     table[xIndex, yIndex] = result;
}

So you won't get confuse the result variable is the data generator.
What could be missing on my condition?
I tried doing something like this
if (result.Equals(newPreviousValue) && result.Equals(newPreviousValueTie) &&  yIndex < table.GetLength(1) - 1) but what's happening here is they're all in y axis falling in line .


texts: Online MMO collision detection for players & walls

texts:
Let's assume the following:

I have a server which stores the player's position (float x, float y, float z)
Client sends the server it's updated position ever 250ms or so.
Server has bounding boxes for all buildings & players ( Let's say each wall has it's own AABB or OBB)
For broad-phase collision detection, I use spatial hashing based on the bounding boxes.
Client does full-on triangle level collisions locally.

My question:
- How can I quick calculate if a player has passed through a wall on the server only using AABBs or OBBs. Or, is there no way to do that without going to triangle-level collision detection. Maybe some other data structure? Any help would be appreciated.


texts: Get normal dependent on collisions position

texts:
As I hask ask here I'm working on how my objects can move over the terrain and other objects. My proposal and also an idea in the answers was to calculate the rotation from the object with the normals from other objects around (under and in front) the moving object.

My main problem for that is how I can get the normal from an object at a special position. Let's take the ramp on the road from the old example. It depends from which side my car comes. If it comes from front it can drive along the ramp but if it comes from back it moves against the wall. Of course there are other normals if I come from the other side. All my objects have these variables:

float vertices[];
float normals[];
short drawOrder[];

float[] modelMatrix;
AABBox boundingBox;

So you see I can allways get the vertices, normals and the position. I can also test if the object collides with another object with the bounding box (axis aligned) but I have no idea how I can get the normal where the collision happens but that is the important thing for the rotation of the car. Do you have any ideas or are there usual way how to do this?


texts: What is the best way of storing transformations for an object and then applying them with OpenGL?

texts:
First some background info...

I have been working on a platformer game, which I draw with OpenGL. The platforms are cubes and the player is a cube.

The platforms and the player (both cubes) are given a position, from which the vertices should be drawn. However, the first cube is at position [0, 0, 0] and I would like the player to be on top of this cube. The size of the cubes and player is [0.5, 0.5, 0.5] initially.

However, I didn't manage to get the player on [0, 1, 0] (cubes are drawn from their center point I remembered), because the scaling didn't seem to work, which led me to believe the method I'm using to store the translations and scaling is inherently bad.

I am currently storing the translations and scaling in a matrix, which is part of the object. The object also holds the vertices and the VBO. Let's call it class Cube, which thus holds glm::mat4 m_transform.

I expose m_transform and pass it with glUniformMatrix4fv(shader.GetUniformLocation("model"), 1, GL_FALSE, glm::value_ptr(m_transform));

And at some point I call glDrawArrays(GL_TRIANGLES, 0, 36); to draw the platform/player cube.

So to alter the position of such a cube, I would alter m_transform. Such as: m_transform = glm::translate(m_transform, vec); where glm::vec3 vec is the desired translation to apply.

However, the issues arise when u wish to scale a cube as well, so if we scale with vec3(0, 2, 0), the translations will be twice as large. And I'm unsure where to go from here.

I've read that having different matrices for translation, rotation and scaling is the way to go, which I will try, however, I would like to know what the best practices are surrounding this subject.

Any suggestions are much appreciated!


texts: How to create a Raining Effect(Particles) on Android?

texts:
I am developing a 2d android strategy game, it runs on SurfaceView, so I can't(or can I?) use LibGdx's particle system. And I would like to make a raining effect, I am aiming for something like this( http://ridingwiththeriver.files.wordpress.com/2010/09/rain-fall-animation.gif ), I don't need the splash effect in the end (although that would be superb, but probably would take up a lot of system resources).
How could I achieve that raining effect? Any ideas?

Thank You a lot in advance!


texts:
I have done multi-pass rendering, before, and understand how it works. I made a simple example, which rendered a basic scene with shadows. This was all part of one file. Now, I am trying to figure out is how to put it into my game engine.

Currently, my game engine uses a single pass. It is in a hierarchical structure, and uses Direct3D 9. I have a graphics component, which will load and draw a 3D model. In my game loop, I update all of the entities in the world, then I call the draw function for each one. This draw function gets the vertex buffer, index buffer and texture or material, and draws the 3D model using a shader. This works fine.

To do multi-pass rendering, to allow for shadows, I will need to draw each model multiple times. It doesn't seem right, to me, that in each models draw function I should put the second pass code; this will then be completed before the next models first pass.

How should I implement multi-pass rendering in a game engine?


texts:
I wanna stop immediately (not instantly) when I release a key so it would not slide. I don't wanna use rb.isKinematic = false; because it's just stopping so instant. So like I thought about:
x = GetAxisRaw("Horizontal");
z = GetAxisRaw("Vertical");

move = transform.right * x + transform.forward * z;

if (no inputs pressed)
{
   rb.AddForce(force * -maxSpeed); // maybe force will be the current velocity
}

I tried this but seems like nothing is hapenning. And so I think I need some improvements


texts: How do I stop my game from Skipping Screens?

texts:
I used the code from this - http://www.xnadevelopment.com/tutorials/thestateofthings/thestateofthings.shtml (The second method using enumerations)

I modified it to add a 3rd screen for gameplay and it functioned like the previous screen. The issue is that since the Controller Detect Screen and Title Screen both use the A button to advance. Because of this, it advances through both at the same time, going straight to the gameplay screen. I changed the code (as seen below) so that the Title Screen uses a different button. However, I want to have it so it uses the same button, but not advance at the same time.

Hopefully I explained it correctly.

        private void UpdateControllerDetectScreen()
    {

        //Poll all the gamepads (and the keyboard) to check to see

        //which controller will be the player one controller

        for (int aPlayer = 0; aPlayer < 4; aPlayer++)
        {

            if (GamePad.GetState((PlayerIndex)aPlayer).Buttons.A == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.A) == true)
            {

                mPlayerOne = (PlayerIndex)aPlayer;

                mCurrentScreen = ScreenState.Title;

                return;

            }

        }

    }

    private void UpdateTitleScreen()
    {

        //Move back to the Controller detect screen if the player moves

        //back (using B) from the Title screen (this is typical game behavior

        //and is used to switch to a new player one controller)

        if (GamePad.GetState(mPlayerOne).Buttons.B == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.B) == true)
        {

            mCurrentScreen = ScreenState.ControllerDetect;

            return;

        }

        if (GamePad.GetState((PlayerIndex)mPlayerOne).Buttons.A == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.C) == true)
        {

            mCurrentScreen = ScreenState.GamePlay;

            return;

        }

    }

    private void UpdateGamePlayScreen()
    {

        //Move back to the Controller detect screen if the player moves

        //back (using B) from the Title screen (this is typical game behavior

        //and is used to switch to a new player one controller)

        if (GamePad.GetState(mPlayerOne).Buttons.B == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.B) == true)
        {

            mCurrentScreen = ScreenState.Title;

            return;

        }

    }


texts: How to programmatically overlay a shader on a terrain by mask (Unity)?

texts:
I can paint the terrain with textures.I would like to see water drawn with a shader, and not a stationary water texture on the terrain. Moreover, it was possible to assign a shader to the terrain, but the problem is that in this case the shader is superimposed on the entire terrain tile.
How to write a code that would apply a shader to a terrain using a mask?


texts: Colors for villains, good guys and neutrals

texts:
I am looking for 4-6 color schemes for three factions, good, evil and neutral (in a space strategy if that matters). I'd like the player to choose which side they want to play and each side will have an optional ally. Each team can have one or two colors (major/minor), if that makes the problem easier.

EDIT: I know that color perception can be subjective, context sensitive and influenced by culture. I am looking for a scheme that majority of players would see as a traditional fight between Good and Evil (Blue and Red comes to mind when having only two colours, two factions).

Based on this article about movie faction colour I'd pick:

Good: Blue (player) + Gold (ally)
Neutral: White (player) + Grey (ally)
Evil: Red (player) + Black (ally)

But something doesn't feel right about the scheme. Maybe it's the absence of color and using three shades of gray. Also it will be impossible to create gray and black "lights", "aura" and similar effects.


texts:
I'm making a game and I want to play sounds in it.
I have AssetManager which loads the sounds and I made a class which has playSound(String sound) method. This method calls the get() method of the assets manager with the string, creates Sound type file and calls it's play() method.
The code:

public void playSound(String sound) {
    Sound file = gameRenderer.assetsManager.get("sfx/sounds/" + sound + ".wav");
    file.play();
}

It works fine.
But then I noticed there is a log that occurs every time the sound is played:

AUDIO_OUTPUT_FLAG_FAST denied by client

I also noticed a small "tick" sound in the end of the sound every time it's played in the game.
I read about it and from what I've learned it has something to so with sample rate. I tried many types of sounds (44KHz, 48KHz, and lower values too) but it doesn't stop printing that log.
I couldn't find a solution anywhere.

If it really has something to do with sample rate, does it mean I need to have different types of file of the same sound (With every sample rate)?
If it does, my game would be heavy...
I'm using Nexus 5.
Thanks!


texts: Linear gradient shader ( Photoshop-like)

texts:
I'm searching a way to implement a linear gradient shader that behaves as the linear gradient in Photoshop (only the vertical case is necessary). It will be applied to 2D sprites.

Currently I'm passing to the pixel shader these parameters:

StartColor.
EndColor.
Offset: an offset applied to the gradient starting point.
Length: the gradient length (the range inside where the colors will be
interpolated).
isFixed: a boolean parameter that indicates if the
gradient must be influenced by the camera position or not.

Here a first attempt of the vertex shader and the pixel shader that I've implemented:

struct VsInput
{
    float3 position : VES_POSITION;
    float2 uv       : VES_TEXCOORD0;
    float4 color    : VES_COLOR;
};

struct VsOutput
{
    float4 position : HPOS;
    float2 uv       : TEXCOORD0;
    float4 color    : COLOR0;
    float4 outPos   : TEXCOORD1;
};

VsOutput main(VsInput input)
{
    VsOutput vsOutput;
    vsOutput.position = MUL(float4(input.position, 1.0f), WorldViewProjection);
    vsOutput.uv = input.uv;
    vsOutput.color = input.color;
    vsOutput.outPos = vsOutput.position;

    return vsOutput;
}
struct PsInput
{
    float4 Position : HPOS;
    float2 UV       : TEXCOORD0;
    float4 Color    : COLOR0;
    float4 outPos   : TEXCOORD1;
};

float4 startColor;
float4 endColor;
float offset;
float len;
bool isFixed;

float4 main(PsInput psInput) : COLOR
{
    psInput.outPos = psInput.outPos / psInput.outPos.w;
    float yScreenSize = 900.0f;
    float yPixelCoordinate = 0.0f;
    if (isFixed)
    {
        yPixelCoordinate = 0.5f * (1.0f - psInput.UV.y) * yScreenSize;
    }
    else
    {
        yPixelCoordinate = 0.5f * (psInput.outPos.y + 1.0f) * yScreenSize;
    }

    float gradient = (yPixelCoordinate + offset) / len;
    gradient = clamp(gradient, 0.0f, 1.0f);
    return lerp(startColor, endColor, gradient);
}

When isFixed is false I want the gradient influenced by the camera position. But my shader is wrong, since the starting point of the gradient is the bottom of the window instead of the bottom of the sprite.
The question is: how can I modify the shader in order to have the gradient starting from the bottom of the sprite? Maybe I need the size of the sprite in pixel? Or there are other convenient ways?

The other question regards the "fixed gradient": if I want the gradient not influenced by the camera position, what is the convenient way? It's possible to have these two behaviors in the same shader?

Thanks.

Edit: more details based on DMGregory suggestion.

Maybe the sentence gradient influenced by the camera, it is not correct. I'll try to be more clear with a few images (taken using the shaders above).

In the first image you can see a base sprite (in black) with an orange gradient applied to it. On top of the base you can see the player sprite; the camera is attached to this one.

In the second image the player has jumped and the camera follows him: the isFixed attribute is false and, as you can see, the gradiend moves with the player and the camera.

The third image shows the same situation of the second image, but the isFixed attribute is true and, as you can see, the gradient don't moves with the player and the camera.

I hope it's a bit more clear what I'm looking for.


texts: Unity Screen.height / Screen.dpi is *not* equal to the screens height in real life

texts:
On mobile, I was planning on using Screen.dpi to work out the physical size of the screen and size controls accordingly.

But this quick test on my Galaxy S5 proves that the numbers from Unity are wrong.

1080 / 480 = 2.25 But the screen in real life is over 2.5 inches high.. So this is way off.

Any suggestions..? Right now I think I'll just leave this, and have the controls the same size in world space.. rather than risk making them worse.


texts: Which language and tools should I choose for creating 2D games?

texts:
Recently I have returned to my childhood hobby (programming games) and found it quite enjoyable. I've been tinkering with PyGame (for Python) for a few months, made a couple of projects for educational purposes. PyGame is nice, however there is not an awful lot of commercial games using PyGame, and I'd like to invest my time in the best way and ideally to make an extra buck in the future.

What I like:

doing things alone. I do not dream about working at huge corporation and making one tiny bit of World of Duty-7
frameworks like LÖVE (for Lua) or PyGame. I doubt I am able to figure out
how to draw those fancy pixels without it
cross-platform things.
free stuff.

What I don't like:

C++ scares me, however feel free to tell me how stupid I am
IDEs like GameMaker, RPGmaker etc. I like making my own tools.

My goal is to make 2D games like Terraria, Super Meat Boy, DefCon, etc. Which language and tools should I choose to accomplish my goal?


texts: Transform luminosity (Watt) to be usable in shader

texts:
I'm studying the color and the Luminosity of Stars.
I'm trying to figure how to transform information of Luminosity i perceive at a given distance to something usable into a shader.
For instance , Given the Radius and temperature of a star, with inversed square law on Distance(meters) i obtain the perceived luminosity of a star in Watt (brut force, without any scattering).
For sample, the luminosity I obtain for the Sun ON Earth is about 1361W and a RGB color about

w=1361
r=255 g=245 b=242

Astronomical and physics are quite OK, but how to transform this values into usable shader formulas or values? best practices ? samples ?

I guess i will simply take the aboves value as Light reference an normalize the intensity(1361) to be 1 on each rgb componemt value. I' ll keep you posted.


texts:
I am trying to determine the gun elevation angle of a gun that fires ballistic projectiles.

For a target at a certain distance D, I will have to compute an angle that increases with D.

This relation ship is non-linear, by the way, because the projectile loses velocity as it travels, for starters, due to drag.

In the past, I have done this with a lookup table.... for a whole bunch of test firings, see where the projectile hits the ground.

But this only works if there is no delta in the elevation between gun and target.

A target that is on a hill top, will need adjustment for extra range. Whereas a target in a valley below, would mean a lower gun elevation.

This means that the table-lookup will break down, and a 2D table seems like a kludge.

What would be an effective way to compute this targeting? I know things also depend on nozzle-velocity and air-drag, but these will not vary (but drag will be non-zero.) Neither will I be modeling the wind.

Additional information:

This is for AI assisted targeting. NPC or player targets a point in the world. The algorithm will find the corresponding angle to hit the target.

Currently, I am using Bullet Physics, with a discretely stepped world.


texts: Working with Screen Space - Overlay canvases

texts:
So, say you've started a new project. You drop your in desired sprite. You can see how big it is relative to the Main Camera. That's cool.
Now you want to add a persistent bit of UI to the game, so you use a canvas in the "Overlay" mode. That canvas is added in but is hundreds of times bigger than your Main Camera view.
My question is, are you all just cool with that? Or is there something I should do? It's a bit odd that there's some massive UI taking up so much space in my Scene view. If I want to add something to it, I have to zoom out for a while before it fits in my view.
I'm new to Unity development, so it's possible that's just how things are. But I was wondering if I'm misunderstanding something.


texts: What are the benefits of designing a KeyBinding relay?

texts:
The input system of Quake3 is handled using a Keybinding relay, whereby each keypress is matched against a 'binding' which is then passed to the CLI along with a time stamp of when the keypress (or release) occurred.

I just wanted to get an idea from developers what they considered to be the key benefits of designing your input system around this approach?
One thing i don't particularly like is the appending of the timestamp to the bound command. This seems like a bit of a hack to bend the CLI into handling the games input?
Also I feel that detecting the keypress only to add the command to a stream of text that gets parsed at a later date to be a slightly latent way of responding to input? (or is this unfounded?)

The only real benefit i can see is that it allows you to bind 'complex' commands to keypresses; like 'switch weapon;+fire;' for example. Or maybe for journaling purposes?

Thanks for any insights!


texts: Google play services error DEBUG: Application is pausing, which disconnects the RTMP client

texts:
I am having this issue from past day with Google Play Services & Unity.

What happens is, when I install app directly ot device via Unity, the Google Play Services work fine but when I upload it as beta to play store console and install it via that then it starts to give " DEBUG: Application is pausing, which disconnects the RTMP client" error.

I have a proper SHA1 key.


texts: Is there a way to start with OpenGL 3.0+ without need to write my own shaders?

texts:
I'm starting with OpenGL and found out that after OpenGL 3.x you must write your own shaders (think it's obligatory). Am I right here?

I have made some research but I can't seem to find the answer.
If it's necessary to write the shaders for OpenGL 3 the I still can use 2.x right? Just because I'm just starting and OpenGL seems a little bit more level than I'm accustomed to. So I think I'll have a really hard time writing a shader myself.

P.S. My GPU only supports up to OpenGL 3.0. I think it's because of the drivers, I'm running a Linux distro that only has FLOSS (no proprietary software).


texts: Unity3d web player fails to load textures

texts:
I'm having a problem with Unity3d Web Player. I have developed a project and succesfully deployed it in a web app. It works with absolutely no problem on my PC.

This app is to be installed on two identical machines. I have installed them in both and it only works properly in one. The issue I have is on a computer it fails to properly load the models and textures, so the game runs but instead of the models I can only see black rectangles on a blue background. It has the same problem with all browsers and I get no errors either by the player or by JavaScript.

The only difference between these computers is that one that has the problem is running on Windows 8.1 and the other one on Windows 8 only. Could this be the cause of the issue?

It works fine on my computer with Windows 8.1. However both of the other computers have specs that are significantly lower than mine.

I have already searched everywhere and it seems that it has to do with the individual games, however I think it may have to do with the computer itself because it runs properly in the other two.

The specs on the computes I'm installing the app on are as follows: Intel Celeron 1.40 GHz, 2GB RAM, Intel HD Graphics

If anybody could point me in the right direction I would be very grateful

I forgot to mention, I'm running Unity Web player 4.3.5 and the version on the other two computers is 4.5.0


texts:
I want to use a .mtl file to draw my objects in unity.
Can I somehow convert a .mtl file into a normal Unity material?

My .mtl file is like this:

newmtl phongE1SG
illum 4
Kd 0.00 1.00 0.00
Ka 0.00 0.00 0.00
Tf 1.00 1.00 1.00
Ni 1.00
Ks 0.50 0.50 0.50

Is this the same as a Unity material which has the sliders "albedo", "metallic", "smoothness", etc?

Or is there any shader to do it?


texts:
I am considering designing a Tetris game where instead of a traditional flat game board, the game will transform the board into different kinds of surfaces. I think I lack the appropriate mathematical terms to describe the behavior I'm looking for, but here is one example of the design. The board starts as a flat plane, and starts bending outwards until it forms a cylinder (at which point the entire board is not visible in one view). My question is what strategy can I use to implement the interactive graphics on non-uniform surfaces? I've seen that meshes are used a lot, but how can I show this Tetris board on any random mesh?

Here is an example of the transformation I am trying to make. Note that it will not be limited to curvature on a single axis.


texts: Read access violation, pointer was nullprt

texts:
Im trying to figure out how to use pointers to make a single instance of an object that in this example will just change direction on x-axis.

Splav.h (eng. Paddle.h)

#pragma once
#include "SDL.h"
#include "Prikazi.h"

class Prikazi;

class Splav
{
private:
    int splavTrenutniX = 0, splavTrenutniY = 0; //current x and y axis position of the paddle
    int splavPocetniX, splavPocetniY; //starting position of paddle

public:

    Prikazi *pr; //pointer to the Prikazi (eng. Draw) class

    SDL_Rect rectSplav; //Rect used to store texture of paddle

    Splav(); //default constructor, used to initialize paddle for 1st load or reset
    Splav(int trenutniX, int trenutniY); //overload constructor where current x and y points on axis become points on paddle movement

    void gibanjeSplavi(); //move the paddle

};

Splav.cpp (eng. Paddle.cpp)

#include "Splav.h"

Splav::Splav()
{
    splavPocetniX =pr->sirinaEkrana / 2; //sirinaEkrana = Screen width
    splavPocetniY = pr->visinaEkrana - pr->visinaSplavi; // screen height- paddle height

    rectSplav.x = splavPocetniX;
    rectSplav.y = splavPocetniY;
    rectSplav.w = pr->sirinaSplavi;
    rectSplav.h = pr->visinaSplavi;
}

Splav::Splav(int trenutniX, int trenutniY)
{

    splavTrenutniX = trenutniX;
    splavTrenutniY = trenutniY;

    gibanjeSplavi();
}

void Splav::gibanjeSplavi() //when paddle starts to move
{
    const Uint8 *tipka = SDL_GetKeyboardState(NULL);

    if (tipka[SDL_SCANCODE_A] && rectSplav.x > 0)
        rectSplav.x--;

    if (tipka[SDL_SCANCODE_D] && rectSplav.x < 1280-pr->sirinaSplavi) //1280-200(paddle width)
        rectSplav.x++;
}

Prikazi.h (eng. Draw.h)

#pragma once

#include "SDL_image.h"
#include "Splav.h"

class Splav;

class Prikazi
{

private:

    SDL_Window * ekran = NULL;
    SDL_Renderer *renderer;

    SDL_Texture *pozadina;
    SDL_Texture *splav;
    SDL_Texture *loptica;

    SDL_Rect rectPozadina;

public:

    Splav *sp ;

    const int sirinaEkrana = 1280, visinaEkrana = 720; //screen width and height
    const int sirinaSplavi = 200, visinaSplavi = 10; //paddle width and height

    Prikazi();
    ~Prikazi();

    void crtajPocetno();

    SDL_Rect initRect(int x, int y, int sirina, int visina);
};

Prikazi.cpp (eng. Draw.cpp)

#include "Prikazi.h"

Prikazi::Prikazi()
{

    ekran = SDL_CreateWindow("Breakout", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, sirinaEkrana, visinaEkrana, SDL_WINDOW_SHOWN);
    renderer = SDL_CreateRenderer(ekran, -1, 0);
    pozadina= IMG_LoadTexture(renderer, "Assets/pozadina1.png");
    loptica = IMG_LoadTexture(renderer, "Assets/loptica.bmp");
    splav = IMG_LoadTexture(renderer, "Assets/splav.bmp");

    rectPozadina = initRect(0, 0, sirinaEkrana, visinaEkrana);

//this is where I get nullptr value
    sp->rectSplav = initRect(sp->rectSplav.x, sp->rectSplav.y, sirinaSplavi, visinaSplavi);

    crtajPocetno();
}

Prikazi::~Prikazi()
{
    //SDL_DestroyWindow(ekran);
}

void Prikazi::crtajPocetno()
{
    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer, pozadina, NULL, &rectPozadina);
    SDL_RenderCopy(renderer, splav, NULL, &(sp->rectSplav));

    SDL_SetRenderTarget(renderer, pozadina);
    SDL_SetRenderTarget(renderer, splav);

    SDL_SetRenderTarget(renderer, NULL);
    SDL_RenderPresent(renderer);

}

SDL_Rect Prikazi::initRect(int x, int y, int sirina, int visina)
{
    SDL_Rect r;
    r.x = x;
    r.y = y;
    r.w = sirina;
    r.h = visina;

    return r;
}

My question is: How to define that pointer so I can just use it to store Rect coordinates to my Prikazi class (eng. Draw) so It can use that info to render it on the screen? Same question goes to creating Prikazi pointer inside Splav.h ( so I can use constants for screen height, width etc. )


texts: Should I Have a Ridiculously Easy First Level?

texts: I am making a game based on a grid and filling in certain squares with certain colors according to some rules. It is level-based, and the difficulty of a level is determined by the size of the grid and how many colors you have to fill in. Should the first level be ridiculously easy to allow players to get used to the UI?


texts: How do I make dialogue only appear once?

texts:
So I made it so when I walk over a NPC it brings up 12 lines of dialogue, and you press E to get to the next line. When the dialogue is over you can keep pressing E and it will bring the dialogue up every time. I want it so it only brings the dialogue up once. How do I do that?

This is my script for it:

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

public class dialogHolder : MonoBehaviour
{
    public string dialogue;
    private DialogueManager dMan;

    public string[] dialogueLines;

    public float questComplete;

    // Use this for initialization
    void Start()
    {
        dMan = FindObjectOfType<DialogueManager>();
    }

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

    private void OnTriggerStay2D(Collider2D other)
    {
        if (other.gameObject.name == "Shrump")
        {
            if (Input.GetKeyUp(KeyCode.E))
            {
                //dMan.ShowBox(dialogue);
                if (!dMan.dialogActive)
                {
                    dMan.dialogLines = dialogueLines;
                    dMan.currentLine = 0;
                    dMan.ShowDialogue();
                }
            }
        }
    }
}


texts: C++ Pass the reference of the class to a vector inside the constructor

texts:
Okay so i have an extern vector of pointer type 'Entity', and what i want to do is, when a new Entity type class gets constructed it gets pushed back in the vector of Entities, in C# this would be possible by passing 'this' as a parameter, but i'm unable to do that in c++ ! Here is my code:

'Public.h':

// other code
    #ifndef Entity_h
    #include "Entity.h"
    extern vector <Entity*> AllEntities;
    #endif
// other code

I've put the code in Include guards to not get in trouble, because i'm including 'Public.h' from 'Entity.cpp' and if i didn't have guards it would become a circular dependency !

'Public.cpp':

// other code
#ifndef Entity_h
vector <Entity*> AllEntities;
#endif
// other code

Everything fine, no errors!

'Entity.cpp':

#include "Public.h"
#include "Entity.h"

Entity::Entity()
{
// other code
    AllEntities.push_back(this);
}

i'm trying to do this, but doing this causes me some linker errors:

   Error    3   error LNK2005: "void __cdecl AddToAllENT(class Entity *)" (?AddToAllENT@@YAXPAVEntity@@@Z) already defined in Entity.obj    C:\Users\drin-_000\Documents\Visual Studio 2013\Projects\ECSystem\ECSystem\Public.obj   ECSystem
    Error   4   error LNK2001: unresolved external symbol "class std::vector<class Entity *,class std::allocator<class Entity *> > AllEntities" (?AllEntities@@3V?$vector@PAVEntity@@V?$allocator@PAVEntity@@@std@@@std@@A) C:\Users\drin-_000\Documents\Visual Studio 2013\Projects\ECSystem\ECSystem\Entity.obj   ECSystem
    Error   5   error LNK1120: 1 unresolved externals   C:\Users\drin-_000\Documents\Visual Studio 2013\Projects\ECSystem\Debug\ECSystem.exe    1   1   ECSystem

When i try to do this:

Entity::Entity()
{
// other code
    AllEntities->push_back(this);
}

it gives me these errors!

Error   1   error C2819: type 'std::vector<Entity *,std::allocator<_Ty>>' does not have an overloaded member 'operator ->'  c:\users\drin-_000\documents\visual studio 2013\projects\ecsystem\ecsystem\entity.cpp   9   1   ECSystem
Error   2   error C2232: '->std::vector<Entity *,std::allocator<_Ty>>::push_back' : left operand has 'class' type, use '.'  c:\users\drin-_000\documents\visual studio 2013\projects\ecsystem\ecsystem\entity.cpp   9   1   ECSystem
    3   IntelliSense: expression must have pointer type c:\Users\drin-_000\Documents\Visual Studio 2013\Projects\ECSystem\ECSystem\Entity.cpp   9   2   ECSystem


texts:
I am trying to decide what the best method is to call "level complete-screen" and "game over-screen" in my real-time android 2d game. Currently I am using game-states and only updating my game when its in gamestate==GAMEPLAY, but this sometimes makes resetting some stuff awkward. Another method I have tried is calling a new activity during real-time using context, like this:

public void startMenu() {
    final Context context = this.getContext();
    ((Activity) context).runOnUiThread(new Runnable() {
        public void run() {
            thread.setRunning(false);
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // Context context = getContext();
            Intent intent = new Intent("nielsen.happy.activities.MENU");
            intent.putExtra("level", level);
            ((Activity) context).startActivity(intent);
        }
    });

This method calls another activity during real-time from a View-class. But it seems a bit clumsy and forced. Just want to know if there is a preferred way to call these screens in real-time games?


texts: Finding rotation quaternion from orthonormal basis?

texts:
Given three 3D unit vectors \$a\$, \$b\$, \$c\$ such that:

\$a \times b = c\$

\$b \times c = a\$

\$c \times a = b\$

(ie \$a, b, c\$ form an orthonormal basis)

How do we calculate a unit quarternion \$q\$ such that the sandwidch product (ie rotation) of \$q\$ on (1,0,0) is \$a\$, (0,1,0) is \$b\$ and (0,0,1) is \$c\$ ?


texts:
I need to run my game without graphics and user input (headless mode).

I googled it but I actually couldn't find a solution, except something like this:

using UnityEngine;
using System.Collections;
using UnityEditor;

public class a : MonoBehaviour {

    public static void BeforeBuild()
    {
        EditorUserBuildSettings.enableHeadlessMode = true;
    }
}

Unfortunately, this doesn't work for me as it seems to work only on Linux.

Am I forced to run my instance on Linux?

I would be really thankful if anyone could help me!


texts: Android/Java AI agent framework/middleware

texts:
I am looking for an AI agent framework to use as a starting point in an Android game I have to create for a university research project. It has been suggested to me to use JADE, but, as far as I can tell, it's not a suitable framework for games (at least for my game idea) because it runs in a split-execution mode, and it needs an always-active network connection to a main host.

What I want is just a little something to give me a headstart. I am willing to adjust the game's features to the framework because it's more of a mockup game, and the purpose is to compare the performance of a couple of agents in the game world. The game will be very simplistic, with a minimal UI that displays various stats about the characters in the game (so no graphics, no pathfinding).

Thank you.


texts: How to set orthographic camera for libgdx

texts:
I have implemented a basic demo of camera but it is not showing any sprites on screen.
I cannot figure out what's wrong with my code.

public class MyGdxGame extends ApplicationAdapter {
    private int width, height;
    private OrthographicCamera camera;

    private SpriteBatch batch;
    private Texture roboTex;

    private Sprite roboSprite;

    private World world;

    private Body robot;

    @Override
    public void create() {
        width = Gdx.graphics.getWidth();
        height = Gdx.graphics.getHeight();

        world = new World(new Vector2(0, 0f), false);
        camera = new OrthographicCamera();
        camera.setToOrtho(false, Constants.viewportWidth,  Constants.viewportWidth *(height/width));
        camera.update();
        batch = new SpriteBatch();

        //textures
        roboTex = new Texture("Images/robot.png");
        roboSprite = new Sprite(roboTex);
        roboSprite.setBounds(0,0,3,6);

    }

    @Override
    public void render() {
        batch.setProjectionMatrix(camera.combined);
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.begin();
        roboSprite.draw(batch);
        batch.end();

    }

    @Override
    public void resize(int width, int height) {
        float screenAR = width / (float) height;
        camera.setToOrtho(false, Constants.viewportWidth, Constants.viewportWidth/screenAR);
        camera.update();
        batch = new SpriteBatch();
        batch.setProjectionMatrix(camera.combined);
    }

    @Override
    public void dispose() {
        world.dispose();
        roboSprite.getTexture().dispose();
        batch.dispose();
    }

}

Did I missed anything??


texts: Letting the player create a combination of any 4 items that the game will then give the player on a set timer

texts:
Okay, so I've researched scriptable objects and I've realized that it's something that might be very useful for the kind of game I'm making. I've managed to create my own scriptable object for weapons that is able to hold weapon upgrades, range, damage, and other special stuff. I was told scriptable objects are much better for larger scales than enums so that I can hold data for each weapon. I do know how to implement them into
 [CreateAssetMenu(fileName = "New Weapon", menuName = "Weapon")]
 public class Weapon : ScriptableObject
 {
     public new string name;
     public string _discription;

     public Sprite _artwork;

     public int _range;
     public int _damage;
     public int _upgrades;
     public int _element;

     public void Print()
     {
         Debug.Log(name + ": " + _discription + " The weapon does:  " + _damage + "damage.");
     }
 }

I've researched how to show these on the UI, but is there any hint you could give me on getting scriptable objects working with an inventory system, and point me in a direction on how I can give the player control of the order of weapon in the inventory that the game will use to give said weapons in the same order the player set for themselves.
For Example, I want the player to be able to take any of the four weapons: Katana, Spear, Axe, Chakram, and be able to set them in any order. Even using multiple of itself. Eg. (Chakram, Spear, Spear, Axe) and then the game will then give the player the items list they created on a set timer. (Weapons are one-time use, and the player can only hold one weapon at a time, and the timer won't start until the player has used up their current weapon)
 public class Weapon
 {
     public WeaponType type { get; set; }
 }

 public enum WeaponType
 {
     Katana,
     Axe,
     Spear,
     Chakram
 }
 public class WeaponCycle: MonoBehaviour
 {
     [SerializeField] private Weapon[] _weapon;

     public Weapon[] weapons = new Weapon[4];

     List<Weapon> InventoryWeapons = new List<Weapon>();

     // Start is called before the first frame update
     void Start()
     {
         for (int i = 0; i < weapons.Length; i++)
         {
             weapons[i].type = (WeaponType)Random.Range(0, 3);
         }

         StartCoroutine(GiveWeapons(1));
     }

     IEnumerator GiveWeapons(float delay)
     {
         for (int i = 0; i < weapons.Length; i++)
         {
             yield return new WaitForSeconds(delay);
             InventoryWeapons.Add(weapons[i]);
         }
     }
 }

Sorry if it feels like I'm asking for too much, but I'm a beginner when it comes to C# and I'm trying to learn as efficiently as I can.


texts: How to auto animate character movement - Unreal engine 4

texts: I am learning Unreal 4. And basically I want to find out how to auto move character. Which means when I start playing I want the character to auto move forward without my interaction. I know how to do it in UDK, but can't do it in Unreal 4.


texts: Rendering texture buffers to one single texture

texts:
I am attempting to render multiple font textures onto one single texture,
my issue is that each font texture gets repeated, but i would like to have single instance of that font character.

The characters container seems to be too large for it, but i can't figure out why.

Example of the issue below.


texts: Why is Camera turning with different speed than Player with same code in different scripts? (with unity)

texts:
I want to integrate a running character in my game, so I downloaded an animation via Mixamo. The player is running and if I attach the camera directly to the Player, it's shaking the camera and the game is not playable. Therefor I made a different script for the camera. In there, the camera is always following the player but turns (like the player) via
float h = PlayerMovement.horizontalSpeed * Input.GetAxis("Mouse X");
transform.Rotate(0, h * Time.deltaTime * 60, 0);

(for the camera) and
float h = horizontalSpeed * Input.GetAxis("Mouse X");
transform.Rotate(0, h * Time.deltaTime * 60, 0);

for the player. (horizontalSpeed is a constant) But after a few seconds I'm running in a completely different way then I look. Why is that and how can I solve this?
I tried different animations - nothing worked.
Update: If there is no rigidbody and no collider attached to it it works fine. But I need them.


texts: Variables in static library are never initialized. Why?

texts:
I have a bunch of variables that should be initialized then my game launches, but must of them are never initialized.

Here is an example of the code:

MyClass.h

class MyClass : public BaseObject {
    DECLARE_CLASS_RTTI(MyClass, BaseObject);
    ...
};

MyClass.cpp

REGISTER_CLASS(MyClass)

Where REGISTER_CLASS is a macro defined as follow

#define REGISTER_CLASS(className)\
class __registryItem##className : public __registryItemBase {\
    virtual className* Alloc(){ return NEW className(); }\
    virtual BaseObject::RTTI& GetRTTI(){ return className::RTTI; }\
}\
\
const __registryItem##className __registeredItem##className(#className);

and __registryItemBase looks like this:

class __registryItemBase {
    __registryItemBase(const _string name):mName(name){ ClassRegistry::Register(this); }
    const _string mName;
    virtual BaseObject* Alloc() = 0;
    virtual BaseObject::RTTI& GetRTTI() = 0;
}

Now the code is similar to what I currently have and what I have works flawlessly, all the registered classes are registered to a ClassManager before main(...) is called. I'm able to instantiate and configure components from scripts and auto-register them to the right system etc...

The problem arrises when I create a static library (currently for the iPhone, but I fear it will happen with android as well). In that case the code in the .cpp files is never registered.

Why is the resulting code not executed when it is in the library while the same code in the program's binary is always executed?

Bonus questions:

For this to work in the static library, what should I do?

Is there something I am missing?
Do I need to pass a flag when building the lib?
Should I create another structure and init all the __registeredItem##className using that structure?


texts: How would one generate a Navigation Grid for a 3D world?

texts:
I am attempting to find a solution to this problem. I'm trying to build a navigation mesh in the format of a grid of vertices locked to x, y floored coordinates in the shape of squares for 3D space. But I'm having problems trying to figure out a way to go about it.

I tried looking into the Recast library. It's a pretty robust method, but it apparently slows down with larger maps and open space. I also don't know how they generate vertices and edges for the world space with the height map.

My next thought was to do what Unreal Engine 3 used to do.

https://udn.epicgames.com/Three/NavigationMeshReference.html

Which was to use raycasts to generate the mesh. I couldn't figure out how to have the raycasts stop.

So... my next option was box, possibly a box cast. Create a subdivided volume with a size that's a power of 2. Align the box to the grid, and shoot rectangular prisms downwards as a ray. If it lands on a piece of geometry that's part of the ground and the rectangle is not being intersected, leave a square there. And continue down until the bounds of the volume is reached. To check if edges need to be linked, I suppose I could check to see if the slope between two pairs of vertices is within the walkable slope, merge them if this is true.

My main problems are... this doesn't seem to be very optimal. Without thinking of it, at estimation the process is O(N^3) for a multilayered level. Which can get pretty nasty.

And the last bit is for automatically creating rectangular groups of these squares. I'm not entirely sure how to do this. The Unreal implementation separates them by slopes. However, I'm trying to keep the grid format. So that's not entirely necessary. The trouble still remains on creating large rectangular tiles to split up the path finding process into a per tile basis. The tiles can't be too large, nor too small.

So the questions are...

What would be an efficient way to generate this girded navmesh? And what would be a good way to create the tiles?


texts: Will working with a publisher help me prevent my game from being cloned?

texts:
I read many articles on "How (or why not without) to make mobile game without publisher". But the question that bothers me is:

"What if I make a game, that really hits the market in the eye and people start playing it BUT some publisher will see my game and make the very similar game in 2 weeks and makes it ever more succesfull?"

Is this the main reason why I should choose to go with the publisher?

EDIT: My main concern is not about my weeks spent on developing (I love it!). My concern is: Me working WITHOUT publisher (therefore using not so great marketing techniques) can take some time to get my game to peoples hart VS other developer (USING publisher) can clone my game and with publishers help get their cloned game to public much faster. Before people even realizing it is a copycat.


texts: I have read source code of asteroids game. I want to know why when updating the ship's position in X, and Y Axis, we must write it in sin and cosine of the current angle. Is it angular velocity ? why we can't use linear velocity and update the position by a linear velocity?


texts: In opengl how do I render 2d sprites in opengl given that I have a png of the sprite? See images as an example of the effect I'd like to achieve. Also I would like to overlay weapons on the screen like the rifle in the bottom image. Does anyone know how I would achieve the two effects? Any help is greatly achieved.


texts: Space Shooter Unity 5 Collisions not working

texts:
After upgrading the official Space Shooter Tutorial to Unity 5, collisions stop working.

Additionally, the following error is reported:
Non-convex MeshColliders with non-kinematic Rigidbodies are no longer supported in Unity 5.0.


texts: Getting sprites to move exactly the same on different devices

texts:
Background

When moving a sprite along the X axis, this is my code:

spriteXReal = spriteXReal + (spriteXVel * dt);  //.5 would be halfway point of, 1 would be right hand side screen etc...
spriteXScreen=spriteXReal*deviceWidth;

And the spriteXVel value above is worked out as:

spriteXVel = 1/spriteXTime;

So I would set spriteXTime to 10 if I wanted my sprite to work it's way across the screen in 10 seconds.

My code:

Uses a fixed delta time
Has tics per second capped at 60 (so my delta is 1/60)

The issue

This is great and works well, however, I am getting odd results when running on a different device (with a different screen res).

When comparing the 2 devices (simply by starting the game on both devices at the exact same time, they are almost identical save for a tiny difference in speed.

The game world is tile based. Let's say the play area on my development device is 16 tiles wide.  16 tiles fit perfectly onto this device So, if I'm moving between 8 tiles, I'm effectively crossing 1/2 of the screen.

Initially, the sprite appears to move the same on both devices, (going back and forth between say the 1st 'proper' tile and the 8th 'proper' tile), but after about 25 seconds, they are clearly out of sync.

On this device, the tiles would look something like this:

So, I'm working out my sprite movement using the device's width as above.

However, if the tiles don't fit exactly, I'm centering the original tiles and adding 'padding' tiles to the play-area like so:

Therefore, my confusion lies in how I should be working out my sprite's new position.  because, now 8 tiles is actually less than 1/2 of the device's screen.  So should I still be using the code above or something like this:

spriteXScreen=spriteXReal*(Block18X - Block2X);

I have actually tried both and when I did, the problem was still evident, so I'm not sure which one I'm supposed to be using.

What is really odd is that when I set my sprite's Time variable to certain amounts, it appears that everything stays in perfect sync between these 2 devices so I'm completely stumped - that's what I've observed thus far anyway.  I'm going to test that theory a bit more.

What else could be causing this discrepancy?!

Really appreciate some help with this one!

Edit

I've pretty much tried everything I can, I've even tried implementing a very simple 'test' game loop that updates sprite positions once every second, and put the two devices side by side, however, the Samsung Galaxy Ace Always runs ahead of the Google tablet, is it possible that System.CurrentTimeMillis(); is actually running faster on the Ace than on the tablet?


texts: I do not want a mobile phone, but are there any issues I'd run into by developing games on an iPod for iPhone?


texts: Which is the way to pass parameters in a drawableGameComponent in XNA 4.0?

texts:
I have a small demo and I want to create a class that draws messages in screen like fps rate. I am reading a XNA book and they comment about GameComponents. I have created a class that inherits DrawableGameComponent

public class ScreenMessagesComponent : Microsoft.Xna.Framework.DrawableGameComponent

I override some methods like Initialize or LoadContent. But when I want to override draw I have a problem, I would like to pass some parameters to it.

Overrided method does not allow me to pass parameters.

        public override void Draw(GameTime gameTime)
        {
            StringBuilder buffer = new StringBuilder();

            buffer.AppendFormat("FPS: {0}\n", framesPerSecond); // Where get framesPerSecond from???

            spriteBatch.DrawString(spriteFont, buffer.ToString(), fontPos, Color.Yellow);
            base.Draw(gameTime);
        }

If I create a method with parameters, then I cannot override it and will not be automatically called:

        public void Draw(SpriteBatch spriteBatch, int framesPerSecond)
        {
            StringBuilder buffer = new StringBuilder();

            buffer.AppendFormat("FPS: {0}\n", framesPerSecond);
            spriteBatch.DrawString(spriteFont, buffer.ToString(), fontPos, Color.Yellow);
            base.Draw(gameTime);
        }

So my questions are:

Is there a mechanism to pass parameter to a drawableGameComponent? What is the best practice?
In general is a good practice to use GameComponents?


texts: How to Calculate Caridnal Direction from Unit Vector

texts:
I have unit Vector of acceleration in local space of object.
Now I want to calculate Cardinal Direction from (North, East, South, West).

So Far I tried to:

FQuat QRot = LocalAcceleration.ToOrientationQuat();
    FRotator Rot = FRotator(QRot);
    float Angle = Rot.Yaw;
    float Angle2 = (FMath::RoundToInt(Angle) + 360) % 360;

(Another version was calulcating atan2).

Then:

if (FMath::IsWithin(IntAngle, 0, 46)
    && FMath::IsWithin(IntAngle, 314, 0))
{
    NewDir = EFourCardinalDirection::N;
}
if (FMath::IsWithin(IntAngle, 134, 228))
{
    NewDir = EFourCardinalDirection::S;
}
if (FMath::IsWithin(IntAngle, 46, 136))
{
    NewDir = EFourCardinalDirection::E;
}
if (FMath::IsWithin(IntAngle, 229, 313))
{
    NewDir = EFourCardinalDirection::W;
}

I also tried to calculate eighth directions and then just assign the four based on the previous eight.

Neither way provided stable results. There are some jumps between directions depending on object movement.


texts: On the game I am developing, I have a very small amount of left-over space on each level screen (but on no other screens.) It is a little less than 5 millimeters (~1/5in) on the left side and bottom. It is caused by the size of blocks, etc. and a few other factors. I could center the level, but still then there would still be dead space. By the way, the player cannot go past the edge of the screen or into the whitespace, so having the level appear to extend past the screen would be misleading. What should I do?


texts: Are the Minecraft animations hardcoded into the game?

texts:
I would like to know how the animation system works in minecraft. I get a feeling that all the mobs are hardcoded into the game. Did notch really sit there and create the matrices for all the animation bones by hand?

I like recreating games for fun, so I would like to know how he did this. Also, if he truly does hardcode them... is there a better way?


texts: What does the update button in the Unreal Engine launcher actually update the engine to?

texts:
Unreal Engine 4 seems to have a very handy way of managing different versions of the engine - mainly you get to keep several copies and choose which one to launch.

That said, not having used the new launcher recently I see that I am quite behind in engine versions but where previously I had to download the new version (as can be seen by my several copies of the engine) there is now an update button on the engines.

My internet is really slow so I'm curious if anyone could tell me what the update button actually does? For example, in the circled one, will it update to some 4.2.x minor version or will it update to the 4.7.2 version that I can freshly install? If I can save some bandwidth by upgrading to 4.7.2 over downloading a fresh copy that would be ideal.


texts: Render live MJPEG stream on a plane in Unity

texts:
I'm trying to display a live video stream as a texture in Unity. It comes from a Raspberry Pi using motion and encoded as MJPEG.

Is there an easy way to implement the stream in my project? I don't need controls for the stream, nor audio solution. Only the video itself.


texts:
Right now I'm facing the issue of rendering the same objects more than once in Directx 11, as the object has:

A diffuse shader
A directional lighting shader
A texture shader

Now the final color should be all of them somehow put together, maybe something like this:

Render Diffuse
Render Texture
Render Directional
Final Color = (Diffuse + Texture) * Lighting // Not sure about this though

But how can this be archieved? Without the EFFECTS FRAMEWORK!


texts:
Is there any way how to draw a Polygon / Fixture from Farseer Physics with XNA?
As I deform these polygons at runtime I can't take any texture from my Content folder, the texture must be generated at runtime too.


texts: When load my unity scene on vmware windows virtual machine, the color/lightening of the scene randomly changes? It turns pink

texts:
Hi I have a unity scene doing all it is suppose to on mac but I had to load that scene on vmware windows virtual machine and when I did that, the color or the lighting of the scene was randomly changed and I don't know how to fix that. Any help will be highly appreciated.
Thanks


texts: Rendering clouds similar to Sky: Light Awaits?

texts:
I'm interested in adding clouds to my game, with a style similar to those in Sky: Light Awaits

You can see them in motion in these videos:

(Starts at 26:00)
https://www.youtube.com/watch?v=ttIo9miMizE
(Starts at 4:00)
https://www.youtube.com/watch?v=QFyibYpxidA&t=260s

The cloud rendering in this game really is fascinating but meanwhile efficient enough to be run on mobile platforms.

How could I do something like this in my own game?


texts: Why is Unity MouseLook very shaky and jittery?

texts:
I'm working on a first person shooter game.

My problem is that my Mouselook script is shaky and jittery when I looking around.

Here is my code:

Transform MyTransform;

const string vert_input = "Mouse Y";
const string horz_input = "Mouse X";

public float mouseSensitivity = 100.0f;
public float clampAngle = 80.0f;

void Update()
    {
        the_time = Time.deltaTime;

        ROTX_ROTY.y += (Input.GetAxis(horz_input) * mouseSensitivity * current_speed_offset * the_time);
        ROTX_ROTY.x += (Input.GetAxis(vert_input) * mouseSensitivity * current_speed_offset_vertical * the_time);

        ROTX_ROTY.x = Mathf.Clamp(ROTX_ROTY.x, -clampAngle, clampAngle);

        MyTransform.rotation = Quaternion.AngleAxis(ROTX_ROTY.y, Vector3.up);
        x_rot_transform.localRotation = Quaternion.AngleAxis(ROTX_ROTY.x, Vector3.left);
    }

And this is my input settings for Mouse X and Mouse Y:

For more explanation: I put my camera inside one of my controller children and if I put it out of controller the issue is still there.

I tried Lerp, Slerp, smoothdamp , euler but does not make any difference.

I tried this script for Android and I used a touch instead of a mouse and the result was same.

I tried it on FixedUpdate and the result was same.

Is there any way to fix this problem?

Here is a video about my problem.


texts: Do you need a license for weapon models?

texts:
When creating your own model for a weapon, say the M4 carbine, and using the model in your game. Do you need a license to use it commercially?
I know that racing games like GT5 has a license for each and every car, but the same apply for weapons?


texts: Are hard coded "rooms" better than dynamically generated on a smart phone, from performance point of view

texts:
This question pertains to a type of platform/maze game (made with Unity 5) for typical smartphones (iOS/Android).

This game has following characteristics:
 1. an upper limit (about 100) on the amount of rooms
 2. 3-5 different "levels", each with a different amount of rooms
 3. the shape and type of the "ground" in each room is dynamically generated
 4. each room has some items that are dynamically placed in the room but are generated from a prefab

A rough idea on the rooms in this game is given in below screen shot.

In that image only the platforms (black and white tiles) and the ground (light brown) would be shaped by an algorithm. The other objects shown in the image are prefabs that would be located somewhere in the room by an algorithm.

But considering that this game would not exactly be an infinite runner, and since it should run on smart phones, would it be better from performance perspective, to create 100 hard coded rooms instead?


texts: Right click a location and move towards it (C# Monogame)

texts:
I would like the player to move towards the mouse when the player right clicks. The player does move, but doesn't stop when the player reaches the point.
Here is the code.

void playerUpdate(GameTime gameTime)
    {
        float dT = (float)gameTime.ElapsedGameTime.TotalSeconds;
        player.pos.X += player.vel.X * dT;
        player.pos.Y += player.vel.Y * dT;

        player.checkDest(x2y2, player.pos);

        if ((mouse.RightButton == ButtonState.Pressed) && (player.moving == false))
        {
            x2y2.X = mouse.X;
            x2y2.Y = mouse.Y;

            player.move(x2y2, player.pos);

        }
    }

The player's file,

        public void move(Vector2 dest, Vector2 pos)
    {
        dist.X = pos.X - dest.X;
        dist.Y = pos.Y - dest.Y;

        vel.X -= dist.X;
        vel.Y -= dist.Y;

        moving = true;
    }

    public void checkDest(Vector2 dest, Vector2 pos)
    {
        if (pos == dest)
        {
            vel.X = 0;
            vel.Y = 0;
            moving = false;
        }
    }

I assume it is because of the player's position and its use of decimals and the mouse position being integers. How could I work around that?


texts: Type Object does not support slicing Unity3D

texts:
I am getting the following error in my code and I can't seem to understand why. Can anyone help me with it?

This is my current code. The line causing the error is marked in a comment near the end.

var rows : int = 4;
var cols : int = 4;
var totalCards : int = cols * rows;
var matchesNeedToWin : int = totalCards * 0.5;
var matchesMade : int = 0;

var cardW : int = 100;
var cardH : int = 100;

var aCards : Array;
var aGrid : Array;

// This Array will store the two cards that the player flipped
var aCardsFlipped : ArrayList;

// To prevent player from clicking buttons when we don't want him to
var playerCanClick : boolean;

var playerHasWon : boolean = false;

class Card extends System.Object {
var isFaceUp : boolean = false;
var isMatched : boolean = false;
var img : String;

    function Card () {
        img = "robot";
    }
}

function Start () {

    var i : int = 0;
    var j : int = 0;

    playerCanClick = true;
    aCards = new Array ();
    aGrid = new Array ();
    aCardsFlipped = new ArrayList ();

    for ( i = 0; i < rows; i++) {
        aGrid [i] = new Array ();

            for (j = 0; j < cols; cols++ ) {
            aGrid [i] [j] = new Card (); // <------ Error over here
        }
    }
}

function Update () {
    Debug.Log("Game Screen has loaded");
}

The error states as follows:

  Error BCE0048: Type 'Object' does not support slicing. (BCE0048) (Assembly-UnityScript)


texts: I'm wondering what is the most efficient collision shape to use with APIs like Bullet or Havok for rooms/interiors. Rooms tend to be boxes but are concave since the normals point inward which means no to the box shape. Rooms also can have holes in the walls (doors, windows, etc) too. If I'm assigning shapes with a modeling tool like Blender it seems like my only option is a Triangle Mesh shape but it seems like I should be able to get away with a cheaper (performance-wise) shape for something like this.


texts: How to do Marching Cubes Meshing in unity 3D

texts:
I'm getting very peculiar results from my marching cubes based surface generator within unity and figured this must be a pretty common problem that has been solved already, so I thought I would extract this out as a tiny example project that only includes the broken generation code ...

http://ccoder.co.uk/files/mc.zip

... if you download and run the example you should get something like this ...

... so my question is:

How can I resolve the logic in the marching cubes meshing code to generate a complete mesh with consistent uv mappings all the way around?

  If someone can solve this I will edit the sample in this question with
  the solution so others can download this solution in the
  future.

UPDATE:

So I figured out what was causing the vertex generation issue, it looks like paul burkes lookup tables however result in some cases returning the vertex data in different orders to others which appears to be the cause of this uv issue (see image, updated)

I have updated the sample project too, anyone fancy debugging the marching cubes tri table?, something tells me this will be a long winded task!


texts: MonoGame / XNA Texture2D.SetData results in black texture

texts:
I use the following method to draw a box onto the screen:

private void DrawBox(Rectangle rect, Color color, Vector2 offset)
{
    Texture2D tex = new Texture2D(GraphicsDevice, rect.Width, rect.Height);
    Color[] data = new Color[rect.Width * rect.Height];

    for (int i = 0; i < data.Length; i++)
        data[i] = color;

    tex.SetData(data);

    var pos = new Vector2(rect.Location.X, rect.Location.Y) + offset;

    spriteBatch.Draw(tex, pos, Color.White);

    tex.Dispose();
}

However, this results in a completely black image being drawn onto the screen, regardless of the colour I pass to this method. Why is this happening and how can I fix this?


texts: Is C++ "still" preferred in game development?

texts:
I am a 2D Game Programmer.Some programming languages which I am good at are C,Java ,C#. I also know Actionscript 2.0,3.0 and some javascript.
I'm interested in learning 3D Game programming. So far from the research I have accumulated by googling and reading different game development forums and articles. I've noticed that most programmers tend to prefer C++.Also in an online game programming teaching course I noticed they prefer to teach C++ and Visual C++ as the starting course. The reason I am asking this question since I would like to know the "strength" difference of C++, C# and Java for 3d game programming.

Also include links to good 3d game programming articles for the already 2d game programmer.

P.S : IMHO , I also find C++ to be cryptic.


texts:
Working in C#/XNA for a Windows game: I'm using Texture2D to draw sprites. All of my sprites are 16 x 32. The sprites move around the screen as you would expect, by changing the top X/Y position of them when they're being drawn by the spritebatch.

Most of the time when I run the game, the sprites appear like this:

and when moved, they move as I expect, as one element.

Infrequently they appear like this:

and when moved it's like there are two sprites with a gap in between them - it's hard to describe.

It only seems to happen sometimes - is there something I'm missing? I'd really like to know why this is happening.

[Edit:] Adding Draw code as requested:

This is the main draw routine - it first draws the sprite to a RenderTarget then blows it up by a scale of 4:

protected override void Draw(GameTime gameTime)
{
    // Draw to render target
    GraphicsDevice.SetRenderTarget(renderTarget);
    GraphicsDevice.Clear(Color.CornflowerBlue);
    Texture2D imSprite = null;

    spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointWrap, null, null);
    ManSprite.Draw(spriteBatch);
    base.Draw(gameTime);
    spriteBatch.End();

    // Draw render target to screen
    GraphicsDevice.SetRenderTarget(null);

    imageFrame = (Texture2D)renderTarget;

    GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0);
    spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointClamp, null, null);
    spriteBatch.Draw(imageFrame, new Vector2(0, 0), null, Color.White, 0, new Vector2(0, 0), IM_SCALE, SpriteEffects.None, 0);
    spriteBatch.End();

}

This is the draw routine for the Sprite class:

public virtual void Draw(SpriteBatch spriteBatch)
{
    spriteBatch.Draw(Texture, new Vector2(PositionX, PositionY), null, Color.White, 0.0f, Vector2.Zero, Scale, SpriteEffects.None, 0.3f);
}


texts: Animator.SetBool: am I supposed to call it only when its value changes?

texts:
I've searched around the web for a while, but didn't manage to find anything about it.

Despite using Animator in several projects so far, I've never been in this exact situation, so I'm unsure what to do.

Does calling Animator.SetBool have any performance issue, so that I'd better call it only when its value has changed, or when its value doesn't change it's so quick that I can call it every frame?

Keep in mind that, due to the nature of this question, I don't care if it's slow when I change its value, I only care if it's slow when it's false and I call it to set it to false again (same thing for true ofc).


texts: Unity: Slow deployment to Android devices?

texts:
From the time I hit "Build & Run", I wait 2 minutes (each) for Unity 5 to push to two different 'Droids. Fresh project, one script to generate a simple mesh, and no other assets. I am deploying via a USB 2.0 port.

IIRC from using Unity 4 in 2012, the same was true then, including for iOS deployments.

Is this to be expected? My dev machine is an i7 with 16GB RAM and everything else is fast.


texts:
I really hope you can help me fix this code:
List<Vector3> verticesToExport = new List<Vector3>();//vertices of the triangles facing upwards.
        List<int> trianglesToExport = new List<int>();//new triangle facing upwards.
        //meshToCut is the original mesh, then I just try to replace it with the new data.
        int[] triangles = meshToCut.triangles;
        Vector3[] vertices = meshToCut.vertices;

        for (int i = 0; i < triangles.Length; i += 3)
        {
            Vector3 corner = vertices[triangles[i]];
            Vector3 a = vertices[triangles[i + 1]] - corner;
            Vector3 b = vertices[triangles[i + 2]] - corner;

            float projection = Vector3.Dot(Vector3.Cross(b, a), Vector3.down);
            if (projection > 0f)
            {
                verticesToExport.Add(vertices[triangles[i]]);
                verticesToExport.Add(vertices[triangles[i + 1]]);
                verticesToExport.Add(vertices[triangles[i + 2]]);
                trianglesToExport.Add(triangles[i]);
                trianglesToExport.Add(triangles[i + 1]);
                trianglesToExport.Add(triangles[i + 2]);
            }
        }
        meshToCut.SetVertices(verticesToExport);
        meshToCut.SetTriangles(trianglesToExport, 0);//probably I'm doing wrong here!

It works great by retrieving the vertices facing up, and I guess the triangles too but when I put it into a mesh filter I believe the triangles are not in order...
1.The model I'm trying to separate; the triangles facing upwards.

2. This is what happens if I just take the vertices and triangulate them again. It proves that vertices are alright!

3. The result I get from the code above:


texts: clip space, normalized device coordinate space and window space in OpenGL

texts:
I am learning OpenGL. Clip space, normalized device coordinate space and window space are confusing. I searched but still don't understand them clearly.
So, the question is- what are differences between them and how are they converted from one to another? And what coordinate do the built-in OpenGL functions (e.g.: glBufferData) take as input?


texts:
I have drew a hemi-sphere by myself, and would like to do basic jellyfish animation by animating the vertices of the hemi-sphere. I tried a lot of experiments but it seems I'm doing it wrong. I need hints or idea on about doing it.

This is the code on how to draw a hemi-sphere. I don't know what values actually to play with to animate the sphere as a jellyfish.

for(float phi = 0.0; phi < 1.567; phi += factor) {

        glBegin(GL_QUAD_STRIP);

        for(float theta = 0.0; theta < 2*3.14 + factor; theta += factor)
        {
            x = rh * sin(phi) * cos(theta);
            z = rh * sin(phi) * sin(theta);
            y = -rh * cos(phi);

            gl::vertex(Vec3f(x, y, z));

            x = rh * sin(phi + factor) * cos(theta);
            z = rh * sin(phi + factor) * sin(theta);
            y = -rh * cos(phi + factor);

            gl::vertex(Vec3f(x, y, z));

        }
        glEnd();
    }


texts:
I am creating an endless game, which constantly spawns tiles. The problem is that after a few tiles the player gets stuck on random tile and stops moving. I noticed this problem even when i was designing a level, where when I align two tiles side by side, the player gets stuck on the junction of these two tiles. I am including a video link to my problem. Please help me and please try to be in detail because i very very new to Unity.

Video for the problem im facing.
https://photos.app.goo.gl/JrCPWkGclUA2UiMy1

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

public class TileManager : MonoBehaviour {

public GameObject[] tiles;
private Transform player;
private float SpawnLocationZ = -30.0f;
private float tileLength = 36;
private float amountOfTilesOnScreen = 5;
private float SafeZone = 45;
private List<GameObject> activeTiles;
private int lastPrefabIndex = 0;
private bool StartCompleted = false;
// Use this for initialization
void Start () {
    activeTiles = new List<GameObject>();
    player = GameObject.FindGameObjectWithTag("Player").transform;
    for(int i =0; i<amountOfTilesOnScreen; i++){
        Debug.Log("Start Method");
        SpawnTile(-1);
    }

}

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

    if((player.transform.position.z -SafeZone > (SpawnLocationZ - amountOfTilesOnScreen * tileLength))){
        Debug.Log("started");
        SpawnTile(0);
        DeleteTile();
    }
}

void SpawnTile( int prefabIndex){
    if(prefabIndex == -1){
        GameObject gor;
        gor = Instantiate(tiles[0]) as GameObject;
        gor.transform.SetParent(transform);
        gor.transform.position = Vector3.forward * SpawnLocationZ;
        SpawnLocationZ += tileLength;
        activeTiles.Add(gor);
    }else{
    GameObject go;
    go = Instantiate(tiles[Randome()]) as GameObject;
    go.transform.SetParent(transform);
    go.transform.position = Vector3.forward * SpawnLocationZ;
    SpawnLocationZ += tileLength;
    activeTiles.Add(go);
    }
}

void DeleteTile(){
    Destroy(activeTiles[0]);
    activeTiles.RemoveAt(0);
}

private int Randome(){
    if(tiles.Length <=1){
        return 0;
    }
    int randomIndex = lastPrefabIndex;
    while(randomIndex == lastPrefabIndex){
        randomIndex = Random.Range(0, tiles.Length);
    }
    lastPrefabIndex = randomIndex;
    return randomIndex;
}
 }


texts: How to correctly implement player acceleration caused by player input

texts:
In my game I implement movement in the Player class like so:

// called from Player's update() method, which is called from the gameloop.
void move(){
    velocity.x += acceleration.x;
    velocity.y += acceleration.y;
    position.x += velocity.x;
    position.y += velocity.y;
}

Keyboard input affects the acceleration directly, for example:

// in Player, called from main gameloop.
void update(){
    if(playerInput.rightPressed()) (acceleration.x += 2);
    // .. etc
    move();
}

I think so far this is standard (if not, please say so).

Now my question:

During movement invoked by player input, I want the acceleration to be constant. So when the player presses the right arrow key, the acceleration.x will always be 2 - and not 2, and then 4, and then 6, etc.

I could easily acheive this be having if(playerInput.rightPressed())(acceleration.x = 2), but then other forces acting on the entity will be ignored.

What is the standard way to implement this?


texts: How to use WorldToScreenPoint function in a texture context?

texts: I am rendering a scene into a RenderTexture and I have a set of 3D points. I want to convert these points from 3D to texture coordinate frame. It worked, when I rendered into screen and used camera.WorldToScreen() function. Now I have to render into texture. Is there any way to do the same as WorldToScreen() function does for the render/2D texture?


texts:
I'm working on a perfect information game in my spare time. I've implemented a naive minmax algorithm for the computer player. I've further optimized it using alpha-beta pruning.

What I'm looking for is next logical steps to improve the speed of the search (currently the computer player searches 5 nodes deep with acceptable time taken).


texts: Invoking a common method after a button press

texts:
I want to implement a common method that handles several numeric values and performs and action based on those values. So I have buttons with specific methods to change this values without affecting the rest. However I want to link them all to a final method that runs right after the press of a button, so this way the game will change only when the player chooses to change it and changes according to the players decisions. How can I implement this in my script?
Most of my methods are like this:

public void "ButtonIDGoesHere" (int "SpecificVariable"){
//Add, Sub, Multiply, etc.

}

What can I add so that it goes to a common method right after it executes its instructions?


texts:
Are there any robust performant libraries for indexing objects?

Objects would have bounds themselves, rather than being represented by points; and an object could therefore be in more than one compartment if the index divides things in fixed sized partitions.

It would need frustum culling and visiting objects hit by a ray as well as neighbourhood searches.

I can find lots of articles showing the math for the component parts, often as algebra rather than simple C, but nothing that puts it all together (apart from perhaps Ogre, although apparently PyOrge doesn't expose the octree).  Surely hobby game makers don't all have to make their own spartial indices?

(I am sitting down writing my own sphere-sphere, sphere-ray, ray-aabb, cone-aabb, cone-fustrum, aabb-fustrum and octree implementation; surely there is a better way i.e. someone has already done this and make a nice package?!?!)

(Python or C/C++ w/bindings preferred)


texts: Clipping polygons in XNA with stencil (not using spritebatch)

texts:
The problem... i'm drawing polygons, in this case boxes, and i want clip children polygons with its parent's client area.

    // Class Region
    public void Render(GraphicsDevice Device, Camera Camera)
    {
        int StencilLevel = 0;
        Device.Clear( ClearOptions.Stencil, Vector4.Zero, 0, StencilLevel );
        Render( Device, Camera, StencilLevel );
    }

    private void Render(GraphicsDevice Device, Camera Camera, int StencilLevel)
    {
        Device.SamplerStates[0] = this.SamplerState;
        Device.Textures[0] = this.Texture;
        Device.RasterizerState = RasterizerState.CullNone;
        Device.BlendState = BlendState.AlphaBlend;
        Device.DepthStencilState = DepthStencilState.Default;

        Effect.Prepare(this, Camera );

        Device.DepthStencilState = GlobalContext.GraphicsStates.IncMask;
        Device.ReferenceStencil = StencilLevel;

        foreach ( EffectPass pass in Effect.Techniques[Technique].Passes )
        {
            pass.Apply( );
            Device.DrawUserIndexedPrimitives<VertexPositionColorTexture>( PrimitiveType.TriangleList, VertexData, 0, VertexData.Length, IndexData, 0, PrimitiveCount );
        }

        foreach ( Region child in ChildrenRegions )
        {
            child.Render( Device, Camera, StencilLevel + 1 );
        }

        Effect.Prepare( this, Camera );

        // This does not works
        Device.BlendState = GlobalContext.GraphicsStates.NoWriteColor;
        Device.DepthStencilState = GlobalContext.GraphicsStates.DecMask;
        Device.ReferenceStencil = StencilLevel; // This should be +1, but in that case the last drrawed is blue and overlap all

        foreach ( EffectPass pass in Effect.Techniques[Technique].Passes )
        {
            pass.Apply( );
            Device.DrawUserIndexedPrimitives<VertexPositionColorTexture>( PrimitiveType.TriangleList, VertexData, 0, VertexData.Length, IndexData, 0, PrimitiveCount );
        }
    }

    public static class GraphicsStates
    {
        public static BlendState NoWriteColor = new BlendState( )
        {
             ColorSourceBlend = Blend.One,
             AlphaSourceBlend = Blend.One,
             ColorDestinationBlend = Blend.InverseSourceAlpha,
             AlphaDestinationBlend = Blend.InverseSourceAlpha,
             ColorWriteChannels1 = ColorWriteChannels.None
        };

        public static  DepthStencilState IncMask = new DepthStencilState( )
        {
            StencilEnable = true,
            StencilFunction = CompareFunction.Equal,
            StencilPass = StencilOperation.IncrementSaturation,
        };

        public static  DepthStencilState DecMask = new DepthStencilState( )
        {
            StencilEnable = true,
            StencilFunction = CompareFunction.Equal,
            StencilPass = StencilOperation.DecrementSaturation,
        };
    }

How can achieve this?

EDIT: I've just relized that the NoWriteColors.ColorWriteChannels1 should be NoWriteColors.ColorWriteChannels. :)

Now it's clipping right.

Any other approach?


texts: How can the game graphics be stabilised when after each frame hundreds of calculations are taking place?

texts: I am building a very basic 2D game purely using pygame library in Python 3x. The "game object" is blit(ed) onto the screen using a loop and after each pass, there are calculations taking place in the background for example, to test for collision. Now as the game get's more complex with more features, the calculations take longer and hence the "game object" is put onto the screen once, but disappears for a split second when the calculations are taking place and appears again during the second pass, meaning it flickers. How can I tackle this problem? I cannot move ahead with more complex calculations for other features without avoiding the flickering due to more time required for the calculations.


texts: How to delete a score after collecting all collectibles

texts:
I'm making a small game for my English class, and in the beginning, you have to collect rocks. I already have the code for counting how many rocks have been picked up, and the GUI to display while the game runs. After the player collects all 9 rocks I would like for the GUI to disappear or delete itself since it won't be used anymore throughout the game, and for new text to appear at the top of the screen saying "Go To The Lottery"

I'm still very new to Unity so posting the code, and then following up with a brief explanation as to what does what would be majorly appreciated (but not at all demanded)

Both codes are in JavaScript

#pragma strict

static var currentScore : int = 0;
var offsetY : float = 40;
var sizeX : float = 100;
var SizeY :float = 40;

function OnGUI () {
GUI.Box (new Rect (Screen.width/2-sizeX, offsetY, sizeX, SizeY), "Rocks Collected: " + currentScore);

}

^^ This is my GameMaster script, which is in a empty game object galled "_GM" ^^

#pragma strict

function OnTriggerEnter (info : Collider)
{
    if (info.name == "Player")
    {
    GameMaster.currentScore += 1;
    Debug.Log ("Picked stone up");
    Destroy (gameObject);
    }
}

^^ This is my RockCollection script and it's what actually tells the GameMaster script to add 1 to the score and then delete the rock so you can't continuously pick it up


texts: using DirectX to generate a sprite sheet

texts:
I am building a site in HTML5 for my client and it must run on the iPad/iPhone (i.e. Safari on iOS).

They want a 3D effect where they have a simple, yet, specific product they want to show on the site in 3D with user generated data as the texture.

Normally, I would use either flash/silverlight/webgl but these are not supported on iOS.

Also, CSS 3D transforms are close, but since I need a specific shape and size, creating hundreds of div elements and transforming them just wont work in the long run.

My idea, is to use server side code to generate a sprite sheet that could be used on the site to fake the 3D-ness of the object.

What I really lack is the knowledge around DirectX/OpenGL in order to automate this process.

My question is, can I use DirectX/OpenGL from a command line (or programatically) to pass is a model and textures to generate a PNG/JPG sprite sheet of a rotating object?


texts: Got garbage when getting shader compile log

texts:
I got garbage when trying to compile shader and get error log. I checked my code against some sample code, and could figure out where I did wrong.

Below is my code:

bool LoadShader(GLuint ShaderType, char const* ShaderFileName)
{
    os_file ShaderFile = OSReadFile(ShaderFileName);
    GLint ShaderHandle = glCreateShader(ShaderType);
    DebugPrint("Shader source: %s\n%.*s\n", ShaderFileName, ShaderFile.Length, ShaderFile.Contents);

    GLchar* ShaderSource = (GLchar*)&ShaderFile.Contents;
    GLint ShaderSourceLength = ShaderFile.Length;
    glShaderSource(ShaderHandle, 1, &ShaderSource, &ShaderSourceLength);
    glCompileShader(ShaderHandle);

    OSFreeFile(&ShaderFile);

    GLint Success;
    glGetShaderiv(ShaderHandle, GL_COMPILE_STATUS, &Success);
    if (!Success)
    {
        GLchar CompileLog[512];
        glGetShaderInfoLog(ShaderType, 512, NULL, CompileLog);
        switch (ShaderType)
        {
#define SHADER_TYPE_ERROR(ShaderType) case ShaderType: { DebugPrint(#ShaderType " Compile error!\n"); } break;
            SHADER_TYPE_ERROR(GL_VERTEX_SHADER);
            SHADER_TYPE_ERROR(GL_FRAGMENT_SHADER);
#undef SHADER_TYPE_ERROR
        }
        DebugPrint("%s\n\n", CompileLog);
        return false;
    }
    return true;
}

Below is some output:

Shader source: shader/fragment.glsl
#version 330 core

out vec4 Colour;

void main()
{
    Colour = vec4(1.0, 0.5, 0.2, 1.0);
}

GL_FRAGMENT_SHADER Compile error!
p��R�


texts: Unity calculating the boundaries of camera in 2d game

texts:
So im starting to learn Unity, working on a top down 2D game. I know I can use something like Cinemachine to clamp my camera to a 2DCollider, but I decided to try it to implement this manually as a exerciser.
Here is my plan:
1.) I put a BoxCollider2D around my map. I set collider to trigger mode to avoid collisions (although I guess I could just put it on another layer)
2.) I add that Box Collider to my camera object.
3.) In my camera object i put the following update code
        Vector2 min = (Vector2) roomColider.bounds.min + new Vector2(6,6);
        Vector2 max = (Vector2)roomColider.bounds.max - new Vector2(roomColider.offset.x / 2 + 1, roomColider.offset.y / 2 + 1);
        if(transform.position != target.position) {
            Vector3 targetPosition = new Vector3(target.position.x, target.position.y, transform.position.z);
            targetPosition.x = Mathf.Clamp(targetPosition.x, min.x, max.x);
            targetPosition.y = Mathf.Clamp(targetPosition.y, min.y, max.y);
            // Lerp for a smooth camera motion
            transform.position = Vector3.Lerp(transform.position, targetPosition, smoothing);
        }

However this seems to be off. It does clip the camera, but the boundingbox is some amount of units (~6 units) off in this case.


texts: How to create soft Icecream like particles with Liquidfun and Corona

texts:
Currently using the "elastic" flags for particle behavior, which looks decent when it is flowing downwards but when the icecream collects in cup it is too liquidy.  Also this gives it a springy bounce which I am not sure how to take out. I am wondering how I should make it thicker more solid along but to stay a bit elastic? Can I change behavior of particle after it is created?

I have tried with a "spring" flag and "viscous" flag but it looks sort of the same.

Demo Clip

Corona/LiquidFun

  -- Create Particle System
  local particleSystem = physics.newParticleSystem{
    filename = _PRT,
    radius = 1,
    imageRadius = 2
  }

  offset_x = _C.x + 70
  offset_y = _UL.y + 100
  -- Paramaters for red particle faucet

  local particleParams_red =
  {
          flags = { "elastic"},
          linearVelocityY = -10,
          color = { 1, 0, 0.1, 1 },
          x = offset_x,
          x = offset_x + display.contentWidth * 0.15,
          x = offset_x + display.contentWidth * -0.15,
          y = offset_y,
          lifetime = 60.0,
          radius = 5,
  }


texts: What are standard methods for organizing game code? Grouping by standard "kinds" of methods?

texts:
I've made a few games, and am getting faster and better organized each time. I'm well out of the "just make it work" phase and working on methodology and readability. I need some tips on code organization though.

I don't mean patterns - I'm having great success with MVC - but the organization of methods inside the classes themselves. I've noticed that methods in my state models can usually be grouped into four categories: (1)constructor/destructor, (2)data access (3)actions (4)events.

My controllers usually have c/d and input methods. My views usually have c/d, view updaters, and event listeners.

I feel like I'm reinventing the wheel though; someone must have spelled out "these are the common types of methods" somewhere before, right? Storage has Create, Read, Update and Delete (CRUD), so what are the equivalents for objects?

EDIT:
Found some cocoa-specific advice here:
http://www.mactech.com/articles/mactech/Vol.21/21.07/StyleForCocoa/

and some generic advice here:
https://stackoverflow.com/questions/73045/whats-the-best-way-to-organize-code/73081#73081

I'm going to use that as a foundation, modified for game-specific stuff. More info still appreciated if you have any.


texts: A* move to excact position, if close, otherwise approach

texts:
I'm using the A* project from http://arongranberg.com/ and have this annoying problem, that I'm incapable of solving.

When walking to a destination, I want my units to just get close to the waypoints in order to have less calculations and let the path look more natural. But with the current method, they also only approach their destination, which makes formations etc. look awful.

I tried to check if the distance to the target is smaller than the approaching distance (nextWaypointDistance = 1.0f) but this resulted in the unit stuttering. Here's the full Method, that's called every Update:

public void moveAction()
    {
        if (path == null) // kein Pfad
            return;

        if (currentWaypoint >= path.vectorPath.Count) // Ende des Pfades
        {
            moving = false;
            return;
        }

        Vector3 dir = path.vectorPath[currentWaypoint]; // Richtvektor für nächsten Wegpunkt

        if (can_move) // Bewege zum nächsten Wegpunkt
        {
            if (rotating) TurnToTarget();
            else if (moving) MakeMove(dir);
        }

        if (currentWaypoint < path.vectorPath.Count)
        {
            if (Vector3.Distance(transform.position, path.vectorPath[currentWaypoint]) < nextWaypointDistance)
            {
                currentWaypoint++;
                return;
            }
        }
    }

I removed my workarounds from the code, hoping that some of you can provide a better idea.

I somehow believe that this is an obvious thing I missed

EDIT:

As requested, the MakeMove function:

   private void MakeMove(Vector3 dir)
    {
        inCover = false;
        transform.LookAt(dir);
        float scaledSpeed = 1 / moveSpeed;
        transform.position = Vector3.Lerp(transform.position, dir, scaledSpeed);
        if (transform.position == destination) moving = false;
        CalculateBounds();
    }

Example: I want my units to go from a single line to a double line.
Using a hardcoded transform.position = position[unit] will created the wanted result as seen here:

but using the A* movement this would be the result:

And I have absolutely no clue, why. If I'd keep spamming the formation hotkey, it eventually will create a proper line after about 20 clicks

Another example with only one unit would be this:

As you see, the cursor and marker is at the desired spot, but the unit is far away. (using the same movement method)