texts: Data structures for a 2D multi-layered and multi-region map?

texts:
I am working on a 2D world editor and a world format subsequently. If I were to handle the game "world" being created just as a layered set of structures, either in top or side views, it would be considerably simple to do most things.

But, since this editor is meant for 3rd parties, I have no clue how big worlds one will want to make and I need to keep in mind that eventually it will become simply too much to check, handling and comparing stuff that are happening completely away from the player position.

I know the solution for this is to subdivide my world into sub regions and stream them on the fly, loading and unloading resources and other data. This way I know a virtually infinite game area is achievable. But, while I know theoretically what to do, I really have a few questions I'd hoped to get answered for some hints about the topic.

The logic way to handle the regions is some kind of grid, would you pick evenly distributed blocks with equal sizes or would you let the user subdivide areas by taste with irregular sized rectangles?
In case of even grids, would you use some kind of block/chunk neighbouring system to check when the player transposes the limit or just put all those in a simple array?
Being a region a different data structure than its owner "game world", when streaming a region, would you deliver the objects to the parent structures and track them for unloading later, or retain the objects in each region for a more "hard-limit" approach?
Introducing the subdivision approach to the project, and already having a multi layered scene graph structure on place, how would i make it support the new concept? Would you have the parent node have the layers as children, and replicate in each layer node, a node per region? Or the opposite, parent node owns all the regions possible, and each region has multiple layers as children? Or would you just put the region logic outside the graph completely(compatible with the first suggestion in Q.3)
When I say virtually infinite worlds, I mean it of course under the contraints of the variable sizes and so on. Using float positions, a HUGE world can already be made. Do you think its sane to think beyond that? Because I think its ok to stick to this limit since it will never be reached so easily..
As for when to stream a region, I'm implementing it as a collection of watcher cameras, which the streaming system works with to know what to load/unload. The problem here is, i will be needing some kind of warps/teleports built in for my game, and there is a chance i will be teleporting a player to a unloaded region far away. How would you approach something like this? Is it sane to load any region to memory which can be teleported to by a warp within a radius from the player?

Sorry for the huge question, any answers are helpful!


texts: Character getting slow when reached to speific path point

texts:
I have manually placed some cube on the floor and aim to walk my character on those cube as they are appearing in the hirarchey and here is the walk code.

 if (Vector3.Distance(pathPositions[pathIndex], walkingCharacter.transform.position) > 0.5f)
        {
            Vector3 newPosition = pathPositions[pathIndex] - walkingCharacter.transform.position;
            walkingCharacter.transform.position += newPosition * Time.deltaTime * walkingSpeed;
            walkingCharacter.transform.rotation = Quaternion.LookRotation(newPosition);
        }
        else {
            pathIndex++;
        }

I have walk in place animation which is working fine and the above code moving my character to specific points but not smoothly. As my character approach to specific path point it get slow then suddenly move towards next point. What i am doing wrong. Here is the video of the problem maybe it will helpful to understand the problem.


texts: How do I use the DirectX Extension-Library in Windows 8?

texts:
I need to use the extended DirectX-Library (D3DX...), but I am programming
on Windows 8 (VS), so the DirectX 11-SDK is already included. However, it's included without the extension-library.

Do I have to download the June 2010 SDK? If so, how do I set up VS to work with the extended library?


texts: Is there a way to make lowpoly characters close to looking like anime?

texts:
I have never used MakeHuman but i am trying to find a way to make lowpoly human models for a game. simple game so thats why i want lowpoly.

I want to have lowpoly but be looking like anime (Japanese Cartoons).

FYI: Im using Blender and Unity for the game. i just hope i can make anime from makehuman.


texts: RGB to xyY color space conversion and luminance

texts:
The luminance calculated by following GLSL functions (fragment shaders - tonemap) has different value:

float GetLuminance (vec3 rgb)
{
     return (0.2126 * rgb.x) + (0.7152 * rgb.y) + (0.0722 * rgb.z);
}

vec3 RGB2xyY (vec3 rgb)
{
     const mat3 RGB2XYZ = mat3(0.4124, 0.3576, 0.1805,
                               0.2126, 0.7152, 0.0722,
                               0.0193, 0.1192, 0.9505);
    vec3 XYZ = RGB2XYZ * rgb;

    return vec3(XYZ.x / (XYZ.x + XYZ.y + XYZ.z),
                XYZ.y / (XYZ.x + XYZ.y + XYZ.z),
                XYZ.y);
}

I used a glm library to calculate an example result. For glm::vec3(2.0f, 3.0f, 8.0f) GetLuminance returns 3.1484. RGB2xyY returns glm::vec3 which z component is equal 3.8144. What is wrong ?


texts: Alpha Blending: use the pixel with the smallest alpha

texts:
I'm writing a transparency shader where I need any intersecting textures to, wherever they overlap, take the texture pixel with the smallest alpha value and render only that, discarding the other pixel(s).

Turn this:

Into this:

In pseudocode, something along the lines of…

if ( newPixel.alpha < currentPixelInFrameBuffer.alpha )
    currentPixelInFrameBuffer = newPixel;

I can't seem to find if there is a native alpha blending command that will do this. There exists DstAlpha, which is an alpha blending property that compares against the current fragment's frame buffer source alpha value, but I obviously cannot use that in the following manner…

AlphaTest Less DstAlpha

I've found there's a BlendOp Min, which is supposed to "Use the smaller of source and destination." but I can't seem to get that to work and I can't find documentation on what it means by 'smaller'.


texts: Player keeps bumping when walking over to another sprite

texts:
So, my problem is that my play when he walks over to another sprite he will stop.

I fixed that by adding a physics material with 0 density and 0 friction to the player

and adding a circle collider instead of a box collider to the player.

However now I have another problem where my character keeps bumping when it enters another sprite.

The sprites are at the exact same height, the objects are just as big and the colliders have the exact size.

I would like to get a fix for this problem, which still allows me to use Rigidbody2D.AddForce for movement.

Video of my problem :

Video :>

How to recreate the problem :

Make a sprite, add a Circle Collider 2D to it and a Rigidbody2D.

That will be the player.

Next, make some platforms and add a Box Collider 2D

Now, if you let your player walk over the platforms it will (or should..) start bumping.


texts:
I've implemented picking based on color coding, but I don't want the background color to be pickable. Is there any way in openGL (2.x) to exclude the background color? For some reason, doing glClear(GL_COLOR_BUFFER_BIT) just before rendering in "color picking" mode, excludes the background in windows but not in Linux.

I'm using glut btw.


texts: How to eliminate screen jitter in Flash game?

texts:
We made a flash game with a big screen size(1000x600), and the terrain graphic will jitter while the screen scrolling(that's, camera moving with player) continuously.

What's the root cause? Or if you know how to eliminate this problem, please tell me. Any help is appreciated.

UPDATE:

The map's size is more bigger than screen, e.g 6000x1200. And the map has more than one layer, generally it has 3 layers. Terrain is composed by tiles. And FPS is 24.

If the FPS is set to 60, things will be better. But any way, it should work well at 24 FPS. I'm not sure if it is a natural problem of flash player, because some times a terrain object(e.g a house) look like a little bit distorted.


texts:
Im making a game in java as a hobby and ive reached a part where i have a few game elements which i want to have collision. Since im using a tilemap, the collision with the wall tiles is pretty simple and since every game element has a pointer to the tilemap, the tile collision code can be placed in the game element class itself, so that every game element collides with the map, at least.

but as for the collision between the game elements themselves, which im going to do with separate axis theorem, i dont really know where to place it. the objects of each level are created on the said level class, since im using a game state manager and each level has a separate class (everything is a state basicly, lets say menu, level1, level2 etc)

So i COULD put the collision code in a, lets say, superclass of Level, but it sounds kinda wrong to put collision code on a class like that, and i dont really have any ideas.

So i would like to know how you organize your collision code in your games, i appreciate any kind of technique or simple architecture


texts:
I'm having a problem with drawing 2 RenderTargets to the screen.

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

namespace Please
{
    class Class1
    {
        RenderTarget2D rt;
        Texture2D temp;
        Vector2 v;
        public Class1(Vector2 v,GraphicsDevice g)
        {
            this.v = v;
            rt=new RenderTarget2D(g,800,600);
        }

        public void Draw(SpriteBatch sb,GraphicsDevice gd,ContentManager cm)
        {
            gd.SetRenderTarget(rt);
            sb.Begin();
            sb.Draw(cm.Load<Texture2D>("Untitled.png"),v,Color.White);
            sb.End();
            gd.SetRenderTarget(null);

            temp = (Texture2D)rt;

            sb.Begin();
            sb.Draw(temp, Vector2.Zero, Color.White);
            sb.End();
        }
    }
}

Here's my draw function in the actual "game"

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);
    base.Draw(gameTime);
    one.Draw(spriteBatch, graphics.GraphicsDevice, Content);
    two.Draw(spriteBatch, graphics.GraphicsDevice, Content);
}

one and two have positions (100,200) and (300,200) respectively, so, they should be drawn 100 pixels apart, however, only two is being drawn with the rest of the screen black


texts: Function called only once from another script

texts:
I have a spawn function which is

public void spawnobstacle(){
    number_of_spawn = Random.Range (1, 3);
        if (number_of_spawn > 0) {
            spawnposition = Random.Range (0, 3);
            if (spawnposition == 0 && !rightisoccupied) {
                Instantiate (obstacle, rightpos, Quaternion.identity);
                rightisoccupied = true;
            }
            if (spawnposition == 1 && !midisoccupied) {
                Instantiate (obstacle, midpos, Quaternion.identity);
                midisoccupied = true;
            }
                if (spawnposition == 2 && !leftisoccupied) {
                Instantiate (obstacle, leftpos, Quaternion.identity);
                leftisoccupied = true;
            }
            number_of_spawn -= 1;
    }

and I have another script in the obstacle GameObject that if the obstacle is triggered by it, it destroys the obstacle and spawn some other obstacle.

The content of the script is this:

public class DestroyObstacle : MonoBehaviour {
public GameObject world;
void OnTriggerEnter2D (Collider2D thecollision){
    if (thecollision.gameObject.tag == "destroypoint1") {

        world.GetComponent<Spawn> ().spawnobstacle ();
        Destroy (this.gameObject);
    }
}
void Start(){
    world = GameObject.Find ("World");
    }
void Update() {

}

Why is the function only calls one obstacle every time and the function is called only once, 2 times max (not every time the obstacle is destroyed)?


texts: Stopping player from spamming movement keys which causes glitches Unity C#

texts:
I wrote a script for the player movement in c#. Whenever the player presses A or D, it moves him/her to the left or right by 12 units and when the player presses W or S, it moves him/her up or down by 12 units. My script works fine, but if a person starts to spam all of the keys at once, it glitches out and the player object is not in line with the level anymore. I want to have the script check if there a movement is currently happening before executing the movement on the keypress. Here is my script:

void Update () {

    transform.Translate(Vector3.forward * ForwardSpeed * Time.deltaTime);

    if (Input.GetKeyDown (KeyCode.A) && side > maxSideLeft) {
        MoveObjectTo(this.transform, new Vector3(this.transform.position.x - 12, this.transform.position.y, this.transform.position.z + 10), movementSpeed);
        side -= 1;
    } else if (Input.GetKeyDown (KeyCode.D) && side < maxSideRight) {
        MoveObjectTo(this.transform, new Vector3(this.transform.position.x + 12, this.transform.position.y, this.transform.position.z + 10), movementSpeed);
        side += 1;
    }

    if (Input.GetKeyDown (KeyCode.W) && level < maxLevelHeight) {
        MoveObjectTo(this.transform, new Vector3(this.transform.position.x, this.transform.position.y + 12, this.transform.position.z + 10), movementSpeed);
        level += 1;
    } else if (Input.GetKeyDown (KeyCode.S) && level > minLevelHeight) {
        MoveObjectTo(this.transform, new Vector3(this.transform.position.x, this.transform.position.y - 12, this.transform.position.z + 10), movementSpeed);
        level -= 1;
    }

    if (Input.GetKeyDown (KeyCode.R) || Input.GetKeyDown(KeyCode.Space)) {
        SceneManager.LoadScene ("Scene1");
        Time.timeScale = 1;
    }
}

private void MoveObjectTo(Transform objectToMove, Vector3 targetPosition, float moveSpeed)
{
    StopCoroutine(MoveObject(objectToMove, targetPosition, moveSpeed));
    StartCoroutine(MoveObject(objectToMove, targetPosition, moveSpeed));
}

public static IEnumerator MoveObject(Transform objectToMove, Vector3 targetPosition, float moveSpeed)
{
    float currentProgress = 0;
    Vector3 cashedObjectPosition = objectToMove.transform.position;

    while (currentProgress <= 1)
    {
        currentProgress += moveSpeed * Time.deltaTime;

        objectToMove.position = Vector3.Lerp(cashedObjectPosition, targetPosition, currentProgress);

        yield return null;
    }
}


texts:
I'm trying to compute the line intersecting my plane (transformed to NDC) and the near plane.
I have troubles to get a correct result and I think it is coming from the near plane equation.

I suppose that the equation in normalized device coordinates is \$N=(0,0,1)\$ and \$O=(0,0,near)\$.
But what is the value of \$near\$? Is it constant or it depends on the frustum?


texts: OpenGL ES draw pre-rendered background onto depth buffer

texts:
I want to create a scene with 2D pre-rendered background and 3D models for characters (like those classic Final fantasy games).
For the background, I have 2 textures:

one to be displayed, with colors, details...
one to be used as depth buffer (depth value presented as grayscale value maybe)

I want to write a shader program to help me discard all the pixels(frags) which have the depth smaller than current depth.
But then, do the background and the models have to use the same shader?
What value to compare with the depth value?
Is this approach even possible?


texts: How can I draw a perspective-correct quad?

texts:
I'm trying to draw a quad in 2D (in SharpDX, but that is basically XNA). But texture correction is not working, and I'm getting only an affine textured quad.

I'm using BasicEffect to render it.

BasicTextureEffect = new BasicEffect(Device)
{
    Alpha = 1.0f,

    TextureEnabled = true,
    LightingEnabled = false,
    VertexColorEnabled = true,

    Projection = Matrix.OrthoOffCenterLH(0.0f, ScreenWidth, ScreenHeight, 0.0f, 0.0f, 1.0f),
};

It is an 2D isometric game. I have pseudo-3D coordinates in isometric world (it's a shadow on the ground) converted to screen space, and then rendered using DrawQuad.

Do I need to set-up view (or projection?) somehow, to real 3D (emulate the isometric camera), and then draw this quad in 3D coordinates instead? How eventually? Or is there a way to correct this in 2D?

Update:

I've uploaded the actual partial screen-shot (Figure A), for you to see it's almost the same. (I cut it a bit, but it goes all to the corner)

            Figure A                                         Figure B

Update 2:

I can confirm now, that plain SharpDX (XNA) BasicEffect does this with just plain UW mapping (4 corners of a square), and plain DrawQuad. I've temporarily changed it to include center point, and I do draw 4 triangles instead of 2 (Figure B), this reduces effect to minimum, but it's still there. It still needs to be solved, because I won't be using it only on shadow.


texts: Why do Unity layer masks need to use bit shifting?

texts:
I've finally figured out why my layer masks for my ground collision code weren't working. I was using NameToLayer() to get the layer I needed, but layer masks use bit shifting to actually set the layer mask value. This is extremely unusual and I don't see any reason why this isn't handled in the code behind. Why do we have to use code like this:

mask = 1 << LayerMask.NameToLayer("Default");

when something like this:

mask = LayerMask.NameToLayer("Default");

makes more intuitive sense and works similar to the rest of the Unity API?


texts: Precision problem when doing collision detection?

texts:
I've got this problem, and I don't know what may be the cause of it.

I finished reading this article on sphere-triangle collision.

My character (the sphere) stops before it reaches the triangle, and then over like 2 seconds it slowly reaches the "expected" spot where I really want it to stop.

Thing is, I tried switching my whole algorithm from floats to doubles, and they problem stays. So I'm not really sure if that's a number precision problem, although after many debugging I think that there could be a problem with the precision of the next calculation: (t0 and t1)

Real signedDistToTrianglePlane = trianglePlane.signedDistanceTo(colPackage->basePoint);

Real normalDotVelocity = glm::dot(trianglePlane.normal(),colPackage->velocity);

t0 = ((Real)-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
t1 = ((Real)1.0 - signedDistToTrianglePlane) / normalDotVelocity;

Could the dot product function be a trap for precise calculations? (signedDistanceTo() uses glm::dot as well)

Here's my collision detection & response algorithms.

One last thing to note is that on page 47 in the article, the author uses a verySmallDistance number where he only updates some variables if distanceToCollision is bigger than it. I don't understand these lines.

I've been struggling with this issue for a week now. Any help or idea on the subject will be highly appreciated!


texts: How many localisations are too much for a game?

texts:
We are making an RTS game and we intend to add localizations to all languages our players use. So far we have 16 locales and about 3-4 are being planned.

Now some crazy ideas pop up from our community, players ask for "funny text" localizations. We have been already offered a pack that makes it for 1 of our languages. Now I was thinking where should we draw a line between official localizations which we include into the game and unofficial mods that players will have to install on their own?

Obviously overcrowding locale selection menu with all sorts of funny locales (LOL-cat, redneck, welsh, medieval, simplified, etc.) for all the languages seems way too much. But is it really? What are the hidden pros and cons of having too much locales and how much is too much?


texts: How do I change the size and specific height values of Unity generated terrain?

texts:
I'm having problems with terrain scripting while trying to do a infinite-world with Unity's terrain generation.

How do I change the terrain height at specific points? And how do I set the amount of terrain generated?

Edit: What I'm having problem with is doing that from a script, from the editor is plain easy.


texts: Programming Pattern: Representation of pick up objects

texts:
I'm pondering about the best way to represent objects that can be picked up in my 2D engine.

I have an Actor class which is the base for all objects that can be spawned into the game. This class offers a location and some other information needed by all actors.

Now, let's take an Apple for example. It's derived from Actor and carries with it all the information needed to be in the game-world. But when I pick this item up and put it inside an inventory, I don't need all that Actor stuff. So I was pondering. Does it make sense to maybe have an AppleActor class instead that derives from Actor, and inside it have an Apple class derived from something like InventoryItem?

When I pick up an Actor, I would take the InventoryItem out of it, store it in my inventory and destroy the Actor. Then, when I drop the InventoryItem, I would first create the corresponding Actor for it, put the InventoryItem inside it and spawn that Actor in the world.

Does this make sense at all? Any feedback or advice from more experienced people here is welcome.


texts: Best practice to use Sprites in a game using AndEngine GLES2

texts:
Currently I am having static reference to all my sprites and loading and initializing them in my OnCreateResource mthod of SimpleBaseGameActivity, But now I have to override onAreaTouched listener on spirtes and the way I can override it while Initializing the Sprite. But I have a static method creating Atlas and Texture Region for every sprite. And I am using these sprites in my scene class and I want to override onAreaTouched there. I can registerTouchArea for that specific sprite in my scene so that can be done But I want to Override OnAreaTouched in a way so that Code reusability can be done. Here is how I am currently creating and loading sprites.

defualtCageSprite = createAndLoadSimpleSprite("bg.png", this, 450, 444);

And this is my Method createAndLoadSimpleSprite.

public static Sprite createAndLoadSimpleSprite(String name,
    SimpleBaseGameActivity activity, int width, int height) {

BitmapTextureAtlas atlasForBGSprite = new BitmapTextureAtlas(
        activity.getTextureManager(), width, height);
TextureRegion backgroundSpriteTextureRegion = BitmapTextureAtlasTextureRegionFactory
        .createFromAsset(atlasForBGSprite, activity, name, 0, 0);
Sprite sprite = new Sprite(0, 0, backgroundSpriteTextureRegion,
        activity.getVertexBufferObjectManager());
activity.getTextureManager().loadTexture(atlasForBGSprite);

return sprite;

}
Now How Can I override onAreaTouched for some sprites while not losing the code reusability.


texts: Move an object with other objects connected (via joints) the right way

texts:
What is the best way to move an object with other objects connected to it via joints?

Let's assume we have the following setup:

A player that can move on the x and the z axis

"Normally configured" RigidBody
Moving like this:

    void FixedUpdate() {
        Vector3 movement = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
        movement = movement.normalized * 2f * Time.deltaTime;

        // m_rb is the RigidBody of the player
        m_rb.MovePosition(transform.position + movement);
    }

Another object that should be moving with the player as it were its child

Connected to the player via a fixed joint
"Normally configured" RigidBody

When moving the player without any object connected the movement looks as expected:

Now moving the player with the object connected results in some kind of dragging effect as seen here:

One way to solve this behaviour would be to also move the connected object:

// m_otherRb is the RigidBody of the connected object (m_other)
m_otherRb.MovePosition(m_other.transform.position + movement);

Is there a better way to solve this? Shouldn't the joint handle the movement of the other object? Moving the connected object like this results in many problems like to high impulse forces when colliding with something as both elements get pushed towards the collider. Also handling the rotation of the connected object isn't as easy as the position.


texts:
I have created a map using UDK and I am exporting it as a .fbx for use within an XNA project.

My question is, can I generate a UV map for texturing the map or is there an easier way to texture a map made within UDK to be used in an XNA project?

Thanks.


texts: Synchronization problem with Visual Studio 2017 and Unity 2017.1.1f

texts:
Sometimes I need to change a lot of files and Clean and Rebuild the Solution to get the changes on Unity, am I missing some configuration on Visual Studio or Unity? I uninstalled everything and make a clean install and few days later I'm getting the same problems.

Sometimes if I create a stardard MonoBehaviour script from Unity and I try to attack it to a gameObject I get the error: "Can't add script component XXXXXX because the script class can't be found"(see image: screenshot). The class name and file name are the same, with no syntax errors.

Some times opening a file with an external editor changing the encoding, cleaning and rebuilding the project solves the problem, but just sometimes and I'm tired of do that for test any change, now I have a lot of Debug.Log just to check if Unity is getting my code changes.

Any suggestion will be very greatful


texts:
I'm developing a JavaScript Multiplayer Game (Using NodeJS and Socket.IO). The problem I'm having is, on a Player's movement, the Event with the X and Y positions is sent to the server and then to all the other Players on that Server. Now, on a 60 FPS Machine, the event is sent to the server 60 times a second, resulting on smooth movement on all other Machines with 60 FPS. However, on a 30 FPS Machine, it's only sent 30 times a second, resulting on jumpy movement on higher FPS Machines (E.g. 60 FPS).

Is there any way to resolve this problem?

Thanks!


texts:
Can someone please explain whats going on in this code written by Paul Irish?

I did not understand the draw().

function draw() {

    var time = new Date().getTime() * 0.002;
    var x = Math.sin( time ) * 192 + 256;
    var y = Math.cos( time * 0.9 ) * 192 + 256;
    toggle = !toggle;

    context.fillStyle = toggle ? 'rgb(200,200,20)' :  'rgb(20,20,200)';
    context.beginPath();
    context.arc( x, y, 10, 0, Math.PI * 2, false );
    context.closePath();
    context.fill();

}


texts: UI Text and Image components no longer load a default GUI material

texts:
I have a bunch of UI Image and Text components attached to various game objects throughout my app. When I created these components I didn't need to explicitly add a material to them in order for them to render. For example in the Text component, once I add the font, the text would appear even though there was an empty Material field in the inspector view. IIRC they used a Default GUI material.
Today, I was messing around with adding materials to one instance of a Text game object. I'm not exactly sure how I did this, but now every single UI Text and Image object does not render unless I explicitly add a material to them.
Is there a setting somewhere to toggle this behavior?
How can I undo this so that all existing Text and Image component uses the default gui materials so that I don't have to manually and redundantly add a material to every single instance?

Below: Text component that would render before, but no longer renders
Below: Text component with font material manually attached in order to render

Thanks!


texts: How to turn a 3d camera (in HTML5 2D Canvas)

texts:
A few years back I started experimenting with 3d in canvas. Everything went pretty well untill I had to to turn the camera, I couldn't get it done.

A few days back I just happened to stumble upon that project again and noticed I got pretty far with it, sure, the code was a mess... so I cleaned it up a little and started fixing the camera rotation... And... I still have no clue how to do it. I tried google but so far nothing worked, I just have no idea what I'm doing....

Can somebody help me with this?

The code is located here: http://johandam.com/etc/3d

The relevant pieces are (probably) located here:

http://johandam.com/etc/3d/js/obj.js < General 'entity' class, here the 3d world coordinates are translated to 2d screen coordinates, it used to adjust it's position based on the camera's rotation but then distance-checking got all messed up so I moved it to the camera class, which I think makes more sense anyway.

http://johandam.com/etc/3d/js/camera.js < the camera object. A lot of movement code and at the end I try to adjust the camera based on it's rotation.

The idea is to have a target point around which the camera rotates but I'm pretty sure that somewhere a long the line I mixed a couple of different methods in it and I have no idea what I'm doing...

Who can help me out here?


texts: OpenGL Poor FPS when models outside view

texts:
I have been testing my game to see how well it renders a few hundred complex models onscreen at once point but even when all the models are outside my viewpoint, i still get poor fps.

I have face culling enabled to get rid of back facing triangles, but I'm not sure how to stop processing triangles behind or outside my viewpoint.


texts:
So I'm working on a proceduraly generated level, that is composed of multiple chunks, so you don't go over the maximum amount of verts allowed in Unity Meshes.

Another function is the ability to raise/lower the mesh to modify it on click.

However, the borders of the chunks break this functionality. And I can't edit both at the same time.

Currently to raise/lower, i have a raycast returning the mesh that you are clicking on, and extruding those points. However, this dosen't allow me to edit overlapping boundaries.

Any ideas on a better solution?

Thanks for the help!


texts: Time series for creating new events in a PVP game

texts:
This is more like a mathematical problem, but I guess this is the best place to ask it.

I am working on a PVP concept and I have the following problem. There is a "battle" between two players that both have set their moves before the match starts. So, during the battle, they just watch the screen and text describing the events.

This battle takes 30 min and attacking/defending text events are appearing during this time. In average, I have about 5 main events and 3 secondary events. When the battle start, the code is aware of the number of main events, but not the secondary. They are calculated on the fly.

The process is like,

newEventTime = previousEventTime + formulaForRandomTimeInterval

What I try to do is to build that formula and avoid having big empty time gaps on the battle and also avoid having a lot of them in a small period.

Also, I want to have slightly more events as the time pass to increase the interest.

Was thinking something such as:

formulaForRandomTimeInterval = (battle_time*2/main_events)*random(0,1)

where battle_time = 30 and main_events the number for that battle.

Any idea for a better solution?

Edit

Sorry for the confusion. Here are a couple of more details about it.

An example of events:

At 3' Player A attacked and made 45 damage. (Main event)
At 8' Player B attacked with a sword and made 110 damage. (Main event)
At 12' the weather changed and started raining. Both players had issues with the mud. (Secondary event)
At 19' Player A made a move but player B dodged the attack. (Main event)
...
...

There is another part of the code that decide which event will be the next and what exactly would be. The battle will be over only when the main events are finished. As I said, each battle has different number of main events of average 5, but the code know this number as the battle starts. But doesn't know the number of secondary events which are created by random.

So, when the code does the loop on the events and decide the type of the next event, the time code is called to decide in what minute it will be appeared.


texts: OpenAL listener position for isometric camera

texts:
I have an isometric camera for an RTS that looks like this:

Basically, I don't know how to set the listener's position in OpenAL because I represent the camera's position with only two coordinates.

I build my projection matrix as a standard orthographic projection:

projectionMatrix = new Matrix4f()
            .setOrtho(-25, 25, -25 / aspect, 25 / aspect, -300, 300);

and my view matrix like so:

viewMatrix.identity()
            .rotate(-rotation.x / 180.0f * Util.PI, 1, 0, 0)
            .rotate(-225.0f / 180.0f * Util.PI, 0, 1, 0)
            .rotate(-rotation.z / 180.0f * Util.PI, 0, 0, 1)
            .scale(zoom)
            .translate(-position.x, 0, -position.y);

Where rotation is a 3D vector of the Euler angles, and position is a 2D vector controlled by the keyboard or dragging the mouse. (rotation.y is ignored)

How would I translate this 2D position into the 3 coordinates required for OpenAL? I tried to give a y-offset like: alListener3f(AL_POSITION, position.x, 20, position.z);, but it gave really weird attenuation results.

(PS: I'm using Java, LWJGL, and JOML for math)


texts: How do I let a game support different rule sets?

texts:
I'm making a MUD game engine that supports D&D , Pathfinder and other tabletop-RPG rule sets. I am starting to build out how characters interact with the world (e.g. dialog, battle, searching for traps).

The engine is pretty loosely coupled, to facilitate swapping out components with downloaded plugins and I want to continue down that path with the rules. I've got an ICharacter interface and both a player and non-playable character interface that inherits from ICharacter. I feel that making a developer re-implement those interfaces when making a plugin because the developer is building a Pathfinder plugin instead of a D&D plugin is poor design. Instead, I want to allow them to specify at runtime (via an editor) what rules each character must abide by when performing specific tasks.

I was thinking I'd have a RuleEngine that would be provided an object and process a rule. Some pseudo code for this:

public void Attack(ICharacter target)
{
    IRuleResult result = RuleEngine.Process(
            RuleFactory.CreateRule("CharacterAttack"),
            this);
    // Check result to see what was given back like damage, hit/miss etc.
}

The user within my editor can specify that for CharacterAttack rule requests, uses PathfinderAttackRule, which would be a Type implementing IRule.

This approach feels like it might be to restrictive though. The interface would have to have some knowledge of D&D implementations, like critical miss, damage amounts etc. What if the user wants to build something that isn't D&D, but just a custom combat rule? The interface doesn't allow it and the engine would expect the interface properties to be usable.

Another option I was thinking about was having delegates perform the rule checks and process the attack.

public void Attack(ICharacter target)
{
    Func<ICharacter, IPlayer, bool> attackCheck =
            RuleFactory.CreateRule<IPlayer>("PreAttach");

    if (attachCheck(target, this))
    {
        // Invokes a delegate fetched by an internal factory.
        RuleFactory.Process<IPlayer>("AttachPlayer");
    }
}

This lets builders specify within the editor what custom delegates to use before an attack starts. (it would be a dropdown list of delegates supported, scanned from the assemblies loaded). The user might want a D&D rule delegate from a plugin they downloaded for pre-attack rule checks, then use a pathfinder rule for the actual attack from a 2nd plugin they downloaded.

Now that I've explained what I'm wanting to do, am I way off base here? Are both of the above examples horribly thought-out and/or is there a better approach to take that is loosely coupled and allows swapping rules out?

As a side-note, I chose player combat as the example, but rules are applied to more than just combat, and more than just players. Rooms, items and other objects will have rules. Some of the rules can be shared, some can not.

Where should I be going with this? I'm looking for general concepts and best-practices.


texts: Anyone have a source for pictures/screenshots/demos of Mud OLC systems?

texts:
I really want to get access to some images of MUD (multi user domain/multi user dungeon) OLC (mud OnLine Creation), to use the structure of npcs/mobs/characters/areas/rooms that muds use on my own webgame project (http://www.ninjawars.net), which features a near predominant use of text itself.

I've played a mud for years, and experienced the OLC system of that mud first hand, but the mud went under, so I'm looking for

I tried compiling the type of Mud it was from source (ROM 2.4) but haven't been able to accomplish that.

I'm expecting that there are some images of the OLC of items/mobs/etc out there already, but I haven't been able to find any to base my implementation of the same concepts in my game off of.  If there's some live way to get access to a demo of OLC, that would be even better.


texts: How do I resolve the inability to get an input stream from URL?

texts:
I am unsure if anyone has ever had problems with this, but I am having difficulty trying to get the URL to work properly however, this is what the logs says

javax.imageio.IIOException: Can't get input stream from URL!
at javax.imageio.ImageIO.read(Unknown Source)

I am unsure now what to do and I hope some of you would be able to assist me.

https://drive.google.com/open?id=0B8TpyQpSFyEPaGtxQzAxYzdRMFE


texts: Gameobject stops moving or gets stuck when colliding with another GameObject

texts: I'm currently making a brick breaker style game. My issue comes when the ball is launched off the pad it gets stuck in between two blocks. I have all the blocks on a "Foreground" layer with an "Order in Layer" set to 0. The Ball is on the "Foreground" with an "Order in Layer" set to 1. But the ball will get stuck and quit moving. I've tried changing the orders of the players and it didn't help. Any thoughts?


texts: What would be the best way to find a Game Object that is closest to another Game Object in unity?

texts:
I made a 2d space shooter game awhile ago and I want to go back into it and overhaul some things. I'll provide a link to the game so anyone can play and get a better understanding of what I'm trying to do.
https://your-pal-drewdle.itch.io/starspeed
With how the game is currently set up, all the enemies are constantly setting their rotation to be facing the position of the player. I want to go back in and add a co-op mode where there are 2 players, however, if I just added a second player without changing any code, the enemies would always be facing Player 1, never directly facing Player 2.
I was thinking that I could get around this by giving each enemy an invisible circle with the center at the enemies position that would constantly expand until it hit one of the two players, I could then set the enemies rotation to face the point where the circle collides with one of the players.
In theory, this would make it so that each enemy is facing towards whichever player is closest to it.
So my question is: How could I go about implementing this in unity? Or, is there a better or more efficient way to do this that would yield the same result? I've spent a decent amount of time researching this and I haven't had much luck.
All help is appreciated, if you need more explanation just let me know and I will do my best to explain in more detail.


texts:
I have a basic camera setup which is angled like so:

x: 30
y: 0
z: 0
Projection: Orthographic

And i attached a C# component to it and made it so the camera moves with a right click and drag movement.

The problem is its not moving at the same amount as the mouse. I had to set a value for scroll speed to 1000 and even then its still too slow.

I want the camera to move with the mouse in a more raw amount, then i wish to add some lerp effect to it so it feels a bit more slick.

I don't know why the movement is so slow, i come from a 2D background and am learning 3D so i suspect my lack of understanding of 3D positions might be the issue.

This is my current code:

using UnityEngine;
using System.Collections;

public class cameraMove : MonoBehaviour {

// VARIABLES
public float panSpeed = 1000.0f;

private Vector3 mouseOrigin;
private bool isPanning;

void Start ()
{
    Vector3 pos = GameObject.Find("Sun").transform.position;
    Camera.main.transform.LookAt (pos);
}

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

    if (Input.GetMouseButtonDown (1))
    {
        //right click was pressed
        mouseOrigin = Input.mousePosition;
        isPanning = true;
    }

    // cancel on button release
    if (!Input.GetMouseButton (1))
    {
        isPanning = false;
    }

    //move camera on X & Y
    if (isPanning)
    {
        Vector3 pos     = Camera.main.ScreenToViewportPoint (mouseOrigin-Input.mousePosition);

        // update x and y but not z
        Vector3 move    = new Vector3 (pos.x * panSpeed, pos.y * panSpeed, 0);

        Camera.main.transform.Translate (move, Space.World);
        mouseOrigin = Input.mousePosition;
    }
}

}


texts: OpenGL render to texture causing edge artifacts

texts:
This is my first post here so any help would be massively appreciated :)

I'm using C++ with SDL and OpenGL 3.3

When rendering directly to screen I get the following result

And when I render to texture I this happens

Anti-aliasing is turned off for both. I'm guessing this has something to do with depth buffer accuracy but I've tried a lot of different methods to improve the result but, no success :( I'm currently using the following code to set up my FBO:

GLuint frameBufferID;
glGenFramebuffers(1, &frameBufferID);
glBindFramebuffer(GL_FRAMEBUFFER, frameBufferID);

glGenTextures(1, &coloursTextureID);

glBindTexture(GL_TEXTURE_2D, coloursTextureID);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,SCREEN_WIDTH,SCREEN_HEIGHT,0,GL_RGB,GL_UNSIGNED_BYTE,NULL);

glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

//Depth buffer setup

GLuint depthrenderbuffer;
glGenRenderbuffers(1, &depthrenderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, depthrenderbuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, SCREEN_WIDTH,SCREEN_HEIGHT);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthrenderbuffer);

glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, coloursTextureID, 0);

GLenum DrawBuffers[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, DrawBuffers); //

if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
        return false;

Thank you so much for any help :)


texts: Corona SDK: Animation takes a long time to play after "prepare" step

texts:
First off, I'm using the current publicly available build, version 2011.704

I'm building a platformer, and have a character that runs along and jumps when the screen is tapped. While jumping, the animation code has him assume a svelte jumping pose, and upon the detection of a collision with the ground, he returns to running. All of this happens.

The problem is that there is this strange gap of time, about 1/2 a second by the feel of it, where my character sits on the first frame of the run animation after landing, before it actually starts playing. This leads me to believe that the problem is somewhere between the "prepare" step of loading up a sprite set's animation sequence and the "play" step. Thanks in advance for any help :).

My code for when my character lands is as follows:

local function collisionHandler ( event )
    if (event.object1.myName == "character") and (event.object2.type == "terrain") then
        inAir = false
        characterInstance:prepare( "run" ) -- TODO: time between prepare and play is curiously long...
        characterInstance:play()
    end
end


texts: I've created a SpriteKit Mac OS X app and I am using a simple finite state machine to manage the game states. I've seen some solutions, especially for C++ games, where a GameState class and a GameStateManager class are used to regulate states of the game through the use of a stack of GameState objects. What I don't understand is what these GameStates objects would be in SpriteKit. Would they be separate SKScene nodes? How would I implement this into a SpriteKit game?


texts: A star pathfinding path too narrow for enemy

texts:
The tiles for my top down 2D shooter are 32x32 and the player and enemies are too. But obstacles like walls and other things can of course be smaller than this - the smallest being 8x8. This causes a problem where a single 8x8 barrier intruding in a 32x32 tile will cause that whole tile to be impassable if my AI Grid is based on 32x32 tiles, like as follows:

This results in a grid with more impassable area than it should have. (On the left the red being the AI grid's impassable area, and on the right, the green being the box2d barriers for the same map section).

The other option is to make the grid 8x8 based and then the grid will perfectly calculate the actual impassable areas but it will create paths too narrow for the 32x32 enemy to pass through. With design I can make the first way (pathfinding grid of 32x32 tiles) work but it's not ideal since you're limited to placing everything in perfect tiles so as to not create impassable areas that are in fact passable.


texts: How do find the right GLxx object for a given function in LWJGL?

texts:
I'm just starting to learn the fundamentals of OpenGL via LWJGL. Every OpenGL function is implemented as a method on a GLxx class. The xx corresponds to the version of the spec when that function was introduced, such as GL20 for functions added in OpenGL 2.0. So far, so good.

The difficulty comes when following tutorials or looking at code that is written against the C API. I'm finding myself having to either guess or Google the version for every single function that I want to use. This is quite time consuming.

Is there a quick way of finding out which version of OpenGL any given feature was introduced? (Or any other way of figuring out the right LWJGL class for a function?).


texts: Rigidbody has unintended effect, velocity limiter from unknown source

texts:
I have made a script that alters a rigidbody's angular velocity. It works well but has one issue, its speed plateaus past a certain point.

Here is the script:

    void Start(){
    //Get references.
    bat = transform.GetChild (0).gameObject;
    rig = bat.GetComponent<Rigidbody> ();
    //Initialize variables.
    initPos = bat.transform.position;

    initAngle = bat.transform.rotation.eulerAngles.y;
    if (leftSide) {
        maxAngle = bat.transform.rotation.eulerAngles.y - 45;
        rig.centerOfMass = bat.transform.localPosition;
    } else {
        maxAngle = bat.transform.rotation.eulerAngles.y + 45;
        rig.centerOfMass = -bat.transform.localPosition;
    }
}

void Update(){
    if(leftSide){ // True and false does the same but mirrored effect.
        if(Input.GetButton ("Left Bat")){// button pressed?
            if(bat.transform.rotation.eulerAngles.y > maxAngle){//lower than max angle?(since this is the mirrored version, its rot starts at 180 and turns CCW, thus the '>')
                currAngle = -1 * turnSpeed; // then allow turning
            } else {// otherwise
                currAngle = 0f; //prevent further turning
            }
        } else {// button not pressed?
            if(bat.transform.rotation.eulerAngles.y < initAngle){// greater than resting angle?(same reason as above explanation)
                currAngle = 1 * turnSpeed; // then automatically return
            } else {//otherwise
                currAngle = 0f; //stop returning
                bat.transform.rotation = Quaternion.Euler (new Vector3 (bat.transform.rotation.eulerAngles.x, initAngle, bat.transform.rotation.eulerAngles.z));// this statement re-aligns the rotation of the flipper its initial state(instantly) to prevent slight kinks due to inconsistencies.
                bat.transform.position = initPos;//turning the flipper for some reason can deviate its own position(slight but cumulative), this returns the flipper to its initial position.
            }
        }
    } else { // default version.
        if(Input.GetButton ("Right Bat")){
            if(bat.transform.rotation.eulerAngles.y < maxAngle){
                currAngle = 1 * turnSpeed;
            } else {
                currAngle = 0f;
            }
        } else {
            if(bat.transform.rotation.eulerAngles.y > initAngle){
                currAngle = -1 * turnSpeed;
            } else {
                currAngle = 0f;
                bat.transform.rotation = Quaternion.Euler (new Vector3 (bat.transform.rotation.eulerAngles.x, initAngle, bat.transform.rotation.eulerAngles.z));
                bat.transform.position = initPos;
            }
        }
    }
}

void FixedUpdate(){// rigidbodies should be processed in fixedupdate I think
    rig.angularVelocity = new Vector3( 0, currAngle, 0);
}

The issue is, no matter how high a value I enter for the movement part, it doesn't get faster than a specific speed. I tried hardcoding a value instead of changing the variable but it didn't make a difference. If I enter a small value, the movement is slower though.


texts: How to load new scenes or models from network in unity or unreal engine?

texts:
I have a project to be done. I had done some research to accomplish some features. Event so, I couldn't find some answers.

The project needs to have some features as follow;
Charachter creation in runtime to be used as an avatar for a user.
Online/Multiplayer interaction with others.
Network updates for scenes and models.

I looked for unity a bit and I am able to do a dummy gameobject and move it around the scene. These types of things are easy to be done as I see. But what I havn't find out yet is;

How I can allow the user create his/her own model with variaty of hairstyles, cloths etc. and save it in localy. When he/she becomes online, that avatar or model of his/her should be updated to the server and donwloaded by the other clients. Or another approach can be modifying the base character and transfer just required some parameters between clients and server rather than the actual model.

It can be interactive and dynamic, therefore it can be flexible as it can accept to import some models or scenes for some specific events or period of the year. Let's say I want to create a theme with Christmas and add some model accordingly. How should the software/game accept those models and know the parameters.

As far as I see, everything is done in coding section. But, I need to upload those model into server and create new event. then clients should get that event and model/scene updates, without needing to create additional executable with new models.

For now I don't have any idea about the server side though. How to setup such environment and communicate?

I know I coudn't done anything so far to show and ask where the problem is, I just need some starting points.

thanks for reading. Have nice day.


texts: Welcoming new players to an MMO game with veteran players who have amassed lots of wealth

texts:
One of the main problems in the game Knight Online has been that the servers that have been open for a long time have users with a lot of items.

If I want to join as a new player, it is not logical for me to play the game in those servers because there is no way that I can catch up with the players there (unless I buy a lot of item with real money). Because, in order to obtain "good" items, you have to be in the regions of the game where you will fight with other users, so as a newbie, there is no chance that you can compete with those users.

For example, there is a trend in KO: a new server opens, after ~two years people get quite strong and almost no new user joins the server, and then those strong users just gain more and more items and sell them. Then the server dies practically, with no new blood joining it and old users eventually leaving.

What is a strategy I can use in my MMO to regulate the wealth distribution, or keep it accessible to new players, even when other players have been accumulating wealth for a long time?


texts: Frame Rate Independence for Non-Linear Increases

texts:
So while working on my game, I decided that I would have a speed variable increase in the fashion

speed += 1/speed;

with the goal being that in the beginning it increases fast and then it increases slow as it gets higher. However this is being called each frame and I need to make it framerate independent, however just scaling it based on time doesn't give the same results throughout. How would I go about creating a framerate independent increase that dampens like this?


texts: Does the protagonist's age matter in a 3rd person shooter?

texts:
There have been very young characters in modern games that wield weapons including firearms before. Two good examples include Ellie from The Last of Us, and Clementine from The Walking Dead. Whilst I don't support the idea of having gun wielding children as characters, I do understand the context of use in the above two examples and the points being made.

I am designing the concepts of a 3rd person action game. The protagonist is a modern male adolescent (about 13 years old) and their age is important because the game's design is centred around the idea of growth and having the protagonist learn and achieve milestones through the game's progression. Being an action game there is combat and weapons including firearms. What I would like to know is, is there particular considerations I need to take with the issue of having firearms and a very young protagonist? At the moment the gameplay progression has the protagonist starting of as completely unarmed, having to initially rely solely on hand to hand combat and other stealth and platformer based skills to progress and learn new abilities. I would like to make more weapons and eventually firearms available to the protagonist, but have their use be completely up to the player and not a necessity for game progression. Most importantly I would like to make sure that the finished game does not come across as promoting the underage use of guns.

So is the protagonist age an important consideration in this type of game genre, or not? For example would I need to make sure I include a tutorial scene where the protagonist is taught how to fire a gun by an adult?


texts:
I want to add some extra functions to editor inspector for UI.Button but, I can't setup my script in this way :-/ How can I write custom inspector for UI Objects ?
This is what I wrote:

using UnityEngine;
using System.Collections;

[CustomEditor(typeof(UnityEngine.UI.Button))]
[CanEditMultipleObjects]
public class AlignmentEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        EditorGUILayout.HelpBox("Test", MessageType.Info);
    }
}


texts: Best practice for setting Effect parameters in XNA

texts:
I want to ask if there is a best practice for setting Effect parameters in XNA. Or in other words, what exactly happens when I call pass.Apply(). I can imagine multiple scenarios:

Each time Apply is called, all effect parameters are transferred to the GPU and therefor it has no real influence how often I set a parameter.
Each time Apply is called, only the parameters that got reset are transferred. So caching Set-operations that don't actually set a new value should be avoided.
Each time Apply is called, only the parameters that got changed are transferred. So caching Set-operations is useless.
This whole questions is bootless because no one of the mentions ways has any noteworthy   impact on game performance.

So the final question: Is it useful to implement some caching of set operation like:

private Matrix _world;
public Matrix World
{
    get{ return _world; }
    set
    {
        if (value == world) return;
        _effect.Parameters["xWorld"].SetValue(value);
        _world = value;
    }
}

Thanking you in anticipation.


texts: how to implement ARVR controller in unity & vuforia

texts:
hello i've been strugling figuring out this thing. i'm trying to make ar controller for my vr cardboard game, so the idea is using AR and VR simultaniously. you will completely in vr game but your phone camera wil be turned on and set to AR mode. while you're in vr mode and your AR camera will detect your marker and repositioned it based on your view and the distance between camera and object. that marker will appear in your vr game and you'll make it as a controller. then maybe you want to make that marker appear as a gun, a sword, a shield or whatever it is that can be work with this concept

or maybe you just can watch it to get the idea if my explanation is not clear enough https://www.youtube.com/watch?v=a_v_a23u6n0

so i'm trying to implement it with vuforia as it's augmented reality API and of course Unity. now i'm on the stage where i already now how to use AR & VR simultaniously and how to transtition between AR to VR or otherwise. i'm still strugling on how to re-potitioning my marker to correct position in my VR world.

i already tried asking this in vuforia forum but there's still no answer until now. if you guys can help me with this it would be a big help !!

thx before


texts: Unity Tilemap.BoxFill is not filling correctly

texts:
So I have a tilemap that already has tiles on it. What I want is to clear it all out and create a solid rectangle of one tile, with which the rest of the monobehaviour will 'carve out' to create a cave complex.
So in my Start() I begin with:
tilemap.ClearAllTiles();

tilemap.BoxFill(Vector3Int.zero, wallTile, -mapSize, -mapSize, mapSize, mapSize);

Let's say mapSize is 8, and "tilemap" is a reference to a Tilemap that previously had some tiles on it. I expect to see all the prior tiles removed, and a new filled area of "wallTile" that goes from -8,-8 to 8,8
Instead I get a single tile at 0,0,0 and that's it.
If I leave out the ClearAllTiles(), it does nothing; the old tiles remain, and no new tiles are placed at all.
The only way it seems to do anything is if the tilemap was empty before in the scene, but I need to work with a tilemap that was previously in use.
Any suggestions on what I'm doing wrong?


texts: Need help with my on collision restart program

texts:
I tried using the program

using UnityEngine;

private void OnTriggerEnter(Collider other)
{
    if (other.tag == "setting_object_tag")
    {
        Application.LoadLevel(Application.loadedLevel);
    }
}

But the OnTriggerEnter command came up with an error saying "a namespace cannot directly contain members such as fields or methods".

And the Application.LoadLevel(Application.loadedLevel); program had an error saying "application.loadedLevel is obsolete, use sceneManager to determine what scenes have been loaded".


texts: Attempting to remove extra "edges" from truncated icosahedron lead to excessively global concequences

texts:
I need a truncated icosahedron.  Blender lets me do that with add -> mesh -> math function -> regular solid (assuming the extra plugin is installed.) So far so good.  However, the mesh that is created does not use ngons.  This means that each hexagon or pentagon face is cut by an unusable edge approximately through the middle.  These extra "lines" destroy the visual symmetry I need for the wireframe.
I have tried deleting the extra edges. This results in the in the removal of far more than just the offending edge.  It blows a huge hole in the whole object. I have tried merging the two faces (which compose the pentagon or hexagon) into an ngon. Somehow this again ends up doing far more than just merge the two parts of the face.
No matter what I try I get unintended effects that are far to global. I have also considered drawing fresh lines over only the desired edges. I cannot figure out how to do this either. I have also extracted the faces and edges with python, but those are too cumbersome to edit... and then what?
How do I get a nice clean geometric wire Frame without distracting extra edges?


texts:
This question in very similar to this question, however I am still confused about how one would implement a story and quests in a finite state automaton RPG.

This is my first game that I am making (my background is in computational science not games) and it is similar to this game. At every frame in my game you are in a state. Examples of states might be Shops, Worlds, Battle state, Inns, Player Stats screen, etc. Each state has a next and previous state that allows one to progress (or back out) to one state after the other. For example if you are currently in the World state, upon moving to the door of an inn the state changes from World to Inn. After clicking to leave the inn the state then reverts back to the World state. All of this appears to be what is described in the this question.

However, quests and story don't seem to fit all that well here and I am confused about what data structures to use for quests and how they should be implemented in the game. One problem with quests is that they cross states and time. For example, you might get a quest from the inn keeper (in state Inn) and then have to go back into the world and perform some action to complete the quest (World state). Maybe you then have to turn in the quest to the potion shop keeper (Potion Shop state). All of this crosses multiple states and knowing when to post dialogue to the screen is time and state dependent.

The easiest solution seems to just create a quest dictionary and make it global. This way all states can see all the quests and data in the quest dictionary (e.g. different flags etc) can be modified at will. The downside here is that a) we are using globals, a generally frowned upon idea by most programmers, b) this quest dictionary could easily become quite large and cumbersome, and c) this idea is hardly OOP. Another idea I had was to create a class called Quest and each quest would just be an instance of a this class. I would then pass these instances to whatever states need them. This is also pretty cumbersome though. Having to pass quests around to different states (and basically hard coding different quests to all the states that need access to them) seems like a bad idea. I could also implement the quests directly into the states. For example the Inn state has methods and flags to deal with quest 1, quest 2, ... etc. This isnt very OOP though because what if I want more then one inn? The quests associated with my first inn would be different from those associated with my second inn (different inn keepers after all!!). I would have to write two different versions of my Inn state class.

I suspect I am missing something obvious here given that my background is not in game design. I understand the finite state automaton at least in terms of moving from location to location within my game, but I am failing to grasp how to do something similar for quests and story. Should I have a global quest data structure? Hopefully this isn't marked as duplicate. Thanks for any help you can give in clarifying this for me.


texts: How can I convert .obj files to .3ds on Mac?

texts:
I am on a Mac. I am currently looking for a tool that is able to correctly convert  .obj files (Wavefront) to .3ds files (Autodesk 3ds Max).

I tried Blender but the exported file failed to include the smoothing groups.

What do you recommend I use?


texts: Why has it become commonplace for NPCs to have one weapon per class instead of variants?

texts: For instance, in Half-Life 2 you have Civil Protection, Combine Soldier and Combine Elite. Each class has a weapon. Is there a shift away from this at all, where the NPCs are matched with the player in the sense that the weapon they choose to use is based upon their advantage, while still maintaining some sense of competitiveness? Is there a reason this became the norm? Does it have to do with all the variables and complications that can arise from doing that?


texts:
I know that the Unity editor can import/export packages which could contains Scenes (levels), but is it possible to import a Scene into a game at runtime without the Unity Editor?

What I am trying to achieve is:

The client should only need to download/install the game once.
The original game would NOT include any Scenes/levels except the start-up Scene.
The original game would also not be aware of any levels so that developers can create more levels AFTER the game was released.
The client should be able to place separate pre-created level-files (whether in some Unity scene format or any other format) into some directory where the game can at RUNTIME import these files without the Unity Editor.
After the game imported these levels, the game should be able to play those new added levels without re-compiling/restarting.

Before I go and create my own special level-format and Unity Scene exporter/importer I was wondering if this problem has not already been solved.


texts: D3D11InfoQueue Isn't filtering out messages

texts:
I have followed the Coordinator's code advice from this page on how to query and filter the messages in the debug layer but it doesn't seem to be working. You can see from the following code that I try to filter out 2 messages but they still keep zinging by in debug output. Does anyone know how to do this correctly? Here is the code:
void CDebugLayer::CreateD3DDebugLayer(void)
{
    if(SUCCEEDED(s_pApplication->m_spEngine->GetD3DObj()->m_spD3DDevice.Get()->QueryInterface( __uuidof(ID3D11Debug), (void**)s_spD3DDebug.GetAddressOf())))
    {
      if(SUCCEEDED(s_spD3DDebug.Get()->QueryInterface( __uuidof(ID3D11InfoQueue), (void**)s_spD3DInfoQueue.GetAddressOf())))
      {
         #ifdef _DEBUG
             s_spD3DInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, true);
             s_spD3DInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_ERROR, true);
             //s_spD3DInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_WARNING, true);
             //s_spD3DInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_INFO, true);
             //s_spD3DInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_MESSAGE, true);
         #endif

         D3D11_MESSAGE_ID stHide [] =
         {
             D3D11_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS,
             D3D11_MESSAGE_ID_OFFERRELEASE_NOT_SUPPORTED
             // Add more message IDs here as needed
         };

         D3D11_INFO_QUEUE_FILTER stFilter;
         memset(&stFilter, 0, sizeof(stFilter));
         stFilter.DenyList.NumIDs  = _countof(stHide);
         stFilter.DenyList.pIDList = stHide;
         HRESULT hr = s_spD3DInfoQueue->AddStorageFilterEntries(&stFilter);
         assert(hr == S_OK);

         D3D11_INFO_QUEUE_FILTER stFilter2;
         memset(&stFilter2, 0, sizeof(stFilter2));
         SIZE_T ByteLength;

         // Perform debug tracking to confirm what is being stored
         uiNumMsgs = s_spD3DInfoQueue->GetNumMessagesAllowedByStorageFilter(); // = 7
         hr = s_spD3DInfoQueue->GetStorageFilter(&stFilter2, &ByteLength);
         assert(hr == S_OK);
         uiNumMsgs = s_spD3DInfoQueue->GetNumMessagesDeniedByStorageFilter();  // = 0

         //Pass copy to Application then store in CEngine for global engine access
         s_pApplication->m_spEngine->SetDebug(s_spD3DDebug.Get());
      }
    }
} // CreateD3DDebugLayer

EDIT
This is the error message I'm trying to filter out:
D3D11 INFO: ID3D11DeviceContext::OfferResources: OfferResources is not supported on operating systems older than Windows 8.  It is valid to call OfferResources, and an offerred resource must still be acquired with ReclaimResources before using it, however there is no benefit to calling OfferResources on this operating system besides testing the code path for Windows 8. [ EXECUTION INFO #3146071: OFFERRELEASE_NOT_SUPPORTED]
Caused by:
ID2D1DeviceContext->EndDraw()

on Windows 7 Sp1 x64. Using Windows SDK 8.1.


texts: AdMob Rewarded Video Ads always shows same ad

texts:
I have integrated AdMob rewarded video ads in my iOS game. Currently, the game is in development stage and not released on the store. Currently, the fill rate is around 30%-40% and I always see the same rewarded video ad. I have following questions:

Why the fill rate is such low? I am testing the game in India and the US.
Why the game is receiving the same ad from AdMob? Are there any settings that can allow different ads from the network?

I would appreciate any suggestions and thoughts on this topic. Thank you

More information:

The test ads gives 95%-98% fill rate. Hence, I think there is no problem with the AdMob SDK configuration. Previously, I tried using AdMob mediation and the ads were coming other ads networks (NO ADS FROM ADMOB).

Is there a AdMob policy where they don't provide enough ads to "under development" game/application?


texts:
I'm new to game development, so please be kind if this is a very simple question.

I have a Sprite sheet with 18 frames of the same character (6 col x 3 rows) moving slightly. I want to get the frames cut out of the sheet into cocos2dx project. There is no xml or plist defining the boundaries but obviously I want the Sprite to be in the same place as it animates as it's an idle action. What's the quickest way to get the frames? I tried texture packer but it seems designed to build a sheet not unpack one?


texts:
So I'm making a game in Python and PyGame.  I have aliens and blocks that each adopt one of several colors; rather than make several copies of them in different colors, I plan on making the sprite once in white, and recoloring individual aliens and blocks.

Problem is, with PyGame, I only know how to use PixelArrays to replace specific colors with other colors (e.g. pure white with pure red, or (255, 255, 255) with (25, 34, 255)).  The sprites aren't going to be super complex, but they will be shaded.

I could use the Python Imaging Library, but I'd kind of like to minimize dependencies.  If this is the best way then so be it.

What I'd like to know is this; how can I use color-blending in PyGame?  More than anything I'm concerned about color-blending algorithms (that ignore certain desired colors, e.g. black for outlines).  Alpha blending is not of concern.


texts: A* : Partial recalculation when one node *changes*

texts:
I have implemented an A* library. Its most interesting feature is that it is "interruptible"; for example, you can stop the calculation loop on a game frame, and resume it later on the following frame.

The library works by creating "Nodes". Each node holds information about a cell in a grid: what is the cost to get there, what is the cell's "parent" (from which it is cheaper to get to the cell) etc. This information is stored until manually released; it is available for other uses if needed.

The "bestNode" is a pointer to one of such nodes. When the search starts, it is the "origin", and it gradually changes until the destination is reached.

Now I'd like to use that information to "partially recalculate" the node information when a node changes; the typical example is a door which opens/closes, allowing new paths/cancelling existing paths. Since I have already calculated the path from the origin to the "changed" node, I'd like to conserve that info, instead of re-calculating everything.

So far my thinking is:

function update(location)
  If the modified location is not in a node, return // not affected
  let node = self.nodes[location]
  let parent = node.parent
  delete all nodes that where created after parent
  add parent to the open list
  bestNode = parent
end

So I have two problems:

I don't know how to select the "nodes created after parent". Would a "unique increasing integer", like in a database, be enough?
This looks kind of complicated and clumsy. Is there a simpler way to do it?

Are there any other "partially-re-calculable" A* algorithms out there? I could not find anything on the subject.

Regards!


texts: GameObject's scale gets 0 after being parented in editor

texts:
1) Before

2) After being parented.

I found a pattern. When adding the child, if the parent's scale.z = 0 the child scale.xyz becomes 0 on parenting. If the parent's scale.z != 0 it works. Another experiment that I tried was, after successfully adding the child(without getting scaled down to 0) and then to make the parent's scale.z = 0, the children's scales don't get affected at all.

Why?


texts: Triangles in a C++ STL Vector as an Objective-C member sometimes draws incorrectly in OpenGL ES

texts:
The polygons draw correctly 80% of the time. When it fails, a vertex is dislocated. The polygon is consistently drawn with the wrong vertex. I checked that the vector is correct during initialization, even when it's wrongly drawn.

I'm using Cocos2d.

The class member:

@interface Polygon : CCSprite {
  std::vector<float> triangleVertices;
}

The draw function called in [Polygon draw]:

+ (void)drawTrianglesWithVertices:(const std::vector<float> &)v
{
    //glEnableClientState(GL_VERTEX_ARRAY);
    glDisable(GL_TEXTURE_2D);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);

    glVertexPointer(2, GL_FLOAT, 0, &v[0]);
    glDrawArrays(GL_TRIANGLES, 0, v.size());

    //glDisableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glEnable(GL_TEXTURE_2D);
}

Any ideas?


texts: How can I escape my field delimiter in my game's packet data?

texts:
For my game I decided to not encrypt my packet's payload. Instead I'm just going to check everything on the server to make sure the packet is legitimate.

As I'm not doing any encryption, my packet's raw payload looks like this:

PacketID|Arg1|Arg2|Arg3[|Arg4...]

Now I want to encode those arguments, so if I have a | in for example a chat message, I can still handle my packet. How can I achieve this?


texts: What are some strategies for handling a zoomed out grid of sprites?

texts:
I'm writing a grid-based 2D game in Unity3D that would ideally use grid sizes of around 200x200 or so, with multiple zoom levels, including all the way out. When I tried render a 200x200 grid at the most zoomed-out level where everything is visible, Unity crapped out saying that there were too many vertices to attempt to draw. This makes sense, as it's trying to render 40,000 sprites.

I was wondering, how do games like Dwarf Fortress and OpenTTD manage so many sprites at once on the screen when the map is zoomed out all the way? Are there any general strategies for handling the rendering of a large number of sprites such as this?


texts: How do I prevent a Box2d dynamic body from sticking to static body walls in zero gravity?

texts:
I'm still making this air hockey game. I have it mostly there now, but the dynamic body which is the puck always sticks to the walls (static body rectangles that form the border of the table).

I read on box2d forums that there is a setting called b2_velocityThreshold, which needs to be set to 0 for games like billiards. I'm assuming that would help me, here, but I can't find any such setting in libgdx box2d.

Is there any setting which I can change to allow the puck to bounce off the walls? If not, how should I go about making such a game in libgdx?


texts: How to sync random incidents over network?

texts:
In my Photon powered game, I have a shotgun weapon and when a player fires a bullet, I call an RPC on other clients and it's bullets get direction from a random function, Random.Range, and on different clients it acts differently.

How can I sync this so in every client, the bullets behave the same, i.e. in this case they would have same directions?

I tried setting the same seed via Random.Seed but it didn't help.


texts: How to determine the best approximate direction

texts:
I want to determine which sprite to use when one agent is "facing" another agent.

My game is 2d, and uses 8-directional movement. Deciding which sprite to use for movement is easy enough since there are only 8 options when moving form one square to another.

def direction(self, start, end):
    # method for determining facing direction
    s_width = int(start[0])
    s_height = int(start[1])
    e_width = int(end[0])
    e_height = int(end[1])
    # check directions
    if s_height < e_height and s_width == e_width:
        return 'down'
    elif s_height < e_height and s_width > e_width:
        return 'downright'
    elif s_height == e_height and s_width > e_width:
        return 'left'
    elif s_height > e_height and s_width > e_width:
        return 'upleft'
    elif s_height > e_height and s_width == e_width:
        return 'up'
    elif s_height > e_height and s_width < e_width:
        return 'upright'
    elif s_height == e_height and s_width < e_width:
        return 'right'
    elif s_height < e_height and s_width < e_width:
        return 'downleft'

It's verbose, but gets the job done. start is the agents current coordinate position, and as you might guess end is the next step in the list of waypoints which makes up an agents path. The problem is that using the same function for determining which sprite should be used when attacking another agent does not look very good at all.

For example, if the target is down, but only one pixel to the right, we would want to show the 'down' sprite, but this function returns 'downright' instead. How can we change it to appropriately return the fitting sprite?


texts: Unity mouse input not working in webplayer build

texts:
I have a button script with the following code

void OnMouseDown()
{
    animation.Play("button-squish");
    enlarged = true;
    audio.PlayOneShot(buttonSound);
}

void OnMouseUpAsButton()
{
    if (enlarged)
    {
        SelectThisButton();
        enlarged = false;

        animation.Play("button-return");
    }
}

void OnMouseExit()
{
    if (enlarged)
    {
        enlarged = false;
        animation.Play("button-return");
    }
}

It works great in the editor, but when I made a build and tested it in Chrome none of the buttons had any response.  Further testing revealed that it did work in Firefox.  Rather than telling people to change their browser if they want to play, I want to make the button code work.  How else can I get the buttons to know when they're being pressed if the built-in stuff isn't working?


texts: Can't parent the standard FPSController during gameplay

texts:
I'm parenting the standard assets FPS controller during play with a simple script. The controller get's parented but also instantly inherits the rotation of the parent. This doesn't happen in Editor mode. This incorrect behavior happens regardless if I move the player with a script or by parenting him with my mouse cursor.

I suspect the error comes from the way the character controller script is set up.

In the FPS controller script the player rotates via mouse movement in the Update function in the following way:

private void Update()
{
    RotateView();
}

private void RotateView()
{
    m_MouseLook.LookRotation (transform, m_Camera.transform);
}

m_MouseLook get's its rotation from m_Camera.transform. It in turn uses transform.localPosition.

I think it's the use of localposition that causes the strange behavior.

How do I fix it?

I added the script that I used to re-parent the fps controller below:

    public Transform ParentTarget;
    public GameObject player;

     void OnTriggerEnter(Collider other)
    {
        player.transform.SetParent(ParentTarget, true);
    }

     void OnTriggerExit(Collider other)
    {
        player.transform.parent = null;
    }

As I said the script is fairly simple and the same error happens when I re-parent the controller by dragging it with my mouse during play.

If I set worldPositionStays to false then the player is offset and doesn't inherit the parent rotations at all. This isn't what I want.

Here is my scene before the player steps unto the trigger. The red box is the trigger. The blue box is the new parent (the parent is rotated 45 degrees)

Here is the original incorrect behavior. The player is instantly rotated 45 degrees as he steps unto the trigger. This is wrong

Here is the behavior when worldPositionStays is set to false. Rotating the parent has no effect. This is wrong.

The desired behavior is to keep the player rotation, and then change it as the parent is rotating after the re-parenting event. This is what would happen if I re-parented any ordinary GameObject.

It is the character controller mouse look part that is most likely causing all the trouble.

I suspect I have to abandon the re-parenting solution and simply add the transforms to the camera mouse look part of the character controller script.

I would be very grateful is someone more knowledgeable would help me out with achieving this. Hopefully by getting re-parenting to work, since it is simpler, and simplicity is always king. I would settle for help with writing a script to add rotations and positions correctly to the controller.


texts:
This is kind of an odd question, but what would be the best solution for rendering a 3D scene without a render window active? The end goal would be to simply render a 3D scene to an image file.

I have done similar things in the past with DirectX and XNA but both required me to have a render window running in-order for the API to initialize. Is there a way to render directly to a texture so that you could perform the rendering with a DLL file in other desktop applications?

The way I envision it working is you create a self contained DLL which has all the rendering logic, a user is using a standard windows application to customize his parameters, once he has them locked he sends a render request to the DLL and it responds with a PNG file of the rendered scene. Ideally this would be a CPU based render since performance is not a huge issue.

Are there APIs out there which one could use to accomplish this?


texts:
RGB is the natural color model for OpenGL. But a lot of other color models exist.
For example, CMY(K) for printers, YUV for JPEG, the little cousins YCbCr and YCoCg, HSL & HSV from the 70's, and so on.
All these models tend to share a common property : they are based on 3 components.

Therefore my question is :
Does it exist a 2-components color model ?
I'm surprised to not find any. I was expecting something along the line of Hue+light could exist.
I guess it cannot be as "complete" as a true 3-components color model, but a fine-enough approximation will be good for my usecase.

The end objective is to store the 2 components into a single BC5 texture (GL_COMPRESSED_RED_GREEN_RGTC2 in OpenGL). The 3rd component requires a second fetch into a second texture, which hurts performance.


texts: From Position/Target to Orientation/Elevation

texts:
I have an orbit camera class that calculates the camera position from Orientation/Elevation and distance from target. I decided to replace these initial values for the camera instantiation with simply Vector3's position and target. How do I calculate Orientation/Elevation and distance from target from these two vectors?

I only got as far as creating a Matrix (Matrix.LookAt) and decomposing it. The translation that can be used for the distance from target partition is trivial, but what do I do with the Quaternion portion to get the elevation/orientation?


texts:
I have a chessboard with all the black pieces that move with this code:

I found that when I move the pieces, they will stack on top of each other. How can I prevent this?

I have since changed the code to this:

When I move a piece over another it still picks that piece up, but now it will occasionally completely prevent any stacked pieces from moving. What can I do, and is there a way to do this while still being able to move one piece over top of another?

Also, the pieces origin and collision box ( all similar to the king) look like this:


texts:
So I'm trying to create a input class that implements a InputHandler & GestureListener in order to support both Android & Desktop. The problem is that not all the methods are being called properly.

Here is the input class definition & a couple of the methods:

public class InputHandler implements GestureListener, InputProcessor{
...
public InputHandler(OrthographicCamera camera, Map m, Player play, Vector2 maxPos) {
...
@Override
public boolean zoom(float originalDistance, float currentDistance) {
    //this.zoom = true;
    this.zoomRatio = originalDistance / currentDistance;
    cam.zoom = cam.zoom * zoomRatio;
    Gdx.app.log("GestureDetector", "Zoom - ratio: " + zoomRatio);
    return true;
}

@Override
public boolean touchDown(int x, int y, int pointerNum, int button) {
    booleanConditions[TOUCH_EVENT] = true;
    this.inputButton = button;
    this.inputFingerNum = pointerNum;
    this.lastTouchEventLoc.set(x,y);
    this.currentCursorPos.set(x,y);

    if(pointerNum == 1) {
        //this.fingerOne = true;
        this.fOnePosition.set(x, y);
    }
    else if(pointerNum == 2) {
        //this.fingerTwo = true;
        this.fTwoPosition.set(x,y);
    }

    Gdx.app.log("GestureDetector", "touch down at " + x + ", " + y + ", pointer: " + pointerNum);
    return true;
}

The touchDown event always occurs but I can never trigger Zoom (or pan among others...). The following is where I register and create the input handler in the "Game Screen".

public class GameScreen implements Screen {
...
   this.inputHandler = new InputHandler(this.cam, this.map, this.player, this.map.maxCamPos);
   Gdx.input.setInputProcessor(this.inputHandler);

Anyone have any ideas why zoom, pan, etc... are not triggering?

Thanks!


texts: Achieving 1 pixel outline around sprites which changes colour depending on the background?

texts:
Here's an example of what I mean:

In this gif, when the character is on the dark background, his outline is almost black, whilst it retains more colour if the background he's on is the sky one. How can I achieve this in Unity? I don't think it's individual sprites


texts: XNA DepthBias increases performance even when EarlyZ is turned off. Why?

texts:
My 3d scene consists of three main polygons:

The first and the second polygons overlap each other (have the same World matrix and use the same geometry), the third one is perpendicular to the first two and is positioned a few meters away from them. All three polygons are rendered with a forward shader that uses clip() function to do alpha cutoffs. As I read in a Radeon's article,
this causes EarlyZ test to be turned off and my simple subjective tests proved it: I had around 480 FPS when the second polygon's texture was empty (resulting in clip being called in every pixel) and dropping to 415 when it had a colorful for-section square in it (see the picture).

I did try to make sure that Z-test happens: I tried drawing the second polygon first while "rising" it above the ground (polygon #2) and thus bringing it closer to camera - it changed nothing. I also tried removing clip() function from the shader and recieved an FPS boost just as expected. But obviously this produced incorrect results as the ground underneath the second polygon was never drawn as it always failed the Z-Test. So I decided to try using DepthBias to be able to draw two polygons one over another and have no depth-fighting. This is what MSDN writes about it:

  Sets or retrieves the depth bias for polygons, which is the amount of
  bias to apply to the depth of a primitive to alleviate depth testing
  problems for primitives of similar depth. The default value is 0.

  Property Value The amount of bias to apply to the depth of a
  primitive. The value ranges from 0 to 16 (inclusive).

When I finally managed to make it work, I surprisingly got a performance boost. Now the thing is I even managed to gain FPS applying it to the third polygon! This is how I render them to gain the best performance:

GraphicsDevice.RasterizerState = CCWLayer1;
DrawSecond(gameTime);
GraphicsDevice.RasterizerState = CCWLayer2;
DrawThird(gameTime);
GraphicsDevice.RasterizerState = CCWLayer3;
DrawFirst(gameTime);

public RasterizerState CCWLayer1 = new RasterizerState()
{
    CullMode = CullMode.CullCounterClockwiseFace,
    DepthBias = 0.005f,
};

public RasterizerState CCWLayer2 = new RasterizerState()
{
    CullMode = CullMode.CullCounterClockwiseFace,
    DepthBias = 1,
};

public RasterizerState CCWLayer3 = new RasterizerState()
{
    CullMode = CullMode.CullCounterClockwiseFace,
    DepthBias = 0.015f,
};

I now 525 FPS and it only drops down to 515 when I draw the huge colored square on the second polygon, which clearly shows that only one set of pixels is being drawn at a time in that particular place (which is similar to EarlyZ test!).

So here is the question: can anyone explain to me what is going on? If I could understand this system better I could make more use of it and gain even more FPS.

Update: now I only draw the two polygons (no other geometry), both using clip(), the one with the colored quad (second) is always closer to the camera. With this code:

DrawSecond(gameTime);
DrawFirst(gameTime);

I get 1.5 ms per frame. With this:

GraphicsDevice.RasterizerState = CCWLayer1;
DrawSecond(gameTime);
GraphicsDevice.RasterizerState = CCWLayer2;
DrawFirst(gameTime);

public RasterizerState CCWLayer1 = new RasterizerState()
{
    CullMode = CullMode.CullCounterClockwiseFace,
    DepthBias = 0.03f,
};

public RasterizerState CCWLayer2 = new RasterizerState()
{
    CullMode = CullMode.CullCounterClockwiseFace,
    DepthBias = 0.045f,
};

I get 1.2 ms.

NO BIAS:

BIAS APPLIED:


texts: Libgdx get texture from Texture Atlas with findRegion

texts:
I have this code

textureAtlas = TextureAtlas("atlas.atlas")

val box = textureAtlas.findRegion("box")

I want to create a texture with "box". Is it possible? box.texture return the original texture, not the regioned. Oh and I don't want to use Sprite and SpriteBatch. I need this in 3D, not 2D.

Thanks


texts: Serializing and writing a Dictionary of Vector2 keys and custom class values in Unity

texts:
I have tried to create code to serialize a Dictionary of <Vector2, Block>, where Block is a custom serializable class, loosely based off of this guide. I need to do this so that I can write this data to disk.

public static void SavePiece (string ObjectName, int index, Dictionary<Vector2, Block> VoxelSlice) {
    string saveFile = FileName (ObjectName, index);

    Stream stream = new FileStream(saveFile, FileMode.Create, FileAccess.Write, FileShare.None);
    formatter.Serialize(stream, VoxelSlice);
    stream.Close();
}

However, I am experiencing this error:

SerializationException: Type UnityEngine.Vector2 is not marked as Serializable.

I'm an absolute beginner to all things serialization and file writing, so I don't have much knowledge to go on, and I'm pretty stuck. I have a few questions:

Is there any way to save lots of data without serializing?
Can I somehow make Vector2 serializable?
While I would rather not spend time re-working my code, would serialization work if I replaced Vector2 with a custom class?
Can Dictionary be serialized at all anyway? A quick search for "unity serialize dictionary" seems to indicate that Dictionary can't be serialized.
If Dictionary can't be serialized, what could I use instead to my store key/value pairs?


texts: Two issues with testing LibGDX on Android

texts:
1) When I test my game on desktop it is 100% fine. When I test it on my Nexus 7 physical device, it is the same except the backgrounds have no color. For example my splash screen has a greenish background, On desktop this is visible, on android it's just a white background.

Splash screen:

@Override
public void render(float delta) {
    manager.update(delta);
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    backgroud.begin(ShapeType.FilledRectangle);
    backgroud.setColor(147, 112, 219, .4f);
    backgroud.filledRect(0, 0, Gdx.graphics.getWidth(),
            Gdx.graphics.getHeight());

    backgroud.end();
    batch.begin();

    leftLogo.draw(batch);

    batch.end();

}

2) When running my game on an Android emulator, it just shows up as a blank black screen on so far 5+ different emulators. What does this usually mean? No errors anywhere.

I also have cfg.useGL20=true;


texts: How do I move a camera to a new X and Y position when the player collides with a certain object?

texts:
The lowdown is this: I'm making a 2D overhead game that takes place in separate screens in a room. Each screen is separated by a few blocks of black space (to give the impression of screens being separate rooms) and a rectangular "transition block" in doorways. My idea is, once a player touches this block, they are moved to the next adjacent screen along with the camera instantly.

I can move a player to the next screen this way, the big hangup that I'm having is moving the camera as well. I want every collision box to have the coordinates needed to set the camera around the next screen once player-box collision happens, similar to the setup I have with the player character.


texts: How to properly visualize Physics2D.CircleCast function in Unity?

texts:
I have a Physics2D.CircleCast() function in order to set true or false if the character is on the ground.
Based on this function, I want to draw a circle, mostly for debugging. I think this method could be quite useful to understand distances between different objects. such as between the character and the platform. The following image shows the variable set to true when the character is on the ground.

In order to draw the circle, my approach was to create an empty object with a Line Renderer component. Then, I created the following script (removing the section in which variables were declared):
public class DrawCircleCast : MonoBehaviour
{
    // Call Game Object
    public GameObject player;

    // Start is called before the first frame update
    void Start()
    {
        sizeValue = (2.0f * Mathf.PI) / 0.01f;
        size = (int)sizeValue;
        size++;

        lr = GetComponent<LineRenderer>();

        lr.material = new Material(Shader.Find("Standard"));
        lr.material.color = Color.cyan;
        lr.startWidth = 0.03f;
        lr.endWidth = 0.03f;
        lr.positionCount = size;
    }

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

    void DrawCircle()
    {
        playerPosition = player.transform.position;
        transform.position = playerPosition;
        radius = player.GetComponent<Player>().shapeRadius; // which is 1f

        theta = 0f;
        thetaScale = 0.01f;

        for (int i = 0; i < size; i++)
        {
            theta += (2.0f * Mathf.PI * thetaScale);
            x = radius * Mathf.Cos(theta);
            y = radius * Mathf.Sin(theta);

            x += gameObject.transform.position.x;
            y += gameObject.transform.position.y;

            pos = new Vector3(x, y, 0);
            lr.SetPosition(i, pos);
        }
    }
}

This piece of code creates a circle around the character, as follows:

So, my next approach consisted on change the circle's position from the character to around the CircleCast measure, in order to have a better position. So I added new variables to the function and changed the circle's position:
void DrawCircle()
{
    playerPosition = player.transform.position;
    platformPosition = platform.transform.position;

    X = playerPosition.x;
    Y = (playerPosition.y + (platformPosition.y)) / 2;

    transform.position = new Vector3(X, Y, 0);
    radius = player.GetComponent<Player>().shapeRadius;

    theta = 0f;
    thetaScale = 0.01f;

    for (int i = 0; i < size; i++)
    {
        theta += (2.0f * Mathf.PI * thetaScale);
        x = radius * Mathf.Cos(theta);
        y = radius * Mathf.Sin(theta);

        x += gameObject.transform.position.x;
        y += gameObject.transform.position.y;

        pos = new Vector3(x, y, 0);
        lr.SetPosition(i, pos);
    }
}

The result changed as follows:

Although the circle's position is now located around the CircleCast measure, I am missing the distance value that I also added to the Physics2D.CircleCast() function.
So my question is how can I improve the circle's position to have a better sense of how CircleCast is measuring the distance between two objects (i.e. character and platform). I couldn't relate the distance, which is a parameter of the Physics2D.CircleCast() function, to the values I used to draw the circle. How the distance affects CircleCast() and how can I use this value to improve the circle's position.
Any ideas would be appreciated. Thanks in advance for your support!


texts: How do I draw a context menu next to my object?

texts:
I want to show a menu next to an item in an inventory. This is what I try to rebuild:

I do this by placing a canvas in 3D world space next to the inventory:

As I don't want the menu to be rotated, I rotated the menu the opposite X value as the camera. The camera has an X rotation of -11, so I rotate the menu by 11 to make it look straight:

Since I don't want the menu to get stuck in the case, I move it closer to the camera:

One can see that the menu is now offset to the left and to the top because of the camera perspective.

How could I offset the menu in such a way that it still aligns with the right top corner of the item?

Thank you!


texts: How does one get adjacency information in a geometry shader?

texts:
If you use triangle_adjacency as the input type of a geometry shader, do you need to do something on the client side besides make the primitive mode triangle_adjacency?

Basically what I'm asking do you need to do anything in your application to make the adjacency information available to the geometry shader besides setting the primitive mode in your draw commands?


texts: How can I play a particle system only when it's visible?

texts:
I am making a game and it has a lot of particle systems in it as special effects, and all of them are supposed to be playing at the same time, but doing that will be heavy on the game's performance, then I thought:
Is it possible to play a particle system only when it is visible to the camera and stop playing it when it is out of range or hidden from the camera, maybe with physics raycasting? If it is, can someone help me to write codes that will do so.