texts:
I am using the Phaser framework for game development, but while working on it I face a bug which is annoying, I have the following message:

  InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

The consequence is that because of it I now cannot move my hero, I need to first click once on the phaser window and then it worked, so I tried to debug it, and even by using the default phaser demo the same error message appear and cause the same but, so i concluded that my code is not the problem.

Do you please have any idea? Is there a way to know how to fix it ? Otherwise  how can have more details about it in the console?

Note: if you wanna download the official starting tutorial to reproduce the error:

Download .zip: here
Beginner Tutorial: here


texts: Characteristics, what's the inverse of (x*(x+1))/2?

texts:
In my game you can spend points to upgrade characteristics. Each characteristic has a formula like:

A) out = in :
for one point spent, one pont gained (you spend 1 point on Force so your force goes from 5 to 6)

B) out = last level (starting at 1) :
so the first point spent earns you 1 point, the next point spent earns you an additional 2 and so on (+3,+4,+5...)

C) The inverse of B) :
You need to spend 1 point to earn one, then you need to spend 2 to earn another one and so on.

I have already found the formula for calculating the actual level of B when points spent = x :

charac = (x*(x+1))/2

But I'd like to know what the "reverse" version of B) (usable for C) is, ie. if I have spent x points, how many have I earned if 1 spent gives 1, 1+2=3 gives 2, 1+2+3=6 gives 3 and so on.

I know I can just calculate the numbers but I'd like to have the formula because its neater and so that I can stick it in an excel sheet for example...

Thanks!

ps. I think I have nailed it down to something like charac = sqrt( x*m +k) but then I'm stuck doing number guessing for k and m and I feel I might be wrong anyway as I get close but never hits the spot.


texts: Platform jumping problems with AABB collisions

texts:
See the diagram first:

When my AABB physics engine resolves an intersection, it does so by finding the axis where the penetration is smaller, then "push out" the entity on that axis.

Considering the "jumping moving left" example:

If velocityX is bigger than velocityY, AABB pushes the entity out on the Y axis, effectively stopping the jump (result: the player stops in mid-air).
If velocityX is smaller than velocitY (not shown in diagram), the program works as intended, because AABB pushes the entity out on the X axis.

How can I solve this problem?

Source code:

public void Update()
{
    Position += Velocity;
    Velocity += World.Gravity;

    List<SSSPBody> toCheck = World.SpatialHash.GetNearbyItems(this);

    for (int i = 0; i < toCheck.Count; i++)
    {
        SSSPBody body = toCheck[i];
        body.Test.Color = Color.White;

        if (body != this && body.Static)
        {
            float left = (body.CornerMin.X - CornerMax.X);
            float right = (body.CornerMax.X - CornerMin.X);
            float top = (body.CornerMin.Y - CornerMax.Y);
            float bottom = (body.CornerMax.Y - CornerMin.Y);

            if (SSSPUtils.AABBIsOverlapping(this, body))
            {
                body.Test.Color = Color.Yellow;

                Vector2 overlapVector = SSSPUtils.AABBGetOverlapVector(left, right, top, bottom);

                Position += overlapVector;
            }

            if (SSSPUtils.AABBIsCollidingTop(this, body))
            {
                if ((Position.X >= body.CornerMin.X && Position.X <= body.CornerMax.X) &&
                    (Position.Y + Height/2f == body.Position.Y - body.Height/2f))
                {
                    body.Test.Color = Color.Red;
                    Velocity = new Vector2(Velocity.X, 0);

                }
            }
        }
    }
}

public static bool AABBIsOverlapping(SSSPBody mBody1, SSSPBody mBody2)
{
    if(mBody1.CornerMax.X <= mBody2.CornerMin.X || mBody1.CornerMin.X >= mBody2.CornerMax.X)
        return false;
    if (mBody1.CornerMax.Y <= mBody2.CornerMin.Y || mBody1.CornerMin.Y >= mBody2.CornerMax.Y)
        return false;

    return true;
}
public static bool AABBIsColliding(SSSPBody mBody1, SSSPBody mBody2)
{
    if (mBody1.CornerMax.X < mBody2.CornerMin.X || mBody1.CornerMin.X > mBody2.CornerMax.X)
        return false;
    if (mBody1.CornerMax.Y < mBody2.CornerMin.Y || mBody1.CornerMin.Y > mBody2.CornerMax.Y)
        return false;

    return true;
}
public static bool AABBIsCollidingTop(SSSPBody mBody1, SSSPBody mBody2)
{
    if (mBody1.CornerMax.X < mBody2.CornerMin.X || mBody1.CornerMin.X > mBody2.CornerMax.X)
        return false;
    if (mBody1.CornerMax.Y < mBody2.CornerMin.Y || mBody1.CornerMin.Y > mBody2.CornerMax.Y)
        return false;

    if(mBody1.CornerMax.Y == mBody2.CornerMin.Y)
        return true;

    return false;
}
public static Vector2 AABBGetOverlapVector(float mLeft, float mRight, float mTop, float mBottom)
{
    Vector2 result = new Vector2(0, 0);

    if ((mLeft > 0 || mRight < 0) || (mTop > 0 || mBottom < 0))
        return result;

    if (Math.Abs(mLeft) < mRight)
        result.X = mLeft;
    else
        result.X = mRight;

    if (Math.Abs(mTop) < mBottom)
        result.Y = mTop;
    else
        result.Y = mBottom;

    if (Math.Abs(result.X) < Math.Abs(result.Y))
        result.Y = 0;
    else
        result.X = 0;

    return result;
}


texts: Making XNA Play Nice With 3DS Max, Boundiing Spheres

texts:
I'm using 3DS Max 2010 with the KW x-porter plugin, which outputs a .X file (just downloaded the very latest version).

Been getting some odd results:
http://www.picvalley.net/u/2930/2265240220441812321333990933PAStFeSONWQslOrMQC5q.PNG

Looks like the culling is screwed up.  Note, that models I make in Milkshape don't seem to be having these problems.

I've also tried to export an FBX file from 3DS Max 2010 and have been getting similar results.

What are your suggestions in terms of exporting *.3DS models to a workable XNA form?  What tools do you use?.

To be clear, the model in question has none of these defects when viewed from similar angles in 3DS Max 2010.

http://www.picvalley.net/u/2563/151728957814855401111333991302mSvEJ03Zv22GwHFgIhiV.PNG

Any ideas on this oddity would also be appreciated!

Edit 1 -- Add'l issue
Forgot to mention, that the model otherwise seems alright, but that rotation seems to double -- in other words, when I scroll my camera view left to right, the model (whose draw I give the camera for the view and perspective matrices w/ BasicEffect seems to rotate twice as much as models I draw natively in XNA


texts: Is it possible to have lightmapping on runtime generated combine children in Unity? It is possible to bake combined meshes when they are done in the editor, but the .apk/.ipa size increases too much.


texts: Why does my game display the wrong "required Android version" on Google Play?

texts:
I'm porting a Unity game to Android, and I've set up the "Minimum API Level" in the Player settings to "2.3.3 (API level 10)".

However, on the store, it says "Requires Android: 1.6 and up".

On the Google Developer Console I didn't find this setting, so I guess the store is just trying to "guess" it examining the application, and failing.

Did I miss something?


texts: WebGL techniques for normal mapping on morph targets?

texts:
I'm currently morphing some meshes by interpolating their positions and normals between target arrays, on the GPU, in WebGL.

Now I need to apply normal maps to those morphs.

For normal maps on static meshes, I'm computing the vertex tangent vectors in JavaScript, which I then use in the shader for the normal mapping math.

For morphs, what I was about to do was compute those tangents for each morph target, then include those in the morph interpolations within the shader morphing routine, so that at every instant we have interpolated tangents with which to do the normal mapping.

Does anyone have experience with this? Does this seem reasonable? Know any examples out there I should look at?


texts:
My problem is, I want to create a 2D tiled map. Yes, I know it's been asked a lot. I've seen answers that propose the use of tiled however it only allows (or so it seems to me) to generate static maps that do not change once generated. And I need a large empty uniform space of empty tiles, upon which players may place various buildings (some spanning more than one tile and logically being the same one).

How to approach this in Android? Do I make some kind of TableLayout, use arbitrarly large amount of rows and imageviews (with my emptyTile), than somehow work event-based changing of image ids from there? I'd think that only a portion of that map should be visible at a time, but I don't see how scrolling around could be the part of that structure.


texts: God rays shader - Trouble with sun position

texts:
I have found a shader that I like here: https://www.shadertoy.com/view/4dyXWy

The code for the fragment shader from the link above is:

#define DITHER          //Dithering toggle
#define QUALITY     0   //0- low, 1- medium, 2- high

#define DECAY       .974
#define EXPOSURE    .24
#if (QUALITY==2)
 #define SAMPLES    64
 #define DENSITY    .97
 #define WEIGHT     .25
#else
#if (QUALITY==1)
 #define SAMPLES    32
 #define DENSITY    .95
 #define WEIGHT     .25
#else
 #define SAMPLES    16
 #define DENSITY    .93
 #define WEIGHT     .36
#endif
#endif

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 uv = fragCoord.xy / iResolution.xy;

    vec2 coord = uv;
    vec2 lightpos = texture(iChannel0, uv).zw;

    float occ = texture(iChannel0, uv).x; //light
    float obj = texture(iChannel0, uv).y; //objects
    float dither = texture(iChannel1, fragCoord/iChannelResolution[1].xy).r;

    vec2 dtc = (coord - lightpos) * (1. / float(SAMPLES) * DENSITY);
    float illumdecay = 1.;

    for(int i=0; i<SAMPLES; i++)
    {
        coord -= dtc;
        #ifdef DITHER
            float s = texture(iChannel0, coord+(dtc*dither)).x;
        #else
            float s = texture(iChannel0, coord).x;
        #endif
        s *= illumdecay * WEIGHT;
        occ += s;
        illumdecay *= DECAY;
    }

    fragColor = vec4(vec3(0., 0., obj*.333)+occ*EXPOSURE,1.0);
}

That is in GLSL, but I am using DirectX 11. I've been able to port it across quite easily, but I feel like I have some knowledge gaps that are making it hard for me to get correct. For example, I don't understand the difference between texture(iChannel0, uv).x and texture(iChannel0, uv).r if someone wouldn't mind explaining ( I understand sampling the colour channels but xyz while sampling?).
I also do not understand the channel resolution. Is it the dimensions of the 2D texture that I'm rendering to? Or perhaps the ratio of the texture?

Here is what I have come up with so far, just the bare minimum of changes to get it working:

SamplerState g_samSampler   : register( s0 );
Texture2D g_texInfo         : register( t0 );

#define DITHER
#define DECAY       0.974f
#define EXPOSURE    0.24f
#define SAMPLES     64
#define DENSITY     0.97f
#define WEIGHT      0.25f

struct PixelInput
{
    float4 vPosition : SV_POSITION;
    float2 vTexCoord : TEXCOORD0;
};

float4 PS( PixelInput input ) : SV_TARGET
{
    float2 uv = input.vTexCoord;

    float2 coord = uv;
    float2 lightpos = g_texInfo.Sample( g_samSampler, uv ).zw; //TAKE NOTE OF THIS LINE

    float occ = g_texInfo.Sample( g_samSampler, input.vTexCoord ).g; //light
    float obj = g_texInfo.Sample( g_samSampler, input.vTexCoord ).b; //objects
    float dither = g_texInfo.Sample( g_samSampler, uv/float2( 4.f, 3.f ) ).x;

    float2 dtc = (coord - lightpos) * (1.f / float(SAMPLES) * DENSITY);
    float illumdecay = 1.;

    for(int i=0; i<SAMPLES; i++)
    {
        coord -= dtc;

        #ifdef DITHER
            float s = g_texInfo.Sample( g_samSampler, coord+(dtc*dither) ).g;
        #else
            float s = g_texInfo.Sample( g_samSampler, input.vTexCoord ).g;
        #endif

        s *= illumdecay * WEIGHT;
        occ += s;
        illumdecay *= DECAY;
    }

    return float4(float3(0.f, 0.f, obj*.333f)+occ*EXPOSURE,1.f);
}

Please note that my green channel of the passed in texture g_texInfo stores the light texture (the white circle for the sun) and the blue channel stores the light occluders.
I am doing this as a post processing effect on a screen quad. (Is this correct?)
My suspicion is the line float2 lightpos = g_texInfo.Sample( g_samSampler, uv ).zw; is causing the trouble - I don't really understand this part - how can I find the position of the sun?

Here's what I'm receiving from my current shader, it appears that the light rays are being emitted in the wrong direction.

When I shift the camera so that the sun is in the top left, it gives the correct effect, it is also occluded properly when putting an object in the way.


texts: Having Your Own Copyrighted App Automatically After Publishing

texts: I have a question regarding for the game app and in business. You see, I decided to publish an app to Google Play. When I published it, does this app automatically declared that this app is copyrighted or copyright protected by the publisher and creator like me itself or not? If not, does it have to seek something or required to register this app for copyright authentication via online or at office or not?


texts: pyOpenGL draw loop - slow with just 1500 items to draw

texts:
I've been trying to build myself a simple little game API using pyOpenGL (previously I tried using just Tkinter, but I keep hitting the same wall whatever I do!)

I rewrote everything using my very limited knowledge of OpenGL and came up with the following for my draw loop:

def _draw(self):
    vertex_count = 0
    items = 0
    coords = numpy.array([], numpy.float32)

    for item in self.graph:
        z = item.z - 1
        if z < 0:
            z = 0

        x1 = item.x * 2.0 / self.width - 1
        y1 = (item.y+z*item.height) * 2.0 / self.height - 1

        x2 = (item.x+item.width) * 2.0 / self.width - 1
        y2 = ((item.y+z*item.height)+item.height) * 2.0 / self.height - 1

        coords = numpy.hstack((coords, numpy.array([
        # X,    Y,      Z     U,                                V
        x1,     y2,     0.0,  self.sprite_sheet[item.frame][0], self.sprite_sheet[item.frame][1],
        x2,     y2,     0.0,  self.sprite_sheet[item.frame][2], self.sprite_sheet[item.frame][3],
        x1,     y1,     0.0,  self.sprite_sheet[item.frame][4], self.sprite_sheet[item.frame][5],
        x1,     y1,     0.0,  self.sprite_sheet[item.frame][6], self.sprite_sheet[item.frame][7],
        x2,     y2,     0.0,  self.sprite_sheet[item.frame][8], self.sprite_sheet[item.frame][9],
        x2,     y1,     0.0,  self.sprite_sheet[item.frame][10], self.sprite_sheet[item.frame][11],
        ], numpy.float32)) )

        vertex_count += 6

    glBufferData(GL_ARRAY_BUFFER, coords.nbytes, coords, GL_STATIC_DRAW)
    vertices = glGetAttribLocation(self.shader_program, 'a_position')
    tex_coords = glGetAttribLocation(self.shader_program, 'a_texCoords')

    glEnableVertexAttribArray(vertices)
    glEnableVertexAttribArray(tex_coords)
    glVertexAttribPointer(vertices, 3, GL_FLOAT, GL_FALSE, 20, None)
    glVertexAttribPointer(tex_coords, 2, GL_FLOAT, GL_TRUE, 20, ctypes.c_void_p(12))

    return vertex_count

... in calling func ...

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Clear all pixels.

count = self.scene._draw()

glDrawArrays(GL_TRIANGLES, 0, count)

glutSwapBuffers()
glutPostRedisplay()

glFlush()

I'm testing it with a window 720 x 512, drawing a simple set of 2d tiles 32x32 each, so ~1500 items in total, but it is sooo slow, each frame is taking about 0.1 seconds. I thought I'd be safe with OpenGL until I was trying to draw >10,000 things!

I have tried a few permutations of building 1 big array and writing it all in one chunk (as above), or creating a big empty buffer then using glBufferSubData() to write in each item as needed (still creating a numpy.array() for each item then writing it to the buffer).

I have a very simple vertex and fragment shader which really just pass everything through:

attribute vec3 a_position;
attribute vec2 a_texCoords;

uniform mat3 u_matrix;

varying vec2 v_texCoords;

void main()
{
    gl_Position = vec4(a_position, 1);

    v_texCoords = a_texCoords;
}

and

uniform sampler2D u_image;

varying vec2 v_texCoords;

void main()
{
    gl_FragColor = texture2D(u_image, v_texCoords);
}

Sorry for the giant walls of code, trying to be thorough.

Have I done something terribly stupid?


texts: Creating a victory zone / Count units inside zone

texts:
So I am attempting to create a zone implementation where if the amount of units with a certain tag exceeds the number of units with another tag an objective will be captured standing in the zone will capture an objective.

However, the problem occurs when counting the units and what the most optimal way of doing it is which is what I hope you guys can help me with! (Also if you have a better way of implementing it then I am all ears).

So in my implementation, I have added a game object with a box collider which is set as a trigger collider

my idea was that as soon as a unit enters or leaves the script will update the count of users with a certain tag.

Should the count of one tag type be greater than the other the victory/capture condition will begin.

This is an ok solution however it has a major problem. Should one of the NPC's inside of the box collider die the script will never detect it as the body has never left the box.

So how do i overcome this problem in a sensable way?


texts: Instantiate from two values, each in separate array

texts:
I have a problem with Instantiating GameObjects from floats in arrays, which I have to merge into one Vector2 (or Vector3). I have only two values in arrays:
GameObject = somePrefab
float[] = value1
float[] = value2

First I have to combine them into a vector, then Instantiate as many prefabs as the combined vector number is...
Can anybody help me with how to merge these floats into a vector and instantiate?


texts: displaying image on modelmesh with transparency

texts:
i have a modelmesh that has a image on it. When i draw the modelmesh i get the image but i also get a black bacground. The image is png and transparent and is added in 3ds max(i don't give it coordinates to be drawn, it sits on the modelmesh). How can i make the black background transparent?

Here is my drawing code:

 foreach (BasicEffect effect2 in modelMesh)
 {
     effect2.DiffuseColor = Color.White.ToVector3();
     effect2.LightingEnabled = true;
     effect2.AmbientLightColor = new Vector3(1, 1, 1);
     effect2.Projection = camera.projectionMatrix;
     effect2.View = camera.viewMatrix;
     effect2.World = transforms[modelMesh.ParentBone.Index] * gameobject.orientation;
     effect2.Alpha = 1;

  }
  modelMesh.Draw();


texts: How can I handle invulnerability in an entity system?

texts:
I currently have an entity component system with messaging. The messages are delivered to each subscriber, but each subscriber gets their own copy, basically meaning that altering a message doesn't affect any other subscriber. While this works fine for now, I was wondering how I would add an invulnerable state.

I have a combat system that solves combat. It takes a combat event (an intent to attack something) and emits a resolved combat event. This event contains information of who attacked whom and what kind of damage they took. It also has a bool which gives the status of whether or not the defending entity is alive after the attack. It also controls the the HP and deletes the entity if it was killed.

I do not have a problem breaking down this system. A system that calculates damage, a system that applies the damage, and a system that kills the entity. But where do I add my invulnerability? If I simply make it a component, then it has to be handled by the system that applies damage. What if I want to add something else later? I have to build up and up the damage system and it has to handle all the little edge cases and intricacies. What if I want to add an attack that goes through invulnerability?

Clearly this is an exponential nightmare, which is exactly what I hoped to avoid with an ECS. How should I handle invulnerability?


texts:
I've made an object and when the player has pick it up, rise it up and stop it out of screen. But because you can see the shadow of that object, I will destroy it after the animation has played. But how can I do this whit Unity and C#?

Just destroy is just like this:

Destroy(gameobject);

and start an animation like this:

private Animator _anim;           // global variable
_anim = GetComponent<Animator>(); // in start() methode
_anim.SetTrigger("Picked");       // in other methode


texts: Prevent players from wallhacking in an online FPS?

texts:
Why do we still complain about wallhackers in multiplayer first-person shooters?

Isn't it possible to perform occlusion culling for all players server-side? For example, send player xyz information to client only when the player is visible in client's frustum and not occluded by any object ? Even if the collision-geometry is very, very simplified, most of the time cheater won't receive tactical information.

Why not do this?


texts: google play services resources not found error

texts: Everything used to work till yesterday but suddenly today I am getting this error as "Google play services resources not found".What may be the reason for it?


texts:
I created a rounded rectangle in photoshop, and I rasterized the rectangle before I saved it. Yet, when I try to use the rectangle in libGDX, it looks pixelated. How can I make it so that it's smooth?

Here is how my rectangle looks now:

My original image is 2048x2048, and I'm using batch to rescale it depending on the screen size. For example, this is how I draw the rectangle:

    batch.draw(img, Gdx.graphics.getWidth()/2-fitW/2, Gdx.graphics.getHeight()/2-fitH/2, fitW, fitH);

Where fitW and fitH depend on the current screen width and height (arbitrarily set to 300 now). So I'm essentially downscaling the original 2048x2048 rectangle to one that's 300x300. Can this be why the image is not rasterized?


texts:
I have this code which is rotating my camera object based on Gyro it is working fine

public void CalibrateYAngle()
    {
        calibrationYAngle = appliedGyroYAngle - initialYAngle; // Offsets the y angle in case it wasn't 0 at edit time.
    }

    void ApplyGyroRotation()
    {
        transform.rotation = Input.gyro.attitude; //
        transform.Rotate(0f, 0f, 180f, Space.Self); // Swap "handedness" of quaternion from gyro.
        transform.Rotate(90f, 180f, 0f, Space.World); // Rotate to make sense as a camera pointing out the back of your device.
        appliedGyroYAngle = transform.eulerAngles.y; // Save the angle around y axis for use in calibration.
    }
 public void Update() {

            ApplyGyroRotation();
            ApplyCalibration();

    }

but sometime my camera start to rotate slowly slowly automatically. It slowly rotate left or right but sometime not always. What I am doing wrong? due to inaccurate sensors values?


texts:
Background

I'm trying to implement a little MMORPG. I'm planning to use Cassandra DB for the database.

Question

I don't really understand which data should be store in DB and which one should be just kept in memory.

For example : the friend list. Friend list will be stored in DB, but what about connected / disconnected friends ? Should I keep in memory all connected account and access it directly ? Or should I store this information in the DB (therefore writing / reading quite often for something that could be kept in the memory) ?


texts: Reloading scene in Unity gives weird result

texts:
I am making an infinite racing game where you fly an airplane while trying to avoid obstacles. I recently finished my menu that comes up when you die. When I press the restart button that simply reloads the current scene like this:
SceneManager.LoadScene(1);
it gives me a weird result. The obstacles starts generating at about the same position as you died previously. I never get this problem when I start the game with the Unity play button. The only thing I could think off was player prefs. It should not affect the generation of obstacles but tried anyway to use:
PlayerPrefs.DeleteAll();
before reloading the scene, but that did not work. What could be causing this strange problem?


texts: bmGlyph alternative for windows (Bitmap font generator)

texts:
I have been using this tool (bmGlyph http://www.bmglyph.com/) to create fonts from apple machines, but now, I'm on windows and need a program with same / more features. The main features about this program is the possibility of give a grandient color and apply a texture to each glyph. Could anybody recommend something like this for windows?

Thanks in advance.


texts: Why do these DirectXMath functions seem like they return column-major matrics?

texts:
I know these questions have been asked a million times in various formats, but I'm getting weirdly skeptical about some of the row-major vs. column-major claims about the DirectXMath library.

If I run the following code to get a translation matrix for example:

DirectX::XMMATRIX a = DirectX::XMMatrixTranslation(1.0f, 1.0f, -1.0f));

I would expect the memory layout to look like the following (with rN indicating some row, but all the numbers contiguously in memory):

r1: 1.0   0.0   0.0   1.0      r2: 0.0   1.0   0.0   1.0     r3: 0.0   0.0   1.0  -1.0     r4: 0.0   0.0   0.0   1.0

This would correspond to the following matrix (in standard notation) where each row is stored as a contiguous array:

1.0   0.0   0.0   1.0
0.0   1.0   0.0   1.0
0.0   0.0   1.0  -1.0
0.0   0.0   0.0   1.0

Except when I look at the memory, it's the transpose of the above (i.e. the last array in memory is the last column above) which I'm to understand is "column-major" order. So, in memory, what I'm actually getting is this:

r1: 1.0   0.0   0.0   0.0     r2: 0.0   1.0   0.0   0.0     r3: 0.0   0.0   1.0   0.0     r4: 1.0   1.0   -1.0   1.0

This leaves me thoroughly confused with all the commentary and documentation around DirectXMath matrices needing to be transposed before putting them into HLSL constant buffers (of which I'm using the default column-major order). Everything states that DirectXMath matrices are stored in row-major order, but when I actually look at the memory (either as an XMMATRIX or a more direct XMFLOAT4X4) I find myself staring at a translation matrix that looks like it's been stored in column-major order.

So my confusion then lies in the fact that my transformations actually work when I don't transpose the matrices prior to putting them into the constant buffer.

Am I missing something here?


texts: Unity + UMA Power tools 2.10 - issues with saving prefabs

texts:
I just got familiar how to work with UMA 2 and I personally would like to use those characters as prefabs so bought the power tools package as well.
I managed to figure out how to save the dcs to prefab but prefab is missing the mesh. Any idea what I'm missing? Downloaded UMA 2 + power tools today so I don't think that it's version issue as well.
Screenshot from unity added
characters should be the same

Thanks already in advance!
Steps to reproduce:

install uma 2 + uma 2 power tools assets
Create new scene
Drag UMA_DCS and UMADynamicCharacterAvatar prefabs to scene from UMA/Getting Started
Modified the UMADCA to be human female with no wardrope
Press play from unity
Click the UMADCA to be active
From menu press UMA -> Powertools -> Save Characters Prefab
Choose location
Drag newly created prefab to scene
Result is empty character with needed assets (textures etc)


texts: How to rotate within a fixed interval in Unity?

texts:
I have very recently started to learn Unity.

I'm trying to write code that will make a character swing a flag. I want to use this object and rotate the arm up and down. So I need to make it rotate up and down with within 30 degrees.

This is my attempt but it simply keeps on turning. How would I make the hand rotate in motion within the interval [-30, 30] degrees.

private GameObject myobject;
public float timeElapsed =0;
public float delay = 3.0f;
float OO = 0.0f;

void Start () {
    myobject = GameObject.Find ("rightarm").gameObject;
}

void Update () {
    timeElapsed += Time.deltaTime;
    Debug.Log (timeElapsed);

    if (timeElapsed >= delay) {
        OO = 30.0f;
        timeElapsed = 0;
        if (myobject.renderer.enabled == false) {
            myobject.renderer.enabled = true;
        }

        myobject.transform.Rotate (OO, 0.0f, 0.0f);
    }
    else
    {
        myobject.transform.Rotate (-OO,0.0f, 0.0f );
    }
}


texts: How can I interpret NSF (Nintendo Sound Format) data as audio?

texts:
First, I'm not asking about details regarding the layout and format of an NSF file.  The original spec (see here) covers most of the information that I need regarding finding the data associated with each track.

My question is that once I've loaded an NSF and consumed the header, how can I meaningfully interpret the data for audio playback?  I've found multiple sites that talk about the NSF format, but I've yet to find a site that explains how the data can be used once the file has been dissected into all of it's components.  How do I read and prepare this audio information for playback?

I'm not looking to emulate an NES device but I would like to pull out the raw audio information (or calculate/convert the information to raw audio data.)

For those who are interested, this is for a personal fun project. I'd like to dissect some of these sound-bytes and convert them to audio that I can manipulate within my own application.  I'm completely new to audio processing but I've done my share of low-level work.  This seemed like a fun project where I'd be jumping in way over my head but I'd have fun trying to figure out all that I want to accomplish.

To start, though, I need to get audio data that I can manipulate from sources that I am interested.  in this case it's NES carts.  Since the cartridge data is already available in NSF files, I figured I'd dissect the NSFs rather than the ROM files for audio content.

Apologies if this questions is to big for a simple specification of data layout.  Any answer that can point me in the right direction is what I'm looking for.


texts: How can I make a sprite based animation using Cocos2d JS?

texts:
I am learning Cocos2d JS, but I can find very few tutorials and I find the documentation very vague. I can put a simple image on a layer like this:

var sprite = new cc.Sprite(res.my_image_png);
sprite.setAnchorPoint(0.5, 0.5);
sprite.setPosition(cc.winSize.width / 2, cc.winSize.height / 2);
this.addChild(sprite);

I can also move it like this:

var actionTo = cc.moveTo(2.5, cc.p(100, 100).easing(cc.easeInOut(1));

sprite.runAction(
    new cc.Sequence(
        actionTo,
        new cc.CallFunc(
            function() {
                cc.log("Animation complete");
            },
            this
        )
    )
);

How could I improve this code to also show some sprite-based animation? I would like to exchange the sprite image every 0.25 seconds. What is the designed way to do that in Cocos2d JS?


texts:
I'm working as an educator - I am wondering is there any way to wrap the text of lines output from the Unity editor console?...

Thanks!


texts: How to wait until other script is ready?

texts:
I have two scripts, first is AsteroidSpawner script that literally spawns object named Asteroid, and second is HUD that control all UI related stuffs.

There are some labels in UI, so I used onready to get those nodes:

extends CanvasLayer

class_name HUD

onready var asteroids_label = $Control/RightContainer/AsteroidCountLabel

func set_asteroids_label(value: float):
    asteroids_label.text = "Asteroids: " + str(value)
    pass

However, when I try to access HUD script, with setasteroidlabel, it gives me null error:

var spawned_asteroids: Array = []
onready var hud: HUD = get_tree().get_root().find_node("HUD", true, false)

func _ready():
    spawn_asteroids()

func spawn_asteroids():
    ... spawn asteroid ...

    spawned_asteroids.push_back(asteroid_instance)

    hud.set_asteroids_label(spawned_asteroids.size()) # UPDATE HUD

  Invalid set index 'text' (on base: 'Nil') with value of type 'String'

I guess that HUD is not ready, but AsteroidSpawner script try to accessing it, wasn't it? Then how should I wait until HUD is loaded?


texts: How can I prevent 2D teleportation from teleporting through solid objects?

texts:
In my 2D game, the player is able to teleport to any place on the screen with the click of the mouse button. What I am trying to prevent is the ability to teleport across solid objects. If the point from the player and the mouse click position is across an object then I want the player to teleport next to that object instead of across it.

I am currently trying to achieve this with raycasting. The code I wrote somewhat works but only if the mouse click is on an object, if the mouse click is across another object, it still teleports me accross the object without it registering that there is an object between the player and the mouse position.

My code:

Vector3 player_position = Camera.main.WorldToScreenPoint(transform.position);
Vector3 to_object_vector = transform.position - Camera.main.transform.position;
Vector3 linear_distance_vector = Vector3.Project(to_object_vector, Camera.main.transform.forward);

float distance_to_camera = linear_distance_vector.magnitude;
Vector3 mouse_position = Input.mousePosition;
float dist = Vector2.Distance(player_position, mouse_position);
Vector3 dir = (mouse_position - player_position).normalized;
mouse_position.z = distance_to_camera;

RaycastHit2D hit = Physics2D.Raycast(new Vector2(player_position.x, player_position.y), new Vector2(dir.x, dir.y), dist, 0);
if (hit.collider != null) {
     Debug.Log(hit.point);
     mouse_position = new Vector3(hit.point.x, hit.point.y, mouse_position.z);
}

Is there a better approach to this problem?


texts:
Is there any editor out there that would allow me to define complex entities, with joins connecting their multiple bodies, instead of regular single body entities? For example, an editor that would allow me to 'define' a car as having a main body with two circles as wheels, connected through joints.

Clarification:

I realize I haven't been clear enough about what I need. I'd like to make my engine data-driven, so all entities (and therefore their Box2D bodies) should be defined externally, not in code.

I'm looking for a program like Code 'N' Web's PhysicsEditor, except that one only handles single body entities, no joints or anything like that. Like PhysicsEditor, the program should be configurable so that I can save the data in whatever format I want to. Does anyone know of any such software?


texts: How do I allocate to a C# dictionary having a string key and an integer 2D array or transform for value?

texts:
I'm working in C# on a Unity 2D game that spawns a shape that has only one correct landing place. There are 7 basic shapes but the component 4 squares of each shape are unique, with each bearing, say, a unique number. There are many more than 7 unique shapes because any component square is unique to the shape set. So the shapes have squares bearing a unique number (1,2,3,4 on a square; 5,6,7,8 on another square; 9,10,11,12 in a line (I-shape), 13,14,15,16 in another line (I-shape), etc. each of these shapes must be moved (by dragging, dropping or rotating) to its particular place in the grid.

I need to swiftly (1) indicate whether a shape has landed correctly and, if not, (2) move the misplaced (and possibly mis-rotated) shape to its proper location so that remaining falling pieces are not blocked from attaining their correct placements.

For (1), I'm  using a dictionary with a string for the key that identifies the square component of the shape and an integer 2D array for the grid location values. Here is the declaration:

Dictionary<string, int[,]> dictOfProperLocations = new Dictionary<string, int[,]>();

Visual Studio is OK with that. But I am unable so far to allocate key-value pairs to the dictionary. I've tried the following and variants to indicate that a straight shape (an I-shape) bearing the numbers 1-4 belongs at the origin at its left end and stretches straight to the right:

dictOfProperLocations.Add("1", [0,0]);
dictOfProperLocations.Add("2", [1,0]);
dictOfProperLocations.Add("3", [2,0]);
dictOfProperLocations.Add("4", [3,0]);

But Visual Studio objects to that. I find many examples for C# dictionaries with string-keys and 1D-array-values, but no examples for this case with 2D-array-values.

Or might this be better handled with a 2D Transform[,] for the values representing the proper grid locations? Thank you.


texts:
How to drag an andEngine sprite anywhere on the phone screen?

I have written this code in onAreaTouched function of IOnAreaTouchListener interface which is implemented in my activity, but its not working:

public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
      ITouchArea pTouchArea, float pTouchAreaLocalX,
      float pTouchAreaLocalY) {
    // TODO Auto-generated method stub

    Log.v(TAG,"Sprite Touched ##########");

    secondSprite = new
    Sprite( CAMERA_WIDTH/2, CAMERA_HEIGHT/2,
            playerTextureRegion, this.getVertexBufferObjectManager()){
        @Override
        public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
                                     final float pTouchAreaLocalX,
                                     final float pTouchAreaLocalY) {
            secondSprite.setPosition(pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
            System.out.println(String.format("spriteB %fx%f", pSceneTouchEvent.getX(),
                pSceneTouchEvent.getY()));
            return true;
        }
    };
    scene.registerTouchArea(secondSprite);
    return true;
}


texts: Breakout Collision Detection: Ball gets trapped inside block

texts:
I'm writing a breakout clone where blocks to hit can be of various sizes and the projectile can move at different speeds, and I seem to be having some trouble getting the collision detection perfectly right.

I have a side-detection algorithm working just fine (projectile reflects in the proper direction when hitting top/side of a block), but sometimes the projectile seems to get stuck inside the blocks, especially when the projectile is moving fast. The function I have simply tells the projectile to reflect it's X or Y axis, but, when the projectile can't get away from the block in time, it gets trapped constantly reflecting on its axes, causing it to "freak out" and get trapped bouncing around inside the block itself.

I attempted to fix this by disabling collision detection for a very short time after each detected collision (defined as PROJECTILE_TICK = 0.05f in the code below), but this doesn't seem to solve the problem, and the projectile still gets trapped.

Is there a standard way this sort of problem is typically handled? I know I'm far from the first person to try and make a breakout clone, so someone must have run into this problem before.

My collision detection function is below. The blocks are referred to as "ptfm" in the code below.

 private void checkPlatformCollisions(float deltaTime) {
    tickTime += deltaTime;

    for(int i = 0; i < projectiles.size(); i++) {
        Projectile proj = projectiles.get(i);

        for(int j = 0; j < platforms.size(); j++) {
            Platform ptfm = platforms.get(j);
            if (OverlapTester.overlapCircleRectangle(proj.boundingRadius,
                    ptfm.bounds)) {

                if(ptfm.breakable) {
                    //this part works just fine; it's the else clause that's screwy

                    }
                } else {

                    //tick is so projectile wont get stuck in a reflection loop
                    //move these to the projectile class later
                    if(tickTime > PROJECTILE_TICK) {

                        //reset tick time
                        tickTime = 0;

                        if(ptfm.type == Platform.PLATFORM_TYPE.WALL) {
                            proj.reflectX();
                            continue;
                        }

                        float angle = (float) Math.atan2(ptfm.pos().y - proj.pos().y,
                                ptfm.pos().x - proj.pos().x);

                        //atan2 returns in radians
                        angle *= Vector2.TO_DEGREES;

                        if(angle < 0) {
                            angle = 360 - (-angle);
                        }

                        if ((angle >= 0 && angle <= 45) ||
                                (angle >= 315 && angle <= 359)) {
                            //hit from top
                            proj.reflectX();
                        } else if ((angle >= 45 && angle <= 135)) {
                            //hit from left
                            proj.reflectY();
                        } else if ((angle >= 135 && angle <= 225)) {
                            //hit from bottom
                            proj.reflectX();
                        } else if ((angle >= 225 && angle <= 315)) {
                            //hit from right
                            proj.reflectY();
                        } else {
                            proj.reflectX();
                        }

                    }

                }

            }

        }
    }


texts: Keeping a object(world space canvas) always in the cameras viewport

texts:
So I have the following problem: I have a world space canvas following a arrow that moves around the screen. The canvas itself is just a child of the arrow. The problem is that sometimes when the arrow is pointing to something on the edge of the screen parts of the canvas go off screen. I want to write some code that keeps the entire canvas inside the viewport at all times. I found a solution online but this keeps the pivot point of the object inside the camera bounds and not the whole object. I simply cant figure out how to keep the whole object inside the camera bounds. Here is the code I have :

void LateUpdate()
{
  transform.rotation = rotation;// This simply keeps the objects original rotation independant from the parent
  Vector3 pos = Camera.main.WorldToViewportPoint(transform.position);
  pos.x = Mathf.Clamp01(pos.x);
  pos.y = Mathf.Clamp01(pos.y);
  transform.position = Camera.main.ViewportToWorldPoint(pos);
}

Edit: this is how it looks with the first answer:
The gif is too large to upload so here is a link to it.


texts:
I am memory profiling my game in Visual Studio and about 60% of memory usage is happening from calls to glBufferData(). I may be missing something but should this consume GPU memory instead of system memory? I call it using GL_ARRAY_BUFFER and GL_STATIC_DRAW I was just wondering is there a way I can force it to use only VRAM?

Visual Studio attributes the memory usage to "nvoglv32.dll"


texts: OpenGL binding and relations among entities

texts:
This is mostly a documentation question. I hope this is the proper place to ask and not, for example, programmers or stackoverflow.

I did not read the OpenGL specification, but from books (Red Book) and various tutorial, I cannot properly grasp how different objects and parts of the API interact and relate.

For example, I know that if a VAO is bound, then binding a VBO and setting an attribute will result in the VBO being bound to the VAO.

But there are many objects, their relation may vary. For example, the VAO is completely unrelated to the current shading program, but the outcome of drawing operations may depend on both of them.

Among all the various OpenGL components, I can see some relations like A-binds-to-B or A-and-B-are-used-by-C. All these relations concur in determining how one can alter the state of the context, how can change things, how can save things together and optimize.

I am looking for resources explaining just these relations. Like an UML diagram, a graph, or even a text document, which does not focus about the calls, but describes in a compact way how the various OpenGL components interact and relate one to each other.

Do you know where to find such a resource?


texts: How can I make libGDX text buttons look like clickable buttons?

texts:
I have this problem with my game where UI build a nice menu and other stuff with TextButtons and labels, but it doesn't look nice because it's mostly displaying the text of the buttons (which don't look like they are buttons).

Right now I'm using this little snippet of code to style my TextButtons:

TextButton.TextButtonStyle buttonStyle = new TextButton.TextButtonStyle();
buttonStyle.font = new BitmapFont();
buttonStyle.fontColor = WHITE;

What do i need to add to make them look like a button and not like simple text? I'm using libGDX.


texts: Is it possible to work out rotate in degrees per second based on this rotate logic?

texts:
I have this code to rotate an object towards another at a given speed.

    /// <summary>
    /// Rotate towards the target.
    /// </summary>
    /// <param name="lookPosition"></param>
    private void RotateTowardsTarget(Vector3 lookPosition)
    {
        // Determine which direction to rotate towards
        Vector3 targetDirection = lookPosition - transform.position;

        // The step size is equal to speed times frame time.
        float singleStep = weaponRotationSpeed * Time.deltaTime;

        // Rotate the forward vector towards the target direction by one step
        Vector3 newDirection =
            Vector3.RotateTowards(turretYRotation.transform.forward, targetDirection, singleStep, 0.0f);

        // Draw a ray pointing at our target in
        //Debug.DrawRay(turretYRotation.transform.position, newDirection, Color.red, 3);

        newDirection.y = 0;
        // Calculate a rotation a step closer to the target and applies rotation to this object
        turretYRotation.transform.rotation = Quaternion.LookRotation(newDirection);
    }

And I'd like to convert this to a "Degrees per second" to give the user useful feedback on how quickly it rotates. Is there a formulae I can apply to work it out?


texts: How to fill/initialize D3D11_SAMPLER_DESC properly?

texts:
If I want to set explicitly every parameter of the structure I just do so and that's it. But what if I want to set only some of them and leave the rest with default values? I've seen in some tutorial zeroing the structure:

ZeroMemory(&samplerDesc, sizeof(D3D11_SAMPLER_DESC));

but the default values (http://msdn.microsoft.com/en-us/library/windows/desktop/ff476207%28v=vs.85%29.aspx) aren't always 0. Is this incorrect? Should I always specify all values explicitly (especially LOD values seem tricky)?

I'm asking about D3D11_SAMPLER_DESC but maybe the same rules apply to other DX structures?


texts: Creating an AABB is simple. But, if the 3d model has become rotated, how do you update the AABB to become accurate? Or is the AABB supposed to be in local space?


texts: AS3: Using a SharedObject for showing/hiding a Tutorial

texts:
Basically, I am either having trouble understanding how to use SharedObjects correctly, or I am not properly referencing a variable (from a seperate class from which it is defined) within a SharedObject, and I think the latter is my problem, although I’m not sure.

When my character dies, my game goes to a game over screen, where I create 2 variables within a SharedObject: the bestScore (user’s all-time best score in the game) and then a tutorialBoolean (which will determine if the tutorial shows up or does not in future game play). My bestScore works 100% fine, so I set that up correctly. Now the problem is, in a different class, I want to make an if statement, so that if my tutorialBoolean does not exist or is true, the tutorial runs, and if it is false, the tutorial does not run.

When I try to say

if (sharedObject.data.tutorialBoolean) {runTutorial()}

I get TypeError: Error #1009: Cannot access a property or method of a null object reference. And I am sure that it's having trouble with the sharedObject because I have created a tutorialBoolean without using SharedObjects and it works just fine. So all in all, I just want to be able to make an if statement in separate class than where my sharedObject variable is defined. I will probably have to use

if (sharedObject.data.tutorialBoolean == null)...

or

if (sharedObject.data.tutorialBoolean == "undefined")...

although I'm not really sure which one to use....neither is working at the moment. Shouldn't one of these work no matter what?...I mean if my variable is non existent surely one of these would work...

GameOver Class

package  {

    import flash.display.MovieClip;
    import flash.display.SimpleButton;
    import flash.events.MouseEvent;
    import flash.text.TextField;
    import flash.ui.Mouse;
    import flash.net.SharedObject;

    public class GameOver extends MovieClip {

        public static var sharedObject:SharedObject;
        public var finalScore:TextField;
        public var bestScore:TextField;

        public function GameOver() {

            sharedObject = SharedObject.getLocal( "smgScores" );
            sharedObject.data.tutorial1BooleanShared = false;
            sharedObject.flush();
        }

        public function onClickRestart(mouseEvent:MouseEvent):void
        {
            dispatchEvent( new NavigationEvent( NavigationEvent.RESTART ) );
        }

        public function onClickMainMenu(mouseEvent:MouseEvent):void
        {
            dispatchEvent( new NavigationEvent(NavigationEvent.MAINMENU));
        }

        public function setFinalScore( scoreValue:Number ):void
        {
            trace(sharedObject.data.bestScore);
            try
            {
                finalScore.text = scoreValue.toString();
                if ( sharedObject.data.bestScore == null )
                {
                    sharedObject.data.bestScore = scoreValue;
                }
                if ( scoreValue > sharedObject.data.bestScore )
                {
                    sharedObject.data.bestScore = scoreValue;
                }
                bestScore.text = sharedObject.data.bestScore.toString();
                sharedObject.flush();
            }
            catch( sharedObjectError:Error )
            {
                trace( "Caught this error:", sharedObjectError.name, sharedObjectError.message );
                bestScore.text = "change flash storage options";
            }
        }

}

and in my playScreen class I basically just want to be able to say

if (GameOver.sharedObject.data.tutorial1BooleanShared)
{
    runTutorial1();
}

But I get the error as I said above. I'm not sure if it's worth reconstructing my classes a bit and using sharedObjects in different places, or if there is a simple fix. I like the structure I have at the moment, so the latter is preferable. Thanks!


texts:
I'm implementing arcball camera rotation, whereby a camera is looking at a coordinate and rotates around it in the x-axis or the y-axis such that the camera is circulating around it; the y-axis will be capped to prevent flipping.

Suffice it to say it's not producing the output I want as it isn't rotating around the target. I'm not sure where the problem may lie, though my code:

void Camera::rotate(float x, float y)
{
    x *= pMouseSensitivity;
    y *= pMouseSensitivity;

    pYaw += x;
    pPitch += y;

    if (pPitch > 89.0f)
        pPitch = 89.0f;
    if (pPitch < -89.0f)
        pPitch = -89.0f;

    pPosition = glm::rotate(pPosition, -x, pUp);
    pPosition = glm::rotate(pPosition, -y, pRight);
}

The rotate function takes in x and y from where the mouse position is at. These values are then added to yaw and pitch respectively before the position of the camera is rotated based on the x and y. I update the camera as follows:

void Camera::update()
{
    pForward = pPosition - pTarget;
    pRight = glm::normalize(glm::cross(pForward, pWorldUp));
    pUp = glm::normalize(glm::cross(pForward, pRight));

    pViewMat = glm::lookAt(pPosition, pTarget, pUp);
    pProjMat = glm::perspective(pFieldView, pAspectRatio, pNearPlane, pFarPlane);
}

The world up vector is always vec3(0, 1, 0) and is unchanged throughout, for resetting the camera. I set the target of the camera with:

void Camera::orbitAround(glm::vec3 focus)
{
    pTarget = focus;
}

This function would then take in an arbitrary point or even the position of a 3D rendered model. I have been looking at a few tutorials regarding arcball rotation, and from what I can understand it involves pTarget being what's looked at, and the rotation revolving around it. What does strike me is that I'm not using pitch and yaw, so will have to look into what I should be doing with them. Producing the arcball rotation is what confuses me, and I require some help on it. Pseudocode would be great!


texts:
I am currently shifting from unity to monogame to make 2d platformers. I am not aware of any sort of "raycasting" provided with monogame, I am aware of AABB collision detection and I am planning to implement it.
I was wondering how do I deal with slope detection. Making a level without slope would make it look very bland to my liking and I want to some slopes in it. Is there any way to achieve slope detection?
Thanks


texts: Making sense of the positions of gameObjects

texts:
Project files: https://github.com/Sebastian-Nielsen/makingSenseOfPositions

Note: There are no scripts running, all I am doing in between each picture is manually changing the x-coordinate in the inspector of the given gameObject.

See the problem: Gif

Here we got my lovely little scene

Now, take note on the x-position of the tile the dark soldier is standing upon; it's -13.78.

Take a look at the Dark Soldier's x-position now. There is a difference of 3 between those two on the x-axis!

Now, look what happens when I change the x-coordinate of the Dark Soldier to -13 to match that of the tile. (I expect the Dark Soldier to now be precisely on top of the tile he was standing on in the first picture -- maybe he was a little off in that pic).

Wait what? He moved away from the tile at position x=-13.

Why is that?! I think I'm going crazy! Please make sense of this, why is this happening?


texts: In Maya- how can I merge mulitple primitive cubes together into one parent item? (And is this actually needed for using in unity etc)?

texts:
Im trying to make some 3d models in Maya and then put them into Unity as characters which I can give rigidbody to etc. (Im new to Unity and 3d modelling software, but i have a small amount of programming experience in LWJGL,  LibGDX  and XNA).

I'm focusing on making some assets out of blocks. To give a kind of 2.5D feel to a platform game.

I have made the following image but as you'll see its just a bunch of cubes. I think i need this to be turned into a single piece (but im not sure if 100% necessary or not). Of course, I will be adding animation to this by way of moving the blocks about for different frames of animation.

As I said, im very new to this so I may be doing things completely wrong.

Heres the image:

What i need is to be able to refer to this as one piece with its own transform position, scale etc that I can adjust. Currently if I select it all and try to change the scale it only changes on of the cubes scale even when all are selected.

Also once I've created this and want to add it to my game in unity, will each cube get a rigidbody when i add it or will the whole item get it as standard?

Thanks for any help


texts: How to use a boolean to activate every item with the same tag?

texts:
I've been really stuck on this one and need some help.

I've got some accessories for my player, and my goal is to have a collider,
with the script attached. When the player walks into the script, the inactive model components on the player, will be set to active.

This is the script I'm using:

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

public class ItemEquip : MonoBehaviour
{
    public GameObject[] Apparel;
    public bool SetActive;

    void Start()
    {
        Apparel = GameObject.FindGameObjectsWithTag("Apparel");
    }

    void OnTriggerEnter(Collider ApparelCollect)
    {
        if (ApparelCollect.CompareTag("Player"))
        {
            GameObject[] clothes = GameObject.FindGameObjectsWithTag("Apparel");
            foreach (GameObject apparel in clothes)
            {
                apparel.SetActive(true);
            }
        }
    }
}

I'm really stuck on this. It's something basic but despite trying several tutorials, asking some people I know and experimenting, nothing is getting this script to work.

What I've tried:
-Deactivating the individual components
-Attaching a script to each component, along with the trigger
-Activating the individual components (from inspector)
-Activating the script (from inspector)
-Double checking that each component I want affected has the Apparel tag
-Cry in a corner

I've been going around in a loop for ages trying to get this thing to work, but still nothing.

I'm self taught on game development, working on my first game. I've read the Unity manual (that absolutely did not help) as well as hit up YouTube and multiple forums, all with no luck.


texts: Are there any math limitations on the near plane in a perspective matrix?

texts:
I've noted that if in the perspective camera I put near plane to a low number like 0.000001 and far plane to 1000 my render has some problems, like strange depth artifacts (see images below) or division by zero during the unprojection procedure.

I'm not very skilled in math but there should be something strange because if I put near plane at 0.1 everything is working as expected.

Is there any mathematical limitation to the near plane value I'm not aware of?

I'm on WebGL with JavaScript (I'm not using Three.js; my question is related to the math, not to a particular framework). If it matters, I'm using Float32Array to store matrices, and I'm using those libraries to do the math:

https://github.com/Jam3/camera-unproject
https://github.com/stackgl/gl-mat4
https://github.com/stackgl/gl-mat4/blob/master/perspective.js

In particular the division by zero happens here:

function project (out, vec, m) {
  var x = vec[0],
    y = vec[1],
    z = vec[2],
    a00 = m[0], a01 = m[1], a02 = m[2], a03 = m[3],
    a10 = m[4], a11 = m[5], a12 = m[6], a13 = m[7],
    a20 = m[8], a21 = m[9], a22 = m[10], a23 = m[11],
    a30 = m[12], a31 = m[13], a32 = m[14], a33 = m[15]

  // DIVISION BY ZERO HERE:
  var lw = 1 / (x * a03 + y * a13 + z * a23 + a33)

  out[0] = (x * a00 + y * a10 + z * a20 + a30) * lw
  out[1] = (x * a01 + y * a11 + z * a21 + a31) * lw
  out[2] = (x * a02 + y * a12 + z * a22 + a32) * lw
  return out
}


texts: If two objects interact, what holds the interaction code?

texts: Think of a bullet and an enemy, or the player and the floor. If these objects interact, what holds the interaction code?


texts:
I recently converted the display style of a isometric map from staggered to diamond and I can't figure out the tile picking process.
I'm well aware of the other existing threads regarding this subject and I read all of them but I haven't figured out a solution (my concentration these days is a mess)
I'm using a very basic system which consists of passing through all tiles and pick the one where the mouse points at (something like this Map.Tile.Intersects(mouse.Rect) ) and then with the help of a color map I pick the correct tile.
But I don't like this system because is pretty inefficient compared to some mathematic solutions I saw and didn't understand.
So here is the code I use to create the map :

                int x = 128 * j;
                int y = 64 * i;
                int isoX = (6 * 64) + (x - y);
                int isoY = (x + y) / 2;

128 is the tileWidth , 64 tileHeight and 6 * 64 is the xOffset

And the coordinates are like this :

Can somebody give me some hints or explain what I should do ?
Thank you.


texts: Texture Wrapping isn't being applied properly

texts:
I've debugged my application with codeXL and can verify that my texture is getting these attributes applied:

GL_TEXTURE_MIN_FILTER: GL_LINEAR
GL_TEXTURE_MAG_FILTER: GL_LINEAR
GL_TEXTURE_WRAP_S: GL_CLAMP_TO_EDGE
GL_TEXTURE_WRAP_T: GL_CLAMP_TO_EDGE
GL_TEXTURE_WRAP_R: GL_CLAMP_TO_EDGE

With the following UV data:

0, 0,
1, 0,
1, 1,
1, 1,
0, 1,
0, 0,
0, 0,
1, 0,
1, 1,
1, 1,
0, 1,
0, 0,
0, 1,
0, 1,
0, 0,
0, 0,
0, 0,
0, 1,
1, 1,
1, 1,
1, 0,
1, 0,
1, 0,
1, 1,
0, 0,
1, 0,
1, 0,
1, 0,
0, 0,
0, 0,
0, 1,
1, 1,
1, 1,
1, 1,
0, 1,
0, 1

Yet my cube still looks like this:
http://imgur.com/Dj2hCkp

The Front and Back are being mapped fine, but the sides and top/bot are all stretched. I've tried with GL_REPEAT, GL_CLAMP_TO_EDGE/BORDER, GL_MIRRORED_REPEAT, it's all the same result. I've tried only doing it with S and T. At this point I'm not sure what the problem is.

Vertex Shader + fragment + Buffers: (It's not that long)

https://ideone.com/5U39M3

I'm not really sure what it could be at this point. I thought my texture wasn't getting it's attributes applied correctly, but it is. Then i thought it was just my wrapping method, but all methods lead to the same result.


texts: Xna Equivalent of Viewport.Unproject in a draw call as a matrix transformation

texts:
I am making a 2D sidescroller and I would like to draw my sprite to world space instead of client space so I do not have to lock it to the center of the screen and when the camera stops the sprite will walk off screen instead of being stuck at the center. In order to do this I wanted to make a transformation matrix that goes in my draw call.

I have seen something like this: https://stackoverflow.com/questions/3570192/xna-viewport-projection-and-spritebatch

I have seen Matrix.CreateOrthographic() used to go from Worldspace to client space but, how would I go about using it to go from clientspace to worldspace?

I was going to try putting my returns from the viewport.unproject method I have into a scale matrix such as:

blah = Matrix.CreateScale(unproject.X,unproject.Y,0);

however, that doesn't seem to work correctly.

Here is what I'm calling in my draw method(where X is the coordinate my camera should follow):

Vector3 test = screentoworld(X, graphics);
var clienttoworld = Matrix.CreateScale(test.X,test.Y, 0);
animationPlayer.Draw(theSpriteBatch, new Vector2(X.X,X.Y),false,false,0,Color.White,new Vector2(1,1),clienttoworld);

Here is my code in my unproject method:

Vector3 screentoworld(Vector2 some, GraphicsDevice graphics):

Vector2 Position =(some.X,some.Y);
var project = Matrix.CreateOrthographic(5*graphicsdevice.Viewport.Width, graphicsdevice.Viewport.Height, 0, 1);
var viewMatrix = Matrix.CreateLookAt(
  new Vector3(0, 0, -4.3f), new Vector3(X.X,X.Y,0), Vector3.Up);

//I have also tried substituting (cam.Position.X,cam.Position.Y,0) in for the (0,0,-4.3f)

 Vector3 nearSource = new Vector3(Position, 0f);
 Vector3 nearPoint = graphicsdevice.Viewport.Unproject(nearSource,
        project, viewMatrix, Matrix.Identity);

return nearPoint;

I would also like to be able to move the camera around without moving my sprite.  Before I was doing something like:

if(directionofsprite == positive && sprite position is not less than 200)
 {
   sprite-=5;
   map-=5;
 }

This would make it appear as though the camera is moving to the right.  I just want to simplify all of this by making my sprites draw to worldspace.


texts: How do I transform from local points to world when using a scroll view?

texts:
I'm using a scroll view to store my game character icons (basically an RPG). The movement system for the characters is tile based, but in game hazards could be located anywhere. So I need to detect if a certain tile will interset with a hazard if a character moves into it. To do this I can calculate the corners of the tile using the co-ordinate system of the scroll view. I thought I could turn these into world co-ordinates then query to see if the collider attached to the hazard contains the point (the collider could be rotated so I can't just do the math myself).

When I try to convert the co-ordinates into world co-ordinates though the numbers I get just don't match up. For example, the lower left corner of the tile a character will move into is at (-1250.0, -938.0). If I convert that to world co-ordinates I get (-28.7, -49.8). The actual position for the hazard I'm testing against has a world position of (-8.0, -1.5, 93.4) though and the test tile should be right on top of it.

I'm using code like this to try to get the world co-ordinates:

  Vector2 charPosition5 = travellingCharacter.owningGameObject.GetComponent<RectTransform>().transform.TransformPoint(travellingCharacter.GetComponent<RectTransform>().anchorMax);
  Vector2 charPosition6 = travellingCharacter.GetComponent<RectTransform>().transform.TransformPoint(travellingCharacter.owningGameObject.GetComponent<RectTransform>().anchorMin);

Can someone tell me what values I should be feeding in or what other function I should be using please?


texts: Map displacement transformation to texture space?

texts:
I am trying to displace geometry in object space without giving the appearance of texture warping.

My idea is to displace the UV lookup by a relative amount to the geometry displacement.

Any ideas on how I can do this?


texts: Why I'm getting ArgumentException: failed to convert parameters when trying to load a scene?

texts:
I have two scenes the first one and the one that is loading when running the game is main menu. The second scene is scene002.

I want to load scene002.

In the main menu scene I have a button.
Attached to the button this script:

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

public class LoadSceneOnClick : MonoBehaviour
{
    private bool loaded = false;

    public void LoadByIndex(int sceneIndex)
    {
        SceneManager.LoadScene(sceneIndex);

        SceneManager.sceneLoaded += SceneManager_sceneLoaded;
    }

    private void SceneManager_sceneLoaded(Scene arg0, LoadSceneMode arg1)
    {
        if (arg0.isLoaded == true)
        {
            loaded = true;
        }
    }

    public void ActivatePlayer(GameObject player)
    {
        if (loaded == true)
        {
            player.SetActive(true);
        }
    }
}

When loading the scene002 i want to enable the Player.

In the button On Click I added to the list the two methods LoadByIndex and ActivatePlayer but when I click the button the player object I dragged to the inspector of the button is gone and I'm getting this exception:

ArgumentException: failed to convert parameters
System.Reflection.MonoCMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:484)
System.Reflection.MonoCMethod.Invoke (BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:528)
System.Reflection.ConstructorInfo.Invoke (System.Object[] parameters) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/ConstructorInfo.cs:77)
UnityEngine.Events.PersistentCall.GetObjectCall (UnityEngine.Object target, System.Reflection.MethodInfo method, UnityEngine.Events.ArgumentCache arguments) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:469)
UnityEngine.Events.PersistentCall.GetRuntimeCall (UnityEngine.Events.UnityEventBase theEvent) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:436)
UnityEngine.Events.PersistentCallGroup.Initialize (UnityEngine.Events.InvokableCallList invokableList, UnityEngine.Events.UnityEventBase unityEventBase) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:609)
UnityEngine.Events.UnityEventBase.RebuildPersistentCallsIfNeeded () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:775)
UnityEngine.Events.UnityEventBase.PrepareInvoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:811)
UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:53)
UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:36)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:45)
UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:50)
UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:261)
UnityEngine.EventSystems.EventSystem:Update()


texts: What are atan and atan2 used for in games?

texts:
I am having some trouble understanding Math.tan() and Math.atan() and Math.atan2().

I have basic knowledge of trigonmetry but the usage of SIN, COS, and TAN etc for game development is very new to me.

I am reading on some tutorials and I see that by using tangent we can get the angle in which one object needs to be rotated by how much to face another object for example my mouse. So why do we still need to use atan or atan2?


texts: Which Python package/library is best for this kind of game?

texts: I'm wanting to make a small scale version of the game Hearthstone and other 2d games that I can implement self-learning ai in. I was wondering which python GUI would be best to display them. It would need buttons and the ability to place images in specific locations in the GUI.


texts: Where to generate data in an Entity-Component System?

texts:
So I'm making a small game where I generate 2D landscape using perlin noise when the game first loads.

I've got it working in a OO way, but want to move over to an ES architecure, and I'm  just struggling to work out the right place for the code that does the generation to go?

In OO world, I have a World object which gets passes a coordinate value that is used as the seed for the perlin noise, and generates all the points for the land mass when the world is created.

I'm thinking I need a World component with a coordinate field on it - that's an easy part.

From there - is it right for a component to generate data when it's first initialised (or is that too OO?)?
Or should a System be doing that instead, when the game first starts?

Or... some other solution I'm not aware of?

Thanks in advance for any guidance.


texts:
I've run into the following problem. I'm following some tutorials for shading to the exact letter.
It all works except my meshes have really bad shadowing in/on them.

I see the difference with the tutorial: the Clamp UVs checkbox in the SceneTexture nodes has disappeared from the material editor GUI.. How should I replace this function? I already have some clamps in my blueprint but they are also part of the tutorial so they aren't there to replace the checkbox that disappeared under "Scene Texture Id".

Many thanks!


texts: How can I animate 2d sprite rotation without interpolation?

texts:
I would like to animate a weapon being swung in 2 frames - all I'm doing is changing the position and rotation of the weapon sprite. However, I don't want unity to interpolate the rotation (generate sub-frame rotations that smooth out the animation).

How can I do this? Using flat curves (constant tangents) does not work, and my options seem to be Euler interpolation and Quaternion interpolation (there is no "No interpolation" option).

I would like to not have to make spritesheets for every frame of every weapon.

Edit: Here is my current solution, which isn't ideal since I have to specify the number of frames and the speed I want per weapon

IEnumerator AnimateAttackManually () {
    float numFrames = attackFrames-1; // 1 frame per second, zero indexed
    for(int currentFrame = 0; currentFrame <= numFrames; currentFrame++){
        animator.Play("Attack", -1, (currentFrame/numFrames));
        animator.speed = 0;
        yield return new WaitForSeconds(1/attackSpeed);
    }
    animator.Play("Idle");
}


texts: Html5 games, what is the standard dimension to use?

texts:
I am trying to make html5 games to be played on the browser(not offline apps), and I am trying to support the maximum number of platforms, hence I need to know what dimension should I use for the game canvas so that it works in the most number of places.

Also is there anyway to "scale" a large game to fit in the tiny size of iphone(around 320x356px I think). By "scale" I don't mean to actually resize just the canvas, as because that can mess up the coordinate based calculations, and for a large number of objects, re-positioning based on canvas size can be a real hassle.


texts: Why does my implementation of "is 2D point inside 2D polygon" have slightly different results on either side of the same axis?

texts:
My 2D game is tile-based, 16 pixels per tile. Colliders are defined by an array of points which determine a polygon. With debugging enabled (as it is in the photos) those colliders are outlined with red lines. You can see this on the player and on the water tiles I am using to explain the issue.

The following two photos are both what happens when the player moves leftwards into the collider of the water tile.

The difference between these two photos is the fact that the player's collider collides with the tile collider on its corner. The second picture represents the desired effect. I should clarify that in the photos, the second (lower) water tile is not required to be there to have the same effect.

Currently this issue only happens when approaching a tile collider moving upwards or leftwards. This has the effect of preventing the player from moving along the tile into a new tile - the corner of the adjacent tile catches the player's collider and stops movement.

Here is the code I'm using to determine if a point is within a polygon. This function is called on each point that makes up the collider of the player.

def self.point_in_poly(testx, testy, *poly)
  return false if outside_bounding_box?(testx, testy, *poly)

  point_in_poly = false
  i = -1
  j = poly.count - 1
  while (i += 1) < poly.count
    a_point_on_polygon = poly[i]
    trailing_point_on_polygon = poly[j]
    if point_is_between_the_ys_of_the_line_segment?([testx, testy], a_point_on_polygon, trailing_point_on_polygon)
      if ray_crosses_through_line_segment?([testx, testy], a_point_on_polygon, trailing_point_on_polygon)
        point_in_poly = !point_in_poly
      end
    end
    j = i
  end
  return point_in_poly
end

private

def self.point_is_between_the_ys_of_the_line_segment?(point, a_point_on_polygon, trailing_point_on_polygon)
  (a_point_on_polygon[1] <= point[1] && point[1] < trailing_point_on_polygon[1]) ||
  (trailing_point_on_polygon[1] <= point[1] && point[1] < a_point_on_polygon[1])
end

def self.ray_crosses_through_line_segment?(point, a_point_on_polygon, trailing_point_on_polygon)
  (point[0] < (trailing_point_on_polygon[0] - a_point_on_polygon[0]) * (point[1] - a_point_on_polygon[1]) /
             (trailing_point_on_polygon[1] - a_point_on_polygon[1]) + a_point_on_polygon[0])
end

def self.outside_bounding_box?(x, y, *poly)
  max_x, max_y, min_x, min_y = nil
  x_coords = poly.map {|p| p[0]}
  y_coords = poly.map {|p| p[1]}

  max_x = x_coords.max
  max_y = y_coords.max
  min_x = x_coords.min
  min_y = y_coords.min

  return x < min_x || x > max_x || y < min_y || y > max_y
end

Any insight as to why this might be happening at only at leftwards and upwards directions is appreciated.


texts: As an Android dev, what should I keep in mind for porting to iPhone?

texts: As an Android game developer, what should I keep in mind while developing my game if I ever wanted to cross-platform the game to the iPhone?  Any strategies, tips, etc. on porting to both of these mobile platforms?


texts: Implementing a skybox with GLSL version 330

texts:
I am trying to get a skybox working with OpenGL 3.3 and GLSL version 330.

I could not find a completely modern OGL skybox tutorial anywhere on the web, so I modernised an older one (using glVertexAttribPointer() instead of gl_Vertex for vertices, etc.). It's mostly working, but for 2 major details:

The skyboxes are more like sky triangles, and the textures are badly warped and stretched (they are supposed to be star fields, I get while lines on a black background). I'm 99% sure that this is because I didn't port the old tutorials completely correctly.

Here is my skybox class:

static ShaderProgram* cubeMapShader = nullptr;

static const GLfloat vertices[] =
{
    1.0f, -1.0f,  1.0f,
    1.0f,  1.0f,  1.0f,
    1.0f,  1.0f, -1.0f,
    -1.0f, -1.0f,  1.0f,
    -1.0f, -1.0f, -1.0f,
    -1.0f,  1.0f, -1.0f,
    -1.0f,  1.0f,  1.0f,
    -1.0f,  1.0f, -1.0f,
    1.0f,  1.0f, -1.0f,
    1.0f,  1.0f,  1.0f,
    -1.0f,  1.0f,  1.0f,
    -1.0f, -1.0f,  1.0f,
    1.0f, -1.0f,  1.0f,
    1.0f, -1.0f, -1.0f,
    -1.0f, -1.0f, -1.0f,
    1.0f, -1.0f,  1.0f,
    -1.0f, -1.0f,  1.0f,
    -1.0f,  1.0f,  1.0f,
    1.0f,  1.0f,  1.0f,
    -1.0f, -1.0f, -1.0f,
    1.0f, -1.0f, -1.0f,
    1.0f,  1.0f, -1.0f,
    -1.0f,  1.0f, -1.0f
};

Skybox::Skybox(const char* xp, const char* xn, const char* yp, const char* yn, const        char* zp, const char* zn)
{
if (cubeMapShader == nullptr)
    cubeMapShader = new ShaderProgram("cubemap.vert", "cubemap.frag");

    texture = SOIL_load_OGL_cubemap(xp, xn, yp, yn, zp, zn, SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS);

    glBindTexture(GL_TEXTURE_CUBE_MAP, texture);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
    glBindTexture(GL_TEXTURE_CUBE_MAP, 0);

    glGenVertexArrays(1, &vaoID);
    glBindVertexArray(vaoID);
    glGenBuffers(1, &vboID);
    glBindBuffer(GL_ARRAY_BUFFER, vboID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
    glBindVertexArray(0);

    scale = 1.0f;
}

Skybox::~Skybox()
{

}

void Skybox::Render()
{
    ShaderProgram::SetActive(cubeMapShader);
    glDisable(GL_DEPTH_TEST);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_CUBE_MAP, texture);
    cubeMapShader->Uniform1i("SkyTexture", 0);
    cubeMapShader->UniformVec3("CameraPosition", Camera::ActiveCameraPosition());
    cubeMapShader->UniformMat4("MVP", 1, GL_FALSE, Camera::GetActiveCamera()->GetProjectionMatrix() * Camera::GetActiveCamera()->GetViewMatrix() * glm::mat4(1.0));
    glBindVertexArray(vaoID);
    glDrawArrays(GL_QUADS, 0, 24);
    glBindVertexArray(0);
    glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
}

Vertex Shader:

#version 330
layout(location = 0) in vec3 Vertex;

uniform vec3 CameraPosition;
uniform mat4 MVP;

out vec3 Position;

void main()
{
    Position = Vertex.xyz;
    gl_Position = MVP * vec4(Vertex.xyz + CameraPosition, 1.0);
}

Fragment Shader:

#version 330 compatibility

uniform samplerCube SkyTexture;

in vec3 Position;

void main()
{
    gl_FragColor = textureCube(SkyTexture, Position);
}

Here's an example of the glitches. If anyone could take a look who knows GLSL well (I'm still learning it), or skyboxes, I would appreciate any help you could give. Also, kudos if you can teach me how to use non-deprecated functions in the fragment shader so I don't have to use the compatibility profile of glsl 330.

EDIT: Immediately found the problem with the stretching textures: I was using Position = Vertex.xyx instead of Position = Vertex.xyz in the vertex shader. Oops. But the triangle error still exists.


texts: Make some black pixels transparent in Love2D


texts: Why do games seemingly reload the entire level when restarting a level?

texts:
Is the data really modified that much during play?

I'm assuming the longish pause between restarting a level is the entire level reloading. But it seems to me that a well implemented system should just be able to 'ping' back to the start of the level.

It's more noticeable on consoles, but its not unnoticeable on PC games.


texts: CanDraw in large hierarchical scene with rotation

texts:
I've been assigned to write small simulation visualization, that contains thousands of cubes (I know you heard that before). Now I'm working on optimization of stuff that takes place there, but suddenly I came across a brain teaser (maybe my math foo is to weak).

Scene is arranged in hierarchy, each cube can contain another cubes and so on (cubes always must be contained in parent cube, position is relative to parent cube (including transformation except scale). Now we added ability to rotate cubes and all hell broke lose. We use simple culling of objects that shouldn't be drawn this look like this (Warning C#):

    public bool CanDraw(ICamera camera, Vector3d offset)
    {
        Vector3d pos = _translation + offset;

        _inFrustum = camera.SphereInFrustum(pos, _radius);

        if (_inFrustum == InFrustum.Partial && Children != null)
            foreach (IDrawable item in Children)
                item.CanDraw(camera, pos);

        return _inFrustum != InFrustum.No;
    }

InFrustum enum can be Yes, No, Partial.

Now the problem that we get is when parent cube is rotated for example by 45 deg around Z axis and is partially visible all children are tested, but rotation is not included this results in child cubes not being drawn... further more if child cube is drawn, but is rotated problem is starting to get worse.

Do any of you how to solve this without moving test draw code into rendering loop (after transformations are made to see if point 0,0,0 is in frustum?

I imagine that I would have to rotate pos using offset as axis origin and parent rotation (how?), but still that parent object (offset and rotation) might be already rotated by it's parent.

I must do those checks, cause scene contains around 300k+ boxes and drawing all of them ends up in <0.1 FPS on machines that it's used.


texts: State Machines: State Object versus sequential check: what are the pro/cons?

texts:
I dont know much about finite state machine in AI or other game behaviors in game, except this quick tutorial with a Miner: http://www.ai-junkie.com/architecture/state_driven/tut_state1.html which is object oriented.

I don't really know if this tutorial describes the State pattern or not, what do you think ?

I'm not speaking about other more arithmetic-oriented stuff like steering or physics or path-finding or collisions, but rather about game logics, state-driven AI, and things that involves a lot of simultaneous states and ifs and/or switches

What are the pro/cons of using either a State Pattern or a sequential check of a plain state structure like this:

struct States
{
bool is_walking, is_running, holds_a_weapon, is_crouch;
int weapon_id, int id_team;
};

void HandleStates (States state)
{
//etc
}


texts: Is it viable to wrap D3D to change its API style?

texts:
I have an interest in developing games professionally and have started learning DirectX 11 to that end.

I come from a Java background, but with the recent changes introduced with C++11, I've come to like C++ a lot. Coming from Java, I find that the DirectX API reliance on output arguments and a lot of descriptor structs a little disconcerting.

I'm trying to build a framework around the API that returns values instead of using output arguments. The framework also rolls descriptors into the class (e.g. DXGI_SWAP_CHAIN_DESC into a SwapChain class) and internally handles the updating that would be required for any changes. I also plan to use exceptions rather than return codes to handle error conditions.

Is such a framework viable or it just a Java programmer carrying over his coding style into C++?

EDIT: The goals I'm trying to achieve with the framework are that, I want it to rely on returning values, throwing exceptions, handling memory using C++11 and ATL smart pointers. An early iteration of the framework can be found at:
https://github.com/Dolvic/DirectX-Classes


texts:
I have a simple camera class working in directx 11 allowing moving forward and rotating left and right. I'm trying to implement strafing into it but having some problems.

The strafing works when there's no camera rotation, so when the camera starts at 0, 0, 0. But after rotating the camera in either direction it seems to strafe at an angle or inverted or just some odd stuff.

Here is a video uploaded to Dropbox showing this behavior.
https://dl.dropboxusercontent.com/u/2873587/IncorrectStrafing.mp4

And here is my camera class. I have a hunch that it's related to the calculation for camera position. I tried various different calculations in strafe and they all seem to follow the same pattern and same behavior. Also the m_camera_rotation represents the Y rotation, as pitching isn't implemented yet.

#include "camera.h"

camera::camera(float x, float y, float z, float initial_rotation) {
m_x = x;
m_y = y;
m_z = z;
m_camera_rotation = initial_rotation;

updateDXZ();
}

camera::~camera(void)
{
}

void camera::updateDXZ() {
m_dx = sin(m_camera_rotation * (XM_PI/180.0));
m_dz = cos(m_camera_rotation * (XM_PI/180.0));
}

void camera::Rotate(float amount) {
m_camera_rotation += amount;

updateDXZ();
}

void camera::Forward(float step) {
m_x += step * m_dx;
m_z += step * m_dz;
}

void camera::strafe(float amount) {
float yaw = (XM_PI/180.0) * m_camera_rotation;

m_x += cosf( yaw ) * amount;
m_z += sinf( yaw ) * amount;
}

XMMATRIX camera::getViewMatrix() {
updatePosition();

return XMMatrixLookAtLH(m_position, m_lookat, m_up);
}

void camera::updatePosition() {
m_position = XMVectorSet(m_x, m_y, m_z, 0.0);
m_lookat = XMVectorSet(m_x + m_dx, m_y, m_z + m_dz, 0.0);
m_up = XMVectorSet(0.0, 1.0, 0.0, 0.0);
}


texts: How does Component Entity System Manages Game Mode?

texts:
I would like to create a simple game fire and shoot game using Component Entity System (CES). This game has two game modes(1): play mode and settings mode. The play mode is the actual game itself whereas the setting mode is where the player updates his sprite's settings, like type of weapon, inventories, etc.

Now, how does one implement game modes in CES? How would one switch to different game modes?

(1) The game mode i refer is something like the one implemented in Final Fantasy I, where it has four game modes (http://en.wikipedia.org/wiki/Final_Fantasy_(video_game)#Gameplay)


texts: Circular movement - eliminating speed ups near Y = 0

texts:
I have a basic algorithm to rotate an enemy around a 200 unit radius circle with center 0. This is how I'm achieving that:

if (position.Y <= 0 && position.X > -200)
{
   position.X -= 2;
   position.Y = 0 - (float)Math.Sqrt((200 * 200) - (position.X * position.X));
}
else
{
   position.X += 2;
   position.Y = (float)Math.Sqrt((200 * 200) - (position.X * position.X));
}

It does work, and I've ensured that at no point does either X or Y equal NaN. However, when Y approaches 0, it seems to go significantly faster. This surprises me, because the Y values are locked to the X, which is being incremented by a steady amount. What can I do to smooth the speed?


texts: Alert Dialog Box font color in AndEngine

texts:
I am developing an app using AndEngine and I am using my own custom theme to use white background theme. My styles.xml file looks like this:

<resources>

<color name="white_opaque">#FFFFFF</color>
<color name="pitch_black">#000000</color>

<style name="AppTheme" parent="android:Theme.Light">
  <item name="android:background">@color/white_opaque</item>
  <item name="android:windowBackground">@color/white_opaque</item>
  <item name="android:colorBackground">@color/white_opaque</item>

</style>
</resources>

Everything is working fine except in the dialog box the font color is white and it looks like this:

How can I change the font color to black for the text?


texts:
what are The Best practies To load game data that are Stored in a mysql database?

I'm using ajax request. But The async Call is a problem because i can't sync The game level with The data load. And game does Not start because the variable is  not defined. If i use sync Call, The loop wait The result And all the entities are blocked on The screen.

How Can i resolve?


texts: How can I make my app to be free for certain period of time? Is it ok to switch it to free and then after a day or two switch back to my original price, is it possible and where can I do it?


texts:
public AssetLabelReference imgs;
List<IResourceLocation> myImgs = new List<IResourceLocation>();
[SerializeField]List<Texture2D> loadedImages = new List<Texture2D>();
private void Start()
{
    Addressables.LoadResourceLocationsAsync(imgs.labelString).Completed += imgReady;
}
void imgReady(AsyncOperationHandle<IList<IResourceLocation>> op)
{
    myImgs = new List<IResourceLocation>(op.Result);
    insta();
}
 void insta()
{
    Addressables.LoadAssetsAsync<Texture2D>(myImgs, cb);
}
void cb(Texture2D s)
{
    loadedImages.Add(s);
}

I get the locations of the images but not the asset themselves
I get an error of

  Exception encountered in operation Resource(Man.png): Unknown error in AsyncOperation
  UnityEngine.ResourceManagement.Util.DelayedActionManager:LateUpdate() (at


texts:
My game outputs a replay file for each individual game and allows the player to watch past games.

Just a quick example of what our replay files look like:

m 6 2098.25 917.125 -1 0 224 56ööööö843949615
m 2 1715.25 1835.25 1 0 224 44ööööö843949621
m 11 1661.125 1890.875 1 0 224 56ööööö843949627
m 5 1818.125 929.0 0 1 224 56ööööö843949633
death 9 3 4 5ööööö843949663
hit 9 3 4 48 26 2114 1987 2.8266926 1865 1891ööööö843949663

Some info on the identifiers:

Movement: // m (player id) (x coord) (y coord) (x-movement) (y-movement) (remaining health) (shot energy remaining) (timestamp)

Death: // death (dead player id) (killer player id)

Hit: // hit (hit player id) (hitter player id) (weapon (1-4)) (damage dealt) (life remaining ) (x coord) (y coord) (angle of hit) (total damage dealt) (total damage taken)

There are a lot more than what I listed, but you get the idea.

What's in the replay files are essentially the same as what is sent to the server during a live game.

Right now, if we want to take a video of the game, we just go into our replay system and record it with Fraps, but I'd like to convert our replays into some kind of video format.

I know this may be a bit far-fetched, but I thought I'd give it a shot here.

The game is written in Java and is sprite based.


texts: Bullet Physic: Transform body after adding

texts:
I would like to transform a rigidbody after adding it to the btDiscreteDynamicsWorld.
When I use the CF_KINEMATIC_OBJECT flag I am able to transform it but it's static (no collision response/gravity). When I don't use the CF_KINEMATIC_OBJECT flag the transform doesn't gets applied. So how to I transform non-static objects in bullet?

DemoCode:

btBoxShape* colShape = new btBoxShape(btVector3(SCALING*1,SCALING*1,SCALING*1));

/// Create Dynamic Objects
btTransform startTransform;
startTransform.setIdentity();

btScalar mass(1.f);

//rigidbody is dynamic if and only if mass is non zero, otherwise static
bool isDynamic = (mass != 0.f);

btVector3 localInertia(0,0,0);
if (isDynamic)
    colShape->calculateLocalInertia(mass,localInertia);

btDefaultMotionState* myMotionState = new btDefaultMotionState();
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,colShape,localInertia);

btRigidBody* body = new btRigidBody(rbInfo);
body->setCollisionFlags(body->getCollisionFlags()|btCollisionObject::CF_KINEMATIC_OBJECT);
body->setActivationState(DISABLE_DEACTIVATION);

m_dynamicsWorld->addRigidBody(body);

startTransform.setOrigin(SCALING*btVector3( btScalar(0), btScalar(20), btScalar(0) ));

body->getMotionState()->setWorldTransform(startTransform);


texts:
I've been writing, deleting and rewriting OpenGL programs in C++ but usage of shaders confuse me. I don't know how it should be structured.

Scenario A:
(In a world we have a sun, the sun should shine upon everything in the world and on a lake or there would be fog which should only be visible from outside the building but not inside)

So far, I am thinking that I would write a global sun structure in C++ then pass its value to all shaders, then in all used shaders I would write the same lighting functions over and over again.

So I would be repeating codes...
How would you construct your shader program in such scenario?
And Should I write a shader for each model?


texts: Manually creating an instance of object derived from MonoBehaviour

texts:
I'm currently "newing" an instance of a class I have that derives from MonoBehaviour and store it in a list. The value of this instance is "null" however, even though it has all the fields of my derived class in it so it passes as null in null checks. After more reading it seems it's a bad idea to manually new up an instance of an object that derives from MonoBehaviour.

The class is an Actor class. I have a situation where enemy actors are 3D models in my scene and so I want them to derive from MonoBehaviour, but the player actors don't have world representations really. I just have a picture of them in the corner. Similar to Legend of Grimrock.

I wanted the 1 Actor class since the data they need is all the same and I wanted to avoid having 2 classes for no seemingly reason other than not newing up a MonoBehaviour derived class.

What are my options with this requirement when my player actors don't need MonoBehaviour but my enemy actors do but they all need to have the same properties?


texts:
I've made a game in 1920x1080 res in XNA, and I can't seem to find a way for the graphics device to squash the screen images to other resolutions like 1600x900 when played on different computers.

How can I get my game to be in proportion, and fit on smaller screens with the same aspect ratio?


texts: Physics.CheckSphere() appears not to work in Unity

texts:
My scene is simple, I have a single GameObject with the following script attached:
usings ...

public class GalaxyManager: MonoBehaviour
{
    public int numberOfStars = 300;
    public int maximumRadius = 100;

    public float minDistBetweenStars = 2f;

    void Start()
    {
        for (int i = 0; i < numberOfStars; i++)
        {
            float distance = UnityEngine.Random.Range(0, maximumRadius);
            float angle = UnityEngine.Random.Range(0, 2 * Mathf.PI);

            Vector3 cartPosition = new Vector3(distance * Mathf.Cos(angle), 0, distance * Mathf.Sin(angle));

            if (!Physics.CheckSphere(cartPosition, minDistBetweenStars))
            {
                GameObject star = GameObject.CreatePrimitive(PrimitiveType.Sphere);
                star.transform.position = cartPosition;
            }
            else
            {
                i--;
            }
        }
    }

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

    }
}

What this is supposed to do is generate 300 "stars" within the maximumRadius of 100 that are separated by at least minDistBetweenStars.
I haven't been able to figure out what's actually happening -- sometimes the check finds a collider and sometimes it doesn't.  It's almost as if the CheckSphere() check is happening before the stars get placed via the star.transform.position = cartPosition.
I'm very new to Unity and appreciate the help.  Anyone have any idea what's going on?
*edit:
Some more information, I've tried the script in both 2020.1.12f1 and 2019.4.14f1 to no avail.
I'm also aware that this will lead to an infinite loop if it can't find a placement.


texts: Specular intensity of non-metals(plastics) in metalness pbs workflow

texts:
The specular color in metalness/roughness workflow is usually defined as following:

float3 specColor = lerp(0.03f, albedoColor, metallic);

The Cook-Torrance BRDF is given with the following formula:

The final color will be:

Ci = (diffColor*(n.l)+Ks*specColor*cook);

My question is - won't specular be too dim for non-metals? Cook-Torrance term will be multiplied by 0.03 in case of dielectrics - this will make the specular component virtually non-existent. This doesn't seem realistic to me, because smooth plastic reflects a lot of light, almost as much as metals:

What am I missing?


texts: Calculating the angular momentum of rigidbody in Unity3D

texts:
Knowing that angular momentum in 3D is L = Iω (moment of inertia times angular velocity), how do I calculate it in video game world?

In unity3d I have the diagonal inertia tensor rigidbody.inertiaTensor and I know the angular velocity rigidbody.angularVelocity am I correct when I calculate it like this?

Vector3 angularMomentum = new Vector3(
    rigidbody.inertiaTensor.x * rigidbody.angularVelocity.x,
    rigidbody.inertiaTensor.y * rigidbody.angularVelocity.y,
    rigidbody.inertiaTensor.z * rigidbody.angularVelocity.z
);

Though, that leaves out the property rigidbody.inertiaTensorRotation which makes me think that this is not correct. What actually led me to the other question: In Unity3D, what is the relation between inertiaTensor and inertiaTensorRotation?


texts:
Good day.
I would like to create a "rich" GUI for my game.

How can i add a 3d model to a GUI Button (with continous rotation ) ?
If I can't add a 3d model to a GUI button, what is the best way to visualize a 3d model rotating ?

Maybe creating a video file or animated gif and adding it to my button ?

Thanks


texts:
Im doing a online game havingclient, js html5, and server, nodejs with websockets.
I've read some blogs about websockets security, and its limitations, but no real implementation or example.

Could JWT tokens in the messages sent to the server, be a good option? Meaning when the clients connect to the server, it gets a token and passes it around on every message? And use wss instead of ws.

Thanks in advance!


texts: Unity3d 2017 trail renderer behaving weird

texts: Please see the screenshot I attached, I am trying to make skid marks using trail renderer, but one side of trail is going upwards just after it renders, it was working fine Unity 5.4, but when I upgraded it to 2017, it is behaving like this.