texts: Isometric 3D grid - what order do I render elements in the grid?

texts:
I'm trying to create a screensaver, so strictly speaking this isn't for developing a game, but the subjects discussed on this SE site are a better match than any of the other sites, and I think the answer to my problem will be of value to game developers facing the same issue.

I'm trying to render an isometric grid of bricks, using 2D graphics to represent a 3D grid of bricks.

The algorithm I'm using is rendering them in the wrong order so that bricks are appearing as if they're on top of bricks which they're actually behind. For example:

The white, black, and blue bricks should be rendering behind the long red brick. In terms of render order, they should be drawn before the red brick, but because the red brick is 1 step lower along the Z axis, it gets rendered first.

All of the bricks are aligned to integer coordinates. The "flat" bricks are 1 unit tall, and the "regular" bricks are 3 units tall.

The code I've got so far is:

    for (int i = 0; i < world.getDimension().z; i++) {
        for (int j = world.getDimension().y - 1; j >= 0; j--) {
            for (int k = 0; k < world.getDimension().x; k++) {
                BrickInstance brick = world.getBrickGrid().get(k, j, i);
                if (brick != null && !brick.hasBeenProcessed()) {
                    try {
                        BrickRenderer renderer = getBrickRenderer(brick);
                        renderer.setBrick(brick);
                        renderer.setGraphicsOffset(xOffset, yOffset);
                        renderer.drawBrick(gfx);
                    } catch (InstantiationException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

So it loops along z, y, and x axes to determine render order, and the first time it encounters a brick in the grid, it renders the brick and marks it as done.

I also tried swapping the x and z axes:

    for (int i = 0; i < world.getDimension().x; i++) {
        for (int j = world.getDimension().y - 1; j >= 0; j--) {
            for (int k = 0; k < world.getDimension().z; k++) {
                BrickInstance brick = world.getBrickGrid().get(i, j, k);
                ...

This seems to help at first, but the same problem occurs, a little less obviously:

Here the 1x4x1 green brick is sitting on the 1x1x1 blue brick, but it renders behind it instead of on top of it.

What order should I be rendering these elements so that they overlap correctly? What should my algorithm look like, either in code or pseudo-code or plain English?

Github link (I linked to the specific commit, so 6 months from now it should still link to the right version)


texts: What game objects can have a "material"?

texts:
In Unity, I created an empty GameObject called "Person". I created some child objects to it, such as "head" (a sphere), "body" (a capsule), "leg" (a box), etc. Then, I wanted to change the person's color, so I created a material. However, I could not drag & drop it on the person - I could only drag and drop it on each child object separately.

My question is: what game objects in Unity are allowed to have a "material" on them? And, is there a way I can put a material on a parent object, and let it affect all its child and descendant objects?


texts: Why would I receive a NullReferenceException when the object is clearly set, and still works?

texts:
I am getting the exception "NullReferenceException: Object reference not set to an instance of an object" while changing text of a user interface text field, even though the text changes successfully, as you can see in the image. It still gives me a null reference exception; if it was not set, then how can it change the text?

I don't know what is happening, here. I have re-imported the project, but the problem stays.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Menu : MonoBehaviour
{

    public Text headingaccuracy;
    public Text magneticheading;
    public Text rawvector;
    public Text trueheading;

    private void Start()
    {
        headingaccuracy.text = "Heading Accuracy  ";
    }
}


texts: How do I center the view around specific coordinates in SFML

texts:
I want to use sf::View in SFML in order to change the position of the view, such that the player sprite is always in the center of the screen. Thus I want to write a function which allows me to input a set of coordinates and thus center the screen around those coordinates. In addition I want to be able to set a limit to this, such that when the player reaches the side of the map, that axis of the camera stops following the player, as it has reached a "limit". How do I achieve this?

Thank you in advance.


texts: How can I combine multiple bodies into one in Farseer?

texts:
I want to create a windmill in Farseer, but I don't know how to combine the 3 windmill sails bodies to one body. During gameplay, the sails could get destroyed. For example, if another body hits one of the sails, then this sail will be destroyed, separating the sails. This means the parts should be able to come apart again.

I'll use the following sprites to create the windmill:

The final windmill should look like this:

What method should I use to combine these together, but have them able to separate when destroyed?


texts: Trigger issues (multiple events, enter/exit)

texts:
not sure if this is a scripting issue or if I've implemented something wrong with the colliders, but here it goes:
All I want is a simple platform trigger that registers when the player steps on it and when they get leave.
I have BoxColliders with IsTrigger on both the platform and the player and in general everything works okay.
However there are some strange edge cases where the OnTriggerExit happens immediately after the OnTriggerEnter. Once I've even managed to stand in a place where it constantly went from Enter to Exit to Enter etc. without the player moving at all!
So I put position outputs in the debug text and the positions of where the Enter/Exit happens is in really strange places, nowhere near the trigger volume!

Initially I put a cooldown on the trigger volume, so it could only trigger every second but that doesn't solve the issue of the Exit triggering for some reason when it shouldn't.
Here's my code for the platform:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TriggerScript : MonoBehaviour
{
    public Collider player;
    public Material activeMaterial, inactiveMaterial;
    public float TriggerVolumeCooldown = 1f;

    private Renderer m_Renderer;
    private bool m_IsOnCooldown;
    private float m_CooldownStartTimestamp;

void Start()
{
    m_Renderer = GetComponent<Renderer>();
    m_Renderer.material = inactiveMaterial;
    m_IsOnCooldown = false;
}

void OnTriggerEnter(Collider collider)
{
    if (collider == player && !m_IsOnCooldown)
    {
        print(" Player entered " + collider.name + " CD: " + m_IsOnCooldown + " xyz: " + collider.GetComponentInParent<Transform>().position);
        m_Renderer.material = activeMaterial;
        m_IsOnCooldown = true;
        m_CooldownStartTimestamp = Time.time;
    }
    else
    {
        print("cooldown");
    }
}

void OnTriggerExit(Collider collider)
{
    //i++;
    if (collider == player)
    {
        print(" Player left " + collider.name + " xyz: " + collider.GetComponentInParent<Transform>().position);
        m_Renderer.material = inactiveMaterial;
    }
}

void Update()
{
    if (m_IsOnCooldown)
    {
        if (Time.time - m_CooldownStartTimestamp > TriggerVolumeCooldown)
        {
            m_IsOnCooldown = false;
        }
    }
}

}


texts:
PlayerMovement.cs :
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody rb;
    public float forwardForce=2000f;

    void FixedUpdate()
    {
        rb.AddForce(0,0,forwardForce * Time.deltaTime);
        if(Input.GetKey("d")){
            rb.AddForce(30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
        }else if(Input.GetKey("a")){
            rb.AddForce(-30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
        }

        if(!Input.touchSupported)
        {
            // Still support PC keys
            if(Input.GetKey(KeyCode.D))
            {
                rb.AddForce(30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
            }
            else if(Input.GetKey(KeyCode.A))
            {
                rb.AddForce(-30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
            }
        }
        else
        {
            // For touch devices
            if(Input.touchCount == 1)
            {
                var touch = Input.GetTouch(0);
                var touchPos = touch.position;

                var isRight = touchPos.x >= Screen.width / 2f;

                if(isRight)
                {
                    rb.AddForce(30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
                }
                else
                {
                    rb.AddForce(-30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
                }
            }
        }

//        if(Physics.Raycast(transform.position,Vector3.down,0.5f)==false){
            // rb.velocity = new Vector3(0, rb.velocity.y, 0);
//            rb.constraints = RigidbodyConstraints.FreezePositionZ;
//        }else{
//            rb.constraints = RigidbodyConstraints.None;
//        }

        if(rb.position.y < -1f){
            FindObjectOfType<GameManager>().EndGame();
        }
    }
}

I tried to debug am I able to click any button. Than, I noticed I got message in console. I think I am unable to add force to player.
PlayerCollision.cs :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerCollision : MonoBehaviour
{

    public PlayerMovement movement;

    void OnCollisionEnter(Collision collisionInfo)
    {
        Debug.Log(collisionInfo.collider.name);
        if (collisionInfo.collider.tag == "obstacle")
        {
            movement.enabled = false;
            FindObjectOfType<GameManager>().EndGame();
        }else if(collisionInfo.collider.name == "END"){
            FindObjectOfType<GameManager>().CompleteLevel();
        }
    }
    void Restart(){
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}

Ground:

Actually, now I think physics isn't working on Player.

The Player object is floating. it isn't falling down. Even, it has RigidBody it's not freeze while running the game.


texts: How to simulate cylinder shape in collision detection?

texts: AFAIK, many physics engines like Physx and Havok don't incorporate cylinder as basic shape because it is expensive than sphere, box and capsule. But bullet engine does incorporate cylinder as a basic shape. Do they found any fast algorithm to simulate the cylinder and what is that?


texts: I wan tto give delay in java without using thread. I need to load images one by one with approx half second delay. Is there any way to do this other than thread because if I am using thread my whole game is going into the sleep mode.


texts: How can I create an aperture-closing effect?

texts:
I'm looking to create an effect like this in a game I'm making:

I would describe it as a camera aperture closing.

I have the following requirements:

I need to be able to reverse the fade (open the aperture instead of close it)
The hole should close/open towards/from a given center point.

I can't really think of a great way to do this. I'm so used to SpriteBatch and Texture2D that I don't know how I could draw an ellipse style effect.

My current thoughts would be to make a few Texture2D frames and then animated them on the screen but that seems crazy.

If I just wanted to create pseudo-code to do it, it would probably look something like this (coming from a GDI/GDI+ background):

Call: Create_Relevant_Ellipse_Bounds;
Call: Set_Graphics_Exclusion_Clip_From_Ellipse;
Call: Fill_BackColor_With_Black_Using_Clip;
Call: Update_Ellipse_Bounds;
Call: Wait_For_Next_Draw;


texts: How to scale bitmap font without having it pixelated

texts: How do i increase the size of a bitmap font without having it get pixelated, in libgdx?


texts: Is it possible to measure Used vs Unused time in a 60hz frame in Unity?

texts:
In custom engines I've often made a frame rate meter that shows how much of the each frame was actually used. In other words if the game is locked to 60fps using vblank I show a graph of how much of each frame was used for processing and how much was just waiting for the next vblank. This gives a visual indication of how much more can be added to a scene without hitting my frame rate budget.

Is this possible to do in Unity?

What I tried:

I made a script that creates a System.Diagnostics.StopWatch and starts it. I set that script's Script Execution Order to be the very first script.

In the script's Update I record the ElapsedTicks from the stopwatch as startTicks. In the scripts's OnGUI I compute a deltaTicks as in

long deltaTicks = m_stopWatch.ElapsedTicks - startTicks;

I can then compute how much of a 60fps frame was taken with

long ticksPerFrame = System.Diagnostics.Stopwatch.Frequency / 60;
float amountOfFrameUsed = (float)((double)deltaTicks / ticksPerFrame);

Note: I get that OnGUI is called multiple times per frame but the way I end up storing amountOfFrameUsed I only end up recording the time from the last time OnGUI is called that frame.

Anyway, this does give me a graph to look at but I have no idea if what it's slowing me is correct for Unity.

In my own engine I'd record the time at VBlank and then in my code, when all processing was done I'd compute the elapsed time since vblank.

Is what I'm doing correct? Is there a better or another way I should be doing this? (note: I have not used the profiler because I wanted to see this FPS meter in a production app, not in the Editor where there is tons of overhead).


texts: Animations not working using scene2d and actor class in LibGDX

texts:
I have a problem making a simple animation using the Actor class.

public class fondoanima extends Actor {

protected TextureRegion currentFrame;
protected TextureRegion[] walkFrames;
protected Animation walkAnimation, idleAnimation, currentAnimation;
private Texture texture;
float stateTime;

public fondoanima() {

    texture = new Texture(Gdx.files.internal("image.png"));
    TextureRegion[][] tmp = TextureRegion.split(texture, texture.getWidth()/5, texture.getHeight() / 1);

    walkFrames = new TextureRegion[5];
    for (int j = 0; j < 5; j++) {
        walkFrames[j] = tmp[0][j];
    }

    walkAnimation = new Animation(0.4f, walkFrames);
    currentAnimation = walkAnimation;

    stateTime = 0f;

    }

@Override
public void draw(Batch batch, float parentAlpha) {
    // TODO Auto-generated method stub
    super.draw(batch, parentAlpha);

    Color col = getColor();
    batch.setColor(col.r, col.g, col.b, col.a*parentAlpha);
        batch.draw(currentFrame, 10, 10);

}

@Override
public void act(float delta) {
    // TODO Auto-generated method stub
    super.act(delta);

         stateTime += Gdx.graphics.getDeltaTime();
        currentFrame = currentAnimation.getKeyFrame(stateTime, true);
}

public void dispose(){}

I have been guided by different examples and the wiki, But I get not make it work. It is an animation that will be as the background. (image.png=>1600x350=>5 images are linked horizontally). Thanks.

Solution:
initialize currentFrame = tmp[0][0];


texts: I am working on a game(a platformer) that is physics and momentum based. I want to make it so that the player(a single dot) can bounce off of the lines with correct physics, but to do that, I need to know which line it is touching. Knowing if it is touching a line or not is simple. I just have to check for a white dot where the player is. The problem is that I cannot find out which line the player is touching. I thought of making a ton of rects along each line and testing for the player, but that would cause too much lag. Does anyone have any ideas? :/


texts: "exception at 0x53C227FF (msvcr110d.dll)" with SOIL library

texts:
I'm creating a game in C++ using OpenGL, and decided to go with the SOIL library for image loading, as I have used it in the past to great effect. The problem is, in my newest game, trying to load an image with SOIL throws the following runtime error:

This error points to this part:

// SOIL.c
int query_NPOT_capability( void )
{
/*  check for the capability    */
if( has_NPOT_capability == SOIL_CAPABILITY_UNKNOWN )
{
    /*  we haven't yet checked for the capability, do so    */
    if(
        (NULL == strstr( (char const*)glGetString( GL_EXTENSIONS ),
            "GL_ARB_texture_non_power_of_two" ) )
        ) //############ it points here ############//
    {
        /*  not there, flag the failure */
        has_NPOT_capability = SOIL_CAPABILITY_NONE;
    } else
    {
        /*  it's there! */
        has_NPOT_capability = SOIL_CAPABILITY_PRESENT;
    }
}
/*  let the user know if we can do non-power-of-two textures or not */
return has_NPOT_capability;
}

Since it points to the line where SOIL tries to access the OpenGL extensions, I think that for some reason SOIL is trying to load the texture before an OpenGL context is created. The problem is, I've gone through the entire solution, and there is only one place where SOIL has to load a texture, and it happens long after the OpenGL context is created.

This is the part where it loads the texture...

   //Init glfw
if (!glfwInit())
{
    fprintf(stderr, "GLFW Initialization has failed!\n");
    exit(EXIT_FAILURE);
}
printf("GLFW Initialized.\n");

//Process the command line arguments
processCmdArgs(argc, argv);

//Create the window
glfwWindowHint(GLFW_SAMPLES, g_aaSamples);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
g_mainWindow = glfwCreateWindow(g_screenWidth, g_screenHeight, "Voxel Shipyard", g_fullScreen ? glfwGetPrimaryMonitor() : nullptr, nullptr);
if (!g_mainWindow)
{
    fprintf(stderr, "Could not create GLFW window!\n");
    closeOGL();
    exit(EXIT_FAILURE);
}
glfwMakeContextCurrent(g_mainWindow);
printf("Window and OpenGL rendering context created.\n");

//Create the internal rendering components
prepareScreen();

//Init glew
glewExperimental = GL_TRUE;
int err = glewInit();
if (err != GLEW_OK)
{
    fprintf(stderr, "GLEW initialization failed!\n");
    fprintf(stderr, "%s\n", glewGetErrorString(err));
    closeOGL();
    exit(EXIT_FAILURE);
}
printf("GLEW initialized.\n"); <-- Sucessfully creates an OpenGL context

//Initialize the app
g_app = new App();
g_app->PreInit();
g_app->Init();
g_app->PostInit(); <-- Loads the texture (after the context is created)

...and debug printing to the console CONFIRMS that the OpenGL context was created before the texture loading was attempted.

So my question is if anyone is familiar with this specific error, or knows if there is a specific instance as to why SOIL would think OpenGL isn't initialized yet.


texts: Maximizing efficiency on space distribution

texts:
Imagine you have a room X metres long. You have different parts P of diverse lenghts L and importances I. However, the quantity Q of each part is limited and different. You want to fit in as many of these parts as possible while also prioritizing those with higher importances. ¿How do you do it?

I've been trying to find a better way to resolve this than testing all combinations, but without success. ¿Any suggestions? (And by the way, if this kind of problem has a name, please post it as a comment or a reply)

  Example:

  Lenth of room: 5m
  Number of parts: 4
  Part data:

    Part 1: 0.75m, 1 Units, 2 Importance
    Part 2: 1m, 3 Unit, 0.75  Importance
    Part 3: 0.47m, 4 Units, 1  Importance
    Part 4: 1.33m, 2 Units, 3 Importance

  Now as X, P, L, Q:
  X = 5;
  P.Lenght = 4;

  P0.L = 0.75;
  P0.Q = 1;
  P0.I = 2;

  P1.L = 1;
  P1.Q = 3;
  P1.I = 0.75;

  P2.L = 0.47;
  P2.Q = 4;
  P2.I = 1;

  P3.L = 1.33;
  P3.Q = 2;
  P3.I = 3;


texts: OpenGL's matrix stack vs Hand multiplying

texts:
Which is more efficient using OpenGL's transformation stack or applying the transformations by hand.

I've often heard that you should minimize the number of state transitions in your graphics pipeline.  Pushing and popping translation matrices seem like a big change.  However, I wonder if the graphics card might be able to more than make up for pipeline hiccup by using its parallel execution hardware to bulk multiply the vertices.

My specific case.  I have font rendered to a sprite sheet.  The coordinates of each character or a string are calculated and added to a vertex buffer.  Now I need to move that string.  Would it be better to iterate through the vertex buffer and adjust each of the vertices by hand or temporarily push a new translation matrix?


texts:
What is the difference between the two circles in the rotation tool in Unity?
In 2D rotation tool there are two circles which allow to rotate an object. And I can not conceive a difference between them. Could someone explain me what is the purpose of having both of them? It seems they both do the same.


texts: Bubble shooter clone, structure for storing/adding of bubbles

texts:
Im having a few issues trying to figure out what the best data structure to use for storing bubbles on the grid, and how to connect new bubbles to the grid when a moving ball collides with a ball on the grid.

My first implementation was to create a 2d array and populate it with a bunch of bubbles. I then iterate through the array and make a connection between bubbles only if there are adjacent bubbles in all directions from the current bubble. After Ive build the grid, and made all the connections, I added each bubble to list that I can look up and find connections between bubbles when a collision is detected.

When a moving ball collides with a stationary ball, I create a connection between the ball and then run a recursive BFS search from the colliding ball, finding all balls that are of the same color of the ball I just collided with. This works, but isnt very bulletproof, as I often get broken connections between balls when certain balls are deleted, or often groups of balls wont disappear that should.

My second implementation was to use a Hex grid. I had read similar questions on here where users suggested using a hex grid, so I thought I would try that approach. Again, I created a 2d array with a bunch of bubbles and tried running a mapper which mapped certain balls to each other depending on where they are in the grid. I still had a bunch of issues with connections, and often connection would end up getting broken or not connected properly.

Theres a lot of edge cases that Im still stuck on that im not exactly sure how to solve. For example, when I a colliding ball makes a connection with another ball, how should I deal with if that ball collides with a second ball at the same time. Or how should I look for balls within a certain area.

I feel like Im just overthinking this, and making the problem way more complex then it needs to be.


texts:
Does anyone have experience implementing this triangle-triangle intersection code that I found online? I don't understand it. I made a post on Stack Overflow about this and got the advice that:

  From the sample code it seems like what it mean by an edge is the vector from the originating vertex to the end vertex. In the case of a triangle with three vertices C1, C2, C3, the two >input edges would be P1 = C2-C1, P2=C3-C1

I tried feeding it my triangles like that, but ended up with a pretty wildly inaccurate false positive:

Triangle* triangle1 = new Triangle(glm::vec3(-0.323523998f, 1.68264794f, -1.20740700f),
        glm::vec3(-0.478354007f, 1.68264794f, -1.15484905f),
        glm::vec3(-0.465537012f, 1.80764794f, -1.12390494f));
Triangle* triangle2 = new Triangle(glm::vec3(1.00000000f, -0.682647943f, -0.999998987f),
        glm::vec3(1.00000000f, -2.68264794f, -1.00000000f),
        glm::vec3(-1.00000000f, -0.682647943f, -1.00000000f));
collisionDetector.checkForCollision(triangle1, triangle2)

returned true, with the collisionDetector being a wrapper for this function and checkForCollision defined as:

bool TriangleTriangleCollision::checkForCollision(Triangle* triangle1, Triangle* triangle2)
{
    return checkForCollision(triangle1->_vertex0, triangle1->_vertex1, triangle1->_vertex2,
        triangle2->_vertex0, triangle2->_vertex1, triangle2->_vertex2);
}

bool TriangleTriangleCollision::checkForCollision(glm::vec3 t1vert0, glm::vec3 t1vert1,
    glm::vec3 t1vert2, glm::vec3 t2vert0, glm::vec3 t2vert1, glm::vec3 t2vert2)
{
    double C1[3], P1[3], P2[3], D1[3], Q1[3], Q2[3];

    glmVecToArray(t1vert0, C1);
    glmVecToArray(t1vert1 - t1vert0, P1);
    glmVecToArray(t1vert2 - t1vert0, P2);

    glmVecToArray(t2vert0, D1);
    glmVecToArray(t2vert1 - t2vert0, Q1);
    glmVecToArray(t2vert2 - t2vert0, Q1);

    return (tr_tri_intersect3D(C1, P1, P2, D1, Q1, Q2) > 0);
}

void TriangleTriangleCollision::glmVecToArray(const glm::vec3 vector, double v[3])
{
    v[0] = vector.x;
    v[1] = vector.y;
    v[2] = vector.z;
}

unless I am wrong, these two triangles are not at all near each other.

If not, does anyone have any reliable triangle-triangle intersection code? I'm on a time crunch working on a collision detection system for a school project and spent all my time implementing the code to weed out triangle-triangle collision detection so I'm going to have to use some code from someone else and just cite it in my program.


texts: How can I implement caching into my Rectangular Symmetry Reduction pathfinding algorithm?

texts:
I have a working implementation of Rectangular Symmetry Reduction (see here and here for more information on RSR).

I'm interested in further improving performance over raw A* by implementing caching of paths. My assumptions are as follows:

We're working on a 4-connect square grid
The Destination position is more important than the start position.
Because RSR is made possible via contiguous rectangular regions, the fastest path between two points in the same region is likely to be the same (but not always)

It's at this point that I get stuck -- I'm unsure how best to use those assumptions and the information generated by a path calculation to better future path calculations.

I've considered storing the path cost from the final waypoint (that is, where the resultant path leaves the first rectangle), but as far as I've been able to consider, that is only useful if I have the path cost from every other potential waypoint on the rectangle's edge -- so good if you've got a lot of rectangular rooms separated by doors (few open edges), less so if you're pathing around wide open fields with a few scattered rocks (many open edges).

Essentially, my intuition is that going that route would potentially necessitate a lot of pathfinding before caching could provide any returns, so I'm looking for someone else's opinion on whether I'm on the right track, or if I'm missing a simpler way of implementing a performance-boosting caching algorithm.

Thoughts? I'm more than happy to discuss more of what I understand of the algorithm or share specific code if requested.


texts: Java enum pairs / "subenum" or what exactly?

texts:
I have an RPG-style Item class and I stored the type of the item in enum (itemType.sword). I want to store subtype too (itemSubtype.long), but I want to express the relation between two data type (sword can be long, short etc. but shield can't be long or short, only round, tower etc). I know this is wrong source code but similar what I want:

enum type
{
    sword;
}

//not valid code!
enum swordSubtype extends type.sword
{
    short,
    long
}

Question: How can I define this connection between two data type (or more exactly: two value of the data types), what is the most simple and standard way?

Array-like data with all valid (itemType,itemSubtype) enum pairs or (itemType,itemSubtype[]) so more subtype for one type, it would be the best. OK but how can I construct this simplest way?
Special enum with "subenum" set or second level enum or anything else if it does exists
2 dimensional "canBePairs" array, itemType and itemSubtype dimensions with all type and subtype and boolean elements, "true" means itemType (first dimension) and itemSubtype (second dimension) are okay, "false" means not okay
Other better idea

Thank you very much!


texts:
I'm trying to draw elements from a texture atlas with OpenGL ES 2.0

Currently, I'm drawing my elements using something like this in the shader:

uniform mat4 uCamera;

uniform mat4 uModel;
attribute vec4  aPosition;
attribute vec4  aColor;
attribute vec2  aTextCoord;

uniform vec2 offset;
uniform vec2 scale;

varying lowp vec4 vColor;
varying lowp vec2 vUV;

void main()
{
    vUV = offset + aTextCoord * scale;
    gl_Position = (uCamera * uModel) * aPosition;
    vColor  = aColor;
}

For each element to draw I send it's offset and scale to the shader. The problem with this method is: I can't rotate the element but it's not a problem for now.

I would like to know, which is better for performance:

Send uniforms like that for each element on every frame
Update quad geometry (uvs) for each element

Thanks!


texts: Pros and Cons of making geometry not only leaf in scene heirarchy

texts: I was wondering why most game and graphics engines prefer to make geometry/mesh class only as a leaf in the scene hierarchy; more precisely they are not allowed to have children. So what are the pros. and cons of making it able to have children from performance and software design point of view?


texts: How would you create a single object effect with ecs like a shadow moving straight and a bouncing ball?

texts:
I have a bullet that has projectile motion, this bullet is also an effect. Also the bullet has a shadow, that fade on specific time relatively  to bullet. So I'm thinking of using the libgdx particle system (I am using an Entity Component-based System approach) so I created a particle component, or would you rather recommend to create another component for that specific effect? like a projectile component and linear component or a motion component in general.

Creating shadow, bullet, and other single object effect entity. Notice that I doesn't use any Box2d Physics yet.

Entity shadow = engine.createEntity();

... add texture, transform, movement or with gravity components

engine.addEntity(shadow);

To move the shadow entity

// Shadow
Vector2 linear = ...
movement.velocity.set(linear);

To move the bullet entity

// Bullet
gravity.vertical = 9.8f; // set earth gravity
Vector2 projectile = ...
movement.velocity.set(projectile);
// Also I need to calculate the time to reach its destination to add in lifespan

To create and move a ball entity

Entity ball = ...

// assume that the world has zero horizontal and 9.8 vertical Vector2 gravity
// set the physics body and set restitution to have bounce
physics.body = createCircleBody(...);

add(texture);
add(transform);
add(physics);

Every single object has lifespan so I added some lifespan component

LifespanComponent lifespan = ...
lifespan.duration = 0.5f; // let say half a second

Then the lifespan system will handle if the time reached the duration, then remove entity.

The problem is, Because Particle System has many moving objects, I don't know if I could use libgdx Particle System to create a single moving object that has a lifespan, like shadow, ball, bullet.


texts: Get pressed character in LWJGL (Ignoring modifier keys)

texts:
I have a basic text field setup in LWJGL, however pressing any modifier keys (Shift, F1-19, Page Up, etc.) inputs a space into the text field. How would I ignore those characters? Here's some code so far.

Note: value is a string variable

while (Keyboard.next()) {
    if (Keyboard.getEventKeyState()) {
        if (Keyboard.getEventKey() == Keyboard.KEY_BACK) { //Backspace
            if (value.length() > 0) {
                value = value.substring(0, value.length() - 1);
            }
        } else if (/* Character is not a modifier key*/) {
            value += Keyboard.getEventCharacter();
        }
    }
}


texts: Play animation with the help of the animator once, wait until it ends playing and continue script code

texts:
How can I play animation with the help of the animator once, wait until it ends playing and continue script code?

I am playing an animation with the help of the animator this way:

animator.SetBool(what, toAnimate);

I am starting my animation in that way:

rabit.animate("die", true);
I am making a transition to another animation this way:

rabit.animate("die", false);

I need to wait after step 1. before making step 2. so that animation plays. How can I do that?


texts: How to vary the initial velocity of a jump based on hold time?

texts:
What I want to do is, the longer player holds the screen, the longer distance the object will jump when they release the hold.

Here is my code:

private float timeBeginTap;
switch (touch.phase)
{
    // Finger start touching the screen
    case TouchPhase.Began:
        print("Start tapping");
        timeBeginTap = Time.time;
        break;

    // Finger leaving the screen
    case TouchPhase.Ended:
        //when finger release,the object jump
        float timeHolding = Time.time - timeBeginTap;
        Debug.Log($"The player1 touched the screen for {timeHolding} seconds.");

        Vector2 jumpVelocity = new Vector2(timeHolding, timeHolding);
        rb.velocity = rb.velocity + jumpVelocity;

        break;
}

So with the code above I can get the value like 0.6324167, or 0.423567 for timeHolding, which is the amount of time that user hold the finger on screen.

And I able to make the object jump by using this code below:

Vector2 jumpVelocity = new Vector2(timeHolding,timeHolding);
rb.velocity = rb.velocity + jumpVelocity;

But the distance traveled or "force" with which the object jumps is very small and it doesn't make sense. Therefore I make an attempt with the code below:

float right = 5;
float up = 10;
Vector2 jumpVelocity = new Vector2(right*timeHolding,up*timeHolding);
rb.velocity = rb.velocity + jumpVelocity;

With the code above, the distance is of course longer. But it feels constant and not dynamic, because the relationship between the Vector2's X and Y value is always constant.

Therefore my question is,

What is the correct way to define the values of X and Y for a Vector2 object based on the value of Time?

If I missed anything, please guide me in the right direction.

Desired Outcome:

For example,the velocity added to the box is to let the box jump from pole to another pole and stand on it.

The velocity is define by using the time user hold on the screen,the longer the user hold on screen,the greater the velocity,means the x,y value of Vector2 is define by the timeHolding.

Now when I hold the screen for the long time,the box will jump to  the 3rd or 4th pole,and it not guarantee will reach the pole.Like everything is by chance.

What I want is,the box will jump from 1st pole to 2nd pole,from 2nd to the 3rd and continuously.At the same time,the velocity to go higher or lower and the distance is depends on the time user hold the screen.

This is what I want and my limited understanding of the problem.


texts:
I have downloaded robotic demo from here. It contains robotic arm, which I can move by keyboard

While moving, parts of arm oscillating naturally, which proves that physics is applied to them.
How can I "relax" joints? I.e. turn off them from maintaining fixed positions and allow them fall down physically correct?


texts: Disconnect signal that connected from script

texts:
I connected signal when a scene is instantiated.

# AsteroidSpawner.gd
func spawn_asteroid():
    var asteroid_instance = asteroid_scene.instance()
    asteroid_instance.connect("destroy", self, "handle_asteroid_destroy")
    add_child(asteroid_instance)
func handle_asteroid_destroy():
    ... # TO SOME STUFFS WHEN ASTEROID DESTROYED...
    ... # How to disconnect this handler from here?

But the problem is, I want to disconnect handle_asteroid_destroy handler when object destroyed(or will destroy, use queue_free). How do I disconnect signal on specific object? Is Godot Engine will free the handler automatically?


texts: I have a game based on combining 2 ingredients to create a product. What is the best way to code this? (Unity)

texts:
So to go a bit more in depth, in my game, you can combine a variety of ingredients to make a product. For example, you could combine water and dirt to make mud.

What I am currently doing to achieve this is by listing each combination possibility that a particular ingredient has. The one thing i managed to do to make it a little more efficient is that I managed to remove duplicates (So for example, if i have coded ingredientA + IngredientB = Cheese, there isn't another entry for IngredientB + Ingredient A = Cheese).

The problem I have with my method is that it is very annoying adding new ingredients. If i do so, I have to go back to every previous ingredient i have coded, and add it's interaction with the ingredient(s) i want to add.

The amount of ingredients I have means this is becoming increasingly time consuming.

Is there a better way to do this?

This is a Unity game, coded in C#. Let me know if you need any further info.


texts: C# How to add inventory to player, NPCs, and in-game objects?

texts:
I'm a beginner in C# and trying to implement a player, an item interface, and some kind of storage system (for player inventory, NPC inventory/drop list, and storage like chests), and having some trouble implementing it in a way that requires the least work for a large amount of class types (and instances).

This is my current Player class:

namespace RogueBase.Classes
{
    public class Player
    {
        public Iitem[] inventory { get; set; }

        private int _hp;
        public int hp
        {
            get { return _hp; }
            set
            {
                if (value <= 0) _hp = 0;
                else if (value > 100) _hp = 100;
                else _hp = value;
            }
        }

        public Player()
        {
            hp = 100;
        }
    }
}

And my Storage class:

using RogueBase.Interfaces;
namespace RogueBase.Classes
{
    public class Storage
    {
        public Storage(int capacity)
        {
            inventory = new Iitem[capacity];
        }

        public bool Add(Iitem newItem)
        {
            for (int i = 0; i < inventory.Length; i++) // check each slot
            {
                if (inventory[i] as Iitem != null) { continue; } // skip items

                inventory[i] = newItem; // assign item to empty slot
                return true; // report success
            }
            return false; // inventory full
        }

        public bool Remove(Iitem targetItem)
        {
            for (int i = 0; i < inventory.Length; i++) // check each slot
            {
                if(inventory[i] == targetItem) // when match is found
                {
                    inventory[i] = null; // remove it
                    return true; // report success
                }
            }
            return false; // no item found
        }
    }
}

Item interface (just for reference):

namespace RogueBase.Interfaces
{
    public interface Iitem
    {
        string name { get; set; }
        int sellValue { get; set; }
        bool consumable { get; set; }

        void Equip();
        void Sell();
        void Consume();
    }
}

The problem right now is that every time I want to create a new inventory for something, I need to prepare a variable for it (not a problem when it comes to the player), but I'd like to be able to create friendly and hostile NPCs on demand with their own unique inventory that could be randomly generated,

In order to do this, is it my only option to turn the Storage class into an interface and copypaste the functions for every NPC/storage type? Or can I somehow turn the Add/Remove functions static? If I try to do it right now I get an error:

  An object reference is required for the non-static field, method, or
  property 'Storage.inventory'

Edit; Specified question:

How can I access Iitem[] inventory in class Player to be used in class Storage's methods?


texts:
I've created a textured cube in Blender, which I have uv-mapped like this:

The tiles are 256x256, and I've mapped the coordinates exactly at the edges (e.g. x: 256, y: 512). I then export my model as an fbx-file to Unity. In Unity, if I put many cubes adjacent to each other, seams appear between the cubes, like this:

I think I understand why this happens, because the uv-coordinates are exactly on the edges, and thus two faces sample from the same points along an edge.
I could solve this in some ways:

By making the uv-tiles smaller, but it would look ugly with patterns.
By adding some space between the tiles in the texture, and aligning the uv-coordinates to them.

My question: is there a better proper way for achieving this?

UPDATE:
So, about half a year later I still have issues with the seams. I've tried many things:

Start uv-coordinates at 256.5 instead of 256, and so on...
Turned of mipmapping.
Set wrap mode to clamp.
Set filter mode to point filter.
Edge padded the texture atlas with first 4px, 8px, 16px, 32px. But still bleeding occurs at certain angles. Also updated the uv-coordinates accordingly.
Changed my atlas to be of Power of 2 instead, i.e. 1024x1024 instead of 1024x768.
Set "Non Power of 2" in Unity to None so Unity doesn't rescale my texture to nearest Power of 2.
Set texture format to Automatic Truecolor instead of Compressed.

With 32px edge padding it actually gets a lot better, but it still isn't perfect, I guess I could go on and try even more padding, but my textures will get bigger and bigger.
I understand now that it is the mip-levels that are causing the bleeding. At far distances I don't think this is a problem, but I can see this occuring just about 5-7 units away from the player, if the player is looking down.
I believe there is something trivial about this that I'm missing. This is really a showstopper for me, forever grateful to the one who helps me solve this.
Thanks in advance!
This is how I have edge padded my texture (lines not visible on real texture), the problem does not only occur when the faces has such extremes distinct difference in colors as this one. It also occurs when the faces have patterns.


texts: Should I use OGRE3D or start from scratch with OpenGL for a large, procedural, open world game?

texts:
This question has probably been asked quite a few times, or something similar to it, but I'd like to get some better information on OGRE, since I felt that any descriptions I found weren't very comprehensive as to what it truly does.

I've been dabbling in OpenGL for a while now, and am currently doing my best to tackle shaders, with varying levels of success. Now the reason I'm learning OpenGL is ultimately to be able to develop a game, of course, but I was wondering if I could get started faster if I began using OGRE instead of programming the graphics engine from scratch.

So I looked into it, but nothing really seemed to inform me what kind of development the engine is actually good for. The game I have in mind will have a large open world, partially using procedural terrain generation, so I'm wondering how feasible is something like that in OGRE? Can it be used effectively to generate vertices in real time? Or am I better off skipping OGRE and building from scratch...


texts:
I'm currently testing out Unity 3D and one of the things I can not figure out, is how to create textures that are what I would describe as "Soft Gradient".

Here is an image of what I would describe the textures as "Soft Gradient"

If you look at the top of the hexagons (the grass). you can see that its not just one color, its a texture that is a "Soft Gradient".

Currently, this is what I have,

Does anyone have tips or can help my understand how to make my hexagon pillars look similar to the ones in the picture?


texts: How to avoid character controller collider for slide over floor.?

texts:
I have a character controller to move my player on a surface. All the things work fine, but I can't make a perfect slide with the character controller on the surface.

When I try to slide, my player animation plays in the center of capsule collider, which is attached to the  player. That's why my player can not touch floor, which means my animation play in mid air. After some time I found that my problem occurs due to using the character controller. I am using Character.Move() to move my player.

Can anyone help me? How can I avoid the collider on the character controller, or change something to make my player slide animation perfectly align with the floor.?

I am using controller.transform.Rotate(0,0,60) to rotate my player on floor.

This is my script:

using UnityEngine;
using Assets.Scripts;
using System.Collections;
using UnityEngine.SceneManagement;

public class ControllerMovement : MonoBehaviour {

private Vector3 moveDirection = Vector3.zero;
public float gravity = 20f;
private CharacterController controller;
public float JumpSpeed = 8.0f;
public float Speed = 0.1f;
public int swipeStep = 3;
int swipeD,pos;
bool rx ;
int i=0;
public Transform CharacterGO;
bool isInSwipeArea;
private Animator anim;
IInputDetector inputDetector = null;

// Use this for initialization

void Start()
{
    moveDirection = transform.forward;
    moveDirection = transform.TransformDirection(moveDirection);
    moveDirection *= Speed;
    UIManager.Instance.ResetScore();
    UIManager.Instance.SetStatus(Constants.StatusTapToStart);
    GameManager.Instance.GameState = GameState.Start;

    anim = CharacterGO.GetComponentInChildren<Animator> ();
    inputDetector = GetComponent<IInputDetector>();
    controller = GetComponent<CharacterController>();
}

// Update is called once per frame
void Update()
{
    switch (GameManager.Instance.GameState)
    {
    case GameState.Start:
        if (Input.GetMouseButtonUp(0))
        {
            //anim.SetBool(Constants.animaationStarted, true);
            var instance = GameManager.Instance;
            instance.GameState = GameState.Playing;
            UIManager.Instance.SetStatus(string.Empty);
        }
        break;
    case GameState.Playing:
        UIManager.Instance.IncreaseScore (0.001f);
        CheckHeight ();
        DetectJumpOrSwipeLeftRight ();

        //apply gravity
        moveDirection.y -= gravity * Time.deltaTime;
        //move the player
        controller.Move (moveDirection * Time.deltaTime);
        break;

    case GameState.Dead:
        ////anima.SetBool(Constants.//animaationStarted, false);
        if (Input.GetMouseButtonUp(0))
        {         SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        }
        break;
    default:
        break;
    }
}
private void CheckHeight()
{
    if (transform.position.y < -10)
    {
        GameManager.Instance.Die();
    }
}

private void DetectJumpOrSwipeLeftRight()
{
    var inputDirection = inputDetector.DetectInputDirection();

    if (Input.GetKeyDown (KeyCode.Space)) {
        moveDirection.y = JumpSpeed;
        anim.SetBool ("RunToJump", true);
    } else {
        anim.SetBool ("RunToJump", false);
    }
    if(Input.GetKey(KeyCode.A) && controller.isGrounded){
        controller.transform.Translate (-0.1f,0,0);
    }
    if(Input.GetKey(KeyCode.D) && controller.isGrounded){
        controller.transform.Translate (0.1f,0,0);
    }
    if (Input.GetKey (KeyCode.S) && controller.isGrounded) {
        anim.SetBool ("RunToSlip", true);
        controller.transform.Rotate (-40, 0, 0);
        Invoke ("StopSlidding", 0.2f);
    }
        }
 void StopSlidding(){
    anim.SetBool ("RunToSlip", false);
    controller.transform.Rotate (40,0,0);

  }

 }


texts: Why haven't graphics cards been designed for voxel rendering?

texts:
I stumbled across the following article on Wikipedia regarding voxels that says:

  One such problem cited by Carmack is the lack of graphics cards designed specifically for such rendering requiring them to be software rendered, which still remains an issue with the technology to this day.

Does anyone know why this is the case and why voxels are not supported or optimized on a hardware level by graphics cards?


texts:
I have a camera that is moved by changing its X and Z coordinates. However, the camera is rotated, so when an object moves by 1 unit in the world, the number of pixels it moves by isn't trivial to determine.

How could I move the camera so that if the pointer is at a set point, that point will be under the cursor after the cursor moves?

I have a PerspectiveCamera and the number of pixels that the pointer was dragged in each direction (X and Y) on the screen.


texts: How to identify entrances of a cluster in HPA*?

texts:
Recently I've become interested in understanding and implementing HPA* in a RTS game. I've found the following presentation which is really good for explaining how HPA* works: https://harablog.files.wordpress.com/2009/06/beyondastar.pdf

At slide 28 it says "identify entrance points between clusters". Slicing my map into several clusters is easy, but I can't get the idea how to identify the points between clusters. "Should I take the middle? Border points? All of them?"

I've struggled to look at some implementation in java, C# or C++ but games like 0 A.D. use a different strategy for implementing hierarchical graphs mixed with Jump-point search. Others like libgdx-ai use multi-level HPA* and can't find an implementation simple enough to understand and reproduce, specially on the matter regarding entrances and how to connect them.

Can anyone enlighten me?

Thanks


texts: How do I incorporate .tmx files into my game?


texts: Backup virtual goods to survive game reinstalls

texts:
I'm developing a game using Unity3D (for Android and iOS). I would like to save all user's virtual goods, so they are available even if the user remove and reinstall the app, or even if the user install it on a new device.

AFAIK an approach would be to authenticate the user, and save all the data on my backend server. But, to not reinvent the wheel, can you share your approach? i.e.: how do you authenticate users? are you using your own server, or any BaaS?

EDIT: After reading your answers, I think the best approach is to use "Google Play Game Services Saved Games" on Android, using the official plugin for Unity3D. For iOS, there is a similar feature for GameCenter, but I can't find any official plugin for Unity3D. But this plugin may work: https://www.assetstore.unity3d.com/en/#!/content/11626

Soomla plugin can be useful: https://www.assetstore.unity3d.com/en/#!/content/6103

Also, this plugin can be useful too: https://www.assetstore.unity3d.com/en/#!/content/20152


texts: How can I clear the entire display in Corona?

texts:
How can I clear the entire display?  I have tried doing display.remove(obj) and obj:removeSelf() on everything that was drawn, but it seems to miss a few things and I am unsure why.

A very basic version of this part would look like this:

Runtime:addEventListener("accelerometer", onShake)
Runtime:addEventListener( "touch", draw );

--Initialize arrScreen and other variables

function onShake (event)
  if event.isShake then
    --for loops
      display.remove(arrScreen[i][j])
      --arrScreen[i][j]:removeSelf()
    --end for loops
  end
end

function draw(event)
  if event.phase == "began" then
    arrScreen[event.x][event.y]=display.newRect(event.x,event.y,size,size)
    lastPoint.x=event.x
    lastPoint.y=event.y
  elseif event.phase ~= "ended" then
    arrScreen[event.x][event.y]=display.newLine(event.x,event.y,lastPoint.x,lastPoint.y)
    lastPoint.x=event.x
    lastPoint.y=event.y
  end
end


texts: How to get one KinematicBody2D to push another?

texts:
I am working in Godot 3, where my player is a KinematicBody2D. When I collide with a block which is also a KinematicBody2D I'd like my player to push it without losing velocity.

My block is in a group called moveables, has no script, and has no other forces acting on it.

After I calculate the velocity of my player in _physics_process(), I have the following code.

# update position and handle collision

var collision = move_and_collide(vel * delta)
if collision:
    var collider = collision.collider
    var normal = collision.normal
    var remainder = collision.remainder
    var collision_angle = rad2deg(acos(normal.dot(Vector2(0,-1))))

    # floors
    if collision_angle == 0:

        # reset y vel so it doesn't keep accumulating
        vel.y = 0

        var horizontal_movement = Vector2(remainder.x, 0)
        move_and_collide(horizontal_movement)

    # moveables
    elif collision_angle == 90:
        if collider in get_tree().get_nodes_in_group("moveables"):
                collider.move_and_collide(remainder) # move block by remainder
                move_and_collide(remainder) # move player by remainder

This code does allow the player to push the block, but only slowly. I can't figure out why. Ideally, the player would push the block without losing any velocity.

Even if I directly update only the horizontal position of my block, it still moves slower than expected, and my player sprite is blurred, presumably because of collision corrections.

        if collider in get_tree().get_nodes_in_group("moveables"):
            collider.global_position.x += remainder.x
            move_and_collide(remainder)

The problem seems to be that when I move the player by the remainder, the player is still colliding with the block, even though I move the block itself in the previous line. This is confirmed by analyzing the collision object move_and_collide(remainder).

What's wrong and how can I achieve the desired movement?

I asked a variant of this question on a Godot forum, but am also asking it here for increased visibility.


texts:
So i have this line of code:

if(input.isKeyDown(Input.KEY_W)&&canJump())
    {
        body.applyLinearImpulse(new Vec2(0, 30), cam.screenToWorld(body.getPosition()));
        System.out.println("I can jump!");
    }

My problem is that the console display I can jump! but the body doesn't do that. Can you explain to me if i do something wrong?

Some more code.
This function creates my 'hero' the one supposed to jump.

private Body setDynamic(float width, float height, float x, float y)
{
    PolygonShape shape = new PolygonShape();
    shape.setAsBox(width/2, height/2);

    BodyDef bd = new BodyDef();
    bd.allowSleep = true;
    bd.position = new Vec2(cam.screenToWorld(new Vec2(x + width / 2, y + height / 2)));
    bd.type = BodyType.DYNAMIC;
    bd.userData = new BodyInfo(width, height);

    Body body = world.createBody(bd);
    body.createFixture(shape, 10);

    return body;
}

And this is the main update loop:

if(input.isKeyDown(Input.KEY_A))
    {
        body.setLinearVelocity(new Vec2(-10*delta, body.getLinearVelocity().y));
    }
    else if (input.isKeyDown(Input.KEY_D))
    {
        body.setLinearVelocity(new Vec2(10*delta, body.getLinearVelocity().y));
    }
    else
    {
        body.setLinearVelocity(new Vec2(0, body.getLinearVelocity().y));
    }

    if(input.isKeyDown(Input.KEY_W)&&canJump())
    {
        body.applyLinearImpulse(new Vec2(0, 30), body.getPosition());
        System.out.println("I can jump!");
    }
    world.step(delta * 0.001f, 10, 5);

}


texts: How do i writing timing function for lightning flash in C++?

texts:
I need to write a horror scene with lightning flash. Unfortunately I am new to both C++ and OpenGL and I am looking for efficient way to mimic lightning timing in C++/OpenGL?

I don't need graphical implementation, just algorithmic implementation.

as such, the function should return a float representing lighting intensity and the delay of lightning flash should be random (5 seconds followed by 10 seconds then 3 seconds.. etc)

I hope I made everything clear!


texts: I'm currently creating a voxel game like Minecraft. To display the damage of blocks, I want to combine the alpha channel of one part of my texture map with the actual texture (like Minecraft does), how could I do that in Unity?


texts: Unable to stop navmeshagent for rotation before moving

texts:
I'm trying to get the NavMeshAgent to rotate before calculating a path and proceed walking.

I stumbled upon a thread that said this can be done by manually rotating the object first.

However, I am still stumped as to how to do this as my unit either a)refuses to move or b)moves, but does not stop to rotate.

Below is the code I've attempted.

void Update() {

    RaycastHit hit;
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit) && hit.collider.tag == "Ground")
        {
            targetPosition = hit.point;
        }
    }

    if (transform.rotation != _lookRotation) //check if unit is in line with direction of hit.point
    {
        agent.Stop(); //stops the navmeshagent from moving.

        _direction = (targetPosition - transform.position).normalized;
        _lookRotation = Quaternion.LookRotation(_direction);

        transform.rotation = Quaternion.RotateTowards(transform.rotation, _lookRotation, Time.deltaTime * speed);

    } //perform rotation
    else //else, if already in line, set path and walk.
    {

        agent.SetDestination(targetPosition);

    }


texts: Rotating A 2D Cannon Based On Mouse Position

texts:
I'm creating a game like bubble shooter, I have a cannon which is in the image bellow:

I want to rotate the cannon based on mouse position.

So far I tried various solutions I found over the web but non of them are working, I know that I only need to rotate the cannon on the Z axis because this is a 2D game, so I don't touch X and Y axis.

Does anybody know how can I rotate the cannon based on mouse position?

Or at least provide me a sample script on where to start.

Thank You.


texts: How do I prevent flickering when drawing to a JPanel?

texts:
So I have a JFrame holding a JPanel, to which I'm drawing at about 60 FPS. I've been told that "Swing is double buffered by default", but, nevertheless I'm getting massive flickering. At first, I tried modifying the Graphics object from JPanel.getGraphics(), but was not surprised when it flickered (to black, the background colour of the game so far), as I assumed that it was redrawing when I blanked the screen. However, then I overrode paintComponent(), passing the Graphics to all objects to draw with, and made it call the super version, which I assumed would solve it, but no difference.

I'm still getting the Graphics object from the same place, i.e. JPanel.getGraphics(), because paintComponent() needs a Graphics argument. Should I be getting it from some other place? If not, what else could be causing the problem?


texts: How to compute tile offset for different isometric angles?

texts:
I am working on an isometric game and the designers want to use a different isometric angle than the default one, where I simply had to do a 2/1 offset based on tile size.

I know what the new isometric angle is, how can I work out the w/h ratio to offset my tiles ?


texts: How are collision and collision callback systems usually implemented?

texts:
I'm writing my own game engine for learning purposes and was wondering about common ways to handle collision callbacks/responses. I'm NOT looking for ways to resolve collisions (no math needed here), I just want to know how systems are commonly set up to respond to one another.

For example, what I have designed now is a system where any entity, if they want to interact with the physical world, adds one of a few predefined shapes to the "physical objects list". One entity might want to add two squares to use as various bounding boxes, another entity might just add a circle as a collision area etc. Once every iteration, the collision detection system looks for collisions, and if it finds one, it checks the shape object's "parent" (the entity that added the shape) and notifies it of a collision and passes it a vector that can resolve it.

Even if someone can simply point me to an article that discusses this concept I would be grateful, as I haven't found any with some basic Google searches. (I also wouldn't know what to call this, collision callback is a term I made up, not sure if it makes sense).


texts:
I'm trying to tranlate a matrix by xy but the result is strange. can someone help me translate and rotate the matrix properly?

void Transform_Update(Transform *transform, GLfloat depth)
{
    Matrix4_SetToIdentity(transform->transformationMatrix);
    Matrix4_Set(transform->transformationMatrix, 0, 3, transform->position->x);
    Matrix4_Set(transform->transformationMatrix, 1, 3, transform->position->y);
    Matrix4_Set(transform->transformationMatrix, 2, 3, depth);
}

Here is my Matrix set value.

void Matrix4_Set(Matrix4 *m, GLuint line, GLuint column, GLfloat value)
{
    m->data[line * 4 + column] = value;
}

Here is where I make the matrix to the identity matrix

void Matrix4_SetToIdentity(Matrix4 *m)
{
    GLfloat data[16] = { 1, 0, 0, 0,
                         0, 1, 0, 0,
                         0, 0, 1, 0,
                         0, 0, 0, 1 };

    memcpy(m->data, data, sizeof(GLfloat) * 16 );
}

This is where I render my mesh and update shader values

void Renderer_Render(Renderer *renderer, Camera *camera)
{
    glUseProgram(renderer->shader->id);

    Transform_Update(renderer->gameObject->transform, renderer->depth);

    GLint location = Shader_GetUniformLocation(renderer->shader, "transformationMatrix");
    glProgramUniformMatrix4fv(renderer->shader->id, location, 1, GL_FALSE, renderer->gameObject->transform->transformationMatrix->data);

    GLint location2 = Shader_GetUniformLocation(renderer->shader, "projectionMatrix");
    glProgramUniformMatrix4fv(renderer->shader->id, location2, 1, GL_FALSE, camera->projectionMatrix);

    GLint location3 = Shader_GetUniformLocation(renderer->shader, "viewMatrix");
    glProgramUniformMatrix4fv(renderer->shader->id, location3, 1, GL_FALSE, camera->viewMatrix);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, renderer->texture->id);

    Mesh_Render(renderer->mesh);
}

Here is my shader transforming the vertices :

#version 400 core

in vec3 position;
in vec2 textureCoords;

out vec2 pass_textureCoords;

uniform mat4 transformationMatrix;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

void main(void) {

    vec4 worldPosition = transformationMatrix * vec4(position, 1.0);
    vec4 positionRelativeToCamera = viewMatrix * worldPosition;

    gl_Position = projectionMatrix * positionRelativeToCamera;
    pass_textureCoords = textureCoords;
}

Here is how I get the view and projection matrix :

void Camera_Render(Screen *screen, Camera *camera)
{
    glClearColor(camera->backgroundColor->red, camera->backgroundColor->green, camera->backgroundColor->blue, camera->backgroundColor->alpha);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glLoadIdentity();
    glTranslatef(camera->transform->position->x, camera->transform->position->y, 0);
    glRotatef(camera->transform->angle, 0, 0, 1);

    glGetFloatv(GL_PROJECTION_MATRIX, camera->projectionMatrix);
    glGetFloatv(GL_MODELVIEW_MATRIX, camera->viewMatrix);
}

The current output when I change X is this :


texts: I've just begun working on my game and I don't know how to organize my game in separate classes, because I need some variables/methods to be available to every class. I have a screen manager class and some screen classes which inherit a base screen class. But I can't access the screen manager's methods without making it a singleton, and I would like to avoid this solution. And I would like some game variables or methods to be available from any other class, but I can't do it without making them static. Let's say I have variable which stores the game difficulty throughout the game screens. If I would like to implement such a thing I would need to make it static in the Game1 class. Short story, I don't know how to make methods/variables global without making them static.


texts: Can I change the order of these OpenGL / Win32 calls?

texts:
I've been adapting the NeHe OpenGL/Win32 code to be more object-oriented and I don't like the way some of the calls are structured.
The example has the following pseudo-structure:

Register window class
Change display settings with a DEVMODE
Adjust window rect
Create window
Get DC
Find closest matching pixel format
Set the pixel format to closest match
Create rendering context
Make that context current
Show the window
Set it to foreground
Set it to having focus
Resize the GL scene
Init GL

The points in bold are what I want to move into a rendering class (the rest are what I see being pure Win32 calls) but I'm not sure if I can call them after the Win32 calls.
Essentially what I'm aiming for is to encapsulate the Win32 calls into a Platform::Initiate() type method and the rest into a sort of Renderer::Initiate() method.
So my question essentially boils down to: "Would OpenGL allow these methods to be called in this order?"

Register window class
Adjust window rect
Create window
Get DC
Show the window
Set it to foreground
Set it to having focus
Change display settings with a DEVMODE
Find closest matching pixel format
Set the pixel format to closest match
Create rendering context
Make that context current
Resize the GL scene
Init GL

(obviously passing through the appropriate window handles and device contexts)
Thanks in advance.


texts: Optimize a vertex buffer and generate its associated index buffer

texts:
I need to generate a 64*64 grid with each cell being 32*32 wide.

The following code works perfectly but I was wondering whether it can be further optimized when creating the index buffer for it.

I've been searching the web for an algorithm that would generate indices and optimize a buffer but without much success ...

var vector3s = new[]
    {
        new Vector3(0, 0, 0),
        new Vector3(1, 0, 0),
        new Vector3(0, 1, 0),
        new Vector3(1, 1, 0),
    };

List<VertexPositionTexture> positions = new List<VertexPositionTexture>();
for (int y = 0; y < 64; y++)
{
    for (int x = 0; x < 64; x++)
    {
        foreach (var vector3 in vector3s)
        {
            var translation = Matrix.CreateTranslation(new Vector3(x, y, 0));
            var transform = Vector3.Transform(vector3, translation);
            var multiply = Vector3.Multiply(transform, 32.0f);
            VertexPositionTexture vpt = new VertexPositionTexture(multiply, new Vector2(vector3.X, vector3.Y));
            positions.Add(vpt);
        }
    }
}

Output sample :

{Position:{X:0 Y:0 Z:0} TextureCoordinate:{X:0 Y:0}}
{Position:{X:32 Y:0 Z:0} TextureCoordinate:{X:1 Y:0}}
{Position:{X:0 Y:32 Z:0} TextureCoordinate:{X:0 Y:1}}
{Position:{X:32 Y:32 Z:0} TextureCoordinate:{X:1 Y:1}}
{Position:{X:32 Y:0 Z:0} TextureCoordinate:{X:0 Y:0}}
{Position:{X:64 Y:0 Z:0} TextureCoordinate:{X:1 Y:0}}
{Position:{X:32 Y:32 Z:0} TextureCoordinate:{X:0 Y:1}}
{Position:{X:64 Y:32 Z:0} TextureCoordinate:{X:1 Y:1}}

For instance, positions at 1 and 4 are identical but their texture coordinates are not.

What are the options for optimizing it and how does one generate the associated index buffer ?

Should positions be separated from texture coordinates and each have an index buffer ?

EDIT

Actually texture coordinates are wrong but it's not really relevant for the question.


texts: How can I test if my rotated rectangle intersects a corner?

texts:
I have a square, tile-based collision map. To check if one of my (square) entities is colliding, I get the vertices of the 4 corners, and test those 4 points against my collision map. If none of those points are intersecting, I know I'm good to move to the new position.

I'd like to allow entities to rotate. I can still calculate the 4 corners of the square, but once you factor in rotation, those 4 corners alone don't seem to be enough information to determine if the entity is trying to move to a valid state.

For example:

In the picture below, black is unwalkable terrain, and red is the player's hitbox. The left scenario is allowed because the 4 corners of the red square are not in the black terrain.

The right scenario would also be (incorrectly) allowed, because the player, cleverly turned at a 45* angle, has its corners in valid spaces, even if it is (quite literally) cutting the corner.

How can I detect scenarios similar to the situation on the right?


texts: I am developing a game in android and I want to be able to use device rotation for moving. So, I am not sure what sensors should I use. I tried gyroscope, it will do, but there are not a lot of devices that supports gyroscope sensors. So, I want to use rotation around x,y,z axis not change like landscape/portrait mode. What sensors would be the best? I already tried to google it but I couldn't find anything.


texts: How can I turn off the sound from another scene?

texts:
I attached music file to my first scene and thanks to following javascipt code, sound continues without stopping in other scenes.

public static var object : SingletonMusic = null;

function Awake()
{

    if( object == null )
    {
        object = this;
        DontDestroyOnLoad(this);
    }
    else if( this != object )
    {
        Destroy( gameObject );
    }
}

My problem is that I want to turn off the sound from the button in the another scene (setting scene) so that I added a new button to my setting scene and attached the following javascript code to the button that I have created.

Javascript code:

var objects: AudioSource = SingletonMusic.object.GetComponent(AudioSource);
if( objects.isPlaying )
objects.Pause();
else
objects.Play();

However, it gives following errors:

If I start the game from Setting scene; I get this error:

If I start the game from first scene and then, go to Setting scene; I get this error:


texts: Can't go above max speed with RigidBody2D.AddForce()

texts:
I'm having trouble making a character move faster than a certain limit using RigidBody2D.AddForce(). My game is a top-down 2D game (constrained to the x/y plane).

I'm using a float 'MovementSpeed' to scale a normalized vector passed to RigidBody2D.AddForce(), however, when I increase MovementSpeed past 1000, there's almost no noticeable difference in the object's "speed"; going from 100 to 1000 is a drastic difference, but there's almost no noticeable difference going from 1000 to 1000000. Here's my WASDMovement() function (called during FixedUpdate() ):

private void WASDMovement() {
    Vector3 translationVector = Vector3.zero;

    if (Input.GetKey(KeyCode.W)) {
        translationVector += new Vector3(0.0f, 1.0f, 0.0f);
    }
    if (Input.GetKey(KeyCode.A)) {
        translationVector += new Vector3(-1.0f, 0.0f, 0.0f);
    }
    if (Input.GetKey(KeyCode.S)) {
        translationVector += new Vector3(0.0f, -1.0f, 0.0f);
    }
    if (Input.GetKey(KeyCode.D)) {
        translationVector += new Vector3(1.0f, 0.0f, 0.0f);
    }

    translationVector.Normalize();
    rigidbody2D.AddForce(translationVector * MovementSpeed);
}

Here's a video demonstrating my problem to make it easier to see what I'm doing wrong: http://youtu.be/9kwKvfDOYoo


texts:
I was trying to understand the gluOrtho2D function. I have drawn 4 lines originating from the center reaching up to 4 corners of the screen.

You can follow the below code. osize is a variable which is used to set the parameters of gluOrtho2D. It will create a window of size 2*osize.

If works fine when osize is 1. Lines reach the corners. But as I increase the value of osize, the length of the lines decreases (cross becomes smaller and does not cover the whole screen). But I think it should reach the corner.

void display()
{
    glClear( GL_COLOR_BUFFER_BIT );

    //glViewport(0, 0, 100, 100);

    glMatrixMode (GL_PROJECTION);
    float osize = 1.2;
    //glOrtho(-osize*1.0, osize*1.0, osize*1.0, -osize*1.0, -1.0, 1.0);
    gluOrtho2D(-osize*1.0, osize*1.0, osize*1.0, -osize*1.0);
    glMatrixMode (GL_MODELVIEW);

    glBegin(GL_LINES);
       glColor3f(0.0, 0.0, 1.0);
       glVertex2f(0.0, 0.0);
       glVertex2f(-osize*1.0, -osize*1.0);
       glVertex2f(0.0, 0.0);
       glVertex2f(-osize*1.0, osize*1.0);
       glVertex2f(0.0, 0.0);
       glVertex2f(osize*1.0, -osize*1.0);
       glVertex2f(0.0, 0.0);
       glVertex2f(osize*1.0, osize*1.0);
    glEnd();

    glutSwapBuffers();  //includes glFlush();
}

What is the problem?


texts:
I made a Rubik's cube by arranging smaller cubes. Now I want to apply animations to it. For that I am choosing to use the Rotate class and set the angle of rotation and the axis of rotation,like this

ar[12].setRotationAxis(Rotate.X_AXIS);//The array elements refer to the small cubes which make up the Rubik's cube.These elements represent the left face.
        ar[13].setRotationAxis(Rotate.X_AXIS);
        ar[14].setRotationAxis(Rotate.X_AXIS);
        ar[15].setRotationAxis(Rotate.X_AXIS);
        Rotate rotation1 = new Rotate(90);
        rotation1.setAxis(Rotate.X_AXIS);

Then I am applying the rotations as an animation,like this

Timeline timeline = new Timeline(
                new KeyFrame(Duration.seconds(2), new KeyValue(ar[12].rotateProperty(), 90)),
                new KeyFrame(Duration.seconds(2), new KeyValue(ar[13].rotateProperty(), 90)),
                    new KeyFrame(Duration.seconds(2), new KeyValue(ar[14].rotateProperty(), 90)),
                    new KeyFrame(Duration.seconds(2), new KeyValue(ar[15].rotateProperty(),  90)));
            timeline.stop();

            timeline.setCycleCount(Timeline.INDEFINITE);
            timeline.setAutoReverse(true);
            timeline.play();

 The inner black sides are coming out.
What mistake am I making and how to fix this ?
Basically, I am getting this for each single cube

But I need this for each cube


texts: Scaling Skeletal values to be able to reach objects on the screen

texts:
I have created a game using Kinect + XNA and the game runs on full screen mode.. However when i try to touch or reach a certain area on the screen using hand.. I cant reach it.. I will already be outside the range of the sensor trying to touch the object on the game screen..

Is there anyway I can scale the skeletal values so that the users can easily touch objects on the screen without having to stretch or bend too much?


texts: Rendering multiple textures on same image for terrain with index buffers (LWJGL 3)

texts:
I have started with LWJGL3 and trying to built game engine. I'm stuck on generating terrains and this is my second big problem and I'm exhausted so I need some advice on how to solve my problem.

What I want to achieve :
I want to have all textures in one place and to have some kind of texture map that I will use to render specific texture at that place.

example:
textures

map

but result is

Only thing that I think is problem is because I use same points (index buffers)

So instead of 8 points, I have 6. Is it possible that then texture gets all messed up?

Should I use all points, even if they are at same or almost the same location? But then I would have a lot more vertices than actually need it.


texts: Unity - Bool doesn't change to false anymore

texts:
I got into a Unity-Tutorial and halfway-through I face this weird problem. I used this code so that my player may attack if he pressed a leftShift. When the player attacks, the animation starts playing in a loop - he never stops attacking and debugging show that attack is never false after the first "leftShift"-Input.

I removed the loops from the animator etc. - but that doesn't seem to be the problem because "attack" never get's to false anyways. I tried different approaches. If I set "attack = false" immediately after attacking, he doesn't attack at all.

Sorry for asking such a beginner question but I can't seem to find my error.

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

public class Player : MonoBehaviour
{
private Rigidbody2D myRigidbody;

[SerializeField]
private float movementSpeed;

private bool facingRight = true;

private Animator myAnimator;

private bool attack = false;

// Start is called before the first frame update
void Start()
{
    myRigidbody = GetComponent<Rigidbody2D>();
    myAnimator = GetComponent<Animator>();
}

void Update()
{
    HandleInput();
    Debug.Log(attack);

}

// Update is called once per frame

void FixedUpdate()
{
    float horizontal = Input.GetAxis("Horizontal");
    HandleMovement(horizontal);
    Flip(horizontal);
    HandleAttacks();
    ResetValues();

}

private void HandleMovement(float horizontal)
{
    if (!this.myAnimator.GetCurrentAnimatorStateInfo(0).IsTag("Attack"))
    {

        myRigidbody.velocity = new Vector2(horizontal * movementSpeed, myRigidbody.velocity.y);
        myAnimator.SetFloat("speed", Mathf.Abs(horizontal));
    }
}

private void HandleAttacks()
{
    if (attack)
    {
        myAnimator.SetTrigger("attack");

    }
}

private void HandleInput()
{
    if (Input.GetKeyDown(KeyCode.LeftShift))
    {
        attack = true;

    }
    attack = false;
}

private void Flip(float horizontal)
{
    if(horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
    {
        facingRight = !facingRight;
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }
}

private void ResetValues()
{
    attack = false;
}
}


texts:
For my RTS game I have got A* pathfinding working, and that's fine.  Basic collision detection exists too.  When a unit is moving it checks if the position it will occupy next move is a node occupied by another unit, and if so it finds another way to the destination.  I also think I understand the basics of flocking; that during movement it's just making sure that boids are checking the distance to their flock friends, and then correcting for this.

But I am a little confused.  Right now my pathfinding system works on a square grid of nodes, but if I'm to create a flocking system which works by taking a boid's circular footprint into account then this complicates matters, because in a tightly packed flock, or indeed a flock with a number of members with various footprint sizes, then their placement won't always match the square node grid designed for A*.

In theory, how then do a bunch of boids pack together in a ball, or flow through terrain bottlenecks (some nodes flagged unwalkable, etc) in an orderly manner?  Is this sort of behaviour emergent from a functional flocking system?

But I'm sure I'm misunderstanding this system and would like someone who understand how to implement it to explain the theory so that I can implement this myself.  I assume flocking isn't really congruent with A*: that's just used to find a path, and during movement flocking is the only way it manages collision detection and avoidance for units?  But then what about obstacles which can create bottlenecks?  How is A* and flocking reconciled?  Avoiding boids and terrain obstacles are different systems.


texts: How To Have My Character Turn When The Camera View Moves

texts:
So I have recently finished animating my character, having it move with key presses and have applied a camera to it. But I am stumped on how to have the player turn when the camera view moves, and have them both in sink. I want to have this instead of using keys to turn because that can be very awkward and hard to control. I would really appreciate any help I can get on this, as it will allow me to finally finish my character.

Thanks, Nova


texts:
I've done a reasonable number of small hobby projects using DirectX 9 but it's time to move to DirectX 11 now.

I have Frank Luna'a book on 3D programming using DirectX 10 but nothing on DirectX 11. I believe they are pretty similar, but was wondering if anyone could enumerate the main differences at a code level that I'll need to be aware of (or point to an existing source).


texts:
the first picture is the texture I'm using.
and the second is result. problem!

the model file it self is no problem. I think the mode is problem.

I saw uv coordinates is more than 1.

what kind of sampler state I should use?

I used default sampler state that is wrap mode for u,v,w.


texts: Pub/Sub or message passing in multiplayer server backend?

texts:
For my masters thesis I'm going to develop a scalable multiplayer server for locationbased games. It's going to be a "service oriented architecture" e.g. one dedicated service for positions, one for the database, login etc. However 1..n frontend services for the clients to connect to. Scalability will be tested with simulated clients on some other machines. However, I'm still undecided on how my services will talk to each other.

On the one hand, there is publish/subscribe. And even there are different ways to implement it, using Multicast or let each subscriber subscribe directly with the publisher. The good thing with pub/sub is, that each message will be sent to every service that is interested, e.g. the Logger-Service receives a position update as well as the position service. I can also have some "shadow" services that keep in sync in case the major services crashes. Depending on the implementation pub/sub feels like flooding my internal network with messages. And flooding is never a good idea.

Then there is message passing. When the Frontend-Service receives a message, it finds out what type of message it is, finds the service that deals with this type and forwards the message to it. But there has to be a service discovery first, which requires some multicast or service directory.

There are pros and cons for each type. In an article on high scalability I read that Playfish uses the message passing method. But using pub/sub sound appealing too. Maybe someone can tell me which way is better.

Edit:
I have to admit it isn't so clear what I'm asking.
Imagine one frontend service receives a "position update" message from one of the clients. With a pub/sub system, I think about calling something like this: Network.publish(Topic,Message) or Network.publish(PositionUpdateType, Message).
Using a message passing system I might call: Network.send(PositionManager, Message).
I think pub/sub seems to be like "fire and forget", where the message passing is some kind of "direct" connection. My question is: Which one is better suited for the job or should I even use a combination of both?


texts: What's the implication of right-handedness when building camera to world matrix?

texts:
I found these slides which go through the viewing transform in what I think is a easy way. However, I have hard time understanding two thigs:

What would be the implication of using a right-hand coord system when building this matrix?
In order to get the final camera-to-world matrix, I thought I should do a matrix composition, i.e. C = T * R. Why on slide 18, it just puts the translation vector in the last column instead of doing such a multiplication?


texts:
I have decided to try out pygame. I created a class that is supposed to handle all the GUI and game related stuff.
My idea is that I would have two seperate threads. One to handle the GUI and one to handle all the calculations the game does in the background.
import threading
import pygame
import pygame_gui

class Game ():

    engine_running = True
    gui_running = True
    clock = pygame.time.Clock()

    gui_framerate = 60.0
    engine_framerate = 120.0

    def __init__(self):

        pygame.init()
        pygame.display.set_caption('Explodotech')
        self.window_surface = pygame.display.set_mode((800, 600))
        self.background = pygame.Surface((800, 600))
        self.background.fill(pygame.Color('#000000'))

        self.manager = pygame_gui.UIManager((800, 600))

        ### Define GUI Elements here

        self.quit_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((650, 500),
                        (100, 50)), text='Quit', manager=self.manager,
                        tool_tip_text = "Quit the game")

        ### Create and start the threads
        self.gui_thread = threading.Thread(target = self.gui_loop)
        self.engine_thread = threading.Thread(target = self.engine_loop, args = [])

        self.gui_thread.start()
        self.engine_thread.start()

    def start_polling(self):
        """Starts the main loop"""
        self.engine_running = True

    def stop_polling(self):
        """Stops the main loop"""
        self.engine_running = False

    def gui_loop(self):
        """Managing all the GUI stuff"""

        print ("GUI-loop started!")

        while self.gui_running:
            print("Polling GUI")
            dT = self.clock.tick_busy_loop(60)/1000.0

            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    self.gui_running = False

                if event.type == pygame.USEREVENT:
                    if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
                        if event.ui_element == self.quit_button:
                            self.quit_button_event()

                self.manager.process_events(event)

            self.manager.update(dT)

            self.window_surface.blit(self.background, (0, 0))
            self.manager.draw_ui(self.window_surface)

            pygame.display.update()

    def engine_loop(self):
        """Doing all the game calculations in the background"""
        while self.engine_running:
            print(self.clock.tick_busy_loop(1))

    ### Define GUI events here

    def quit_button_event(self):
        """Shut down the GUI"""
        print("Quit-button pressed!")
        self.gui_running = False
        self.engine_running = False

Basically what's happening here is that I have two threads one should run the "gui_loop" function the other should run the "engine_loop". However when the gui thread starts and gets into its while-loop it get stuck. The windows goes unresponsive and I have to force windows to shut it down.
However if I a create a Game-object and call the function directly it all works fine (obviously commenting out the party where I create the Thread-object):
g = Game()
g.gui_loop()

Any pointers what I am doing wrong would be greatly appreciated!


texts:
My team is working on an engine implementation and we are trying to add multithreaded scene traversal for updating and rendering our components... The question has come up as to whether or not we can create command list for a subscene once and reuse it across multiple frames. Current code recreates the subscene command list for each frame but we would like to track renderables being added or removed from the subscene and only regenerate the command list as needed.

Google searches have revealed that it is OK to reuse the device context for a new cycle after FinishCommandList is called, but there is nothing definitive about reusing the the command list from frame to frame once it is created.


texts: Finding all hexagonal grid coordinates inside cover arc

texts:
I got a turret that points at the corner of hexagon (point A). It can shoot in cover arc that's shown here:

I need to check if my target lies within this cover arc.
From this tutorial: Hexagonal Grids I know how to get a hexgrid coordinate of my target by cliking on it.

How can I get coordinates of all the hexes in cover arc (not only red hexes but all that lie within CA)?


texts: How to make a car move sharper at high speed?

texts: I am working on a car-racing game on Unity 2018.1. My car works perfectly at low speed but as it speeds up, I lose control over the car and it starts to drift independently. What can I do to prevent this?


texts: Saving predesigned tilemap "rooms" and access them in script in Unity3D?

texts:
I'm working on a top-down rogue-like in Unity3D, and I already have some kind of dungeon generation.

The next feature I'd like to implement, is to predesign some kind of "event rooms" (i.e. boss fight rooms), so my algorithm could place them at random locations.

Is there some kind of Unity feature for this, or I have to implement an editor script which could save and load tilemaps into and from scriptable objects?


texts: C# Fastest way to iterate over certain tiles overlapping multiple chunks?

texts:
What's the fastest way of iterating over certain tiles overlapping multiple chunks in C#.

Ideally without having to iterate over everything, just a specific set of coordinates? (green cubes example below)

I had some partial solutions, but i'd like to see what you guys come up with.

For example:

I would like to set every tile.IsBuiltOn = true for every tile beneath the building.

I could also use this to check if tile.IsBuiltOn = true to refuse placement of another building.

Chunks and each array of tiles of chunks start at [0,0].

class World
{
    public Chunk[][] Chunks { get; set; }
}

class Chunk
{
    public Tile[][] Tiles { get; set; }
    public Dictionary<CoordinateKey, Building> Buildings { get; set; }
}

class Building
{
    public BuildingID BuildingID { get; set; }
    public CoordinateKey ChunkCoordinate { get; set; }
    public CoordinateKey TileCoordinate { get; set; }
    public int WidthInTiles { get; set; }
    public int HeightInTiles { get; set; }
}

class Tile
{
    public bool IsBuiltOn { get; set; } = false;
}

CoordinateKey is just a struct with int X, Y.


texts: XNA's SetData in a SharpDX Texture2D object in DirectX 11?

texts:
I'm trying to load a texture given a swap chain, and then populate that texture with data. I already have some bitmap data (although not sure if it is in the correct format) that I want to populate the texture with.

However, XNA's SetData method of the Texture2D object is obviously not present in SharpDX. What do I do to populate my texture with data? I load the texture using the following code.

var texture = Resource.FromSwapChain<Texture2D>(swapChain, 0);


texts: custom mesh object orientation is not correct using

texts:
I am making a custom mesh with the help of Traingulator script.  At runtime, user can click and and generate a point then mesh creation start. Here is the way i am getting user input.

void Update()
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
        {
            if (Input.GetMouseButtonDown(0))
            {
                GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
                sphere.transform.position = hit.point;
                sphere.transform.localScale = new Vector3(0.2f, 0.2f, 0.2f);
                positions.Add(sphere.transform.position);
                positionsVector2.Add(new Vector2(sphere.transform.position.x, sphere.transform.position.z));

                traingulatorTester.MeshMaker(positionsVector2.ToArray());
            }
        }

    }

And here is the mesh maker function that calling tringulator

 public void MeshMaker(Vector2[] vertices2D)
    {
        // Use the triangulator to get indices for creating triangles
        Triangulator tr = new Triangulator(vertices2D);
        int[] indices = tr.Triangulate();

        // Create the Vector3 vertices
        Vector3[] vertices = new Vector3[vertices2D.Length];
        for (int i = 0; i < vertices.Length; i++)
        {
            vertices[i] = new Vector3(vertices2D[i].x, vertices2D[i].y, 0);
        }

        // Create the mesh
        Mesh msh = new Mesh();
        msh.vertices = vertices;
        msh.triangles = indices;
        msh.RecalculateNormals();
        msh.RecalculateBounds();
        if (gameObject.GetComponent<MeshRenderer>() == null)
        {
            // Set up game object with mesh;
            gameObject.AddComponent(typeof(MeshRenderer));
            filter = gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter;
        }
        filter.mesh = msh;

    }

Now the problem is the rotation of the custom mesh object is not correct look at this.

Now I have manually set the rotation.


texts: How to make child object a member of two parents in unity?

texts:
So I have an parent game object that has multiple objects.

This format is desirable:

-GameObject
    -object1 (abstract)
        -subobject1

    -object2 (abstract)
        -subobject2

    -object3 (abstract)
        -subobject1
        -subobject2
// There are two objects in the scene, subobject1 and subobject2

The problem is when i drag and drop one subobject from an object it removes it from the other object. When i copy the subobjects to another object, there are now two.

I hope this makes sense.


texts: Unity UI square that fills width OR height

texts:
I'm trying to create a board with this requirements:

It SHALL be square.
It SHALL fit available width OR height.
It SHALL be centered in the canvas.
It MAY be wrapped into as many additional intermediate canvases as needed.

I am playing with anchors but I am not finding any combination to do that. The only solution I can think is script some kind of "OnResize" of the container and set the size of the board programmatically.

This is the original layout. (1) is the BoardCanvas. (2) is the Board.

I want that if the screen becomes taller, the square grows, but still is square:

Or reduces:

But, although those previous examples are snapping to the top and bottom edges, I also want that if the vertical space becomes taller than the available width, then the square limits its size depending on the left and right borders:

Q1: Is there a way to do this with the anchors/pivots? It's ok for me to create intermediate canvases in between the BoardCanvas and Board itself if that works.

Q2: If so, where should I position the anchors? Do I need intermediate objects?

Q3: If not, is scripting the solution? Is there any OnResize on the canvas to handle? I can't see any resizing event in the list, but maybe I dont know where to look for it. I feel that testing it at every frame seems a bit overkill, event driven seems better.

Thanks!


texts: Calculating the weights of matrices/bones in opengl/glsl

texts:
I have a basic shape that I want to render. Nothing too complex, just a tall cube. And I want to attach 2 bones to it. Not only that, but I also want one of the bones/matrices to influence the cube more than the other bone, say 60-40 ratio. Can someone show or explain how to do this? I've been trying to find an explanation for this the past few days without luck. How to calculate the weight of a bone/matrix and how (much) effect it will have on the vertex transformation.

Im just using basic c++/opengl for this, looking for an explanation about how weights are calculated in, especially if there are multiple bones.


texts: Date Time math (A little Detail Missing)

texts:
Ok, so I have this method, where I'm trying to subtract one date from the other, and then divide it by an integer number:

public void BonoDatos () {

    //public InputField StartTimeBono;
    //public InputField FinishBono;
    //DateTime BonoStart Datetime BonoFinish
    //public InputField NumeroDeBonos;
    //int NumDeBonos;

    NumDeBonos = int.Parse (NumeroDeBonos.text);
    BonoStart = DateTime.ParseExact (StartTimeBono.text, "MM/dd/yyyy HH:mm:ss", null);
    BonoFinish = DateTime.ParseExact (FinishBono.text, "MM/dd/yyyy HH:mm:ss", null);

    Start2 = DateTime.Now;

    BonoPeriodo = (int)((BonoFinish.Subtract(BonoStart).TotalSeconds) / NumDeBonos);

    print (BonoPeriodo);
    print ("funciona");

    if (MaquinasGanadoras.text.Length > 0) {

        NumGanador.text = Maquina.text;
        CancelInvoke ("NumerAzarBono");
        print (NumGanador.text);

    } else if (MaquinasGanadoras.text.Length == 0) {

        Invoke ("NumerAzarBono", 0.1f);
        print ("Numero al Azar");
    }
}

Now, this code is supposed to take the difference of time between the two dates, and then divide it by the integer, in this case "NumdeBonos" so that the code I have in the update repeats the amount of times I put NumDeBonos to be. For example if I divide the difference between 5, in that amount of time, I need my update to happen 5 times. Problem is, My update isn't working. This is the code:

    if(DateTime.Now.Equals(Start2.AddSeconds(BonoPeriodo))) {
    //if(DateTime.Now.Equals(DateTime.Now, Start2.AddSeconds(BonoPeriodo))) {

        print ("PERIOD FUNCIONA");

        PagPrincipal.SetActive(false);

        Bonos.SetActive(true);

        Invoke ("apagaBonos",5f);

        Start2 = DateTime.Now;

    }

Now, it doesn't show any mistakes, it just doesn't do anything. What little detail am I missing?


texts:
I am new on OpenGl and what I want to achieve is to give a texture the alpha from 1.0 to 0.0

I have been searching and only found "how to load alpha in images" but I cant find how to apply alpha to an object

I has been tried with:

    gl.glEnable(GL10.GL_ALPHA_TEST);
    alpha += 0.002f;
    if(alpha > 1) alpha = 1f;
    gl.glAlphaFunc(GL10.GL_EQUAL, alpha);

But it doesn't work.

How I can give alpha value (to make the effect of fade) to an object/texture?


texts: Options for 2D Web/iPhone/Android, with Test Framework

texts:
I would like to make a 2D game with one codebase that runs on iPhone, Android, and web (any flavour of web -- HTML5, Flash, Silverlight, etc.)

What are my options? I should be able to write my code once, and run it anywhere. I also absolutely need the ability to write unit tests (or write a unit-testing framework) -- I cannot make sizable games without testing.

Unity is good, but unity is 3d; even with hacks, the graphical assets will still be 3d. I'm after 2d, not 3d.

(If you need a Mac or separate licensing for the Mac part, that's okay.)


texts: Unity 5.2 default 3rd person controller makes character fly upwards when moving forward

texts:
I'm new to Unity, and already dealing with a problem using the default third person controller script. I am trying to move and animate the player, but I have a problem, as when I try to move the character it moves beautifully but not only vertically and horizontally - it also moves up on the y axis! It just keeps going higher and higher, and though it's quite funny, it really messes the gameplay.

Here are screenshots of what happens, and yes, I do have gravity turned on:


texts: How can I change Box2D bodyDef type of an object after adding it to the world in Libgdx?

texts:
I have a basic 2d square class that has it's body type set to a Static Body. After the player presses a button on the UI I want to change the body type to a Dynamic Body.

When I change the object to a Dynamic Body within the render method nothing happens.

How can I change the Body Type so that it updates on the screen?

public void show() {
    ...
    s0 = new Square(-10, -20, 5, 5, 3);
    ground = world.createBody(s0.bodyDef);
    ground.createFixture(s0.fixtureDef);
    ground.setUserData(s0.sprite);
    s0.shape.dispose();
    ...
}

public void render(float delta) {
    ...
    if (ready) {
        s0.bodyDef.type = BodyType.DynamicBody;
    }
    ...
}