texts:
To get used to how Godot transforms work, I am attempting to write an orbit control. The goal is for it to behave similarly to the Godot viewport.

So far I have the positioning of my camera working. However, when I try to point it at the center of orbit (0,0,0), the LookingAt() function doesn't seem to work. I have printed the values to the console and just proves beyond a doubt that there isn't any change.

I've tried moving the camera around and using different values for the up-axis, but it still doesn't work.

Here are the pertinent functions from my Camera node's script:

private Vector2 rotateStart;
private Vector2 rotateEnd;
private Spherical spherical = new Spherical();
private Vector3 target = new Vector3();

public void HandleRotation(float delta)
{
    var transform = GetGlobalTransform();
    var viewportSize = GetViewport().GetVisibleRect().Size;

    rotateEnd = GetViewport().GetMousePosition();
    Vector2 RotateDelta = rotateEnd - rotateStart; //Change in rotation
    spherical.SetFromVector(transform.origin); //Spherical = current location

    //Calculate changes to equatorial and vertical rotations.
    spherical.theta += 2 * (float)Math.PI * RotateDelta.x / viewportSize.x;
    spherical.phi += 2 * (float)Math.PI * RotateDelta.y / viewportSize.y;
    var final_transform = new Vector3();

    spherical.CopyToVector3(ref final_transform);
    transform.Translated(final_transform - transform.origin); //Apply position change
    GD.Print(transform);

    //Point at origin (point of orbit)
    transform.LookingAt(target, new Vector3(0, 1, 0));
    GD.Print(transform);
    SetGlobalTransform(transform);

    rotateStart = rotateEnd;
}

public override void _Process(float delta)
{
    if (Input.IsMouseButtonPressed((int)ButtonList.Middle))
    {
        HandleRotation(delta);
    }
    else
    {
        rotateStart = GetViewport().GetMousePosition();
    }
}


texts: Drawing Projected Vertices/Faces In Order

texts:
I recently created a 3d engine, and have gotten to what is (as I've found) the hardest part so far. I need to sort the objects and then draw them. I've looked at sorting algorithms, but my case is rather specialized. I have an array of vertices stored inside the Face3D object which I've created, and need to draw faces correctly when overlapping, Firstly, am I thinking about this correctly? Draw the back vertices first? Secondly, How would I sort this? Here's my code for the Face3D file:

package me.dylan.ThirdDimension.src;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Shape;
import java.awt.geom.Point2D;
import java.util.ArrayList;

public class Face3D {
    Polygon face=new Polygon();
    ArrayList Lines = new ArrayList();
    ArrayList Vertices = new ArrayList();
    Color color;
    public Face3D(int x,int y, int z, int width, int height, int depth,Main m,Color c) {
        color=c;
        Vertices.add(new Point3D(x, y, z, m));
        Vertices.add(new Point3D(x, y+height, z, m));
        Vertices.add(new Point3D(x+width, y+height, z+depth, m));
        Vertices.add(new Point3D(x+width, y, z+depth, m));
        for(int i=0;i
            Vertices.get(i).update();
            Point2D tmp = new Point2D.Double();
            tmp.setLocation((int)Vertices.get(i).x2d, (int)Vertices.get(i).y2d);
            face.addPoint((int)Math.round(tmp.getX()),(int)Math.round(tmp.getY()));
        }

}

public void paint(Graphics g) {
    g.setColor(color);
    Graphics2D g2d = (Graphics2D)g;
    face=new Polygon();
    for(int i=0;i<Vertices.size();i++) {
        Vertices.get(i).update();
        Point2D tmp = new Point2D.Double();
        tmp.setLocation((int)Vertices.get(i).x2d, (int)Vertices.get(i).y2d);
        face.addPoint((int)tmp.getX(),(int)Math.round(tmp.getY()));
    }
    g2d.fillPolygon(face);

}

}

I'd just like to apologize if my question is unclear, it's difficult for me to explain this.


texts: What is the best way to check if a moving 2D object will collide with another immobile one before reaching its destination?

texts:
Provided that both objects have rectangular hitboxes, x and y positions and height/width, what is the best way to check if a moving 2D object will collide with another immobile one before reaching its destination?
No engine is being used.


texts: Screen not rendering after restarting game

texts:
Game works fine on the initial launch on Android, but after that restarting game does not render the graphics on the screen properly.

It is a copy of the question
Sprites not being rendered on screen change - Android Libgdx

but there is no solution yet for the question


texts: How do I calculate collision response between a sphere and a plane?

texts:
I'm trying to create a simple 3D game and need to constrain the player within the limits of the game world. When the player hits the sides of the world I want the player's ship to bounce off slightly.

In effect I'm trying to trap the player within a box, and stop them from escaping through the sides...

I've managed to define the limits of the gameworld as a collection of planes, with normals and distances from the origin. The player has a spherical bounding sphere and from following this website http://www.gamasutra.com/view/feature/3383/simple_intersection_tests_for_games.php I have managed to detect collisions.

I now can't quite work out what to do when a collision is detected. The best I can manage is the player getting stuck in the plane, going straight through it, or bouncing repeatedly off it at a really fast rate.

Common sense tells me I need to calculate the reflected angle off the plane, using its normal and apply that to the player's velocity, however I think I need to first see if the player has gone through the plane which is the bit I can't work out.


texts: What am I missing? (Converting 2D mouse coords to 3D space)

texts:
I'm making a networked game which has a birds-eye view and I'm trying to convert the 2D mouse coordinates into 3D space. Right now I have a perfectly flat grid and it intends to remain perfectly flat, all I really want is the mouse coordinates to translate onto this grid.

I had a solution figured out that worked fine if the camera was perfectly straight looking down which I thought was going to be enough for what I wanted, but now I've found that it would be nicer if the camera had a slight tilt to it which completely messes with what I have. Could someone help me out in what I'm missing?

nearsourceV = GD.Viewport.Unproject(new Vector3(mouse.X, mouse.Y, 0f), camera.Projection, camera.View, camera.World);
farsourceV = GD.Viewport.Unproject(new Vector3(mouse.X, mouse.Y, 1f), camera.Projection, camera.View, camera.World);

mouseCoordinatesIn3D = Vector3.Normalize(farsourceV - nearsourceV);

zoomMultiplier = -mouseCoordinatesIn3D.Y;
zoomMultiplier = camera.CameraOffset.Y / zoomMultiplier;

mouseCoordinatesIn3D = mouseCoordinatesIn3D * zoomMultiplier;

mouseCoordinatesIn3D.X = mouseCoordinatesIn3D.X + camera.CameraOffset.X;
mouseCoordinatesIn3D.Z = mouseCoordinatesIn3D.Z + camera.CameraOffset.Z;

//Sends data and moves character

I figured I needed to include the camera rotation into it somehow, but I'm not really sure how or where.

Thanks!


texts: Trouble with mouseover effect in SDL for square menu buttons

texts:
I have a game with a menu made up of 9 'tiles'. I want the tiles to turn white when the cursor hovers over them (and play a sound), and go back to default when the mouse moves off.  My code works when the cursor is moved slowly, but when it is moved quickly the tiles don't turn back to the default colour when the mouse is moved off, resulting in multiple tiles staying white. I'm not sure if the problem is with my code or with SDL event polling. Below are the relevant code snippets, the full source can be found here

void MenuState::handleEvents(SDL_Event& e) {
    //(...)

    if (e.type == SDL_MOUSEMOTION) {
        int x; int y;
        SDL_GetMouseState(&x, &y);
        mousePos = getActiveTile(x, y);

        if (mousePos >= 0 && tiles[mousePos].tileType() != Tile::type::buttonpressed) {
            tiles[mousePos].setTileType(Tile::type::rollover);
        }
        else if (prevMousePos >= 0 && tiles[prevMousePos].tileType() != Tile::type::buttonpressed) {
            // if mouse is *no longer* inside button
            tiles[prevMousePos].setTileType(Tile::type::button);
            prevMousePos = -1;
        }
    }

    //(...)
}

int MenuState::getActiveTile(const int &x, const int &y) {
    int tilenum = -1;
    for (int i = 0; i < tiles.size(); ++i) {
        if ( !(x < tiles[i].position().x || x > tiles[i].position().x + tiles[i].position().w ||
               y < tiles[i].position().y || y > tiles[i].position().y + tiles[i].position().h) )
            tilenum = i ;
    }
    return tilenum;
}

void MenuState::update() {
    if (mousePos >= 0 && prevMousePos == -1) { // only play when mouse first touches button
        Mix_PlayChannel(-1, rollOver, 0);
        prevMousePos = mousePos;
    }
    //(...)

}

the render function (the 'buttons' are held in a vector of 'Tile's)

void Graphics::drawBoard(const std::vector<Tile>& t, const bool& drawnumber) {
    for (int i = 0; i < t.size(); ++i) {
        SDL_Rect temp = t[i].position();

        if      (t[i].tileType() == Tile::type::invisible)
            SDL_SetRenderDrawColor(renderer, 163, 118, 172, 1); // bg colour

        else if (t[i].tileType() == Tile::type::rollover || t[i].tileType() == Tile::type::buttonpressed)
            SDL_SetRenderDrawColor(renderer, 255, 255, 255, 1); // highlight colour

        else if (t[i].tileType() == Tile::type::shadow)
            SDL_SetRenderDrawColor(renderer, 100, 65, 107, 1); // shadow colour

        else
            SDL_SetRenderDrawColor(renderer, 237, 229, 239, 1); // default colour

        SDL_RenderFillRect(renderer, &temp);

        if (drawnumber){
            if (t[i].tileType() != Tile::type::invisible) {
                std::string num = std::to_string(t[i].number());
                tilenumber = renderText(num, "assets/Calibrib.ttf", fontcolour, 25);
                SDL_QueryTexture(tilenumber, NULL, NULL, &temp.w, &temp.h);
                renderTexture(tilenumber, temp.x+(TILE_SIZE/2 - temp.w/2), temp.y+(TILE_SIZE/2 - temp.h/2), nullptr);
            }
        }
    }

}


texts: How to get smooth movement in a low resolution game?

texts:
I am using monogame to make a simple platformer with a fairly low resolution.

Right now I am struggling to get smooth movement like in the mario games. In those games despite having the low resolution mario can still slowly accelerate from standing still and the movement looks smooth. How did they achieve this?

My current solution performs all of the game's physics and movement in floats and when it comes to drawing the x and y coordinate of the player it is rounded to an int. This results in very jagged looking movement.

Is there any way to improve this so that the movement is smooth and still has acceleration? I was thinking about scaling up all of my assets by 4 and working at a higher resolution but then the player would be able to walk between pixels (as 1 pixel in the assets would be represented by 4 pixels on the screen).

Any help would be much appreciate.

Here is an awful video of my character's movement:https://www.youtube.com/watch?v=riWk8op2VyY


texts:
I have implemented a sprite batching system in OpenGL which will batch sprites based on their texture. However, when I'm rendering ~5000 sprites all using the same texture I'm getting roughly 30fps.

The process is as followed

Create sprite batch which also create a VBO with a set size and also creates the shaders as well
Call begin and initialise the render mode (at the moment just setting alpha on)
Call Draw with a sprite. This checks to see if the texture of the sprite has already been loaded and if so it just creates a pointer to the batch item and adds the new sprite coords. If not then it creates a new batch item and adds the sprite coords to that; it adds the batch item to the main batch. If the max sprite count is reached render will be called
Call end which calls render to render the left over sprites in the batch, and also resets the buffer offset
Render loops through each item in the batch and will bind the texture of the batch item, map the data to the buffer and then draw the array. The buffer will then be offset by the amount of sprites drawn.

I have a feeling that it could be the method I'm using to store the batched sprites or it could be something else that i'm missing but I still can work it out.

The class files are at these URLs:

http://pastebin.com/iCB608tA (header)
http://pastebin.com/ZAytErGB (class)

On top of this, I'm also getting a weird issue where two sprites are batched on after the other the second sprite will use the same coordinates as the last. But, the one that is drawn after it is fine. I can't seem to find what is causing this issue.


texts:
I've just knocked up a fairly basic isometric tile based game and I'm looking for the best way to store the level data.

Each tile coordinate is assigned one or more numbers that correspond to a tile from the tile set. At the moment I have a small level set up in the code but I'm looking for a quicker way to populate a level with tiles and load them into the game.

I was thinking just making XML files would be the way to go and if that's the case any ideas on how I should write them?


texts: Java: creating an instance of a user defined class by reading xml file

texts:
I am trying to write an engine for a game, in particular a component-based one (in my approach components contain both data and logic). So basically I have entities, and each entity has a list of components (each component extends the Component class). Now, I want to be able to define templates for my entities in xml files, and load them at runtime. The template would look something like this:

<Entity>
   <Component name="MovementComponent">
      <...Variables to be initialized...>
   </Component>
   <Component name="RenderComponent">
      <...Animations...>
   </Component>
</Entity>

The "name" attribute is the name of the corresponding component class. Now, of course the components are game-specific so I need a way to create an instance of the component and add it to the entity's list without actually knowing the specific class. I thought about Class.forName("...the "name" attribute...").newInstance(), but this way I can't add the components to the list, since it is an ArrayList of Component and the program cannot know that the object returned by the method newInstance is actually a subclass of Component. Is there any simple way to do this?


texts:
I'm trying to draw currency symbols in an Arial Spritefont. According to this site, the font contains these symbols. I've included the Unicode character region for these symbols in the Content Processor SpriteFont file, like so:
<CharacterRegions>
  <CharacterRegion>
    <Start>&#32;</Start>
    <End>&#126;</End>
  </CharacterRegion>
  <CharacterRegion>
    <!-- Currency symbols -->
    <Start>&#8352;</Start>
    <End>&#8378;</End>
  </CharacterRegion>
</CharacterRegions>

However, whenever I try to draw a € (Euro) symbol, I get this exception:

Text contains characters that cannot be resolved by this SpriteFont

Inspecting the SpriteFont in the IDE at that breakpoint shows the € symbol is in there. I'm at a loss at what could be wrong. Why is this exception thrown?


texts:
I am developing a platformer in Pygame with the eventual hope of releasing it on Steam.

I am currently trying to add input support for multiple controllers.

To do this, I am using the Pygame joystick module, which allows a connected controller to send input events to my event queue (the event types are JOYBUTTONDOWN, JOYBUTTONUP, and JOYAXISMOTION).

I want to have input support for at least keyboards, Xbox 360 controllers, Xbox One controllers, and PS4 controllers.

The problem, of course, is that these controllers all use different button IDs.

One way I thought of getting around this was to call a function in my event processing code which could convert input from any of these devices to a more abstract event tag. For example, keyboard presses of "a", Xbox 360 controller presses of left on the D-pad, and negative motion on the seventh axis of a PS4 controller would all set an abstract "mapped_event" attribute to "left". I could then use this "mapped_event" attribute in my player sprite's process_event() method, which moves him based on event input.

Here's a sketch of how that conversion code would look:

def map_event(event):

    # KEYBOARD BUTTON PRESSES

    if event.type == pg.KEYDOWN:
        if event.key = K_RIGHT:
            mapped_event = "right"
        elif event.key == K_LEFT:
            mapped_event = "left"

    # CONTROLLER BUTTON PRESSES

    elif event.type == pg.JOYBUTTONDOWN:

        if joystick == "Xbox360 controller":
            if event.button == 3:
                mapped_event = "right"
            elif event.button == 2:
                mapped_event = "left"

    # CONTROLLER AXIS MOTION

    elif event.type == pg.JOYAXISMOTION:

        if joystick == "Xbox360 controller":
            if event.axis == 1:
                if event.value == 1:
                    mapped_event = "left"
                elif event.value == -1:
                    mapped_event = "right"

        elif joystick == "PS4 controller":
            if event.axis == 3:
                if event.value == 1:
                    mapped_event = "left"
                elif event.value == -1:
                    mapped_event = "right"

    return mapped_event

From what I can tell, this is the way a lot of people recommend getting around the inconsistent controller issue. For example, I think this is what is meant when people speak about an "intermediate layer" of input processing and "mapping from real buttons to game concepts". Please correct me if I'm interpretting this wrong.

My question is:

How can I extend this method, (or an alternative), to also support all controllers which use, say, XInput/DirectX (according to this answer, a lot of aftermarket controllers use these), while handling multiple OSes?

I am open to using a different framework for processing joystick events, provided the language is Python.

Related Questions

How can one impliment multiple control schemes for a single player?

Correct way to abstract an XBox Controller

Unity3D Joystick Buttons Xbox360 & PS3 have Inconsistent Button Inputs?


texts: Square collision: Detect which side of the wall it collided

texts:
I'm using a standard square collision in my 2D game. The player shoots little balls, and when they hit any wall it should bounce.

The problem is that I know when it hits a wall but I don't know if the collision happened on the side or top/bottom of the wall.

Here's my collision algorithm (pseudo code):

If
A.x < (B.x + B.width) AND
B.x < (A.x + A.width) AND
A.y < (B.y + B.height) AND
B.y < (A.y + A.height)
Then a collision happened

Is it easy to detect if the collision happened on a side or top/bottom? If yes how should I do it?


texts:
I implemented a pathfinding algorithm like this:

There is a mesh of triangles that defines the area the player can walk.
An A* algorithm is used for finding a path from the start triangle to the end triangle.
A funnel algorithm is used for optimizing the path returned by A*.

The result looks like this:

The red lines mark the triangles of the mesh.
The blue lines are the path returned by A*. The path connects the centres of the
 triangles that are found.
The green lines are the path returned by the funnel algorithm.

In the screenshot above, it can be clearly seen that the green path is not optimal. The
optimal path would be a straight line from start to end.

The blue path causes the problem. Since A* just uses the centres of the triangle as a
heuristic to determine the length of the path from one triangle to the next, it thinks
the best way would be to go through the three triangles below rather than the single
triangle above. The blue path is then passed to the funnel algorithm, which only "sees"
the triangles connected by the blue path; it cannot find the optimal path, because it is
given the wrong set of triangles to work with.

So, I suppose the bug is caused by the heuristic of A* failing to determine the correct
length. How to improve this? What is a better heuristic than just measuring the distances
of the centres of the triangles?

Here's the main loop of the A* algorithm:

while ((pCurrent = removeOpenTriangWithLowestEstimatedScore()) != nullptr)
{
    if (pCurrent == pGoal)
    {
        break;
    }

    m_mapClosed[pCurrent] = true;

    for (const CTriangle *pNeigh : pCurrent->neighboursConst())
    {
        ASSERT (pNeigh != nullptr);

        if (isInClosedSet (pNeigh))
        {
            continue; // the neighbour has already been evaluated
        }

        if (!pNeigh->enabled())
        {
            m_mapClosed[pNeigh] = true;
            continue;  // the neighbour is disabled
        }

        auto itNeigh = findInOpenSet (pNeigh);

        if (itNeigh == m_lstOpen.end())
        {
            // Add pNeigh to the open set.
            tas.pT = pNeigh;
            tas.dScore = DBL_MAX;
            m_lstOpen.push_back (tas);
            itNeigh = m_lstOpen.end();
            itNeigh--;
        }

        // Estimate the distance from the neighbour to the goal.

        double dNeighToGoal = pNeigh->distanceOfCentres (*pGoal);

        if (dNeighToGoal < dNearestDist)
        {
            dNearestDist = dNeighToGoal;
            pNearestTriangle = pNeigh;
        }

        // Compute the actual score from start to the neighbour.

        double dScore = actualScore (pCurrent) + pCurrent->distanceOfCentres (*pNeigh);

        if (dScore >= actualScore (pNeigh))
        {
            continue; // this is not a better path
        }

        // This path is the best until now. Record it!

        m_mapCameFrom[pNeigh] = pCurrent;
        m_mapActualScore[pNeigh] = dScore;

        updateEstimatedScore (itNeigh, pNeigh, dScore + dNeighToGoal);
    }
}

And here's the main loop of the funnel algorithm:

for (it++; it != lstTriangles.end(); pPrev = *(it++))
{
    const CTriangle *pT = *it;
    ASSERT (pT != nullptr);
    ASSERT (pPrev != nullptr);

    getOrderedVertices (*pT, *pPrev, ptA, ptB, ptC);

    // ptA is the new vertex, ptB and ptC are shared by pPrev.

    if (isTurnedAway (ptApex, ptA, ptB))
    {
        ptApex = ptB;
        vecResult.push_back (ptApex);
    }
    else if (isTurnedAway (ptApex, ptC, ptA))
    {
        ptApex = ptC;
        vecResult.push_back (ptApex);
    }
}


texts: Unity: How to make script work with duplicated objects?

texts:
I have an object in my game that, when clicked, causes the player to move toward it. It does this by sending its position to the player's SetTarget function. The player's Move function then heads toward the position.

This is working, but when I duplicate the object and click on it, the player still moves toward the original object's position. When I print debugging statements to the console, it appears that both positions are being calculated, but the original position is the last one and wins out. (I'm using the object's this.transform.position to send the position to the player's SetTarget function.)

Can I not duplicate objects like this and expect the script to work? Do I need to use a prefab? If so, how? I know how to create prefabs but am not sure what I would need to change with the script or other settings when they are created. Thanks.

Here's the code:

public class PotController : MonoBehaviour {

private GameObject chefObject;

void Start () {
    chefObject = GameObject.Find ("Chef");
}

void Update() {
    if(Input.GetMouseButtonDown(0)){
        //print ("pot clicked!");
        ChefController chefScript = chefObject.GetComponent<ChefController> ();

        print (this.gameObject.transform.position);
        chefScript.SetTheTarget (this.gameObject.transform.position);
    }
}
}

public class ChefController : MonoBehaviour {

private Vector3 target;
public float speed = 2;

// Use this for initialization
void Start () {
    target = this.transform.position;
}

private void MoveTowardsTarget() {
    Vector3 targetPosition = new Vector3(0,0,0);
    targetPosition = target;
    Vector3 currentPosition = this.transform.position;
    //check distance to target
    if(Vector3.Distance(currentPosition, targetPosition) > 0.4f) {
        Vector3 directionOfTravel = targetPosition - currentPosition;

        directionOfTravel.Normalize();

        this.transform.Translate(
            (directionOfTravel.x * speed * Time.deltaTime),
            (directionOfTravel.y * speed * Time.deltaTime),
            (directionOfTravel.z * speed * Time.deltaTime),
            Space.World);
    }
}

void Update () {
    MoveTowardsTarget ();
}

public void SetTheTarget (Vector3 position){
    target = position;
}

}


texts: How to Steer a Moving Object Away From Another Object(s)

texts:
I'm working with C# in Unity, and I'm making a top-down space shooter game in which there are many different AI-controlled ships flying around. The problem is that these ships often fly on top of one another in passing, and sometimes even will fly the same route on top of one another if given the same waypoint. I want to add a system to steer my AI ships away from each other as well as other obstacles so that instead of overlapping one another when flying the same path they will fly side-by-side, and will also try to avoid things that pass in front of them.

My current system essentially works like this: The AI looks at all of the current objectives, points of interests, etc, and decides where it wants to be on the map (a coordinate). The AI then sends an input direction to the ship, which then applies acceleration in that direction and changes the velocity. Therefore, any solution to alter my ship's pathing would need to alter this input direction somehow.

So my first idea was to check if there are any obstacles (ships, asteroids, structures, etc) within a radius of the ship, increasing this radius based on the ship's velocity (higher velocity = larger "view" radius):

Collider2D[] hits = Physics2D.OverlapCircleAll(transform.position, ship.velocity.magnitude);

If there is something nearby, calculate the direction to that collision, then calculate the opposite direction and scale it to the reciprocal, which also has the added effect of making the aversion stronger the shorter the distance to the collision is:

foreach (Collider2D hit in hits)
{

    if (hit.gameObject == gameObject) continue; // exclude self from the search

    Vector2 v = hit.ClosestPoint(transform.position) - (Vector2)transform.position;
    v = (1 / v.magnitude) * -v.normalized;

I would perform this for every nearby obstacle and add all of these together to get the avoidance vector:

    avoidanceVector += v;
    continue;
}

Then I add the total avoidance vector to the AI's input direction and normalize the result:

inputDirection += avoidanceVector;
inputDirection.Normalize();

However, when i add this avoidance vector to my input direction, my ships exhibit a strange behavior where sometimes they will simply stop moving completely. commenting out the line where i add them together stops this behavior.

I'm really not sure what could be going wrong here, but I think it has to do with my approach altogether. Can anyone help me figure out a clean, simple way to make my ships steer away from other objects?


texts: One VAO takes more time than more than 40 put together despite being simpler

texts:
I was running visual studio's CPU profiling tool when I noticed that of my RenderScene call, my skybox was taking up 30% of the frame time.

This is particularly weird, as as you can see the Object3D::draw call is much less, and I have just one Skybox and 35 Object3Ds.

I went in further and found that glBindVertexArray was taking all of the time. What could be causing this? The VAO in question is defined here:

    glGenVertexArrays(1, &thisVAO);
glBindVertexArray(thisVAO);

//Setup the Vertex buffer
glGenBuffers(1, &vertsVBO);
glBindBuffer(GL_ARRAY_BUFFER, vertsVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*36, skyboxVertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)0);
glEnableVertexAttribArray(0);

and the Skybox Draw call here:

//Shader uniform setting....
    glUseProgram(thisConfig.skyboxShaders->getProgramID());
// ... set view and projection matrix

thisConfig.skyboxShaders->setMats(rs->angle, thisConfig.currLighting->persp);

thisConfig.skyboxShaders->setClipPlane(rs->clipPlane, rs->useClipPlane);

//Actually draw the skybox
glBindVertexArray(thisVAO);

glActiveTexture(GL_TEXTURE0);

glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);

glDrawArrays(GL_TRIANGLES, 0, 36);

Here is visual studio's take on the draw call:

VAOs for Object3D have 5 VBOs and an elements buffer, as opposed to skybox's one VBO, and skyboxVerticies has 96 entries in it for 36 verticies. Most meshes for object3Ds are 1000+ verticies plus, and the Terrain has 48,000. Anything obvious I am missing? The vertex co-ordinates are very large, would that affect the call time for glBindVertexArray()?

Edit : skybox shader

#version 330 core
layout (location = 0) in vec3 aPos;

out of TexCoords;

uniform mat4 projection;
uniform mat4 view;
uniform vec4 clipPlane; // The Plane Clipping
uniform int usePlane; // PLane bool

void main ()
{
    TexCoords = aPos;
    gl_Position = view * vec4 (aPos, 1.0);
}

Edit :
Changing the order has changed things completely, It appears the first glBindVertexArray() per frame has significant overhead (30% of each frame), regardless of shader or vertex array size. Why is this? How can I fix it?


texts:
I use a

 Dictionary<string, Texture2D>

for storing textures and every texture in the game is a reference to a texture from this dictionary. However when all references are gone, does the GC dispose of the textures (I don't think so as they are still accessible)?

And if it doesn't, how can I count the references to the textures so I can dispose of them manually?


texts: How are physical model programmed in simulation games?

texts:
Being a Gran Turismo fan, I'm wondering what are the algorithms used to compute realistic behavior for friction, aerodynamism, velocity, curves etc.

Also, are there sophisticated ways to simulate fluid mechanics in flight simulation which are trivial enough for an amateur project ?

If I wanted to build a flight simulator, neglecting the parameters which have the littlest effect (temperature, pressure, humidity, friction of the air on the wings, gravitational center of the plane, etc), are there some kind of physical formulae or programming models I should know about ?

Or does physics engine feature such kind of simulation dedicated calculation ?


texts:
I have a query about how to create a 2d landscape level using libgdx/ box2d (Or possibly with Unity) for Android and iOs. Let me describe the goal and then the specific points I need help with.
What I'm trying to create is something like "Hill Climb Racing" where the player has to drive across a finite 2d free-form landscape, like the one shown here. Different areas may have different properties (friction, texture, restitution, etc) as shown. The player will be able to pinch and zoom out to see all or most of the map and pinch to zoom in to see details..

The level width will vary from game to game but at most it will be about 800 box2d meters wide. Now if I use 32px/m that requires an image 25,600 pixels across and this is where the issues start.. I can't tile it because that might preclude me from making free formed curves which I need to be able to do.
So what I need to know is:

How can I create a box2d body for the terrain?
What pixel/meter ratio should I use?
How many pixels wide should the image be?
Should I split the image up into sections and how should I chunk the images together?
What strategies have people used before to achieve this effect?

Hope I have been specific enough and thanks for all the help..


texts:
I am trying to matemathically predict how long will projectile fly until it reach
 the target. I am trying to implement this formula:

t = [V * sin(α) + √(V * sin(α))² + 2 * g * h)] / g

where I know V (velocity of projectile) , α (angle of launch) , h (height of launch) The problem is it shows some weird results. I am not sure what is wrong (using ue4):

float Time = Velocity * FMath::Sin(AngleDeg) + FMath::Sqrt(FMath::Square(Velocity * FMath::Sin(AngleDeg)) + (2.f * Gravity * Height));
Time /= Gravity;

For example this test inputs:
        Gravity = 9.8;
        Height = 10;
        Velocity = 10;
        AngleDeg = 10;
shows 0.97 seconds but theresult should be 1.61 according this calculator: https://www.omnicalculator.com/physics/projectile-motion ... When I try different inputs the result is always wrong... I also got the formula from this website so not sure what's wrong. Thanks for any advice


texts:
Ogre3D

I would like to put some space junk in my game environment. Make it look like the first 2 search results. Those junks don't need to be interactive. Just need to have a 3D junk circling around the earth.

Can the community give some suggestion on how to implement this? Should I use particle in Ogre3D or create entities for those junks, or any other approach? If using particle, how should I make the object still and spread out around the earth? Thanks.


texts: Can Simple Direct Media Layer be used with WebGL?

texts: I have read that on desktop OpenGL + SDL is a great way to learn. In looking at WebGL I couldn't find a Web version of SDL. On their site I see bindings for all sorts of languages, but no JavaScript. It seems obvious that this gives an answer of 'no' to my question, but I also came upon code snips while googling around that seemed to be doing it. Whatever the missing piece is I'm not getting it...


texts:
Looking at examples at http://learnopengl.com/#!Getting-started/Hello-Triangle and many different places, I've found that the draw sequence usually goes like this:

// setup VBO, VAO, load shaders

while (true) { // game loop
  glUseProgram(shader);
  glBindVertexArray(someVAO);
  drawStuff(...);

  // ...
}

Now my question is, is there any reason why I'd want to repeatedly do glUseProgram(...) on each frame, unless I'm using multiple shaders (such as OpenGL clearing currently used shader after rendering?)?

Also, if I am using multiple shaders, do I need to glUseProgram before switching to a different VAO? I'm unclear on whether the VAO just gets set as active, or if it actually modifies the state of a currently used shader. I've tried looking this up in the OpenGL spec, but couldn't quite find it.

edit: Yes I did mean glUseProgram, sorry.


texts:
I'm currently doing my final assessment for my study Game Development. I'm currently facing a real weird (maybe explainable) result from my camera.

I just set up my scene with alot of tiles and a character. When I set up the camera's position and direction, I experience something strange. The camera is tilted somewhat, and I can't explain why that is happening.

This is looking pretty good. Except for when I move the camera, the tilting is becoming worse.

Is this behaviour I should expect from the camera?
I made sure the camera is never rotated, is there any possibility the models are slightly rotated?
I use LibGDX with exported FBX files from 3Ds Max, converted to LibGDX's format "G3DB", are there any known issues with that?


texts: Supersampling - Pixel color average calculation

texts:
I am currently trying to understand Supersampling.

Wikipedia says (or at least Wikipedia tells me) that multiple color samples are taken from one pixel to calculate the final result. But to my mind one pixel has exactly one color and logically, the average of an infinite amount of equal colors remains the same.

So, how can the resulting color differ from the original pixel's color?


texts: Can I use GLFW and GLEW together in the same code

texts:
I use the g++ compiler, which could be causing the main problem, but I'm using GLFW for window and input management, and I am using GLEW so that I can use OpenGL 3.x functionality. I loaded in models and then tried to make Vertex and Index buffers for the data, but it turned out that I kept getting segmentation faults in the program. I finally figured out that GLEW just wasn't working with GLFW included. Do they not work together?

Also I've done the context creation through GLFW so that may be another factor in the problem.


texts: Unity build error: "Could not find file...build.asm.js "

texts:
I made a WebGL game and the first few times it built well, then I continued working on it a bit and when I build it it gives me an error (and does not generate the build files), error: FileNotFoundException:

  Could not find file "C:\Users\Public\Documents\Unity Projects\Infinite
  Side Scroller\Temp\StagingArea\Data\Native\build.asm.js".

Heres the full error message:

  FileNotFoundException: Could not find file "C:\Users\Public\Documents\Unity Projects\Infinite Side Scroller\Temp\StagingArea\Data\Native\build.asm.js".
  System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.IO/FileStream.cs:305)
  System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share)
  (wrapper remoting-invoke-with-check) System.IO.FileStream:.ctor (string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare)
  System.IO.File.OpenRead (System.String path) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.IO/File.cs:363)
  System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.IO/StreamReader.cs:167)
  System.IO.StreamReader..ctor (System.String path, System.Text.Encoding encoding)
  (wrapper remoting-invoke-with-check) System.IO.StreamReader:.ctor (string,System.Text.Encoding)
  System.IO.File.ReadAllText (System.String path, System.Text.Encoding encoding) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.IO/File.cs:587)
  System.IO.File.ReadAllText (System.String path) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.IO/File.cs:582)
  UnityEditor.WebGL.CodeAnalysisUtils.ReplaceDuplicates (System.String builtCodePath, Int32 interations) (at /Users/builduser/buildslave/unity/build/PlatformDependent/WebGL/Extensions/Unity.WebGL.extensions/CodeAnalysisUtils.cs:145)
  UnityEditor.WebGL.WebGlBuildPostprocessor.PostProcess (BuildPostProcessArgs args) (at /Users/builduser/buildslave/unity/build/PlatformDependent/WebGL/Extensions/Unity.WebGL.extensions/BuildPostprocessor.cs:589)
  UnityEditor.PostprocessBuildPlayer.Postprocess (BuildTarget target, System.String installPath, System.String companyName, System.String productName, Int32 width, Int32 height, System.String downloadWebplayerUrl, System.String manualDownloadWebplayerUrl, BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.BuildReporting.BuildReport report) (at C:/buildslave/unity/build/Editor/Mono/BuildPipeline/PostprocessBuildPlayer.cs:186)
  UnityEditor.HostView:OnGUI()

What is the problem? And how can I fix it?

Feel free to ask me for more information?

Thanks in advance for the help!


texts: How to correctly setup latest LWJGL libraries to Eclipse?

texts:
A year ago, I understood how to setup an LWJGL project in Eclipse IDE.
Now LWJGL has a lot of changes including a different file structure.
I downloaded the latest release, LWJGL 3.1.0 Build 40 from the official site.

There's also a page explaining how to get started, but it does not help me to set it up in Eclipse.
When I extract the downloaded .zip file, I only get .jar files (and .txt licences).
I see nowadays there are no .dll natives for a specific operating system.

Instead of that, I see jars like lwjgl-glfw-natives-windows.jar. I expect these are now the files that were previously .dll files.

Can someone explain to me how to set it all up correctly?


texts:
I'm working on a Magic-esque TCG in Unity. Currently, the cards themselves are all prefabs: I have a Satyr Archer prefab, a Candle Wisp prefab, etc. This works fine for now, since I only have a few cards, but by the time I get to several hundred, I feel that this may become unwieldy.

Are prefabs a good way to store a large list of cards? Should I be making those prefabs using an XML document and a script?


texts: Grayscale color mode texture not rendering in libGDX

texts:
I am about to develop a game completely in shades of grey using libGDX and just for testing purposes, i created two textures in photoshop:

2048 x 2048 plain white png image with RGB color mode of size 19.1KB
2048 x 2048 plain white png image with grayscale color mode of size 7.67KB

... so basically both are just plain white images to look at, but the GREY.png one takes comparatively less space than the RGB.png. While rendering the both the images one at a time, RGB image renders perfectly but the grayscale one does not render at all and the output is completely black. My code:

@Override
public void create() {

    texture = new Texture (Gdx.files.internal ("GREY.png")); // ...just change to "RGB.png" to render RGB.png image..
    batch = new SpriteBatch ();

}

@Override
public void render() {

    Gdx.gl.glClearColor (0, 1, 0, 1);
    Gdx.gl.glClear (GL20.GL_COLOR_BUFFER_BIT);

    batch.begin ();
    batch.draw (texture, 0, 0);
    batch.end ();

}

@Override
public void dispose() {
    texture.dispose ();
}

This is all it...No cameras are used, just 2 lines in create() and 5 lines in render() method and 1 line in dispose() method, nothing fancy at all...

Also it will be really stupid to load 19.1KB texture and render it in greyscale using shader when you can directly load same looking image of 7.67KB size.

I don't understand why libGDX does not render the image with grayscale color mode, is it not supported?

UPDATE:
grayscaled images are supported by libGDX and

 texture = new Texture (Gdx.files.internal ("gs.png"), Pixmap.Format.LuminanceAlpha, true);

solved my problem.


texts: Find extreme points of a rotated ellipse function on a given axis

texts:
How to find the points where it is most extreme on the X and Y axis?

For example lets say I have an equation that describes an ellipse that is rotated:

(x * RadiusX * Rx + y * RadiusX * Ux)^2 +
(x * RadiusY * Ry + y * RadiusY * Uy)^2 = RadiusY^2

How can I find the points where it will be most extreme on each axis

Please keep in mind the values for variables RadiusX, RadiusY, Rx, Ry, Ux, Uy are known.

An example with values:

((x * 1 * 0.70711) + (y * 1 * -0.70711))^2 +
((x * 1.414213 * -0.70711) + (y * 1.414213* -0.70711))^2 = 1.414213 * 1.414213


texts:
I'm using lib3ds's 3dsplay example to load this model, whose suffix is .max
but get this error:
3dsplayer: Error: Loading 3DS file failed.

But it can load the .3ds model shipped with lib3ds.
Why lib3ds can't open this .max model?


texts:
The following code works  so good , but it is so long.

How can I use a for loop to write a short script for any number of prefabs?

public GameObject prefab1;
public GameObject prefab2;
public GameObject prefab3;
float timCounter = 0f;

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

  float[]  r = {3,2,1};
  float[]  f = {3,2,1};

  //motion on a circle

  float x = r[0] * Mathf.Cos(f[0] * timCounter);
  float y = r[0] * Mathf.Sin(f[0] * timCounter);

  float x1 = r[1] * Mathf.Cos(f[1] * timCounter);
  float y1 = r[1] * Mathf.Sin(f[1] * timCounter);

  float x2 = r[2] * Mathf.Cos(f[2] * timCounter);
  float y2 = r[2] * Mathf.Sin(f[2] * timCounter);

  float z = 0;

  //position of a any prefab_n = position of prefab_(n-1) + Vector3(x,y,z)

  prefab1.transform.position = new Vector3(x,y,z);

  prefab2.transform.position = prefab1.transform.position + new
  Vector3(x1,y1,z);

  prefab3.transform.position = prefab2.transform.position + new
  Vector3(x2,y2,z);
 }


texts: I was curious as to how you would go about converting from pixel to tile precision on a tile map. For example, let's say my map is comprised of 8x6 tiles, each of which are 50x50 pixels in size. If I could only get the current coordinates of my mouse in pixels, how would I go about finding which tile those pixels are contained in programmatically?


texts: MonoGame EffectPass.Apply() doesn't work

texts:
Currently I'm doing the following:

spriteBatch.Begin(effect: effect);

// Draw stuff normally

effect.Parameters["flag"].SetValue(true);
effect.CurrentTechnique.Passes[0].Apply();

// Draw stuff with flag

effect.Parameters["flag"].SetValue(false);
effect.CurrentTechnique.Passes[0].Apply();

// Draw stuff normally

But this doesn't work. The flag stays false even after I apply the changes.


texts: Position is not what it should be when attaching fixture

texts:
In XNA / Farseer I have something like this:

Body body = BodyFactory.CreateRectangle(world, 1f, 2f, 1f);
FixtureFactory.AttachCircle(0.5f, 1f, body, new Vector2(0f, 1f));

I have been told that body.Position property is the center of the AABB of the Body. In this example it seems not to be so. When I do something like this to display the coordinates of the position I see that they are at the center of the rectangle created at the beginning:

BodyFactory.CreateCircle(world, 0.1f, 1f, Body.Position);
BodyFactory.CreateCircle(world, 0.1f, 1f, Body.WorldCenter);

The center of gravity seems also to be the same.
I need this for drawing my texture over the Body. The origin for drawing is then like this:

Vector2 Origin = new Vector2(Sprite.Width / 2, Sprite.Height / 2);

Am I doing something wrong or does the engine not recognize, that a circle fixture is attached to the rectangle?
Is there any workaround?


texts: Permanently Sync a wiimote with a computer

texts:
i have tried to look up many ways to sync up my wiimotes to my computer so that i can program games with it, but every time it only syncs them up temporarily, or if it says it can permanently sync it, it doesn't actually do it. it gets tiresome when i have to keep on reconnecting it every time i want to save battery life. how would i be able to sync up my wiimote to my computer so that if i turn off my wiimote, i can just hit any button and it will automatically sync it up?

Edit: I have looked here: http://wiibrew.org/wiki/Wiimote under Bluetooth pairing for some advice, but I have no idea how to export the char array to the window (i am using the standard pairing with a Bluetooth device, but instead of pairing without a code, i use the "enter device's pairing code" section. this should work, but I'm stuck at how to enter the weird characters that aren't on the keyboard).


texts: How to implement "identify item" feature in RPG

texts:
In many games there is an approach that you can't use item that hasn't been identified. And usualy you can't identify it by just using it. While this approach simplifies a lot of things it just doesn't feel right to me. It doesn't make sense that I can't equip an armor or sword because I don't know if it has any magical features.

I was thinking about some kind of "identification by use" system but I can't figure out a natural way to do it. What if I drink a potion that boosts my "Speech" skill for a period of time? Should my character instantaneously know that its skill have increased? Should it know the exact value? Or should I increase the skill behind the scenes but leave the displayed value intact and just give some subtle hint ("You suddenly (...)")?

What about weapons and armors? It wouldn't make sense to know anything about it just by equipping it. One approach would be that attacking a target could update weapon's min and max damage basing on damage dealt but then it greatly depends on target's defense and resistances (I'm not sure if that's a bad thing though).

Of course there are conventional ways like identification scrolls and I do have them but I was hoping for some alternative (not a replacement though, you probably can't know everything about every object only by using it).

Has anyone ever thought about it and can share some insight?


texts:
what are the steps to perform downsampling on a texture ?
I've got as far as rendering the scene to a render target, but I'm not sure as to how to then render that to a smaller texture in order to blur it.
I can't seem to find in good explanation or tutorial about this technique.


texts: Questions regarding games architecture with XNA

texts:
So I've finally got around to playing around with XNA and have been toying around with making a 2D game (I have a bunch of art assets from a friend who developed it on iOS)

A lot of things seem to be easy to do and come out of the box however I'm left stumped for a bunch of stuff since most of the literature (the books I bought for instance) don't pay too much attention to 2D.

I'd really appreciate any clarification or being pointed to more information on the following questins:

What is the point of a Game Service?
I understand the whole idiom of registering an object as a service so that any other GameComponent can grab it, however how does this beat out simply making it perhaps public or static?
For instance, my book recommended registering the SpriteBatch object in the Game.cs class. I'm not sure how this is preferrable to simply making it public/static since there should only be one instance of Game anyways (singleton)?
I'm confused on when I should inherit from GameComponent or RenderableGameComponent.
I'm trying to follow a Manager/Controller design, such that all entities are created/owned by a single manager and the same for other things. I currently have each Manager/Controller inherit from GameComponent, however how does this beat out having the Game object own all the Managers and manually call update on them and draw ?
I noticed that Initialize is called before ContentLoad(), I found this annoying since in my Initialize is where I'd like to create some of my entities (i.e. Sprite, Player etc..), however I can't give them their loaded SpriteSheets or Textures since the call to load them hasn't occurred yet.
Am I perhaps initializing incorrectly or do people just assign the texture further down in ContentLoad?

Those seem to be my biggest "WTF" of not really understanding


texts: How can I dynamically switch between graphics APIs?

texts:
In games like the new "Doom", you have a console, from which you can use commands to reduce the game's quality or even to switch graphics API, from Opengl to Vulkan and viceversa.

How is this done? I think it reconstructs the window context based on the chosen graphics API (maybe?). How could this be implemented?


texts: Invulnerability timer while standing on spikes

texts:
I want to decrement the player's health every .7 seconds while the warrior is standing on a spike tile. Every frame, the game calculates what kind of tile the player is walking into. I've tried calling a function that uses setTimeout from the spike tile code in the walkingIntoTileType switch statement and I've tried using setInterval directly in the switch statement. My current implementation has this declaration at the top of the warrior class:

this.interval = setInterval(function() {
            //blank
        }, 1000);
clearInterval(this.interval);

I then have this in the warrior movement code, which gets run every frame:

switch( walkIntoTileType ) {
  case TILE_GROUND:
    this.x = nextX;
    this.y = nextY;
    this.onSpikes = false;
    break;
  //other tile type code...
  case TILE_SPIKES:
    this.x = nextX;
    this.y = nextY;
    this.onSpikes = true;
  default:
    // any other tile type number was found... do nothing, for now
    break;
}
if(this.onSpikes){
    if(!this.running){
        this.running = true;
        this.interval = setInterval(function() {
            this.playerHealth--;
        }, 700);
    }
}
else{
    this.running = false;
    clearInterval(this.interval);
}

Despite this, the player's health never gets decremented when on the spikes, and the console returns no errors. I would think the interval is not falling victim to garbage collection since its variable is declared at the top of the class, but obviously I could be wrong.


texts: How do I detect collision between movie clips?

texts:
I know there are some methods you can use, like hittestPoint and so on, but I want to see where my movie clip collides with another another movie clip. Are there any other methods I can use?

I have had trouble finding a good introduction to game physics, and I would like to know how to something like this, properly.


texts: keeping clients up to date with server state in an mmo-like game

texts:
I'm making an online RPG that could classify as an MMO, but I'm keeping the project scope very small by making the game's systems simple, and focusing mostly on what I want to learn: real-time networking.

The problem I'm facing is that that I don't want to update every player about every other player, all the time. This is a huge waste of bandwidth, and may even be impossible without a really beefy connection.

My solution is:

Keep track of which entities are in the client's visibility range
Send a "full entity state" packet when the client enters the world
Send a "create entity" packet for any entity that enters the visibility range
Send a "delete entity" packet for any entity that leaves the visibility range
Send a "update entity" packet for any entity that updates within the visibility range

I don't like the fact that when the client moves, I have to update the list of entities it can see, because it means I still have to loop over every entity. Is there anything better? Can this solution be improved somehow? If so, could you provide further reading, or possibly even sample implementations?


texts: How to better refactor loops in procedural world generation?

texts:
One of the steps for cell-based dungeon generation is deciding the amount and location of exits for each room. My current set up consists of the following:

Define my exits. There are 15 types of room exits:

Left (L), Right (R), Top (T), Bottom (B).
Every non-redundant combinatoric of two directions (LT, TR, RB, BL, LR, TB)
The same for three directions (LTR, TRB, RBL, BLT)
All directions (LRTB)

Create a list exitsList that contains the type of exit of that index, i.e. exitsList[0] = L means that our first room has a single exit: one to the left.

After creating my basic level layout and having my exit generation ready, it's time to go back to each room and assign its exits, and this is the part I'm having my doubts about.

Currently, my method for assigning rooms is to make a case check looping through each cell. Something such as:

for (each room){
    switch (exitsList[this_room]) {
        case L:
            place_exit_L;
            break;
        case LT:
            place_exit_L;
            place_exit_T;
            break;
        case TR:
        .
        .
        .
        case LTRB:
            place_exit_L;
            place_exit_T;
            place_exit_R;
            place_exit_B;
            break;
        default:
            return_error;
            break;
    }
}

While this can work, it seems very inelegant, and more importantly obnoxious to read by a human. I was able to refactor cases that shared the same type of exit by omitting breaks, for example:

case LTR:
    place_exit_R;
case LT
    place_exit_T;
case L
    place_exit_L;
    break;

But this seems rather arbitrary. I suspect there's a more efficient way to do this, or at least one that won't become a pain to read by other people if the number of exits somehow increases.


texts:
I'm build a multiplayer first person shooter, that supports 32 players.

What is the best way to test large quantities of players?

I'll need 32 steam accounts, with 32 machines to run on. Less, if I can switch to virtual machines.


texts: Efficient collision detection - tile based HTML5/Javascript game

texts:
I'm building a basic RPG game and I'm looking at collisions/pickups etc now.

It's tile based and I'm using HTML5 and Javascript.

I use a 2D array to create my tilemap.

I'm currently using a switch statement for whatever key has been pressed to move the player.

I have if statements to stop the player going off the edge of the map and viewport. If the player is about to land on a tile with tileID 3 then the player stops.

Here is the statement:

canvas.addEventListener('keydown', function(e) {
    console.log(e);
    var key = null;
    switch (e.which) {
        case 37:
            // Left
            if (playerX > 0) {
                playerX--;
            }
            if(board[playerX][playerY] == 3){
                playerX++;
            }
            break;
        case 38:
            // Up
            if (playerY > 0) playerY--;
            if(board[playerX][playerY] == 3){
                playerY++;
            }
            break;
        case 39:
            // Right
            if (playerX < worldWidth) {
                playerX++;
            }
            if(board[playerX][playerY] == 3){
                playerX--;
            }
            break;
        case 40:
            // Down
            if (playerY < worldHeight) playerY++;
            if(board[playerX][playerY] == 3){
                playerY--;
            }
            break;
    }

    viewX = playerX - Math.floor(0.5 * viewWidth);
    if (viewX < 0) viewX = 0;
    if (viewX+viewWidth > worldWidth) viewX = worldWidth - viewWidth;

    viewY = playerY - Math.floor(0.5 * viewHeight);
    if (viewY < 0) viewY = 0;
    if (viewY+viewHeight > worldHeight) viewY = worldHeight - viewHeight;

}, false);

Is there a more efficient way of handling collisions, than loads of if statements for each key?

The reason I ask is because I plan on having many items that the player will need to be able to pickup or not walk through like walls cliffs etc.


texts: Why does my SDL code crash when I move the mouse over the window?

texts:
Whenever I move my mouse below where the image renders in my game, the SDL window crashes and closes down.

I have narrowed the crash down to the bit of code where I check to see if the Escape key was pressed and quit my game; the relevant part of my event loop is:

while (SDL_PollEvent(&e))
{
  if (e.type == SDL_QUIT)
  {
    quit = true;
  }
  if (e.key.keysym.sym == SDLK_ESCAPE)
  {
    quit = true;
  }
}

I found that if I remove the if(e.key.keysym.sym... check, the crashing stops. What is wrong with my code?


texts: self extending factory: return type and serialization

texts:
I'm trying to implement a better management for the objects in my game project.
With input from another thread here on S.O., I decided to implement different collections for different types for better access. Seems to be a common way. So far I #included all the class files and added containers (just maps right now) for each type I needed/wanted, as well as functions to create/add/remove etc., that take care of what is needed. That way no free objects exist (object's constructors are private) that could be missed somewhere.
But ofc that means for every new type the container/manager/factory needs to be modified and that's error prone. So I wanted to try and make it self extending with a registration like this:
template<typename ObjectType>
class Registration
{
    public:
        Registration(const std::string& typeID)
        {
            EntMan::getInstance()->registerTypeCreator(typeID, [] (Properties* props)->Entity* {return new ObjectType(props); } );
        }
};

saving it in a std::map<std::string, std::function<Entity*(Properties* props)> >. This works, ofc it's a common pattern, but has especially one flaw: the return type.
I could add as much additional containers, defined by tags for example, as I want (shurely helps with iteration/preselection), but the contained items would always be just base class pointers.
So if I get an item I still would need to dynamic_cast (or static_cast with if(object->getType == "someThing") ) it to the derived type to get full derived access to the object. Seems wasteful and error prone.
Integrating all functionality with virtual functions would solve this, but in the end turns the base in a kind of blob class. Doesn't feel right either.
Let alone the fact that it would also be also pretty horrible for data locality. Not my main concern right now, but maybe will be in the future.
I'm a bit uneasy with the Properties "parameter amalgamation"-workaround aswell, to fullfill the std::function criteria of having the same signature, as it's a bit error prone doing it "by hand" for example, but should be less of a problem once it's abstracted away with parsing those as prefabs from files and
accessing those. Still, it also would mean a lot of wasted space to save those as prefabs...
So I'm at my wits end here.
How could I go on from here, if I need...

different collections for different types (for preselection)
acessors delivering the proper derived types (for avoiding casts and blobs)
self extending, no modification needed just for adding types
serializable use (ie: create("stone") for use with parsing functions of xml data etc. )

Can this be done? Or is this a dead end? No good idea at all?
Thanks in advance for any help.


texts:
I'm a JS dev but pretty new to Pixi and 2D developemnt so please bear with me as I explain this.

I want to write a simulator for short path finding (for evacuation purposes). I decided to use Pixi.js for this since it seems capable of doing everything I need to do. I followed this tutorial to try to learn how Pixi works and if its right for this.

The tutorial didn't seem to answer many questions I have and I still have some confusion. Before I dive into writing the code, I want to know how wall detection in Pixi acheived.

Take the below map for example:
It is a 800 x 800 png file (where everything but the blue is transparent[no grid lines]) that i can load into Pixi as a Sprite. I created it in Tiled editor. So it can be exported as a tilemap, JSON, CSV etc. When I export it as JSON, here is the file contents: https://pastebin.com/zGh1XmR7

The blue boxes represent walls.
I want to load in other various sprite objects so that it will look like this:

The people in the simulations cannot cross the blue walls and they cannot cross the pink circles (they represent danger zones). I intend to use easystar.js to find the shortest path to exits for the people sprites in the map.

So my question is this, how does Pixi recognise the blue walls? Is it something I have to do when creating the tileset png? Like something defined in the JSON file for the tileset atlas? Maybe SVG? Or is there a pixi function to do this?
Is this the best approach to doing this and is Pixi even the best way to do this?

I'm looking for a tried and tested solution or a pointer in the right direction.


texts: How would one draw many objects using the same VBO

texts:
I'm kind of stuck with this question for some time now, maybe because I don't know exactly what to search for, it might be a term I have not heard of yet as most tutorials ends after drawing one object to the screen using a VBO.

Being a newbie to OpenGL as well as GLSL I do know at least a few things, one being that you always want to send as little information as you can from CPU -> GPU and by as few times as possible (better to send all data at once, instead of many small packages per frame). Knowing this tells me that there must be a better way to draw many of the same object, say a teapot, than looping over transformations then "glDrawArrays" and then repeating that step over and over.

It should be possible to send some kind of array containing the number of teapots you want to draw and all the positions/transformation-matrix you want for them.

I know I could possibly put multiple teapots into the same VBO with all the vertex data offset, but that would double the vertex-data and make it less flexible, seems like a bad solution to me.

So what is the right solution to drawing many of the same VBO at different transformations with a single or as few draw calls as possible?


texts: Instantiating prefabs by dragging in scene not working

texts:
So I have this problem where I try to instantiate prefabs as in this video for example. I can take instantiate one prefab to the scene, but if I try to instantiate a second one to the scene (whether it's with the same prefab or a different one), instead of creating an instance of the second prefab, it brings the first instance I had created to my mouse and I'm in position to move it by dragging it around.

The only work around I have for this so far is to drop into the hierarchy instead of the scene (which works fine), but I have to carefully avoid the scene while dragging and dropping, otherwise the above-described issue happens instantly.

Am I doing something wrong, or is this a bug of some kind?

EDIT : I managed to reproduce the error in a consistent manner. I don't know why it happens, but it does every time. It doesn't involve code and it is very simple to reproduce (at least for me, perhaps not for you if you're not doing the wrong thing that I do...).

I created a new project. I created a cube and a sphere. I turned them both into prefabs and deleted the original instances (they have the .prefab extension in my folder, so I am sure). I drag-dropped the cube in, works fine. I drag the sphere in, and it appears as a cube which I have to position (by releasing the click), and my initial prefab instance of the cube is gone.


texts: Is it safe to cast my 2D points to 3D points for a library which only takes Vector3s?

texts:
I need to cast a ray in 2D space for bullet collision detection, but the Ray.Intersects method requires a BoundingBox which uses vector3's not vector2's. My question is should I just ignore the Z value and pretend it's a vector2? Raycasting is already slow enough so I think having calculations done in an unnecessary 3rd deminsion should be eliminated even if the value is just 0, but I don't know.

So should I implement my own raycasting system maybe using Bresenham's line algorithm which is for 2 dimensions or should I go the cheap way and make a bounding box a bounding plane?


texts:
I found good tutorial on how to do mouse look for 2D game here: http://www.atburrow.com/2010/03/08/objects-facing-the-cursor/

My code looks like this:

w = (double)mouse_x - (double)pos_x;
h = (double)mouse_y - (double)pos_y;
d = sqrt(w * w + h * h);
theta = asin(w / d) * 2 * ALLEGRO_PI;

Problem is i cant figure out how to translate it for Allegro 5.
Tried this on many different ways and its working, but not correctly. First im not using OpenGL (its a simple project for 2D controlls) so what i did after this is:

al_draw_rotated_bitmap(playerLook, imWidth / 2, imHeight / 2, pos_x, pos_y, theta, 0);

Object is rotating a bit faster than it should be. So this is blocking me from further exploration. I also found good tutorial for blitz from guy that im subscribed: http://www.youtube.com/watch?v=zFAaILFJtCY

Just went out, but still there is something that confuse me when using Allegro fixed math and i cant learn it without good example.Do anyone know how to set this code right in allegro5 ? How to do 360 degree rotation using mouse in allegro5?


texts:
I am looking for places on the web to share my game.

I'm relatively new to game development. Not looking to 'promote' my game or sell it. Just want to share it in places where there is a possibility people will download and play it.

Are there any sites that are meant to share indie games? And in general any site where I can post a download to my game will be great.

Thanks


texts: Unity shaders and textures not transferring properly when using github

texts: We have the game code on github, when we try to clone onto different machines the shaders and textures do not transfer over properly. Has anyone else noticed this problem using gitHub?


texts: Complex Machine handling through VR controller

texts:
I have a very Complex Machine which I want to operate through my VR controller (HTC Vive Controller). As you can see its short animated video here. I want to pull the machine cover through VR controller which is easy to do but i want to scale and pull some of the other related objects of the machine too (like spring, piston etc, you can see in the video) as i pull its cover through VR controller.

The problem is that i am unable to do this using Joints and Animation play. I almost tried anything but nothing worked for me. My question how can i imitate animation all work through code or through physics. Like if i pull an object the rest related object should be stretched like chain. And piston should open or closed according to force.


texts:
I'm making a game like angry birds with LibGDX and box2d in which I want to drag a ball (instead of the bird) back before releasing it.

I deploy with testPoint function: when I touch down the screen, I check if the point is within the body of the ball or not but testPoint function never works exactly. Here's what I'm trying thanks so much:

public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    for(Fixture fixture:bird.getBody().getFixtureList()) {
        if(fixture.testPoint(screenX/100, (mapHeight-screenY)/100)) { //100 is scaled parameter
             draggedBird = true;
             return true;
         }
    }
    return false;
}


texts: Error with Quaternion.FromToRotation in Unity?

texts:
I get multiple errors whenever I run this code:

transform.rotation = Quaternion.FromToRotation (Vector3(0, 0, 0), Vector3(0, 0, 270));

Can you suggest a fix for this code?

Errors:

Expression denotes a type', where avariable', value' ormethod group' was expected
The best overloaded method match for `UnityEngine.Quaternion.FromToRotation(UnityEngine.Vector3, UnityEngine.Vector3)' has some invalid arguments
Argument #1' cannot convertobject' expression to type `UnityEngine.Vector3'


texts:
I am making a final boss fight area and it has multiple platforms that go higher and higher up, I need the boss to follow the player up and down. I have a script that has the boss the follow the player but I need to restrict it to the y axis only

Here is the script I have:

 public class FollowPlayerY : MonoBehaviour {

     public Vector3 playerPos;
     public float followSpeed;
     public Transform player;

     void Update () {
         playerPos = player.transform.position;
         float step = followSpeed * Time.deltaTime;

         transform.position = Vector3.MoveTowards (transform.position, playerPos, step);
     }
 }


texts: How can I determine "exact moment" of collision with ray casting?

texts:
I'm currently brainstorming how the physics for my game engine is going to be handled.
It's top down and I'm thinking of using ray casting for collision detection.
I've reached two potential problems (I want collisions to be pretty precise but of course not to operation heavy).

I'd like to use 2 different polygons for each object. One box to check collisions with first and then a polygon for precise checking. Is this wise to do when also checking collisions with ray casting? Or should I go for the more precise polygon right away?
Say I'm going to move an object 10 units X-wise and another object 10 units Y-wise how do I know "when" along this movement they collided so that if they collided after moving 5 units I could handle events at that point?
(One might bounce and move back the same 5 units traveled in the same execution of my update or get instantly destroyed in which case it wouldn't collide with a third object it otherwise would have collided with)

This could be a bit overkill but I still wanna know how one could go about handling this.


texts: Normal Mapping for 3D-Like Lighting in 2D Games

texts:
I recently saw this video about a game engine that uses normal mapping to generate lighting and shadows for amazing, 3d-like lighting effects.  (Like the three barrels below on the right side, they all use a single image, with lighting applied.)

After googling for some time and reading the articles, I'm not sure I understand exactly how this effect works -- that is, how I would implement this. It seems like you need your original image, plus a grey-scale "normal map", where the colour represents depth -- the "farthest away" pixels are black, and the "closest to the viewers" are white.

But even if I have this, how does this information combine with lighting to create that 3D effect?

Also, how would I use this information to create casted shadows (see bottom-left barrels in the picture below)?


texts: Best way to add and remove quads in a VBO?

texts:
What's the best way to handle adding and removing 2D sprites (quads) in a VBO?

I am working on a mobile board game and sometimes game pieces (represented by quads graphically) need to be added to or removed from the screen. Currently, I store all of my quad vertices in an array. When I need to add new quads to the screen, I append this list with the new vertices. However, removing quads is more cumbersome. I track the positions of each quad in the VBO array with a dictionary, and when I comes time to remove it, I remove that block of four vertices from the array. I then have to update the values stored inside the dictionary since the VBO array has been resized.

I am not satisfied with this solution, and I feel like there could be a better way to achieve what I want. I couldn't find any related questions about storing 2D sprites which need to be added or removed during runtime like this. Since the game is really simple graphically, I am thinking it may be easiest to make a draw call per sprite. I can't use instancing since I am restricted to OpenGL ES 2.


texts: How common are Rete algorithms in game development?

texts:
I was looking through some game AI and general AI texts and a couple of them touched on using the Rete algorithm for rule systems. Is this commonly used?
I'm having trouble justifying the extra effort to create a complex Rete decision tree versions a simpler straightforward one.

Is this a worthwhile thing to implement for when my application (or future applications) grow in scale?


texts: Game Engine Class and Subsystem Architecture

texts:
I have a quick question for those who have experience coding their game engine and such. I was wondering what a better approach would be when designing my own game engine. Right now I plan on having different "subsystems" for example a event system and a graphics system (I plan on including more later on and they may or may not contain their own hierarchy). My question is should my engine class inherit these systems or should I make each system a member of the engine class or is there another proper way of structuring my engine? Whatever approach I wish to choose, I want it to be modular yet efficient.

tl;dr: What is the proper architecture for a game engine with subsystems in C++?


texts: Tilemaps not showing up on Android build

texts: I'm having trouble developing a 2d game for Android. I use tilesmaps for the ground and a few other things. On the editor, everything works fine and dandy. But, when I deploy to a phone(Build and Run), the tiles aren't there. It's like they never existed. I go back to the editor and they're there. I play the game directly from the editor and they're there. I even play the game while running unity remote, on the test phone, and the tiles are there. No idea what's going on. This only happens with tilemaps. Everything that isn't a tilemap is visible.  I'm running Unity 2019.3.0f6


texts: I'm starting with GLSL shader programming and have been looking into RenderMonkey. Sadly, AMD no longer supports it. Why? Is there a successor to it?


texts: Why do my velocity estimates have such a large margin of error

texts:
I am writing a script in unity that applies a force to the object to advance it a set distance in an environment without friction or drag, producing a cosine force curve.

However, as the target approaches the destination, the force to apply is less than the value specified by the curve as the time unit is too large and will cause the object to reverse direction.

To resolve this, I estimate what the speed will be after applying this frames force and, if that reverses the direction, we take a proportion of the force.

It is working well around 4 times out of 5, but every so often it will not detect the reverse in direction and will apply the force for an extra frame or 2, causing the object to back up.

Closer investigation revealed that basically the problem stems from my estimate being significantly (some times up to 0.05) different from the velocity the next frame. I compute it as follows:

Vector3 currentVelocity = ship.rigidbody.velocity;
Vector3 direction = ship.transform.right;

// this is the value I use for the "actual" speed
float velocityAlongDir = Vector3.Dot(currentVelocity, direction);

// this is my estimate
float estimatedVelocity = velocityAlongDir + (applyingForce * lDeltaTime);

Where the applyingForce is applied thus:

ship.rigidbody.AddForce((applyingForce * ship.rigidbody.mass) * transform.right);

Some sample data:

Predicted velocity: 0.3048308
Actual velocity: 0.2880591
Predicted velocity: 0.2068605
Actual velocity: 0.1900333
Predicted velocity: 0.09798826
Actual velocity: 0.1900333
Predicted velocity: 0.1082982
Actual velocity: -0.007007703

As you can see by the last entry, the predicted value doesn't change sing, but the real value does. Trying to work around this using does it go below a small value get different problems where the current velocity is too small etc.

Any idea why my calculation for next frame velocity seems so wrong and is there anything I can do about it?

Update

As pointed out in the comments, I needed to apply the force in the FixedUpdate and calculate my next frames velocity using Time.fixedDeltaTime. However, the following can happen, presumably in adverse frame conditions:

Predicted Velocity: 15.67547
Actual Velocity: 15.67547
Predicted Velocity: 17.54726
Actual Velocity: 15.67547 // note the same as the previous update, there has been no physics step!
Predicted Velocity: 17.51759 // estimate is subtly different, because my own timer has advanced

I fixed this by using fixedTime as opposed to fixedDeltaTime. However, then when I do a double update I am wrong for that frame, its like the physics step is trying to make up for the lost time:

// all going well...
Predicted Velocity: 52.25977
Actual Velocity: 52.25977
Predicted Velocity: 52.40138

// the estimate is wrong, we are moving at the same speed => no physics update
Actual Velocity: 52.25977
// we predict the same velocity for next frame
Predicted Velocity: 52.40138
// but we are wrong, like it is trying to catch up for lost time
Actual Velocity: 52.543

// then after that point we are precisely right
Predicted Velocity: 52.66479
Actual Velocity: 52.66479

This wouldn't be an issue except in the edge case where we do this double step precisely at the point we need to detect when the speed will change and apply the ratio. Since the physics step seems to play catch up, I miss the fact we changed speed.


texts:
in OpenGL I want to render a cone in parts like on the image. My problem is to calculate the arc of each block in 3D space.

has someone an idea how to handle this?


texts: 2D physics library that supports curved surfaces and inverse or boolean shapes?

texts:
I've been using box2D for a few months, but I now badly need a physics library which can use boolean shapes (ie; cutting a circle out of a square) and/or curved surfaces. Does anyone have any suggestions?

Edit:
Language is c++


texts: Proper names and wordings for Real/Fake fullscreen video modes

texts:
I have an option in my game which allows Player to choose between video modes:

Fullscreen Fake
Fullscreen Real
Windowed

First and second corresponds to SDL_WINDOW_FULLSCREEN_DESKTOP and SDL_WINDOW_FULLSCREEN in the SDL library.

While their meanings whould be clear for GameDev people, for average Player, I think, it will be not so obvious. I never saw any examples of that kind of Video Settings. Other games often provide just a choice between the two: Fullscreen / Windowed.

What names and explanations I should provide, so it will not be confusing for a common user ?
Are there any examples of games which have similar options ?


texts: Are unit/building types generally stored as full objects or imported properties?

texts:
I'm trying to write a generic turn-based strategy game, with a few unit types, building types, etc. Since this is something I've never done before, and its not a very easily searchable subject, I'm asking here.

[See title question] I thought of two ways to implement unit/building types.

The first is the most obvious, with each unit being a complete object in-and-of itself. This means that it would have all stats, abilities, etc. contained in the object. A factory method would create these objects when units are trained. The main drawback is that each unit of the same type would also have duplicate information, like movement points, that are constant among all units of that type. Of course, in the event of stat upgrades, these could be changed directly, so they would no longer be duplicate.

The second method of doing this, is storing basic unit info, such as base health, movement points, etc. in a Unit_Types class. The unit object could then be done away with completely in favor of a list of unit types (whose important stats are kept in Unit_Types). Alternatively, the unit object could hold unique info, such as stat upgrades. This seems better because its less data being used, as well as making unit type upgrades simpler. The unit would just change its type field to its previous type plus 1. But this might be much harder once I actually begin writing it and encountering issues I haven't thought of yet.

Is there a standard practice? It seems like one of those things where one approach is way better than the other in 90% of situations.


texts: Avoiding lag when playing sound for first time using Cue.Play

texts:
In my code I'm using SoundBank.GetCue("cuename") and Cue.Play() to play my sounds.

On the xbox whenever I first play a cue I get lag of about about one second.
How can I avoid this?

I'm thinking I probably have to do something like call GetCue (without playing it) for every Cue I'm going to use, however I don't have a central place where I list all cues I'll want to play, so is there an easy way to do that?

Update: It seems calling GetCue for all sounds i want to play doesn't work. I'm still getting stuttering in various places in my game when i call GetCue....Play.


texts: translating canvas for rotating sprites that shoot

texts:
I am trying to align bullets to my different sprites guns (top down 2D for android). Right now Im using this method to draw my bullets:

public void draw(Canvas canvas){
    update();
    canvas.save();
    canvas.rotate(angle, x + width / 2, y + height / 2);
    canvas.translate(translaterX, translaterY);
    canvas.drawBitmap(bitmap, x, y, null);
    canvas.restore();
}

The problem here is the translater, Im always having to add or substract from it to make the bullets spawn from my gun when my sprites rotate and I cant figure it out, is there any standard value for this, like translaterX = bitmap.getwidth()/2? I dont really understand how the translater works and I feel like Ive tried everything, what am I missing? For the examples sake lets say that my gun is always in the middle of the bitmap.

Or is there even another way to do this that is simpler?


texts: Glenn Fiedler's fixed timestep with fake threads

texts:
I've implemented Glenn Fiedler's Fix Your Timestep! quite a few times in single-threaded games.

Now I'm facing a different situation: I'm trying to do this in JavaScript. I know JS is single-threaded, but I plan on using requestAnimationFrame for the rendering part.

This leaves me with two independent fake threads:  simulation and rendering. Timing in these threads is independent too: dt for simulation and render is not the same.

If I'm not mistaken, simulation should be up to Fiedler's while loop end. After the while loop, accumulator < dt so I'm left with some unspent time (accumulator) in the simulation thread.

The problem comes in the draw/interpolation phase:

const double alpha = accumulator / dt;
State state = currentState*alpha + previousState * ( 1.0 - alpha );
render( state );

In my render callback, I have the current timestamp to which I can subtract the last-simulated-in-physics-timestamp to have a dt for the current frame.

Should I just forget about this dt and draw using the physics thread's accumulator? It seems weird, since, well, I want to interpolate for the unspent time between simulation and render too, right?

Of course, I want simulation and rendering to be completely independent, but I can't get around the fact that in Glenn's implementation the renderer produces time and the simulation consumes it in discrete dt sized chunks.

A similar question was asked in Semi Fixed-timestep ported to javascript but the question doesn't really get to the point, and answers there point to removing physics from the render thread (which is what I'm trying to do) or just keeping physics in the render callback too (which is what I'm trying to avoid.)


texts:
Several years ago, I made a fast collision detection for 2D, it was just checking a bullets front-pixel's color to check if it were to hit something. Let's say the target rgb color is (124,200,255) then it just checks for that color. After the collision detection, it paints the target with appropriate picture. So, collision detection is made in background without drawing but then painted and drawn.

How can I do this in 3D? Because, a vertex does not just exist as a 2D picture's pixel. I looked at some java3D and other programs and understood that 3D world is made of objects. Not just pictures. Is there a program that truly fills the world with vertices? But it could be needing terabytes of ram even more.

Do you know an easy way to interpolate the color of a vertex in java3D or similar program?

Note: for a rgb color-identifier, I can make 255*255*255 different 2D objects in background.


texts: why collision not detection not happened in Two Sphere

texts:
I start practice 3d collision detection of sphere in OpenGl containing two sphere one sphere hit using cannon gun but collision not detect when it hit and when i debug code collision statement triger when sphere is too far of each other here is sphere One code

    glPushMatrix();
    glTranslatef(400, 50, -400);
    drawBomb();
    glPopMatrix();

Connon gun code is here which control by keyboard handler

glPushMatrix();
    glTranslatef(600, 0, -400);
    glRotatef(-longFire, 1, 0, 0);
    glRotatef(-longFireChaw, 0, 1, 0);

    //glTranslatef(0, 0, -25);
    drawFireHolder();
    //printf_s("Long fire is %d", longFire);

    glPopMatrix();

second sphere code is here which hit by mouse handler

glPushMatrix();
 // bombX is global variable of value 600
 // bombY and bombZ is global variable of value 0
    glTranslatef(bombX, bombY, -400);
    //glRotatef(-longFire, xRotate, yRotate, zRotate);
    glRotatef(-longFire, 1, 0, 0);
    glRotatef(-longFireChaw, 0, 1, 0);
    //glRotatef(longFire, 0, 1, 0);
    glTranslatef(0, 0, bombZ);
    glTranslatef(0, 0, 25);
    drawBomb();
    glPopMatrix();

Timer and Shphere collsion detection code s here

dx = 400 - bombX;  // 400 for sphere one x and bombX for sphere two
        dy = 50-bombY;  //50 for sphere one y and bombY for sphere two
        dz = -400 -(-400);// 50 for sphere one z and bombz for sphere two

        float distance = sqrt(dx*dx + dy*dy + dz*dz);

        if (distance <=6+6) // 6 is radius of first and second sphere
        {
            printf("Collision Occur");
        }

        bombX-=1;

        bombY =0.3+bombY*sin((longFire*3.1424543567) / 180);
        bombZ++;
        //printf("Y IS %f",bombY);

Keyboard Handler  code is here

if (key == 't' || key == 'T')
    {
        xRotate = 1, yRotate = 0, zRotate = 0;
        longFire += 5;
        handlerMove();
    }
    if (key == 'e' || key == 'E')
    {
        xRotate = 1, yRotate = 0, zRotate = 0;
        longFire -= 5;
        handlerMove();
    }
    if (key == 'r' || key == 'R')
    {
        xRotate = 0, yRotate = 1, zRotate = 0;
        longFireChaw += 5;
        handlerMove();
    }
    if (key == 'w' || key == 'W')
    {
        xRotate = 0, yRotate = 1, zRotate = 0;
        longFireChaw -= 5;
        handlerMove();
    }


texts:
I know the following line of code has the effect of moving 3 units per milliseconds independent of framerate, but my sucky mathematical intuition is unable to understand WHY this works

translation *= 3 * (float)gameTime.ElapsedGameTime.TotalMilliSeconds

Could someone please explain why this works?

Are there any other common techniques / variations of framerate independent implementations operations like this?


texts:
A ray is shot from the camera eye to the camera screen at point (i,j) how do I get the coordinates of that point in 3D world coordinates?

The best I could find online is for point S
S = Q + au + bv

Q being the camera direction and u,v are the UV plane of the camera.. not sure how to find their coordinate and if I need them in world coordinates or something else.

If you could clarify this issue, it would be great.

Thanks.


texts: How to load and display an image in OpenGL ES 3.0 using C++

texts:
I'm trying to make a simple app on Android Studio using the NDK, JNI to call C++ code that load and display an image. I have managed to create the surface and draw a simple Triangle already.

Now, I'm looking for a way to load and display an image in OpenGL ES 3.0 using C++. I have done the search around but all of them is either missing some important function or written in Java. It would be great if someone could guide me with a simple example, thanks in advanced :) .


texts: Loading images using their bytes in Unity

texts:
If you import an image into the Unity inspector, the image will be encoded in Unity's own format. Usually the resulting image is much bigger than the original (from 100kb to 1MB). Of course, you can do stuff like compress and change the texture max size to reduce the image's size, but at the end it will almost always be bigger.

I noticed that you can create a Texture2D if you got the necessary bytes. As an experiment, I took my 100kb image and imported it to Unity as a .bytes file. Then I read the bytes and created my Texture2D:

    Texture2D texture = new Texture2D(100, 100);
    texture.LoadImage(myTextAsset.bytes);
    Sprite sprite = Sprite.Create(texture, new Rect(0,0,350, 288));

And it works. And it is smaller (100kb).

So my question is: what's the difference between Unity's builtin way of handling images and my way of loading them using their bytes? Because I'm saving tons of memory with this method. I imagine that it is a bit slower. But if that's the only difference, I can live with that.


texts: Why do I get a jitter/stutter when moving and following a target?

texts:
I am using the script below to move a transform to quickly follow a target (the player), and come to a stop close to the player.
When I move the player around, the transform is following the player, keeping the 1.5 distance.
To ensure the transform can keep up with the player, I set the moveSpeed to 5, But when I do that, the transform jitters/stutters when moving.
If I set the moveSpeed to 1 for example, the transform will move smoothly but will not keep up with the player - the player has to stop moving and wait for it to catch up. But increasing the speed makes the stutter return.
Why is this stutter happening, and how can I make the movement smooth?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;

public class Follow : MonoBehaviour
{
    public Transform targetToFollow;
    public Text text;
    public Text text1;
    public float lookAtRotationSpeed;
    public float moveSpeed;

    private float minMoveSpeed = 0f;
    private Vector3 originPos;

    // Start is called before the first frame update
    void Start()
    {
        originPos = targetToFollow.position;
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 lTargetDir = targetToFollow.position - transform.position;
        lTargetDir.y = 0.0f;
        transform.rotation = Quaternion.RotateTowards(transform.rotation,
            Quaternion.LookRotation(lTargetDir), Time.time * lookAtRotationSpeed);

        var distance = Vector3.Distance(transform.position, targetToFollow.position);

        text.text = "Transform Distance From Target " + distance.ToString();

        float ms = moveSpeed;

        if (distance > 5f)
        {
            ms = moveSpeed + 0.5f;
        }
        else if (distance < 1.5f)
        {
            ms = Mathf.Max(minMoveSpeed, ms - 0.3f);
        }
        else
        {
            //transform.position = Vector3.MoveTowards(transform.position, targetToFollow.position, Time.deltaTime * ms);
        }

        if (distance < 0.5f && originPos == targetToFollow.position)
        {
            ms = 0f;
        }

        if (distance > 1.5f)
            transform.position = Vector3.MoveTowards(transform.position, targetToFollow.position, Time.deltaTime * ms);

        originPos = targetToFollow.position;
    }
}


texts:
I am creating a framebuffer in LWJGL using:
        framebuffer = glGenFramebuffers();
        texture = glGenTextures();
        glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
        glBindTexture(GL_TEXTURE_2D, texture);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, texture, 0);
        glDrawBuffers(GL_COLOR_ATTACHMENT0);

But glCheckFramebufferStatus tells me that the attachment is incomplete. What am I doing wrong? I checked several websites and I don't seem to be missing anything...?


texts: I have an OpenGL code that currently draws several spheres at different locations. I generate the vertex buffer data (and normal data) myself. However, to simplify the code and increase efficiency, I am now trying to use gluSphere instead. The problem is that if I want to draw several spheres at different locations, I think I will need several different model matrices, and thus several different MVP matrices (because I am using OpenGL 4.3 and there is no glTranslate). But if I want to rotate the whole scene, I will need to rotate all of these model matrices, instead of just one as before. Is there a workaround for this? Is there a simple way to draw several different things with gluQuadrics objects at different locations?


texts: Timed Events in a Unity WebGL game with a PHP / MySQL Server

texts:
I want to make an online WebGL game with Unity with button based interaction.

So far I have my login and registration system, with some tables in MySQL to deal with that kind of stuff.

Next I need to deal with timed events.

In the game, you will start a mission just by pressing a button then you will wait a bit, like ten minutes.

How can I implement this wait?

Should I write a waiting routine in PHP, or use MySQL scheduled events? If using events, how many scheduled events can MySQL handle? Or should I use another server-side solution for that?


texts: How do I snap the Unity camera to a 2D, tile-based map?

texts:
I have a 2D, tile-based map. I want to be able to control the number of visible tiles on the screen vertically and horizontally, regardless of resolution. I want the player to be able to move the camera one tile width at a time until it hits the edge.

I do not understand how to manipulate the Unity camera in order to accomplish this. I have read the documentation, and Googled, but there is just something that is not clicking for me.

So, let's say I have a 100x100 map. A 32x24 portion of the map is shown at a resolution of 1024x768, each tile has a size of 1x1 Unity unit. The bottom-left of the visible area of the map starts at the bottom-left of the map (0, 0). The player then clicks the right arrow key and the map moves one tile to the right (1, 0).

How do I accomplish this, given that I am using the latest version of Unity in 2D mode?


texts: Marching cubes over an octree dual - how?

texts:
In Dual Marching Cubes the dual of an octree is tessellated via the standard marching cubes method. But the classical marching cubes algorithm operates only on cubes with eight vertices (it uses signs at eight corners of the cube to construct a bitmask and select the proper configuration of triangles), while cells of octree duals can actually have more than eight edges.

For example, in the following picture a quadtree dual is shown, where the lower left cell has 8 links to neighboring dual vertices:

although the marching squares algorithm needs only 4 corner vertices (4-bit masks - 16 cases) for contouring the grid.

And how to build the surface in this case? Which edges to select to form a bitmask used in the marching cubes/squares algorithm as the algorithm needs only 8/4 points as input?