texts: cocos2dx: RunningScene != Scene You just Replace

texts:
I have this code for cocos2d-x 3.x:

void MainMenu::StartGame(cocos2d::Ref* pSender)
{
    auto director = Director::getInstance();
    auto newScene = Scene::create();
    director->replaceScene(newScene); //run
    Scene *maybeNewScene = director->getRunningScene();
    CCASSERT ( maybeNewScene == newScene , "...") ;          //Assert Fail

    auto hudLayer= HUD::create();
    hudLayer->setPosition(Vec2::ZERO);
    scene->addChild(hudLayer, Z_NORMAL);
}

But When I get runnign scene by director->getRunningScene(), It gives me the scene which was running before calling director->replaceScene(). (the scene which is going to be destructed soon)

When I checked replaceScene() function, This function places newScene in some varibale called _nextScene but not assigned it to _runningScene .

Question:  How can I access newScene, just some lines further? ( for example in HUD::init())


texts: Strange result, when changing variable name

texts:
I have no idea, what is going on. The mat4 xxx is the cause. Renaming it to "bones"/"bone_transfromations" etc. won't work it gives me an error. Renaming it to "test" works perfectly fine... This is my GLSL code:

#version 400 core

//data from VBO
in vec3 position;
in vec2 texture_coordinates;
in vec3 normal;
//bone data
in int bone_pointer;
in float bone_intensity;
//vertex color output
out vec4 color;
//texture coordinates
out vec2 pass_texcoords;
out vec2 texCoord0;
//normal
out vec3 surface_normal;
//vector pointing towards the light
out vec3 to_light_vector;

//position, rotation, scale
uniform mat4 transformationMatrix;
//perspective projection
uniform mat4 projectionMatrix;
//TODO: material color
uniform vec3 in_color;
//camera viewmatrix
uniform mat4 viewMatrix;
//lights
uniform vec3 lightPosition;
uniform vec3 lightColor;
//skeleton data
uniform mat4 xxx;

void main()
{
mat4 total_transform = xxx * transformationMatrix;
vec4 worldPosition;

worldPosition =  total_transform * (vec4(position, 1)) ; //

vec4 pos =  projectionMatrix * viewMatrix * worldPosition;
gl_Position = pos;

//Texture
pass_texcoords = texture_coordinates;

//light
surface_normal = (total_transform *  vec4(normal, 0)).xyz;
to_light_vector = lightPosition * worldPosition.xyz;

//textures
 texCoord0 = texture_coordinates;

}


texts: What is the difference between resource.texture() and resource.image()?

texts:
image = pyglet.resource.image('spritesheet.png')
image.blit(0,0)

And

image = pyglet.resource.texture('spritesheet.png')
image.blit(0,0)

doing the same thing - they are drawing a spritesheet (or only one image), and they returns Texture type.


texts: Forge 1.14.4 Minecraft modding: Override vanilla loot tables

texts:
I cannot figure out how to override vanilla loot tables, I've been at this for hours, and I can't find anything online. Just very outdated tutorials.
I added custom crops and seeds to my mod, now I need those seeds to drop from the in-world grass.

The loot tables for my custom blocks are in data.modId.loot_tables.blocks and they work just fine.

Now, when I try to override the grass to drop an item of my choosing, say, coal, I do this:

1) Make  grass.json

2) Fill it:

{
  "type": "minecraft:block",
  "pools": [
    {
      "rolls": 1,
      "entries": [
        {
          "type": "minecraft:alternatives",
          "children": [
            {
              "type": "minecraft:item",
              "conditions": [
                {
                  "condition": "minecraft:match_tool",
                  "predicate": {
                    "item": "minecraft:shears"
                  }
                }
              ],
              "name": "minecraft:grass"
            },
            {
              "type": "minecraft:item",
              "conditions": [
                {
                  "condition": "minecraft:random_chance",
                  "chance": 0.125
                }
              ],
              "functions": [
                {
                  "function": "minecraft:apply_bonus",
                  "enchantment": "minecraft:fortune",
                  "formula": "minecraft:uniform_bonus_count",
                  "parameters": {
                    "bonusMultiplier": 2
                  }
                },
                {
                  "function": "minecraft:explosion_decay"
                }
              ],
              "name": "minecraft:coal"
            }
          ]
        }
      ]
    }
  ]
}

3) Place it in my project in data.minecraft.loot_tables.blocks

When I test it in game, grass still drops wheat seeds and not coal. Why?


texts: Enter in a match that is already started

texts:
In my Unity mobile game, I need multiplayer online functionalities. All the players should be visible in the world at any given time (of course, with some filtering), and a player should be able to connect at any time. Let's say that, for the purpose of this question, only 100 players at the time will log into the game.

My first try involved using Unity's built-in NetworkManager, but the two problems that arose are that:

One player is always the host, meaning that if that player logs out all the other players.
I did not manage to make it work on two different networks.

The implementation I used comes from this tutorial.

Next try was using an extension of NetworkLobbyManager, that allows through the Matchmaking system to solve problem 2.

This is my implementation:

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

public class AutoLobbyManager : NetworkLobbyManager {

    protected int currentPage = 0;
    protected int previousPage = 0;

    public void CreateOrJoin() {
        StartMatchMaker();
        RequestPage(0);
    }

    public void OnMatchListReceived(bool success, string extendedInfo, List<MatchInfoSnapshot> matches)
    {
        if (matches.Count == 0) {
            // Server does not exist yet. Create one.
            CreateMatch();
            return;
        }

        // There is then a server. Join it.
        JoinMatch(matches[0]);

    }

    public void RequestPage(int page) {
        matchMaker.ListMatches(page, 1, "", true, 0, 0, OnMatchListReceived);
    }

    public void CreateMatch() {
        matchMaker.CreateMatch( "Main Match", (uint)maxPlayers, true, "", "", "", 0, 0, OnMatchCreate);
    }

    void JoinMatch(MatchInfoSnapshot match) {
        matchMaker.JoinMatch(match.networkId, "", "", "", 0, 0, OnMatchJoined);
    }

    public override void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo) {
        base.OnMatchCreate(success, extendedInfo, matchInfo);
        Debug.Log("Match created!");
        ServerChangeScene(playScene);
    }

     public override void OnClientSceneChanged(NetworkConnection conn) {
         string loadedSceneName = SceneManager.GetSceneAt(0).name;
         if (loadedSceneName == lobbyScene) {
           if (client.isConnected)
               CallOnClientEnterLobby();
         } else {
           CallOnClientExitLobby();
         }

         OnLobbyClientSceneChanged(conn);
    }

    void CallOnClientEnterLobby() {
        OnLobbyClientEnter();
        foreach (var player in lobbySlots)
        {
            if (player == null)
                continue;

            player.readyToBegin = false;
            player.OnClientEnterLobby();
        }
    }

    void CallOnClientExitLobby() {
        OnLobbyClientExit();
        foreach (var player in lobbySlots)
        {
            if (player == null)
                continue;

            player.OnClientExitLobby();
        }
    }

}

This makes possible to create a Lobby if there is no Lobby, and join the first if there is. It works, if we remove the highlighted line here:

public override void OnMatchCreate(bool success, string extendedInfo,
MatchInfo matchInfo) {
    base.OnMatchCreate(success, extendedInfo, matchInfo);
    Debug.Log("Match created!");
    ***** ServerChangeScene(playScene); *****
}

Because this starts the game. If that line is activated (since I want to start the game as soon as possible), when a client tries to connect, the Server logs:

NetworkLobbyManager can't accept new connection [hostId: 0 connectionId: 1 isReady: False channel count: 2], not in lobby and game already in progress.

And the client is not added to the game. I understand that lobbies usually work like that, but:

1. Is it possible to add a client after a game is added, with NetworkLobbyManager?

2. Is it the right approach to achieve a multiplayer, non-lobby-based, non-host-based, online game in Unity?


texts: How do we generate overhangs with simplex noise 3d?

texts:
Now I use a simplex noise 2d function with x( voxel's x location ) and y(voxel's y location) to generate heightmap. How do we use simplex noise 3d to generate overhangs? What should the x y z inputs be?
Pseudo code would help a lot.


texts:
There are a lot of topics about this and it seems each one addresses a different problem, this topic does the same.

I was looking into tile collision detection and found this where David Gouveia explains a great way to get around the person's problem by separating the two axis. So I implemented the solution and it all worked perfectly from all the testes I through at it. Then I implemented more advanced platforming physics and the collision detection broke down. Unfortunately I have not been able to get it to work again which is where you guys come in :)!

I will present the code first:

    public void Update(GameTime gameTime) {
        if(Input.GetKeyDown(Keys.A)) {
            velocity.X -= moveAcceleration;
        }
        else if(Input.GetKeyDown(Keys.D)) {
            velocity.X += moveAcceleration;
        }

        if(Input.GetKeyDown(Keys.Space)) {
            if((onGround && isPressable) || (!onGround && airTime <= maxAirTime && isPressable)) {
                onGround = false;
                airTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
                velocity.Y = initialJumpVelocity * (1.0f - (float)Math.Pow(airTime / maxAirTime, Math.PI));
            }
        }
        else if(Input.GetKeyReleased(Keys.Space)) {
            isPressable = false;
        }

        if(onGround) {
            velocity.X *= groundDrag;
            velocity.Y = 0.0f;
        }
        else {
            velocity.X *= airDrag;
            velocity.Y += gravityAcceleration;
        }

        velocity.Y = MathHelper.Clamp(velocity.Y, -maxFallSpeed, maxFallSpeed);
        velocity.X = MathHelper.Clamp(velocity.X, -maxMoveSpeed, maxMoveSpeed);

        position += velocity * (float)gameTime.ElapsedGameTime.TotalSeconds;
        position = new Vector2((float)Math.Round(position.X), (float)Math.Round(position.Y));

        if(Math.Round(velocity.X) != 0.0f) {
            HandleCollisions2(Direction.Horizontal);
        }
        if(Math.Round(velocity.Y) != 0.0f) {
            HandleCollisions2(Direction.Vertical);
        }
    }

private void HandleCollisions2(Direction direction) {
    int topTile = (int)Math.Floor((float)Bounds.Top / Tile.PixelTileSize);
    int bottomTile = (int)Math.Ceiling((float)Bounds.Bottom / Tile.PixelTileSize) - 1;
    int leftTile = (int)Math.Floor((float)Bounds.Left / Tile.PixelTileSize);
    int rightTile = (int)Math.Ceiling((float)Bounds.Right / Tile.PixelTileSize) - 1;

    for(int x = leftTile; x <= rightTile; x++) {
        for(int y = topTile; y <= bottomTile; y++) {
            Rectangle tileBounds = new Rectangle(x * Tile.PixelTileSize, y * Tile.PixelTileSize, Tile.PixelTileSize, Tile.PixelTileSize);
            Vector2 depth;

            if(Tile.IsSolid(x, y) && Intersects(tileBounds, direction, out depth)) {
                if(direction == Direction.Horizontal) {
                    position.X += depth.X;
                }
                else {
                    onGround = true;
                    isPressable = true;
                    airTime = 0.0f;
                    position.Y += depth.Y;
                }
            }
        }
    }
}

From the code you can see when velocity.X is not equal to zero the HandleCollisions() Method is called along the horizontal axis and likewise for the vertical axis. When velocity.X is not equal to zero and velocity.Y is equal to zero it works fine. When velocity.Y is not equal to zero and velocity.X is equal to zero everything also works fine. However when both axis are not equal to zero that's when it doesn't work and I don't know why. I basically teleport to the left side of a tile when both axis are not equal to zero and there is a air block next to me.

Hopefully someone can see the problem with this because I sure don't as far as I'm aware nothing has even changed from what I'm doing to what the linked post's solution is doing.

Thanks.


texts: Change item rotation axis in inventory item visualization

texts:
I'm learning unity and i'm trying now make an inventory, i made a simple interface, and now i'm trying to make a item visualization. I look for some codes from web and i found this one:

using UnityEngine;

public class TurnObject : MonoBehaviour
{
    protected Vector3 posLastFame;
    public Camera UICam;

    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButtonDown(0)) {
            posLastFame = Input.mousePosition;
        }

        if (Input.GetMouseButton(0)) {
            var delta = Input.mousePosition - posLastFame;
            posLastFame = Input.mousePosition;

            var axis = Quaternion.AngleAxis(-90f, Vector3.forward) * delta;
            transform.rotation = Quaternion.AngleAxis(delta.magnitude * 0.1f, axis) * transform.rotation;
        }
    }
}

I know some code, but I'm not good with geometrics. In this code when I move my mouse horizontal way, my object turn in the Y axis. And that's good. But when I move my mouse vertical the object move in the X axis instead of Z axis.

Is there a way in this code for change this? I really have difficulty to understanding geometrics in Unity.


texts: How can I achieve a flickering torch/candle effect in 2D?

texts:
I'm currently working on a 2D lighting system that has point lights effectively rendered as a quad in a top-down 2D view, something like this for each light:

I'd like to achieve a somewhat realistic "flickering" effect by changing the position and attenuation of the light over time, simulating the light emitted from a torch or candle. What would be a good way to adjust these attributes of the light, and how quickly / over how much time?


texts:
I know some differences between Update() and FixedUpdate() and recently I have used both functions in one script. The code is working, but I have a question:

Does using both of these functions cause any problems? Is it safe to use them both?


texts: How to import or "using" a custom class in Unity script?

texts:
I have downloaded the JSONObject plugin for parsing JSON in Unity but when I use it in a script I get an error indicating JSONObject cannot be found. My question is how do I use a custom object class defined inside another class. I know I need a using directive to solve this but I am not sure of the path to these custom objects I have imported. They are in the root project folder inside JSONObject folder and class is called JSONObject.

Thanks


texts: Using gluUnProject to transform mouse position to world coordinates (LWJGL)?

texts:
I am programming on a LWJGL project and have been trying to figure out how to successfully use the GLU.gluUnProject function in order to transform a given point on the screen (mouse position) to world coordinates. I found several examples on Google and really tried hard to get it to work. I do manage to get a result vector but the values it gives me make no sense.
I initialize my scene using GL11.glFrustum(...) as follows:
public void initialize()
{
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glFrustum(-0.5, 0.5, -0.5, 0.5, 1.5, 6.5);
// left, right, bottom, top, zNear, zFar

GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();

GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL11.GL_REPLACE);
}

The window has a size of 800 x 600. Here is a screenshot:

Now to find a corresponding point in the game world for a given mouse position on the screen I use the following method:
public void calcWorldCoordinates(float mouseX, float mouseY)
// mouseX is in the range of [0..800] and mouseY in [0..600]
{
FloatBuffer model = BufferUtils.createFloatBuffer(16);
FloatBuffer projection = BufferUtils.createFloatBuffer(16);
IntBuffer viewport = BufferUtils.createIntBuffer(16);

GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, model);
GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, projection);
GL11.glGetInteger(GL11.GL_VIEWPORT, viewport);

float viewportHeight = viewport.get(3); // = 600.0f
float y = viewportHeight - mouseY;

FloatBuffer posNear = BufferUtils.createFloatBuffer(16);
FloatBuffer posFar = BufferUtils.createFloatBuffer(16);

GLU.gluUnProject(mouseX, y, -1.5f, model, projection, viewport, posNear);
GLU.gluUnProject(mouseX, y, -6.5f, model, projection, viewport, posFar);

// ...
}

For mouseX = 300, mouseY = 400 I receive:

posNear = [x=-0.0580, y=0.0774, z=-0.6964]
posFar = [x=-0.0208, y=0.0278, z=-0.6964]

None of the three resulting coordinates makes sense to me. As far as I can tell x should be somewhere around 240 (each tile in the scene is of size 120 x 80 pixels). It should definitely be positive though and not -0.0580 or -0.0208.
I also looked at the model and projection matrix as well as the viewport size. Those are:

model:
1.0,  0.0,    0.0,    0.0
0.0,  1.0,    0.0,    0.0
0.0,  0.0,    1.0,    0.0
0.0,  0.0,    0.0,    1.0

projection:
3.0,  0.0,     0.0,    0.0
0.0,  3.0,     0.0,    0.0
0.0,  0.0,    -1.6,   -1.0
0.0,  0.0,    -3.9,    0.0

viewport: 0, 0, 800, 600

I rewrote the code several times using different implementations of other people but could not get it to work. Maybe somebody could give me a hint. What I am doing wrong?


texts:
I am confused about pixels and meters in Box2D. I know that Box2D work only in mters so I need SCALING FACTOR. How big I need it? For example I want that from my mouse coordinates position X and Y for example(1527, 30) throw an Box2D object how I need to do that?
if my scaling factor is private final static float PPM = 1/100f; so my

  x = 152,7,
  y = 3meters

Here is my code

private void setBox2DFigures(){
        world = new World(new Vector2(0,-9.81f), true);
        rend = new Box2DDebugRenderer();
        cam = new OrthographicCamera(); // Camera
        body = new BodyDef();
        bodyPhysics = new FixtureDef();

        CircleShape c = new CircleShape();
        body.type = BodyType.DynamicBody;
        c = new CircleShape();
        c.setRadius(20*PPM);
        c.setPosition(new Vector2(Gdx.input.getX()*PPM, Gdx.input.getY()*PPM));
        bodyPhysics.shape = c;
        world.createBody(body).createFixture(bodyPhysics);
}

and here in a draw method I want to coin position set to my mouse position

public void draw(){
    c.setPosition(new Vector2(Gdx.input.getX()*PPM, Gdx.input.getY()*PPM)); // mouse coordinates * PPM
    rend.render(world, cam.combined);

}

But I don't see anything in my screen. Whats wrong? How I need to choose My scaling factor(PPM)?

here's my main

public class DesktopLauncher {
    public static void main (String[] arg) {
        LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();

        cfg.title = "Catch Me!";
        cfg.width = 1800; //1800
        cfg.height = 900; //900

        new LwjglApplication(new Game(), cfg);
    }
}


texts:
Problem: The spotlight I've set up with OpenGL won't light up anything behind it, no matter what values I set for GL_SPOT_DIRECTION

    float[] LightDir = new float[]{0,0,-1,0};
    float[] LightPos = new float[]{0,0,15f,1};

Initialization code for lighting

        glEnable(GL_LIGHTING);
        glEnable(GL_LIGHT0);
        glLightModel(GL_LIGHT_MODEL_AMBIENT,asFlippedFloatBuffer(new float[]{0.1f, 0.1f, 0.1f, 1f}));
        glLight(GL_LIGHT0,GL_DIFFUSE,asFlippedFloatBuffer(new float[]{0.5f, 0.5f, 0.5f, 1f}));
        glLight(GL_LIGHT0, GL_POSITION, asFlippedFloatBuffer(new float[]{0, 0, 0, 1}));
        glLightf(GL_LIGHT0,GL_SPOT_CUTOFF,60.0f);
        glLightf(GL_LIGHT0,GL_SPOT_EXPONENT,2.0f);

        glEnable(GL_COLOR_MATERIAL);
        glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
        glShadeModel(GL_SMOOTH);

Lighting code ran every loop

         glLight(GL_LIGHT0,GL_SPOT_DIRECTION,asFlippedFloatBuffer(LightDir));
         glLight(GL_LIGHT0,GL_POSITION,asFlippedFloatBuffer(LightPos));

The Following shows:

To try and change the direction I hit a key that does

LightDir[1]++;

The angle of the light goes up as expected, but seems to stop turning once it's pointed straight up. Which looks like

Which is the problem, it wont turn around.
Iv'e tried every possible value for LightDir in all it's values, but I cannot get it to illuminate the back pf the tube. I've even tried to transform to light around the scene with glRotate and glTranslate.
The light is supposed to function as a flashlight.
Is this something that would be potentially solved with Shaders?
Thanks in advance!

EDIT:

Anytime LightDir[2] goes above 0 the light goes dark.


texts: Force Reload VS soution Explorer when adding new c# Script via Unity3d?

texts:
When I create C# script (Create -> C# Script) via Unity3d  or delete it from Unity3d - Visual Studio shows me the warning window.

it's annoying.

Is there any way to force "ReloadAll" in solution Explorer without the window?


texts: Creating big scene and little size chasing camera

texts:
I would like to create a climb based game, so I need to have a big scene and a camera that cover only a little part of it and chase my player. This image explains easier what I want:

How can I do it? I'm trying to resize my camera size only, but I don't get the desired result.
Thank you.
s.


texts: Stopping Animations For Player In Java Using Slick2D

texts:
I have a problem with stopping animations for a player in Slick2D. I have tried many solutions to the problem and have looked up a couple of resources but I am still stumped by the fact that it is not working. Here's the code I have for my class:

public SpriteSheet playerSS = null;
protected InputHandler inputHandler;
public float playerX, playerY = 250f;
private Animation sprite, runningAnimationLEFT, runningAnimationRIGHT, runningAnimationUP, runningAnimationDOWN;
private int duration = 200;

public Game (int stateID) {

}

@Override
public int getID() {
    return Main.game; //GAMESTATE = 1
}

@Override
public void init(GameContainer gameContainer, StateBasedGame stateBasedGame) throws SlickException {
    playerSS = new SpriteSheet("res/player_sprite_sheet.png", 50, 75);

    // ANIMATIONS
    runningAnimationDOWN = new Animation();
    runningAnimationDOWN.setAutoUpdate(true);
    runningAnimationDOWN.addFrame(playerSS.getSprite(1, 0), duration);
    runningAnimationDOWN.addFrame(playerSS.getSprite(0, 0), duration);
    runningAnimationDOWN.addFrame(playerSS.getSprite(2, 0), duration);

    runningAnimationLEFT = new Animation();
    runningAnimationLEFT.setAutoUpdate(true);
    runningAnimationLEFT.addFrame(playerSS.getSprite(1, 1), duration);
    runningAnimationLEFT.addFrame(playerSS.getSprite(0, 1), duration);
    runningAnimationLEFT.addFrame(playerSS.getSprite(2, 1), duration);

    runningAnimationRIGHT = new Animation();
    runningAnimationRIGHT.setAutoUpdate(true);
    runningAnimationRIGHT.addFrame(playerSS.getSprite(1, 2), duration);
    runningAnimationRIGHT.addFrame(playerSS.getSprite(0, 2), duration);
    runningAnimationRIGHT.addFrame(playerSS.getSprite(2, 2), duration);

    runningAnimationUP = new Animation();
    runningAnimationUP.setAutoUpdate(true);
    runningAnimationUP.addFrame(playerSS.getSprite(1, 3), duration);
    runningAnimationUP.addFrame(playerSS.getSprite(0, 3), duration);
    runningAnimationUP.addFrame(playerSS.getSprite(2, 3), duration);

    sprite = runningAnimationDOWN;
}

@Override
public void update(GameContainer gameContainer, StateBasedGame stateBasedGame, int delta) throws SlickException {
    inputHandler.updateKeyboardRelay(gameContainer);
    if (inputHandler.keyUP) {
        sprite = runningAnimationUP;
        sprite.update(delta);
        playerY -= delta * 0.1f;
    } else {
        // Stopping Animation goes here.
    }
    if (inputHandler.keyDOWN) {
        sprite = runningAnimationDOWN;
        sprite.update(delta);
        playerY += delta * 0.1f;
    } else {
        // Stopping Animation goes here.

    }
    if (inputHandler.keyLEFT) {
        sprite = runningAnimationLEFT;
        sprite.update(delta);
        playerX -= delta * 0.1f;
    } else {
        // Stopping Animation goes here.

    }
    if (inputHandler.keyRIGHT) {
        sprite = runningAnimationRIGHT;
        sprite.update(delta);
        playerX += delta * 0.1f;
    } else {
        // Stopping Animation goes here.

    }
}

@Override
public void render(GameContainer gameContainer, StateBasedGame stateBasedGame, Graphics graphics) throws SlickException {
    sprite.draw(playerX, playerY);
}

How would I go about stopping the animation from playing over and over again once the movement key is lifted? i.e. If someone presses the 'W' key the player does an animation going upwards, but if the user stops using the 'W' key how would I make it so that the animation stops playing as well?


texts: How can I perform a masked erase in SDL2?

texts:
I'm trying to implement some shadow/lighting effects in my 2D-project, and I've concluded that if there is an easy way to perform a masked erase on an SDL_Texture, it would make the drawing operations quite cheap.

Let's say I have a texture of the part of the level where light is not meant to be rendered.
I also have a texture with my "light map"; I want to use this to just draw omni lights from my light sources.
Then I want to use the first image to 'subtract' the portions of the light map that are not to be rendered on the final scene.
Then I draw my "light map" texture on top of my scene, with additive blending enabled.

This sounds like a good theory in my head, but I can't see any functions in the SDL2 API that let me do masked erase from a texture.

Am I overlooking something?  Does anything like this exist?


texts: Turning a Unity Terrain into stepped stairs aspect

texts:
Having the following code; i'm trying to turn my terrain into a stepped/terraces like terrain:
But sadly it doesn't work; i'm pulling my hairs out here.
What dumb obvious thing am i missing ?

// terrainWidth = 256
// terrainHeight = 256f
// steps = 5
// heightmap = terrain.terrainData.GetHeights(0, 0, terrainWidth, terrainWidth);

public static float[,] Terrace(float[,] heightmap, float terrainHeight, int steps)
{
    // Gets the lowest point of the terrain (range from 0 to terrainHeight)
    float minHeight = GetMinMaxHeight(heightmap).x * terrainHeight;
    // Gets the highest point of the terrain (range from 0 to terrainHeight)
    float maxHeight = GetMinMaxHeight(heightmap).y * terrainHeight;
    float stepSize = maxHeight / steps;

    int mapSize = heightmap.GetLength(0);
    float[,] tmp = new float[mapSize, mapSize];

    UnityEngine.Debug.Log("Height " + terrainHeight);
    UnityEngine.Debug.Log("Min " + minHeight);
    UnityEngine.Debug.Log("Max " + maxHeight);
    UnityEngine.Debug.Log("StepSize " + stepSize);

    for (int y = 0; y < mapSize; y += 1)
    {
        for (int x = 0; x < mapSize; x += 1)
        {
            tmp[x, y] = Mathf.Floor(heightmap[x, y] / stepSize) * stepSize;

        }
    }
    return tmp;
}


texts:
I'm trying to make a mini quiz game, but I'm stuck. I'm showing questions, randomly, but the first question never comes up. Furthermore, when I set the size of the questionsNumberChoosen array to 10 and run the game, it crashes.

public struct Question
{
    public string questionText;
    public string[] answers;
    public int correctAnswerIndex;

    // .. we also construct the Question, directly providing all values.
}

public Text questionText;
public Button[] answerButtons;

private Question currentQuestion;
private Question[] questions = new Question[10];
private int[] questionNumbersChoosen = new int[9];
private int questionsFinished;

void Start ()
{
    questions [0] = new Question("1", new string[]{"A", "A", "A", "A", "A" }, 2);
    questions [1] = new Question("2", new string[]{"A", "A", "A", "A", "A" }, 0);
    questions [2] = new Question("3", new string[]{"A", "A", "A", "A", "A" }, 4);
    questions [3] = new Question("4", new string[]{"A", "A", "A", "A", "A" }, 0);
    questions [4] = new Question("5", new string[]{"A", "A", "A", "A", "A" }, 0);
    questions [5] = new Question("6", new string[]{"A", "A", "A", "A", "A" }, 2);
    questions [6] = new Question("7", new string[]{"A", "A", "A", "A", "A" }, 0);
    questions [7] = new Question("8", new string[]{"A", "A", "A", "A", "A" }, 4);
    questions [8] = new Question("9", new string[]{"A", "A", "A", "A", "A" }, 0);
    questions [9] = new Question("10", new string[]{"A", "A", "A", "A", "A" }, 0);

    setQuestionIndex ();
    assignQuestion (questionNumbersChoosen[0]);
}

void assignQuestion(int questionNum)
{
    currentQuestion = questions [questionNum];
    questionText.text = currentQuestion.questionText;
    for (int i=0; i < answerButtons.Length; i++)
        answerButtons[i].GetComponentInChildren<Text>().text
            = currentQuestion.answers [i];
}

public void checkAnswer(int buttonNum)
{
    if (buttonNum == currentQuestion.correctAnswerIndex)
        print ("Correct!");
    else
        print ("Incorrect!");

    if (questionsFinished < (questionNumbersChoosen.Length - 1))
        moveToNextQuestion ();
}

void setQuestionIndex()
{
    for (int i = 0; i < questionNumbersChoosen.Length; i++)
    {
        int questionNum = Random.Range (0, questions.Length);

        if (!isContain (questionNumbersChoosen, questionNum))
            questionNumbersChoosen [i] = questionNum;
        else
            i--;
    }

}

bool isContain (int[] num, int numbers)
{
    for (int i=0; i < num.Length; i++)
    {
        if (numbers == num [i])
            return true;
    }

    return false;
}

public void moveToNextQuestion()
{
    assignQuestion (questionNumbersChoosen
        [questionNumbersChoosen.Length -1 - questionsFinished++]);
}


texts: How can I tell if an object in a tile grid is surrounded?

texts:
I'm making a game which uses a 10x20 matrix to store the position of the objects.

I have a castle object, represented by a number in a matrix. It is randomly deployed in some cell of the matrix. I also have a wall object, represented by a different number, which the user will deploy into the matrix by clicking on cells. The idea is to surround the castle.

Basically it'll look like this:

0 0 0 0 0 0 0
0 1 1 1 1 1 0
0 1 0 0 2 1 0
0 1 1 0 0 1 0
0 0 1 0 0 1 0
0 1 1 1 1 1 0
0 0 0 0 0 0 0

(2 is the castle, and 1 is the wall.)

How can I tell if the castle is surrounded by walls?


texts:
I can't find any useful information on packing 4 values into a 32 bit float in HLSL.

Ideally, what I want to be able to do in HLSL is:

float4 values = ... // Some values where each component is between 0 and 1.
float packedValues = pack32R(values);
float4 values2 = unpack32R(packedValues);

I realize that there will be precision limitations, and performance tradeoffs between different precisions in different methods. I'm just wondering what ideas are out there.


texts:
I am using DOTween, and I want to create a tweener, store it, and re-use it in the future several times.

    Tweener playerMoveUpTweener = player.transform.DOLocalMove(new Vector3(0,100,0), 0.5f, true);
    playerMoveUpTweener.SetEase (Ease.Linear);
    playerMoveUpTweener.SetRelative (true);
    playerMoveUpTweener.SetRecyclable (true);
    playerMoveUpTweener.OnComplete(() => {
        // some stuff
    });

But, in the future, I can't seem to be able to use it:

playerMoveUpTweener.Play();

Won't work. Not even with Rewind() or Restart().

Is it actually possible to re-use this same tweener?


texts: How can I use web browser controls for non-browser game GUI?

texts:
I'm looking for a way to get a modern browser's level of customization and rendering quality in my c# monogame to avoid using roundabout/limited/buggy GUI toolkits and to get better fonts without having to use pre-generated bitmap spritesheets (unicode support).

Is there a way to, for example, render a behind-the-scenes browser page instance onto a texture and overlay it above everything to act as GUI, along with all or just basic events (click, key press, hover, drag'n'drop)?

I've already tried using WinForms, but it's slow and most importantly, doesn't offer easy addition of custom controls which I'd very much like to use in my game. Otherwise I'd have to reimplement the whole thing in c#, but I'd rather not reinvent any wheels. For example, long lists, spreadsheets, flow controls with titles and descriptions for every item is a typical job for css, but not for WinForms.

And for the font part I'd like to get all the effects, which WinForms doesn't provide, and using the xna content pipeline, they have to be pre-baked in the bitmap font, which makes it insane to try to do dynamic font effects.

I understand that such great functionality might come at a great processing cost, but I think it's really gonna be worth the precision and font quality.


texts: Irradiance Map ( Irradiance environment map)?

texts:
As irradiance map is generated for every possible normal for all the texels in environment map (as every texel act as a light source) so that we can look up irradiance map, based on normal of fragment to find out its resulting illumination.

When Irradiance map is generated, does it get generated for every object in the scene to capture all possible normal and then eventually combined in a single texture?
Is there any example code to create irradiance map and use it to light the scene?
Any one has an example of CG-shader for reading irradiance map?

Thanks


texts: Binding C++ and V8 Javascript from Google

texts:
The examples are quite challenging to grasp if you are still getting your head around other things, so the simplest example would be great.

Is there a simpler example?


texts:
I'm creating a simple tank game. No matter what I do, the turret keeps facing the target with it's side. I just can't figure out how to turn it 90 degrees in Y once so it faces it correctly. I've checked the pivot in Maya and it doesn't matter how I change it.

This is the code I use to calculate how to face the target:

void LookAt()
{

    var forwardA = transform.forward;
    var forwardB = (toLookAt.transform.position - transform.position);

    var angleA = Mathf.Atan2(forwardA.x, forwardA.z) * Mathf.Rad2Deg;
    var angleB = Mathf.Atan2(forwardB.x, forwardB.z) * Mathf.Rad2Deg;

    var angleDiff = Mathf.DeltaAngle(angleA, angleB);
    //print(angleDiff.ToString());
    if (angleDiff > 20) {
        //Rotate to
        transform.Rotate(new Vector3(0, (-turretSpeed * Time.deltaTime),0));
        //transform.rotation = new Quaternion(transform.rotation.x, transform.rotation.y + adjustment, transform.rotation.z, transform.rotation.w);

    }
    else if (angleDiff < 20) {
        transform.Rotate(new Vector3(0, (turretSpeed * Time.deltaTime),0));
        //transform.rotation = new Quaternion(transform.rotation.x, transform.rotation.y + adjustment, transform.rotation.z, transform.rotation.w);

    }
    else {

    }
}

I'm using Unity3d and would appreciate any help I can get!
Thanks!


texts: 2D deferred lighting calculations not working

texts:
I have the following code for my HLSL pixel shader. Modified from another post here on GameDev (Link), but I have a few problems with it:

// calculate UV and get texture and normal.
float2 UV = Input.position.xy / Input.ScreenSize.xy;
float4 DiffuseColor = ColorTexture.Sample( SampleType, UV );
float4 NormalColor = NormalTexture.Sample( SampleType, UV );
float4 normal = 2.0f * NormalColor - 1.0f;

// calculate distance.
float3 LightDir = LightPos - Input.position.xyz;
float distance = 1 - length( LightDir ) / LightRadius;

// calculate dot of normal and light direction.
float NdL = max( 0, dot( normal.xyz, LightDir ) );

// get final color.
float4 finalColor = ( DiffuseColor * ambientIntensity ) + DiffuseColor * distance * LightIntensity * LightColor * NdL;

return float4( finalColor.rgb, DiffuseColor.a );

ambientIntensity and LightIntensity are currently 1.0f to simplify things. LightRadius depends on the size of the geometry, but is in pixels. ~80 for testing. DiffuseColor is a texture resulting from applying self-illumination and darkening the base image. NormalColor is the normal map for the image.

This shader needs to run for every light on the screen, which isn't that many.

For my tests I use the images from the blog post here. It's a little old, but it is pretty much what I need to do, which I can't.

Now; I did enough testing to know that all input and cbuffer parameters are valid but the results I get are not what I hoped for.

Here are my problems:

Problem 1: My knowledge of math is limited and I don't understand exactly what the dot product does, why it is needed in the light calculation or why the distance is calculated as it is. Is there a resource online that would explain lighting in term of HLSL or at least in a way meant for a programmer and not using big equations meant for a mathematician? If I don't understand the basics, I'm afraid I wont be able to improve and I'll be stuck every time I need to add new features (ie: shadows), but I need to get this things running asap.
Problem 2: The results I have are not good. When I move the light around, I can actually see where the geometry cuts off, and it is as if the light does not trail off properly near the edges of the geometry. Are the calculations wrong?
Problem 3: I built a 2D shape editor that I use to design the shape of the lighting geometry, but I don't know how to edit the shaders or the geometry's UV to have the custom shapes (fans, circles, etc) shaded properly. The light I render is always shaded as if it was a circle.

I spent the last two weeks working on this and whenever I search on Google, I keep getting pages I have already visited, so I'm quite lost right now. Any suggestions would be highly appreciated.

My game is a tile-based 2D game, thought I would mention that.


texts: What technique can I use to animate interaction between tiny objects in a sim game?

texts:
In simulation games like Sim City and Factorio, there are numerous interaction between tiny objects that needs to be animated. e.g. random people walking on the sidewalk, then waits for a bus, then board the bus; tiny cars waiting in line for each other at the traffic junction; thousands of items on a convey belt and the robotic arm needs to wait for an item to arrive in front of it to pick it up; conveyor belt sections transferring items from one to another.

I expect the collision detection check for every tiny object independently will eat a lot of CPU; what technique can I use in such a game to avoid the heavy computation and make it look like it's realistic?


texts: LibGDX - Box2D, world, bodies and deltaTime

texts: Can somebody tell me how to correctly handle Box2D "deltaTime"? When I have non-Box2D objects it's sufficient to multiply velocity by deltaTime but what should I do when I use Box2D world and bodies? multiply for example linearVelocity by delta or timeStep?


texts: Unity 5.5 - Modify image of a button from an array of images via script - Logic Help

texts:
Right now i have this:

Is a placeholder for what i want to do. This blue circles are images in different buttons, i have a blue image circle for every letter. I have to display the correct letter image to create a word. For example: word: "DOG" and the word is created by the "D" "O" "G" images.

That is the logic i cannot get my head around.

How can I, via script, select which image to show depending on the word given?

IDEAS:

I have an array of (INDEX, "letter") in my GameController.CS. Maybe i can add a number to the different images name. Separeate the word in characters. Look the position of this character in the Letters[] and that number turn it into a string and find the image with that number in the name.

I really need help to figure this out.

Thanks in advance for any help.


texts: Matinee movement track on multiple actors

texts:
I have some different actors (all spheres) that i want to move along a path (circular) and they also need to roll when they are moving, so i tried this using matinees movement track and attached all spheres to one parent (the first sphere), but all the the other spheres move relative to the first one so if i rotate the childs will rotate on the axis of the parent and not around there own axis. and also they wont follow a path.

would this be possible using matinee? or what would be the best way to achieve this?

i thought of making a parent in the middle of the circular path and rotate around that axis but then the wont roll when moving, so maybe i should make a rolling animation separately. which will triggered when they move?

the spheres will not constantly move, what i want to make is sort of a 3d gallery where the focus is on one sphere and if you want to see the next one, roll that sphere toward you and the other one away towards the background.


texts:
Currently I am learning XNA and while playing around with some tutorials knowing what I am aiming for a game it made me think that the Sprite Class will be something very important and re-used a lot of times, not sure if I am mistaken or not with this thinking.

Bellow you can see the Sprite code I am using at the momment and I was wondering:

How a Sprite Class should be or what
functions in general it should have
or am I mistaken that the Sprite
Class will not be used by every
sprite in my game ?

For example, in my sprite I could hold all property of the sprite even if one property is not being used, let's say an object that does not move around so it would have no speed which I could simple have a property saying that speed is disabled.

So i guess my real question is:

How should I structure my Sprite
Class to have the best usage out of
it ?

If you have a sample code to show I would appreciate aswell not really necessary, just for reference (also it doesnt need to be in c#).

Hope my question is not too confusing.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace MyGameTest
{
    class Sprite
    {
        public string AssetName;

        public Rectangle Size;

        private float mScale = 1.0f;

        public Vector2 Position = new Vector2(0, 0);

        public Vector2 Speed = new Vector2(0, 0);

        private Texture2D mSpriteTexture;

        public float Scale
        {
            get { return mScale; }
            set
            {
                mScale = value;
                Size = new Rectangle(0, 0, (int)(mSpriteTexture.Width * Scale), (int)(mSpriteTexture.Height * Scale));
            }
        }

        public void LoadContent(ContentManager theContentManager, string theAssetName)
        {
            mSpriteTexture = theContentManager.Load<Texture2D>(theAssetName);
            AssetName = theAssetName;
            Size = new Rectangle(0, 0, (int)(mSpriteTexture.Width * Scale), (int)(mSpriteTexture.Height * Scale));
        }

        public void Draw(SpriteBatch theSpriteBatch)
        {
            theSpriteBatch.Draw(mSpriteTexture, Position,
                                new Rectangle(0, 0, mSpriteTexture.Width, mSpriteTexture.Height),
                                Color.White, 0.0f, Vector2.Zero, Scale, SpriteEffects.None, 0);
        }
    }
}


texts: Unity3D: How to convince the user of objects moving closer with layering?

texts:
I'm currently developing a Universe Simulator for Android. I had a question regarding layering. I have a list of 100k 3DPoints each represent a stars co-ordinates. I have decided to break the cameras frustum into a number of chunks.

Chunk[0]: This will be 3D space I will have any star inside here as this model.

Chunks[1-N]: The Chunk will be defined by 8 3DPoints which create that partition of the cameras frustum. These chunks will be rendered as 2D, any stars that appear will be represented as a single/multiple pixels.

How do I sell the illusion to the user that the star is smoothly growing bigger towards them? I hope to each an effect like this while keeping the workload to a minimal, I'm quite new to unity and I was wondering if anyone could point me towards the correct resources or has any insight! Cheers


texts: Apply force to a specific point on a rigid body

texts: In unity I have a rigid body object and would like to apply force to a specific point. For example say I had a cube, I want to hit just the top right corner so it spins as a result. One idea I had considered is spawn a small sphere and fire it at it, then destroy the sphere. But is there a way to just apply the force?


texts: Deferred lighting and projective texturing?

texts: Is posible to use this technique with deferred lighting?


texts:
I'm implementing simple Windows game. Here is my game loop, which I've written based on some tutorials found on the Web:
constexpr nanoseconds ms_per_update(500ms);
TimePoint current_time;
TimePoint start_time = Clock::now();
nanoseconds delta_time;
nanoseconds lag(0ms);

while (continueRunning) {

    while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);

        if (WM_QUIT == msg.message) {
            OutputDebugString(L"--- WM_QUIT (WndMain) ---\n");
            continueRunning = false;
        }
    }

    current_time = Clock::now();
    delta_time = duration_cast<std::chrono::nanoseconds>(current_time - start_time);
    start_time = current_time;
    lag += delta_time;

    while (lag >= ms_per_update) {
        Game::Update();
        lag -= ms_per_update;
    }

    Game::Render();
}

Here are my questions
What really the Update and Render methods should do? Am i right that Update should for e.g. run through all game entities just updating theirs coordinates while the Render should call Render method for every game object which will just draw it on the screen having the position set by Update?


texts: How can I implement online high score in LibGDX?

texts:
I found some posts that said to use Google Play Services.
What about other platforms? Is their some libgdx library that I can use to implement it in core section or do I need to write separate score implementation to each platform?


texts: Ericsson compression for normal and bump maps

texts:
how does ETC2 fares when compressing normal maps and bump/height maps?

Since we are talking about using an algorithm created for visual fidelity, applied to vector and numerical data ⃰ I'm quite sure that the answer is "horribly" and "quite bad" respectively, but since I didn't found much about the topic online, I would like to hear about your experience on the matter.

Thank you!

⃰ compressing a matrix using jpeg is the best comparison I might think of at the moment


texts: How to add scene after build and deployed in Unity?

texts: I want to be able to make new levels after build. I could use a map tool and script but I rather just add scene with all the resource packed with it. But what is the best practice forward?


texts: 2D Physics: What happens with torque when center of mass changes?

texts:
Novice programmer and explorer of simple 2D physics, here.

I have a simple 2D object made up of two rigid bodies connected at a fixed joint.

The two rigid objects can rotate freely about that fixed joint, causing the center of mass and moment of inertia of the whole object to change(but not adding extra energy to the system).

If my 2d object is rotating about it's center of mass, and then the center of mass changes (because one of its components rotates), what happens with the torque?

Since my torque was applied at the initial center of mass, and now the center of mass has changed, it would seem that I could not just preserve the torque for the new object orientation?

One possibility in my head is that some of that initial torque will be converted to linear velocity, but I can't visualize this in any consistent way.

So does the torque value remain the same when center of mass changes or does it need to be recalculated?

What key information am I missing here?

If there's a simple enough answer that could be expressed in some python or pseudo code (in terms of what to do with the torque), that would be appreciated.

EDIT:

I'll try to be more clear.  There's no friction there's no gravity, and no ability for either of these objects to collide with anything (they are in vacuum too).  The two components themselves are connected at a joint but they are effectively rigid (in the sense that torque force does not cause them to change their orientation to joint).  Linear velocity starts at nothing and we apply a  one time (impulse?) torque through the center of mass.  The whole object  rotates in the expected way when all of the sudden one of the components of the object changes its orientation(without adding any additional forces to whole object).  This changes the objects center of mass and moment of inertia. Since the only force applied to this object was torque, what happens in such a hypothetical situation? I'm mostly interested in how to apply the existing energy to the new orientation.  Does the object gain linear velocity and lose torque? If so how do i calculate that.

(I suppose if I were spinning in outer space and stuck out my arm, that might be along the same line?)


texts: Going from WPF to Unity3D, how to implement the MVVM-pattern?

texts:
I've been working with MVVM in WPF for a long time and I'm now trying out Unity3D for a GUI-driven application.

Can I work with view models and bind them to properties in GUI-components? I guess the attached script-instance would be the "data context"? But how do I for instance bind (two-way) a text-property in my script to the text-property of a GUIText?

If Unity3D doesnt support this out of the box, could I implement a "bindable GUIText" myself somehow?

I know there are a few GUI frameworks for Unity3D out there allready and some of them seem to "support" MVVM as well. But I havent been able to find out many details about this. For instance the "data binding" support in NGUI/NData seem to be only between view-components and not between view and viewmodel, which is what MVVM is all about.

UPDATE

Apparently, the guy behind Durandal and Caliburn.Micro is working on a binding-framework for Unity3D which looks very promising. I guess this answers my question basically.


texts:
I want to create multiplayer first person shooter . Now I want to create animation where the soldier is walking with rifle .

I have separated hands from the body of the model and I have dropped hands and rifle in the camera , but when I move the camera hands don`t move with camera but the rifle does .  Hands are controlled by the bone . How can I make the walk animation + camera movement together?


texts: Monogame - Screen transition with fading

texts:
I'm trying to create a fade logic with Monogame for my screen transitions. I've read tutorials online but I'd like to work with Premultiplied Alpha for the fading. I've seen people add 1x1 pixels black images to their content, scale it to the screen's width/height (depending on aspect ratio) and drawing it with the alpha value first decreasing, and then increasing (fade in, fade out). So I would like someone to give me an example code to work with, preferably, 2 methods: FadeIn() and FadeOut in something like a Transition class. I should be able to call these at the begging and at the end of my screen classes. Keep in mind that I'm using the following enum code for screen state management:

public enum gameStates
{
    splashScreen,
    engineScreen,
    titleScreen,
    optionsScreen,
    playScreen,
    gameOverScreen,
    creditsScreen,
}
private static gameStates currentGameState = gameStates.splashScreen;
public static gameStates CurrentGameState
{
    get { return currentGameState; }
    set { currentGameState = value; }
}
// And then switch(currentGameState) in Update() and Draw()

So maybe FadeIn() and FadeOut() should take an enum value as a parameter? So that when they are called, the value is passed and inside them the currentGameState is accessed through the property in Game1 and is changed. Would this be the correct approach? Thanks!


texts: What datatype to use for set of needs in a needs system in C#?

texts:
I am currently gaining experience in Unity by trying to make a basic Citysim.
Since its based on a really small town all my citizen are actual Agents rather than statistical calculations.

I am currently thinking about an Need System but I can't decide on a datatype.

Requirements for the Need System

All needs are regularly iterated over to decrease their Satisfaction level
Certain events trigger a function specific to each need: OnSeekNeed(), OnSatisfyNeed()
Different Actors have different needs: Drug addict has a need "Drugs"
It should be possible to add new generic needs or remove needs from each actor at runtime: Discovery of Internet AddGenericNeed(Citizen c, Need n, float satisfaction)
It should be able to add new needs to the game without changing other classes
The need needs to be comparable: A pizza shop satisfies NeedFood but not NeedSleep`

OLD QUESTION INCLUDING SOLUTION IDEAS - feel free to ignore

I am currently gaining experience in Unity by trying to make a basic Citysim.
Since its based on a really small town all my citizen are actual Agents rather than statistical calculations.

I am currently thinking about an Need System but I can't decide on a datatype.
Each Agent should have his own needs and an satisfaction value for each. Not all Agents have the same Needs, a child for example does not need romantic interactions. An addict will have special drug needs.

My first Idea was to make an own class for each need, allowing me to make more Needs for DLCs or

Parent Need

public abstract class Need
{
    public abstract void OnSeek();
    public abstract void OnFurfill();
    public abstract void OnNotFurfill();
    public abstract bool IsHidden();
    public abstract string GetName();
    //ect...
}

Each Character should then get needs assigned and on each update they will be looped through and the value (0-100) would be decreased by 0.25f.

But how should I arrange the Needs in the Character Class?

Option1 - Harcoded Array

Each Need has an assigned spot in an float Array.

con: Enabling or disabling Needs requires further overhead instead of just editing the set.
con: all Citizen need to have the same need-set
con: no Object orientation allowing to call special events 'OnSeek()'

Option2 - Dictinary<Need,satisfaction>:

I tough this would be the solution unfortunately it's impossible to iterate over it and change the value. If there was this with TypeOf Need as Key and an over writable value it would be perfect.

con: It's impossible to change the satisfaction without replacing the entire node
con: Apparently its not possible to use Types as Keys

private Dictionary<Type, float> n2 = new Dictionary<Type, float>();
private Dictionary<Need, float> n3 = new Dictionary<Need, float>();
//both don't seem to work

Option3 - LinkedList<Need>:

con: slow to find values when events change a need for all citizen 'needs.findByType(NeedRest)'
con: needs can be added twice. Checking for duplicates is expensive
con: Each need is a new Object for every Citizen containing the statisfaction float

So far I believe the Linked List will be my best bet, most of the time I will be looping through it anyway. I'll need to check for duplicates on insert but maybe somebody can help me get the Dictionary to work or knows a better solution.

Please keep in mind, I am new to C# and maybe I am missing something completely obvious... While trying to write this question I somehow managed to answer a lot of my problems and came up with something that will sort of work.
I'll be posting this anyway just in case somebody is stuck on the same problem or has a solution that is way better.


texts:
I successfully added my own font to the default .json file and it displays, however I get some weird sizing issues. Specifically when I try to create a Dialog. This is what it looks like: Ignore the fact that that says "and"As you can see, the title does not fit and the button seems a bit big... This is how I create the dialog:

Dialog d = new Dialog("Error", RBResources.gameSkin);
        d.add(new Label("You cannot continue and empty game.", RBResources.gameSkin));
        TextButton b = new TextButton("Ok", RBResources.gameSkin);
        d.button(b);
        d.show(this);

This is how the skin is initialized:

gameSkin = new Skin(Gdx.files.internal("skins/uiskin.json"));

All I did to add the font was create the font with Hiero, add it to directory with the .json, and change the BitmapFont file reference from "default.fnt" to "text.fnt" (text is what I called the font).

EDIT
I tried changing the font size to 32 (before it was 48) and this is what it gives me:

The title still exceeds the boundaries of the title box. Does that mean, in the .png file containing the different button states and other Drawables, that I have to manually adjust the window Drawable to fit the title or is this a bug?


texts: Integer ops only 3D triangle-triangle collision detection

texts:
I've a need for 3D triangle-triangle collision detection using integer math only. Unfortunately, I'm not in a position where I can use 64-bit integers (only 32-bit) and my vertex values can be larger than 24-bit values. This makes overflows a tricky problem -- otherwise I could probably just use fixed point operations.

The good news is I don't need perfect accuracy -- after all, we're using integers. Additionally, it does not need to be continuous collision detection -- the velocities will be zero. But I may have large triangles tested for collision with small triangles, so coarse approximations of normals can lead to gross relative errors.

The triangles themselves are represented as triplets of 32-bit integer vectors.

Is there a way of doing this?


texts: Why does duplicating my object cause its vertex animation shader to distort it?

texts:
I used a vertex shader (based on this example) to animate a flag waving. When I have a single flag in my scene, it works correctly.

When I duplicate the flag, all of the copies become wildly distorted after I hit play.

Here is the shader code I'm using:

Shader "Custom/Flag" {
    Properties {
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Speed ("Speed", Range(0, 5.0)) = 1
        _Frequency ("Frequency", Range(0, 1.3)) = 1
        _Amplitude ("Amplitude", Range(0, 5.0)) = 1
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        Cull off

        Pass {

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            sampler2D _MainTex;
            float4 _MainTex_ST;

            struct v2f {
                float4 pos : SV_POSITION;
                float2 uv : TEXCOORD0;
            };

            float _Speed;
            float _Frequency;
            float _Amplitude;

            v2f vert(appdata_base v)
            {
                v2f o;
                v.vertex.y +=  cos((v.vertex.x + _Time.y * _Speed) * _Frequency) * _Amplitude * (v.vertex.x - 5);
                o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
                o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                return tex2D(_MainTex, i.uv);
            }

            ENDCG

        }
    }
    FallBack "Diffuse"
}

How can I make this work with multiple flags using the same material?

Should I use a new material instance for each object like this? It doesn't seem optimal:

    material = new Material (Shader); // Create new material
    material.SetFloat ("_Speed", _Speed);
    material.SetFloat ("_Frequency", _Frequency);
    material.SetFloat ("_Amplitude", _Amplitude);
    material.SetTexture ("_MainTex", _MainTex);
    flagObj.GetComponent<MeshRenderer>().sharedMaterial = material; // Set values


texts: In Unity, how can I render borders of provinces from a colored province map in a grand strategy game?

texts:
I am kind of a beginner of Unity and I am trying do work on a grand strategy game. I already have a province map, colored by unique rgba for each province, looks like something below:

I know that the province map is kind of a look up map for province id. But when I obverse the paradox strategy games, I notice that they have render borders differently for the provinces and nations. For example, in the CK3, the Baron collars are separated with dotted lines, and the kingdoms are separated with enhanced yellow lines.

I thought they have some other maps or files containing those information, so I went to read their dev diary, and I find that all province shape information are stored in the province map.

So, my question is:

Is there any way in Unity3D to create those different borders with some shader and some province map such those given above?

I think what I wish to accomplish is something as this link:
Render border on 3D map

Which is:


texts: Formula for replicating glTexGen in OpenGL ES 2.0 GLSL

texts:
I also posted this on the main StackExchange, but this seems like a better place, but for give me for the double post if it shows up twice.

I have been trying for several hours to implement a GLSL replacement for glTexGen with GL_OBJECT_LINEAR. For OpenGL ES 2.0.  In Ogl GLSL there is the gl_TextureMatrix that makes this easier, but thats not available on OpenGL ES 2.0 / OpenGL ES Shader Language 1.0

Several sites have mentioned that this should be "easy" to do in a GLSL vert shader. But I just can not get it to work.

My hunch is that I'm not setting the planes up correctly, or I'm missing something in my understanding.

I've pored over the web. But most sites are talking about projected textures, I'm just looking to create UV's based on planar projection. The models are being built in Maya, have 50k polygons and the modeler is using planer mapping, but Maya will not export the UV's. So I'm trying to figure this out.

I've looked at the glTexGen manpage information:

g = p1xo + p2yo + p3zo + p4wo

What is g? Is g the value of s in the texture2d call?

I've looked at the site:

Mathematics of glTexGen

Another size explains the same function:

coord = P1*X + P2*Y + P3*Z + P4*W

I don't get how coord (a UV vec2 in my mind) is equal to the dot product (a scalar value)? Same problem I had before with "g".

What do I set the plane to be? In my opengl c++ 3.0 code, I set it to [0, 0, 1, 0] (basically unit z) and glTexGen works great.

I'm still missing something.

My vert shader looks basically like this:
WVPMatrix = World View Project Matrix.
POSITION is the model vertex position.

varying vec4 kOutBaseTCoord;
void main()
{
    gl_Position = WVPMatrix * vec4(POSITION, 1.0);

    vec4 sPlane = vec4(1.0, 0.0, 0.0, 0.0);
    vec4 tPlane = vec4(0.0, 1.0, 0.0, 0.0);
    vec4 rPlane = vec4(0.0, 0.0, 0.0, 0.0);
    vec4 qPlane = vec4(0.0, 0.0, 0.0, 0.0);

    kOutBaseTCoord.s = dot(vec4(POSITION, 1.0), sPlane);
    kOutBaseTCoord.t = dot(vec4(POSITION, 1.0), tPlane);
    //kOutBaseTCoord.r = dot(vec4(POSITION, 1.0), rPlane);
    //kOutBaseTCoord.q = dot(vec4(POSITION, 1.0), qPlane);
}

The frag shader

precision mediump float;
uniform sampler2D BaseSampler;
varying mediump vec4 kOutBaseTCoord;
void main()
{

    //gl_FragColor = vec4(kOutBaseTCoord.st, 0.0, 1.0);
    gl_FragColor = texture2D(BaseSampler, kOutBaseTCoord.st);
}

I've tried texture2DProj in frag shader

Here are some of the other links I've looked up

TexGen not working with GLSL, with fixed pipeline is ok


texts: How to make a simple escape the room game?

texts:
I want to make a very simple "escape the room" game.  I was hoping for something that looks something like this.  You would see images of some room and you click around to move or to add things to inventory.  Then, you can select something in your inventory to use that item with something on the screen.  During the whole game there would be a text box describing what is happening (probably in really broken English instead of Japanese).

I am looking for something that can be quite simple.  I would prefer to have the ability to play sound (probably mp3's) when something happens.  It can be web-based or a downloaded executable or .jar file.  It doesn't have to be perfect, just a proof-of-concept really.

What is the best approach to get this game working with minimal effort?  Are there some libraries that can help?  I have plenty of Java experience and some C++, PHP, and others.  I'd rather avoid Windows-based technology as I primarily run Linux.  I am willing to learn other languages if they have a huge advantage.

Ideally, if someone could point me to an example program that I can modify.  I'm not expecting to sell or distribute this game.


texts:
I want my game script to detect mouse clicks everywhere on my screen, except one corner where I have a pair of buttons to control the sound and will be handled separately. To help identify this corner, I've created a soundPanel object with the Rect Transform component (available in the Unity 4 Beta 17+) and have sized/positioned it appropriately in the editor in my UI layer.

In my game's script, I have passed in this corner object, and tried using it in the following way:

bool tap = (Input.GetMouseButtonDown(0) || Input.GetMouseButtonUp(0))
           && !soundPanel.rect.Contains(Input.mousePosition);

Clicking in the soundPanel still triggers a tap. I figured this is because the mouse position and soundPanel.Rect are not in the same coordinate space. Since the documentation on the new Unity Beta UI is a bit lacking / hard to find, I tried converting the mouse coordinates to everything I could:

if (Input.GetMouseButtonDown(0) || Input.GetMouseButtonUp(0))
{
    if (soundPanel.rect.Contains(Input.mousePosition)) { print("Raw"); }
    if (soundPanel.rect.Contains(camera.ScreenToViewportPoint(Input.mousePosition))) { print("ScreenToViewportPoint"); }
    if (soundPanel.rect.Contains(camera.ScreenToWorldPoint(Input.mousePosition))) { print("ScreenToWorldPoint"); }
    if (soundPanel.rect.Contains(camera.ViewportToScreenPoint(Input.mousePosition))) { print("ViewportToScreenPoint"); }
    if (soundPanel.rect.Contains(camera.ViewportToWorldPoint(Input.mousePosition))) { print("ViewportToWorldPoint"); }
    if (soundPanel.rect.Contains(camera.WorldToScreenPoint(Input.mousePosition))) { print("WorldToScreenPoint"); }
    if (soundPanel.rect.Contains(camera.WorldToViewportPoint(Input.mousePosition))) { print("WorldToViewportPoint"); }
    print("-------------------");
}

When I click with the above code, "ScreenToViewportPoint" and "ScreenToWorldPoint" print no matter where I click, and no others trigger. I suspect I need to transform the soundPanel somehow.

Here is the Hierarchy, Scene, and Inspector. The selected rect is the soundPanel, and it is in the bottom-right of the UI Canvas:


texts: Fill with Transparency in Built-In Sprite Editor

texts: When I imported an image for a sprite, I realized it had a white background. I went into the built-in sprite editor to remove it. I tried using fill as there was a transparent color in the color selector. It did not work. Is there a way to do this, or an easier way than erasing it all by hand?


texts:
I am wondering if its possible to dynamically change shaders while the code is running. In my game, I want to have a development mode in which users can change the shader source and dynamically see their changes like so:
https://www.youtube.com/watch?v=hlSG_iVC6xc
this is my current reload method:

//Shader is my shader class and shader is the current shader
//delete all resources of previous shader

if (shader->GetProgram() != 0)
    glDeleteProgram(shader->GetProgram());
if (inShader->GetVert() != 0)
    glDeleteShader(inShader->GetVert());
if (inShader->GetGeom() != 0)
    glDeleteShader(inShader->GetGeom());
if (inShader->GetFrag() != 0)
    glDeleteShader(inShader->GetFrag());

GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER);
GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
GLuint geometry_shader = glCreateShader(GL_GEOMETRY_SHADER);

//create vertex shader
glShaderSource(vertex_shader, 1, (const GLchar**)vertSource, NULL);
glCompileShader(vertex_shader);

//create fragment shader
glShaderSource(fragment_shader, 1, (const GLchar**)fragSource, NULL);
glCompileShader(fragment_shader);

GLuint program = glCreateProgram();

glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);

Shader* theResult = new Shader(context);
theResult->SetVertShader(vertex_shader);
theResult->SetFragShader(fragment_shader);
theResult->SetGeomShader(geometry_shader);
theResult->SetProgram(program);

//replace the shader we created with the old one
*shader = *theResult;
delete theResult;
return shader;

The above code does one of two things when called, it either gives some undefined graphical behaviour or doesn't seem to reload the shader and use the previous ones. Is there something I'm missing regarding how I'm linking the new shaders, or is this even the right approach?

As requested i will add the shader class information:

//shader.h

protected:
/// Shader properties
unsigned int m_VertexShader;
unsigned int m_GeometricShader;
unsigned int m_FragmentShader;
unsigned int m_Program;
OpenGL* mContext;

public:
/// Constructor
Shader(OpenGL* context);
~Shader();

/// Getter/setters shader properties
inline unsigned int GetVert() { return m_VertexShader; }
inline unsigned int GetGeom() { return m_GeometricShader; }
inline unsigned int GetFrag() { return m_FragmentShader; }
inline unsigned int GetProgram() { return m_Program; }
inline void SetVertShader(unsigned int inValue) { m_VertexShader = inValue; }
inline void SetGeomShader(unsigned int inValue) { m_GeometricShader = inValue; }
inline void SetFragShader(unsigned int inValue) { m_FragmentShader = inValue; }
inline void SetProgram(unsigned int inValue) { m_Program = inValue; }

//shader.cpp

Shader::Shader(OpenGL* context)
: m_VertexShader(0),
m_GeometricShader(0),
m_FragmentShader(0),
m_Program(0),
mContext(context)
{}

Shader::~Shader()
{
}


texts: How do I draw my particles when an enemy is killed?

texts:
I have enemies that move left and right.
I was wonder how I could make my particles show up when the enemy is killed?
Here is my particle class
    class explode:

        def __init__(self,x,y,height,width,color):
            self.x = x
            self.y = y
            self.height = height
            self.width = width
            self.explode = [
            pygame.image.load("spark_01.png"),
            pygame.image.load("spark_02.png"),
            pygame.image.load("spark_03.png"),
            pygame.image.load("spark_04.png"),
            pygame.image.load("spark_05.png"),
            pygame.image.load("spark_06.png"),
            pygame.image.load("spark_07.png")]

            self.explode = [pygame.transform.scale(image,(image.get_width()//7,image.get_height()//7)) for image in self.explode]

            self.rect = pygame.Rect(x,y,height,width)
            self.direction = "blobright"
            self.anim_index = 0
        def draw(self):

            self.rect.topleft = (self.x,self.y)
            if self.direction == "blobright":
                window.blit(self.explode[self.anim_index], self.rect)
                self.anim_index += 1
                if self.anim_index == len(self.explode):
                    self.anim_index = 0

    black = (0,0,0)
    explode1 = explode(400,450,50,50,black)
    explodes = [explode1]

This is where I delete my enemies when they are killed. How can I add my particles after it's deleted and remove the particles afterward?

        #--------------------------------------------------------------------------------------------------------- enemys

                # enemys 2
            for enemys in enemying:
                for bullet in bullets:
                    if bullet.rect.colliderect(enemys.hitbox):
                        if enemys.health > -4:
                            enemys.health -= 1
                            minusenemyhealthtext()
                            bullets.pop(bullets.index(bullet))
                        else:
                            enemyscore += 1
                            del enemying[one]
                            enemyors = font.render("" + str(enemyscore), True, (0,0,0))
                            enemydors.center = ((130,125))


texts:
I'm porting an FPS game to Android, and I have a question about the use of wake locks.

Should the client acquire a wake lock when it connects to a server to keep frames running at a proper rate when the player is AFK and the device is in sleep mode?

And should a wake lock be used if the game is running a listen or a dedicated server?


texts: How can I make the background of my game move following my player?

texts:
I'm starting with Libgdx and I would like to make my ParallaxBackground move following my player. I am using a TiledMap along with Scene2d, and have the camera follow the sprite of my player. I'm basing my ParallaxBackground on the example of the following link:

Link here

Best regards


texts: How can I `draw` something on a JavaFX WritableImage?

texts:
I'm migrating a project from Swing to JavaFX, and I have a problem. Since java.awt.BufferedImage provides getGraphics and it has lots of convenient methods (like drawLine, drawImage, etc.), I have some codes that uses these features.

But in JavaFX' WritableImage, I can't find any similar methods.
Did I miss something? Or should I use something else instead of WritableImage?


texts: Collision detection doesn't register until player sprite jumps

texts:
I have implemented a shooting mechanic into my game, and the act of shooting works fine. The shooting work is done in my "game1" class. The issue that arises is when I incorporate collision detection with the bullets and my enemies(zombies). For some reason, I can press shoot all day but none of the zombies will recognize the bullet. It isn't until I press jump with my sprite, that the bullets begin to register and kill the zombies. And jumping is the only way that I can get it to work, moving left or right doesn't do anything. I am going to post the relevant code below.

Zombie Collision code:

public void checkBulletCollision(List<Bullet> bullets)
{
   foreach (Bullet b in bullets)
   {
       if (BoundingBox.Intersects(b.BoundingBox))
       {
           isAlive = false;
           b.isVisible = false;
           bullets.Remove(b);
           break;
       }
   }
}

Shooting code in main game file:

public void UpdateBullets()
{
    foreach (Bullet b in bullets)
    {
        b.position.X += 10;
        if (b.position.X > 1020)
            b.isVisible = false;
    }
    for (int i = 0; i < bullets.Count; i++)
    {
        if (!bullets[i].isVisible)
        {
            bullets.RemoveAt(i);
            i--;
        }
    }
}

public void Shoot()
{
    Bullet newB = new Bullet(this);
    newB.LoadContent();
    newB.position = player1.position;
    newB.position.Y -= 10;
    newB.position.X += 10;
    newB.isVisible = true;
    if (bullets.Count < 1000)
        bullets.Add(newB);
}

Update code in main game file:

 protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        // TODO: Add your update logic here
        float deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
        controls.Update();
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        //update all blocks in array
        for (int i = 0; i < blocks.Length; i++)
        {
            blocks[i].Update();
        }

        //block1.Update();
        //block2.Update();
        //block3.Update();
        //CheckCollisions();
        player1.Update(controls, gameTime, blocks);

        foreach (Zombie z in zombies)
        {
            if (z.isAlive)
            {

                z.Update(gameTime, blocks);

                z.getPlayerPosition(player1);
                z.checkBulletCollision(bullets);
            }

        }
        if (Keyboard.GetState().IsKeyDown(Keys.Space) && pastKey.IsKeyUp(Keys.Space))
        {
            Shoot();

        }

        UpdateBullets();

        pastKey = Keyboard.GetState();

        base.Update(gameTime);
    }

What could be the reason for this?


texts: How can I write only to the stencil buffer in OpenGL ES 2.0?

texts:
I'd like to write to the stencil buffer without incurring the cost of my expensive shaders. As I understand it, I write to the stencil buffer as a 'side effect' of rendering something. In this first pass where I write to the stencil buffer, I don't want to write anything to the color or depth buffer, and I definitely don't want to run through my lighting equations in my shaders.

Do I need to create no-op shaders for this (and can I just discard fragments), or is there a better way to do this?

As the title says, I'm using OpenGL ES 2.0.

I haven't used the stencil buffer before, so if I seem to be misunderstanding something, feel free to be verbose.


texts: Which Type of Collision Detection should I use?

texts:
So over the past week I've been scratching my head over SAT (Separating Axis Theorem). I know how it works, but can't seem to get the C# code right. There's always one face or edge that's letting my player through an obstacle.

So I wanted to know if maybe I'm taking the hard way around, and I don't need SAT for what I want to achieve.

My Game Involves:
- 3D Cubes which will sometimes be on an angle (not a multiple of 90)
 - Not too many cubes (so I don't need my Collision Detection to be too inexpensive) - OBB collisions

So what is the best option for me collision-wise? If SAT is my go to option, what would it look like in C#?

EDIT

My Sat code:

var n1 = (bb1.BCK_TOP_LFTCorner - bb1.BCK_BTM_LFTCorner).Normalized();
var n2 = (bb1.BCK_BTM_LFTCorner - bb1.BCK_BTM_RGTCorner).Normalized();
var n3 = (bb1.FRT_BTM_LFTCorner - bb1.BCK_BTM_LFTCorner).Normalized();
var n4 = (bb2.BCK_TOP_LFTCorner - bb2.BCK_BTM_LFTCorner).Normalized();
var n5 = (bb2.BCK_BTM_LFTCorner - bb2.BCK_BTM_RGTCorner).Normalized();
var n6 = (bb2.FRT_BTM_LFTCorner - bb2.BCK_BTM_LFTCorner).Normalized();
var norms = new List<Vector3>() {
     new Vector3(-n1.X, n1.Y,n1.Z),
     new Vector3(n2.X, -n2.Y,n2.Z),
     new Vector3(n3.X, n3.Y,-n3.Z),
     new Vector3(-n4.X, n4.Y,n4.Z),
     new Vector3(n5.X, -n5.Y,n5.Z),
     new Vector3(n6.X, n6.Y,-n6.Z),
};
norms = bb2.Normals;
float max1 = 0;
float min1 = 0;
float max2 = 0;
float min2 = 0;
for (int a = 0; a < norms.Count; ++a)
{
    //Global.Min/Global.Max are simply Math.Min/Math.Max for an array of parameters
    max1 = Global.Max(Vector3.Dot(bb1.Corners[0], norms[a]),
            Vector3.Dot(bb1.Corners[1], norms[a]),
            Vector3.Dot(bb1.Corners[2], norms[a]),
            Vector3.Dot(bb1.Corners[3], norms[a]),
            Vector3.Dot(bb1.Corners[4], norms[a]),
            Vector3.Dot(bb1.Corners[5], norms[a]));
        min1 = Global.Min(Vector3.Dot(bb1.Corners[0], norms[a]),
            Vector3.Dot(bb1.Corners[1], norms[a]),
            Vector3.Dot(bb1.Corners[2], norms[a]),
            Vector3.Dot(bb1.Corners[3], norms[a]),
            Vector3.Dot(bb1.Corners[4], norms[a]),
            Vector3.Dot(bb1.Corners[5], norms[a]));
        max2 = Global.Max(Vector3.Dot(bb2.Corners[0], norms[a]),
            Vector3.Dot(bb2.Corners[1], norms[a]),
            Vector3.Dot(bb2.Corners[2], norms[a]),
            Vector3.Dot(bb2.Corners[3], norms[a]),
            Vector3.Dot(bb2.Corners[4], norms[a]),
            Vector3.Dot(bb2.Corners[5], norms[a]));
        min2 = Global.Min(Vector3.Dot(bb2.Corners[0], norms[a]),
            Vector3.Dot(bb2.Corners[1], norms[a]),
            Vector3.Dot(bb2.Corners[2], norms[a]),
            Vector3.Dot(bb2.Corners[3], norms[a]),
            Vector3.Dot(bb2.Corners[4], norms[a]),
            Vector3.Dot(bb2.Corners[5], norms[a]));

    }
if (max1 < min2)
    return Vector3.Zero;
    // Get nearest face normal to player so that we can add it to player's velocity.
    var rl = new List<Vector3>() {bb2.Front,
        bb2.Back,
        bb2.Top,
        bb2.Bottom,
        bb2.Left,
        bb2.Right };
    var r = rl.IndexOf(rl.OrderBy(c => c.Distance(bb1.Center)).First());
    var returnval = bb2.Normals[r];
    return returnval;


texts: How do I bring the console window back into the same Unity window?

texts:
I have this issue where somehow I accidentally got the console window separated from the window that all unity things are n, so it floats around, blocking the unity screen behind it, as shown below:

And I don't know how to fix it. I tried right clicking the projects tab but the option to add the console window wasn't there. I also tried dragging around the console window back into place but that didn't work. Whenever I restart this still happens, and even new projects have this issue, ever since I accidentally dragged the window out from the unity window shown behind it in the image I showed. There has to be a simple fix to this.


texts: Mobu: Motion Files Naming Scheme for Unity

texts:
When exporting takes as several fbx files in Motionbuilder 2014 with File > Motion File Export..., the files are named like so:

file_Take1.fbx
file_Take2.fbx
file_Take3.fbx

In order for the motion files to be loaded into Unity correctly, I have to rename them to:

file@Take1.fbx
file@Take2.fbx
file@Take3.fbx

Having to replace underscores with '@' is fine for small projects but can become time consuming when working with many takes in large projects.
Is there a way to change the default naming scheme in Motionbuilder, through preferences or python scripting, so that the default underscore is replaced with an '@'?


texts: Unity Lerping & Following Camera is too slow

texts:
I'm using this script to follow a game object in 2D :
public class CameraFollow : MonoBehaviour
{
    ...
    void LateUpdate(){
        Vector3 position = target_transform.position;
        float targetX = position.x;
        float targetY = position.y;
        targetX = Mathf.Lerp(transform.position.x, targetX, 1/m_DampTime * Time.deltaTime);
        targetY = Mathf.Lerp(transform.position.y, targetY, m_DampTime * Time.deltaTime);
        transform.position = new Vector3(targetX, targetY, initial_z);
    }
}

I've set damping time to 2.
But with this when the object's speed gets higher it can't follow anymore, it lags. Any suggestions or solutions ?
Here is the current situation :


texts:
I have a sf::RectangleShape in my code which is defined like this :

sf::RectangleShape shape_1;

And it's values are set like this :

shape_1.setFillColor(sf::Color::White);
shape_1.setPosition(10, 10);

But when I render it like this :

    window.draw(shape_1);

It wont display in my window.

My rendering part of the code looks like this :

    window.clear();

    window.draw(*box.getSfShape());
    window.draw(*box_static.getSfShape());
    window.draw(shape_1);

    window.display();

Not sure what I'm doing wrong. Have been going on for days thinking it was a position problem with a body but since this won't render either it can't be. :P


texts: Using an array of 3d points to construct point cloud or surface in OpenGL

texts:
I have an array of 3 dimensional point objects, I can manipulate the input into this array into any configuration I want, for example, it could be a vector of floating point numbers, a vector of ints, etc.
Anyway, I want to display this 3d point cloud using OpenGL.  How should I go about doing this? I know enough that I can create a 3d cube from structured inputs but how would I go about creating vertices from this unstructured input?  If I don't need to construct these vertices how would I go about simply displaying these points as a cloud?  Any suggestions or advice is welcome.


texts:
How would i move every sphere that gets spawned every 2 seconds ? Basically i want every sphere to follow the previous spawned sphere or even all N-1 spheres should follow the first spawned sphere along a predefined path and they should keep rolling as a train of spheres. I am lost when i try to imprint movement to each sphere.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Spawner : MonoBehaviour
{
    public GameObject[] prefabs;
    public List<GameObject> listBalls = new List<GameObject>();
    private GameObject x;
    public int timer = 0;
    private float movementSpeed = 5f;

    void Start()
    {
        createBall();
    }

    void Update()
    {
        if (Time.time - timer > 0.8f)
        {
            createBall();
            timer += 2;
        }
        listBalls[listBalls.Count-1].transform.position += new Vector3(0, 0, movementSpeed * Time.deltaTime);
    }

    void createBall()
    {
        x = prefabs[Random.Range(0, prefabs.Length)];
        Instantiate(x, x.transform.position, Quaternion.identity);
        listBalls.Add(x);
    }

    void moveBall(GameObject x, GameObject y)
    {
        x.transform.position += y.transform.position - new Vector3(0,0,-1);
    }
}

Loop added but movement staggered

        void Update()
    {
        if (Time.time - timer > 0.8f)
        {
            createBall();
            timer += 2;
        }
        foreach (GameObject item in listBalls)
        {
            item.transform.position += new Vector3(0, 0, movementSpeed * Time.deltaTime);
        }
    }

```


texts:
How can I simulate the gravity of a sphere instead of a plane?

For a naval warfare game, I wish to implement a surface that simulates a curved plane with horizon. The plane is rendered with water physics, which needs, along with all physical objects, avatars and projectiles, to respond to gravity as a focal point rather than a distributed surface.


texts: Best way to do buttons for an OpenGL ES iPhone game

texts: I'm making a simple 2d game in OpenGL ES and I want to add movement buttons to it. What's the best way of going about this? In previous projects I've simply added UIButtons to the view but I hear there are performance implications in doing so with OpenGL ES so I'm wondering what the possible alternatives are if so.


texts: Phaser.io with Socket.io - What should the Server calculate and what the Client?

texts:
I'm currently playing around with phasio.io and socket.io to create a really simple multiplayer.

For the beginning i created basic movement which is synched via socket.io. The clients are sending their positions to the server and the server broadcasts it to the other clients. This works fine, however I'm aware of the fact that every user could simply cheat by emiting wrong positions.

Exactly this is where I need some new ideas. I'd really like to use phaser because it is really helful with all the animations and rotations etc. However, I kinda know i should calculate movements etc. in the backend - not in the client.

But is there a way to use phaser.io on a node server to run a game instance which then calculates the positions? Or do I need to build my "own game engine" in the backend?

An basic example would be:
A player shots ( in a tank game for example ) towards another player. Using phaser only this would be very simple. But in a multiplayer i would now need to do the collision calculation on my own - right?

Any ideas ?


texts: Processing through multiple shaders (LWJGL/Java/OpenGL)

texts:
Very simple question: Is it possible to process a vbo through different shaders? If so, how? What I want is sth like this:

reflectionShader.bind(); //starts shader
reflectionShader.load(some_values); //loads uniform vars into shader
process(vbo); //"renders" vbo using bound shader
reflectionShader.unbind(); //stops shader
refractionShader.bind();
refractionShader.load(some_other_values);
process(vbo);
refractionShader.unbind();
render(vbo); //output to screen


texts:
Honestly I have never taken a trigonometry class, but I am trying to create a dual stick shooter in XNA, can someone please look at my code and look to see if there are things that can be fixed, The image facing is off? Why?

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace DualStickPC
{

    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            //set window size
            graphics.PreferredBackBufferWidth = 1280;
            graphics.PreferredBackBufferHeight = 720;
        }

        protected override void Initialize()
        {

            base.Initialize();
        }

        Texture2D mytexture;
        Texture2D curTexture;
        Vector2 sPos = Vector2.Zero;
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            mytexture = Content.Load<Texture2D>("Arrow");
            curTexture = Content.Load<Texture2D>("Cursor");
        }

        protected override void UnloadContent()
        {

        }

        protected override void Update(GameTime gameTime)
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Escape))
                this.Exit();

            sPos.X = GraphicsDevice.Viewport.Width/2;
            sPos.Y = GraphicsDevice.Viewport.Height/2;

            base.Update(gameTime);
        }
        protected override void Draw(GameTime gameTime)
        {
            int x2 = Mouse.GetState().X;
            int x1 = (int) sPos.X;
            int y2 = Mouse.GetState().Y;
            int y1 = (int) sPos.Y;
            float rotation = (float)Math.Atan2(Mouse.GetState().Y - sPos.Y + (int)mytexture.Height / 2, Mouse.GetState().X - sPos.X + (int)mytexture.Width / 2);
            float slope = 0;
            try
            {
                slope = (y2 - y1) / (x2 - x1);
            }
            catch
            {
                slope = 180;
            }
            double angle = 100 * Math.Tan(slope);
            float radians = MathHelper.ToRadians((float)angle);

            int msX = (int)(Mouse.GetState().X - sPos.X - mytexture.Width/2);
            int msY = (int)(Mouse.GetState().Y - sPos.Y - mytexture.Height / 2);

            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
            Vector2 mousePos = Vector2.Zero;
            mousePos.X = Mouse.GetState().X;
            mousePos.Y =Mouse.GetState().Y;
            spriteBatch.Draw(curTexture, mousePos,Color.White);
            spriteBatch.Draw(mytexture, new Rectangle((int)sPos.X, (int)sPos.Y, mytexture.Height, mytexture.Width), null, Color.White, (float) (rotation), new Vector2(mytexture.Width/2, mytexture.Height/2), SpriteEffects.None, 0);

            //Testing projectile
            spriteBatch.Draw(mytexture, new Rectangle((int)sPos.X + msX/2, (int)sPos.Y + msY/2, mytexture.Height, mytexture.Width), null, Color.White, 0, new Vector2(mytexture.Width / 2, mytexture.Height / 2), SpriteEffects.None, 0);

            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}


texts: What are 'physically-based' lighting/rendering/materials?

texts: What's the difference between physically based lighting, physically based rendering and physically based materials? How they are different from deferred and forward rendering? And physically based rendering is used in films and deferred rendering is used in games?


texts: Is it possible to simulate a pause in a game for a fake exhaustive task?

texts:
Having windows phone OS 7.1 and it is for better understanding the game pipeline.

Game.IsFixedTimeStep = true and TargetElapsedTime is 60

The idea was to start a new thread and use Thread.Sleep()

protected override void Update(GameTime gameTime)
{
    Sleep();

   base.Update(gameTime);
}

bool m_bSleepRunning;
void Sleep()
{
   m_bSleepRunning = true;
   new System.Threading.Thread(
     () =>
               {
                    Thread.Sleep(2000);
                    m_bSleepRunning =false;
               ;}
     ).Start();
   while(m_bSleepRunning)
   {
      //empty cycle
   }
}

While debug there is a pause for every update, but the property gameTime.ElapsedGameTime.TotalMilliseconds is not updated.


texts: I am new to game programming I currently am using unity's 2D power to remake an 2D game for sake of practice. So I am just little confuse about one thing, so far every enemy in my game was dumb(they move on predefined paths) but this enemy, alien-copter, flies and follow the player wherever the player goes. My question is should I implement any pathfinding algorithm? I had studied A* but I trying to figure out if A* is gonna be helpful in my envoirnment because player will be moving and the enemy have to keep on looking for shortest path. I tried to write code for this AI my code was working perfect when there were no obstacles but my game has obstacles so I want something efficient so what do you people think should I implement A* or any other algorithm or not?


texts: Now that Articles 17 & 11 have passed, what should indie developers do?

texts:
Since on the 26th of March 2019 the EU has voted in favor of Articles 17 (previously known as Article 13) and 11, what should an indie developer who is based in the EU do to setup a game and a website for the game s/he develops?

I'm taking into consideration the following:

The developer has a website for the game he publishes.
The developer also has an account system on the said website (required by the game for customizability and authentication).
The developer sells the game on his/her own website (for 100% profit).
The indie developer is funding the game entirely from his/her own money (no investors).
The game is fully customizable, i.e. all text, textures, sounds and models can be changed.
The marketing is handled only by the game developer. This also takes into consideration the platforms which are available in the EU when these Articles take effect.

I'm curious about this as I'm based in the EU and wish to create a game with a lot of user customizability (to the level that the game's assets are all replaced by custom ones), but I'm unsure of how Articles 17 (upload filter) and 11 (link tax) will affect me. I'm also concerned about how link tax will affect the website, and how marketing is supposed to be done on the EU internet.


texts:
I'm trying to implement pausing by following this tutorial. The tutorial recommends essentially this as the implementation:

if (!paused) {
    Simulate(gameTime);
}

How does this work? What does Simulate mean here?


texts: How can I implement collision detection for these tiles?

texts:
I am wondering how this would be possible, if at all.

In the image below:

The light brows tiles are ground, while the dark brown is background, so the player can pass over those tiles.

Here's the for loops that draws the level:

        float scale = 1f;

        for (row = 0; row < currentLevel.Rows; row++)
        {
            for (column = 0; column < currentLevel.Columns; column++)
            {
                Tile tile = (Tile)currentLevel.GetTile(row, column);
                if (tile == null) { continue; }

                Texture2D texture = tile.Texture;

                spriteBatch.Draw(texture, new Microsoft.Xna.Framework.Rectangle(
                    (int)(column * currentLevel.CellSize.X * scale),
                    (int)(row * currentLevel.CellSize.Y * scale),
                    (int)(currentLevel.CellSize.X * scale),
                    (int)(currentLevel.CellSize.Y * scale)), Microsoft.Xna.Framework.Color.White);
            }
        }

Here's what I have so far to determine where to create a Rectangle:

    Microsoft.Xna.Framework.Rectangle[,,,] groundBounds = new Microsoft.Xna.Framework.Rectangle[?, ?, ?, ?];

        int tileSize = 20;
        int screenSizeInTiles = 30;

        var tilePositions = new System.Drawing.Point[screenSizeInTiles, screenSizeInTiles];

        for (int x = 0; x < screenSizeInTiles; x++)
        {
            for (int y = 0; y < screenSizeInTiles; y++)
            {
                tilePositions[x, y] = new System.Drawing.Point(x * tileSize, y * tileSize);
                groundBounds[x, y, tileSize, tileSize] = new Microsoft.Xna.Framework.Rectangle(x, y, 20, 20);
            }
        }

First off, I'm not sure how to initialize the array groundBounds (I don't know how big to make it). Also, I'm not entirely sure how to go about adding information to groundBounds.

I want to add a Rectangle for each tile in the level. Preferably I'd only make a Rectangle for those tiles accessible by the player, and not background tiles, but that's for a different day.

FYI, the map was made with a freeware program called Realm Factory.


texts: What do you do when you are at an impasse in the design phase?

texts:
I own a small web dev shop, and in our down time, I plan on having my guys work on a game (I will be paying them anyway, right?). A few buddies and I started talking about this game, and have been going through the motions of talking/designing it out.

Only problem we are at an impasse, and can't seem to get passed it. The vote is at 50/50%. Compromising hasn't worked.

I have though about just making an executive decision since I am funding the development/design of the game, but I don't want to lose my friends support for the game, and their other opinions.

I don't know what to do.