texts:
There is a blueprint in UE4 for making Sobol random 3D cell. It places random objects inside cell structure.
How to make this in Unity?

For example, if I make a sphere prefab I would need to generate Sobol distribution in some volume.

EDIT:

@Seyed Morteza Kamali have made a script:


texts:
I've tried placing a white "background" on a font that is being rendered with LibGDX, with no success.

I'm using the font.draw to draw the loaded font on the screen, but every way that I tried, the font only contains a black border and is transparent on "the inside".

I'm using Hiero to make the .fnt from .ttf files that libGDX uses to render the fonts. Is there anyway I should modify from this application to make a font have a white background and not be transparent?

I would like to display the font the second way, although that display that you are seeing is just from the Hiero app preview option (with specific background).


texts: Screenshot preview freezes a game for a few seconds

texts:
I have a screenshot preview at the end of the level, but when I show it my game freezes for a bit(low fps for a few seconds). This is code I use to load screenshot and crop it(for a little preview sample). Please, help me to solve this lag issue

private IEnumerator ShowScreeshotPreview()
{
    yield return 0;

    screenshotTexture = new Texture2D(2, 2);
    byte[] fileData = File.ReadAllBytes(destination);
    yield return 0;

    screenshotTexture.LoadImage(fileData);
    yield return 0;

    Rect croppedSpriteRect = new Rect();
    croppedSpriteRect.height = screenshotTexture.height;
    croppedSpriteRect.width = screenshotTexture.height;
    croppedSpriteRect.y = 0;
    croppedSpriteRect.x = 0;

    croppedTexture = new Texture2D((int)croppedSpriteRect.width, (int)croppedSpriteRect.height);
    yield return 0;

    croppedTexture.SetPixels(screenshotTexture.GetPixels((int)croppedSpriteRect.x, (int)croppedSpriteRect.y, (int)croppedSpriteRect.width, (int)croppedSpriteRect.height));
    yield return 0;

    croppedTexture.Apply(); // Memory leak occurs here
    yield return 0;

    screenshotPrview.mainTexture = croppedTexture;
    yield return 0;

    ScreenshotPreviewAnimator.SetBool("visible", true);
    screenshotLoaded = true;
}


texts:
EDIT: Ok so the question here is how to you generate a linear gradient along a vector.

Here is the function i'm looking for:

function CreateGradient(x,y, x1,y1,x2,y2) {
    // x and y are the point in our image we are looking to create the  color for in grayscale
    // x1,y1,x2,y2 is the vector in which the linear gradient should run
    // Can be in any language
}

What I have so far (that doesn't work):

var width = 2.0;
var offset = 0;

var convX = ((x / RES) * width - width/2) - offset;
var convY = ((y / RES) * width - width/2) - offset;

var angle = Math.atan(y1-y2, x1-x2);

var rx = Math.cos(angle);
var ry = Math.sin(angle);

var here = convX * rx + convY * ry;
var start = x1 * rx + y1 * ry;
var end = x2 * rx + y2 * ry;

var lerpValue = (start - here) / (start - end);

var val = lerp(0,255,clamp(lerpValue,0.0,1.0));

RES is the total resolution of the picture. val in the value (0-255) which represents the R G and B values of the pixel

Final Edit: I have it now thanks code for the future:

var x1 = 0;
var y1 = 0;
var x2 = 255;
var y2 = 255;

var dx = x2-x1;
var dy = y2-y1;

var rx = x-x1;
var ry = y-y1;

var t = ((rx*dx) +(ry*dy)) / ((dx*dx) + (dy*dy));

return lerp(0,255,t);


texts:
I wanted to know if there is a way to draw lines on the viewport, just like on the example image I am posting. My idea is to have a method that receives 2 Vector2, the origin and the end of the line, just like Gizmos.DrawLine (except that it takes Vector3 instead), that would be internally clamped to  be normalized.

public class DrawMeLines : MonoBehaviour
{
    /// Just draw the lines on editor mode, and only when selected.
    void OnGizmosDrawSelected()
    {
        DrawLineOnViewport(new Vector2(0f, 0f), new Vector2(1f, 1f));
    }

    void DrawLineOnViewport(Vector2 origin, Vector2 end)
    {
        origin.x = Mathf.Clamp(origin.x, 0f, 1f);
        origin.y = Mathf.Clamp(origin.y, 0f, 1f);
        end.x = Mathf.Clamp(end.x, 0f, 1f);
        end.y = Mathf.Clamp(end.y, 0f, 1f);

        /// Proceed to draw lines on Viewport...
    }
}

Thanks in advance, let me know if there is any additional information necessary for me to give.

NOTE: I already have a struct that has its values ranged, so the clamping wouldn't be necessary, it was written just for the sake of example.


texts: Render to texture and then to screen cause flickering

texts:
So I have my class vItem which has a vector (consider elements like layers) of textures, origin rects and destination rects plus other stuff.
Basically whenever I update any of the layers in the vector I redraw everything on an internal texture which is then displayed on the screen, here's the function that draws on the texture:

void vItem::draw(){
    if(sprites.size() <= 0)
        return;

    // This calculates the dimensions of a rectangle big enough to contain every texture
    SDL_Point size = calculateSpriteRect();

    if(size.x <= 0 || size.y <= 0)
        return;

    // If the final texture does not exists or its dimensions are different from the new rectangle I destroy it and recreate it
    if(final_sprite == NULL || size.x != final_sprite_size.x || size.y != final_sprite_size.y){
        if(final_sprite != NULL)
            SDL_DestroyTexture(final_sprite);
        final_sprite = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, size.x, size.y);
        SDL_SetTextureBlendMode(final_sprite, SDL_BLENDMODE_BLEND);
        final_sprite_size = {size.x, size.y};
    }

    SDL_RenderPresent(renderer);
    SDL_SetRenderTarget(renderer, final_sprite);
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
    SDL_RenderClear(renderer);
    for(int i = 0; i < sprites.size(); i++){
        SDL_SetTextureAlphaMod(sprites[i].sprite, sprites[i].alpha);
        SDL_RenderCopy(renderer, sprites[i].sprite, &sprites[i].source, &sprites[i].bounds);
    }
    SDL_RenderPresent(renderer);
    SDL_SetRenderTarget(renderer, NULL);
}

The problem comes after this function: I have a child class of vItem called vButton where I have two layers of text (one normal and the other on for when the mouse is over the button), and when I update alpha values of the layers to hide one level and show the other one draw() is called. This transition causes an instant flickering (black background right before drawing).
When I removed vSync I noticed that this wasn't happening anymore, but I need vSync.

UPDATE:
Ok... Apparently if I remove both SDL_RenderPresent(renderer); the flickering is gone and everything is rendering correctly, but I can't understand why. This is the final function:

void vItem::draw(){
    if(sprites.size() <= 0)
        return;

    // This calculates the dimensions of a rectangle big enough to contain every texture
    SDL_Point size = calculateSpriteRect();

    if(size.x <= 0 || size.y <= 0)
        return;

    // If the final texture does not exists or its dimensions are different from the new rectangle I destroy it and recreate it
    if(final_sprite == NULL || size.x != final_sprite_size.x || size.y != final_sprite_size.y){
        if(final_sprite != NULL)
            SDL_DestroyTexture(final_sprite);
        final_sprite = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, size.x, size.y);
        SDL_SetTextureBlendMode(final_sprite, SDL_BLENDMODE_BLEND);
        final_sprite_size = {size.x, size.y};
    }

    //SDL_RenderPresent(renderer);
    SDL_SetRenderTarget(renderer, final_sprite);
    //SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
    //SDL_RenderClear(renderer);
    for(int i = 0; i < sprites.size(); i++){
        SDL_SetTextureAlphaMod(sprites[i].sprite, sprites[i].alpha);
        SDL_RenderCopy(renderer, sprites[i].sprite, &sprites[i].source, &sprites[i].bounds);
    }
    //SDL_RenderPresent(renderer);
    SDL_SetRenderTarget(renderer, NULL);
}

How can the renderer keep information about the texture on texture rendering and texture on screen rendering at the same time (since I have only one SDL_RenderPresent() left at the end of my game loop)? Is it meant to work like that?


texts: How can I write a Save/Load system for my game?

texts: I'm trying to figure out a way to write a save/load system for my game in C++. As of right now, I'm doing it all using binary flags. Anyone got a clue on how to do it another way? I don't mind using binary, but I want to know my options. I also want something in which it would be easy to check on the status of just one event being complete or incomplete in order to decide certain things (a lot of the items system in this game is dependent on what the player has or has not done throughout the course of the game).


texts: How do I stop a monster from dropping a quest item once the related quest is finished?

texts: I'm trying to make a quest. When the quest is activated (switch is on), monsters should drop a certain quest item. After the quest is finished (switch is off), those monsters should stop dropping the quest item. How can I do this?


texts: Does changing a Rasterizer State affect every object (model) on the screen?

texts:
Quick easy question. When setting a Rasterizer State (like for example wireframe).....does that affect every object (model) on the screen?

For example, let's pretend I have 2 cubes. I use:

devcon->RSSetState(pRSWireframe);

Will that affect all the objects on the screen?


texts:
So, I am making a game-like html file that needs to load a few assets. I have a loading animation which uses the timing of the loading files to create a progress bar. This all goes fine. The files all load, and the app launches. However, none of the files can access each other as they are all in different script tags. And I cannot merge them because the JS is never actually put into the html. So what I need to do is to access the local file system (it uses the file:// prototype) and read the file, then stick the text into a script tag. However, all of the examples I have found on the web throw this error:

  Xhtmlrequests can only access (list of protocols not including file)

What I need is a JS way to access the files with no input from the user (other than opening the application). How can this be done?


texts: Drawing Sprites Depending On Mouse Position (LibGDX)

texts:
I'm making a small game where you play as a turret in the middle of the screen trying to shoot the enemies coming after you. I am having difficulties, however, in trying to figure out how to make the turret change sprites depending on where my mouse cursor is pointing. I don't want to rotate the sprite, mind you, as I already have made different variations of the same sprite for the different directions it will face:

I have an idea of how to accomplish this, but I don't know how to make it happen:

The program generates 42 rays, (one for each turret sprite), that originate from the turret
If the cursor falls between two of those rays, a specific sprite will be drawn

How would I go about doing this? It doesn't have to be the method described above as long as it produces the same result.

Thanks for your help in advance!

Plug


texts: How do I detect a destroyed object in Unity?

texts:
I have an object in unity which is spawn through a script. Upon detecting that the object has taken substantial damage, objectDestroy is called and the object is removed.

However, I would like for a message to appear upon having this object destroyed. The code I posted below doesn't work.

hudText.Add ("Use Mouse 1 to fire !", Color.red, 2f);

while(trigger==false){
    if(enemy==null){

        Debug.Log ("Gone");

        yield return new WaitForSeconds(1);
        hudText.Add ("Nice work!", Color.green, 3f);

        trigger = true;
    }
    Debug.Log (trigger);
    yield return null;
}

I suspect that this has to with the fact that the object is destroyed at the end of the frame, but the while loop here never allows the loop to test for the following frame.

How do I do this?


texts:
I want to load all my game's images on the game's startup and have a loading bar to show it's progress. I already know how to create and display the loading bar, but I can't figure out how to load the images, and then add the image's frames to it's array.

Not using SLick


texts: What AI scheme is appropriate for a 4 player, Tic-Tac-Toe style game?

texts:
I am about to release an android game that is like tic tac toe, but on a bigger board, and 4 player. Instead of winning when you get 3 in a row, you get points for chains, and the most points at the end wins.

I'm going to have a later release that will include AI, but I'm quite new to this. Would minimax be a good choice, but does it work in 4 player? I'm worried that because there are around 90 possible moves for each turn then this would get slow too slow for large enough searches.

Any suggestions?


texts: FXC: Error X3501: 'main': entrypoint not found

texts:
I am trying to compile a vertex shader using VS2013, but every time I try, FXC returns the following error:

Error error X3501: 'main': entrypoint not found

I've reduced the vertex shader to its simplest form and yet I'm still getting the same result:
DefaultVS.hlsl
#include "Include.hlsl"

cbuffer CameraTransform {
    float4x4 ViewProjMat;
};

VS_OUT main(VS_IN input) {
    VS_OUT result;

    result.Position = mul(input.Position, mul(input.WorldMat, ViewProjMat));

    return result;
}

Include.hlsl
struct VS_IN {
    float4 Position : POSITION;
    float4x4 WorldMat : INSTANCE_TRANSFORM;
};

struct VS_OUT {
    float4 Position : SV_POSITION;
};

And the properties of both files:

/Zi /E"main" /Od /Fo"Path\To\Output\DefaultVS.cso" /vs"_5_0" /nologo
/Zi /Od /Fo"Path\To\Output\Include.cso" /nologo


texts: How can I achieve dynamic pathfinding in Godot?

texts:
I am new to Godot and trying to implement dynamic pathfinding on a 2D map which includes both static obstacles and moving units. As I understand it, Godot's NavMesh makes it almost trivial to generate a path through a pre-baked polygon map [1], as with the solid-line path in the below image. However, I want my game to be able to re-plan the path if an enemy (or other obstacle) moves to obstruct it--as with the dotted-line path in the image. Is this possible with built-in Godot functionality? And if so, how?

Alternatively, how would you recommend implementing a custom pathfinding script in Godot? I am comfortable with vanilla A* and I plan to learn GDScript and/or C#, but in my experience (in Python/Pygame), grid-based A* is much too slow to re-check the path every frame.


texts: Combining Animations for Colllada export

texts: I need to export an animated character to the Collada file format in Blender. My .blend file has the individual animations (idle, walk cycle, attack, etc) each as separate actions. I discovered after creating it that the Blender Collada exporter cannot export multiple actions, so I need to merge them into one action which can be exported. I have tried the NLA editor, but the resulting NLA track which I create isn't exported at all. Is there any way to convert the track back to an action? Is there another, better way to achieve the result I want?


texts:
I'm rendering a texture to a square.

I have to scale the texture because it is 10 times wider than it is tall.

In my fragment shader I divide both the X and Y texture coordinates (I'm using OpenGL), but I divide the x texture coordinates by 10 times more than the y coordinates and I get this nice looking image:

Then I do some rotation of the texture (the square stays put). I rotate my texture coordinates using a matrix that looks like this:

[cosr sinr]

[-sinr cosr]

where r is the angle of rotation in radians of the player. (OpenGL uses column-major matrices).

When I rotate, of course I have to do something about scaling differently now, but I'm not sure what. For now, I'm doing nothing to adjust my scale factor for the orientation of the texture. Thus, if I rotate a little it looks like this:

And if I rotate by a lot it looks like this: (that green is the green circles from before)

What can I do to accurately adjust scale for changes in orientation in a way that makes mathematical sense?


texts: Libgdx: more efficient way of using Vector 3?

texts:
I currently use

if(cam.frustum.pointInFrustum(new Vector3((float)posX, (float)posY, 0)))

To check if my sprite is in the camera's view. I have to make a new Vector3 every frame wich is very inefficient.

Is there a better way to do this?


texts: Does OGRE do hardware skinning by default?

texts:
I am trying to understand how OGRE works at a lower level, and from what I have read so far, I believe OGRE generates shaders from material scripts using its RTShader system, on the loading of each scene (based on the contents).

My questions are:

Is this correct? (i.e. does OGRE 1.7.1 by default generate shaders at runtime by default?)
If 'yes', do the generated shaders support hardware skeletal animation by default?
In either case, if 'yes' to (1), when I extend a material script specifying a fragment program, is this incorporated into the generated script or does it completely replace it?

EDIT:

OK, so I got PIX to debug a scene with a model with skeletal animation, and it turns out the fixed-function pipeline was in use (no vertex or pixel shaders were available for PIX to debug even as assembly).

I then looked with the debugger for the properties referenced in the skeletal animation example file SkeletalAnimation.h:

    // change the value if hardware skinning is enabled
Pass* pass = ent->getSubEntity(0)->getMaterial()->getBestTechnique()->getPass(0);
    if (pass->hasVertexProgram() && pass->getVertexProgram()->isSkeletalAnimationIncluded()) value = "Hardware";

And found that there was no vertex or fragment program to speak of, hence I can assume the answer to (2) at least is 'no'.

Looking further at OGRE's documentation it seems I can combine shaders with the FFP,  but only replacing specific stages. (i.e. I can't use the FFP vertex processing and then add a vertex shader)

I am still unsure though about RTShader: Is it an established part of OGRE, or still in development? Do I have to turn it on? Or do I have to invoke it manually?


texts: Rendering a model with transparent or translucent uv map applied doesn't work

texts:
Before I try to make anything transparent, the model renders nicely. When I change the uv layout so that one piece of the model will be transparent, it renders horribly. This is the result with a translucent green texture:

I did transparency with OpenGL when I did 2D games and everything worked nicely because of these two lines:

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

Now, I fear, this won't be enough, right? Or maybe I should use some other technique?


texts:
What is the easiest way to store online and serve user-generated levels? What client-server architecture should I use? Will I need backend code, or just a database? What database would be the easiest to use with C++ front-end? Are there any suitable cloud services that would help to minimize the effort?

I am looking for something that can be used on both mobile and desktop.

The game we're going to make will be fairly simple, the levels can fit into one screen, each level is basically collection of integer coordinates of cubes of different types. Any tips on how and where to store such levels?


texts: Reversi/Othello early-game evaluation function

texts:
I've written my own Reversi player, based on the MiniMax algorithm, with Alpha-Beta pruning, but in the first 10 moves my evaluation function is too slow. I need a good early-game evaluation function.

I'm trying to do it with this matrix (corresponding to the board) which determines how favourable that square is to have:

   { 30, -25, 10, 5, 5, 10, -25,  30,},
   {-25, -25,  1, 1, 1,  1, -25, -25,},
   { 10,   1,  5, 2, 2,  5,   1,  10,},
   {  5,   1,  2, 1, 1,  2,   1,   5,},
   {  5,   1,  2, 1, 1,  2,   1,   5,},
   { 10,   1,  5, 2, 2,  5,   1,  10,},
   {-25, -25,  1, 1, 1,  1, -25, -25,},
   { 30, -25, 10, 5, 5, 10, -25,  30,},};

But it doesn't work well.

Have you even written an early-game evaluation function for Reversi?


texts: What is the appropriate way to implement collision in 2D worlds?

texts:
If I want to create a 2D game map which features areas traversable by a player through standard up/down/left/right inputs, and then have areas that are NOT traversable... perhaps just a bush, or a sign post, or a rock.

What is the appropriate agent to enforce these rules?

It seems like the trendy thing is to ship off these responsibilities to Box2D, but that seems wrong to me. Is there a technique with lower overhead to produce the same effect? Is it as simple as inventorying and enumerating through every rock and making sure the player can or cannot walk to the space they are trying to walk to? That's how I am doing it now.


texts: Is it possible to make an input field with non selectable text in Unity?

texts: Can I make an input field with non selectable text in Unity?


texts:
How can I get the position of tile 14 (or any other) when only knowing the following:
Tile ID: 14
Rows: 4
Columns: 7

The end result should be 2x4.


texts: How do I set what beta branch I want to upload my build to in Steamworks?

texts:
I have many beta branches, and when uploading the game I just run a command which executes the app-build-xxxx.vdf file. How do I set what specific branch I want those changes to be uploaded to? My configuration file looks something like this:
"appid"           "xxxxx"
"desc"            "Beta branch xxxx "

"buildoutput"     "..\output\"
"contentroot"     "..\..\Game\"

"setlive"         "<Name of the branch here as it is in steamworks>"


texts: How to keep a round body rotating without rotating it's center

texts:
I want to make a game in Unity in which the Player is a sad star.  I want to have the points (The "arms and legs and head") of the star to rotate like a circle but to keep it's face (which is in it's center) still.  How can I do that ?

The body should rotate and it's center should stay still. Many thanks in advance!


texts: Unity Random.Range not repeat same position

texts:
I have this code that generates blocks in random position and it works but some times it generates blocks at the same position ,how can I fix it?

 var dupeobject : GameObject;

 function Start(){
     yield WaitForSeconds(0);
     var position : Vector3 = Vector3(Random.Range(-50,10),Random.Range(-10,5),Random.Range(-100,20));
     Instantiate(dupeobject,position,Quaternion.identity);
     yield WaitForSeconds(0);
     //Destroy(gameObject);
 }


texts: Avoiding bouncing between states in an FSM

texts:
Suppose you have a simple state machine for a game character with two states:

StandingIdle
Walking

In the update logic for the StandingIdle state you have (pseudo code):

if input received
    setState(Walking)

In the Walking state you have:

intendedLocation = calculate new location based on current heading and speed

if intendedLocation is blocked
    setState(StandingIdle)
else
    move to intendedLocation

Now this creates the problem that the state machine can bounce back and forth between the states, which can result in an awful visual effect. This is because the StandingIdle state may switch to Walking, whereupon the Walking state may determine that something is blocking the way and subsequently switch back to StandingIdle. As long as there is input being received (ie. the player is trying to move), then the state machine will bounce back and forth between these two states.

In order to deal with this, the StandingIdle state could first check whether there is sufficient room in which to start walking. But that requires either duplicating logic that already exists in the Walking state, or exposing that logic in some fashion and calling it from the StandingIdle state. I am leaning towards the latter route at this stage.

Another option I considered was exposing some kind of canTransition() method from my state objects and having the state machine call it prior to allowing a state change. That way, the Walking state could return false if there is insufficient room to walk. This, however, creates other problems.

Is there a best practice way to deal with this problem?


texts: How can I tell if OpenGL has finished rendering the current frame?

texts:
If I make a call to http://developer.android.com/reference/android/opengl/GLSurfaceView.html#requestRender() from my game loop, how can I tell when OpenGL has finished rendering?

I don't want to make a call to requestRender() again in the next frame until the previous frame has finished rendering.

Sorry for the basic question I'm new to opengl and trying to switch to it from canvas.

Also, is GLSurfaceView.requestRender() a blocking call?


texts: 2D animation: Animated 3D models or sprites with animation frames?

texts:
Starting out with new project, I am stuck choosing between:

3D textured model animated directly through the renderer
2D sprites and drawing each animation frame

The game will be 2D platform, I would like the pros and cons of each method to help make a decision between the two.


texts: How would you guys call a class to instantiate both NPCs and players?

texts:
My idea is having a class to instantiate both NPCs and players. I have thought of some names like Entity but that is way too broad, as it could refer to anything from a block to an event really. I've also thought of Character, but that name seems to refer to only important characters in the story, not any NPC that you might encounter in the world.
It's a pretty straightforward question, yet I've been racking my brain for about an hour and can't seem to get any useful ideas.

Thanks guys, and peace.


texts:
I am currently making a 2d top down game in unity and have stumbled upon a problem with my raycast collision. I want my green player to stop moving when colliding with a wall, therefore i made my player object cast a ray in the direction it is moving. Its velocity is nullified when the distance to the collision point is equal to zero, or below. What seems to be the case is that the player object stops moving way to late and ends up overlapping the wall object. I tried to make an offset such that the player stopped a bit earlier, but it seems that the offset needs to differ depending on the side of the wall block. It even feels like the point at where the player stops is arbitrary and differs from time to time.

I would really like to know why this happens and what i can do to fix it. BTW, I would also really like to be able to change the players speed and still have it work.

Here are some pictures of my problem:

The code i use for the player:

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {

    [SerializeField]
    private float speed;

    Rigidbody2D body;
    bool justChangedDir;
    Vector2 moveDir;

    void Start()
    {
        body = GetComponent<Rigidbody2D>();
    }

    void MoveDirection()
    {
        Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

        if ((input.x != 0 && input.y == 0) || (input.x == 0 && input.y != 0))
            justChangedDir = false;

        if (moveDir.x != 0)
        {
            moveDir = new Vector2(input.x, 0);

            if (input.y != 0 && !justChangedDir)
            {
                moveDir = new Vector2(0, input.y);
                justChangedDir = true;
            }
        }

        else if (moveDir.y != 0)
        {
            moveDir = new Vector2(0, input.y);

            if (input.x != 0 && !justChangedDir)
            {
                moveDir = new Vector2(input.x, 0);
                justChangedDir = true;
            }
        }

        else
            moveDir = input;
    }

    void CheckCollision()
    {
        RaycastHit2D hit = new RaycastHit2D();

        if (moveDir.x != 0)
        {
            hit = Physics2D.Raycast(body.position, Vector2.right * moveDir.x, 1);

            Debug.DrawRay(body.position, Vector2.right * moveDir.x, Color.yellow);

        }

        else if (moveDir.y != 0)
        {
            hit = Physics2D.Raycast(body.position, Vector2.up * moveDir.y, 1);

            Debug.DrawRay(body.position, Vector2.up * moveDir.y, Color.yellow);
        }

        if (hit.collider != null && hit.distance <= 0.5 )
        {
            body.velocity = Vector2.zero;
        }
        else
        {
            body.velocity = moveDir * speed;
        }

    }

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

        if (moveDir != Vector2.zero)
        {
            CheckCollision();
        }
        else
            body.velocity = Vector2.zero;
    }

}

Any help will be really appreciated :) Many thanks in advance!

Gusgus


texts: Dynamically generating triangles from points

texts:
I'm working on 2D lighting.

I have a list of points that have been calculated and when I draw lines from the light origin to the point it works. The problem is connecting the points into triangles. It always overlaps the walls, and I can't figure this it.

The problem not being the drawing, but connecting the points as to not overlap the map is my problem.

This is my code that generates the vertices

for (int i = 0; i < rays.size(); i++) {
    int roffset = (i * 2);
    glm::vec3 ray = rays[i];

    glm::vec3 ray2 = rays[i+1];

    if (i == rays.size()-1) {
        ray2 = rays[0];
    }
    pointsV2.push_back(ray.x);
    pointsV2.push_back(ray.y);
    int offset = (6* i);

    lines[offset + 0] = ray.x;
    lines[offset + 1] = ray.y;
    lines[offset + 2] = mX;
    lines[offset + 3] = mY;
    lines[offset + 4] = ray2.x;
    lines[offset + 5] = ray2.y;

}

The rays are sorted clockwise. I'm not sure what else to include, but let me know if I need to give something else.

These are just the lines:


texts: Rotating each quad in a batch separately?

texts:
Background

In my app I use the following code to rotate my quad:

Code

    //Rotate the quad

Matrix.setIdentityM(mRotationMatrix, 0);
Matrix.translateM(mRotationMatrix, 0, centreX, centreY, 0f);
Matrix.rotateM(mRotationMatrix, 0, -angle, 0, 0, 0.1f);
Matrix.translateM(mRotationMatrix, 0, -centreX, -centreY, 0f);

And then apply the matrices:

// Combine the rotation matrix with the projection and camera view
Matrix.multiplyMM(mvpMatrix2, 0, mvpMatrix, 0,  mRotationMatrix, 0);
// get handle to shape's transformation matrix
mMVPMatrixHandle = GLES20.glGetUniformLocation(iProgId, "uMVPMatrix");
// Apply the projection and view transformation
GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix2, 0);

The above code works great when I'm drawing single quads.

Problem

However, if I have a few quads with the same texture to draw, I batch them up and draw them with one call to glDrawArrays.

I can't work out if it is possible to rotate each individual quad before drawing them (or how to do it if it is possible) - I realise, they will all be rotated the same amount at the same time but this isn't an issue).

Rotation method

public void rotateBatchQuads(int[] coordinates, int angle){

    for (x=0;x<coordinates.length;x+=2){

        //Center of quad (Along the x)
        float centreX = coordinates[x]+quadWidth/2;  //Pseudo code
        float centreY = coordinates[x+1]+quadHeight/2 //Pseudo code
        //Center of quad (Along the y)

        //Rotate the quad
        Matrix.setIdentityM(mRotationMatrix, 0);
        Matrix.translateM(mRotationMatrix, 0, centreX, centreY, 0f);
        Matrix.rotateM(mRotationMatrix, 0, -angle, 0, 0, 0.1f);
        Matrix.translateM(mRotationMatrix, 0, -centreX, -centreY, 0f);
    }
}


texts: Efficient way to avoid shadow "streaks" beyond bounds of shadow map

texts:
BACKGROUND INFO:

Using MonoGame.

To maximize shadow resolution, I've got a shadow map that covers only the area closest to the camera. (I am aware of Cascading shadow maps, but for now, I am willing to simply lose shadows far away, in exchange for higher resolution near the camera.)

Specifically, I am rendering shadows of tree billboards, that are then cast on to a ground terrain.

First version worked great except for one issue. If a shadow is drawn that touches an edge of the shadow map, then that final row (or column) of pixels is REPEATED by the "Clamp" setting of the sampler. Result is a shadow "streak" that continues from the edge of map into the distance on the ground.

To eliminate those streaks, give full illumination when "outside" of shadow map,
I added test to my lookup function to return full illumination (1.0) if UV outside of valid range:

if (texCoord.x < 0 || texCoord.x > 1 || texCoord.y < 0 || texCoord.y > 1)
    return 1.0f;

... followed by the code that looks up in shadow map, returns an illumination in range 0..1.

This works.

I have two questions about this:

Is there a more efficient way to test these 4 conditions, or to avoid the need to test?
Is there an efficient way to solve this when the shadow map is created?
The sampler is set to "clamp", so if the first and last row and column of map were all "untouched" (held the default depth value or illumination value, depending on the shadowing technique), then I would not need to do any special tests when using the map; "clamp" would retrieve an edge pixel, so if those all were "untouched" by shadows, I would get the desired result.

2.b. It just occurred to me that one solution to (2) is to write the default value back into the four edge rows/columns. [after all shadows are rendered]  What is an efficient way to do that?


texts: Box2D platformer movement. Should i mess with velocity?

texts:
I have a platformer game in which I implemented the movement using a wheel attached to the hero. For jumping I use this:

player.body.applyLinearImpulse(new Vec2(0, 30000000), player.body.getPosition());

The problem is that the xVelocity doesn't remain the same during the jump so it isn't looking natural. Is there any way to modify only the x velocity of the body so that before jumping I store it in a variable and after jumping I apply it to the body?

I hope you understand what I am trying to say.


texts:
I'm having the following problem creating this hexa tiled map.

this is what I wanted :

[EDIT]
Ok I've Managed to do this:

const float scaleX = ((float)tileWidth) / 10000,
    scaleY = ((float)tileHeight ) / 10000;
    const float hexagon_r = scaleY / 2;
    const float hexagon_dx = hexagon_r * cosf(30*3.14f / 180.0);
    const float hexagon_dy = hexagon_r * sinf(30*3.14f / 180.0);
    const float hexagon_gx = 2.0*hexagon_dx;
    const float hexagon_gy = 2.0*hexagon_dx*sinf(60*3.14f / 180.0);
    Vector2 auxPos;
    auxPos.x = 0;
    auxPos.y = 0;
    float j = 0;
    for (unsigned int y = 0; y < layer->layerHeight; y++, j += hexagon_gx * 2)
    {
        auxPos.y = y * (hexagon_gy * -2 );
        auxPos.x = j;
        for (unsigned int x = 0; x < layer->layerWidth; x++)
        {

            auxPos.x += hexagon_gx * 2;

            float angle =90 * 3.14f / 180;

            auxPos.y += hexagon_gy * 2;

            SetData(stack->vData, stack->vCounter + 0, auxPos.x + ((-scaleX) * cosf(angle) + (-scaleY) * -sinf(angle)));
            SetData(stack->vData, stack->vCounter + 1, auxPos.y + ((-scaleX) * sinf(angle) + (-scaleY) * cosf(angle)));
            SetData(stack->vData, stack->vCounter + 2, layer->layerDepth);

            SetData(stack->vData, stack->vCounter + 3, auxPos.x + ((scaleX) * cosf(angle) + (-scaleY) * -sinf(angle)));
            SetData(stack->vData, stack->vCounter + 4, auxPos.y + ((scaleX) * sinf(angle) + (-scaleY) * cosf(angle)));
            SetData(stack->vData, stack->vCounter + 5, layer->layerDepth);

            SetData(stack->vData, stack->vCounter + 6, auxPos.x + ((scaleX) * cosf(angle) + (scaleY) * -sinf(angle)));
            SetData(stack->vData, stack->vCounter + 7, auxPos.y + ((scaleX) * sinf(angle) + (scaleY) * cosf(angle)));
            SetData(stack->vData, stack->vCounter + 8, layer->layerDepth);

            SetData(stack->vData, stack->vCounter + 9, auxPos.x + ((-scaleX) * cosf(angle) + (scaleY) * -sinf(angle)));
            SetData(stack->vData, stack->vCounter + 10, auxPos.y + ((-scaleX) * sinf(angle) + (scaleY) * cosf(angle)));
            SetData(stack->vData, stack->vCounter + 11, layer->layerDepth);
        }
    }

can't seem to make this work...


texts: Using glm to rotate the modelview matrix based on the cursor position

texts:
I am rendering a 3D model of an object, and I want the user to be able to rotate around that object by dragging the mouse. To do this, I want to use the cursor position to continually update the modelview matrix.

To start with, my modelview matrix is:

1 0 0 0
0 1 0 0
0 0 1 -100
0 0 0 1

So the camera is looking at the origin of the object, and 100 units away from it. Let's say the mouse now moves onto the right-hand side of the screen. This means I want the camera to rotate around the object -- by 90 degrees, for example.

In order to compute the new modelview matrix, I take the identity matrix, rotate it by 90 degrees, and then move away from the object along the camera's z-axis by using glm::translate().

However, the problem I am having is that glm::translate() seems to move the matrix with respect to the world coordinate system, not the camera coordinate system. Therefore, "moving away from the object along the camera's z-axis" does not hold, because the z-axes of the world and camera coordinate systems are no longer aligned after the rotation.

Please could somebody explain how I should be achieving this?

Thank you :)


texts: What criteria should I have met before releasing a game?

texts:
I am working on a hobby game that is played in the browser (not flash). It is a sort of civilization simulator. It is a pretty substantial sized game that I hope one day has many players.

My question is what should my game have before I allow the public to play. I have several thoughts and would appreciate suggestions as well as other thoughts.

Limit the game to colleagues and friends to test until I effectively finish the game.
I open the game up to the public shortly after basic enjoyable functionality is done. I would then release weekly or biweekly updates with new functionality and bug fixes.

So the root question is, is it better to release to the world after everything is "done" (potentially years) or after it is "playable", but lacking?


texts:
I am attempting to rotate a vector3 by a given quaternion.

I know that this is true

$$ v' = q \cdot v \cdot q^{-1} $$

I know that \$ q^{-1} \$ is the inverse which just \$ \frac {-q} {magnitude(q)} \$, but how do I map the multiplication of the vector to the quaternion to get back a vector?

I have found that you can treat \$v\$ as a matrix, and convert \$q\$ and \$q'\$ to matrices, and then convert \$v'\$ from a matrix to a vector, but this seems a little over the top just to get a vector. Is there a cleaner implementation that I could use?


texts: JavaScript - Updating a canvas real-time... from server-side or client-side

texts:
I have this 2D tilemap game 13x13 viewport (169 tiles drawn on canvas at a time) of a 150x150 map. Each tile is 32x32px. Obviously I only update the 13x13 viewport...

I want to update a canvas in real-time as the world-map will be handled server-side. At least the logic... the drawning... should it be server-side or client-side?

Now, I am using Socket.IO for real-time data. Based on that current player's x and y, the canvas is drawn from where that person is on the map.

I can do this two ways:

(Server-side) Use node-canvas to draw the  server-side via NodeJS and
transmit back the new canvas. Is it possible? Because it seems I can
only do it once via a PNG.
(Client-side) Transmit the 169 array of the new tileset (when player moves or action happens). Doing the
logic server-side and draw it on the client-side from the array received from a callback.

Client-side problem: The problem here is that transmitting that large of an array does take seconds (2-3) so there is some lag.

Server-side problem: There is no continuous streaming of a canvas being drawn from the server that outputs to client... is there? Or am I not looking hard enough at node-canvas npm module.

I am not using any JavaScript game framework.

What are my best options here?


texts: How can I implement procedural humanoid generation like MakeHuman?

texts:
Some applications allow you to generate a human mesh by simply adjusting parameters. The results are broad and convincing: you can get from a thin asian girl to a muscular african man by just adjusting those. MakeHuman, for example, exposes the following UI:

What is the technique and what are the formulas used to implement that kind of procedural humanoid generation? Is there any published study/resource with the required information?


texts: How do I make an HTML5 canvas tiled map with tiles which have other than squared edges?

texts:
I'm creating an HTML canvas map and I'm trying to have the edges of the tiles not appear square, as in the tiles merge in to each other.  I've scoured the internet for hours but can't seem to find anything.  How would I go about doing this?

Dropbox link to project

I've included the used images so when the project is downloaded and run on the browser, the map should look like the following picture.  This is not how I want it to look but how it currently looks.

I know it's probably not possible to get this exact effect using a tile based map, and it's not a perfect representation, but here's a general idea of what I want to accomplish.  Notice how the corners are no longer squared but have a more rounded look and appear to be blending in with the next color tile.  That's my goal.

  Thanks in advance.


texts: Is there a legal option for writing Nintendo 64 games?

texts:
Recently, I've been looking into developing games for Nintendo 64 emulators, and modding existing ROMs. I wanted to know if there is the possibility for any legitimate tools out there which can be used to write the code for the emulators or if all of that is off limits.

I heard that the Nintendo 64 SDK has always been sealed by an NDA limited to the game studios, years ago; however, I'm curious about where all the current ROMs that are available came from. Mainly because, unlike discs, cartridges are not typically supported by standard hardware.


texts: How can I create a tunnel/parallax/depth effect based on mobile device tilting?

texts:
I would like to create applications similar to what's displayed in these videos:

VR Tunnel Live Wallpaper for Android
The parallax view Part 1

These mobile application are supposed to react to tilting of the phone, so I created a few 3D objects for this purpose in Blender (one similar shape - 2nd link), but I do not know how to move the back of this object in Unity because I am a beginner.

Can you give me some tips on how to figure this out? I’m not talking about a ready solution or something, I just do not know how to ask a specific question and I do not know what to do next.


texts:
I have a basic 2D tower defense game in C++.

Each map is a separate class which inherits from GameState. The map delegates the logic and drawing code to each object in the game and sets data such as the map path.
In pseudo-code the logic section might look something like this:

update():
  for each creep in creeps:
    creep.update()
  for each tower in towers:
    tower.update()
  for each missile in missiles:
    missile.update()

The objects (creeps, towers and missiles) are stored in vector-of-pointers. The towers must have access to the vector-of-creeps and the vector-of-missiles to create new missiles and identify targets.

The question is: where do I declare the vectors? Should they be members of the Map class, and passed as arguments to the tower.update() function? Or declared globally? Or are there other solutions I'm missing entirely?

When several classes need to access the same data, where should the data be declared?


texts: How to retarget animation from Generic to Humanoid?

texts:
I am in a constant struggle to convert a character that is indeed a humanoid character but its rig has been assigned as a generic rig. I want it to be humanoid so I can easily retarget its animation and apply them to another character of my own.
The problem that I am facing is that the animations when I run from the Animation tab of Unity Editor Works just fine but when I try to play them from the Script. The animations doesn’t play at all.
I don’t know what could be the problem. I need help in this regard. I have explored google all around and I am in a need of serious help. If someone can I’ll be really very grateful.
Thanks


texts: How do i calc what side the ball is of the rect?

texts:
I have this nice drawing:

http://bildr.no/view/1085283

I know the ball's center and the rectangle's center, but how do I know (programming C#) what side of the rectangle the ball is?

By my drawing, the answer in this case should be the right side.


texts: I would like to know how an OpenGL driver will be implemented to learn opengl internals?

texts:
I'm learning OpenGL and really like to know how the interaction with the Graphics card will be.

I feel understanding how it was implemented in the Graphics driver, will let me know complete internals of the opengl(With this I can know what stages/factors influence my decisions regarding performance in opengl).

Are there any ways for this path to proceed.Does exploring the 'Mesa lib' will help me in this aspect? Am I in the right path?

[I posted this question in SOF but it seems here is the right place for this Question.]


texts: Is it a terrible practice to NOT initialize an object in its constructor?

texts:
I'm currently working on my own game engine, more precisely on the resources management part.

For now, most of my assets inherits of the following - simplified - class:

class   Asset
{
public:
    Asset(const char* file);
    virtual ~Asset();

    virtual void    load() = 0;
    virtual void    unload() = 0;
}

As you can guess, the constructor and destructor do almost nothing, while load and unload functions respectively initialize and delete all asset's data.

I'm doing it because I don't want to load a file each time I create an asset object, but instead do it on a method of my AssetsManager that would load everything needed.
But I still want to be able to prepare other objects using these unloaded assets. For instance, an unloaded texture can be set on a mesh material. This material just won't be able to be rendered if the texture is not loaded.

The problem is, I heard this is a terrible way to code a class structure, especially from programmers supporting the RAII idiom.

Is it a correct way to handle assets? If not, what would be better for this class?


texts: Outline of plane slice of arbitrary object

texts:
How would you extract the outline of a shape from slicing a plane through an arbitrary object?

Note: This is related to my Unity Answers question, but not exactly the same.


texts: IConvertGameObjectToEntity interface on Unity ECS

texts:
Was working on ECS and following the tutorials by Mike Geig in Unite Copenhagen on YouTube(https://youtu.be/BNMrevfB6Q0), and understood that unity automatically converts transforms, mesh renderers and things like that to ECS, the IConvertGameObjectToEntity interface converts entities that I want specifically for my game. But, while following his tutorial exactly as he did it, the entities that I have on my game do not have colliders in them, but is seen in his demo, how do I resolve that?

EDIT: I've Instantiated an entity, and it works fine, but then implementing the
void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem); from the IConvertGameObjectToEntity interface,  I just have an entity, and only the mesh is visible, and an empty Component data that I've assigned on the Convert() method is available, I don't have a collider as it is on the prefab.

Here is my Spawn Entity Code:

void Start (){
        manager = World.Active.EntityManager;
        ObjectEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(ObjectPrefab, World.Active);

        for (int i = 0; i < 100; i++)
            SpawnTheObject();

}

private void SpawnTheObject()
{
    Entity object = manager.Instantiate(ObjectEntityPrefab);

    manager.SetComponentData(object, new Translation { Value = transform.position });
    manager.SetComponentData(object, new Rotation { Value = Quaternion.identity });

}

Here is The code attached to The Object:

public class AsteroidLifeECS : MonoBehaviour, IConvertGameObjectToEntity {
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
    MoveSpeed moveSpeed = new MoveSpeed { Value = MovementSpeed }; //A component data that has only one float called Value
    dstManager.AddComponentData(entity, moveSpeed);

    RotateSpeed rotateSpeed = new RotateSpeed { Value = RotationSpeed }; //A component data that has only one float called Value
    dstManager.AddComponentData(entity, rotateSpeed);

    Health health = new Health { Value = Health }; //A component data that has only one float called Value
    dstManager.AddComponentData(entity, health);
}

}


texts: Exists a dedicated non-O(n²) Algorithm for avoiding to have overlapping elements?

texts:
I am generating positions in a random fashion.

In the game world, instantiated elements have a radius, and shouldn't overlap.

The problem is that they will overlap because I use a usual random number generator combined with other fanciness. I can't use other random number generation algorithms where I can guarantee that the elements will never overlap.

A way to solve this is to use a spatial data structure and search for the nearest neighbors in that tree.
When I insert an element into that tree, I update it accordingly.

This solution would do the work and it would be fast but my question is:

Is there a dedicated algorithm without that Tree implementation complexity which is faster than O(n²)?


texts:
Currently I'm working on an Android OpenGL 3D game and now I want to implement a collision detection. For this I want to use oriented bounding boxes but here is my problem. For a normal oriented bounding box I have to store the middle and then the length into every dimension. Now let's say I have a tree and of course my character can walk under the treetop but not into the tree trunk. I tried to sketch up the different bounding boxes here:

Tree as two rectangels                         Normal bounding box

-----------------------                   ------------------------------
|                     |                   |                            |
-----------------------                   |                            |
        |     |                           |                            |
        |     |                           |                            |
        |     |                           |                            |
        |     |                           |             x              |
        |     |                           |                            |
        |     |                           |                            |
        |     |                           |                            |
        |     |                           |                            |
        |     |                           |                            |
        -------                           ------------------------------

If you think about the collision detection in the first sketch you can walk under the treetop because the border of the tree is subdivided into different shapes and the outline of a tree is still visible. In the second picture you can't tell something about the outline of the object because you only have one big box around the whole object so you can't walk under the treetop. You see the first method is much better then the second method for my plan.

Now my question: Do you have any ideas how I can subdivide my objects into different shapes? Maybe even in triangles, circles and so on. Is there an algorithm  for this or do I have to do it by myself?


texts: Infinite detail inside Perlin noise procedural mapping

texts:
I am very new to game development but I was able to scour the internet to figure out Perlin noise enough to implement a very simple 2D tile infinite procedural world.

Here's the question and it's more conceptual than code-based in answer, I think. I understand the concept of "I plug in (x, y) and get back from Perlin noise p" (I'll call it p). P will always be the same value for the same (x, y) (as long as the Perlin algorithm parameters haven't changed, like altering number of octaves, et cetera).

What I want to do is be able to zoom into a square and be able to generate smaller squares inside of the already generated overhead tile of terrain.

Let's say I have a jungle tile for overhead terrain but I want to zoom in and maybe see a small river tile that would only be a creek and not large enough to be a full "big tile" of water in the overhead. Of course, I want the same net effect as a Perlin equation inside a Perlin equation if that makes sense? (aka. I want two people playing the game with the same settings to get the same terrain and details every time).

I can conceptually wrap my head around the large tile being based on an "zoomed out" coordinate leaving enough room to drill into but this approach doesn't make sense in my head (maybe I'm wrong). I'm guessing with this approach my overhead terrain would lose all of the cohesiveness delivered by the Perlin. Imagine I calculate (0, 0) as overhead tile 1 and then to the east of that I plug in (50, 0). OK, great, I now have 49 pixels of detail I could then "drill down" into. The issue I have in my head with this approach (without attempting it) is that there's no guarantee from my Perlin noise that (0,0) would be a good neighbor to (50,0) as they could have wildly different "elevations" or p/resultant values returning from the Perlin equation when I generate the overhead map.

I think I can conceive of using the Perlin noise for the overhead tile to then reuse the p value as a seed for the "detail" level of noise once I zoom in. That would ensure my detail Perlin is always the same configuration for (0,0), (1,0), etc. ad nauseam but I'm not sure if there are better approaches out there or if this is a sound approach at all.


texts: Swing KeyListener doesn't work when pressing Shift X Z and directions at the same time

texts:
My code:

addKeyListener(new KeyListener() {
    @Override
    public void keyPressed(KeyEvent event) {
        if (event.getKeyCode() >= KeyEvent.VK_LEFT && event.getKeyCode() <= KeyEvent.VK_DOWN)
            direction.set(event.getKeyCode() - KeyEvent.VK_LEFT, true);
        if (event.getKeyCode() == KeyEvent.VK_Z) direction.set(4, true);
        if (event.getKeyCode() == KeyEvent.VK_CONTROL)          System.out.println(event.getKeyCode());
    }

    @Override
    public void keyReleased(KeyEvent event) {
        if (event.getKeyCode() >= KeyEvent.VK_LEFT && event.getKeyCode() <= KeyEvent.VK_DOWN) {
            speed = event.isShiftDown() ? 1 : fastSpeed;
            direction.set(event.getKeyCode() - KeyEvent.VK_LEFT, false);
        }
        if (event.getKeyCode() == KeyEvent.VK_Z) direction.set(4, false);
    }

    @Override
    public void keyTyped(KeyEvent keyEvent) {
    }
});

I start my application and press Shift, Z, and X at the same time, at this moment everything was fine (Successfully see command line output).
But when I press UP or DOWN, swing isn't invoking my listener (no command line output).

I've repeated many times and it's all the same.

Is there any work-arounds?


texts:
I'm trying to load my map properly, but it takes some time (after the games has been started) to be how it should. Am I doing something wrong? Why is this happening?

AndroidStudio:

Tiled (map editor):

public class GameScreen extends Screen{
   private TmxMapLoader maploader;
   private TiledMap map;
   private OrthogonalTiledMapRenderer renderer;

   public GameScreen(Game game){
      maploader = new TmxMapLoader();
      map = maploader.load("level1.tmx");
      renderer = new OrthogonalTiledMapRenderer(map, 1);


texts:
Good evening all, about to pull my hair out because I cant figure out why I keep getting this error. The problem is this, I need the player to click on the start button, then, the screen will fade to black and load level 1. (logic and code was provided by a Brackeys tutorial(https://www.youtube.com/watch?v=0HwZQt94uHQ), awesome guy)

here is the code for the button.

public void OnPointerClick(PointerEventData eventData)
{
    float fadetime = GameObject.Find("_GM").GetComponent<FadeScreen>().BeginFade(1);
    yield return new WaitForSeconds(fadetime);
    SceneManager.LoadScene("Level_01");
}

Now the error is highlighted with a red line under OnPointerClick just after "public void".

And the error is - The body of 'StartGame.OnPointerClick(PointerEventData)' cannot be an iterator block because 'void' is not an iterator interface type. Ive been googling for around four hours now and I'm coming up blank.(lack of sleep might be causing me to miss something)

Please can someone point out what I cannot see myself?
Also I do apologize if this has been asked before, I was not able to find anything on the subject.
Thank you kindly.


texts:
I have built a couple of games on the iPad using core animation, but for my next project I would like to built a 3D game. I am not really comfortable with programming OpenGL directly and would also like the toolset that usually comes with a mature 3D engine project. I have used Ogre3D on the PC before and was very happy with that, but I wasn't sure if it had been ported to the iPad specifically and if there were better alternatives available.

What engines have used and can recommend? Specifically I am interested in:

Cost
Tool support
Data import functionality


texts: How would I move a character In an RPG with Bullet Physics/Ogre3D?

texts:
lately I have been having problems with moving my character in my Ogre3D game. Basically I am moving the character with bullet's RigidBody->translate() function, but when doing so and bumping into a wall, I go slightly through it and then get bounced back. I am wondering if there is another good way to move my character(who has a sphere collision shape) around in a simple Plane-type world with walls?

The libraries I am using that are relative to this are 'Ogre3D' and 'Bullet Physics'.


texts:
Hey I at the moment I have got my texture to move however it stutters as I increment by 0.001 every second.  My animation is done via FPS if that make sense and here is some code

FrameCount++;

p_Time = c_Time;
c_Time = PVRShellGetTime();

elapsed = c_Time / 1000.0f;
DT = ((float)(c_Time - p_Time)) / 1000.0f;

fCount += DT;

if(fCount >= 1.0f) //if time is over 1 second reset counters and recount
{
    FPS = FrameCount;
    FrameCount = 0;
    fCount = 0;
    move += 0.001;
    glUniform1f(m_ShaderProgram.auiLoc[eTime], move);
}

My problem is I want it to move more seamlessly and not sure how to achieve this and thought I would get some ideas from you.

Oh and here is my vertex and fragment shader

Vert

    attribute highp   vec3  inVertex;
attribute mediump vec3  inNormal;
attribute mediump vec2  inTexCoord;
attribute mediump vec3  inTangent;

uniform highp   mat4  MVPMatrix;
uniform mediump vec3  EyePos;
uniform mediump float Time;

varying mediump vec3  EyeDir;
varying mediump vec2  TexCoord;
varying mediump vec2  TexCoord2;
varying mediump float vTime;

void main()
{
    // Transform position
    gl_Position = MVPMatrix * vec4(inVertex,1.0);

    /*mediump vec2 waterCoord = inTexCoord;
    TexCoord = waterCoord.xy * waterSX;
    TexCoord += watermovementX;*/
    TexCoord = inTexCoord;
    vTime = Time;
}

and here is my frag

    uniform sampler2D  n_mapTex;
uniform sampler2D  n_mapTex2;

varying mediump vec2  TexCoord;
varying mediump vec2  TexCoord2;
varying mediump float vTime;

void main()
{
    gl_FragColor =  texture2D(n_mapTex, vec2(TexCoord.x + vTime, TexCoord.y + vTime));
}

Thanks


texts: How to not move my character when they collide using Unity and Box Collider?

texts:
I'm trying to get my characters near to each other so they can attack the other one, but when the player character or otherwise gets near they are pushed to the other direction when they collide. How to prevent that happen so they won't move when touching each other?

This is the player objects:

The Treant objects:

I what I want is that they collide and can't move through each other and stop moving. But this keep happen: gif of my treant getting pushed away

Can someone help me with this issue?


texts: Find format of data from Steam API using Python

texts:
I have some user data downloaded using the Steam API (I am following the approach described here) and I need to find the format for each entry of the CSV file I generated (available here).
Using Python, the solution I came up with is the following:
import pandas as pd
import sys

df1 = pd.read_csv("./data/csgo_cheater_data_01_14_21_full.csv")
for ii in range(189):
    print(df1.columns[ii], type(df1[df1.columns[ii]].values[0]))

Running this snipped, the result is that most variables are float64, plus a few int64. Does it make sense? Is this the real format of the data or are they somehow converted when retrieved using the API?


texts: How to get the rotation matrix to transform between two 3d cartesian coordinate systems?

texts:
I'd like to know how to get the rotation matrix for the transformation from one cartesian coordinate system (X, Y, Z) to another one (X', Y', Z').

Both systems are defined with three orthogonal vectors as one would expect. No scaling or translation occurs. I'm using OpenSceneGraph and it offers a Matrix convenience class, if it makes finding the matrix easier:

  http://www.openscenegraph.org/documentation/OpenSceneGraphReferenceDocs/a00403.html.


texts: How do I get the number of Steam friends online programmatically?

texts:
How can I get the current number of Steam friends online in order to insert it into a script or program? I'm looking to use this value to do something like changing an LED colour or for providing data for a desktop widget etc.

Is this possible? How do I get access to that number?

P.S. I got my idea from here: Xbox Live Traffic Light Notifies You When Friends are Gaming


texts:
I'm making some sort of clone for FlappyBird, but with some adjustments.

I want to change from the FlappyBird's mechaninc of jumping to make the bird raise as long as the player is long-pressing the screen.
I've tried to change this:

@Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        if(action==MotionEvent.ACTION_DOWN){
            valo=-30;
            gameSate =true;
        }
        return true;//to have indication when we done
    }

To:

@Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        while(action==MotionEvent.ACTION_DOWN){
            spaceY-=3; //y axis location for the bird
            gameSate =true;
        }
        return true;//to have indication when we done
    }

Which didn't work at all, when I changed the onTouchEvent from the if statement to the while loop, the bird was frozen. With the if statement, pressing only make it bounce once, no matter if the screen is being pressed or not

Is there a way to keep the Y axis change smooth while doing it only when action==MotionEvent.ACTION_DOWN


texts: Can I legally modify the Unity splash to fit the game's theme?

texts:
I've been working on a retro game, and I was wondering whether I could change the Unity logo to make it fit the game's style (eg. pixelating the logo).
I know how to do this, but my question is whether it is illegal, assuming I have a Plus, Pro, or Enterprise licence for Unity that allows me to edit this splash screen at all.


texts: Blending Lights Into An Image Pulled From Memory (2d)

texts:
The circumstances to why I am forced to do things this way are a bit weird, without going into them, I have the following situation:

I have a pointer that points to image data arranged in the form ARGB, that is overlayed over a scene (2d) to give the ambient lighting and colour. What I need to do is blend in image data generated from lights so that the colours combine and each light makes the overlay more transparent based upon its intensity. Doing this pixel by pixel each frame is slow and bogs everything down, but it works just fine for static lights if done at load time (since they don't change, it doesn't need to be redone).

My final solution requires that the final combined overlay for the lighting be contained in the original pointer; so any method that requires using a different setup, or pulling the data from the pointer, then dumping it back in, might be problematic. I do not, unfortunately, have anyway to modify the source and am stuck passing everything thorough a call to a dll, so I have no other means of introducing lights that doesn't use this structure.

I'm working on Windows and using C++. I, also, want to point out that I am not a games programmer, though I am a programmer, so a lot of what I tried looking up is a bit foreign to me.

Thank you for any help:-)

*Currently, everything happens on the CPU, is there a way to shove everything over to the GPU, do the work (ideally using the blending function I wrote), then bring the result back and put it in the pointer? I looked into using Cuda or OpenCL, but they seem a bit dense to just dive into - but, more importantly, I'm not very familiar with them and am not sure how portable everything will be (and, sadly, given the setup I'm working with, I can't do a lot of extensive testing beyond, see if it crashes when the DLL is called, due to the nature of the problem at hand).


texts: Manual occlusion culling with glDrawElements

texts: How should I go about doing occlusion culling with glDrawElements? I am dealing with voxel-like terrain. I want to avoid drawing the faces that are facing another block. I just don't know how to incorporate this with glDrawElements. Should I even use glDrawElements?


texts: Why can't a blueprints project edit BPs derived from c++ classes?

texts:
I am working in a relatively small team.

Now, because our IT guy is incredibly unhelpful, we don't yet have VS on all the machines (as I know this would solve the error). However, I'm still curious as to the answer to this question.

Computer A:

C++ project
Creates C++ classes
Creates BP derived from said C++ classes.
Sends project to Computer B.

Computer B:

Gets project
Tries to edit BP classes
Can't open them
Reason: 'They derive from parent C++ classes'

So my base question is really why is this?

I understand that this can be solved easily, but I'm interested as to why Unreal imposes these limitations.


texts: How do I combine images into a single entity in libgdx?

texts:
I've googled this but can't seem to find anything on "concatenating" two images, especially with libgdx.

Any ideas?


texts: Does Apple currently accept iPhone apps with embedded Lua?

texts: I was researching this and I can't seem to find a concrete answer.


texts: Unity 3D: how to hide/unhide objects as player collides with them without flickering?

texts:
I have a maze grid of cubes that my player navigates through. I'm trying to make it so that each cube is only visible when the player is near it (so the player can only see the 4 cubes immediately around them at any one time).

I've been trying to do this using OnCollisionEnter/Exit, and turning on/off the renderer in each cube when the player is nearby (with colliders large enough that in theory the player should be touching more than one at a time). But this just creates a flicker effect.

I've also tried doing it using OnTrigger but that's not working because I need the cubes to be solid objects the player cannot pass through.

If anyone has some ideas, that'd be awesome. I've been trying to crack this one for a while but I'm a researcher rather than a coder so my programming skills are limited.

Thanks!


texts: Update single variable in DirectX Shader

texts:
I am trying to update a single variable within a CBuffer but I am unsure of how to do this.

I have a LightingBuffer which is passed to the GPU containing, ambient color, diffuse color etc and I want to be able to update the specularPower component of this CBuffer but not the rest.

In openGL I could just do glUniform1f and update it, however I cannot do this is DX / HLSL

How would I go about doing this?


texts: How to make noise-generated terrain more square?

texts:
I use a perlin noise generator to create a map. All works fine and dandy. It uses the following formula:

Generate perlin noise
Posterize the height values to be an integer between 0 and 5.

What I get works well. Just, the terrain is TOO organic for my purposes. Is there a way to make it a little more square and chunky?


texts: Unity - How to get nicer shadows from distant point lights?

texts:
I get too unsatisfying results for shadows when using a point light that is far away. (The quality settings are maxed.)

The scene:

The result:

The light:

What can I do to get better shadows?


texts: How to manage collision between balls in Game Maker 2 (Drag and Drop)

texts: Hey there I'm using Game Maker 2 Drag and Drop for a project, I made a game like Break Out and when the ball collides with the wall it doesn't bounce, in Game Maker Studio we had Bounce Action but in GMS2 is deleted, can anyone help me about this issue?


texts: How to implement SDL Button/Menu GUI with callbacks?

texts:
I have been reading Bjarne Stroustrup's Programming Principles and Practice Using C++ for a while now and am nearing the end of the book. I have to tried to make a very simple game using the SDL libraries as a little exercise to practice programming and utilize techniques from the book.

I've attempted to implement a rather crude GUI system that sort of resembles the one described in the book. The problem that I am having is implementing a callback system so that when a button is constructed it takes a member function as an argument so that it can be called when the button pressed. The reason why it needs to be a member function is that the game has a state system very similar to this http://gamedevgeek.com/tutorials/managing-game-states-in-c/ since I followed the tutorial when crafting my own game state system.

The existing code looks like this:

class Button : public Widget {
private:
    SDL_Surface* m_image;
    SDL_Rect* m_clip;
    bool m_pressed;
    bool m_released;
    int frame;
public:
    Button(int x, int y, int w, int h, SDL_Surface* img, SDL_Rect* clip);
    void handle_events(SDL_Event& event);
    void show(SDL_Surface* screen, GameState* state);
    bool released();
};

Button::Button(int x, int y, int w, int h, SDL_Surface* img, SDL_Rect* clip)
   :Widget(x,y,w,h),
   m_image(img),
   m_pressed(0),
   m_released(0),
   m_clip(clip),
   frame(0)
{
}

So my question is: How do you pass a function in the constructor and call it when the button is pressed? (Like a callback). Currently each state, for example a Menu state, will just look if a button is pressed and perform a corresponding task which is pretty bad and hardly readable.

Stroustrup's code for the GUI system in the PPP book can be found here:
http://www.stroustrup.com/Programming/Graphics/
in the two GUI files.

Thanks in advance.


texts: Bloom shader makes it impossible to render black?

texts:
I am playing around with the bloom shader from the XNA sample page, to do some glow shading. I am rendering primitive vector-ish squares of linelists/linestrips, on a background. However, I am facing a few problems.

With a black background and white squares, I can actually see the squares. However, with a white background and black squares, I can't see them at all.

Why is this happening, and is there any way of me fixing it?

Can I modify my bloom shader to also "glow" dark elements, if that's what is causing it?


texts: Camera and enemy behaviour in AS3 platformer

texts:
beginner in AS3 here. I am working on a platformer game based on the code of a provided example exercise. I have the following problem:

I have an enemy who shoots bullets. The enemy is the parent, and the bullet are the child. When I move to the next scene (level), the bullets are still there, but invisible, even using the removeEventListener to shut down the bullet hit check.

Here is the code of the child "disparoEnemigo_mov":

addEventListener(Event.ENTER_FRAME, fl_MoveEnemyShot);
function fl_MoveEnemyShot(event: Event) {
try {
    if (enemy_shot.y < 300) {
        if (enemy_shot.hitTestObject(Object(this.parent).mario)) {

            variablesGlobales.variables().vidas -= 1;
            Object(root).texto.text =
variablesGlobales.variables().vidas.toString();
            trace("vidas: " + variablesGlobales.variables().vidas);
            if (variablesGlobales.variables().vidas < 1) {
                MovieClip(this.parent).gotoAndStop(2);
            }
            this.parent.removeChild(this);
            removeEventListener(Event.ENTER_FRAME, fl_MoveEnemyShot);
        } else {
            enemy_shot.y += 3;
        }
    } else {
        trace("LLEGADA");
        removeEventListener(Event.ENTER_FRAME, fl_MoveEnemyShot);
        this.parent.removeChild(this);
    }
} catch (error: Error) {
    removeEventListener(Event.ENTER_FRAME, fl_MoveEnemyShot);
}
}

import flash.events.Event;
import flash.media.SoundMixer;

addEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler);

function fl_EnterFrameHandler(event: Event): void {
try{
if (this.hitTestObject(Object(this.parent).mario)) {

    SoundMixer.stopAll();
    var sound:gameOver = new gameOver();
    sound.play();
    Object(this.parent).mario.y=1000;
    Object(this.parent).mario.x-=15;
    trace("Mario dies");
    var cartel:StageLose = new StageLose();
    stage.addChild(cartel);
    cartel.x = -85;
    Object(this.parent).mario.y = 1000;
    }
}catch(error: Error){
removeEventListener (Event.ENTER_FRAME, fl_EnterFrameHandler);
}
}

And this is the code of the parent, "enemigo_mov":

var leftPressed: Boolean = true;
var rightPressed: Boolean = false;
stage.addEventListener(Event.ENTER_FRAME, fl_MoveEnemy);
function fl_MoveEnemy(event: Event) {
try{
if (leftPressed) {
    enemy1.x -= 0;
    if (enemy1.x < -120) {
        leftPressed = false;
        rightPressed = true;
    }
} else if (rightPressed) {
    enemy1.x += 1;
    if (enemy1.x > 120) {
        rightPressed = false;
        leftPressed = true;
    }
}
var number: Number = Math.random();
if (number < 0.05){// &&
variablesGlobales.variables().coleccionEnemigos.indexOf(this) != -1) {
    trace("creation");
    var disparo: disparoEnemigo_mov = new disparoEnemigo_mov();
    this.parent.addChild(disparo);
    disparo.x=enemy1.x +115;
    disparo.y=enemy1.y +115;

    //disparo.z=50;
    trace(disparo.x + " " + disparo.y);
    }

}catch(error:Error){
removeEventListener(Event.ENTER_FRAME, fl_MoveEnemy);
}
}

In both codes, "mario" is the player character.

What I need to do is to stop the bullet creation of ""disparoEnemigo_mov" when we move to the next scene. Shouldn't the "removeEventListener(Event.ENTER_FRAME, fl_MoveEnemy)" line stop the bullets to check if there is any collision with the player?

Any help or resource will be helpful. Thank you so much!


texts: Unity (UNET) Pass custom data when creating and joining a match in multiplayer

texts:
I've written some simple stuff to make a lobby for matchmaking. Now I want to pass some extra info besides the match name to the lobby. Something like Player's avatar and a number of players connected and what not.
Thereto, I also want to pass information to the game from the players.
For example, two players connect to a match and the character pick starts. For this I want to have the player's info regarding the characters they've picked and the character's weapons info (e.g. customized weapons info). I store all that in a json file and load from it to a class object. Is it ok to add these classes to, say, the player connection prefab that holds Network Identity or is it done somehow differently?

Can someone maybe help me with that in the context of Unity 2018 (i.e. give some advice or referrences to some relevant information)?

Appreciate all the help and thanks in advance.


texts: Looking for the reference tutorials for the joints in the Box2D for iphone

texts:
I can't find the tutorials of joints class in the Box2D for iPhone. I am unable to run a Testbed for iPhone Box2D.

(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
       if (_mouseJoint!=NULL)return;
       UITouch *mytouch=[touches anyObject];
       CGPoint location=[mytouch locationInView:[mytouch view]];
       location=[[CCDirector sharedDirector]convertToGL:location];
        b2Vec2 locationWorld=b2Vec2(location.x/PTM_RATIO,location.y/PTM_RATIO);
 //ristrict the player within the ground limit  keep stucking the player with grounditself.....
if (_playerFixture->TestPoint(locationWorld))
{
    b2MouseJointDef md;
    md.bodyA=groundBody;
    md.bodyB=_playerBody;
    md.target=locationWorld;
    md.collideConnected=true;
    md.maxForce=100.0f*_playerBody->GetMass();
    _mouseJoint=(b2MouseJoint *)_world->CreateJoint(&md);
    _playerBody->SetAwake(true);
}
}

-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if (_mouseJoint == NULL) return;
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
if (location.y<240.00&&location.y>=20.0f)
{
    b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
    _mouseJoint->SetTarget(locationWorld);
}
}

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if (_mouseJoint)
{

 _world->DestroyJoint(_mouseJoint);
    _mouseJoint = NULL;

  }

}


texts: How do I improve terrain rendering batch counts using DirectX?

texts:
We have determined that our terrain rendering system needs some work to minimize the number of batches being transferred to the GPU in order to improve performance. I'm looking for suggestions on how best to improve what we're trying to accomplish.

We logically split our terrain mesh into smaller grid cells which are 32x32 world units.  Each cell has meta data that dictates the four 256x256 textures that are used for spatting along with the alpha blend data, shadow, and light mappings.  Each cell contains 81 vertices in a 9x9 grid.

Presently, we examine each cell and determine the four textures that are being used to spat the cell.  We combine that geometry with any other cell that perhaps uses the same four textures regardless of spat order.  If the spat order for a cell differs, the blend map is adjusted so that the spat order is maintained the same as other like cells and blending happens in the right order too.

But even with this batching approach, it isn't uncommon when looking out across an area of open terrain to have between 1200-1700 batch count depending upon how frequently textures differ or have different texture blends are between cells.  We are only doing frustum culling presently.

So using texture spatting, are there other alternatives that can reduce the batch count and allow rendering to be extremely performance-friendly even under DirectX9c?

We considered using texture atlases since we're targeting DirectX 9c & older OpenGL platforms but trying to repeat textures using atlases and shaders result in seam artifacts which we haven't been able to eliminate with the exception of disabling mipmapping.  Disabling mipmapping results in poor quality textures from a distance.

How have others batched together terrain geometry such that one could spat terrain using various textures, minimizing batch count and texture state switches so that rendering performance isn't negatively impacted?


texts: How to keep sprite on screen while increasing its width to screen width

texts:
I have been able to increase the width of a sprite to the width of the screen size, but the sprite exceeds the borders of the screen width to the right or left when I try expanding it when it's not at the center. How can I scale the sprite in such a way that it's width increases on both sides till it occupies the screen width without exceeding it's bounds, regardless of the sprite's initial position? Please see my code below:

bool isScaling = false;

IEnumerator scaleToX(SpriteRenderer spriteToScale, float newXValue, float byTime)
    {
       if (isScaling)
         {
           yield break;
         }
       isScaling = true;

       float counter = 0;
       float currentX = spriteToScale.transform.localScale.x;
       float yAxis = spriteToScale.transform.localScale.y;
       float ZAxis = spriteToScale.transform.localScale.z;

       Debug.Log(currentX);
       while (counter < byTime)
        {
          counter += Time.deltaTime;
          Vector3 tempVector = new Vector3(currentX, yAxis, ZAxis);
          tempVector.x = Mathf.Lerp(currentX, newXValue, counter / byTime);
          spriteToScale.transform.localScale = tempVector;
          yield return null;
        }

       isScaling = false;
  }


texts: How can I set up Unity so that 2d images are displayed in their original resolution?

texts: I took images from my iOS game that I am developing in SpriteKit and put them in a Unity Android 1136x640 screen, which are the same dimensions for the iOS game but the images are a lot smaller. How can I get a similar representation that coincides with the screen size? I would like a 284x640 image to be displayed to take a quarter of the screen width, which is what happens in reality.


texts: How does Ashley keep systems up-to-date with its entities?

texts:
I am currently trying out Ashley and overall learning how an ECS works internally. What I currently don't understand is how Ashley in particular keeps its systems up-to-date by adding or removing entities based on the specified Family. See the following code:

  def main(args: Array[String]): Unit = {
    val engine = new Engine()

    engine.addSystem(new EntitySystem() {
      var entities: ImmutableArray[Entity] = _

      override def addedToEngine(engine: Engine) = {
        entities = engine.getEntitiesFor(Family.all(classOf[MyComponent]).get())
        println("updated entities")
      }

      override def update(deltaTime: Float) = {
        println(entities.size())
      }
    })

    engine.update(0F)
    engine.addEntity(produce())
    engine.update(0F)
    engine.addEntity(produce())
    engine.update(0F)
    engine.addEntity(produce())
  }

  def produce() = {
    val entity = new Entity()
    entity.add(new MyComponent)
    entity
  }

  final class MyComponent extends Component

Which regurgitates the following output:

updated entities
0
1
2

The entities object is an immutable wrapper around LibGDX's Array collection. The wrapped mutable variant isn't exposed either to the outside. There is no way this array can be mutated. The overrided addedToEngine method is only called when the EntitySystem was added to the Engine.


texts: Casting a shadow over a whole scene with GLSL in 2D?

texts: I'm making a (non-isometric) side scrolling 2D game and I want each fragment that I draw to cast a small drop shadow when it is near another object. What sort of algorithms are used in fragment shaders to cast shadows in 2D games?


texts: Event type and SDL_QUIT are incompatible

texts:
I'm following the Lazy Foo SDL2 tutorials, and I've run into a problem when trying to poll for events. While I'm polling for the events, the event type and SDL_QUIT throw an error saying the operand types are incompatible when trying to see if they're equal.
SDL_Event e;

while (!quit)
{
    // Handle vents on queue
    while (SDL_PollEvent(&e) > 0)
    {
        // User requests quit
        if (e.type == SDL_Quit)
        {
            quit = true;
        }
    }
}

I double-checked and everything is linked correctly, and I've tried other scenarios and it always says the same thing. Does anyone have any ideas about what could be going wrong?


texts: How can I calculate the penetration depth between two colliding 3D AABBs?

texts:
I'm currently working on implementing a very basic collision system in my game at the moment that only uses 3D AABBs. My AABB struct currently looks like this at the moment.

/// <summary>
/// This struct represents a 3-dimensional bounding box that is aligned
/// to the three world axes.
/// </summary>
public struct AxisAlignedBB
{
    public Vector3 Position { get; set; }
    public Vector3 HalfScale { get; set; }

    /// <summary>
    /// Constructor for the AxisAlignedBB struct.
    /// </summary>
    /// <param name="position">The position of the AABB.</param>
    /// <param name="halfScale">The half scale of the AABB.</param>
    public AxisAlignedBB(Vector3 position, Vector3 halfScale)
    {
        this.Position = position;
        this.HalfScale = halfScale;
    }
}

I'm stuck on how the penetration depth between two different colliding AABBs with the AABB format I've laid out in the struct above is calculated. I've spent hours trying to come up with and look for a solution to this but I just can't seem to find anything.


texts: Using a shader messes up my alpha in XNA

texts:
I'm making a 2D game that ends up being too dark on some laptops, so I figured I'd use a shader so people could brighten it up if need be.  Unfortunately, once I got it in there nothing would fade in or out, they'd just pop in and out.

Here's my FX file

float intensity;

sampler TextureSampler : register(s0);

float4 Glow(float2 texCoord:TEXCOORD0):COLOR0
{
    float4 Color;
    Color = tex2D(TextureSampler, texCoord.xy);
    Color.rgb *= intensity;
    return Color;
}

technique Technique1
{
    pass Glow
    {
        PixelShader=compile ps_2_0 Glow();
    }
}

Even after commenting out the Color.rgb *= intensity; line it still removes all fading effects.

I'm using the sprite batch to draw, and I begin and end it a few times because I use different BlendStates

brightnessShader.Parameters["intensity"].SetValue(brightness);
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, brightnessShader, Matrix.CreateScale(scale));
...
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive, null, null, null, brightnessShader, Matrix.CreateScale(scale));
....
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, brightnessShader, Matrix.CreateScale(scale));
...
spriteBatch.End();

I'm using XNA 4.0.


texts: Java - Genetic Algorithm - Multi Paint Components

texts:
Currently working on a Genetic Algorithm in Java where I'm using a JPanel to draw my population and my target. The technical code works (generate population, mutate, crossover, get genes, etc...) but I'm stuck with the code to draw all my population.

Currently each individuals have x, y, x velocity ,y velocity and an array of directions ["up", "up", "down", ...] as attributes.

Tried to do:

// Draw the destination square in Red, individuals in Black
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setColor(Color.red);
    g2.fill(new Rectangle2D.Double(destinationX(),destinationY(), 10,10));
    g2.setColor(Color.black);
    // Draw each Individual in black
    for (Individual ind : Population)
      // read their genes one by one and repaint everytime to see the square move
}

But it's extremely messy, ugly and hard to debug.

How should I go from here? Should all individuals be JPanels that I'll add to the main JPanel? Do I need to use Threads? Any suggestion would be appreciated.


texts:
I'm wondering how I can tilt a platform on it's center/axis.

For example, if the player steps on the left of the center, it should tilt to that side like in this picture.

Can a platform like this still be an array of tiles? or does it have to be solid.
Are there any good libraries (javascript) to handle this kind of transformation and the calculations required?

Could someone provide example code for what this might look like?
Thank you.


texts: Can a developer change their product name on Steamworks?

texts:
I recently got access to Steamworks and paid the product submission fee. Now I am able to create an app on Steam.

The app I'm working on is still untitled, but I want to start playing around with the Steamworks functionality.

Unfortunately, when I try to create a new app, Steamworks asks me for my product name. I am not sure if I will be able to change this later, so I am hesitant to proceed.

So my question is: If I use a tentative name for my product on Steamworks, will I be able to change it later?

I tried googling around, but couldn't find anything. There is too much noise from questions about changing one's username, etc.


texts: What is the proper, legal way to make a derivative video game?

texts:
I want to make a game derived from an existing game. That game is owned by a live company.

How do I go about contacting the rights owners correctly and negotiating for the rights to the content?


texts: How can I export a model using the CAT bone system into XNA?

texts:
Has anyone successfully used the CAT bone system in 3ds Max and exported the file into XNA? If so, what was your method of doing so?

There are a number of methods of doing this, apparently, but the ones I've tried have not worked.

I used the Panda Exporter which creates an .X file. This seems to be the latest way of going about this, but when it's loaded in XNA, there is an error saying something about the bone weights. This happens when I export with and without CAT bones.


texts: Default Animations is not playing again when the object is set inactive and made active again

texts:
in my game I have a default animation added through animator. The default Animation is now stops working after playing once. In a non looped Animation clip, When the Object is disabled by setting it's SetActive false, then the default animation doesn't play upon reactivating the object. See the following package. When you open it in Unity 5.5 then Animation play fine but in Unity 5.6 Default animation plays only once

File To download


texts: Strange problem with rotation missile | unity3d - c#

texts:
I have a vertical missile with launcher that should find closest target and fire it's rocket to hitting target!

I use complete code of this 12min tutorial for launching my rocket, and the different between mine and its about the direction of rocket, mine is vertical and its horizontal!

homingMissile.velocity = transform.forward * missileVelocity;
Quaternion targetRotation = Quaternion.LookRotation(target.position - transform.position);
homingMissile.MoveRotation(Quaternion.RotateTowards(transform.rotation, targetRotation, turn));

After running the code, the rotation of my rocket change from (0,0,0) to (-8
.3,-4.7,0)!!!! and just change a little while hit target and explosion do.

In fact my rocket move to target in right path, but in wrong rotation!, in STRANGE!

Standby Rocket

Moving to Target

Anyone can help me for this problem?


texts: Why does my blur shader implementation produce this strange result?

texts:
I tried to implement the blur shader shown here.

Instead of having a simple 2D texture I use Unity's GrabPass function to capture what's behind the plane to have a transparent effect. Then I apply this on a 3D plane:

struct v2f {
    float4 pos : SV_POSITION;
    float4 screenPos : TEXCOORD3;
    float3 uv;
};

v2f vert(appdata_full v)
{
    v2f o;
    o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
    o.screenPos = ComputeScreenPos(o.pos);
    o.uv = UNITY_PROJ_COORD(o.screenPos);
    return o;
}

// In the frag part there is the shader blur computation but based on XYZ, with Z = 0

Then I apply the blur and this leads to this when I zoom in:

Is there a way to avoid this effect?


texts: Unity C# - My parameter 'campfireNew' does not exist (SetTrigger)

texts:
I'm trying to set a SetTrigger parameter to call a different sprite animation on a campfire. I tried this also with a boolean, yet again the same error. parameter 'campfireNew' does not exist. Anyone familiar with this issue?

using UnityEngine;
using System.Collections;

public class WoodBehaviour : MonoBehaviour {

    bool campfire = false;
    private int count;
    public GUIText countText;
    public int startingValue = 100; // The amount of value the fire starts the
                                    // game with.
    public int currentValue;        // The current value the fire has.
    //public Slider valueSlider;    // Reference to the UI's health bar.
    bool inTrigger = false;
    public int increaseValue = 25;  // The amount of health taken away per attack.

    Animator anim;                  // Reference to the Animator component.

    // Use this for initialization
    void Start () {

        count = 0;
        setCountText ();
        currentValue = startingValue;
        anim = GetComponent <Animator> ();
    }

    void Update () {

        if (inTrigger){

            if (Input.GetKeyDown(KeyCode.E) && count > 0){

                count -= 1;                                 // Minus one log
                currentValue += increaseValue;              // adds value
                anim.SetBool ("campfireNew", campfire);
                //  delay("200");
                setCountText ();                            // Updates HUD

                SendMessage ("PressedKey");

            }
        }
    }

    // OnTriggerEnter 2D
    void OnTriggerEnter2D(Collider2D other) {

        // If gameObject comes in contact with player
        if (other.gameObject.tag == "WoodStumps") {
            other.gameObject.SetActive (false);
            count += 1;
            setCountText ();
        }

        // If player comes in contact with gameObject
        if (other.gameObject.tag == "CampFire") {
            inTrigger = true;
        }

    }

    void OnTriggerExit2D(Collider2D other) {
        inTrigger = false;
    }

    void setCountText() {
        countText.text = "Count: " + count.ToString();
    }
}


texts: In Unity3D (and PhysX), how do I calculate the products of inertia?

texts:
Since unity3d uses physx underneath the surface, obviously they share the same features.

One of the features is the moment of inertia tensor - Unity3D one, PhysX one.

Though, they use the diagonal of the tensor, or in other words, only the moments of inertia excluding products of inertia.

Now, how would I calculate the products of inertia... I have to recalculate the whole tensor, or I can somehow extract the products?

I have checked around, but couldn't find a derivation solution (nor I know whether it is possible).


texts:
I'm new to game development in some phases and I want to understand everything I do (at least most of it) so I've started developing in MonoGames framework (XNA) and I saw a function like this.

rocket.angle = System.Math.Atan2(rocket.rocketdirection.X , -rocket.rocketdirection.Y);

I didn't understand this function (I was following a tutorial) and dove deeper into understanding sin, cos and tan. Now I have some understanding over it but one thing is unclear to me.

This was shown to me in a way to show how you calculate sin, cos and tan and I didn't understand it.

Why is the circle represented as 1,1 and -1,-1?
And why is Y = sin and X = cos?
And through this tan = cos/sin?

Can somebody explain this picture in a better way, in a way that is relatively easy to understand?


texts: Javascript injection problems to beat my game! HELP

texts: So I have a web application game that runs completely on the client side and just returns the score back to the server to list the highest scorer. Now I have noticed that I can easily manipulate the scores via accessing the variables from the console and injecting my own value! This SUCKS! I am a total noob in this kinda development and have absolutely no clue how I can stop this apart from obfuscating the code and praying to god that the hacker doesn't figure out which variable is he supposed to use! Now I was hoping there are better ways to stop the hacker to gain access of my variables. Could someone help me out with this issue!?


texts: When should I mark GameObjects as Static?

texts:
Here is the corresponding Unity documentation.

According to explanations of Unity documantation pages about Static GameObjects, sometimes marking GameObjects as static may effect performance in a bad way (for example Static Batching causes more memory usage).

So when should i exactly want to use these functionalities?

Thanks in advance.

Footnotes:
I'm currently developing a 2D top-down game which has lots of Sprites and LineRenderers, but no 3D objects (not even a quad). All GameObjects are being instantiated procedurally from premade prefabs. LineRenderers get updated from scripts each frame. And nearly all Sprites are moving constantly. Majority of Sprites share same material. All LineRenderers also share same material of their own.


texts: What has the most efficient intersection test against an AABB tree - OBB, Cylinder or Capsule?

texts: I'm currently trying to find collisions in 3D between a tighter volume than an AABB and a tree of AABB volumes. I just need to know whether they are intersecting, no closest distance or collision response. An OBB, Cylinder or Capsule would all roughly fit these purposes but Cylinder and Capsule were the first thing I thought of, which I have found little information about detecting intersections online. Am I right in thinking that they would always be more complex to perform Separating Axis Tests on even though they might seem like simpler shapes? I figure by the time I get my head around SAT for curved shapes I could have done the thing with OBBs but I wanted to find out for sure.


texts: How to keep the questions in Math game application ?

texts:
I would like to create a simple Math game application in android phone but I don't know what kind of data storage which I should use to keep the sets of numeric for the questions.
At this time, I am hesitating with the SQLite and text file.
Please suggest me. And If you have any tutorial or example, please give me them.

Appreciate your help.