texts:
I'm new to Nifty GUI, so I'm following a tutorial here for making popups. For now, I'm just trying to get a very basic "test" popup to show, but I get multiple errors and none of them make much sense. To show a popup, I believe it is necessary to first have a Nifty Screen already showing, which I do. So here is the ScreenController for the working Nifty Screen:

public class WorkingScreen extends AbstractAppState implements ScreenController {

//Main is my jme SimpleApplication
private Main app;
private Nifty nifty;
private Screen screen;

public WorkingScreen() {}

public void equip(String slotstr) {
    int slot = Integer.valueOf(slotstr);
    System.out.println("Equipping item in slot "+slot);
    //Here's where it STOPS working.
    app.getPlayer().registerPopupScreen(nifty);
    System.out.println("Registered new popup");
    Element ele = nifty.createPopup(app.getPlayer().POPUP);
    System.out.println("popup is " +ele);
    nifty.showPopup(nifty.getCurrentScreen(), ele.getId(), null);
}

@Override
public void initialize(AppStateManager stateManager, Application app) {
    super.initialize(stateManager, app);
    this.app = (Main)app;
}

@Override
public void update(float tpf) {
    /** jME update loop! */
}

public void bind(Nifty nifty, Screen screen) {
    this.nifty = nifty;
    this.screen = screen;
}

When I call equip(0) the system prints Equipping item in slot 0, then a lot of errors and none of the subsequent println()'s. Clearly it botches somewhere in Player.registerPopupScreen(Nifty nifty). Here's the method:

public final String POPUP = "Test Popup";
public void registerPopupScreen(Nifty nifty) {
    System.out.println("Attempting new popup");
    PopupBuilder b = new PopupBuilder(POPUP) {{
            childLayoutCenter();
            backgroundColor("#000a");

            panel(new PanelBuilder() {{
                id("List");
                childLayoutCenter();
                height(percentage(75));
                width(percentage(50));
                control(new ButtonBuilder("TestButton") {{
                    label("TestButton");
                    width("120px");
                    height("40px");
                    align(Align.Center);
                }});
            }});
    }};
    System.out.println("PopupBuilder success.");
    b.registerPopup(nifty);
    System.out.println("Registerpopup success.");
 }

Because that first println() doesn't show, it looks like this method isn't even called at all!

Edit

After removing all calls on the Player object, the popup works. It seems I'm not "allowed" to access the player from the ScreenController. Unfortunate, since I need information on the player for the popup. Is there a workaround?


texts: Away3D & Directional Light w/ Rotating Meshes

texts:
This is likely a stupid error but I can't seem to find what I've done wrong.

I've got a simple scene with 10 cylinders rotating at a default speed.

If I grab one of these cylinders I can rotate it in the opposite direction or at a greater speed.

I have a single directional light in the scene.

It would appear that the directional light is only calculated at initialization and not on further frames. The shadow created by the light rotates with the cylinder giving the impression that the light is rotating when it isn't.

Camera & Light Initialization

_view = new View3D();
addChild(_view);

_view.antiAlias = 4;
_view.backgroundColor = 0xFFFFFF;
_view.camera.z = -850;
_view.camera.y = 0;
_view.camera.x = 0;
_view.camera.lookAt(new Vector3D());

_view.camera.lens = new PerspectiveLens(15);
_view.mousePicker = PickingType.RAYCAST_BEST_HIT;

_light = new DirectionalLight();
_light.z = -850;
_light.direction = new Vector3D(1, 1, 1);
_light.color = 0xFFFFFF;
_light.ambient = 0.1;
_light.diffuse = 0.7;
_view.scene.addChild(_light);

Mesh and Material creation

var material:TextureMaterial = new TextureMaterial(createPow2Texture(sprite, _colors[i]) , true, false, true);
material.animateUVs = true;
material.lightPicker = _lightPicker;

cylinder = new Mesh(new CylinderGeometry(radius, radius, 13, 70, 1, true, true), material);
cylinder.subMeshes[0].scaleU = spriteWidth / sprite.width;
cylinder.y = y;
cylinder.mouseEnabled = true;
cylinder.pickingCollider = PickingColliderType.AS3_BEST_HIT;
cylinder.addEventListener(MouseEvent3D.MOUSE_OVER, onMouseOverMesh);
cylinder.addEventListener(MouseEvent3D.MOUSE_MOVE, onMouseOverMesh);
cylinder.addEventListener(MouseEvent3D.MOUSE_OUT, onMouseOutMesh);
_cylinders.push(cylinder);

Frame

private function onEnterFrame(event:Event):void
{
    for each (var mesh:Mesh in _cylinders)
    {
        if (mesh == _mouseOverMesh)
            continue;

        mesh.rotationY += 0.25;
    }
    _view.render();
}


texts: Tilting a game object left/right/forward/back with gyroscope, regardless of player's heading

texts:
I'm working on a mobile game in Unity and using the gyroscope to rotate an object along the x and y axes.

float x = Input.gyro.attitude.x;
float y = Input.gyro.attitude.y;

This code give me the rotation I want when pointed in a certain direction along the z-axis. I want the rotation to not depend on the z-axis. I want the rotation to act the same no matter what direction I'm pointed in the real-world.

Here is a 12 second clip of what I get using a mobile gyroscope when pointed at 1 or North on the z-axis:

I want the rotation to be the same no matter what direction I am pointed on the z-axis with the gyroscope. Is there some way to rotate the whole coordinate system?


texts: Repeating UVs wont convert to texture in maya

texts: I have designed a material in Maya which i want to convert to a texture jpg, however i have repeating the UV's on the material. When i convert the material to a jpg the repeating UV's wont convert across. Is there anyway i can get them too?


texts: How (update,set, apply) dynamically color on a model of a XNA project?

texts:
I encounter a problem for set a background color on my model instantiated. I can change the texture but not change color.
Is there a parameter for change the color ? Or change the opacity ? I am looking for a way to highlight a model.

thank you so much

Here is my code used:
Everything works except the two last line. I searched but can not find name parameter for color and opacity

//Does not work

effect.Parameters["Color"].SetValue(new Vector3(0,1,0));
effect.Parameters["Opacity"].SetValue(0.5f);

        void DrawModelHardwareInstancing(Model model, Matrix[] modelBones,
                                             Matrix[] instances, Matrix view, Matrix projection)
            {
                 .......

                foreach (ModelMesh mesh in model.Meshes)
                {
                    foreach (ModelMeshPart meshPart in mesh.MeshParts)
                    {
                        // Tell the GPU to read from both the model vertex buffer plus our instanceVertexBuffer.
                        Game.GraphicsDevice.SetVertexBuffers(
                            new VertexBufferBinding(meshPart.VertexBuffer, meshPart.VertexOffset, 0),
                            new VertexBufferBinding(instanceVertexBuffer, 0, 1)
                        );

                        Game.GraphicsDevice.Indices = meshPart.IndexBuffer;

                        // Set up the instance rendering effect.
                        Effect effect = meshPart.Effect;
                        //effect.CurrentTechnique = effect.Techniques["HardwareInstancing"];
                        effect.Parameters["World"].SetValue(modelBones[mesh.ParentBone.Index]);

                        //Work perfect
                        effect.Parameters["View"].SetValue(view);
                        effect.Parameters["Projection"].SetValue(projection);
                        effect.Parameters["Texture"].SetValue(textureInstancedModel);
                        /* ***************************** */
                        //Does not work
                        effect.Parameters["Color"].SetValue(new Vector3(0,1,0));
                        effect.Parameters["Opacity"].SetValue(0.5f);
                        /* ***************************** */

                        // Draw all the instance copies in a single call.
                        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                        {
                            pass.Apply();

                            Game.GraphicsDevice.DrawInstancedPrimitives(PrimitiveType.TriangleList, 0, 0,
                                                                   meshPart.NumVertices, meshPart.StartIndex,
                                                                   meshPart.PrimitiveCount, instances.Length);
                        }
                    }
               ........
}


texts: How can I quantify a drawn line's straightness?

texts:
I'm working on a game which requires players to draw a line from a point A(x1,y1) to the other point B(x2,y2) on the screen of an Android device.

I want to find how well that drawing fits to a straight line. For instance, a result of 90% would mean the drawing almost perfectly fits the line. If players draw a curved line from A to B, it should get a low score.

The end points are not known in advance. How can I do this?


texts: LibGDX Bomberman bomb arraylist iterator error

texts:
Here is the code of bomb:

private int x, y;
private Texture bTexture;
private boolean bomb_explode;

private Timer timer;
private TimerTask task;
private int timeLeft = 0;

private TileMap map;
public static List<Bomb> bombs = new ArrayList<Bomb>();

public Bomb(TileMap map, int x, int y) {
    this.map = map;
    this.x = x;
    this.y = y;
    bTexture = new Texture("bomb.png");
    bomb_explode = false;
    bombs.add(this);
    createTimer();
}

public void render(SpriteBatch batch, float delta) {
    batch.draw(bTexture, x * Settings.SCALED_TILE_SIZE, y * Settings.SCALED_TILE_SIZE,
        Settings.SCALED_TILE_SIZE, Settings.SCALED_TILE_SIZE);
    if(timeLeft > 1f) {
        bomb_explode = true;
    }
    if(bomb_explode) {
        for(int i = 0; i <= 1; i++) {
            if(x + i <= map.getWidth()) {
                batch.draw(new Texture("flame.png"),
                    ((x + i) * Settings.SCALED_TILE_SIZE), y * Settings.SCALED_TILE_SIZE,
                     Settings.SCALED_TILE_SIZE, Settings.SCALED_TILE_SIZE);
            }
            if(y + i <= map.getHeight()) {
                batch.draw(new Texture("flame.png"), x * Settings.SCALED_TILE_SIZE,
                   ((y + i) * Settings.SCALED_TILE_SIZE), Settings.SCALED_TILE_SIZE,
                   Settings.SCALED_TILE_SIZE);
            }
            if(x - i >= 0) {
                batch.draw(new Texture("flame.png"),
                    ((x - i) * Settings.SCALED_TILE_SIZE), y * Settings.SCALED_TILE_SIZE,
                    Settings.SCALED_TILE_SIZE, Settings.SCALED_TILE_SIZE);
            }
            if(y - i >= 0) {
                batch.draw(new Texture("flame.png"), x * Settings.SCALED_TILE_SIZE,
                ((y - i) * Settings.SCALED_TILE_SIZE), Settings.SCALED_TILE_SIZE,
                Settings.SCALED_TILE_SIZE);
            }
        }
    }

}

public void Boom() {
    bomb_explode = false;
    for(int i = 0; i <= 1; i++) {
        if(map.getTile(x, y).getPlayer() != null) {
            map.getTile(x, y).getPlayer().Die();
        }

        if(x + i <= map.getWidth() && map.getTile(x+i, y).getPlayer() != null) {
            map.getTile(x+i, y).getPlayer().Die();
        }

        if(x - i >= 0 && map.getTile(x-i, y).getPlayer() != null) {
            map.getTile(x-i, y).getPlayer().Die();
        }

        if(y + i <= map.getHeight() && map.getTile(x, y+i).getPlayer() != null) {
            map.getTile(x, y+i).getPlayer().Die();
        }

        if(y - i >= 0 && map.getTile(x, y-i).getPlayer() != null) {
            map.getTile(x, y-i).getPlayer().Die();
        }
    }
    bombs.remove(this);
}

public void createTimer() {
    timeLeft = 0;
    task = new TimerTask() {

        @Override
        public void run() {
            ++timeLeft;
            if(timeLeft > 3) {
                bomb_explode = true;
                Boom();
                clearTimer();
            }
        }
    };

    timer = new Timer();
    timer.schedule(task, 1, 500);
}

public void clearTimer() {
    timer.cancel();
    timer.purge();
    timer = null;
}

In the screen class, I'm rendering the bomb like this :

for(Bomb b : Bomb.bombs) {
    b.render(batch, delta);
}

Here is the error I'm getting:

  Exception in thread "LWJGL Application" java.util.ConcurrentModificationException
  at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
  at java.util.ArrayList$Itr.next(Unknown Source)
  at bomberman.screens.GameScreen.render(GameScreen.java:41)
  at com.badlogic.gdx.Game.render(Game.java:46)
  at bomberman.game.GameObject.render(GameObject.java:23)
  at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:225)
  at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:126)

How can I fix it?


texts: How to fix 'procedural skybox' visible horizon line on 'screen space camera' canvas?

texts:
I can see the horizon line through my screen space camera canvas.

Here are the steps to reproduce it for 2019.3.0f3:

create a new scene
create a new material for the Skybox

set shader to Skybox/Procedural
set Atmosphere Thickness to 4

open Window/Rendering/Lighting Settings

set Skybox Material to material created in step 2
click Auto Generate at bottom

in Hierarchy add a new UI/Panel

set canvas Render Mode to Screen Space - Camera
assign the main camera to Render Camera
set panel image color to non-transparent white

set main camera rotation to 15, 15, 15

The resulting artifacts:

The canvas has been disabled, for reference:

This problem starts appearing when atmosphere thickness is > 3, currently I need 4.

How can this be fixed, if at all ?


texts: How do I know my VRAM upload is ready to be used?

texts:
Previosuly in Direct3D 9 and 11, if I wanted to update a resource in a Default heap, for example, a Vertex Buffer, I would lock the memory of the buffer, copy the data to the returned pointer, and then unlock the buffer. It is my understanding that unlocking the buffer committed the data to VRAM, and I could be certain that the buffer would be ready to be used by any draw commands.

With Direct3D 12, we now have the concept of upload heaps, and instead of locking the buffer each time I want to modify it, I can just get a mapped pointer to the VRAM area with ID3DResource::Map(). This is pretty cool, because I understand that in most cases, the write is performed with write combining, so I don't have to wait until the entire data is committed to VRAM to keep on doing work on the CPU.

Now the question is, how can I ensure that when I execute a GPU command that references that memory, the memory is already committed, and the GPU can safely read it?


texts: how to naturally rotate a ball according to its velocity on a surface, a wall

texts:
I develop a game on cocos2d-x cpp. There is a ball sprite in my game. I move the ball on a surface(wall) via touch events but it can't naturally rotate according to its velocity.

if i use ballSprite->runAction(..) in update(float dt) method then it doesn't rotate.

i use following code:

void GameLayer::updateBall(float dt)
{
  float deltaRotateX = 360.0f * _ballVelocityX;
  _ballSprite->setRotation(90.0f- CC_RADIANS_TO_DEGREES(deltaRotateX));
}

But the ball doesn't naturally rotate. it discretely rotate.
it can't naturally rotate according to its velocity.

Thanks.


texts:
I have a method to calculate angle between two vectors, but it is giving wrong values.

here is the code  :

float Vector2_Dot(Vector2 a, Vector2 b)
{
    return a.x * b.x + a.y * b.y;
}

float Vector2_Cross(Vector2 a, Vector2 b)
{
    return a.x * b.y - a.y * b.x;
}

float Vector2_Angle(Vector2 a, Vector2 b)
{
    return atan2f(Vector2_Cross(a, b), Vector2_Dot(a, b));
}

As you can see in the image bellow the angle is slightly wrong.

I'm giving the two positions marked by a black cross.
is the code correct or Do I have a problema elsewhere?

Here's is where I do my transformation matrix calculation:

float Transform_GetLocalAngle(DeadTransform *transform)
{
    if (transform->parent != NULL)
        return transform->parent->angle - transform->angle;
    else
        return transform->angle;
}
void Transform_Update(DeadTransform *transform, GLfloat depth)
{
    float angle     = Transform_GetLocalAngle(transform);
    Vector2 position    = Transform_GetLocalPosition(transform);
    Vector2 scale       = Transform_GetLocalScale(transform);

    GLfloat data[16] = {(GLfloat)cosf(angle) * scale.x,     (GLfloat)(-sinf(angle)) * scale.y,  0.0f,   position.x / 1000,
                        (GLfloat)(sinf(angle)) * scale.x,   (GLfloat)cosf(angle) * scale.y,     0.0f,   position.y / 1000,
                        0.0f,                               0.0f,                               1.0f,   depth,
                        0.0f,                               0.0f,                               0,      1.0f};
    Matrix_SetData(transform->transformationMatrix, data);
}

This is where I create the road:

direction = Vector2_Subtract(*tile->top->transform->position, *tile->topLeft->transform->position);
            pos.x = tile->top->transform->position->x + direction.x / 2;
            pos.y = tile->top->transform->position->y - direction.y / 2;

            float angle = Vector2_Angle(*tile->top->transform->position, *tile->topLeft->transform->position);

            CreateConnection(application, pos.x, pos.y, angle);

void CreateConnection(struct Application *application, float x, float y, float angle)
{
    DeadGameObject *zone = GameObject_Create("Connection");
    zone->transform->position->x = x;
    zone->transform->position->y = y;
    zone->transform->angle = angle;
    zone->transform->scale->x = 64;
    zone->transform->scale->y = 6;
    DeadRenderer *renderer = Renderer_Create(Texture2D_Create("Images/Connection.png", GL_CLAMP, GL_LINEAR));
    Renderer_SetDepth(renderer, -2);
    GameObject_AddComponent(zone, renderer, Type_Renderer);

    Application_Instantiate(application, zone);
}


texts:
I am instantiating the prefabs time to time and I want them to be destroyed with in 2 to  seconds as well. But I am getting the error that says:

The object of type GameObject has been destroyed but you are still trying to access it

So, somewhere script to trying to access the prefab even after it has been destroyed so probably I need to relocate the the statement where I am destroying the prefab using destroy .

Here is my code:

void Update()
    {
        if (!spawning)
        {
            timer += Time.deltaTime;
        }
        time = Random.Range (20, 40);
        if (timer >= time)
        {
            StartCoroutine(Spawn());

        }
        }
    public IEnumerator Spawn()
    {
        spawning = true;
        timer = 0;
        initial = new Vector3 (Random.Range(rmin, rmax), -0.23f, Random.Range(r.renderer.bounds.min.z, (r.renderer.bounds.max.z + 20)));
        fuelprefab = (GameObject)Instantiate (fuelprefab, initial, Quaternion.identity);
        yield return new WaitForSeconds (Random.Range (1, 3));
        spawning = false;
        Destroy (fuelprefab, Random.Range(1,3));
    }
}

What change do I need to make so that it's not accessed after it hs been destroyed and the newly instantiated prefab is accessed?


texts:
I am doing procedural environment generation using Houdini and Unity. There are two main shader features I want:

Vertex-Color Height Blending - I currently have a shader for this which I purchased. It supports Diffuse/Normal/Metallic/Smoothness/Height/Ambient Occlusion and has the following "pragma" (I don't exactly know what this means but maybe it's useful info):
 // Physically based Standard lighting model, and enable shadows on all light types
 #pragma surface surf Standard fullforwardshadows

 #pragma target 4.0

Triplanar shader - Since the environment is procedurally generated, I don't want to do manual UV mapping. I have just been using automatic UVs so far and it doesn't look that great with the Vertex-Color shader. I do have a Triplanar shader that I downloaded but it doesn't support the Vertex-Color stuff.

I would love to find a way to shader combine these two functionalities. How can I support all those types of textures?


texts:
So I have a bunch of meshes, materials, etc and then all of a sudden the window needs to be torn down and then recreated (such as switching on fullscreen with GLFW) which means I will get a new OpenGL context and my old OpenGL data is invalid.

What is the best way to reload all my OpenGL assets - do I save all the mesh and material data in system RAM (which is quite a waste isn't it? if you do not recreate the window during the game, it does absolutely nothing for alot of RAM) -OR- do you map the filepaths to all assets, and then re-read from disk when you reload them? (could lead to alot of file i/o)

Or is there a better alternative? What is the best-practice here?


texts:
I have a Box2D project and I want to tween an kinematic body from position A, to position B. The tween function, got it from this blog:

function easeInOut(t , b, c, d ){
    if ( ( t /= d / 2 ) < 1){
        return c/2 * t * t * t * t + b;
    }
    return -c/2 * ( (t -= 2 ) * t * t * t - 2 ) + b;
}

where t is the current value, b the start, c the end and d the total amount of frames (in my case). I am using the method introduced by this lesson of todd's b2d tutorials to move the body by setting its linear Velocity

so here is relevant update code of the sprite:

if( moveData.current == moveData.total ){
        this._body.SetLinearVelocity( new b2Vec2() );
        return;
    }

    var t = easeNone( moveData.current, 0, 1, moveData.total );

    var step = moveData.length / moveData.total * t;

    var dir = moveData.direction.Copy();

    //this is the line that I think might be corrected
    dir.Multiply( t * moveData.length * fps /moveData.total ) ;

    var bodyPosition = this._body.GetWorldCenter();

    var idealPosition = bodyPosition.Copy();
        idealPosition.Add( dir );

    idealPosition.Subtract( bodyPosition.Copy() );

    moveData.current++;

    this._body.SetLinearVelocity( idealPosition );

moveData is an Object that holds the global values of the tween, namely:

current frame (int),
total frames (int),
the length of the total distance to travel (float)
the direction vector (targetposition - bodyposition) (b2Vec2) and
the start of the tween (bodyposition) (b2Vec2)

Goal is to tween the body based on a fixed amount of frames: in moveData.total frames.

The value of t is always between 0 and 1 and the only thing that is not working correctly is the resulting distance the body travels.

I need to calculate the multiplier for the direction vector. What am I missing to make it work??

Greetings philipp


texts: Efficiency - Cubemap or Raytraced reflection?

texts:
I'm an amateur in 3D game development. The thing I want to know is shading related.
For reflection purpose, which will be the efficient way? Either "Realtime render to Cubemap" or "Ray trace based" reflection? In which way I will get better frames per second and my gpu gets less tired? No matter which API I use (e.g. DirectX, GL, GL ES, Metal). And please note my question is out of any game engine.


texts: How can I get the texture file name for my polygon?

texts:
I have a problem with the FBX SDK. I read in the data for the vertex position and the UV coordinates. It works fine, but now I want to read for each polygon to which texture it belongs, so that I can have models with multiple textures. Can anyone tell me how I can get the texture file name for my polygon? My code to read in vertex position and uv coordinates is the following:

int i, j, lPolygonCount = pMesh->GetPolygonCount();
FbxVector4* lControlPoints = pMesh->GetControlPoints();

int vertexId = 0;
for (i = 0; i < lPolygonCount; i++)
{

    int lPolygonSize = pMesh->GetPolygonSize(i);

    for (j = 0; j < lPolygonSize; j++)
    {
        int lControlPointIndex = pMesh->GetPolygonVertex(i, j);
        FbxVector4 pos = lControlPoints[lControlPointIndex];
        current_model[vertex_index].x = pos.mData[0] - pivot_offset[0];
        current_model[vertex_index].y = pos.mData[1] - pivot_offset[1];
        current_model[vertex_index].z = pos.mData[2]- pivot_offset[2];

        FbxVector4 vertex_normal;
        pMesh->GetPolygonVertexNormal(i,j, vertex_normal);

        current_model[vertex_index].nx = vertex_normal.mData[0];
        current_model[vertex_index].ny = vertex_normal.mData[1];
        current_model[vertex_index].nz = vertex_normal.mData[2];

        //read in UV data
        FbxStringList lUVSetNameList;
        pMesh->GetUVSetNames(lUVSetNameList);

        //get lUVSetIndex-th uv set
        const char* lUVSetName = lUVSetNameList.GetStringAt(0);
        const FbxGeometryElementUV* lUVElement = pMesh->GetElementUV(lUVSetName);

        if(!lUVElement)
            continue;

            // only support mapping mode eByPolygonVertex and eByControlPoint
        if( lUVElement->GetMappingMode() != FbxGeometryElement::eByPolygonVertex &&
            lUVElement->GetMappingMode() != FbxGeometryElement::eByControlPoint )
            return;

        //index array, where holds the index referenced to the uv data
        const bool lUseIndex
            = lUVElement->GetReferenceMode() != FbxGeometryElement::eDirect;
        const int lIndexCount= (lUseIndex) ? lUVElement->GetIndexArray().GetCount() : 0;

        FbxVector2 lUVValue;

        //get the index of the current vertex in control points array
        int lPolyVertIndex = pMesh->GetPolygonVertex(i,j);

        //the UV index depends on the reference mode
        int lUVIndex = pMesh->GetTextureUVIndex(i, j);
        lUVValue = lUVElement->GetDirectArray().GetAt(lUVIndex);
        current_model[vertex_index].tu = (float)lUVValue.mData[0];
        current_model[vertex_index].tv = (float)lUVValue.mData[1];

        vertex_index ++;
        }

    }

    float v1[3], v2[3], v3[3];
    v1[0] = current_model[vertex_index - 3].x;
    v1[1] = current_model[vertex_index - 3].y;
    v1[2] = current_model[vertex_index - 3].z;

    v2[0] = current_model[vertex_index - 2].x;
    v2[1] = current_model[vertex_index - 2].y;
    v2[2] = current_model[vertex_index - 2].z;

    v3[0] = current_model[vertex_index - 1].x;
    v3[1] = current_model[vertex_index - 1].y;
    v3[2] = current_model[vertex_index - 1].z;

    collision_model->addTriangle(v1,v2,v3);


texts:
I want to set anisotropic filtering to my scene. I use SharpDX (DirectX 11) and C#.

How do i set up anisotropic filtering in my shader?

Currently i try that in the shader:

Texture2D tex;
sampler textureSampler = sampler_state
{
  Texture = (tex);
  MipFilter = Anisotropic;
  MagFilter = Anisotropic;
  MinFilter = Anisotropic;
  MaxAnisotropy = 16;
};

float4 PShader(float4 position : SV_POSITION, float4 color:COLOR, float2 tex0 : TEXCOORD0) : SV_TARGET
{
  float4 textureColor;
  textureColor = tex.Sample(textureSampler, tex0) * color;

  return textureColor;
}

I get my object, textured, but it is not filtered anisotropic. I can write everything in the Parameters, even invalid things and i don't get any errors. The result is the same, objects without applied anisotropic filtering.

Do i have to set that in the shader? Can i do that also with SamplerState? I tested that but i didn't get a result too.

Some steps what i have to set would be helpful.

Edit:

Here the current result. You can see the blurred planes of the cube in the middle:

As comparison the same scene in OpenGL with 16x anisotropic filtering. The planes of the cube are not blurred:

Second Edit:

Based on the idea, that in OpenGL the anisotropic filtering is a texture environment variable, maybe i have set some settings in the texture wrong?

Texture2D texture = (Texture2D)Texture2D.FromFile("Test.png");
ShaderResourceView tSRV = new ShaderResourceView(device, texture);
device.ImmediateContext.PixelShader.SetShaderResource(0, tSRV);


texts: How do I make an object look at an angle in a top-down persepective?

texts:
Given a top-down persepective and lets say I know the angle I want to look at, how do I make a gameobject look into that angle? I currently have code like this:

if (directionX != 0 && directionZ != 0)
{
    transform.rotation = Quaternion.LookRotation(new Vector3(directionX / 2, 0, directionZ / 2));
}
else if (directionX != 0 || directionZ != 0)
{
    transform.rotation = Quaternion.LookRotation(new Vector3(directionX, 0, directionZ));
}

which allows me to move look into 8-directions. I am now looking to make it so I can look in any angle and I've got the angle using:

var angle = Mathf.Atan2(directionZ, directionX) * Mathf.Rad2Deg;

but I don't know how to use it to make my object look into that angle.


texts:
I am a beginner in libgdx and I am coding a simple game. This game is like a word puzzle where each letter is a texture. Before loading the first level I need to load into memory 26 textures, one for each alphabet letter, and also an English dictionary stored in memory as a .txt file. The problem is that my dictionary needs to be processed and loaded into memory (complexity  Big-O is O(n) where n is around 200k). Where should I process it? Inside the asset manager class or in the class where it will actually be used?

Also, different levels may use the exact same textures so it would be great to load them in memory only once rather than disposing them every time a level ends. Is storing them in a static variable in the Assetmanager class a nice solution to this problem?


texts:
I've got a working OBJ loader that loads vertices, indices, texture coordinates, and normals. As of right now it doesn't process texture coordinates or normals but it stores them in arrays and creates a valid mesh with the vertices and indices.

Now I am trying to figure out how can I make the shader use the correct normal in the array for the current vertex if I can't setnormals() to my mesh. If I were to just use an index in my array of normals corresponding to the index in the vertices, how would I retrieve the current index the shader is processing? BTW: I am trying to write a blinn-phong shader technique.

Also when I create the input layout and I've added the semantic NORMAL to it, how would I list the multiple semantics in that single parameter? Would I just separate it with a space?

PS: If you need to see any code, just let me know.


texts: How do I find a component, deferring to the children or parent if there is none?

texts:
I'm trying to create a function in C# in Unity that will take a GameObject and a Component, and return an attached Component from the base, child, or parent elements.

If the target GameObject does not contain the requested Component, I wish to look to any children. If there are no children, or the children do not contain the requested Component, I wish to look to the parent.

How do I find a component, deferring to the the children or parent if there is none?


texts: Make movement speed relative to player character rotation in Unity?

texts:
I'm doing a strict topdown 2D game where the character looks at wherever the mouse is pointing (same perspective as GTA 2 or Darkwood) . I want to make movement speed for strafing and backing up slower than walking forward. I'm having a hard time figuring out how to do this using Angle() and understanding vector math.
Any help would be appreciated


texts:
I have a GameObject car like this:

MyCar

Body with mesh collider
Wheel Left  with wheel collider
Wheel Right with wheel collider
...   and so on

Where I have to put rigidbody ?

Thanks


texts: Brighter pixels around area (OpenGL ES 2)

texts:
I'm trying to achieve an effect like in the image bellow. Basically I will have a 2D texture and I want a small area around a point (let's call it "light source") to be slightly better lit (i.e. be brighter). The light source will never move from its original position nor will it seem to "pulse" like the light of a fire for example. All the other areas further away will have some default brightness.

From my understanding, this can be done using a light map, but I was wondering whether it was possible to come up with a formula in the fragment shader of the texture below that changed the brightness of my pixels so that it is very bright around a particular point and quickly faded to a default value for the pixels further away. I tried working with something like this:

precision mediump float;
uniform sampler2D u_Texture;

uniform vec3 u_LightPosition;
varying vec3 v_Position;
varying vec2 v_TexCoordinate;

void main() {
    float dist = length(v_Position - u_LightPosition);
    gl_FragColor = (1.0 / (c + b * dist + a * dist * dist) + 0.15) * texture2D(u_Texture, v_TexCoordinate);
}

where c, b and a are hardcoded and adjusted by myself. However I wasn't able to find any combination of c, b and a that achieved an effect like the one from the image, because the brightness doesn't fade away quickly enough and it's very gradual. I think that's expected behaviour from a quadratic expression anyway, so my approach is clearly wrong and it's not a matter of adjusting c, b and a. What should I try then?


texts: CCLayerColor gets black when pushed onto the current scene

texts:
In my cocos2d iphone project I have one major layer, the game layer. When the user presses the pause button the scene is paused and another scene is pushed onto it, the pause scene.

[[CCDirector sharedDirector] pushScene:[PauseLayer node]];

I realize the pause scene as a CCLayerColor. I want the layer to be transparent but I can't set both color and opacity. The layer is always black, although I can see my menu on it.

self = [super initWithColor:ccc4(255, 255, 255, 50)]

Any ideas?


texts: Input.GetKeyDown need to press button more than once to work

texts:
So in Unity3D I'm checking for Input.GetKeyDown(KeyCode.E) for stuff like pickups and opening doors. Sometimes it doesn't work the first time I press it and I must press the key E like 2-4 times, and then it works. What could be the possible reason for this to occur?

As a further note, Input.GetKeyDown() is being called from OnTriggerStay()


texts:
There is a part in my script where I need to make a raycast check from my gun's muzzle to the enemy. This enemy could be anywhere around player.

I found my ray is not connecting to the target position!

public Transform target, Bullet_position;

void Update {

  if (target != null)
  {
      RaycastHit hit;
      if (Physics.Raycast(Bullet_position.position, target.position, out hit, 500)
      {
          Debug.DrawRay(Bullet_position.position, target.position, Color.blue, 500);

          if (hit.collider.tag == "enemy")
          {
              print(" In range and I can see you! ");
          }
          else
          {
              print(" None! ");
          }
       }
    }
} // end update.


texts: Loading and unloading "chunks" of tiles in a 2d tile engine with 2d camera

texts:
I am making a 2d tile based game in C# and XNA 4.0. I am having trouble loading and unloading "chunks" of tiles(blocks). The whole world is randomly generated and is infinate on both axis. How would I go about loading and unloading chunks of tile data in the camera's view?

A pastebin to the pastebin links(I still have the 2 link cap):

http://pastebin.com/9PYr8cvC


texts: Are techniques from Warioware: D.I.Y actually useable in creating an actual game?

texts: In a game called Warioware: D.I.Y, it teaches you how to create minigames with certain forms of AI. Can I use the techniques shown in this game to actually develop an advanced game?


texts:
This is a simple sprite rock

and on my LibGDX game I would create a PolygonShape like the following image

Like you see, I need 22 vertices and Box2D doesn't allow me create a PolygonShape with not more than 8 vertices so I think a possible way is merge two or more Polygons, is it possible? or I may use something else like for example a ChainShape?


texts:
I was wondering, in Unity 3D, how I could do something with the Spot Light (Range/cone) as a trigger? Since it would be very interesting to be able to manipulate whats actually in sight of Light range/cone, and then trigger an event / method.

Example of the Spot Light (Range/cone)

Since i'm at a Game Jam right now, I don't have infinite time, so some help or atlest thoughts on this, would be very much appreciated.


texts: Camera stops moving forwards near World-Center

texts:
So basically this is a problem I've been having since forever. I implemented a Camera System, it works fine but somewhere around the center (0, 0, 0) of the world it doesn't work. Actually it works, but it always moves back at the position I was before. Like, if I'm at (1, 0, 0), walking forward will make me stay at (1, 0, 0), while moving backwards will not. The weird thing is that as said before it only happens there and if I'm moving forwards, backwards, left and right work perfectly!

That's how I do my Walking:

XMVECTOR D = XMVectorReplicate(d);
XMVECTOR L = XMLoadFloat3(&m_LookDirection);
XMVECTOR P = XMLoadFloat3(&m_Pos);
XMStoreFloat3(&m_Pos, XMVectorMultiplyAdd(D, L, P));

My Strafing (Left to Right) is basically the same thing.
I update my ViewMatrix like that:

XMVECTOR R = XMLoadFloat3(&m_Right);
XMVECTOR U = XMLoadFloat3(&m_Up);
XMVECTOR L = XMLoadFloat3(&m_Look);
XMVECTOR P = XMLoadFloat3(&m_Pos);
XMVECTOR WU = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

//Compute wuv vectors for camera space
XMVECTOR w = XMVector3Normalize(XMVectorSubtract(L, P));
XMVECTOR u = XMVector3Normalize(XMVector3Cross(WU, w));
XMVECTOR v = XMVector3Cross(w, u);

XMStoreFloat3(&m_LookDirection, w);
XMStoreFloat3(&m_Right, u);
XMStoreFloat3(&m_Up, v);

Then I fill in the ViewMatrix but that's unimportant.

Hope someone knows that basic mistake I'm doing!

Thanks


texts: How can I fix a GameObject along one axis only when it is part of another object in Unity?

texts: Hello I have an Object player and inside player, I have an object Boundary which is supposed to follow the player as he moves up or down only? (As the player moves right or left I don't want the boundary object to move. How can I do it?


texts: What algorithms exist for generating collision geometry from an image?

texts:
I am currently working on a game using SFML and Box2D. I am interested in generating collision geometry from the sprite data that I load into SFML. So, for example, an algorithm that would do this would take an image and find the edges (for example where the alpha area starts) and then generating a polygon that fits to those edges.

Can I be pointed to any resources that describe an algorithm to do this?


texts: How can I turn a Unity game into an MRAID-compliant playable ad?

texts:
I need to create a mini-game, one really simple scene, and export it as a playable that comply with the MRAID requirements.
Basically, I can export a WebGL.
The question is which adaptations the code needs to have (if any) in order to become compatible with MRAID.
I saw the Luna tool that claims to solve this issue and export the scene on its own engine, to avoid any future adaptations, but honestly, I don't really understand what they're doing differently, if their engine still converts to JS and HTML5.
It seems really blurry at the moment and I can't find concrete, coherent answers.
All I'm getting from the company that approached my to get it done is "it needs to be MRAID compatible".
Does anyone have any experience and can shed some light on this subject?
Thanks in advance,
Omer


texts: I am very new to Game Development and I am making a game with a simple Ragdoll which has a body, a head, and 2 limbs(hands). The head and the limbs are hinged to the body and I have kept the Ragdoll above a cube to be used as the ground on which the Ragdoll falls. Till now, I haven't added any scripts for movement or anything, I just want my Ragdoll to fall on the cube below it properly. But when I click play, the Ragdoll just starts to float above its original position. When I move it through the editor away from the cube(ground), it does fall down. It's like the cube is opposing the downward acceleration of the Ragdoll. The Ragdoll won't land on the cube. All the bodies have Rigid body and collider scripts. The Ragdoll also doesn't disassemble, it manages to keep itself together. Can someone please tell me what I am doing wrong. I researched about this but I have found no solution. I am using the free version of Unity.


texts:
I am implementing a game where the player is playing(sliding) the little red rectangle and the purpose is to not hit the black rectangles and to not move out of the inner blue rectangle. The black rectangles are moving in trajectories from left to right(right to left) and from top to bottom(bottom to top). The speed they are moving with is constant e.g. 5 pixels. You can get a better idea in this video.

One of the game modes is the following - 2 paths will be proposed by the game displayed as arrows and one of them may lead to "death", while the other will always be the right one and the user will have to choose one of them until he makes the wrong choice. The movement directions can only be top,bottom,left or right and not diagonal and the speed of the red rectangle is constant e.g. 6 pixels and the black rectangles speed is 5 pixels.
I am struggling with the algorithm for the "successful" direction for more than a week and what I have done so far is the following :

Generate a random float number between 1.0 and 2.0 seconds and then divide the generated number by 0.030 for example to get the number of moves that will be made by the black rectangles and red rectangles.
Calculate the black rectangles and red rectangle move points that will be made for the following time session by multiplying the number of moves by the speed which is 5px for the black rectangles and 6px for the red rectangle.
After I know the speed of the black rectangles and the number of moves I can tell their position in any time of the current time session.
Move the red rectangle to the left until it is being hit and remember that result e.g. 15 moves until hit. Do the same thing for right,up,down direction.
Sort the direction by the moves that can be made before hit in ascending order.
Move the red rectangle in the direction in which the most number of moves can be made.
Do the same thing until the time session ends i.e. the random float number generated in the first step.
This solution works most of the time, but some times it leads to a position where an escape is not possible. The problem is not in the code, but in the algorithm logic.
For example look at the following image :

As you can see the red rectangle will go to a position where it will be stuck by two of the black rectangles. The best possible solution in this situation would be to move to top 1 time and then to left and after that to top, because the black rectangle in the top left corner is going to top, but I really have no idea how to solve this task. What would be the optimal way to accomplish this task.
Thank you in advance!


texts:
I'm learning to build html5 games for mobile. I'm worried about the FPS animation on older model Android... as I use a lot of setTimeouts to update certain aspects and would like some suggestions on other approaches I could adopt.

Any advice on making this run a bit smoother?


texts: How to make your own 2D AABB collision system in unity?

texts: I can't use the built in unity 2d physics engine for my game, so I tried to make my own using the unity bounds.Intersects, that is working perfectly but my problem is that I don't know how to make the player stop when It collides. Ive tried multiple things like storing the players last position and "teleporting" it back to that position when it collides (That looks choppy). Ive also tried to invert the controls when your colliding (So like W makes the player go down, A makes it go right ect) but that is extremely buggy. How should I do it?


texts:
Does anyone know if it's possible to setup a multiplayer game using libgdx in Android Studio?

I've been trying to convert my game to multiplayer using all kinds of tutorials on libgdx & multiplayer but I'm guessing it's just not possible with android Studio. Seems it's only possible to add leaderboard and achievements?

If someone managed to get multiplayer working with libgdx in Android Studio please let me know. And perhaps explain how to get it working?

If someone knows it's impossible please let me know as well.

If impossible, is it worth trying eclipse? Since it's not supported by Google anymore...???

Thnx in advanced


texts:
I want to create a free cam with the lookAt matrix in OpenGL. I just made the control with W, A, S and D so you can move around. But now I nee to look around. I thought doing that with sine and cosine on the target of lookAt, and it's partially working. But the problem is the input. I just don't know how to use the mouse coordinates(btw the mouse is fixed) to move the target or how to prepare the coordinates for sine and cosine.

Is there any example of what I'm looking for?


texts:
I'm in a bit of crunch time and I find myself spending way too much time tinkering with an algo, so I would like some help.

In the game I am working on, there are some old-style, pixelated minigames. One of the minigame is a spaceship in a cavern. The caverns curves and narrows down over time until the ship crashes in a wall. I want them to be generated at random during runtime.

I'm having a problem creating the walls of the cavern and narrowing them while keeping a smooth curve on them.

For the narrowing, I keep track of it with a variable that decreases over time, but how about the curving and how to keep it natural? I've though of a keeping a target point that goes up and down randomly and have the wall try to reach for it, therefore smoothing the randomized number but it is not working great.

Any ideas/algo?


texts:
I'm porting an iPhone game to the iPad.  When I move textures "quickly" (5.0 pixels every update at a rate of 60 Hz) I start to see little "artifacts" or remnants of where the texture used to be.  I'm not sure if I know the correct terminology for this... imagine a texture at some location on the screen... then next to it is the same texture but faded a bit... then the same texture again just faded a bit more.

I'm using CADisplayLink to drive my update loop if that helps.  Also I didn't see this issue on the 3G or the iPhone 4.  Any ideas?

Cheers!


texts:
I'm trying to do a tech tree GUI for my game, but i have limited width and the tree has alot of branches, the problem is if I make them small to fit the width, the tech tree is too small to read.

For example the AOE one is very large (in width):

I could allow scroll bar but as its web based, scrolls are quite ugly. So i was wondering how to deal with branches which slowly cause the tech tree to get wider as you go down the tech tree and how you would fit such a design in a limited space.

Are there different known designs for tech trees that any one knows of so i can look at their types. I don't know the names given to the types of tech tree layouts. But am hoping to find one that is not overly complex for the user aswell.


texts: What are the maths behind 'Raiden 2' purple laser?

texts:
The path of the laser is affected by user input and enemies present on the screen.
Here is a video, at 5:00 minutes the laser in question is shown : Raiden II (PS) - 1 Loop Clear - Part 2

UPDATE

Here is a test using Inkscape, ship is at bottom, the first 4 enemies are targeted by the plasma.
There seems to be a sort of pattern. I moved the ship first, then the handle from it to form a 45° angle, then while trying to fit the curve I found a pattern of parallel  handles and continued so until I reached the last enemy.

Update, 5/26/2012 : I started an XNA project using beziers, there is still some work needed, will update the question next week. Stay tuned !

Update : 5/30/2012 : It really seems that they are using Bézier curves, I think I will be able to replicate/imitate a plasma of such grade. There are two new topics I discovered since last time : Arc length, Runge's phenomenon, first one should help in having a linear movement possible over a Bézier curve, second should help in optimizing the number of vertices. Next time I will put a video so you can see the progress 8-)


texts: How do I implement a JavaScript interpreter into a C# game?

texts:
I'm trying to create a hacking game where players design programs and hack other people's stuff. Users write their programs in JavaScript. I'm aiming for a hackmud-style system, where user programs can interact with the host game, for example, transferring funds.

Trouble is, I don't know where to start. I'm using C# to develop my game. Everything I found online for using JavaScript in C# interprets the script as a program on the host computer. This is a problem because I don't want the user code to have access to the host computer, just the game. Is there a standard architecture for a project like this?


texts: What makes MMOs with real-money economies legal?

texts:
I beieve most MMOs with an in-game currency tied to a real-world currency (e.g. Guild Wars 2's gems or Eve's PLEX) do not allow in-game items to be traded back into real cash for a bunch of reasons—partly because they may be subject to changes to the game's "normal" economy but generally because this would open up a bunch of legal issues with money laundering, gaming/gambling laws and so on.

However, Entropia Universe (wikipedia link) has an in-game economy which is tied directly to US dollars, allowing players to "cash out" of the game and back into real money. They have even gone so far as to produce bank cards which withdraw from the game and have now formed an actual bank to regulate trades.

Why are there not more games which take this approach of a game economy tied directly to real money?

I understand that the economy needs to be carefully designed and balanced to avoid in-game over-inflation or other exploits leading to in-game currency being "created" from nothing, but the bigger concern seems to me to be the legal issues this would create. Given the amount of random chance involved in the game, is this not effectively gambling? If so, how does Entropia Universe allow worldwide users without kicking up a storm of trouble from different regional authorities and governments? Surely this is exactly the kind of thing which is banned in certain US states or other countries. Is it because the game is based in Sweden and their more permissive laws allow it?


texts: How do i get a list of all joysticks connected to my pc in usb using sharpdx with c# ? Getting errors

texts:
The code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using SharpDX;
using SharpDX.DirectInput;

namespace Ps4_Controller
{
    public partial class Form1 : Form
    {
        DirectInput input = new DirectInput();
        Joystick stick;

        public Form1()
        {
            InitializeComponent();

            List<Joystick> sticks = new List<Joystick>();

            foreach (DeviceInstance device in input.GetDevices
                (DeviceClass.GameControl,DeviceEnumerationFlags.AttachedOnly))
            {
                stick = new Joystick(input, device.InstanceGuid);
                stick.Acquire();

                  foreach (DeviceObjectInstance deviceObject in stick.GetObjects())
                    {
                        if ((deviceObject.ObjectType & ObjectDeviceType.Axis) != 0)
                        {
                            stick.GetObjectPropertiesById(deviceObject.ObjectType).SetRange(-100, 100);
                        }
                    }
                    sticks.Add(stick);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
}

I'm getting error on the line:

if ((deviceObject.ObjectType & ObjectDeviceType.Axis) != 0)

Severity    Code    Description Project File    Line    Suppression State
Error   CS0103  The name 'ObjectDeviceType' does not exist in the current

And on the line:

stick.GetObjectPropertiesById(deviceObject.ObjectType).SetRange(-100, 100);

Severity    Code    Description Project File    Line    Suppression State
Error   CS1503  Argument 1: cannot convert from 'System.Guid' to 'SharpDX.DirectInput.DeviceObjectId'


texts: How to change player objects when switching scenes?

texts:
I have a scene for lobby. When player connects to server he gets a lobbyCharacter, which is an empty gameobject with a script on it that create UI element with the players name. In lobby players can select character they want to use.
Now when starting game, i would like to switch scene to the game scene when all players are ready. I have been reading the API, documentation, and different stack questions, but i cant seem to find any info on how this should work. On NetworkManager i can do scene schange which will be changed on all clients. But how do i persist data over multiple scenes? And if the lobby characters are destroyied how are the game characters instansiated according to the choises made in lobby? How does the client connection persist between multiple scenes?
Do i just manage the character locally and use syncHooks to synchronize over the server? Do i need to create somesort of container gameobject that holds the player connection information and some extra stuff?
EDIT
Reading the soruce code of mirror i fouind that NetworkManager holds the connection of the client, sort of. So now the issue has come down to replacing the prefab for the connection.
I have the following code:
 public void switchScene()
    {
        GameObject obj = NetworkClient.connection.identity.gameObject;

        NetworkServer.ReplacePlayerForConnection(NetworkClient.connection, Instantiate(shipPrefab));

        NetworkServer.Destroy(obj);
        ServerChangeScene(gameScene);
    }

This should switch the prefab for connection and then switch scene, but i keep getting error
InvalidCastException: Specified cast is not valid.
Mirror.NetworkIdentity.SetClientOwner (Mirror.NetworkConnection conn) (at Assets/Mirror/Runtime/NetworkIdentity.cs:362)
Mirror.NetworkServer.InternalReplacePlayerForConnection (Mirror.NetworkConnection conn, UnityEngine.GameObject player, System.Boolean keepAuthority) (at Assets/Mirror/Runtime/NetworkServer.cs:837)
Mirror.NetworkServer.ReplacePlayerForConnection (Mirror.NetworkConnection conn, UnityEngine.GameObject player, System.Boolean keepAuthority) (at Assets/Mirror/Runtime/NetworkServer.cs:697)
LobbyManager.switchScene () (at Assets/LobbyManager.cs:51)

And i dont understand why this is happening. New prefab has networkIdentity and networkTransform. Old prefab only has network transform. Up until this point everything wors, but once i want to switch scenes, it breaks.


texts: Whats the best way to light up a scene in unity?

texts:
What I want is a darkish scene with like neon style lights
Currently is use the bloom post processing effect but sometimes it doesn't render well on my main camera and looks not as good as it does in the scene

My game view with main camera -

My aim is to get the lighting similar to look like Brackeys party killer game
How may I achieve this


texts:
i want to display a mesh sequence so i imported my obj files and found a script and partially edit it a bit.My project looks like this:

the script is this:

using UnityEngine;
using System.Collections;

/**
 * Animate a mesh by cycling through different meshes.
 * @author bummzack
 */
public class MeshAnimation : MonoBehaviour {

public Mesh[] Meshes;
public bool Loop;
public float FrameDuration;

private int _index;
private bool _playing = true;
private float _accumulator;
private MeshFilter _meshFilter;

public void Start()
{
    _meshFilter = GetComponent<MeshFilter>();
    _index = 0;
}

public void Update()
{
    _accumulator += Time.deltaTime;

    if(_accumulator >= FrameDuration){
        _accumulator -= FrameDuration;
        _index = (_index + 1) % Meshes.Length;

        if(_index == 0 && !Loop){
            Stop();
            return;
        }

        _meshFilter.mesh = Meshes [_index];
        print ("Hello World");
    }
}

}

the line that causes the problem is this:

_meshFilter.mesh = Meshes[_index];

and the problem shown in the console is this:

NullReferenceException
MeshAnimation.Update () (at Assets/MeshAnimation.cs:43)

i know it has something to do with Meshes[_index} being null but i cant find the solution because i think the Meshes array is properly filled.Can anyone suggest a solution?
Thank you all in advance.


texts: How can I detect the player being crushed in a 2D platformer?

texts:
I'm checking collision for a platformer character as shown in #1. The red dots are the pixels that are checked and the grey lines indicate the axes they pertain to. I like the results I get from checking collision this way (versus, say, bounding box). Everything works exactly as I'd like it except for one problem: crush detection.

In the following images, the light blue box represents the ground, the orange box is an object, and the arrows indicate direction of movement.

The simple solution to detecting when the player is crushed is to see if the collision points on opposite sides are both triggering. If they are, the player is being crushed. In #2, you can see a normal crush scenario. The player is grounded and the top collision points are intersecting with the falling object. This triggers a crush.

#3, 4, and 5 present problematic scenarios. In #3, the player is moving toward the object, which is moving up. A right-side collision point is hitting the object, causing a collision and stopping the player.

Now, if the object continues to move up and the player continues to move right (as shown in #4), the object clears the players right-side collision point and the player moves to the right. But now, having done so, the object is intersecting a top collision point causing an unwanted vertical crush.

A similar scenario is shown in #5. Two objects are far enough apart for the bottom collision points to clear, allowing the player to fall, but no to so far as to allow the side collision points to clear, causing an unwanted horizontal crush.

I've been racking my brain on a solution, but nothing I've come up with has worked particularly well, so I'm wondering if anyone out there has an idea or insight into how to solve these problems.

To clear up some confusion, the red collision points would be within the sprite and the grey lines were only used to denote the relevant axis for each collision point. For example, if the character's sprite was a simple green square, the collion points would look something like this:


texts: Tetris block kinematic rigidbodies pass through one another with Transform.Translate

texts:
I am trying to build a Tetris 3D game in Unity but I am stuck at getting the different blocks to interact (to detect each other, to sit one on top of the other rather than going through each other). I have set the ground with a box collider and the spwaned blocks come in with rigidbodies and trigger colliders.
This works for them to nicely settle on the ground but when I try to sit a block on top of another block they both have kinematic rigidbodies and the collision detection doesn't work and they end up overlapping. The problem is if I remove the rigidbody of the already settled block then it will go through the ground.
Any idea how to get 2 spawned objects to detect each other?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

public class moveBlock : MonoBehaviour
{
    public static float speed = 2;
    public GameObject[] blocks;
    public static List<GameObject> blocksSpawned = new List<GameObject>();
    public static List<Rigidbody> blocksRBSpawned = new List<Rigidbody>();
    public static bool triggerPlatform = true;
    Rigidbody rb;

    void Update()
    {
        Vector3 input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
        Vector3 direction = input.normalized;
        Vector3 velocity = direction * speed;
        Vector3 moveAmount = velocity * Time.deltaTime;

        if (triggerPlatform)
        {
            blocksSpawned.Add((GameObject)Instantiate(blocks[Random.Range(0, 7)], new Vector3(0, 6, 0), Quaternion.Euler(Vector3.right)));
            rb = blocksSpawned[blocksSpawned.Count - 1].GetComponent<Rigidbody>();
            blocksRBSpawned.Add(rb);
            triggerPlatform = false;
        }
        /*if (!triggerPlatform)
        {
            Destroy(blocksRBSpawned[blocksRBSpawned.Count - 1]);
        }*/
        if (blocksSpawned[blocksSpawned.Count - 1] != null)
        {
            blocksSpawned[blocksSpawned.Count - 1].transform.Translate(Vector3.down * Time.deltaTime*speed, Space.World);
            blocksSpawned[blocksSpawned.Count - 1].transform.Translate(moveAmount);
        }
    }
}

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

public class trigger : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        moveBlock.triggerPlatform = true;
    }
}


texts:
I'm creating an Android game that relies heavily on collision detection for a couple of players (at least up to 4). I researched hierarchical structures that could speed up the process. Because I have worked with hierarchies of axis aligned bounding boxes for ray tracing in uni, the sweep and prune algorithm is currently my favorite choice.
However, I had the idea to use bounding boxes not only for the obstacles in a level, but also some boxes containing as much of the free space in the scene as possible. If the player's character stays within one of those during his movement between two frames no further intersection tests should be necessary. Could this approach reduce the number of intersection checks where a player's character intersects one or more axis aligned boxes but not the objects within?
I highly doubt I am the first person who thought of this, yet I didn't find something like it online. So, is there a good reason not to do this?
My best guess for why it isn't done is that there is no good rule to find applicable bounding boxes for empty spaces in between. But if they are precomputed before the game I don't see this as a problem.
Maybe they could be bounding spheres instead. Those could be grown from an obstacle's surface until it touches obstacles in at least three points, like so:

Any advice would be greatly appreciated


texts: What OpenGL version(s) to learn and/or use?

texts:
So, I'm new to OpenGL... I have general knowledge of game programming but little practical experience.

I've been looking into various articles and books and trying to dive into OpenGL, but I've found the various versions and old vs new way of doing things confusing.

I guess my first questions is does anyone know some figures about percentages of gamers that can run each version of OpenGL. What's the market share like? 2.x, 3.x, 4.x...

I looked into the requirements for Half Life 2 since I know Valve updated it with OpenGL to run on Mac and I know they usually try to hit a very wide user-base, and they say a minimum of GeForce 8 Series. I looked at the 8800 GT on Nvidia's website and it listed support for OpenGL 2.1. Which, maybe I'm wrong, sounds ancient to me since there's already 4.x. I looked up a driver for 8800GT and it says it supports 4.2! A bit of a discrepancy there, lol.

I've also read things like XP only supports up to a certain version, or OS X only supports 3.2, or all kinds of other things. Overall, I'm just confused as to how much support there is for various versions and what version to learn/use.

I'm also looking for learning resources. My search results thus far have pointed me to the OpenGL SuperBible. The 4th edition has great reviews on Amazon, but it teaches 2.1. The 5th edition teaches 3.3 and there are a couple things in the reviews that mention the 4th edition is better and that the 5th edition doesn't properly teach the new features or something? Basically, even within learning material I'm seeing discrepancies and I just don't even know where to start.

From what I understand, 3.x started a whole new way of doing things and I've read from various articles and reviews that you want to "stay away from deprecated features like glBegin(), glEnd()" yet a lot of books and tutorials I've seen use that method. I've seen people saying that, basically, the new way of doing stuff is more complicated yet the old way is bad   >.>

Just a side note, personally, I know I still have a lot to learn beforehand, but I'm interested in tessellation; so I guess that factors into it as well, because, as far as I understand that's only in 4.x?

[just btw, my desktop supports 4.2]


texts: SAT - penetration and pull out vector based on previous body position

texts:
I implemented SAT alghorithm that is able to detect collisions and return shortest "pull out" vector.
On the screenshot below this vector is determined by yellow color (P and Q).
If I add Q vector to position of body B, then will be no collision.
However I realized that I can't use this vector to solve collisions, because the body could arrive from completely different direction. I should rather pull out body B by using direction of vector Z.
I already tried to calculate additional overlap by using axis determined by vector Z. However in such case I'm pulling body B too far away from A.
Is there any ellegant solution for that by keep using SAT algorithm?


texts: Weird error with opengl in Android using Libgdx : "EGL_BAD_ATTRIBUTE"

texts:
I am having a weird error when uploading my game in the phones.

E/Adreno200-EGL(5128): qeglDrvAPI_eglGetConfigAttrib:484>: EGL_BAD_ATTRIBUTE

I am uploading the textures with AssetManager.

I am using OpenGL 1.0.

It begans to upload the textures, but when it is about to finish uploading them, it finishes unexpectedly without any message in logcat.

Any ideas what is happening?

When I updated my xperia ray to ics it began having this problem

And when it loads, and I navigate through screens I get this in logcat

<qgl2DrvAPI_glClear:33>: GL_INVALID_VALUE

This is my line using the clear

this.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

The type of gl is GL10

Although the first error occurs when it is loading :/

Here is my logcat output


texts: What do these STATE_CREATION warnings mean in the DX11 debug output?

texts:
So I've been fighting my way through learning the DirectX 11 API with what little documentation there is out there and noticed some new D3D11 warnings in my debug output. (Atleast I think they are new, been rearranging my draw calls to try and solve another problem I'm experiencing at the moment) Anywho, with some Google-fu I've been unable to find any documentation on the error codes or anything but the general consensus of forums seems to be that the COM objects aren't properly being released.

Now the question is, if that is indeed what the warnings mean, what else do I need to do to kill these things other then call their Release() functions? And is there somewhere this kind of information is posted? I sure can't find it on MSDN or Google. Just lots of confused DX11 post with unanswered questions.

Here is the debug output.

D3D11: WARNING: Live Device: Name="unnamed", Addr=0x004C6488, ExtRef=5 [ STATE_CREATION WARNING #2097297: LIVE_DEVICE ]
D3D11: WARNING: Live Texture2D: Name="unnamed", Addr=0x04552E94, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097235: LIVE_TEXTURE2D ]
D3D11: WARNING: Live Buffer: Name="unnamed", Addr=0x04552A64, ExtRef=1, IntRef=0 [ STATE_CREATION WARNING #2097229: LIVE_BUFFER ]
D3D11: WARNING: Live Buffer: Name="unnamed", Addr=0x04566ECC, ExtRef=1, IntRef=0 [ STATE_CREATION WARNING #2097229: LIVE_BUFFER ]
D3D11: WARNING: Live InputLayout: Name="unnamed", Addr=0x0455280C, ExtRef=1, IntRef=0 [ STATE_CREATION WARNING #2097265: LIVE_INPUTLAYOUT ]
D3D11: WARNING: Live PixelShader: Name="unnamed", Addr=0x004CDDE4, ExtRef=1, IntRef=0 [ STATE_CREATION WARNING #2097262: LIVE_PIXELSHADER ]
D3D11: WARNING: Live VertexShader: Name="unnamed", Addr=0x04553944, ExtRef=1, IntRef=0 [ STATE_CREATION WARNING #2097250: LIVE_VERTEXSHADER ]
D3D11: WARNING: Live RenderTargetView: Name="unnamed", Addr=0x0455269C, ExtRef=0, IntRef=0 [ STATE_CREATION WARNING #2097244: LIVE_RENDERTARGETVIEW ]
D3D11: WARNING: Live Texture2D: Name="unnamed", Addr=0x04552214, ExtRef=4294967295, IntRef=1 [ STATE_CREATION WARNING #2097235: LIVE_TEXTURE2D ]
D3D11: WARNING: Live Query: Name="unnamed", Addr=0x004C84AC, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097280: LIVE_QUERY ]
D3D11: WARNING: Live Sampler: Name="unnamed", Addr=0x004C8274, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097268: LIVE_SAMPLER ]
D3D11: WARNING: Live RasterizerState: Name="unnamed", Addr=0x004C804C, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097277: LIVE_RASTERIZERSTATE ]
D3D11: WARNING: Live DepthStencilState: Name="unnamed", Addr=0x004C7E24, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097274: LIVE_DEPTHSTENCILSTATE ]
D3D11: WARNING: Live BlendState: Name="unnamed", Addr=0x004C7C6C, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097271: LIVE_BLENDSTATE ]
D3D11: WARNING: Live Context: Name="unnamed", Addr=0x0453006C, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097226: LIVE_CONTEXT ]
D3D11: WARNING: Live Device Child Summary: Device Addr=0x004C6488
Using ID3D11Debug::ReportLiveDeviceObjects with D3D11_RLDO_DETAIL will help drill into object lifetimes. Objects with ExtRef=0 and IntRef=0 will be eventually destroyed through typical Immediate Context usage. However, if the application requires these objects to be destroyed sooner, ClearState followed by Flush on the Immediate Context will realize their destruction.

Note: Clearing and Flushing the device context doesn't seem to affect anything.

Thanks in advance!

Solution

A slight tweak in my code prevented objects from being shut down and releasing their COM objects.


texts:
Today i was following a tutorial about making a shop, but i got a problem.

and i've followed the scripting tutorial, but it seems i can't spawn a button inside the grid when i pressed GetItemButton. here's how the script goes:

public class ItemCatalogue : MonoBehaviour {

public Items[] AvailableItems;
public Text DisplayArray;

public void GetItem() {
   Items item = AvailableItems[Random.Range(0, AvailableItems.Length)];
    InventoryCatalogue.Instance.AddMaterialToCatalogue(new ItemStack(item, 1));
    DisplayArray.text = item.name;
}

// Use this for initialization
void Start () {

}

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

    }
}

and another one:

public class InventoryCatalogue : MonoBehaviour {

public static InventoryCatalogue Instance;

public List<ItemStack> MatStorage;

public Transform ScrollList;
public GameObject ItemPrefab;

void Start()
{
    if (Instance != null) {
        return;
    }
    Instance = this;
    MatStorage = new List<ItemStack>();
}

public void AddMaterialToCatalogue(ItemStack Stack) {
    bool hasItem = false;
    foreach (ItemStack i in MatStorage) {
        if (i.item.name == Stack.item.name) {
            hasItem = true;
            i.amount += Stack.amount;
        }
    }
    if (!hasItem) {
        MatStorage.Add(Stack);
    }
  }
}

Anybody know why?


texts: I'm building an editor. Is it possible to create a child window of SDL2 within a Win32 gui? (The most obvious page from SDLTutorials works for earlier versions of SDL)


texts: How to draw a smoother solid-fill circle?

texts:
I'm experimenting with drawing circles and have brute-forced a very simple one:

Pseduocode:

r=7
d=r*2

for y = 0 to d
  for x = 0 to d
    if (x-r)^2 + (y-r)^2 <= (r)^2
      plot(x+r, y+r, c)
    endif
  next
next

The principal is simple. Step through every point in a square and plot every point which lies within the area of the circle.

I end up with something like this:

I don't want the single-pixels that appear on on each side so I adjusted this line from:

if (x-r)^2 + (y-r)^2 <= (r)^2

to:

if (x-r)^2 + (y-r)^2 < (r)^2

I end up with a circle like this:

While this IS a circle, it's not quite the circle that I want. The edges are too sharp and don't slope in a convincing way. Instead, I want to draw something little smoother like this:

But I'm not sure how to "relax" the the pixels to achieve this.

The code I posted is meant to illustrate how I'm drawing the circle-- I'm not looking for optimizations. I'm only interested in tweaking it to manipulate the smoothness of the circle being drawn.

This is more than an adjustment for the last pixel along each side. I want something that scales with the size of the circle.

UPDATE

I experimented with the code provided by @user1118321 an found that I could manipulate which pixels were drawn along the edge by considering the distance of the point being plotted from the center of the circle.

This allows me to apply a threshold on the points at the very edge of the circle and to decide which ones I want to skip over.

The results vary depending on a few different factors and would benefit from fine-tuning with a table for an optimal threshold for very small circles to taste.

Here is one solution which provided me with the circle I was looking for:

for y = 0 to r*2
  for x = 0 to r*2
    deltaX = r - x
    deltaY = r - y
    distance = sqr(deltaX^2 + deltaY^2)

    // Point lies outside of the circle
    if distance-radius > 1
      continue
    endif

    // Edge threshold
    if radius/distance < 0.9
      continue
    endif

    plot(x, y)
  next
next

Here are some examples of various circles I was able to create:


texts: How do i put apps on sleep while my game is running in an Android Device. I m a Game Developer (intermediate Level). And i Wanna know the Can i put apps of phone running in background to sleep to free some ram and make my game run on 1 gb of phone smoothly (Android 9).


texts: I have 3d object as Wall ( Cube with texture and width and height large ) with some texture and attached c# ( Unity 5.3.2 ) script to that wall. I want to programmatically draw rectangles on that Wall with green semitransparent color and after 5 seconds remove them. I am new to Unity and found OnGui but it is not drawing in 3d space but in front of screen. How to achieve this to draw and remove rectangles on Wall ?


texts: Is there an efficient way to identify in which run-time generated room a character is, in a non-grid 3D environment? How?

texts:
Here is what I am trying to implement. I wrote a script that allows the player to place walls during run-time, in non grid-based 3D environment (walls can be diagonal with rotation increasing/decreasing in amounts of 10 degrees). Like the figure below shows, since wall can form different angles, rooms might end up having both convex and concave angles:

What I have been looking for, without success so far, is a way to detect in which room a given character is, according to its position. Of course, if that was a grid-based setting, I could only pass an ID for each cell and then retrieve the ID of the cell where the given character stands. However, that being a non-grid setting and with irregular rooms that have shapes unknown in advance, how could I accomplish that in an efficient way?

Many thanks.

EDIT:
Although it is a 3D environment, the problem may be treated as a 2D one since height is not a concern here.


texts: How to properly render a Frame Buffer to the BackBuffer in Stage3D / AGAL

texts:
After doing a render pass with RenderToTarget (RTT), how do you properly render that texture buffer to the screen while maintaining original scale / proportions so it doesn't stretch or lose quality?

Can an AGAL VertexShader & FragmentShader be written so it's adaptable to any Texture size and Viewport dimensions?

I find I'm getting some "blocky" effects in some of my first attempts at "ping-ponging" between two Texture buffers (to create trailing effects). Perhaps I'm not using the UVs correctly between the rendering-to-target and/or the backbuffer?

Is there a simpler way just to "splash" the texture on the backbuffer, or is a Quad absolutely necessary (4 vertices, 2 triangles)?

If it needs the Quad, should the Texture buffer be fully drawn (0.0 to 1.0 for vertical and horizontal UVs), or only a percentage of it should, like the example below?

Texture Buffer U: 0.0 to viewport.width/texturebuffer.width;
Texture Buffer V: 0.0 to viewport.height/texturebuffer.height;

Thanks!


texts:
How does the interpolation in a fragment shader work when it comes to the alpha parameter?

I'm programming a shader with SharpDX, DirectX11. My idea is to interpolate 2 3d points of a segment, so that I'll have the position interpolated in between in the pixel shader. But I want to know what happens with the alpha parameter when that position is blocked by another polygon.

For instance, if alpha is 1.0 at the left end of my segment and 0.0 at the other one. What is the value of alpha in the middle, 0.5? Or does it depend on the visibility at that point (meaning it could be, for instance, 1.0 OR 0.0 depending on if that part of the segment is hidden by a poolygon?


texts: Best way to get elapsed time in miliseconds in windows

texts:
I'm trying to do it using two FILETIMEs, casting them to ULONGLONGs, substracting the ULONGLONGs, and dividing the result by 10000. But it's pretty slow, and I want to know if there is a better way to do it.I use c++ with visual studio 2008 express edition. This is what I'm using:

FILETIME filetime,filetime2;
GetSystemTimeAsFileTime(&filetime);
Sleep(100);
GetSystemTimeAsFileTime(&filetime2);
ULONGLONG time1,time2;
time1 = (((ULONGLONG) filetime.dwHighDateTime) << 32) + filetime.dwLowDateTime;
time2 = (((ULONGLONG) filetime2.dwHighDateTime) << 32) + filetime2.dwLowDateTime;
printf("ELAPSED TIME IN MS:%d",(int)((time2-time1)/10000));


texts: I have a sprite that is a few buttons but need them in the center of the screen for all android devices. I tried setting it's location to the center of the screen by dividing the orthogonal camera by 2, but it doesn't help. Any simple way to fix this?


texts: Set the LineTraceByChannel to use my custom created channel? C++

texts:
I want to use LineTraceSingleByChannel function for my SightRay component which will be used for my adventure game. I want to mark certain objects in game as 'Viewable' in Trace Channel. Then the ray will only be true if it hits a 'Viewable' object.

I have created the Viewable trace channel in the Collision settings of Project Settings. But I have two problems now.

In the actual c++ code I am writing, how do I reference this new 'Viewable' channel in the ECollisionChannel parameter of the method?
How do I assign this channel to each object in the scene?

I have been trying to figure this out for hours, I've read many Unreal documentation pages and forum threads but can't get a straight answer, particularly without using Blueprint nodes.

Here is my code:

bool USightRay::GetLineTraceHit(FHitResult &OutHit)
{

FVector LineStart = UGameplayStatics::GetPlayerCameraManager(this, 0)->GetCameraLocation();
FVector LineEnd = LineStart + UGameplayStatics::GetPlayerCameraManager(this, 0)->GetCameraRotation().Vector() * LineTraceLength;
//ECollisionChannel viewable =  WHAT CAN I PUT HERE?????
if (GetWorld()->LineTraceSingleByChannel(OutHit, LineStart, LineEnd, viewable))
{
    UE_LOG(LogTemp, Warning, TEXT("HIT ME WITH YOUR RHYTHM STICK!"));
    return true;
}

return false;
}

I actually thought this would be simple before I started to code it. I've used it before but I just used ECollisionChannel::ECC_Visibility  in place of 'viewable'. This time I want to learn to filter the collisions and traces properly.

Thank you for any help.


texts: Why does PIX crash while creating render target views in my D3D11 application?

texts:
I'm trying to use PIX to debug my Direct3D11 application. PIX crashes and gives the following stack trace:

Frame 000001 ........PRE: <this=0x054338e0>IDXGISwapChain::GetBuffer(0, IID_ID3D11Texture2D, 0x00B3E0F0)
Frame 000001 ........POST: <S_OK><this=0x054338e0> IDXGISwapChain::GetBuffer(0, IID_ID3D11Texture2D, 0x00B3E0F0)
Frame 000001 ........PRE: <this=0x05433978>ID3D10Texture2D::Map(11788512, Unknown D3D10_MAP, 1843764804, 0x00B3EA08)
Frame 000001 ........POST: <E_INVALIDARG><this=0x05433978> ID3D10Texture2D::Map(11788512, Unknown D3D10_MAP, 1843764804, 0x00B3EA08)
Frame 000001 ........PRE: <this=0x054b70d0>ID3D11Device::CreateRenderTargetView(0x05433978, NULL, 0x00B3E0F4)
Frame 000001 ........POST: <E_INVALIDARG><this=0x054b70d0> ID3D11Device::CreateRenderTargetView(0x05433978, NULL, 0x00B3E0F4)

What can I do to get around this problem so that I can debug my application?


texts:
How would I go about creating vehicle physics for a car that can loose traction? I want it to seem like the driver has a flat foot, so when you press the gas, they cars driving (rear) wheels loose traction, and makes it somewhat hard to control. I would also like to be able to do doughnuts and "drift" around corners.

I would also need to know how much "skid" is happening, so I can add a proportional amount of smoke and tire marks.

Assume a 2d, top-down style car game.

Thanks


texts: What are the basics of implementing a Goal Oriented AI?

texts:
I am currently developing a nations / factions simulator on a map with in-depth resource system, population system, important characters system.. and this is where I finally met a real obstacle.

You see, I wish to give important characters a set of actions which their AI will use to achieve goals, goals that will depend on their character type. For example, an important character who spawns because he leads a migration wave will have two goals : to keep himself and his party alive and to reach his destination and start a new "population node" there. Another example : warlords could seek to increase their "power" variable by making plans to get ahead of other warlords through simple actions like giving money to a local lord to help develop his land, etc.. this would take very long to describe in great detail.

As you can see, or at least as I see it, the best AI architecture for this kind of behavior would be a Goal Oriented AI : it would allow me to keep expanding the set of actions characters have to advance their interest and at the same time allow me to easily create new types of important characters.

I have done quite a lot of research, and most of the sources I found explain the same thing clearly, which I understood : GOAP is about having a starting "world state" and through a "path" of actions, get to a desired world state called a "goal".

The thing I couldn't understand is how exactly you can achieve this with actions other than actions which do not require any parameters. I could implement a basic system right now, I think, provided actions can fully run by themself with no external information, and more importantly no knowledge of eachother, because that would break the point of the whole system I believe.

The articles talk about that very vaguely. I've read about a "blackboard" system where information like what is the current target, where to move.. can be stored. But while planning how do you use this ? Where does that information come from ? How do you associate it with "world state" key-value pairs ?

Finally, I found that some people solve this problem, or at least solve it for the movement, by making a FSM over the GOAP, where one of the state is "moving" and the other one is, basically "GOAP". But I do not think this is the best approach and more importantly I'd like not to go with a hybrid if I can.

So if someone would be kind enough to explain the basic concepts of implementing a Goal oriented AI, or at least help me deal with actions that require a parameter, I'd be extremely grateful. If you want me to expand this wall of text I can provide more detail, simply ask.

PS : I use Unity, coding in C# exclusively.


texts: Shader models, when to use "ps_4_0_level_9_x" instead of "ps_4_0"

texts:
I've made a very simple post processing shader for my 2D game. It produces scanlines by dimming every other line. For this I use the position of the pixel on the screen.

When using ps_4_0_level_9_3, I receive the message:

shader model ps_4_0 feature level_9_3 doesn’t allow reading from position semantics

So I switched to just ps_4_0 and things work fine. I probably won't be using any advanced shaders in my 2D game.

My questions are:

By setting the pixel shader to 4_0 only, what impact does that have for my game (if any) - is it a mistake to 'downgrade' the pixelshader?
How do I know what pixelshader version to use? I found this: Direct3D featurelevels but I'm unsure when to use what shader? Is there a list like "for windows use this", "for mobile this" or is it, use the lowest version that supports the feature you need?


texts:
What I'm hoping to achieve is that when the player steers into a wall the movement is smoothed out by hugging along the wall, moving only with the velocity parallel to the wall, zeroing out the normal force) rather than bouncing back from the wall using the "generic" avoidance method.

I want this: Not this:

The two images are actual behaviors from my code. One removes the velocity normal to the wall so it glides smoothly hugging the wall. The other steers away from the wall creating the bouncing effect. The latter case actually works quite reliably but I do not like the bouncing behavior.

Here's my design for the for handling this case:

The vertical wall is actually made up of many square tiles
The wall avoidance steering checks one unit ahead to see if it is in contact with a tile
The normal is determined by which edge on the tile I'm closest to
zero out the velocity of the player normal to the wall

However this is not reliable for several reasons:

in the gif above, if the look ahead ends up on the bottom edge of a tile, it gets the wrong normal (goes horizontal instead)
the player can get stuck if it happens to penetrate the wall to much (i.e. stay on track for 1 frame, then next frame gets the wrong/perpendicular normal, then both velocities are canceled out)
player can penetrate the wall quite easily if they pick the right spot (which I don't have an obvious sense why)

I am wondering if anyone has a better suggestion on how to handle this case? The only requirement that I prefer to keep is the tile based wall as I have a map editor that generates the map data. Also if there is a method that can be extended to sloped walls that would be even better!

Thanks!


texts:
I asked in SO, but no responses so I'm posting here since it's probably more relevant here.

EDIT: SO question closed.

I'm trying to tween primitive data-types the way Action tweens position to create movement. The main reason is to take advantage of the easing functions, rather than hand-code all the easing. This is helpful when implementing things like tweening money counter values (When the teller's display goes ka-ching, you can see the number tween towards the final value.)

Is there a way to directly apply Action or some variant of this onto datatypes like int or float?

Or do I have to cheat by keeping a Node, apply the Action onto the node's property, and read the property? (I'd rather not do this)


texts: (Efficiently) Generate Unique Random Numbers

texts:
Sorry my terminology is somewhat limited so I'll have to use more words to explain what I mean.

In games that require critical hits, I've heard it's not good to generate a random number but instead one should randomly pick a number from a list of possibilities then exclude that number from the next picking. This way, the dev is given more control over the player's experience.

To do this, I've been thinking somewhere along the lines of generating a random number then excluding that number from the next generation. In C#, how can I exclude a number from a random number generation? I don't think that using a while loop to continually check for another number if the currently generated one is excluded is a very efficient method, especially when most of the numbers have been excluded. Is there a built-in method to do this or some clever way to implement it?

Not: I need upwards of 100 numbers to possibly generate so hard-coding it would be tedious.


texts:
I have been reading up about path finding and find it all very confusing, however this is probably the best I have found for a logical explanation:

Path

If the cost of two nodes has the same value, I'm not sure how the path would be worked out though. How would it be worked out?


texts: Converting UnityScript code to C#: What is the alternative for .ToBuiltin?

texts:
I'm trying to convert this code from UnityScript (Unity's version of JavaScript) to C#:

var polys = new Array(); // array to collect vertex locations
polys.Push((scanpoint + padding) + Vector2(0.5, 0.5) * Pixel_vs_Unit_Scale);
var poly:Vector2[] = polys.ToBuiltin(Vector2);

I converted the first two lines like so, with no errors:

var polys = new List<Vector2>();
polys.Add((scanpoint + padding) + new Vector2(0.5f, 0.5f) * Pixel_vs_Unit_Scale);

But when I try to adapt the last line like this:

Vector2[] poly = polys.ToBuiltin(Vector2);

I get two errors:

  ToBuiltin does not exist.

And also an error on the Vector2 inside the ():

  Vector2 is a type which is not valid in the given context.

How can I convert this code to C# correctly?


texts: Numerical integration of multiple off-center forces on a solid body

texts:
I am trying to develop a little simulation (for the sake of learning a little bit about physics) involving a circle (mass m, radius r, regular density) and two forces f1, f2 that can be applied on any two points within the circle.

I have read that when a force doesn't go through the center of mass, then you have to split it up into two components, one parallel to the offset and one perpendicular to it. The parallel part of that force obviously now goes through the center of mass and thus "a=F/m" applies whereas the perpendicular force applies a torque, allowing me to use "alpha = torque/moment of inertia".

In my tests, this has worked perfectly, for as long as only one force acts on the body at a time.

However how (if at all) do I need to resolve multiple forces that influence the same body? At first I thought I can simply resolve each force in the pattern I described above and thus I calculated the sum of the linear forces on the CoM as well as the sum of the torque components. However this doesn't work for a number of examples, such as one where f1 and f2 act on either "side" of the circle in the same direction and both have the same length. For each individual force, there is no parallel component and thus no force is acted on the body. The sum of the torque is 0 as well, thus the body is not accelerated at all.
However from playing KSP I realize that the net force applied on the body should be f1+f2.

This problem should have been solved numerous times, however I am unable to find a proper numerical solution (or don't use the right search terms). Can you guys help me out?


texts: Separation of drawing and logic in games

texts:
I'm a developer that's just now starting to mess around with game development. I'm a .Net guy, so I've messed with XNA and am now playing around with Cocos2d for the iPhone. My question really is more general though.

Let's say I'm building a simple Pong game. I'd have a Ball class and a Paddle class. Coming from the business world development, my first instinct is to not have any drawing or input handling code in either of these classes.

//pseudo code
class Ball
{
   Vector2D position;
   Vector2D velocity;
   Color color;
   void Move(){}
}

Nothing in the ball class handles input, or deals with drawing. I'd then have another class, my Game class, or my Scene.m (in Cocos2d) which would new up the Ball, and during the game loop, it would manipulate the ball as needed.

The thing is though, in many tutorials for both XNA and Cocos2d, I see a pattern like this:

//pseudo code
class Ball : SomeUpdatableComponent
{
   Vector2D position;
   Vector2D velocity;
   Color color;
   void Update(){}
   void Draw(){}
   void HandleInput(){}
}

My question is, is this right? Is this the pattern that people use in game development? It somehow goes against everything I'm used to, to have my Ball class do everything. Furthermore, in this second example, where my Ball knows how to move around, how would I handle collision detection with the Paddle? Would the Ball need to have knowledge of the Paddle? In my first example, the Game class would have references to both the Ball and the Paddle, and then ship both of those off to some CollisionDetection manager or something, but how do I deal with the complexity of various components, if each individual component does everything by itself? (I hope I'm making sense.....)


texts: Missing UI options in Inspector window when I import FBX files

texts:
I am missing all the animation options in the Animation tab in the Inspector Window when importing FBX files.

In the picture below, there are only 2 checkboxes. I can't see the list of animations, options, animation events etc., but you can see on the lower left window that the animations we're imported. Also, the Materials tab is empty as well.

This FBX was exported from Blender. If I directly drag the .blend file to Unity, all those tabs appear normally, but when dragging an FBX, they become empty. I am using Unity 2019.3.0f6.


texts: Unity - paiting terrain details vs combining a large mesh

texts:
I am about to start making my landscape, and am using a low poly style.

I think I'd prefer not to use the terrain system and instead just use a bunch of meshes, since all my grass/flowers are 3d models.

Does anyone know how this will effect performance, keeping in mind that Ill combine all my vegetation to one large mesh when Im done, so that it's not hundreds of gameobjects. Is it a lot worse than using the terrain tool with detail painting?


texts: FBX model from Blender doesn't show it's surface in Unity3D

texts:
I've create a model from Blender and exported it as .FBX file. However when I import this into Unity, the surface is missing.how can i fix?

Screenshot attached:

in Blender it look like this:

in Unity it look like this which only shows it inside:


texts: Computing depth from position of fragment in world space

texts:
I have a raymarching shader which computes the location of a hit on the scene in world space.

float3 worldPos = ... ;

I can verify that the world position is right, because the position of everything renders correctly, even in stereoscopic rendering.

Now I'm trying to convert this to clip space so that I can write the right value into the Z-buffer. I initially thought it would be like this:

float4 clipPos = mul(UNITY_MATRIX_VP, float4(worldPos, 1.0));
output.depth = clipPos.z / clipPos.w;

But this turns out to be completely wrong:

What is the correct way to get the right Z value?

Investigation 1:

Tinkering with it a bit, I started trying random multiplication factors:

float4 clipPos = mul(UNITY_MATRIX_VP, float4(worldPos, 1.0));
output.depth = clipPos.z * 100 / clipPos.w;

This turns out to look exactly right in the editor:

But it looks wrong in the game view. This, however, looks right in the game view:

float4 clipPos = mul(UNITY_MATRIX_VP, float4(worldPos, 1.0));
output.depth = clipPos.z * 96 / clipPos.w;

I assume that the difference is somehow due to the settings on the different cameras. So now I'm trying to figure out: what is the correct way to do this, to get the right value irrespective of the camera?

Investigation 2:

I'm trying to render this as the scene skybox.

If I render the same thing onto a cube, the generated depth values appear to be correct. Is there a different value in UNITY_MATRIX_VP when rendering the skybox, which results in the wrong result?

How far away is the skybox actually? Everyone just says "it's infinitely far", but that's nonsense - if it were really infinitely far, the world position of every point on the thing would be infinity, and transforming that to view space and clip space would also give infinity.


texts: Determine the z coordinate of a deformed plane based on uv (xy) coordinates

texts:
I am using a formula to turn the following texture

into what looks like two 3 dimensional planes

The formula I am using for the texture deformation is

float2 texUV = float2(uv.x / abs(uv.y), (1.0 / abs(uv.y)));

Based on the deformation equation above, how can I work out a value for z on the surface of the plane at any given uv (xy) coordinate?


texts: Selling Android game with using Google Play Games

texts:
I'm making an Android Game that using Google Play Games for authentication, and storing user data to cloud.

Originally I planned this game as free, and put some in-app-purchasement stuffs in it, but unfortunately there is a serious technical issue, so that I have to rid off IAP from my game.

I spent lots of my time to developing this game, and I want to get some reward from my work, so I decided to sell this stuff with reasonable cheap price, but is it ok to sell the game that using Google Play Games? I googled it already, but couldn't find any related information about this.


texts: How can i loop over all the childs of childs?

texts:
In top of script i added:

public Transform parentToSearch;

Then:

private void OnGUI()
    {
        if (hasDescription == true && clickForDescription == true)
        {
            foreach (Transform child in parentToSearch)
            {
                if (child.GetComponent<ItemInformation>() != null)
                {
                    ItemInformation iteminformation = child.GetComponent<ItemInformation>();
                    if (child.name == objectHit)
                    {
                        var centeredStyle = GUI.skin.GetStyle("Label");
                        centeredStyle.alignment = TextAnchor.UpperCenter;
                        GUI.Label(new Rect(Screen.width / 2 - 50, Screen.height / 2 - 25, 100, 50), iteminformation.description, centeredStyle);
                    }
                }
            }
        }
    }

But when i make the loop:

foreach (Transform child in parentToSearch)

It will find the first level childs of the first parent but this childs have also childs and so on. And i want to loop all the childs and childs of childs under the Transform.

For example in the Hierarchy i have:

Test

Test1
Test2
Test3

Test31
Test32

Test4
Test5

Test51

So now it will loop only over Test 1,2,3,4,5 but I want also to loop over Test31,Test32,Test51