texts: Unity mesh only rendering one set of triangles

texts:
I've been using Unity3D to procedurally generate terrain with Perlin Noise and I've come across a problem where the mesh that I've constructed only renders one set of triangles.

The following is my MeshGeneration code:
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using NUnit.Framework.Internal.Execution;
using UnityEngine;

public static class MeshGenerator
{
    public static MeshData GenerateMesh(float[,] heightMap)
    {
        int height = heightMap.GetLength(0);
        int width = heightMap.GetLength(1);
        int vertexIndex = 0;

        MeshData meshData = new MeshData(width, height);

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                meshData.vertices[vertexIndex] = new Vector3(x, heightMap[y, x], y);
                meshData.uvs[vertexIndex] = new Vector2( x/(float)width, y/(float)height);

                // If we are not on the edge, then add two triangles to the mesh
                if ((x != width - 1) && (y != height - 1))
                {
                    meshData.AddTriangle(
                        vertexIndex,
                        vertexIndex + width,
                        vertexIndex + width + 1
                    );
                    meshData.AddTriangle(
                        vertexIndex,
                        vertexIndex + 1,
                        vertexIndex + width + 1
                    );
                }

                vertexIndex++;
            }
        }

        return meshData;
    }
}

public class MeshData
{
    public Vector3[] vertices;
    public Vector2[] uvs;
    public int[] triangles;

    public int triangleIndex;
    public MeshData(int meshWidth, int meshHeight)
    {
        vertices = new Vector3[meshWidth * meshHeight];
        uvs = new Vector2[meshWidth * meshHeight];
        triangles = new int[(meshWidth - 1) * (meshHeight - 1) * 6];
    }

    public void AddTriangle(int a, int b, int c)
    {
        triangles[triangleIndex] = a;
        triangles[triangleIndex + 1] = b;
        triangles[triangleIndex + 2] = c;
        triangleIndex += 3;
    }

    public Mesh CreateMesh()
    {
        Mesh mesh = new Mesh();
        mesh.vertices = this.vertices;
        mesh.uv = this.uvs;
        mesh.triangles = this.triangles;

        mesh.RecalculateNormals();
        return mesh;
    }
}

I'm then passing in the mesh that I get from MeshData.CreateMesh() into the following function.
public void BuildMesh(MeshData meshData, Texture2D texture)
    {
        meshFilter.sharedMesh = meshData.CreateMesh();
        meshRenderer.sharedMaterial.mainTexture = texture;
    }

I'm following this tutorial: https://www.youtube.com/watch?v=4RpVBYW1r5M&list=PLFt_AvWsXl0eBW2EiBtl_sxmDtSgZBxB3&index=5
The Mesh generation code works by creating arrays of vertices, uvs, and triangles, and the populating them by iterating over a Vector3[] heightMap that I created with perlin noise.


texts:
In my game, the score can go up quite rapidly and by varying amounts, depending on the action taken.

For instance, at the start of the game, one could climb from 1 - 50 one by one, or they could rocket past 50 by getting a score of 10, 25, and 40.

My question is: How do I call a function every time they pass a factor of 50 (50, 100, 150, 200, etc.)?


texts: XNA 3d Terrain using rectangular elements

texts:
Possible Duplicate:
  Creating a 3D map for XNA ?

I am developing using XNA, a simple 3d tower defense game. I wanted create a 3d terrain.
Here is how I am doing it:

fundamental element is a texture of grass, overlaid on a --> rectangle / cube ...( not sure about this)
These elements are much smaller than the entire game screen. Some equi-spaced elements are filled on the game screen with some randomly generated z values.
others need to interpolate between the z values.

Now the question is how to :

Actually implement it. method 1 is to have each element be completely straight, with normal in y direction, and vary z gradually. method 2 is have the rectangle/ cube surface tilt.
If I do method 1 it might look pretty shabby. using method 2, I don't know how to get the surface z value at all the points, on the eventual terrain, which moving enemies will walk on / towers will be placed on.

Any help is appreciated.
Thnx.


texts: Weird issue with Member Initializers C++

texts:
I'm making a game with C++ and SDL2. I have a class called "text" and a class called "buttonObj"

The constructor of "text" is a void function that takes an SDL_Color variable.

The first part of buttonObj looks like this:

string textContent;
text buttonText;
text highlighted_buttonText;

//Constructor
buttonObj(string tex, SDL_Color notHighlighted, SDL_Color highlighted) :
  textContent( tex ),
  buttonBase( img ),
  buttonText( notHighlighted ),
  highlighted_buttonBase( hI ),
  highlighted_buttonText( highlighted )
{}

Currently, this works, but I don't exactly know WHY it works. With a constructor initializer, the value outside the parenthesis gets assigned to the value within the parenthesis. So, how come an SDL_Color (i.e "notHighlighted") can get assigned to a text variable? (i.e buttonText)

I assume this is because with a class, the variable inside the parenthesis is a parameter of the constructor of that class. So, since the constructor of text takes an SDL_Color variable, the program treats "notHighlighted" as a parameter, rather than the regular one-line initializer. Right?

Speculation Aside, this works. From my console, I can see two "text" instances are constructed, one for "highlighted" and one for "notHighlighted". Once the texts are constructed, they remain as they should and render as they should later on in the code.

However, this isn't what I want... Instead of passing an SDL_Color into the constructor and having buttonObj turn the color into text, (via constructing it)  I want to load some text beforehand (elsewhere during runtime) and pass the text into buttonObj directly. Like so:

string textContent;
text buttonText;
text highlighted_buttonText;

//Constructor
buttonObj(string tex, text notHighlighted, text highlighted) :
  textContent( tex ),
  buttonBase( img ),
  buttonText( notHighlighted ),
  highlighted_buttonBase( hI ),
  highlighted_buttonText( highlighted )
{}

According to my knowledge of what one line initializers are SUPPOSED to do, "highlighted_buttonText" should become equal to the parameter "highlighted." So "highlighted_buttonText" is set to whatever the parameter "highlighted" is, since they're both of type "text"

However, this doesn't work. In my console, I see that the texts are constructed and then destructed! As if something is calling the destructor... this means that the variables don't work fine later on in the code. (And then I get a bunch of exceptions in the library I'm using for text rendering. It's a text chaching library based on SDL_TTF called SDL_FontCache)

I know this is a hard issue to explain and I might not be describing it well. But please, any advice would be awesome! Weird problems like this irk me...


texts: Unity mobile game generates too much cache

texts:
I have built a game I have been working on for Android (Unity). It's a simple game: air hockey. It weights 21mb with all the assets and scripts.

After playing for a bit I have noticed that cache of the game is growing very fast and probably infinitely (to use all phone memory). The game itself takes 43.20mb installed. But cache for me right now is 80mb.

I have similar games installed and they take up to a 6mb max. And definitely, the cache is growing slower for them.

Previous games that I have developed doesn't have this issue. For example, the game that takes 80mb disk space has only 532KB of cache and it's not growing.

I thought of manually clearing the cache every time player leaves the game. I haven't found any relative information on how to do that in unity, but that is probably even not the right way to do it. All I have found is how to delete GI cache... and the google search doesn't show anything relevant.

How can I track what is creating so much cache? Is there an easy way to do it within Unity? Or how can I request cache deletion from code?


texts: What is the most efficient way to access resources?

texts:
I have a resource manager that loads and returns resources. Currently, I just return shared_ptrs for the resources I create, but I'm thinking about going over to using something like simple handles, whereby you get an ID you use to access the resource. The reasons are more explicit ownership, and also less overhead, rather than using smart_ptrs.

Are resource handles the most efficient way to access resources, should I stick with shared_ptrs or are there other alternatives?

The reason I am asking is that I was reading this article, which made me wonder if I should implement something like that, instead.


texts:
I'm working on a plugin for Unity that takes data extracted from a 2D animation software and convert them to work with Unity Animator.

I'm blocked with the "skew" property. Here are the data I got in the animation software when I skew my object on Y axis.

And here is what a custom (very artistic) drawing looks like:

After few manual tests in Unity I know it's possible, with 3D rotations and 2D scale to get the same result.

However I can't understand the mathematical logic behind the input and the needed output (my knowledge in mathematics is limited). Do you know how I can convert a skew into 3d transformations (rotation + scale)?

Any help would be greatly appreciated.


texts: how to make client and server to develop independently?

texts:
Currently,  all i want to do is rapid prototyping of Tower-Defense-Like game, which means that i just need write client code only,single player, play with AI system. but shortly afterwards, maybe it's going to be a multiplayer game .
my question is how can i design my game architecture suited for singleplayer mode firstly, and for multiplayer mode latterly, it doesn't mess up my previous effort(single player only). any design pattern, or architecture , or hint?

I really appreciate for your answer, thank your guys in advance.
Have a good day!


texts: Lost transparency in SDL surfaces drawn manually

texts:
I want to create SDL_Surface objects for each layer of my 2d tile-based map so that I have to render only one surface per layer rather than too many tiles. With normal tiles which do not have transparent areas this works well, however I am not able to create a SDL_Surface with transparent pixels everywhere to be able to draw some tiles on specific parts which should be visible (I do NOT want the whole surface to appear with a specific opacity - I want to create overlaying tiles where one can look through).

Currently I am creating my layers like this to draw with SDL_BlitSurface on them:

SDL_Surface* layer =
    SDL_CreateRGBSurface(
        SDL_HWSURFACE | SDL_SRCALPHA,
        layerWidth, layerHeight, 32, 0, 0, 0, 0);

If you have a look at this screenshot I have provided here

you can see that the bottom layer with no transparent parts gets rendered correctly. However the overlay with the tree tile (which is transparent in the top left corner) is drawn own its own surface which is black and not transparent as expected. The expected result (concerning the transparency) can be seen here

Can anyone explain me how to handle surfaces which are actually transparent rather than drawing all my overlay tiles separately?


texts: SpriteBatch being drawn outside of Stage?

texts:
Currently working on my first game, though running into some problems with libgx and screen aspect ratio.

What I have is a Stage which contains things like menu buttons etc, and the rest of the game is pretty much sprites being drawn with via SpriteBatch. To avoid having multiple SpriteBatches and cameras, I have re-used the ones that are created when Stage is created.

    stage = new Stage(WIDTH, HEIGHT, true); // keep aspect ratio
    batch = stage.getSpriteBatch();
    camera = (OrthographicCamera) stage.getCamera();
    // move camera so 'active' screen is centred
    stage.getCamera().translate(-stage.getGutterWidth(), -stage.getGutterHeight(), 0);

Anything that is Stage/Actor related is drawn fine - all goes within the aspect ratio adjusted boundaries.

The problem I'm having is anything that drawn via SpriteBatch, seems to ignore this viewport that is defined by Stage and can be visible outside of the Stage area.

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

For example, in the above, if Sir Wuffles is generated outside of the defined WIDTH/HEIGHT it might still appear in the "gutters" of the screen.

Tried to explain it in the below screenshot. It's an exaggerated screen ratio to make the gutters large. I've also covered most of the gutter area in the blue/cyan rectangle so they are very obvious.

Does anyone know what is happening? and how to fix it?

Currently, my "fix" is to use ShapeRenderer to draw rectangles that correspond to the gutters on top of the sprites...


texts: How to make a gameObject follow non trivial trajectories?

texts:
as the title of the question says, I was wondering if there is common method to make gameObjects e.g. enemies or bullets follow curvilinear trajectories before reaching their target. For instance, assuming to be talking about a top-down 2D game, there are multiple ways to make an gameobject, say an enemy follow a straight line like this to go hit the player:

But how to make it so that before reaching the player it would do something like this?

Does somebody have an idea?

I know that the question may sound not too specific, therefore for sake of argument, how could I make so that a bullet shot from an enemy follows an arch "à la Wanted" before hitting the player instead of just flying straight?


texts: Unity: why game app on Android takes up much more memory than Unity Profiler reports?

texts:
We are profiling a game app on Android 4.4.2 device via Unity’s ADB profiling.

We have set up ADB profiling following the official guide: http://docs.unity3d.com/Manual/Profiler.html

The ADB profiling works fine, when the app is running, Unity Profiler reports its memory usage as following:

Used Total: 100.4 MB  Unity: 40.5 MB  Mono: 10.1 MB  GfxDriver: 34.9 MB  FMOD: 3.9 MB  Profiler: 14.8 MB
Reserved Total: 112.8MB  Unity: 47.0 MB  Mono: 15.4 MB  GfxDriver: 34.9 MB  Profiler: 15.5 MB

Meanwhile, we are also running another performance test tool (i.e. Emmagee, https://github.com/NetEase/Emmagee) to monitor the app, which can monitor CPU, memory, network traffic, battery current and etc. However, the memory usage of the app reported by Emmagee tool is much larger:

As shown above, Unity Profiler reported 112.8M memory is totally reserved for running the app, but Emmagee tool reported >200M PSS memory is used. Obviously, more than 90M memory taking up is happened somewhere by something that Unity Profiler does not take into account.

(We also tried other performance monitoring tool for Android apps, e.g. APT, and the result is similar to what Emmagee reported. The extra memory usage problem remains.)

We noticed that the Unity Profiler itself would take up ~15M memory, which is included in the profiler’s report. Also, we knew that PSS memory includes proportional shared libraries with other processes, but 90M+ extra is such large amount considering that Unity Profiler only reported 112.8M totally.

Our puzzle remained: Where does the 90M+ memory come from? How are they used by the app? Why Unity Profiler does not report the extra memory? What can we do for reducing the extra memory and the total PSS memory of the running app, and/or get it close to what Unity Profiler reports?

Any help could be appreciated!


texts:
Sometimes a "real" random event seems unfair and makes players frustrated. For instance a enemy has probability of 20% to cause double damage("critical hit"). Thus he could make 4 critical hits in a row with 1/725 probability. It's not as small as it sounds.

I hope the probability could be adjusted after each hit. If the player just got a critical hit, the probability decreases for the next hit. Otherwise it increases.

Is there a mathematical model for this behaviour?


texts:
I've been focusing on other games recently but it annoyed me that I skipped the AI part of making my pong game a 1 player game too. I have found out how to RayCast but am struggling with being able to make a path to predict where the ball will end up on the computer side. I have managed to get the first ray to work but in the second if-statement from the code below, it's somehow a loop. If anyone is able to help me, I would be extremely grateful!

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

public class RaycastTest : MonoBehaviour {

private Rigidbody2D rb2d;
private RaycastHit2D hit;
private Vector2 predictedCollision;
private Vector2 collisionPoint;
private int numberOfCollisions;

void Start () {
    rb2d = GetComponent<Rigidbody2D> ();
    numberOfCollisions = 0;
}

void FixedUpdate () {
    //Directions of the ball (normalized)
    Vector3 forward3 = new Vector3 (rb2d.velocity.normalized.x, rb2d.velocity.normalized.y, 0) * 20;
    Vector2 forward2 = new Vector2 (rb2d.velocity.normalized.x, rb2d.velocity.normalized.y);

    // If the ball has just hit the player paddle
    if (BallMovement.isOnPath == true) {
        if (numberOfCollisions == 0) {
            //make sure we have the correct initial collision point from another script
            collisionPoint = BallMovement.collisionPoint;

            //draw and cast a ray to detect the next point of collision
            Debug.DrawRay (collisionPoint, forward3, Color.red, 20f);
            hit = Physics2D.Raycast (collisionPoint, forward2, Mathf.Infinity);
            //print the name of the object that has been hit
            print (hit.collider.name);

            //change the initial collision point to the new one
            collisionPoint = new Vector2 (hit.point.x, hit.point.y);
            print (collisionPoint);

            //add on to the number of collisions
            numberOfCollisions += 1;
            print (numberOfCollisions);
        }

        //if we still haven't reached the HitArea we need to do another bounce
        if (hit.collider.name != "HitArea") {

            //make sure we get the velocity after impact and reverse the direction of the y velocity.
            forward2 = new Vector2(rb2d.velocity.normalized.x, rb2d.velocity.normalized.y * -1f);
            forward3 = new Vector3 (rb2d.velocity.normalized.x, rb2d.velocity.normalized.y * -1f, 0) * 20;

            //draw and cast a ray to detect the next point of collision
            hit = Physics2D.Raycast(collisionPoint, forward2, Mathf.Infinity);
            Debug.DrawRay(collisionPoint, forward3, Color.red, 20f);

            //change the initial collision point to the new one
            collisionPoint = hit.point;
            print (collisionPoint);

            //add on to the number of collisions
            numberOfCollisions += 1;
        }

        //If we've hit the HitArea, we reset everything so it stops looping and we've got our predicted point of collision on the computer side.
        if (hit.collider.name == "HitArea") {
            predictedCollision = hit.point;
            numberOfCollisions = 0;
            BallMovement.isOnPath = false;
        }
    }
}

}


texts: Creating and Destroying OpenGl objects dynamically

texts:
I was trying to build a game like this

and i want to create and destroy these ships at runtime ,
I have used GL_QUADS and used an image to plot over the QUAD,
how can I dynamically create multiple Quads,paste (ship) image over them and destroy them when they collide with the canon ball, thanks

here is a chunk of code

ship = SOIL_load_OGL_texture(
        "ship2.png",
        SOIL_LOAD_RGBA,
        SOIL_CREATE_NEW_ID,
        SOIL_FLAG_INVERT_Y
        );
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glColor3f(1, 1, 1);
    glBindTexture(GL_TEXTURE_2D, ship);
    glBegin(GL_QUADS);
    glTexCoord2d(0, 0);
    glVertex2d(450 - x, 0);
    glTexCoord2d(1, 0);
    glVertex2d(500 - x, 0);
    glTexCoord2d(1, 1);
    glVertex2d(500 - x, 100);
    glTexCoord2d(0, 1);
    glVertex2d(450 - x, 100);
    glEnd();


texts: Would I perform one pass per effect in Deferred Shading?

texts:
I'm implementing deferred shading the first time. Doing so I came up with a conceptual question.

First I render the geometry in a framebuffer with muptiple rendering targets for depth, normals, and so on. Say that I want to apply several post effects, I think I have two options now. I could either render a quad with the depth, normals, ... texture to the screen buffer once applying all effects in that pass. Or I could perform one render pass to another framebuffer for each effect and lastly combine those effect in a pass to the screen buffer.

Would both ideas work and if so what is the common approach?


texts:
I sometimes run into small issues when doing my JavaScript projects.
That is because most build in functions of JavaScript run  X,Y if positions are needed. (In that order).

But when I build a 2D Array I start out with Y, it seems more logical for me to to run the X axis horizontal. If I am bad at explaining it, let me show you:

So my loops look like this:

for(var y = 0; y < 10; y++){
    for(var x = 0; x < 10; x++){
        console.log("Doh!");
    }
}

Is this so insane?
I would like to convert to the normal practise so that I have an easier time while building my game and don't have to do constant switcherroos.

So why is it X before Y ?

Edit:
Here is another example, and probably the main reason for my confusion:
X is Horizontal, and Y is Vertical in my books..

[
[0,1,2,3,4],
[0,1,2,3,4],
[0,1,2,3,4],
[0,1,2,3,4],
]


texts: Is it possible to move a parent object independent of the child object

texts: I need to be able to move a Parent Object without moving the Child Objects.


texts: How to implement the “technological tree” drawing?

texts:
I want to make a tech tree at least like in Civilization, but I don't know how to do it. I want to fill in some data structure and then display it on the screen in the form of a technology tree, but I don't know how to implement it in code.
The only way I came up with was:
public class Technology1
{
String name;
TextButton button;
LinkedList<Technology1> NextTech;
}

TextButton is the libGDX class with which I was going to display each individual technology on the screen.
LinkedList NextTech- all technologies that are accessed after studying the current one are stored here. In other words, "children" are stored here .
The problem is how to set the coordinates for all technologies when rendering the tree, so that the technologies do not overlap when displayed and so that the whole looks more or less normal.
If I started to do it wrong, then please tell me a more correct option.


texts: Bullets won't shoot out of barrel in top-down shooter

texts:
So I am working on a top down shoot and have been stumped on why my bullets refuse to come out of the barrel of the gun. I know about the rotation equation which is

x2 = x * cos(theta) - y * sin(theta)
y2 = x * sin(theta) + y * cos(theta)

Here is part of my shoot method for my shotgun

    float dx = (float) (5 * Math.cos(direction) + 40 * Math.sin(direction));
    float dy = (float) (5 * -Math.sin(direction) + 40 * Math.cos(direction));

    //PlayState.effects.add(new MuzzleFlashEffect(x + dx, y + dy, (float) Math.toDegrees(-direction)));

    for(int i = 0; i < randNum; i++){
        float var = MathUtils.random(-accuracy, accuracy);
        float dir = direction + (float) Math.toRadians(var);
        PlayState.projectiles.add(new Bullet(this, x + dx, y + dy, dir));
    }

    bulletsInClip--;
    lastShot = System.currentTimeMillis();

The bullets always tend to shoot out of the left side and I don't have a clue why. The player sprite origin is the center and not the top left but I can't get it shooting out of the barrel.

Can someone explain why this is happening and how I can fix this. I have spent too many hours and losing my sanity.

Thanks in advance!

EDIT

Here are some pictures of the character shooting in different directions

RIGHT

LEFT

DOWNWARD


texts: What kind of projection is demonstrated in this screenshot?

texts:
I want to know what projection is used in the following game:

The game is Goodgame Empire.


texts: Season system Implementation system in unity

texts:
So I am planning on implementing a seasons system for a 2D top-down game. Each season will have a characteristic terrain feature e.g. summers will have patches of grass spread out .. which I wanna reproduce by green bloat spread around on a 2D plane or quad...  These features will need to generate dynamically for every season. The implementation will be simplistic nonetheless... using green bloats for grass patches, blue bloats for waterholes.. Can you guys give me like pointers to solve this problem?

Some Reference images:-

Notice how the backdrop/background changes for each season
Green Patches denotes grass
Light blue denotes unfrozen water, dark blue denotes frozen water
These bloats are to be generated dynamically, with some conditions like frozen water and unfrozen water need to spawn next to each other

Summer Season #### Monsoon Season #### Winter Season ##


texts:
I'm trying to implement reflections on flat surfaces and render a simple scene with a reflection. So I'm rendering the scene from the point of view of a camera symmetrical to the reflection plane and then I pass the resulting rendered scene as a shader resource to the shader that renders the quad and I use projectiv texturing by sampling the texture using the quad screen space coordinates mapped to 0 - 1:

Texture2D quadTexture;
SamplerState textureSampler;

struct PS_Input
{
    float4 pos : SV_Position;
    float2 texCoords : TEX_COORDS;
    float4 clipPos : CLIP_POS;
};

float4 main(PS_Input input) : SV_Target
{
    float2 projectiveCoords = (float2)0;
    projectiveCoords.x = (input.clipPos.x / input.clipPos.w + 1.0) / 2.0;
    projectiveCoords.y = (-input.clipPos.y / input.clipPos.w + 1.0) / 2.0;
    float4 color = quadTexture.Sample(textureSampler, projectiveCoords);
    color.a = 0.2;
    return color + float4(0.0, 0.01, 0.01, 0.0);
}

I assume that since the y and the v axis are inverted with respect to each other that I need to negate the second texture coordinate (and all the code I saw on the net do so).  But my code only works if I DON'T negate the second coordinate. If I negate the second coordinate the reflection is upside down:

The way I compute the reflected camera is I calculate the symmetric direction vector and use it in XMMatrixLookAtLH(). So when I calculate a new direction vector with a horizontal plane I should get a symmetric direction vector and the same right vector so my image is non mirrored on the horizontal axis. All works well when I don't invert the sign which is strange.

EDIT

I was not considering the fact that when rendering reflection on an horizontal plane, I have to take into account that the image being rendered is upside down with respect to the image I need to render on the surface. Not inverting the second projective texture coordinate has the effect of inverting the image (DirectX's v axis goes downwards, while projective texture coordinate y goes upwards). So when rendering a reflection on an horizontal surface I need not negate the coordinate. I need to negate both when rendering on a vertical surface (I always compute the symmetric camera direction vector and use the same world Up vector to compute the "reflected" view matrix):

float4 main(PS_Input input) : SV_Target
{
    float2 projectiveCoords = (float2)0;
    projectiveCoords.x = (input.clipPos.x / input.clipPos.w + 1.0) / 2.0;
    projectiveCoords.y = (input.clipPos.y / input.clipPos.w + 1.0) / 2.0;
    if (normal.y == 0)
    {
        projectiveCoords.x = -projectiveCoords.x;
        projectiveCoords.y = -projectiveCoords.y;
    }
    float4 color = quadTexture.Sample(textureSampler, projectiveCoords);
    color.a = 0.2;
    return color + float4(0.0, 0.01, 0.01, 0.0);
}

Now I have a new question:
everything is fine if I want to render a reflection on an horizontal plane or a vertical one. How can I render a reflection on an (arbitrarily) incined surface? using the same calculations doesn't work anymore.


texts:
I have two pixes stored in a 32 bit unsigned integer (4 bytes per pixel, using SDL's types for convenience):

Uint32 pixel1;        // Source pixel, format: SDL_PIXELFORMAT_BGRA8888
Uint32 pixel2_format; // Format of the pixel2 (can change)
Uint32 pixel2;        // Destination pixel

How can I convert the format from pixel1 to pixel2?


texts:
Sometimes you'll see people recommend that rather than using graphics/sound files/etc. like this...

// Game code
Image myImage = new Image("path/to/image.png");

... you should use a manifest file as a level of indirection instead:

// Manifest file
MY_IMAGE: path/to/image.png

// Game code
Manifest myManifest = new Manifest("path/to/manifest");
Image myImage = myManifest.getImage("MY_IMAGE");

What reasons would I have of taking this sort of approach? If I'm not using a compiled language, would there still be reasons to do this?


texts: how to join the body of snake in 2D snake game

texts:
i'm making a snake game in javaScript from scratch. The problem is that the snake looks disjoint(see image). How can I connect the body(rectangles) of the snake?

here is the code of drawing snake:

    paintSnake(margin) {
    //draws the body of the snake
    this.snake.forEach((egg) => {
      //console.log(egg)
      const isSnakeHead = egg.cellX === this.headCellX && egg.cellY === this.headCellY
      if (!isSnakeHead) {
        this.ctx.fillStyle = "#9ef739"
        this.ctx.fillRect(egg.cellX * this.cellSize + margin,
          egg.cellY * this.cellSize + margin,
          this.cellSize - 2 * margin,
          this.cellSize - 2 * margin)
      }
    })
    //snake head
    // this.ctx.beginPath()
    // this.ctx.lineWidth = 4
    // this.ctx.strokeStyle = "red"
    // this.ctx.rect(this.headCellX * this.cellSize + margin, this.headCellY * this.cellSize + margin, this.cellSize - 2 * margin, this.cellSize - 2 * margin)
    // this.ctx.stroke()
    let head =
    {
      X: this.headCellX * this.cellSize + margin,
      Y: this.headCellY * this.cellSize + margin,
      width: this.cellSize,
      height: this.cellSize
    }

    const args = [head.X,
    head.Y,
    head.height,
    head.width]
    //draw the head of the snake
    if (this.direction === "up") {
      this.ctx.drawImage(
        snakeHeadUpImg,
        ...args)
    }
    else if (this.direction === "down") {
      this.ctx.drawImage(
        snakeHeadDownImg,
        ...args)
    }
    else if (this.direction === "right") {
      this.ctx.drawImage(
        snakeHeadRightImg,
        ...args)
    }
    else if (this.direction === "left") {
      this.ctx.drawImage(
        snakeHeadLeftImg,
        ...args)
    }
  }
}

to see the whole code go to: https://github.com/hackasaur/snake-game/blob/master/main.js

i know that the rectangles(body parts) need to be extended in the direction of the next rectangle but how can i achieve this?


texts: How to initiate a TCP secure connection using LibGdx to a remote server?

texts:
Can anyone point to a link or share with me a piece of code which does:
- Base on LibGdx (Gdx.net package)
- Use a TCP secure connection to connect to a remote server

Many thanks


texts: Efficient method for Sprite Stacking in LibGDX

texts:
What would be a very efficient method for creating a suede 3D effect by stacking sprites much like the game like NIUM in LibGDX
I find it easy to create a rudimentary system that stacks textures in a sprite batch and rotate them accordingly but a system where each texture has to have it's rotation updated and then drawn with the sprite batch isn't a very efficient way to create such an effect. It tends to struggle for larger scenes and for large objects with many sprites to create this effect seems to bring it to its knees.


texts: Box2d making a body follow the mouse accurately

texts:
I am trying to make a box2d b2Body follow my mouse position. This is the code I am using at the moment but it is not performing very well:

deltaPos = mousePos - body->GetPosition();
deltaPos *= k;
body->ApplyForce(deltaPos, b2Vec2(0, 0));

I have tried playing with k but the body either lags too far behind the mouse or flies round and round the mouse like crazy. Should I be using an exponentiation there instead of multiplication? I am scared of applying too much force and breaking the sim (I suppose I could use a max).

Is there a more straightforward way to do this?


texts: Mesh distorted during animations exporting from Blender + Rigify to Unity 2020

texts:
I finished my first 3D Character with a couple of animations using Blender 2.8 and Rigify.
I'm exporting it to Blender as FBX file and everything seems to work. The only problem I have is with the Walk animation. There are points where the mesh of my character just starts to deform when I play the animation in Unity.
Here you can see the differences between Blender and Unity:

Export Settings:

What am I doing wrong? In Blender, everything works properly and there are no deformations.


texts:
I have a game with a beat-em-up perspective (think Final Fight, Streets of Rage) where movement is in X and Z. My movement logic consists of checking controller input of X-axis for X movement and Y-axis for Z movement. I use this logic to move enemy as well, using this method:

internal bool MoveTowardsPosition(Vector3 targetPosition)
{
    bool reachedPosition = false;
    bool reachedX = false;
    bool reachedZ = false;

    // Determine x direction
    if (Mathf.Round(Mathf.Abs(targetPosition.x - _enemy.transform.position.x)) > 0)
    {
        if (targetPosition.x < _enemy.transform.position.x)
            Input.HorizontalMove = -1;
        else
            Input.HorizontalMove = 1;
    }
    else
        reachedX = true;

    // Determine z direction
    if (Mathf.Round(Mathf.Abs(targetPosition.z - _enemy.transform.position.z)) > 0)
    {
        if (targetPosition.z < _enemy.transform.position.z)
            Input.DepthMove = -1;
        else
            Input.DepthMove = 1;
    }
    else
        reachedZ = true;

    if (reachedX && reachedZ)
        reachedPosition = true;

    return reachedPosition;
}

So what happens here is that given a target position, I add to the HorizontalMove (X) and DepthMove (Z) until the enemy reaches the destination (these X and Z additions will be read on Update to do a transform.translate()). The enemy does move to the destination but in a unnatural path. So when Z is larger, it will reach the destination X first then traverse Z. So for example, X=2 and Z=5, it'll traverse with a path like this:

What I'm trying to do is for it to traverse a path like this:

I figured instead of adding fixed 1/-1, I need to determine X and Z based on that angle but I'm lost on how to compute/do it. Can you guys lend me a hand, please?


texts:
I'm in the midst of developing a 2D sprite-based game for Windows 7 Phone, using XNA. The training and tutorials available for it are pretty helpful, but the problem I face is that each of them approaches their class design differently, and the code is not particularly well-factored. As a result, it has been difficult for me to gain a good understanding of which responsibilities I should give to a particular class.

For example, I could have a base sprite class BaseSprite that knows how to draw itself, check for collisions, etc. I could then have an AnimatedSprite class that would know how to navigate its sprite sheet, an ExplodingSprite class, and so on. This technique is demonstrated in the Space Invaders example in the Windows 7 Phone Jumpstart Session 2 materials.

Alternatively, I could instead place the bulk of rendering and running the game responsibility in a GameScreen class; that class and its derived classes behave more like forms or web pages in terms of their responsibilities. Sprite classes are more simple containers with much less logic.

This is the technique used in the Windows 7 Phone Training Kit's Alien Sprite game and other game state manager examples.

What is the correct object-orientated approach to class design in game development?


texts:
What in the BOTW game engine makes physics behave wildly when certain actions are triggered during bullet-time?
https://www.youtube.com/watch?v=dXKsTrwZ6XY
Also, what can you do to prevent it? Is this problem unavoidable when you include bullet-time?


texts: OOP architecture problem between Camera, Player, Weapon

texts:
I am making an FPS game in Unity, trying to keep myself to OOP principles as much as I can but I found dead-end.
I want to add recoil to my game, now logically thinking the amount of recoil should be stored in the Weapon instances, but the recoil itself should be done by the Camera. The problem here, it doesn't make sense for the weapon to have a dependency towards the Camera, I think this could cause trouble down the line. I thought of making an Action (observer pattern), where the Weapon is a broadcaster while the Camera is an observer.
The problem here is there will be multiple players, so the Camera instance shall know if it's their Player who made the shot (the weapon would broadcast it's Player reference as well), so in order to do this, every Camera should store a reference to their own Player which again brings the problem I described with the gun. The Camera shouldn't have a reference to its player, for example, if I later want to add the ability to spectate a game, this would cause problems.

So the Player can have a Camera dependency
The Camera shouldn't have any dependencies
The Weapon can have a Player dependency

How would one go about implementing this recoil, how could I avoid the problems I've described?


texts:
I've run into an issue that breaks my collisions. Here's my method:

Gather Input
Project Rectangle
Check for intersection and ispassable
Update

The update method is built on object_position * seconds_passed * velocity * speed. Input changes velocity and is normalized if > 1.

This method works well with just one object comparison, however I pass a list or a for loop to the collision detector and velocity gets changed back to a non zero when the list hits an object that passes the test and the object can pass through.

Any solutions would be much appreciated. Side note is there a more proper way to simulate movement?


texts: Single pass separable gaussian blur problem

texts:
I created a single pass gaussian blur using HLSL compute shader. I also want it to be separable, which means, that first I perform blur along the horizontal direction, write out the result to the texture, then perform the vertical blur with the horizontally blurred data.

I do this by creating DeviceMemoryBarriers before and after writing out the blur results to the globallycoherent Texture2D.

This is my shader:

Texture2D<float4> input:register(t0);
globallycoherent RWTexture2D<float4> input_output:register(u0);

// Note: Shader requires feature: Typed UAV additional format loads!
[numthreads(16, 16, 1)]
void main(uint3 DTid : SV_DispatchThreadID)
{
    // Query the texture dimensions (width, height):
    uint2 dim;
    input_output.GetDimensions(dim.x, dim.y);

    // Determine if the thread is alive (it is alive when the dispatchthreadID can directly index a pixel)
    if (DTid.x < dim.x && DTid.y < dim.y)
    {
        // Do bilinear downsampling first and write it out:
        input_output[DTid.xy] = input.SampleLevel(sampler_linear_clamp, ((float2)DTid + 0.5f) / (float2)dim, 0);
        DeviceMemoryBarrier();

        uint i = 0;
        float4 sum = 0;

        // Gather samples in the X (horizontal) direction:
        [unroll]
        for (i = 0; i < 9; ++i)
        {
            sum += input_output[DTid.xy + uint2(gaussianOffsets[i], 0)] * gaussianWeightsNormalized[i];
        }
        // Write out the result of the horizontal blur:
        DeviceMemoryBarrier();
        input_output[DTid.xy] = sum;
        DeviceMemoryBarrier();
        sum = 0;

        // Gather samples in the Y (vertical) direction:
        [unroll]
        for (i = 0; i < 9; ++i)
        {
            sum += input_output[DTid.xy + uint2(0, gaussianOffsets[i])] * gaussianWeightsNormalized[i];
        }
        // Write out the result of the vertical blur:
        DeviceMemoryBarrier();
        input_output[DTid.xy] = sum;
    }
}

The problem is that the result flickers a bit, and has some errors in the image, too. Seems a bit like a thread group can't see writes by other groups.

But there is a globallycoherent modifier before the RWTexture2D which should flush the entire resource so that writes are visible in every thread group (MSDN). Indeed, if I remove that modifier, then the flickering becomes a whole lot worse than if I leave it there.

Here is a screenshot of the problem:

(Notice the lines on the windmill, and it also flickers on the whole image from time to time which is not visible on a still shot)

Anyone here has an idea what I can do about it? (PS. the blur is performed when creating mipmaps, so I very much want to avoid multiple passes because it is already one pass for each mip)


texts: How game engines generate single executable games?

texts:
I was taking a look at Cryengine's and Unreal's code and when built both engines generates lots of dlls. Inside Cryengine's System code I could see that it calls LoadLibrary to load the dlls and Initialize the modules.

Ex:. LoadLibrary("CryPhysics.dll")

But when you see Cryengine's or Unreal's deployed games they have only a single big .exe and no first-party dlls. In Crysis 3 Bin32 directory there is only Crysis3.exe and some third-party dlls, there is no CryPhysics.dll for example.

How do they achieve that? How can the LoadLibrary work without those dlls?

PS:. There is no #if wrapping the LoadLibrary to differentiate Debug from Release mode


texts:
I've been trying my best on porting my 3D game from Java to C++, but to no avail.
I use only LWJGL with OpenGL but I cannot find any other library in C++ that supports as much as LWJGL does for Java. Especially on the math part.

For instance.
I'm trying to port this TransformationMatrix maker to C++.

public static Matrix4f createTransformMatrix(Vector3f translation, float rx, float ry, float rz, float scale){

    Matrix4f newMatrix = new Matrix4f();
    newMatrix.setIdentity();
    Matrix4f.translate(translation, newMatrix, newMatrix);
    Matrix4f.rotate((float) Math.toRadians(rx), new Vector3f(1,0,0), newMatrix, newMatrix);
    Matrix4f.rotate((float) Math.toRadians(ry), new Vector3f(0,1,0), newMatrix, newMatrix);
    Matrix4f.rotate((float) Math.toRadians(rz), new Vector3f(0,0,1), newMatrix, newMatrix);
    Matrix4f.scale(new Vector3f(scale,scale,scale), newMatrix, newMatrix);

    return newMatrix;
}

I've tried using Eigen and GLM, but none of them work the same like LWJGL.
Now I wouldn't mind this, but the lack of actual 3D tutorials on OpenGL in C++ is just abysmal.

Any tips or help with even converting this piece of code would be greatly appreciated.


texts: How to make effective permament rubble in a voxel game made in Unity3D?

texts:
I'm working on a semi-voxel game, and I already optimized the voxel structures' meshes by combining and chunking them.

When I destroy a voxel, I spawn a low poly voxel fragment, with a rigidbody and a collider. And then I add an explosion force.

Even if I turn off rigidbodies when they stop moving, or disable overall physics, the amount of separate meshes to render causes a huge fps loss after a few destroyed voxels.

How could I achieve permanent rubbles?


texts:
I've heard the term "perfect imbalance" thrown around a lot, which seems to imply that it is okay for different game options to be strictly superior to others as long as the 'better' options require more player skill to use.

What strategies does one employ, generally, to achieve this? And am I even understanding the principle correctly?


texts:
I'm working on iOS application which is going to include a few unity games.
And I investigate an opportunity to exit from the Unity game to the native iOS app with games list.
I know that the Unity provides methods Application.Quit() and Application.Unload()

I haven't try but I'm not sure that Application.Unload() is correct ways to exit from unity to the native iOS app.


texts: Are there any command line swf packing tools?

texts:
I want to packing image files(png, jpg) into swf, then game can load files easily. But I want to do this by a Makefile, not FLASH CS.
Do you know any command line swf tool set can do that? And can I packing XML files into it as well?


texts: What bones are involved in a walk cycle like Leon's in RE4?

texts:
I would like to create a character that moves like Leon in RE4. This video demonstrates Leon's walk cycle, which I'd like to reproduce. I'm confused about which bones of my character's skeleton should be rotated to achieve the desired cool "sideways" look.

At first I thought that his feet and hip are not rotated at all and that only his abdomen was rotated. But after watching the above video (for example at 00:20) where a camera FOV hack was applied and one can finally see his lower body, I'm not sure anymore.

How has this walk cycle been created? Did they take a walk-straight-forward-animation and then rotated some bones? If yes, which ones?
I guess somebody who has a great eye for animations can see that.

Thank you.


texts:
I have a server-client setup where each client has a number of screens attached, and the screens together form the display. As such, the visuals displayed by each client needs to be roughly in sync. Luckily the domain is not high speed, so I don't have to have them all perfectly in sync, but obviously more in sync is better.
The physical network: About 10 clients need to be synced together. All clients that need to be synced are on the same gigabit LAN, latency is sub 1ms.
The network protocol: Clients are running 100ms behind real time (so there is a 100ms buffer for the server to send out updates).
The digital environment: Realistic environments moving at generally a slow speed (think rate of turn in the order of 10 degrees/minute generally, however it's possible to increase up to maybe 720 in extreme circumstances).
Requirements: There should be as little visible lag between clients as possible.
Requirements for answers: A concept is enough, pointing out the limitations or advantages to different methods would be appreciated. It would be great if it's something you've tried and had failures or successes with in the past, but spit-balling is ok too.
What a good answer would look like: "Using NTP is fine up to X ms or syncing Y clients, but if you need more accuracy than that you should look into doing Z". It doesn't need to be crazy in depth!


texts: Box2D Difference Between WorldCenter and Position

texts:
So this problem has been brothering for a couple of days now.  First off, what is the difference between say Body.getWorldCenter() and Body.getPosition().  I heard that WorldCenter might have to do with the center of gravity or something.

Second, When I create a Box2D Body for a sprite the Body is always at the lower left corner.  I check it by printing a Rectangle of 1 pixel around the box.getWorldCenter().  From what I understand the Body should be in the center of the Sprite and its bounding box should wrap around the Sprite, correct?

Here's an image of what I mean (The Sprite is Red, Body Blue):

Here's some code:

Body Creator:

    public static Body createBoxBody( final World pPhysicsWorld, final BodyType pBodyType,
            final FixtureDef pFixtureDef, Sprite pSprite ) {

        float pRotation = 0;
        float pCenterX = pSprite.getX() + pSprite.getWidth() / 2;
        float pCenterY = pSprite.getY() + pSprite.getHeight() / 2;
        float pWidth = pSprite.getWidth();
        float pHeight = pSprite.getHeight();

        final BodyDef boxBodyDef = new BodyDef();
        boxBodyDef.type = pBodyType;

        //boxBodyDef.position.x = pCenterX / Constants.PIXEL_METER_RATIO;
        //boxBodyDef.position.y = pCenterY / Constants.PIXEL_METER_RATIO;

        boxBodyDef.position.x = pSprite.getX() / Constants.PIXEL_METER_RATIO;
        boxBodyDef.position.y = pSprite.getY() / Constants.PIXEL_METER_RATIO;

        Vector2 v = new Vector2( boxBodyDef.position.x * Constants.PIXEL_METER_RATIO, boxBodyDef.position.y * Constants.PIXEL_METER_RATIO );
        Gdx.app.log("@Physics", "createBoxBody():: Box Position: " + v);

        // Temporary Box shape of the Body
        final PolygonShape boxPoly = new PolygonShape();
        final float halfWidth = pWidth * 0.5f / Constants.PIXEL_METER_RATIO;
        final float halfHeight = pHeight * 0.5f / Constants.PIXEL_METER_RATIO;
        boxPoly.setAsBox( halfWidth, halfHeight );  // set the anchor point to be the center of the sprite

        pFixtureDef.shape = boxPoly;

        final Body boxBody = pPhysicsWorld.createBody(boxBodyDef);
        Gdx.app.log("@Physics", "createBoxBody():: Box Center: " + boxBody.getPosition().mul(Constants.PIXEL_METER_RATIO));
        boxBody.createFixture(pFixtureDef);

        boxBody.setTransform( boxBody.getWorldCenter(), MathUtils.degreesToRadians * pRotation );

        boxPoly.dispose();

        return boxBody;
}

Making the Sprite:

    public Car( Texture texture, float pX, float pY, World world ) {

        super( "Car" );

        mSprite = new Sprite( texture );
        mSprite.setSize( mSprite.getWidth() / 6, mSprite.getHeight() / 6 );
        mSprite.setPosition( pX, pY );
        mSprite.setOrigin( mSprite.getWidth()/2, mSprite.getHeight()/2);

        FixtureDef carFixtureDef = new FixtureDef();

        // Set the Fixture's properties, like friction, using the car's shape
        carFixtureDef.restitution = 1f;
        carFixtureDef.friction = 1f;
        carFixtureDef.density = 1f; // needed to rotate body using applyTorque

        mBody = Physics.createBoxBody( world, BodyDef.BodyType.DynamicBody, carFixtureDef, mSprite );
}


texts: Java applet game design no keyboard focus

texts:
THIS IS PROBABLY THE WRONG PLACE. POSTED ITHERE (STACKOVERFLOW)

I'm making an applet game and it is rendering, the game loop is running, the animations are updating, but the keyboard input is not working. Here's an SSCCE.

public class Game extends JApplet implements Runnable {

    public void init(){
        // Initialize the game when called by browser
        setFocusable(true);
        requestFocus();
        requestFocusInWindow();  // Always returning false
        GInput.install(this);    // Install the input manager for this class
        new Thread(this).start();
    }

    public void run(){
        startGameLoop();
    }

}

And Here's the GInput class.

public class GInput implements KeyListener {

    public static void install(Component c){
        new GInput(c);
    }

    public GInput(Component c){
        c.addKeyListener(this);
    }

    public void keyPressed(KeyEvent e){
        System.out.println("A key has been pressed");
    }

    ......

}

This is my GInput class. When run as an applet, it doesn't work and when I add the Game class to a frame, it works properly.

Thanks


texts: Camera changes view when controller connected

texts:
I have a weird situation. I have a model set to 0 for X,Y and Z. My camera's position is set to:

0 (X-value, but updates when the model moves around)
the model's height + 20f (about the same level as the model's
shoulders)
25f (behind the model)

Without the controller plugged in, everything looks fine as I want it. But as soon as I plug the controller in, the camera aims to the sky! But when I unplug the controller, the camera is back to what it should be.

Does anyone have any insight as to what may cause this from plugging a controller in?


texts: deformable and variable text on a mesh in unity

texts: So I am working on a sports game and I want the jerseys to be customizables with names and numbers. I have the character models as a single mesh however I can't place a text on the back of the jersey for the player to customize. I've found that unity has a Text Mesh, however it is not deformable. When the player runs, the number and name instead of being glued to the shirt actually appear more as a sign attached to the avatar's back. How can I do this text on the players jerseys, that can change its value via user input and to have the properties of the shirt object?


texts: What parts of a GPL game engine must be released?

texts:
I'm hoping I can clarify this issue.

Note, a similar question has been asked here, but it doesn't really give a specific enough answer that I can comprehend at this point! :- How does one escape the GPL?

I plan to use a game engine that has been released under GPL to develop a MMOG, and I plan to distribute the client for free. I'm concerned that when it comes time to release my game, I'm going to have to release the entire source code under GPL, which opens my game to risk of abuse, where someone can learn how to potentially hack my game client and give them an unfair advantage etc.

If I understand GPL, I only need to distribute code that I've edited directly. In the case of Java, I can extend the available classes, do to what I need them to do, rather than go back and make edits in the classes themselves. If i'm using the original code in this way, do I just need to point out that the code is available from the engine developers

Does extending a class constitute 'editing the source?'


texts: Game planning and software design? I feel that UML is not convenient

texts:
In my university, they always emphasize and hype about UML design and stuff, in which I feel it is not going to work well with game structure design. Now, I just want a professional advice on how should I begin my game designing? The story is I have some skill in programming and have done many minor game such as getting some 2D platformer working to some extend. The problems that I find about my program is the poor quality design. After coding for a while, things start to break down due to poor planning (When I add new feature, it tends to make me have to recode the whole program). However, to plan everything out without a single design flaw is a bit too ideal. Therefore, any advice to how should I plan my game? How should I put it into visible pictures, so that me and my friends are able to overview the designs?

I planned to start coding a game with my friend. This is going to be my first teamwork, so any professional advices would be a pleasure. Is there any other alternatives than UML?

Another question is how does "prototyping" normally looks like?


texts: Is there a way to get relative center of a Rect object in pygame?

texts:
Now, suppose I always want to draw a circle at the center of a rect object, now, the problem is:

For example, if I do

pygame.draw.circle(Surface, BLUE, Surface.rect.center, radius, width=3)

This will and does fail because Surface.rect.center is actually the coordinates of the center of the Rect object relative to the (0,0) point -top left corner- of the display screen, not relative to the (0,0) point of the Rect object. However, the draw() function works relative to the Surface coordinate axis.

As far as here, those are my knowledge and I just think so, might be wrong in some aspects, if so, please let me know.

So, I can solve this simply by replacing Surface.rect.center, with:

(Surface.rect.width // 2, Surface.rect.height // 2)

However, I wonder, is there a way to get that center coordinate of the Rect object relative to its (0,0) point(origin) ?


texts: Sprite Kit - keeping character level with the terrain 2d endless runner

texts:
I've been trying to figure this out exhaustively for the past few days and still haven't found an answer.  I have an endless runner built using swift where the character is fixed and the terrain moves to the left.  I have edge physics bodies on the terrain, and edge physics bodies that go up and down slopes.

The problem is, if I want my character to collide with the ground without being pushed back by it, since the only thing that can make contact with an edge is a dynamic volume.

My goal is to keep the character level with the terrain, (assuming they're not jumping).  Even on slopes.

I've tried ray casting using enumeratebodiesalongraystart, but can't seem to figure out how to get coordinates of where it intersects with the ground.  I've tried having an edge body that is vertical, that intersects with the ground(two edge bodies cannot make contact in sprite kit).  I've tried dynamic volumes.  I've tried Static volumes.  Nothing works.  I'm not posting code here since I'm really just looking for a general answer to sort of point me in the right direction, but I'm coding in swift.  Thanks in advance.  Also I have the character in a different bitmaskcatagory than the terrain catagory and they are set up to recognize each other, and do if one of them is a dynamic volume physics body.


texts: Unity Runtime Surface Snapping (Like Shift+Cntrl in Editor)

texts:
I am trying to allow the user of my VR game to move objects around using a pointer, then when holding down a button, snap to a grid and align to the highest surface, essentially replicating the Editor behavior or holding down shift+control and moving around a transform gizmo. (Try it, it's fun!)
I have the grid part down, but can't wrap my head around how to do the surface snapping.
Here is the code I have so far. I would appreciate any and all help!

// offsetPos is where the VR pointer is.
Vector3 offsetPos = pointer.objectControlPoint.transform.position + cursorOffset;
Vector3 newPos;

if (isSnapping) // Snap to ground code.
{
// I read previously to do this up then down thing, but It's not working as expected
    RaycastHit groundHit = new RaycastHit();
    if (Physics.Raycast(selectedObject.transform.position, Vector3.down, out groundHit))
    {
         RaycastHit objectHit = new RaycastHit();
         if (Physics.Raycast(groundHit.point, Vector3.up, out objectHit))
         {
                Vector3 snapDiff = groundHit.point - objectHit.point;
                snapYPos = snapDiff.y + (selectedObject.collider.bounds.extents.y);
          }
    }
      // worldGrid is a monoBehavior on another object, and gridCellSize is just a float
      float gridPosX = Mathf.Floor(offsetPos.x / worldGrid.gridCellSize) * worldGrid.gridCellSize;
      float gridPosZ = Mathf.Floor(offsetPos.z / worldGrid.gridCellSize) * worldGrid.gridCellSize;
      newPos = new Vector3(gridPosX, snapYPos, gridPosZ); // Sets the target position to the nearest grid cell, with a Y of the snap position.
}
else // If not in snap mode, set target position to just the VR cursor.
{
       newPos = new Vector3(offsetPos.x, offsetPos.y, offsetPos.z);
}

// I know lerp might not be the most efficient, but I like the smooth effect, and it looks good when snapping to the grid...
selectedObject.transform.position = Vector3.Lerp(selectedObject.transform.position, newPos, movementLerpSpeed * Time.deltaTime);

The objects I need to be snapping all are different sizes and have their origins in different places, but all do have appropriate box colliders.
Thanks so much!


texts: What shall I choose between CoronaSDK or AirPlay?

texts:
1st Question is I want to write a board game for iOS and Android so I'm coming up with CoronaSDK and AirPlay. Since I have a mac, development platform is not an issue but the problem is which one should I choose. I'm fluent with PHP and web languages and familiar with C but it's a new language for Lua. I know a lot of people prefer Corona but why not Airplay? It even provides more devices and able to write in C/C++.

2nd Question is I want a SDK with shortest development time and easier coding. I don't need complex 3D or animation engine since the game is a board game like chess or monopoly. What would you recommend?

Really appreciate anyone trying to answer my questions here :)


texts:
If I resize the window (e.g. fullscreen) the texture size also changes!

I want that behaviour: If I change to fullscreen you will see more of the game world. The size (Pixel) of the texture stay the same. Not a scaling.

Thanks.

Regards,
Matthias


texts: How can I get started making textures for 3D games?

texts:
Just wondering where to find good tutorials on making textures for 3D games?

Also, is it common practice to take photographs and convert them into game textures or do designers draw the textures themselves?

UPDATE:

To make the situation more specific, I am trying to make a simple game where the game character is in a small building so I would be making textures for computers, tables, chairs, doors, windows, walls, etc... What is outside the building is mostly irrelevant. I don't have any experience in 3D modeling though I'm thinking of using Blender.


texts: RuntimeInitializeOnLoadMethod only on certain scenes

texts:
I'm using [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] to initialize a prefab that contains all the components required for the game to work propertly.
public class FrameworkInitializer : MonoBehaviour
{
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    public static void InitializeFramework()
    {
       Instantiate(Resources.Load("_GameEngine")) as GameObject;
    }
}

It works fine.
Now I'm creating some scenes to try out things before implementing them in the final game, and I don't really need the default prefab to initialize. I tried adapting the script to this:
public class FrameworkInitializer : MonoBehaviour
{
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    public static void InitializeFramework()
    {
        if (GameObject.FindWithTag("Framework Support") != null) return;
        if (GameObject.Find("NoFrameworkSupportRequired") != null)
        {
            Debug.LogWarning("Carla Framework initializer skipped because of NoFrameworkSupportRequired gameobject in scene.");
            return;
        }
        var framework = Instantiate(Resources.Load("_GameEngine")) as GameObject;
    }
}

But it's not working, because the scene is not loaded yet so it can't find any gameobject.
And if I change BeforeSceneLoad to AfterSceneLoad, some of the scripts that require the prefab in the Awake and onEnable cycle fails.
How can I make this script to run only on some of the scenes?


texts: In A star, do I use the sum or the edge cost?

texts:
When you add a new node to the closed list, you need to check all the adjacent nodes. If you find any adjacent nodes on the open list, you have to check if G would be lower if you went through the current node to get there.

My questions is, when checking if the G would be lower if you went through the current node, do you add up from the last node or start from 0?

Say you're using G = 14 for diagonal and G = 10 for horizontal. Last one on the closed list's G was 20. Your current node is one block lower from the last one on the closed list, and has an adjacent one that's on the open list with G = 34. Are you supposed to check if the G would be lower if you went through your current node by doing 20 + 10 + 14 = 44, 44 !< 34. Or, are you supposed to start from 0, so 0 + 10 + 14 = 24, 24 < 34?

I'm pretty sure it's the latter as with the former, the number is never going to be lower. But if it's the latter, wouldn't the number be lower every single time after a certain point?


texts: What is the appropriate way of placing game objects in a 2d game?

texts:
I'm developing a 2d game for Android.It will be an endless game.I have some items like coins ,plants and other special items.How can i place them effectively?Are there any algorithm or any suggestion for this?

I'm already know that i have to use random numbers for placing them along x and y axis.It's important to not placing two different item at the same x and y position.


texts: I made simple puzzle game. I want to add a "Resume" option to it, so when user opens the game, he can pick up where he left off last time.


texts: How can I move a vehicle using speed and steering angle?

texts:
I want to drive a vehicle in x and y coordinate area with range from (0,0) to (6000,5000). I am using Visual Components (using Python API).

On input I have speed data and steering angle of wheels from Simulink. For example speed of 30 (0.25 m/sec) with the steering angle of wheels from 35 to -35.

I can use something like x = speed * COS( steeringAngle ) and y = speed * SIN( steeringAngle ) while adding up the values of x and y together respectively for each loop.

But the problem is it goes in one direction. If the vehicle turn and comes to area below the value of current x and y. I don't know how to actually get the right x and y value when the turn is so much that it goes to reduced values of x and y. A concept photo is attached. Anyone knows how to solve this?

Here is my code:

Speed= [1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000] #Incoming Speed
  Angle= [0,0,0,10,0,0,-20,-20,0,35,35,35,35,35,35,35,35] #Incoming Angle
  item = app.findComponent('Ball') #Find component in VC
  delay(0.1)

  newposition = [10,2500,0,90,0,180] #New position array
  x = newposition[0]
  y = newposition[1]
  z = newposition[2]
  w = newposition[3]
  p = newposition[4]
  r = newposition[5]   #wpr is yaw, pitch, roll
  Xold=0
  Yold=2500
  Rold=0     #store x y and r

  for s, a in zip(Speed, Angle):        #get values from array
    delay(1)
    print "(Speed, Angle) ->",(s, a)
    x=s
    y=Yold
    r=a         #just store

    rad=math.radians(a)
    x=math.cos(rad)*s
    y=math.sin(rad)*s           #convert to radians

    Xold=Xold+x
    Yold=Yold+y
    Rold=Rold+r              #add to prev value
    x=Xold
    y=Yold
    r=Rold
    print x,y,r

    mtx = item.PositionMatrix         #get position of BALL
    mtx.P = vcVector.new(x,y,z)   #Position
    mtx.WPR = vcVector.new(w,p,r) #Orientation as yaw,pitch,roll
    item.PositionMatrix = mtx             #store new location
    item.update()
    app.render()


texts: Extracting tiles from a tileset programatically?

texts:
How do I programatically extract tiles from a tileset such as this one:
http://opengameart.org/sites/default/files/grassland_tiles.png

I want to use these tiles in my game. I see that some tiles here are of different sizes (or maybe all tiles are a multiple of some fixed size). For example, if I want to use one of the tree tiles in my program, how can I figure out what offset into the tileset image I must use, and how big of a sub-image i must extract? I don't see any metadata associated with any of these tilesets that I can use.

Thanks!


texts:
Assume a character is located on a n by n grid and has to reach a certain entry on that grid. Its current position is (x1,y1). Also on the same grid is an enemy with coordinates (x2,y2). Each step algorithm randomly generates new candidate locations for the hero (if there are k candidates then there is a kx2 matrix of new potential locations.

What I need is some distance objective function to compare the candidates. I'm currently using d1 - c * d2, where d1 is distance to the objective (measure in terms of number of pixels for each axis), d2 is distance to the enemy and c is some coefficient (this is very much like a set-up for Lagrangian). It's not working very well though. I'd be quite keen to learn how what constrained distance function are used for similar cases.

Any suggestions are very much appreciated.


texts:
Possible Duplicate:
  Should actors in a game be responsible for drawing themselves?

How can I refractor the following, to move my drawing functions from the h-file into a GraphicsManager class?

I have the following scenario:

//drawingFunctions.h
void drawTexturedQuad( Texture texture, Vector2 pos, Vector2 dim) {
    // bind texture...
    glBegin(...);    // draw
    //...
    glEnd(...);
}

#include "drawingFunctions.h"
class Player {
    void drawPlayer(){ drawTexturedQuad( texture, pos, dim) }
};
class Enemy {
    void drawEnemy(){ drawTexturedQuad( texture, pos, dim) }
};
class Item {
    void drawItem(){ drawTexturedQuad( texture, pos, dim) }
};
// and so on for the other  components, you get the idea...

I figured I could make all these classes extend another class, say drawableGameComponent. Would that be a good idea? What are other suggestions?


texts:
I have the fundamentals of TCP sockets, UDP communication etc, but can't find much on how to apply these to a real time game environment.

I have a Pong clone, with 4 players, and need to synchronise the paddle positions between the three clients and the server (the server is the fourth player). Currently I use UDP to send real time updates (paddle movements), and TCP for setting up the game lobby etc.

Is it a BAD THING to be spamming out huge amounts of UDP traffic? Should I look into something like DCCP for its congestion features? Or is this not really a problem with a small scale project like this?

When should synchronise messages be sent between client/server? Currently the server is spamming out UDP packets with the current game state as fast as it can manage, and clients are spamming out their paddle position back to the server as fast as they can.
Is this the best way to do it? Is there some sort of delay I should add so messages are sent once every X milliseconds, or should I only be sending out messages as events happen? (eg paddle velocity changed due to user input)

Would it be better to make clients communicate their paddle positions with each other peer to peer?

I am asking these questions within the context of Pong but am also interested in how these problems would be overcome in other games, or generalised solutions.


texts: How can I implement simple distributed processing in a Unity game?

texts:
I'm looking to set up a game which uses distributed processing. Just a simple brick shooter in unity with the distributed part being that the calculations for the falling blocks are handled by another PC and the transformations are sent back and applied to a clients machine.

To use this in Unity I assume I'll be using Remote Procedure Calls?
Will I also require socket programming? Any other networking elements I require?


texts: Is there a way to specify normals as per-face instead of per-vertex in Unity?

texts:
The documentation says that mesh.normals

  are assigned to vertices, not triangles.

I've got a somewhat detailed mesh where faces are joining at right angles. If I don't set the normals, everything takes on a kind of metallic appearance. If I set the normals on the vertices, though, then I have to specify which face I'm using and then the edges are very rounded.

I don't mind making separate meshes for each surface, but it seems kind of a waste to not share the vertices. Is there a way to specify per-face normals instead of per-vertex?


texts: Does Unity's "Compression quality" affect ETC2 compression?

texts:
In Unity I am using "Advanced" texture options on Android with ETC2 8-bit compression. There is an option for "Compression quality" as described here: http://docs.unity3d.com/Manual/class-TextureImporter.html

It seems like the compression quality can impact runtime performance according to that documentation -- but as far as I can tell, ETC2 8-bit doesn't normally have different performance characteristics based on how the texture was compressed... Does the Compression Quality setting actually make a difference with ETC2 8-bit compression on Android?


texts: GetContactList stops reporting collisions on welded bodies

texts:
I have some strange problem with my game which uses Box2D as physics engine and I'm out of ideas on what I can do to solve it.

My game is a class assignment where I need to build a simple game where the main character moves in a 2D environment while square blocks comes from below him. Each time a collision occurs, that block is attached to the character using a weld joint, when three blocks of the same colors are together, they annihilate themselves(an effect similar to Bejeweled). I'm using a recursive function to iterate through all the attached blocks of a given block to see if there are enough blocks for them to be deleted.

I'm using GetContactList function to iterate through the list of contacts to see which blocks are adjacent to each other. The results are quite disappointing, the blocks only get annihilated in few cases. After a lot of debugging, I found the issue, but I still don't know how to solve.

My issue is: after some time, GetContactList STOPS returning contacts (return NULL) to blocks that were already attached for some time. I spent some time reading the Box2D manual as well as some tutorials and still didn't find any clue of what is happening.

Below there's some simplified version of the code that I wrote.

for(int a = 0; a < blocksList.size(); a++)
{
   blocksList[a].BuildConnections();
}

And on BuildConnections

b2ContactEdge* edge = body->GetContactList();
while(edge != NULL)
{
   if (long_check_to_see_if_there's_a_block_nearby)
   {
       // add itself to the list to be anihilated
       globalList.push_back(this);
       //if there's, call BuildConnections again on the adjacent block
       adjacentBody->GetUserData()->BuildConnections;
   }
   edge = edge->next;
}

I know that there's another issue related to circular inclusions, but I fairly sure that this problem isn't causing the problem with the collisions.

You can download my entire code from this page if you'd like http://code.google.com/p/fellz/source/list


texts: How can I generate high feature point images for recognition within an Augmented Reality app?

texts:
I need to automatically generate 300-400 images (for a print medium) which will be used by an AR app (using ARCore).

The printed physical image ideally would be 5" x 8" but can be 5" x 5" as well.
The printed physical image ideally would be in Black & White.

I can of course use a QR code generator, but am open to use something better if it exists. There is no text / URL that needs to be encoded in the resultant image - I am just trying to choose something that makes things very easy for the ARCore / image recognition piece.


texts: UDK Modular construction (customisable vehicles etc)

texts:
I'd like to build an interface whereby the user can attach various components and blocks onto a vehicle, this is then saved (as object/coordinate, rotation, scale values - in database) and can be used again later.

After looking into sockets I haven't been able to find a way of saying connect ObjectA's SocketOne to ObjectB's SocketX with rotation Z and Scaling V for instance.

If that sounds infeasible to you (which it may well be), is there another way of scripting 2 objects to be "joined", so they act as one item when they move/animate?

   Create ObjectA at 0,0,0
   Create ObjectB is at 10,0,0
   ObjectA.link(ObjectB)

I would like the sub objects to still be animated etc (like meshes connected to sockets can)

If anyone has any pointers they would be greatly appreciated.

Thanks,
Martin


texts: LibGDX Shader does not work with FBO texture

texts:
I have a shader and I want to run the shader on the whole rendered image at the end instead of each individual sprite that I render on screen. For this purpose I created an FBO, I render the all my images to the FBO and then I render to colorBufferTexture generated by the FBO. There is just one problem, the shader does not work when I render the FBO texture. The withoutFbo() method render the image with the shader working just fine, but the withFbo() method only renders the image without the shader. Also I know that the shader in withFbo() is working because if I try to render something other then the colorBufferTexture from the FBO the shader will work. So why isn't the shader working with the texture generated by the FBO?

public class Application3 extends ApplicationAdapter
{
    float time;
    Sprite sprite;
    FrameBuffer fbo;
    SpriteBatch batch;
    Texture noiseTexture;
    TextureRegion fboTexture;
    ShaderProgram shaderProgram;

    @Override public void create()
    {
        ShaderProgram.pedantic = false;
        batch = new SpriteBatch();

        sprite = new Sprite(new Texture("game.png"));
        sprite.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

        shaderProgram = new ShaderProgram(Gdx.files.internal(Shader.GLITCH2.getVertex()), Gdx.files.internal(Shader.GLITCH2.getFragment()));

        noiseTexture = new Texture(Gdx.files.internal(Shader.GLITCH2.getPath() + "noise.png"));
        noiseTexture.bind(0);

        fbo = new FrameBuffer(Pixmap.Format.RGBA8888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
        fboTexture = new TextureRegion(fbo.getColorBufferTexture());
        fboTexture.flip(false, true);
    }

    @Override public void render()
    {
        //withFbo();
        withoutFbo();
    }

    void withoutFbo()
    {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        time += Gdx.graphics.getDeltaTime();

        shaderProgram.setUniformi("u_noise", 0);
        shaderProgram.setUniformf("u_time", time);
        batch.setShader(shaderProgram);
        batch.begin();

        batch.draw(sprite, sprite.getX(), sprite.getY(), sprite.getWidth(), sprite.getHeight());

        batch.setShader(null);
        batch.end();
    }

    void withFbo()
    {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        time += Gdx.graphics.getDeltaTime();

        fbo.begin();
        batch.begin();

        batch.draw(sprite, sprite.getX(), sprite.getY(), sprite.getWidth(), sprite.getHeight());

        batch.end();
        fbo.end();

        shaderProgram.setUniformi("u_noise", 0);
        shaderProgram.setUniformf("u_time", time);
        batch.setShader(shaderProgram);
        batch.begin();

        batch.draw(fboTexture, sprite.getX(), sprite.getY(), sprite.getWidth(), sprite.getHeight());

        batch.setShader(null);
        batch.end();
    }
}


texts: How to handle Animal AI biting and holding onto the character

texts: Example state of decay, zombie biting the player


texts: How are methods like Awake, Start, and Update called in Unity?

texts:
I'm developing with Unity 5 and I know that there are some methods you can use like in the code below:

public class MyGameElement : MonoBehaviour
{
    private void Awake() { }
    private void Start() { }
    private void Update() { }
    private void FixedUpdate() { }
    // and more
}

I know what they do but I find it strange that the methods can be private. However they are not called into my code I've written. Here you've an image with code lens (I use VS 2015 Professional for coding) where you can really see that it has zero references.

The second 'strange' thing for me is that the methods aren't overwritten.

So my question is now is there anything that Unity has implemented into the MonoBehaviour class that the methods can call?


texts: Unreal Visual Studio 2019 taking forever for tellisense

texts: I'm using the latest unreal engine and visual studio 2019.  I'm having a problem where intellisense can take way too long.  This usually happens when I have just opened the project inf VS 2019, but not sometimes it happens for apparently no reason.  either way, the intellisense is not very snappy.  Is there a fix for this?


texts: Is Update() called on the very first frame in Unity?

texts:
I'm calling Time.frameCount inside Update() and then immediately Debug.Break() to pause the simulation before Update() is finished. This of course happens (supposedly) on the very first frame, and yet Time.frameCount returns 1, as if one frame had already been rendered by at that point. Also, I'm calling Time.deltaTime the same way, on the first frame inside Update(), and it returns a value too, as if a previous frame had been rendered and took X milliseconds.

Considering Time.deltaTime returns the value of the "time it took to complete the last frame", and I'm calling it on the first frame and it's returning a value, is there an "invisible" first frame that Update() doesn't run on?

I couldn't find any reference to this specific issue on the Unity docs.


texts: Why do I only receive the first message I send with SDLNet?

texts:
I am sending two messages from server.exe like this:

sprintf( buffer,"%d %s",1,data1);
SDLNet_TCP_Send(clientSocket, buffer, strlen(buffer)+1); // first message

sprintf( buffer,"%d %s",2,data2);
SDLNet_TCP_Send(clientSocket, buffer, strlen(buffer)+1); // second message

and I am reading messages from client.exe like this:

if(SDLNet_CheckSockets(socketSet, 0)>0)
{
    if(SDLNet_SocketReady(clientSocket)>0)
    {
        if(SDLNet_TCP_Recv(clientSocket, buffer, 5000)>0)
        {
           //there i take only first message
        }
    }
}

Why am I not receiving all sent messages in the client?


texts: Advices fo starting a video game design career

texts:
I'm 24 and have a passion for video games and game-design. I've decided I want to design video games as my career.

I have no experience with designing video games or coding but I'm interested and willing to learn. I want a job at any level but what would I need to land a job?

I have no college experience and I have no money. What is a cheap school, or do I really need to go to school for this, or can I learn on my own? Is it possible to do this with no money? I'm literally broke but I want this so bad I feel like its the only career I'll enjoy.

I want to call up company's and ask them what they are looking for in someone they want to hire, is that a good idea?

Also I don't know the history of video game design and I don't want to sound like a dummy when someone says something about this field or talks about a famous designer and I have no idea who they're talking about. So what is key info when it comes to this field and where should I find it?

Hopefully some of you guys and girls can help me out: I know in the future I will create something everyone will enjoy and you guys will remember when you gave me advice and I will always remember you guys for helping me. I'm gifted I know I am and I want to share my gift with the rest of the world by making games that change the Industry. Help me out please.


texts: AdMob interstitial ads not showing after publishing in playstore

texts:
I have create a Unity game, 1st I add an AdMob interstitial ads script on game object then try on my main camera when I test in my mobile before publishing. It has worked like real time ads and mistakenly clicked it and earn 0.3 so I create new ad unit placed it on my game then published my game. But the ads are not showing in real time. No error was found in AdMob but 147 ad requests are shown in AdMob and ads are not visible when my game 1st scene opens.

Here is my interstitial ads script code:

using UnityEngine;
using System.Collections;
using GoogleMobileAds.Api;

public class AdmobScript : MonoBehaviour
{
   private InterstitialAd interstitial;

   private void RequestInterstitial()
   {
      #if UNITY_ANDROID
         string adUnitId = "ca-app-pub-3129337025883034/9036322***";
      #elif UNITY_IPHONE
         string adUnitId = "INSERT_IOS_INTERSTITIAL_AD_UNIT_ID_HERE";
      #else
         string adUnitId = "unexpected_platform";
      #endif

      // Create an interstitial.
      this.interstitial = new InterstitialAd(adUnitId);
      // Load an interstitial ad.
      this.interstitial.LoadAd(this.CreateAdRequest());
   }

   // Returns an ad request
   private AdRequest CreateAdRequest()
   {
      return new AdRequest.Builder().Build();
   }

   private void ShowInterstitial()
   {
      if (interstitial.IsLoaded())
      {
         interstitial.Show();
      }
   }

   public void Start()
   {
      RequestInterstitial();
   }

   void Gameover()
   {
      if(interstitial.isloaded){
        ShowInterstitial();
      }
   }
}


texts: most efficient AABB vs Ray collision algorithms

texts:
Is there a known 'most efficient' algorithm for AABB vs Ray collision detection?

I recently stumbled accross Arvo's AABB vs Sphere collision algorithm, and I am wondering if there is a similarly noteworthy algorithm for this.

One must have condition for this algorithm is that I need to have the option of querying the result for the distance from the ray's origin to the point of collision. having said this, if there is another, faster algorithm which does not return distance, then in addition to posting one that does, also posting that algorithm would be very helpful indeed.

Please also state what the function's return argument is, and how you use it to return distance or a 'no-collision' case. For example, does it have an out parameter for the distance as well as a bool return value? or does it simply return a float with the distance, vs a value of -1 for no collision?

(For those that don't know: AABB = Axis Aligned Bounding Box)


texts: How can I make a Unity Animation (interpolation from A to B) "procedural", by varying A and B?

texts:
Goal
One might use a coroutine to interpolate an object's position from point A to point B.
What I'm trying to do is store that interpolation as a Unity Animation file, but have the ability to manually enter points A and B each time it plays.
Description
I have a simple Animation — a "jump", if you will — which I want to chain with the aforementioned interpolation:

the object does a little jump;
mid-air, the object moves/interpolates to another position.

Of course, I could do this by playing the coroutine after the first animation is done, but it'd be cleaner to store both as Animation files and use an Animator Controller to manage them, especially since the 2 animations are technically parts of one whole.
Is that possible?
If so, how could I record/create it? If not, what's a clean alternative?


texts:
I'm in the process of building a JavaScript / HTML5 game (using Canvas) for mobile (Android / iPhone/ WebOS) with PhoneGap. I'm currently trying to design out how the UI and playing board should be built and how they should interact but I'm not sure what the best solution is. Here's what I can think of -

Build the UI right into the canvas using things like drawImage and fillText
Build parts of the UI outside of the canvas using regular DOM objects and then float a div over the canvas when UI elements need to overlap the playing board canvas.
Are there any other possible techniques I can use for building the game UI that I haven't thought of? Also, which of these would be considered the "standard" way (I know HTML5 games are not very popular so there probably isn't a "standard" way yet)? And finally, which way would YOU recommend / use?

Many thanks in advance!


texts: Technique for multiple shadow casting lights in 2D

texts:
I'm trying to create shadows in a 2D game in such a way that I can have an arbitrary number of lights in a scene, all of which can cast shadows. To do this I think I have to generate a mesh for each light that models where the light can come (e.g. where there is no shadow).

In this tutorial: http://youtu.be/4BtjcH-iLR0?t=4m40s (at 4 minutes 40 seconds) Chris Molini does exactly what I want describing it as 'a polygon clipping pass' for each edge that intersects with the light. However I don't understand what kind of polygon clipping he is refering to here. I have tried to mimick his technique on my own but without success. (I get lost in corner cases and radial+distance ordering around the light).

Here's a screenshot from the video. The square is the light's mesh (basically an AABB containing the light's sphere of influence). Which is gradually adjusted for each edge that intersects with the light's mesh.


texts: Rigidbody freeze rotation around global Y

texts:
My player is a cube that moves in all directions, but cannot jump. I want to achieve that the cube cannot rotate around global Y axis, but can rotate around global X and Z. This cannot be simply done by freezing the local Y rotation, since the cube can fall from higher ground and rotate mid-air - after that the local and global y axes are not parallel anymore and some other axis should be frozen.
Currently, I am using this line:
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(transform.rotation.eulerAngles.x, Mathf.Round(transform.rotation.eulerAngles.y / 90) * 90, transform.rotation.eulerAngles.z), 1f);

which is located in the FixedUpdate(). The resulting movement is shown in this video. Clearly, this always snaps the axis that is parallel to the global Y to the closest 90° angle. This solution, however, has a few unwanted side effects. One of them is clipping with the terrain or other player cubes, the second one is that the cube randomly rotates if walking over the edges or corners, and the third one is that if one cube is on top of another and both have this script attached, they start lagging, jittering and sometimes spinning.
I also tried by freezing the rotation based on what side of the cube is "on the bottom", but this does not work OK, since it often happens that the cube does not rotate for exact 90° when it drops from higher ground and ends up frozen standing on only one edge, just slightly off from being on the ground with the whole bottom side.
What is the "to go" solution for this type of movement?


texts: Is there any way to get PVRTexTool's version from the command line?

texts:
I am to make an automated task which involves requiring the version of the PVRTexTool that comes with the Unity installed in a machine.

Is it possible to get the version of PVRTexTool on the command shell?


texts:
Does SpriteBatch in XNA draw to the screen only when a sprite would appear on the screen?

Say I have 5 identical sprites placed exactly on top of each other, is SpriteBatch able to determine that it only needs to draw one?

Also, say I have a large map that I've tiled off the screen in every direction.  Does SpriteBatch handle that it does not need to draw these sprites that are off the screen.

(Note: Yes my code should handle this, I am just curious)


texts:
I recently saw this and this, and that got me thinking

When publishing a commercial game without DRM, would it be a good idea to upload a slightly modified copy of the game that shows a screen like this at startup to, say, The Pirate Bay:

  Hello pirate! Looks like you downloaded this game from The Pirate Bay! That's okay, but:
  Making a game costs time and money. If you like the game, please buy it so we can continue to update this game with new content! You buy it for only $xx.xx at www.example.com!

  In the meantime: Have fun!

  Press Enter to continue

And then continues to the title screen and from there is identical to a legal copy.

The point is that it will probably (very, very, VERY high chance that it will) be uploaded sooner or later anyway, so this may decrease the harm.

Would that be a good idea?


texts: Code to generate a color gradient within a texture using a diagonal line

texts:
I want to generate a color gradient between two colors from x1,y1 to x2,y2. I'm unsure how to do this though. I can use Color.Lerp to get all of the color steps, but the problem is that I don't understand how to then apply that to a plane (the texture pixels) when the line would be at an angle.

If it was a horizontal/vertical line, that would be easy, because it's just plotting the same color along the appropriate axis. But if it's a diagonal line of any degree, that seems way more complicated and I'm unsure how to do calculate it.

As an example, here is a gradient from a picture editor program. It goes from green-to-red. The actual start and end positions are the circles. Therefore, the solid start/end colors continue solid outside of the gradient area.


texts:
I'm trying to understand if it makes sense to call what I have a scene graph or not.

Im doing an asteroid-like game, where all objects in the game are described in world space coordinates (an asteroid will be at X 50, Y 50 and it wont have objects orbiting, the player avatar is at X 100, Y 100 and it does'nt have a turret rotating the base of the ship. Objects are all described in world space, not in relationship to each other cause it just dose'nt make any sense).

For clarity (on why I will be mentioning a view matrix and a projection matrix bellow) - this is a 3D game with 3D objects in it, but the camera is locked facing one direction.

What I have is an object with a set of vectors containing all the objects visible in the scene. To me, this is still a scene graph - it just happens to be a flat graph where everything in the scene is a single node, not a child of a parent.
The scene graph also stores the projection and view matrix, as these are common to all objects scene (the view and projection matrix are static, only world space coordinates are updated). One could consider this view matrix as a transformation "node" that will be applied to all the children in the scene graph I guess.

So my question is - am I stretching it calling this a a "Scene Graph" and should I use another name for it?


texts: Am I experiencing a gimbal lock problem when rotating my cube?

texts:
So I'm trying to build a simple mechanic where the player see's 3 sides of a cube at a time: top, left and front(I called the front-side "Right" in my code, due to the orthographic view). The player can click on the front side or left side of the cube to rotate the cube so that the side that was pressed moves and becomes the top face. I want to smooth/animate the rotation.

The red faces are the faces that the user can click on.

My Logic seems to work quite well when I click on the left face (Rotating along the x axis), but doesn't seem to work well for the front/right face(It usually works once and then does weird stuff on the next click, this is on the z-axis)

public class CubeRotator : MonoBehaviour
{
    private const float STOP_THRESHHOLD = 0.1f;
    private const float ROTATE_AMOUNT = 90f;

    [SerializeField, Header("Touch Quads Colliders")]
    private Collider touchQuadLeft;
    [SerializeField]
    private Collider touchQuadRight;

    [SerializeField, Space(10)]
    private float timeToRotate;

    private bool mustRotateLeft = false;
    private bool mustRotateRight = false;

    private float targetX = 0.0f;
    private float targetZ = 0.0f;

    private float xVelocity = 0.0F;
    private float zVelocity = 0.0F;

    int layerMask;

    private void Start()
    {
        layerMask = LayerMask.GetMask("Touch Quad");
    }

    void Update()
    {
        ListenForTouch();
        RotateCube();
    }

    private void ListenForTouch()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector2 touchPoint = Input.mousePosition;
            RaycastHit rayCastHit;
            Ray ray = Camera.main.ScreenPointToRay(touchPoint);

            if (Physics.Raycast(ray, out rayCastHit, 150f, layerMask))
            {
                if (rayCastHit.collider == touchQuadLeft)
                {
                    mustRotateLeft = true;
                    targetZ = targetZ - ROTATE_AMOUNT;
                    zVelocity = 0f;
                }

                else if (rayCastHit.collider == touchQuadRight)
                {
                    mustRotateRight = true;
                    targetX = targetX + 90f;
                    xVelocity = 0f;
                }
            }
        }
    }

    private void RotateCube()
    {
        float zAngle = transform.rotation.eulerAngles.z;
        float xAngle = transform.rotation.eulerAngles.x;

        if (mustRotateLeft)
        {
            zAngle = Mathf.SmoothDampAngle(zAngle, targetZ, ref zVelocity, timeToRotate);

            if (Mathf.Abs(zVelocity) <= STOP_THRESHHOLD)
            {
                mustRotateLeft = false;
            }
        }

        if (mustRotateRight)
        {
            xAngle = Mathf.SmoothDampAngle(xAngle, targetX, ref xVelocity, timeToRotate);

            if (Mathf.Abs(xVelocity) <= STOP_THRESHHOLD)
            {
                mustRotateRight = false;
            }
        }

        transform.rotation = Quaternion.Euler(xAngle, 0f, zAngle);
    }
}

Inspector Values:

I've tried several things, the only problem I can think of is, gimbal lock. Thanks in advance.


texts: How do I add auto login system firebase auth Unity?

texts:
I want to add an auto login/sign in ability into my game, so when the player quits the game or goes to main menu, the login panel is gone and the player is automatically logged in. Then, I want the player to be logged out and no longer automatically sign in when he presses the "sign out" button.
Here are some previews of my game:

I'm sure this code works like this, but I have low experience on firebase. Additionally, there is lack of documentation on it with Unity so I don't know what is wrong with this script.

void Awake()
    {
        //Check that all of the necessary dependencies for Firebase are present on the system
        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
        {
            dependencyStatus = task.Result;
            if (dependencyStatus == DependencyStatus.Available)
            {
                //If they are avalible Initialize Firebase
                InitializeFirebase();
            }
            else
            {
                Debug.LogError("Could not resolve all Firebase dependencies: " + dependencyStatus);
            }
        });

        //singleton
        if (instance != null)
        {
            Destroy(gameObject);
        }
        else
        {
            instance = this;
            DontDestroyOnLoad(gameObject);

        }

    }

    private void InitializeFirebase()
    {
        Debug.Log("Setting up Firebase Auth");
        //Set the authentication instance object

        if (auth != null)
        {
            _MainMenuUI.instance.loginPanel.SetActive(false);
        }
        else
        {
            auth = FirebaseAuth.DefaultInstance;
            DBreference = FirebaseDatabase.DefaultInstance.RootReference;
        }
    }