texts: Plugin system with AssemblyLoadContext and unloading

texts:
I'm building a game engine from scratch and trying to implement a basic plugin system within my engine.
Using AssemblyLoadContext to load the target dll dynamicly and unloading it with AssemblyLoadContext.Unload()
However it seems even if there is a one class instance created from this assembly hanging somewhere in the whole app domain AssemblyLoadContext.Unload() does not unload it until the all the instances are dereferenced.
This is where my problem begins.
There are infinite number of scenarios whether a class which belongs to the plugin can be instantiated and used across the whole appdomain right?.
So how do i keep track of the plugin instances across the whole AppDomain.
(How unity unloads the user scripts and cleans every last one of the instances i wonder)
My engine system is nearly identical to both unreal and unity.
I have entities and the components just like unity.
My current unload workflow is like this.

Loop through every component via reflection and check if one the assembly classes instantiated then set that field/property null
Loop through every assembly and check for static fields/properties which might contain some instance
Now unload it.

However the approach above seems well idiotic and sluggish not to mention it should be slow as hell.
It seems i have a desing problem within my plugin system and i fear if i overcomplicated things.
Are there better way to cleanup assembly instances or am i missing something? (Please tell me im missing something obvious)


texts:
I found two ways of doing tone mapping (first, second):

//Ld - this part of the code is the same for both versions
float lum = dot(rgb, vec3(0.2126f, 0.7152f, 0.0722f));
float L = (scale / averageLum) * lum;
float Ld = (L * (1.0 + L / lumwhite2)) / (1.0 + L);
//first
vec3 xyY = RGBtoxyY(rgb);
xyY.z *= Ld;
rgb = xyYtoRGB(xyY);
//second
rgb = (rgb / lum) * Ld;

For an example pixel data above equations produces different results. Which way is correct ?


texts: How to render animated models via instanced rendering?

texts:
I have an animated model with a maximum of 60 bones. That means i have an array of 60 matrices when i want to render the model. Previously i would just create a uniform with the fixed size (mat4[60]), but now i want to render the model via instanced rendering, which means i need to write 60 matrices per instance into the VAO of the model.

This would mean i have to create 240 vertex attributes each containing 4 floats because thats the maximum number of floats an attribute can have. This is obviously a ridiculous solution, besides the fact that i think it exceeds the maximum number of attributes a VAO can have.

So how do i render animated models via instance rendering?


texts:
I am trying to write a sphere mesh algorithm. Unfortunately, is the texture stretched vertically at the very end of the image. This should be near U 0.99~.

Below is the code used for the sphere creation. In the Image below that you can see a sphere created by Maya with the correct textures applied to it. Therefore, the issue is defiantly the UV map created by this code.

If I increase the number of parallels that are wrongly called meridians. Then the texture looks nearly spot on, but one thin line of garbage.

Hope someone sees the issue. I worked on it for 2 days now :(
There is a live version online for a closed examination of the object.
https://upmkuhn.github.io/AGAV/AGAV/

Btw what is the correct terminology for such an issue?

function makeSphere(radius, numParallels, numMeridians)
{
    var index = 0;
    var grid = [];
    var vertecies = [];
    var normals = [];
    var texture = [];
    var faces = [];

    for (var p = -1; p < numParallels; p++)
    {
        var row = [];
        var parallel = Math.PI * (p +1) / numParallels
        for (var m = -1; m < numMeridians; m++) {
            var meridian = 2.0 * Math.PI * m / numMeridians
            var cartesian = sphericalToCartesian(radius, meridian, parallel);
            var vec3xyz = vec3.create(cartesian);
            vertecies.push(cartesian);

            //NORMALS
            vec3.normalize(vec3xyz, vec3xyz);
            normals.push(vec3xyz);

            x = vec3xyz[0] == 0 ? 0 : vec3xyz[0];
            y = vec3xyz[1] == 0 ? 0 : vec3xyz[1];
            z = vec3xyz[2] == 0 ? 0 : vec3xyz[2];
            //UV
            var u = (Math.atan2(x, z) / (2 * Math.PI) + 0.5);
            var v = y * 0.5 + 0.5;

            texture.push(u,v);
            row.push(index++);
        }
        grid.push(row);
    }

    for (var i = 0; i < texture.length;i+=2)
    {
        var u = texture[i];
        var v = texture[i+1];
        if (Math.abs(u-v) < 0.5)
        {
        }
    }

    for (var p = 0; p < (numParallels ); p++) {
        for (var m = 0; m < numMeridians; m++) {

            if (m < numMeridians) {
                var p1 = grid[p][m];
                var p2 = grid[p + 1][m];
                var p3 = grid[p][m + 1];
                faces.push(p1, p3, p2, grid[p + 1][m + 1]);
            }
        }
    }

    return {
        vertecies: vertecies,
        normals: normals,
        texture: texture,
        faces: faces
    }
}

function sphericalToCartesian(radius, azimuth, elevation)
{
    var x = radius * Math.sin(elevation) * Math.cos(azimuth)
    var y = radius * Math.sin(elevation) * Math.sin(azimuth)
    var z = radius * Math.cos(elevation)
    return [x , y , z];
}


texts:
I didn't understand this point yet. for me its complicated. What i'm trying to do is a level as loading scene work to appear before load the game level. when loading progress bar complete you have to press any button to play the game. Here is my script:

// game level01
// game level02
// loading scene

 public float progressBar;
 public void nextlevel() // this for button
{
 LoadNextLevel();
}

IEnumerator LoadNextLevel()
{
    AsyncOperation async = Application.LoadLevelAsync("level02");
    yield return async;

}

Example from "ninja gaiden black". when you select any level to play. loading scene show up. when complete loading the level. new word appear inform yo to press X to play.


texts:
I'm making a game in AS3, and it's a rather simple shooting game because I'm original. Anyway, probably the most subjective question here yet: what is the best way to implement bullets in my game?

Would it be smarter to make a universal bullet manager class on the game that handles all the bullet related data or have every entity that has bullets (players, enemies) have this sort of 'bullet manager'?

Make a level-wide bullet manager --or-- bullet manager for each entity?

Oh, and a side question: I actually have an enemy manager class. How would I check for collisions from the aforementioned bullet manager class.


texts: Making a sound every time I get to the edge of the platform

texts:
I'm trying to make a runner game for the blind, and I need help making a sound every time it is time to jump. I am using Game Maker, and I have no idea how to do it.

How do I play a sound when my player gets to the edge of a platform in Game Maker?


texts: How to detect collision with non-rectangular objects in 2D games?

texts:
Detecting collision with rectangular objects is quite easy. I am able to write simple tile based games. Now I want to learn to write non-tile based games in which objects may not be rectangular, for example, a mountain.

Suppose I want an uneven terrain with hills and mountains how do I store the shape of the terrain? Also how do I detect the collisions for such uneven objects?


texts:
I'm making a 2D Tile based game in OpenTK at the moment. Performance was really bad (laggy and slow) with direct drawing, so I switched to VBOs. The performance hasn't changed, it might even be slower than it was.

I render the tiles from a list, but use a single VBO.

public void DrawTiles()
        {
            foreach(Tile t in Tiles)
            {
                if(t != null)
                {
                    GL.Color4(System.Drawing.Color.White);
                    GL.BindTexture(TextureTarget.Texture2D, Global.LoadTexture(t.TileTexture.Path, 1));
                    var i = (CellNum * CellSize) / 2;
                    GL.PushMatrix();
                    GL.Translate((t.Position.X * CellSize) - i, 0, (t.Position.Z * CellSize) - i);
                    var x = CellSize;
                    verts = new Vector3[8]
                    {
                        new Vector3(0, 0, 0), new Vector3(0, 0, 0),
                        new Vector3(x, 0, 0), new Vector3(1, 0, 0),
                        new Vector3(x, 0, x), new Vector3(1, 1, 0),
                        new Vector3(0, 0, x), new Vector3(0, 1, 0)
                    };

                    GL.EnableClientState(ArrayCap.VertexArray);

                    GL.EnableClientState(ArrayCap.TextureCoordArray);

                    GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
                    GL.BufferData<Vector3>(BufferTarget.ArrayBuffer, (IntPtr)(Vector3.SizeInBytes * CellNum), verts, BufferUsageHint.StaticDraw);
                    GL.BindBuffer(BufferTarget.ArrayBuffer, 0);

                    GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
                    GL.VertexPointer(3, VertexPointerType.Float, Vector3.SizeInBytes * 2, 0);
                    GL.TexCoordPointer(3, TexCoordPointerType.Float, Vector3.SizeInBytes * 2, Vector3.SizeInBytes);
                    GL.DrawArrays(PrimitiveType.Quads, 0, verts.Length / 2);
                    GL.Flush();
                    GL.PopMatrix();
                }
            }
        }

That method is called in OnRenderFrame, CellSize and CellNum tell me how big the tiles are supposed to be and how many there are each side of the grid. Even if I run say a 20 tile grid, my program is incredibly laggy.

Does any one know a more efficient way to render these tiles, or better yet, speed up my current method?


texts: How can I import an Excel file in an Unity WebGL game?

texts: Currently, we have a project that runs on Windows and uses an Excel spreadsheet to save/retrive some data/information. Now we want to build that project for WebGL. The problem is that file reading support is not available on the WebGL platform.  How do I solve this problem? Do I need to write a backend or there another way to use excel in WebGL platform even though the file reading API of the .NET framework is not supported on WebGL?


texts: How can I implement a simple "jump" action with three.js and/or Physijs?

texts:
Assume I have a simple Physijs object like this car.  How can I adapt something like this to "jump" (hydraulics ftw!) when pressing spacebar for instance?

I'm currently thinking applyCentralImpulse should come into play.


texts: What is the technical definition of "sprite batching?"

texts: Platform and language agnostically, how is sprite batching defined? It seems as though there are many different techniques for lessening the amount of work when drawing, and that they are often lumped with "batching". It occurs to me that there may not be a real answer, but perhaps someone here has found something I have not.


texts:
I'm using XNA 4 with Visual Studio 2010. I'm trying to create a simple 3D world with walls and doors in which the user to free to roam around.

A wall is just a rectangle which is currently being rendered with four vertices using triangle strips. But to create a door, I'd have to split it into three rectangles as shown in the figure.

Four quadrilaterals if I want to have the following door-style

It will become more complex to have multiple doors on the same wall or if I have windows.

Is there any shorter way to handle this? I am looking for something that will just make the wall transparent wherever I want.

I found a solution but facing a problem here


texts: How to show part of the world scaled to screen size?

texts:
I have a world size of 100x100
I want to map this world size to screen size using this mapTo function
function mapTo(pos, from, to) {
  let n = pos / from;
  return n * to;
}

Now I want to show only a portion of this world scaled up to the screen size, let's call it view size of 10x10 now how should I map this world size of screen size with regards to view size?
I want to show 10x10 world units fit the whole screen.
I've tried to do:
let aWorldPosition = [0, 0];

let worldSize = [100, 100];
let viewSize = [10, 10];
let screenSize = [20, 20];

let r = mapTo(aWorldPosition, worldSize, viewSize);
r = mapTo(r, viewSize, screenSize);

but that doesn't work.
Also I want to be able to move the view so I can show portions of the world.
I've tried this and seems to be working but I don't know if it's correct:
let r = mapTo(aWorldPosition, viewSize, screenSize);

Here viewSize is in world coordinates.


texts:
If you like developing flash games just for fun, why not make money through them?
There are different ways you can monetize your flash game:

In Game Ads: Some common examples:

Mochi Ads
gamejacket
ad4game
CPMStar
InviziAds

You can make money by helping online gaming companies test and evaluate new games. Many of those companies are seeking feedback and reviews of their newest games.
Find a sponsor and license your game. One of the quickest yet hardest ways to make money from the flash games you create is to find a website who is willing to sponsor them. With a single sponsorship, an individual can make anywhere from $1000-$7000 for a game.

What are the best ads from these sites?

If the game will be in social websites like Facebook and MySpace, will it still be useful to try other sites?

Are there any other ways to earn money from a Flash game?


texts:
I'm making a simple game, and one of the problems I encountered is the annoying delay when pressing a key continuously.

So basically, when I press (for a very long time) for example Up, my object will move 1 unit up, not move (for approx. 1 second), and then move continuously 1 unit up (without any delays).

Currently, I use this to move the object (SDL2):

while (SDL_PollEvent(&event))
{
    switch (event.type)
    {
    case SDL_KEYDOWN:
        switch (event.key.keysym.sym)
        {
        case SDLK_UP:
            //Move object 1 unit up
            break;
        //Other unrelated things omitted
        }
        break;
    //Omitted other cases
    }
}

What I would like to have is to remove the delay, so that the object can immediately move Up very quickly. Is there any way to do this?


texts:
For an assignment, I am required to implement an A* algorithm in order to find the shortest path between two object using different heuristics

null, this effectively becomes Dijkstra
Euclidean distance
Clustering

So I have successfully implemented the A* algorithm and the first two heuristics and they work wonderfully. However the third heuristic I am having trouble with. According to the text

  The cluster heuristicworks by grouping nodes together in clusters. The nodes in a cluster represent
  some region of the level that is highly interconnected. Clustering can be done automatically using
  graph clustering algorithms that are beyond the scope of this book

  When the heuristic is called in the game, if the start and goal nodes are in the same cluster, then
  Euclidean distance (or some other fallback) is used to provide a result. Otherwise, the estimate is
  looked up in the table.

I'm not one to give up on a challenge so I would like to implement some automatic clustering technique. I am lazy and I really don't feel like manually clustering nodes, I want it to be automated. So I have been doing research on clustering and I've come across this technique: Markov Cluster Algorithm(MCL)

Are there any good methods besides the one presented? I have searched the IEEE database for clustering techniques but I am not entirely sure if those are valid for the scope of my assignment. I'm not looking for any code but I would surely appreciate any guidance on the matter.

Edit: I should clarify what is required in the assignment for clustering.

  For the Cluster heuristic consider the nodes in each room to contain a cluster, and each
  corridor to contain a cluster. Using Dijkstra’s algorithm, between each pair of clusters
  compute the shortest distance between any two nodes (one from each cluster). Use
  these results between pairs of clusters to create a lookup table.

Furthermore this is the requirements for the level. Each convex polygon represents an obstacle. If I had to guess, there are 7 clusters in total


texts: UPDATED: Deserialise Nested JSON with JSON Utility Unity 5.4

texts:
I am trying to deserialise a JSON with Unity 5.4's JSON utility (here).

This is what my JSON looks like: {"series":[{,"points":[{"ts":"1473850836254","value":"11.27"},{"ts":"1473851256637","value":"6.44"}]}]}

I am trying to access the values in "points" by calling something like: data.series.points[0].ts

Void Start(){
IncomingData data = IncomingData.CreateFromJSON(jsonResponse.text); // **error 1**
print("Series point length" + data.series.points.Count);
print("Series point 0" + data.series.points[0].ts); // **error 2**
}

//----------------------------------------- classes -------------------------

[System.Serializable]
public class IncomingData
{
    public Series series;
    public static IncomingData CreateFromJSON(string json)
    {
        return JsonUtility.FromJson<IncomingData>(json);
     }
}

[System.Serializable]
public class Series
{
    public List<Points> points = new List<Points> { };
}

[System.Serializable]
public class Points
{
    public int ts;
    public int value;
}

Errors

1. keystr == NULL UnityEngine.JsonUtility:FromJson(String)

1. Unexpected node type. UnityEngine.JsonUtility:FromJson(String)

2. ArgumentOutOfRangeException: Argument is out of range. Parameter name: index

I think it has something to do with how I embed the classes within each other - I am not really good at OOP ...


texts: Button Press Detection not working while detecting collision

texts:
I am trying to make a sign that brings up a panel when you press Enter while the player is over the sign. The code I have written is:

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

public class SignScript : MonoBehaviour
{
    public GameObject Panel;

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Player")
        {
            UnityEngine.Debug.Log("Triggered1");
            if (Input.GetAxis("Submit") == 1)
            {
                UnityEngine.Debug.Log("Triggered2");
                if (Panel == false)
                {
                    Panel.SetActive(true);
                    UnityEngine.Debug.Log("Triggered3");
                }
            }
        }
    }
}

I added code that prints "Triggered1", "Triggered2", and "Triggered3" to the Debug Log when you reach certain parts of the code. When the player is over the sign and is pressing Enter, it should print "Triggered2". For some reason, it is not doing this. Does anyone know why?


texts: Reference counting with resource handles

texts:
I have implemented a resource handle and resource cache class.  The handle stores an integer id.  The cache stores a vector of objects e.g., Textures.  The handle id acts as an index into the cache asset vector.
I then have a third class which provides methods to get the object(Texture) associated with a given handle.  The class also stores a map of filename, handle for previously loaded objects.
I am trying to add reference counting to the system.  At the moment I store a std::size_t* ref_count in Resource_handle and have the following constructor/destructor/assignment operators:
Resource_handle() : id(0), verifier(0), ref_count(new std::size_t(1)) {}

Resource_handle(const Resource_handle<T>& handle)
: id(handle.id), verifier(handle.verifier), ref_count(handle.ref_count) { ++*ref_count; }

template<typename T>
Resource_handle<T>& Resource_handle<T>::operator=(const Resource_handle<T>& rhs)
{
    ++*rhs.ref_count;
    if (--*ref_count == 0) {
        delete ref_count;
        // reset handle
    }
    id = rhs.id;
    verifier = rhs.verifier;
    return *this;
}

template<typename T>
Resource_handle<T>::~Resource_handle() // reference handling 515 C++ Primer
{
    if (--*ref_count == 0) {
        delete ref_count;
        // unload resource in handle
        // reset handle?
        reset();
    }
}

The above code is not complete but I have two problems I'm aware of so far.

The objects in the Resource_cache vector are not allocated on the heap and Resource_handle has no pointer to them to delete them.

The reference count ref_count is actually counting copies of a particular handle rather than of objects in the cache vector.

How can I resolve these two issues?  I'm wondering if the reference handling should be done in the cache class instead?  However the cache would have no knowledge of how many handles refer to a particular object in its object vector.
Many thanks.
Edit: I did consider std::shared_ptr<T> however research lead me to using handles for the ability to reload resources, easier serialisation and the more lightweight approach.


texts: How can I use the animation transitions?

texts:
So I want to make my animation transitions smooth, thats why I made transitions on the animator, but how can I activate them if I use trigger paramaters???
Heres the code:

public float speed = 0.3f;
public float sprintSpeed = 2.5f;
private Rigidbody rigidB;
private float midJump = 1f;
public float rotSpeed = 2;
Animator anim;

void Start()
{
    rigidB = GetComponent<Rigidbody>();
    anim = GetComponent<Animator>();
}
void Update()
{

    //Character rotation with A and D

    var z = Input.GetAxis("Horizontal") * rotSpeed;

    //Character movement with W and S

    var y = Input.GetAxis("Vertical") * speed;

    //Character animations

    if (Input.GetKey(KeyCode.RightShift))
        y = y * sprintSpeed;

    if (Input.GetKey(KeyCode.RightShift) && y > 0.31)
        anim.Play("Sprint");

    if (y < 0.001)
        anim.Play("Idle");

    if (y > 0.001 && y < 0.31)
        anim.Play("Run");

    transform.Translate(0, -y, 0);
    transform.Rotate(0, 0, -z);

    //Character Jump

    if (midJump == 1 && Input.GetKeyDown(KeyCode.Space))
    {
        rigidB.velocity = new Vector3(0, 45, 0);
        midJump = 2;

    }
    else if (rigidB.velocity.y == 0)
        midJump = 1;

}


texts:
I have been trying to make a game, but mask collision doesn't seem to work. Here is my code:

    class Player(pg.sprite.Sprite):
            def ___init__(self, game, x, y, lvl):
                    self.group = game.all_sprites
                    pg.sprite.Sprite.__init__(self.groups)
                    #nothing else important

            def update(self):
                    self.mask = pg.mask.from_surface(self.image)
                    #check if hits
                    hits = pg.sprite.spritecollide(self, self.game.kill, False, pg.sprite.collide_mask)
                    if hits:
                            #stops game
                            self.game.playing = False

    class Kill(pg.sprite.Sprite):
            def ___init__(self, game, x, y, lvl):
                    self.group = game.kill
                    pg.sprite.Sprite.__init__(self.groups)
            def update(self):
                    self.mask = pg.mask.from_surface(self.image)

The problem is that the game sets self.game.playing to False even before the pixels collide.


texts: How do I render endless terrain using TerrainGrid?

texts:
I have started to learn game development, using the jMonkey engine. I am able to create single tile of terrain using TerrainQuad, but in the next step, I'm stuck at making it infinite. I have gone through the wiki and a tutorial, and want to use the TerrainGrid class, but my code does not seem to work. I have looked around on the web, and searched other forums, but cannot find any other code example to help.

I believe in the below code; ImageTileLoader returns an image, which is the height map for that tile. I have modified it to return the same image, every time, but all I see is a black window. The Namer method is not even called.

terrain = new TerrainGrid("terrain", patchSize, 513,
    new ImageTileLoader(assetManager, new Namer() {
        public String getName(int x, int y) {
            //return "Scenes/TerrainMountains/terrain_" + x + "_" + y + ".png";
            System.out.println("X = " + x + ", Y = " + y);
            return "Textures/heightmap.png";
        }
    }));

This is the result, when I use TerrainQuad:

This is my full code:

// Sample 10 - How to create fast-rendering terrains from heightmaps, and how to
// use texture splatting to make the terrain look good.
public class HelloTerrain extends SimpleApplication {
    private TerrainQuad terrain;
    Material mat_terrain;
    private float grassScale = 64;
    private float dirtScale = 32;
    private float rockScale = 64;

    public static void main(String[] args) {
        HelloTerrain app = new HelloTerrain();
        app.start();
    }

    private FractalSum base;
    private PerturbFilter perturb;
    private OptimizedErode therm;
    private SmoothFilter smooth;
    private IterativeFilter iterate;

    @Override
    public void simpleInitApp() {
        flyCam.setMoveSpeed(200);

        initMaterial();

        AbstractHeightMap heightmap = null;
        Texture heightMapImage = assetManager.loadTexture("Textures/heightmap.png");
        heightmap = new ImageBasedHeightMap(heightMapImage.getImage());
        heightmap.load();

        int patchSize = 65;

        terrain = new TerrainGrid("terrain", patchSize, 513,
            new ImageTileLoader(assetManager, new Namer() {
            public String getName(int x, int y) {
                System.out.println("X = " + x + ", Y = " + y);
                return "Textures/heightmap.png";
                // set to return the same height map image.
            }
        }));

        terrain.setMaterial(mat_terrain);
        terrain.setLocalTranslation(0,-100, 0);
        terrain.setLocalScale(2f, 1f, 2f);
        rootNode.attachChild(terrain);

        TerrainLodControl control = new TerrainLodControl(terrain, getCamera());
        terrain.addControl(control);
    }

    public void initMaterial() {
        // TERRAIN TEXTURE material
        this.mat_terrain = new Material(this.assetManager,
            "Common/MatDefs/Terrain/HeightBasedTerrain.j3md");

        // GRASS texture
        Texture grass = this.assetManager.loadTexture("Textures/white.png");
        grass.setWrap(WrapMode.Repeat);
        this.mat_terrain.setTexture("region1ColorMap", grass);
        this.mat_terrain.setVector3("region1", new Vector3f(-10, 0, this.grassScale));

        // DIRT texture
        Texture dirt = this.assetManager.loadTexture("Textures/white.png");
        dirt.setWrap(WrapMode.Repeat);
        this.mat_terrain.setTexture("region2ColorMap", dirt);
        this.mat_terrain.setVector3("region2", new Vector3f(0, 900, this.dirtScale));

        Texture building = this.assetManager.loadTexture("Textures/building.png");
        building.setWrap(WrapMode.Repeat);

        this.mat_terrain.setTexture("slopeColorMap", building);
        this.mat_terrain.setFloat("slopeTileFactor", 32);
        this.mat_terrain.setFloat("terrainSize", 513);
    }
}


texts: Algorithm for constructing the corners of a regular, n-sided polygon

texts:
I've googled this using a lot of keyword combinations, but to my great surprise I could not find an algorithm for constructing a regular, n-sided polygon into a given circle, i.e., finding the coordinates for the n corner points. All I could find were instructions how to do it by physical compass and straightedge, or interactive browser plug-ins without source.

So where could I find such an algorithm?


texts: How to change color of text in canvas in phaser.js?

texts:
I want to change the text color in my game that is build in phaser.js. But i have no idea how to do this, because i am not a coder.

Can somebody help me to change the color of my game text?

My Game is http://games.eyebraingym.com/slotreading/

I want to change the color on the canvas where the heading is 'Slot Reading'.


texts: Game Modeling good practice regarding quads and ngons

texts:
I'm asking myself if using quads is really the better practice instead of using ngons (for flat surfaces!) when it comes to game modeling.

I often read this and saw models that look like this (96 tris!).

But I can't understand why this should be preferred instead of this model using ngons (60 tris!)

Are there reasons why the quad variant with more tris should be preferred also for a final game model (that also does not use displacement mapping for example) or is the n-gon actually preferred in such cases because of the lower triangle count?

Because it came up in the discussion: This should be of course only valid for static objects that do not deform, my question came up because I saw that models which are most likely not supposed to deform are modelled using the additional quads and I'm wondering if there's really any benefit of doing it (I just see the disadvantage of additional triangles so far).


texts: How do I extract a translation vector from a dual quaternion?

texts:
I'm trying to do some things with rigid body dynamics using dual quaternions (these are not the same thing as normal quaternions!) and I'm so close to getting things to work. The problem I'm having is extracting the translation vector from a dual quaternion. After looking some things up I found that if I have an array representing a dual quaternion like this one:

    JOINT[0,0]
    JOINT[0,1]
    JOINT[0,2]
    ...
    JOINT[0,7]

Then the translation vector part is given by 2*(dual)'real where (dual)' is the conjugate quaternion of the dual part of the dual quaternion. This is what it looks like all typed out:

   x = 2*(-JOINT[0,4]*JOINT[0,1] + JOINT[0,5]*JOINT[0,0] - JOINT[0,6]*JOINT[0,3] + JOINT[0,7]*JOINT[0,2]);
   y = 2*(-JOINT[0,4]*JOINT[0,2] + JOINT[0,5]*JOINT[0,3] + JOINT[0,6]*JOINT[0,0] - JOINT[0,7]*JOINT[0,1]);
   z = 2*(-JOINT[0,4]*JOINT[0,3] - JOINT[0,5]*JOINT[0,2] + JOINT[0,6]*JOINT[0,1] + JOINT[0,7]*JOINT[0,0]);

However this isn't quite right. If I have an object not located at the origin it will rotate fine on the x and z axes but will freak out if I try to rotate it on the y axis. And if I rotate an object and then move it it will not move correctly. Anyways after a bunch of trouble shooting I'm pretty sure I am not extracting the translation portion of the dual quaternion correctly so I was hoping someone could tell me what I'm doing wrong.

@Christian Rau
Thanks. You're right it was 2*d*r'. I don't suppose that you also know how to combine dual quaternions do you? I've tried multiplying two together (using the convention Q1*Q2 = r1*r1 + e(r1*d2 + r2*d1) where r is the real part and d is the dual part). I should probably explain that what I'm trying to do is combine a dual quaternion that describes and object's current position and orientation with one that describes it's change in position and orientation in order to find a dual quaternion that describes it's position and orientation after the change. However right now I can't get it to come up with the correct translation after multiplying the two together (I've tried both orders, Q1*Q2 and Q2*Q1).

@Christian Rau
I meant to say Q1*Q2 = r1*r1 + e(r1*d2 + d1*r2) which is how I've been multiplying them together so far. The object that I'm displacing is sort of behaving correctly. It rotates relative to its own center of mass but as it rotates the axis of rotation changes. For instance if I rotate it on its z axis its x and y axes will rotate with it. I can get it to move only relative to its own axes. So it will move along its x axis If I want it to but if its x axis is no longer parallel to the global x axis it isn't doing much for me.


texts: Implementing a switch statement based on user input

texts:
I'm trying to delay the time it takes for the main menu screen to pop up after a user has won / lost a match. As it stands, the game immediately displays a message stating "you won / lost" and waits for 6 seconds before loading the menu screen.

I would also like players to have the ability to press a key to advance to the menu screen immediately but thus far my switch statement doesn't seem to do the trick. I've included the switch statement, along with my (theoretical) inputs. What could I be doing wrong here?

if (gamestate == GameStates.End)
                    switch (input.IsMenuDown(ControllingPlayer))
                    {
                        case true:
                            ScreenManager.AddScreen(new MainMenuScreen(), null); // Draws the MainMenuScreen
                            break;

                        case false:
                            if (screenLoadDelay > 0)
                            {
                                screenLoadDelay -= gameTime.ElapsedGameTime.TotalSeconds;
                            }
                            ScreenManager.AddScreen(new MainMenuScreen(), null); // Draws the MainMenuScreen
                            break;
                    }

     /// <summary>
    /// Checks for a "menu down" input action.
    /// The controllingPlayer parameter specifies which player to read
    /// input for. If this is null, it will accept input from any player.
    /// </summary>
    public bool IsMenuDown(PlayerIndex? controllingPlayer)
    {
        PlayerIndex playerIndex;

        return IsNewKeyPress(Keys.Down, controllingPlayer, out playerIndex)
               || IsNewButtonPress(Buttons.DPadDown, controllingPlayer, out playerIndex)
               || IsNewButtonPress(Buttons.LeftThumbstickDown, controllingPlayer, out playerIndex);
    }


texts:
I have a game where the user controls a box to collect falling balls. However, very often the balls will just fall through the walls of the box and be flung away. What could be causing the balls to do that?

Here is a video of the issue.

Here's how I'm creating the box and the balls:

//BOX CODE

private Body pbox() {

    pbdef = new BodyDef();
    PolygonShape shape=new PolygonShape();
    pbdef.type=BodyType.StaticBody;
    pbdef.position.set(Gdx.graphics.getWidth()/2,100);
    Body body1=world.createBody(pbdef);
    FixtureDef fdef = new FixtureDef();
    shape.setAsBox(30, 5);
    fdef.shape=shape;
    fdef.density=1;
    fdef.friction=0.5f;
    body1.createFixture(fdef);
    //
    shape.setAsBox(5, 20,new Vector2(-25,15),0);
    fdef.shape=shape;
    fdef.density=1;
    fdef.friction=0.5f;
    body1.createFixture(fdef);
    fdef = new FixtureDef();
    //
    shape.setAsBox(5, 20,new Vector2(25,15),0);
    fdef.shape=shape;
    fdef.density=1;
    fdef.friction=0.5f;
    body1.createFixture(fdef);
    body1.setGravityScale(-3);
    body1.setBullet(true);
    return body1;

}
//BALLS CODE

private void spawner() {

    bbdef= new BodyDef();
    FixtureDef fdef = new FixtureDef();
    CircleShape circle = new CircleShape();
    bbdef.type=BodyType.DynamicBody;
    bbdef.position.set(Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight());
    bbody = world.createBody(bbdef);
    circle.setRadius(5);
    fdef.shape=circle;
    fdef.density=0;
    fdef.friction=0;
    bbody.createFixture(fdef).setUserData("ball");
    bbody.setBullet(true);

}


texts: 3ds Max Skeleton Import into Unreal Engine Fail

texts:
I tried following the "Introduction to UE4 Animation and Rigging Tools" tutorial with maya but I dislike maya and don't under stand it so I tried importing the skeleton from the "3rd Person Game with Blueprints" tutorial into 3ds max and hoping I could just edit the mesh because I want about the same skeleton.

So I imported it and just made a basic mesh to test, Then removed the old mesh

Now I did it like this hoping I could use the existing animations for the original but when I try to play an animation with it in unreal engine 4.7.3 it says it does have any with the same skeleton, then when I tested it trying to ragdoll it stays rigid and just falls over.

Please help, am I importing it wrong am I missing a step? Why doesn't it work?


texts: How to handle edge cases for a cell divided multiplayer world?

texts:
The most common practice that I read about for overcoming floating point precision in video games with large worlds is by dividing the world into cells and load it with player's position and shift origin of objects with respect to player.

However this seems to be only valid for single-player games. As soon as you change to multiplayer with authoritative server scenario a lot of anomalies
arises.

Since a authoritative server has to keep track of all of the world its not possible to base the origin off a single player

For a object that is halfway through two or more cell's co-ordinate system. which cell's part should it be ? and how should it react to it?

There seems to be extremely little to no information about supporting such worlds for multiplayer which are larger than what a common origin can support with enough precision.

Can anyone shed some light on the topic ?


texts: Box2d RopeJoint bug - fix or alternative solution?

texts:
What I am trying to do is to create rope game. Below you can find a movie how it looks like now.

https://youtu.be/QTULCGNF70I

I am using RopeJoint and I am reducing maxLength each frame to be able to accelerate. Everything seems fine, but the problem appears for bubble kind of ball. I realized that shortening rope does not increase balls velocity. For example if I throw the rope fully vertical and the only "force" is from shortening the rope, the velocity is 0,0. Seems like, body movement is not simulated?

After I let the rope go the momentum is lost. The bubble can fly, but the factor from rope shortening is ignored.

I don't know if you understand what I mean. The movie should clarify it better.

Workarounds I tried:

Good idea was to use prismaticJoint, but the rotation is fixed, so it
doesn't work. I couldn't swing
Another idea was to use wheelJoint and make use of it's frequency
parameter. However here there's a problem that rope becomes rubber.
Swing feeling is bad, when it can extend more than initial length, it
should always only shorten.

Solutions I see, but they are not available

RopeJoint which keeps body momentum from rope shortening
PrismaticJoint without fixed rotation
WheelJoint with possibility to set max length or create the rope with it's max length, not the rest position.


texts:
I am looking for a way to move my scene so that when I translate forward/back/left right it moves directly up/down/left/right on the screen.  Currently it does do that until I rotate (by anything other than 360...).  After rotation the up/down/left/right moves in the direction of the rotation.  I need it to move directly up/down/left/right on screen.  I've been racking my brains trying all kinds of different matrix rotations and multiplication but I can't get it.  MOST IMPORTANTLY - I need it to maintain a single rotation axis of 0,0,0 so the centre of rotation is always near the middle of the screen regardless of how far I scroll.  I can easily rotate on the centre of the scene itself and have it translate how I want (translate to co-ord, rotate, translate back, go to position) but I need that axis to remain fixed.  Otherwise the centre of rotation could be somewhere way off-screen.

Fig 1. Shows the starting position of the model(scene).
Fig 2. The modelview is rotated 45deg.
Fig 3. Decrementing the z-value causes the model to move out along z - which I do not want.
Fig 4 I need the model to move straight back (between z and x).

I have tried using sin / cos rule in an attempt to translate the vertices back along the arc between the undesired position (Fig 3) and the desired one (Fig 4) but the math is off and the process is messy.  I just know there has to be a clean/simple solution out there.
I am coding this in Java (JOGL) and passing modelview and projection matrices to a vertex shader.
Also, I am not using deprecated functions (no begin/end/glRotate etc).

Does anyone know of a matrix multiplication that will accomplish this?


texts:
Currently I am working on a 3D visualization app. A requirement of my app is that host's graphics card supports Shader Model 3. How can I check for Shader Model 3 support?

I know that these versions are supposed to support these models:

DirectX 8.0 - Shader Model 1.0 & 1.1
DirectX 8.0a - Shader Model 1.3
DirectX 8.1 - Shader Model 1.4
DirectX 9.0 - Shader Model 2.0
DirectX 9.0a - Shader Model 2.0a
DirectX 9.0b - Shader Model 2.0b
DirectX 9.0c - Shader Model 3.0
DirectX 10.0* - Shader Model 4.0
DirectX 10.1* - Shader Model 4.1
DirectX 11.0* - Shader Model 5.0

But some graphic hardware doesn't support Shader Model 3.0 even with the proper DirectX version. So I want to determine it by checking the hardware not just the DirectX version.


texts: How to make walls opaque in PuzzleScript

texts:
On the PuzzleScript home page, there is an example of an enemy (Eyeball) which, when you (Player) are directly in its line of sight, will move one square closer to you, using the rule

[ Eyeball | ... | Player ] -> [ > Eyeball | ... | Player ]

However, the Eyeball will walk towards Player even if it shouldn't be able to see you, for instance if there is a wall in the way. This is apparent in a level like

#########
#....O..#
#.......#
#########
#.......#
#..P....#
#########

where, if Player passes below Eyeball, Eyeball will move one square down.

How do I make it so that the enemy can't see me through walls?

Inserting no Wall into the rule above doesn't work, as that doesn't tell ... to only match wall-free tiles, but rather checks whether there is at least one non-wall tile between Eyeball and Player. And adding the rule

[ > Eyeball | ... | Wall | ... | Player ] -> [ Eyeball | ... | Wall | ... | Player ]

in an attempt to correct the movement doesn't work as two ellipses in a single match pattern isn't allowed.


texts: I need to access a variable from another script in Unity

texts:
I have been trying to aimlessly make a unity game around a 3d aim trainer and I have been trying to set up the targets that pop up. For now, I just wanted to create targets that pop up once every second at a maximum of 3 targets at one time ever. I have already set up the random spawn of the targets and the removal of them with the help of raycast shooting and made a max of 3 targets, however, to make the max of 3 targets I used an integer with a simple targetCount += 1 and the deletion of the target is being done on a different script as seen below. My problem is making the targets respawn once being shot after spawning the first 3 targets. I tried to use getComponent to reach the targetCount variable in my Target code to just simply targetCount -= 1 every time I delete a target so that as long as the variable doesn't reach 3, it will continue to spawn targets however I was having some troubles.
Please let me know if you have any ideas
This is my target spawning code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GenerateEnemies : MonoBehaviour
{
    public GameObject theTarget;
    public float xPos;
    public float yPos;
    public int targetCount = 0;

    void Start(){
        StartCoroutine(TargetDrop());
    }

    IEnumerator TargetDrop()
    {
        while (targetCount < 3)
        {
            xPos = Random.Range(-6, 11.5f);
            yPos = Random.Range(2.4f, 9);
            Instantiate(theTarget, new Vector3(xPos, yPos, 13.5f), Quaternion.identity);
            yield return new WaitForSeconds(1);
            targetCount += 1;
        }
    }
}

And this is my Code attached to my target
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Target : MonoBehaviour, IDamageable
{
    [SerializeField] private TargetStats targetStats;

    private int currentHealth;
    /*
    public GenerateEnemies generateEnemies;

    private void Awake()
    {
        generateEnemies = GetComponent<GenerateEnemies>();
    }
    */
    private void Start()
    {
        currentHealth = targetStats.maxHealth;
    }

    public void DealDamage(int damage)
    {
        currentHealth -= damage;
        CheckIfDead();
    }

    private void CheckIfDead()
    {
        if(currentHealth <= 0)
        {
            Destroy(gameObject);
            /*GenerateEnemies.targetCount -= 1;*/
        }
    }
}


texts: In a game such as Star Wars Galaxies, Planetside, and Warcraft how would server-side collision/terrain navigation work?

texts:
I'm trying to learn some advanced topics in multiplayer networking for fun and education, specifically how server-side collision/terrain navigation works in MMOs and/or any online game.

Personally, I have a nice little test server where I can move two units around a plane and they can collide with one another, no big issue, then I started to think about real terrain. Features such as mountains, rivers, cliffs, etc.

I know that a map can be chunked out and I could use spatial partitioning to narrow my collision detection down to small chunks, however, I'm a bit stumped if the server and client would be running the exact same physics calculations (gravity, physics, etc).

I'm assuming the server would need to have an exact duplicate of the map-data that the player is seeing client side to perform the appropriate collision/terrain calculations to make sure nothing nefarious is going on - such as a way to prevent map hacks and hiding in walls/mountains.

This is all assuming the player has direct control over the movement/direction of their character ala WoW/SWG/Planetside, and not like a MOBA/RTS game.

My question boils down to this (as I know implementation details vary) what does the server-side need in order to properly keep track of players in a varied terrain world?


texts:
I'm piecing together the beginnings of an extremely basic engine which will let me draw arbitrary objects (SceneObject). I've got to the point where I'm creating a few sensible sounding classes, but as this is my first outing into game engines, I've got the feeling I'm overlooking things. I'm familiar with compartmentalising larger portions of the code so that individual sub-systems don't overly interact with each other, but I'm thinking more of the low-level stuff, starting from vertices working up.

So if I have a Vertex class, I can combine a list of those with a list of indices to make a Mesh class. How does the engine determine identical meshes for objects? Or is that left to the level designer? Once we have a Mesh, that can be contained in the SceneObject class. And a list of SceneObject can be placed into the Scene to be drawn.

Right now I'm only using OpenGL, but I'm aware that I don't want to be tying OpenGL calls right in to base classes (such as updating the vertices in the Mesh, I don't want to be calling glBufferData etc).

Are there any good resources that discuss these issues? Are there any "common" heirachies which should be used?


texts: In XNA, how should I organize content shared between projects?

texts:
I have an XNA library using several custom effects.  They need to be accessed by:

a content pipeline project (models are built with the effect), and
projects that use my game library (they should be able to load a standalone instance of the effect).

Where should I put the .fx files for the custom effects?  How do I access them from separate projects?


texts:
Lets suppose that I have a large, 2048 by 2048 pixel texture uploaded to the GPU.

I'd like to occasionally be able to edit parts of it, e.g. a 64x64 area.

Re-uploading the entire texture would be a huge waste of resources so is there any other way of doing this?


texts:
I'm trying to generate irradiance map with spherical harmonics coefficients.

I have a function SH(l, m, N) that evaluate the basis function for specified band (l, m) and normalized direction N.

The problem is when I project the irradiance map onto a sphere it has seams and wrong direction of lights.

I knew it has to be caused by wrong direction of normal N.

This is how I determine the normal for each cube face.

vec2 getUV(in int x, in int y, in int width, in int height) {
    float w = float(width);
    float h = float(height);
    float xx = float(x);
    float yy = float(y);
    return vec2((2.0*xx/(w-1.0))-1.0, (2.0*yy/(h-1.0))-1.0);
}

vec3 getNormal(in vec2 uv) {

    float u = uv.x;
    float v = uv.y;
    vec3 n;

    if (u_side == 0) n = vec3(0,0,1)*u + vec3(0,1,0)*v + vec3(1,0,0); // x+
    if (u_side == 1) n = vec3(0,0,-1)*u + vec3(0,1,0)*v + vec3(-1,0,0); // x-
    if (u_side == 2) n = vec3(1,0,0)*u + vec3(0,0,1)*v + vec3(0,1,0); // y+
    if (u_side == 3) n = vec3(1,0,0)*u + vec3(0,0,-1)*v + vec3(0,-1,0); // y-
    if (u_side == 4) n = vec3(-1,0,0)*u + vec3(0,1,0)*v + vec3(0,0,1); // z+
    if (u_side == 5) n = vec3(1,0,0)*u + vec3(0,1,0)*v + vec3(0,0,-1); // z-

    return normalize(n);
}

void getIrMap() {
    int x = int(gl_FragCoord.x);
    int y = int(gl_FragCoord.y);

    vec2 uv = getUV(x, y, IRMAP_WIDTH, IRMAP_HEIGHT);
    vec3 N = getNormal(uv);
    vec3 E = vec3(0);

    // band factor
    const float bf1 = 2.0 / 3.0;
    const float bf2 = 1.0 / 4.0;

    E += u_coeff0.xyz * SH(0, 0, N);
    E += u_coeff1.xyz * SH(1, -1, N) * bf1;
    E += u_coeff2.xyz * SH(1, 0, N)  * bf1;
    E += u_coeff3.xyz * SH(1, 1, N)  * bf1;
    E += u_coeff4.xyz * SH(2, -2, N) * bf2;
    E += u_coeff5.xyz * SH(2, -1, N) * bf2;
    E += u_coeff6.xyz * SH(2, 0, N)  * bf2;
    E += u_coeff7.xyz * SH(2, 1, N)  * bf2;
    E += u_coeff8.xyz * SH(2, 2, N)  * bf2;

    gl_FragColor = vec4(E, 1.0);
}

From my understanding SH() expects direction in spherical xyz coordinate. So I mapped the normal from right hand coordinate system to spherical coordinate with:

vec3 n = vec3(N.z, -N.x, N.y);

Still weird results.

vec3 n = N.zxy;

Doesn't work also.

I also tried arranging normal in getNormal() with spherical coordinate in mind. The seams are gone, but the lights still off by about 45 to 90 degrees.

For this test I used a precalculated coefficients of Grace Cathedral from the paper 'An Efficient Representation for Irradiance Environment Maps'.

What gives?

EDIT
The SH() take (x, y, z) = (sinθ cos φ, sin θ sin φ, cos θ). With xyz mapped to world -z,-x,y respectively.


texts: How do I implement a sparse voxel octree?

texts:
I've been working on a voxel engine and I want to implement sparse voxel storage. As I understand it, it works a bit differently from a regular octree and has some neat performance increasing "tricks". But I could not find a good explanation with readable source or even pseudocode about how to build them.

I saw lots of references to this page but their primary target is GPU, and there is no real source walkthrough there, just the basic idea.


texts:
When I am using the same spritebatch to draw texture and calling shaperenderer inside it, it is kind of misbehaving, like texture is not getting drawn or font is not getting drawn, Why is it happening?

For example(pseusdo code):

spritebatch.begin()
draw texture
shaperenderer.begin()
shaperenderer.end()
spritebatch.end()

but when I use it with different ends and begins it is drawing the way I want it to, but drawing so many spritebatches is reducing the performance of the phone.Reason I have to draw many spritebatches is because I want some texture to overlap on on some other shaperender's function.Any suggestions?


texts: Destroying a networked projectile and creating a client side visual for all clients in Unity?

texts:
I'm making a shooter in Unity with UNET, and of course I handle projectile (like arrows) collision on the server.

The arrows are Networked rigidbodies with NetworkBehaviours, and I would like to spawn a Non-networked, eye candy like client side prefab at the collision point.

Current solution:

protected override void OnServerFixedUpdate()
{
    var distanceSincePreviousFrame = Vector3.Distance(positionAtPreviousFrame, rb.position);
    Collider collider;
    Vector3 impactPoint;
    if(CheckForImpactInNextFrame(distanceSincePreviousFrame, out collider, out impactPoint))
    {
        transform.position = impactPoint;
        DoImpactEffect(collider);
        GetComponent<Rigidbody>().isKinematic = true;
        NetworkServer.Destroy(gameObject);
    }
    positionAtPreviousFrame = rb.position;
}
void OnDestroy()
{
    var go = Instantiate(ClientSidePrefab, transform.position, transform.rotation);
}

The rigidbody flies on the server (rigidbody synced), and CheckForImpactNextFrame checks collision by raycasting. (needed so projectiles won't go through things due to simulation errors).
If it collides, then it does its impact effect, then destroys itself on the network.
Clients instantiate a client side, non networked prefab for visuals when the networked projectile is destroyed.

At the server side this works well, "client side arrow" is instantiated at the impact position,

but at clients, it's instantiated at its previous position, because the transform.position = impactPoint; in the if isn't synced before it is destroyed on the clients.

How could I make those client side visuals appear at the correct position?

Could I call a "force sync" before destroying?

I can't call an RpcCreateVisuals(position) method, because the entity may be destroyed on the client when the Rpc message arrives. (because the destroy message was faster.)

I could call an "always alive" object's Rpc, like a ProjectileManager's method, and I think that it will always arrive, because destroying the projectile has no effect on it. But it feels hacky, non OOP. Doesn't it?

How should I solve this solution? What is the common approach for this problem?

The same problem described by someone else: https://answers.unity.com/questions/1636182/client-objects-not-traveling-same-distance-as-on-s.html

Maybe I could disable them, and subscribe them to a "GarbageCollector" system, which destroys them only after a delay? Is this a well designed solution?


texts: How to distort an image using perlin noise?

texts:
I'm trying to generate a 2D map and currently I'm doing so by the use of voronoi diagram. The problem I found is that all biomes have really hard edges and I would like to smooth them out a bit.

Initially I was thinking smoothing out voronoi curves, which appears to be far more complex as I imagined. Then I thought about perlin distorion, which seems far more doable. Although, I'm not sure what is the best way to implement this.

This is the function I use to generate a voronoi diagram:

void Generate()
{
    Vector2Int[] centroids = new Vector2Int[regions.Length];
    Color[] regColors = new Color[regions.Length];
    for (int i = 0; i < regions.Length; i++)
    {
        centroids[i] = new Vector2Int(Rand.Range(0, map), Rand.Range(0, map));
        regColors[i] = regions[i].color;
    }
    Color[] colors = new Color[map * map];
    for (int x = 0; x < map; x++)
    {
        for (int y = 0; y < map; y++)
        {
            int index = x * map + y;
            colors[index] = regColors[GetClosestCentroidIndex(new Vector2Int(x, y), centroids)];
        }
    }
}
int GetClosestCentroidIndex(Vector2Int pixelPos, Vector2Int[] centroids)
{
    float smallestDst = float.MaxValue;
    int index = 0;
    for (int i = 0; i < centroids.Length; i++)
    {
        if (Vector2.Distance(pixelPos, centroids[i]) < smallestDst)
        {
            smallestDst = Vector2.Distance(pixelPos, centroids[i]);
            index = i;
        }
    }
    return index;
}

While doing some research I stumbled upon this website, which shows the exact result I'm trying to achieve:
https://observablehq.com/@kerryrodden/image-distortion-with-perlin-noise

Can someone help me with this problem? Thank you

[Solved]

By the help of the user DMGregory, the map is now looking much better!
This is the new voronoi diagram, after the distortion had been applied.

Currently, I'm using these settings, but I will probably tweak them later.
Scale: 10
Octave Count: 1
Amplitude: 4
Lacunarity: 1
Persistence: 1
And for the seed, currently, I'm using just a randomly generated seed.


texts: How To Find Child Object and set is own criteria/condition?

texts:
I am Making 2D Game.

I Apply a Two Tag On Multiple Child Game Object..

Crate A Empty Game Object and Put Script Obstacle.cs and Rigidbody2d.

Child GameObject -> Static OnTriggerEnter2D

Obstacle.cs

    void Start()
    {
        foreach (Transform item in GetComponentsInChildren<Transform>())
        {
            if (item.tag == "someobstacleslow")  //7 child game object find successfully
            {
                Debug.Log("someobstacleslow:" + item.tag);
            }

            if (item.tag == "someobstaclefast") //4 child game object find successfully
            {
                Debug.Log("movefastobstacle:" + item.tag);

            }
     }

Referance:

https://imgur.com/a/ozcJcO4

I want to some obstacleslow is going slow and someobstaclefast is going fast but nothing happens.

Output: all obstacle going very fasy?? what i miss my programme??

But Child GameObject not working its own condition?

Obstacle.cs

   float speed = 2.5f;                             //normal speed

    float movefastobjectspeed = 3f;                //fast spped

    void Update()
    {
        goTopToDown();
    }

    void goTopToDown()
    {
            foreach (Transform item in GetComponentsInChildren<Transform>())
            {
                if (item.tag == "someobstacleslow")   //issue here
                {
                    //move top to down object normal speed
                    transform.position += Vector3.down * speed * Time.deltaTime;

                    Debug.Log("GameObject obstacle object:" + item.tag);
                    Debug.Log("inside obstacle object");

                }

                if (item.tag == "someobstaclefast") // issue here
                {
                    //move top to down object fast speed
                    transform.position += Vector3.down * movefastobjectspeed * Time.deltaTime;

                    Debug.Log("GameObject movefast object:" + item.tag);
                    Debug.Log("inside movefast object");
                }

            }
    }

When My Obstacle Touch My Player then Ontrigger2d Is fire

Obstacle.cs

 void OnTriggerEnter2D(Collider2D other)
    {
        foreach (Transform child in GetComponentsInChildren<Transform>())
        {
            if (child.tag == "someobstacleslow" || child.tag == "someobstaclefast")
            {
                Debug.Log("chiildtag:" + child.tag);
                gameovertext.SetActive(true);

                StartCoroutine(gameover());
                Debug.Log("inside triggerfire");
            }
        }
    }

But Issue Is all obstacle going very fast(See in referance).I want to some obstacleslow is going slow and someobstaclefast is going fast but nothing happens.??help


texts: Is creating a separate thread for each game session a bad idea?

texts:
I'm currently working on iocp game server. My game is just like diablo3 basically. 1~4 players join a separate session.

I did basic iocp preparations and now I'm working on game session class. The reason why I'm stuck right now is that I'm not sure if I should create a separate thread for each game session. This concept is the first idea that I came up with but I can't come up with other ideas to avoid creating so many threads for sessions when there are so many game sessions.

So here's my question.

Should I create a separate game logic loop(thread) for each game session? Because that sounds so inefficient when it comes to the situation where only one player joins each session.
If there are some other ways to design the server, please let me know what I should look for to study.

Thanks for your help in advance and sorry for my bad English.


texts: Why does my ID3DXSprite appear to be incorrectly scaled?

texts:
I am using D3D9 for rendering some simple things (a movie) as the backmost layer, then on top of that some text messages, and now wanted to add some buttons to that.

Before adding the buttons everything seemed to have worked fine, and I was using a ID3DXSprite for the text as well (ID3DXFont), now I am loading some graphics for the buttons, but they seem to be scaled to something like 1.2 times their original size.

In my test window I centered the graphic, but it being too big it just doesnt fit well, for example the client area is 640x360, the graphic is 440, so I expect 100 pixel on left and right, left side is fine [I took screenshot and "counted" the pixels in photoshop], but on the right there is only about 20 pixels)

My rendering code is very simple (I am omitting error checks, et cetera, for brevity)

// initially viewport was set to width/height of client area

// clear device
m_d3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_STENCIL|D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0,0,0,0), 1.0f, 0 );

// begin scene
m_d3dDevice->BeginScene();

// render movie surface (just two triangles to which the movie is rendered)

m_d3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE,false);
m_d3dDevice->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR ); // bilinear filtering
m_d3dDevice->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR ); // bilinear filtering
m_d3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
m_d3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); //Ignored
m_d3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 );
m_d3dDevice->SetTexture( 0, m_movieTexture );
m_d3dDevice->SetStreamSource(0, m_displayPlaneVertexBuffer, 0, sizeof(Vertex));
m_d3dDevice->SetFVF(Vertex::FVF_Flags);
m_d3dDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 2);

// render sprites
m_sprite->Begin(D3DXSPRITE_ALPHABLEND | D3DXSPRITE_SORT_TEXTURE | D3DXSPRITE_DO_NOT_ADDREF_TEXTURE);

// text drop shadow

m_font->DrawText( m_playerSprite, m_currentMessage.c_str(), m_currentMessage.size(),
&m_playerFontRectDropShadow, DT_RIGHT|DT_TOP|DT_NOCLIP, m_playerFontColorDropShadow );
// text
m_font->DrawText( m_playerSprite, m_currentMessage.c_str(), m_currentMessage.size(),
&m_playerFontRect, DT_RIGHT|DT_TOP|DT_NOCLIP, m_playerFontColorMessage ) );

// control object
m_sprite->Draw( m_texture, 0, 0, &m_vecPos, 0xFFFFFFFF ); // draws a few objects like this

m_sprite->End()

// end scene
m_d3dDevice->EndScene();

What did I forget to do here? Except for the control objects (play button, pause button etc which are placed on a "panel" which is about 440 pixels wide) everything seems fine, the objects are positioned where I expect them, but just too big.

By the way I loaded the images using D3DXCreateTextureFromFileEx (resizing wnidow, and reacting to lost device, etc, works fine too).

For experimenting, I added some code to take an identity matrix and scale is down on the x/y axis to 0.75f, which then gave me the expected result for the controls (but also made the text smaller and out of position), but I don't know why I would need to scale anything. My rendering code is so simple, I just wanted to draw my 2D objects 1;1 the size they came from the file...

I am really very inexperienced in D3D, so the answer might be very simple...


texts: How Best to Implement Fixed Time Step for Gsync/Freesync Monitors?

texts:
I currently implement my game loop using a variable fixed timestep, i.e. dt = 1 / monitor_refresh_rate with vsync (or pseudo vysnc with delays where vsync is disabled). I want to maintain using a fixed timestep to keep the replay system I have implemented. For variable refresh rate monitors like gsync and freesync, I'm unsure as to how best accomodate them using this pattern. I'm aware that I could easily cap the loop at say an assumed 60fps and that would work fine. However, I feel that this would not be taking full advantage of what these monitors  have to offer as I'd be effectively restricting their frame limit.

Any advice?
Thanks.


texts:
I think I understand the basic idea behind a Finite State Machine-based game loop. But I'm trying to write a little game in which the same object can simultaneously be in multiple, independent states. At least that's what I want to do.

To give you an idea: Robot may be in FleeState and FireLaserState at the same time, besides in each of them individually at any time.

Would something like this be possible using the FSM pattern? Or ought I to look elsewhere?

After all, does the whole idea make sense?

Pasted from my comment below: A little clarification of why I'd like states to be kept separate:  I want the player to have the ability to program simple state changes before a game... say "if (health_is_way_too_low) flee". But then I want multiple such rules to be active simultaneously in order to keep the game interesting, and cannot know beforehand which other states may be active.


texts: Gizmos not being drawn until GameObject selected

texts:
I have implemented Scene loading in my game and have three scenes: Persistent, Main Menu and Game
By default, the player is loaded into the Persistent scene, which immediately loads the Main Menu, and when the player clicks on Play, Main Menu is unloaded and Game is loaded.
Now, the two active scenes are Persistent and Game.
However, I have a script with OnDrawGizmos on a GameObject in the Game scene. It seems that by default gizmos only begin to be drawn when I click on that GameObject, sort of activating it, and everything works fine. This used to just work before because Game was my only scene and Unity automatically selected that first GameObject. Now, with multiple scenes, no GameObject is selected by default and my gizmos won't draw until I manually click on it.
How can I solve this?


texts: Libgdx explain steps for beginner to create and use image as a box2d body

texts:
I am basically from corona background and new to LibGdx , familiar with stage and actor from scene2D.  Now wants to use physics body from box2d  in the game besides using actor from scene2D.

But I need to use images in the game as body... not shapes..

anyone please explain me the steps to use images as a body.

Thanks..


texts: What are my options other than game engines?

texts:
I'm a programmer. I've experience in Java, python, and c++.
I see that some big games are built using game engines (Crysis uses Cryengine).
However, other don't (Bayonetta for example).
what's their approach ?
Do they start coding from scratch using OpenGL or Directx ?
is this approach feasible considering time, cost, porting to many platforms ?

I want to know what's the options before I start


texts: The camera goes up and down when following a rolling sphere

texts:
I have this CameraController script attached to my camera, to follow a sphere that moves using WSAD.

public class CameraController : MonoBehaviour
{

    public GameObject player;

    private Vector3 offset;
    // Start is called before the first frame update
    void Start()
    {
        offset = transform.position - player.transform.position;
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        transform.position = player.transform.position + offset;
    }
}

It follows the object fine, but it bounces up and down on the Y axis when it's moving, and I don't know how to stop the camera from doing it.


texts: How can I handle the difficulty level between co-op and single player?

texts:
I'm working on an action-adventure game, and I was considering adding a co-op option. What I'm trying to decide is if when another player joins the game, if the game should get harder. On the one hand, I don't want the game to just get easier. On the other hand, I don't want to break continuity by making enemies suddenly stronger, eg I was able to take this down it two hits before, why does it take four all of the sudden.

I do not want there to be an "AI co-op" that comes with you in single player, I think that would make the game worse since it would detract from player agency.

How can I handle this? How can I keep the game challenging when a second player joins in?


texts:
I have been making a 2D game in Unity, with a group of mine. We have made a character and are able to make him run and jump. Currently, I have been trying to make him double jump so someone can't just spam the jump button and go flying, but nothing has been working.

I've been through about at least 10 different tutorials on it, but nothing has worked. How do I make my character double jump?

public float speed;
public float jump;

float moveVelocity;
private Rigidbody2D myRigidBody;
private bool grounded = true;

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

void Update ()
{
    //constant run
    myRigidBody.velocity = new Vector2(speed, myRigidBody.velocity.y);

    if (Input.GetKeyDown (KeyCode.Space))
    {
        if (grounded)
        {
            myRigidBody.velocity
                = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, jump);
        }
    }
}


texts: Unity: Edge of quad is dark. How do I avoid this?

texts:
I have four quads together like this

These are just the default Unity quad from create\3d object\quad

the texture is white with grey borders on two sides and a black border on other two sides..

Lets zoom in..

How do I get rid of these black lines?

I am generating these bigger shapes out of quads and applying the texture using code...
I noticed that If I didnt change the material in code then there were no black lines.
So I made prefabs for each material, and am now spawning those in instead of changing a material on a quad. But I still get the same lines.
Also, if I drag the prefabs into the scene when the game is running they appear perfect.
I have no idea whats going on.


texts: Calculating the vector to catch a falling object

texts:
I have two objects in a three dimensional world. One is a ballistic projectile: that is, it is free-falling with some known gravitational acceleration. The other is a catcher that travels with constant velocity and is not subject to gravity. I want to calculate the vector that the catcher must travel along in order to intercept and catch the falling projectile (or the position of intercept between the catcher and the projectile).

By my reckoning, the problem can be formulated into equations like this:

Intercept position = Catcher start position + Catcher velocity * Intercept time

Intercept position = Projectile start position + Projectile start velocity * time + 1/2 * Gravitational acceleration * Intercept time^2

...where all the named variables except intercept time are three-dimensional vectors. Within those equations, I know:

The catcher and projectile start positions
The projectile's current velocity
The projectile's gravitational acceleration
The magnitude of the catcher's velocity.

I don't know, and could solve the problem by finding out any one of:

The direction of the catcher's velocity
The intercept position
the intercept time

...but I have really struggled to make any headway finding a solution to these equations. Can anyone help me out? Is there something missing from/incorrect about my approach here?


texts: Is it possible to record video, depth map and 6D pose of any games?

texts:
I'm not a game developer, but a researcher working on improving video quality in various contexts. For my current problem, I need to collect videos which have both RGB data as well as depth data. Video can be monocular or stereo. However, if there is egomotion, I'll need the camera pose (rotation and translation) as well. Is there any way to record all these information in any kind of games? Games can be on any platform: PC games, mobile games or VR games.
In short, I want to record gameplay but with additional information such as depth map and camera pose.


texts:
I'm trying to determine the angle NPCs are pushed in when the PLAYER collides with them, like how 'Retro City Rampage' and 'Shakedown Hawaii' do when you bump in pedestrians.

Here the PLAYER (green) is coming in at an angle of -45, what's the math or formula I need to be looking at to decide the new angle each NPC (red) should adopt?


texts: Flexible and extendable system of level objectives (victory/failure conditions) in Unity

texts:
I'm trying to come up with a flexible system of level objectives for a Unity game. What I'd like to achieve is to have a system that on each level (scene) can accept a different set of (configurable) success/failure conditions. Conditions can be repeated between levels but on every level a given type of condition should accept different parameters.

For example on one level success conditions would consist of destroying all enemy units and on the other level success conditions would require destroying a specific enemy unit and escorting a friendly unit to a specific place on map. Failure conditions would for example be player death (on all levels) or not reaching a specific destination within a given time.

First I've tried to approach this problem by using ScriptableObjects but abandoned this idea as it's not possible to save scene object references in a ScriptableObject.

So I've come up with a kind of polymorphic system like this (pseudocode):

public interface Condition {

    bool IsFulfilled();
}

public abstract class VictoryCondition : MonoBehaviour, Condition {

    public virtual bool IsFulfilled();
}

public abstract class AllUnitsKilledCondition : VictoryCondition {

    public List<Unit> units;

    public bool IsFulfilled() {
        foreach (Unit unit : units) {
            if (unit.IsAlive) {
                return false;
            }
        }
        return true;
    }
}

public abstract class FailureCondition : MonoBehaviour, Condition {

    public virtual bool IsFulfilled();
}

public abstract class TimeOutCondition : FailureCondition {

    public float timeLeft;

    void Update() {
        timeLeft -= Time.deltaTime;
    }

    public bool IsFulfilled() {
        return timeLeft <= 0;
    }
}

The idea here is to have a level manager that is given a set of victory/failure conditions in the editor and have it continuously monitor all those conditions. In a simplest scenario a level is won if all victory conditions are fulfilled and lost if any failure condition is fulfilled.

Unfortunately, I'm not sure how to create a LevelManager component that would expose those lists letting me add various conditions and configure them (for example letting me add a list of units from scene to AllUnitsDestroyedCondition). I think it would be doable with a set of custom property drawers for each type of condition but I'm wary of digging into this until I'm sure there is no other, easier way.

I've come up with a way of adding various conditions by adding multiple condition components to a GameObject and then dragging those components to victory/failure conditions lists in LevelManager. But this solution seems awkward and inflexible because it's not possible to dynamically add and configure new conditions in runtime and creating more complex conditions (for example some condition activating only after some other condition is fulfilled) seems like a sure way to create a huge pile of unmaintainable condition component mess.

Please, let me know if I'm approaching this problem correctly and if not, what are other, simpler, more flexible solutions.


texts: I am making a game where you fly a ship around some randomly generated planets. Since I am using a for loop to draw over 5000 planets, using the rectangle class or an oval-type class for this is not an option, since creating many objects will severely affect performance. Bitmasking each planet will likely result in performance issues too, so the only candidate is color based collision detection, because I don't need to apply some sort of object to everything I want to check for collisions. Is any way to check the perimeter around the ship for a certain color?


texts: What is "mapping seams" and "hard edges (doubled-up vertices)" in UV?

texts:
According to GPU: Optimizing model geometry:

  Try to keep the number of UV mapping seams and hard edges (doubled-up vertices) as low as possible

What is "mapping seams" and "hard edges (doubled-up vertices)"? Can someone point it out with image (use software like Maya/3Ds Max/Blender)?

Here are my guesses, but I don't know if my guesses are right:

I guess "mapping seams" is the "UV edge"

But I think it doesn't make sense when they said keep the number of UV edges as low as possible, of course I can't reduce the number of edges in my model, so I don't know what is "mapping seams".

About "hard edges (doubled-up vertices)", I guess it's double edge overlap each other by human's accident.


texts: How do I handle walking up and down bridges at any angle?

texts:
I'm currently trying to create a 2D platformer puzzle game like Mario vs. Donkey Kong: Mini-land Mayhem! within Flash. My issues reside in the bridge collision with the walking AI.

The game allows the player to create a bridge from one end point to another at any angle. Then the player's AI mummies (in this case) walk across the bridge to reach another platform.

Now, seeing that the bridge can be constructed at any angle, I'm only going to have a rotated rectangle to represent the body of it.I obviously can't use the typical AABB to check collision against this, instead it looks like I'm going to need to do a SAT or pixel perfect check.

The AI mummy must always stick to the platform or bridge as it walks across it (not to mention rotate to the bridge's angle). Therefore, I suppose I'm going to need some gravity and sliding collision? The walking speed should also be the same on both the platform and bridge.

Lastly, since I'm using a grid for my platform tiles (including the end points) connecting a bridge to them isn't going to be perfect. Going up and down the bridge may need some offsetting with floor in order to make a smooth transition from or two the bridge.

An example

Some things I have tried in the past week or two:

Using SAT collision with rotated rectangular bodies on the mummy and the bridge. I tried having the mummy walk up the bridge by adding 3 mini-hitboxes on the bottom-left, bottom-mid, and bottom-right to him. I had a hard time trying to get this to look right and trying to stick all of the hitboxes onto the bridge and the floor (especially when I rotated the mummy to that of the bridge).
Using Box2D Flash port library. Just doing something simple as this is seeming like an uphill battle with this physics engine. It looks as if it will be troublesome to get a predictable movement with a constant speed especially when going up the bridge. I've tried their 'conveyor' example, but for some reason, the classes that were used for it are missing in the Flash port. I've also tried disabling the physics and just using it for collision detection, however I dislike it entirely. I also don't receive any contact information for collision on the sensors (like distance, normal, point of collision, etc.). I'm better off with using my own SAT implementation for this task.
I've also tried placing nodes above each end point and when a bridge is connected, the mummy will know to go from one node to the other when he collides with the starting node itself. This has drawbacks of needing to offset the nodes perfectly so the mummy's feet will always be on the bridge, so I'd have to make sure to never change the size of the character and the bridge. Also, I'd need two nodes per end point, since going down and up a bridge will need different offsets.

It feels as though a fully fledged physics engine just doesn't feel right for this game. It would handle a lot of my current problems, but it will be introducing more at the same time. If I want a smooth walking transition from the platform to the bridge, it seems as it's the only choice.

Now my question is how would you guys go about having the mummies walk up and down a bridge smoothly at a constant speed and angle? Just use a physics engine? Create your own physics? Or trying raycasts?

Thanks


texts: Dragging an object by touching on Android

texts:
I am trying to move and object by touching it and dragging. I am testing it on my Samsung Galaxy SIII.

I have used the following code. For some reason it moves faster than my finger. It should always be beneath my finger. What is wrong? (note: I haven't done the "only move object if you touch onto it" part, so right now it moves where ever I touch)

#pragma strict

var speed : float = 1;

function Start () {

}

function Update () {
    if (Input.touchCount > 0 &&
        Input.GetTouch(0).phase == TouchPhase.Moved) {

        // Get movement of the finger since last frame
        var touchDeltaPosition:Vector2 = Input.GetTouch(0).deltaPosition;

        var touchPosition:Vector2;

        touchPosition.Set(touchDeltaPosition.x,
                           touchDeltaPosition.y );

        // Move object across XY plane
        transform.position = Vector2.Lerp(transform.position,
                                                touchPosition,
                                                Time.deltaTime*speed);
    }

}


texts: Simple game engines / development tools made with artists in mind?

texts:
I've been working in the 2d art side of games for a while now, and my full time job keeps me very busy on the art side of things, but I'm becoming more and more interested in learning to prototype my own games.

I know very very little programming, though I did take some in college (in TorqueScript, of all things), and while I could probably take the time to learn it, the learning curve is a bit too steep for me as it's completely separated from my current job.

I'm wondering if there are any game engines out there with an interface designed with artists in mind, where the learning curve might be easier for me, and where my current skill set will be more easily applied. I bought an indy license for Torque Game Builder but it still requires a lot of scripting and finding good, basic, entry-level tutorials is proving difficult.

Basically I'm looking for a tool where I can focus on the art and game design, and where the programming is minimal, or is easy to learn and has really excellent documentation. No idea if anything like that exists, but it's worth a shot. :]

Any ideas?


texts: What threading strategy does a game like Transport Tycoon use?

texts:
Transport Tycoon is a simulation game where you control a transport company, place railroad tracks and trains, airports, bus depots, boats etc. Now the game is about 15 years old and I remember running it on a 486sx25 with 4Mb of RAM without any problems.

I was recently thinking about modern simulation game requirements and how high they are for relatively little increase in graphics and gameplay, so how did they managed to pull it with so little resources back in the day?

Does each train car have a thread, that moves it every 100ms, sleeps, wakes, recalculates position and does crash detection, and goes back to sleep?

Or is it one thread that moves every 100ms? What happens if there is too much work to do in each 100ms interval?


texts:
In a 2D game, I simply want to draw the trajectory of an arrow in flight. With the code below, the trajectory (the parabola) looks right, but the angle (or rotation) or the arrow isn't.

float g = -9.8f;
float x = (launchVelocity * time);
float y = (launchVelocity * time) + (0.5f * g * (float)Math.Pow(time, 2));
float angle = (float)Math.Tanh(y / x);

What am I missing? Thanks.


texts: Aggregated assets from demo projects in UE4

texts:
Unreal engine allows you to download demo projects under the "Learn" tab of their launcher.

 How do I access the resources and assets used in these projects in an aggregate form?

To put it simply, there are textures and meshes and such that i would obviously like to utilize in my projects. These assets do not however seem to be readily available for use in any and all projects. How do i get them all in one place so i can access them?

Thanks in advance.

EDIT: I should note that i am aware of the "Hard way" of doing it, im kinda just hoping there is a better solution...

EDIT: The hard way doesn't seem to be immediately effective... Thinking...

EDIT: It seems that some are able to be directly added to projects, im still working on figuring out how to add these to the viewport. But others (like "a boy and his kite") provide no such option. thinking...


texts: Heightmap, how can i prevent bad odd numbers

texts:
I am building my world-editor for my game. I've noticed, that, no matter how i implement the heightmap, i'll end up with dumb odd numbers in calculations.

For example, lets take a HeightMap of 4x4 which covers a area of 2x2 OpenGL-Units. Thats a small image which shows the problem. The black lines and numbers represent units in OpenGL, the red lines and numbers repesent pixel/values on my heightmap.

You can easily see, that in the top image, every number is really odd and i actually need a lot of additional code to calculate everything correctly (OpenGL-position -> heightmap-pixel and heightmap-pixel -> OpenGL-position).

In the bottom image however, i am missing height-values for the right and the bottom row of vertices.

I thought i could just use +1 pixel for every heightmap, this would solve this problem but i am sure it will introduce problems at other ends.

How would you guys handle this?

As stated in the comments, the real problem here is, that i need to calculate OpenGL-position -> heightmap-position and OpenGL-range -> heightmap-range fairly often to draw on the heightmap and the math gets really hard to handle with the mapping as seen in the top-image.


texts:
FXAA is a cheap post processing anti-aliasing method which works great with deferred pipelines where traditional MSAA may not be a viable option. It's also easier to implement than alternatives such as SMAA.

Unfortunately, as a quick Google search will show, a lot of PC gamers hate it because even when setting the shader to its best quality settings it still adds a slight blur to the outputted image. This is particularly noticeable when a scene has textures with fine detail and/or small specular highlights.

Is there a way to counteract this blur without reintroducing significant aliasing?


texts: if touching line renderer (do something)

texts:
I have this laser script for a ship and I am trying to make it kill an enemy when it is hit with the line rendered laser. How can I achieve this. All things I found online I just could not get to work. An outline of the code would be (this isnt real code).

public gameobject linerenderer;

void update()
{
   if (touching gameobject.linerenderer)
   {
       die
   {
}

 private LineRenderer lr;
    void Start()
    {

        lr = GetComponent<LineRenderer>();
    }

    void Update() // consider void FixedUpdate()
    {

        lr.SetPosition(0, transform.position);
        RaycastHit hit;
        if (Physics.Raycast(transform.position, transform.forward, out hit))
        {
            if (hit.collider)
            {
                lr.SetPosition(1, hit.point);
            }
        }
        else lr.SetPosition(1, transform.forward * 5000);

    }

However there is an anoying bug with this code...
Before:

After you play the game for about 30 secs:

Settings:


texts:
I am making small isometric game, where I want to do something when user clicks a tile. I can simple do it by mouse location, but I want to be able for zooming and moving camera. It will be 2D game using Java awt. I will be printing grid with the diamond style. Can I make that I will make object of the tile map and locate the mouse whatever the camera is?

Thanks for any help, Maratonec.


texts:
I know this is a common question, but I can't find an answer to it that isn't written using a huge game library sadly.

I'm trying to write a scrollable tile system, which allows the user to move around it (from an arial perspective). I have this partially working, but it doesn't work as expected.

Could anyone help me out with this please, or link to where I can find a tutorial which doesn't use a huge java library?

Thanks

Edit:: http://thepb.in/private/L5elnMb3PU
This is a concise example of the problem, you seem to move a lot faster when the player should be 'in the center' (Please ignore the loop for redrawing)


texts: Is there a way to balance a binary tree continuously?

texts:
In my game I have a tree of objects in 3D space, to which new objects are frequently added.

Over time, the binary tree becomes unbalanced which is a big problem for efficiency as the tree can become quite large. It might even be at risk of stack overflows from deep recursion.

At the same time, it is important to keep branches of the tree close together in 3D space. So I can't arbitrarily swap tree nodes around to balance the tree.

Is there an efficient algorithm that will do the following:

Allow efficient additions to the tree (O(log n) max)
Keep the tree approximately balanced as additions are made
Ensure that branches of the tree contain objects that are close to each other in 3D space (i.e. it works at least approximately as a spatial subdivision tree)


texts: Collision Detection problems for vertically moving platforms

texts:
Background

My game is a static screen (ie, no scrolling) 2d platformer and my CD routine is split into 2 - after vertical movements, (ie, gravity etc) I check for collisions, and if they are detected, correct the sprite positions vertically.  Then after horizonal movements do the same thing, correcting any overlaps in the horizontal direction.

My CD code iterates through all the tile coordinates, and when it find a collision, it corrects the position, then exits and checks no more until the next game tic.

This works perfectly for static tiles, however, I've introduced platforms which are comprised of 3 horizontal tiles and which move up and down (ie, like an elevator).

The problem

The problem occurs if my character is standing 'over the edge' of a static block and then the elevator is moving up from under him - what I'm after is for the platform to 'catch' his over-hanging side and take him with it if you see what I mean.  However, what happens is that he gets shoved to the side.  I know why this is, but I'm not sure of the best way to correct it.

I think it happens because gravity is applied, pushing him into the static block, then the elevator move up so he is now embedded in 2 blocks.  The vertical CD routine detects the first overlap (say with the static block), corrects it and then moves onto the rest of the game logic (but now he is still embedded in the platform) - then it eventually gets to the horizontal collision detection which moves him out of the collision horizontally.  Please see my diagrams below, I hope these make it clearer.

Possible solution

Basically, I guess what I need is for the CD routine to carry on checking once it's corrected the first collision, but this would be so wasteful and 99% of the time it only needs to check one collision.  I thought about simply making it check through the tile coordinates twice, but like I say, this seems inefficient.  However, I'm trying to keep things as simple as possible and this seems the simplest solution.

Diagrams

Would appreciate any suggestions for how best to get around this........


texts:
I'm having a problem with AI movement in my top-down game. AI builds path and than moves using libgdx FollowPath (this problem is still actual) steering behavior. I have some solutions, but can't guess whitch is better(or I even need other solution). FollowPath params:

followp = new FollowPath<Vector2, LinePathParam>(this,
            new LinePath<Vector2>(path));
    followp.setPredictionTime(0.08f);
    followp.setArriveEnabled(true);
    followp.setArrivalTolerance(0.001f);
    followp.setDecelerationRadius(40f);
    followp.setTimeToTarget(0.1f);

Problem. Character doesn't move straightly according to the path - cuts corners through obstacles.
Solution 1. Find right proportion between character speed/acceleration, character size, obstacles size. Curent parameters: maxLinearSpeed = 100; maxLinearAcceleration = 150; maxAngularSpeed = 15; maxAngularAcceleration = 30; characterRadius=40; obstacleSize=120 (width and height). But if acceleration and speed are too big, character will move like "on rails" and even sticks on corners. Too small - character will be skidding.

Solution 2. Write own FollowPath steering behavior, whitch requires character to get close enough to every point of the path (without using predictionTime,that prevents sticking, but allows cutting corners) and using Arrive on every point of the path, that won't allow skidding.

Solution 3. Use RaycastObstacleAvoidance with FollowPath together(Priority steering). Here comes another problem: cause of raycasting character shakes (especially when it needs to turn around near wall or just target is near wall). Probably, it is solved by usage of lower angular acceleration (causes skidding).


texts: Is there ever a time when creating a level/world editor with your game is a bad idea?

texts:
I have created a few smaller games on my own in the past. My approach has always been to create a completed editor where it has all the functionality needed to save a level file and load it into the game.

This has always made most sense to me but I keep hearing from people that a game is never fully done in the editor.
I have never worked in a game development team and so I don't have first hand experience, but not adding everything needed to make the game to the editor just seams wrong.

Am I missing something? Is there ever a reason not to add a tool to the editor?


texts: OpenGL 2.0 Android Scrolling Horizontally and Vertically

texts: I am new to OpenGL2.0 in Android. How can I scroll the GLSurfaceView both horizontally and vertically?


texts: How to play more than one background song in XNA?

texts:
The current tutorial I am using to play background songs only allows me to play one song throughout the entire game.

Link to tutorial --> http://rbwhitaker.wikidot.com/playing-background-music

I want to have multiple songs where after one song is finished playing another random song will be selected and played.

How would I do that?

Also I would not liked to get involved in XACT.


texts:
Why am I getting this error. I think it has problem with port so I change port number and still getting same error. yesterday it was working fine but when I start today it giving me error like this.

  ClientDisconnected due to error: Timeout
  UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate()

I refer this question but, there is not any answer presence for this error.


texts: Trouble with LineRenderer with orthographic camera in Unity

texts:
When a weapon is fired, I want to draw a line for the bullet's trajectory.

I am using a LineRenderer to draw the trajectory with the code below:

    void FixedUpdate () {
        timer += Time.deltaTime;

        if (Input.GetButton ("Fire1") && timer >= timeBetweenBullets && Time.timeScale != 0) {
            Shoot ();
        }

        if (timer >= timeBetweenBullets * effectsDisplayTime) {
            DisableEffects ();
        }
    }

    void DisableEffects () {
        gunLine.enabled = false;
    }

    void Shoot () {
        timer = 0f;

        // Set first point
        gunLine.SetPosition (0, transform.position);

        shootRay.origin = transform.position;
        shootRay.direction = -transform.forward;

        gunLine.SetPosition (1, shootRay.origin + shootRay.direction * range);
    }

I am using an orthographic camera in the scene. The line will show up but at certain rotations the line will partially render or be completely hidden. Oddly, the line will always render in the scene view-- the problem only exists in the game view.

Has anyone had this issue?


texts:
Broad question, but I'm looking for some better ideas.

Currently I have a Player class and booleans for hasSeenLevel2, hasSeenLevel3, etc. When I give a player exp I call a checkLevel method that checks to see if they level up.

checkLevel(){
    if(totalExp > 100){
         level = 2;
         if(!hasSeenLevel2){
             display("You gained level 2");
             hasSeenLevel2 = true;
         }
    }

}

this works, but is incredibly tedious to setup and inefficient.

What better ways are there to organize player levels and exp?