texts: NavMesh.SamplePosition() fails after rebaking NavMesh?

texts:
So today I was refurbishing a scene when this happened. After baking a new Navmesh the SamplePosition() returned only infinity. I tried a lot of things out but eventually went back to an older version of my project. Sooner or later I will have to bake a new Navmesh though, so I'd really like to know what happened there.

Here is the part of the code that appears to cause trouble:

Vector3 randomDirection = Random.insideUnitSphere * roamRadius;
NavMeshHit hit;
NavMesh.SamplePosition(randomDirection, out hit, roamRadius, 1);
direction = hit.position;

And of course this, since it tries  to look into infinity I suppose:

transform.LookAt(transform.position - direction, Vector3.up);

Again, this code works fine. Only after baking a Navmesh this fails horribly.


texts:
In my pursuit to write code that matches todays OpenGL standards I have found that I am completely clueless about interleaving arrays. I've tried and debugged just about everywhere I can think of but I can't get my model to render using interleaved arrays (It worked when it was configuered to use multiple arrays) Now I know that all the data is properly being parsed from an obj file and information is being copied properly copied into the Vertex object array, but I still can't seem to get anything to render. Below is the code for initializing a model and drawing it (along with the Vertex struct for reference.)

Vertex:

struct Vertex {
    glm::vec3 position;
    glm::vec3 normal;
    glm::vec2 uv;
    glm::vec3 tangent;
    glm::vec3 bitangent;
};

Model Constructor:

Model::Model(const char* filename) {
    bool result = loadObj(filename, vertices, indices);

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

    glGenBuffers(1, &vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW);

    glGenBuffers(1, &elementbuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned short), &indices[0], GL_STATIC_DRAW);
}

Draw Model:

Model::Draw(ICamera camera) {
    GLuint matrixID = glGetUniformLocation(programID, "mvp");
    GLuint positionID = glGetAttribLocation(programID, "position_modelspace");
    GLuint uvID = glGetAttribLocation(programID, "uv");
    GLuint normalID = glGetAttribLocation(programID, "normal_modelspace");
    GLuint tangentID = glGetAttribLocation(programID, "tangent_modelspace");
    GLuint bitangentID = glGetAttribLocation(programID, "bitangent_modelspace");

    glm::mat4 projection = camera->GetProjectionMatrix();
    glm::mat4 view = camera->GetViewMatrix();
    glm::mat4 model = glm::mat4(1.0f);
    glm::mat4 mvp = projection * view * model;

    glUniformMatrix4fv(matrixID, 1, GL_FALSE, &mvp[0][0]);

    glBindVertexArray(vertexArrayID);

    glEnableVertexAttribArray(positionID);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glVertexAttribPointer(positionID, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), &vertices[0].position);

    glEnableVertexAttribArray(uvID);
    glVertexAttribPointer(uvID, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), &vertices[0].uv);

    glEnableVertexAttribArray(normalID);
    glVertexAttribPointer(normalID, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), &vertices[0].normal);

    glEnableVertexAttribArray(tangentID);
    glVertexAttribPointer(tangentID, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), &vertices[0].tangent);

    glEnableVertexAttribArray(bitangentID);
    glVertexAttribPointer(bitangentID, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), &vertices[0].bitangent);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
    glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_SHORT, (void*)0);

    glDisableVertexAttribArray(positionID);
    glDisableVertexAttribArray(uvID);
    glDisableVertexAttribArray(normalID);
    glDisableVertexAttribArray(tangentID);
    glDisableVertexAttribArray(bitangentID);
}


texts: Is there a sound library for C to generate sound samples from code?

texts:
I'm working on an engine for a retro-style game in C.  I'm looking for a sound library that would produce chip sounds from code...I want to make my own simple chiptune tracker for the engine to create music.  Does such a thing exist?

I'd also be interested in a library to use .nsf files in my project.

I'm using Linux for development.


texts:
I am creating a very simple script for my stamina bar to go down when I press M, but when I am not pressing M, for the bar to go back up slowly back to 100.The bar goes down fine when I press M, however, while the bar does go down, it refuses to go back up.

Attached is the code:

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

public class StaminaBar : MonoBehaviour {
    public Scrollbar StaminaGUIBar;
    public float Stamina;

    void Start()
    {
        Stamina = 100;
    }

    void Update()
    {
        Debug.Log(Stamina);
        if (Input.GetKey(KeyCode.M))
        {
            Stamina -= 5;
            StaminaGUIBar.size = Stamina /100f;
            Refuel();
        }
    }

    public void Refuel()
    {
        while (Stamina < 100)
        {
            Stamina += 5f;
            StaminaGUIBar.size = Stamina * 100f;

            if (Stamina >= 100)
            {
                break;
            }
        }
    }
}

Any Ideas


texts: Can we merge multiple FBX files, using Maya, and export as a single FBX file?

texts:
I have a humanoid model which is made up of four FBX files; one is for the human, one is for the T-shirt, one is for the pants and one is for the hair. I want to merge them into one FBX, because the manner in which I am using it requires using a single FBX file to represent the character.

Can we merge four FBX files into one, using Maya, and export as a single FBX file?


texts: I have it when the player clicks the mouse they can move the peice aoround the board. I am trying to have the chess pieces snap to a grid after the mouse has been released. Is there any way to round numbers so that I can round the X and Y coordinates so that it will snap to the grid?


texts: Path finding: avoid being surrounded by enemies

texts:
I'm building a bot that plays a simplified version of Pac-Man. The bot does a pretty good job, but sometimes it chooses a path where it ends up surrounded by enemies.

Here is an example:

XXXXXXXXXXXXXXXX         XXXXXXXXXXXXXXXX         Legend:
xxxxO1   E1              xxxxPE1
XXXX XXXXXXXXXXX    ---> XXXX XXXXXXXXXXX         O Objective
E2   P        O2            E2 E3      O2         P Player
XXXXXXXX XXXXXXX         XXXXXXXX XXXXXXX         E Enemy
XXXXXXXX XXXXXXX         XXXXXXXX XXXXXXX         X Wall
XXXXXXXXE3XXXXXX         XXXXXXXX XXXXXXX         x Wall

In this situation, my bot is at the point of no return. It will choose to move
to and pick up objective one (O1), as it is the closest objective in sight,
and in theory is still a safe path. However, in doing so, enemies will surround
him and he will die. (Map on the right).

I'm trying to come up with ideas on how to make my bot avoid that path, and go for a safer one. The bot should determine if completing the current path (to O1) is a good idea or not, in advance, and make a decision.

How would I go about this? I'm using a simple A* for path finding over a grid.


texts: Simple 2D Platformer Collision Detection?

texts:
I'm relatively new to programming and I am attempting to write a 2d platformer in C++ using the SFML library.

The structure of my code is that I have a Stage class which contains a vector of sf::RectangleShape 's (the stage platforms).  I have a method in the stage class to check for the collision between a player's hitbox and the stage as follows:

bool Stage::checkForStageCollisions(sf::RectangleShape player)
{
    for (unsigned int i = 0; i < collidableObjects.size(); i++)
    {
        if (player.getGlobalBounds().intersects(collidableObjects[i].getGlobalBounds()))
        {
            return true;
        }
    }
    return false;
}

Then in my player class I can perform logic based on whether there was a collision.  The problem is that I need to know which object the player collided with to move them to the appropriate spot.  Am i going about this the wrong way?  Any help would be appreciated.  Thank you!


texts:
I have 2 related questions, please.

I am using a wiimote on a robotics project and I need to convert X and Y values into new bounded values.

So, give the following accelerometer data:

[X]: 2.17925555556
[Y]: -6.53776666667
[Z]: -0.754357692308

[1] I need to convert/map X to between -0.22 and 0.22, Y to -2.84 and 2.84.

To accomplish the conversion/mapping, I'm told I need the range of X and Y accelerometer data.

[2] Does anyone know what the range of accelerometer data is on a wiimote?


texts: How do I generalise Bresenham's line algorithm to floating-point endpoints?

texts:
I'm trying to combine two things. I'm writing a game and I need to determine the grid squares lying on a line with the floating-point endpoints.

Moreover I need it to include all the grid squares it touches (i.e. not just Bresenham's line but the blue one):

Can someone offer me any insight on how to do it? The obvious solution is to use naive line algorithm, but is there something more optimized (faster)?


texts: How to add the sound effect of a ball rolling, based on his velocity?

texts:
I have a ball which roll (like all ball does :) ) ...

My ball can roll on different type of surfaces (2 or 3) and at different velocity.

I don't know how to approach to reproduce in my game the sound effect.

I can assume to do :

Get an Sfx of a rolling ball
Run in loop if my ball is moving

then ?

Well.. i need some help.

Thanks


texts:
I'm developing a game in XNA(C#) and I wonder what are the best practices for having different types of pads.
For example I have 2 types of pads:

Pad that just moves left (decreasing X coordinate)
Pad moves left and moves up and down (cos function on Y coordinate)

Later I would like to implement more pads. I know I could check type in Update method and do a proper method for updating but I think it could be done better.
I have the Pads class:

class Pads
    static list of pads;
    public void draw();
    public static void drawAll(); //Iterate through list and draw each item
    public void update();
    public static void updateAll(); //Iterate through list and update each item

Should I create another class for example cosPad which would extend Pads?

I really don't have idea how to make everything logical.


texts: Camera position and angle different when running inside Unity and when running on Android

texts:
On Windows, running Unity 4.6.1p5, my simple game with only a cube, camera and light looks like this

but under Android (Gingerbread on a 5 inch Galaxy Player) the cube appears lower down, slightly different angle and smaller (relative to the screen size).  Sorry couldn't get a screenshot with my screenshot app...

Any ideas why please?


texts: UI background animation makes camera render beyond canvas, need fix?

texts:
I have a background animation for a menu where I have to make the background larger than the canvas and drag it over it. Even though I am using a panel the same size as the canvas as a mask, this causes the camera to render beyond the canvas. How can I get this same effect while only rendering what's on the canvas?

w/o mask (so you can see how big this background is):

w/ mask:

running in editor (looks good):

running build of the game from executable (camera shows more than it should but nothing was changed):

The camera bounds are fixed to the canvas, as it should be, if I remove the animated background, so that is the major cause.

(BTW, I know the gifs look crappy but the animation is seamless; I just had to crop the gifs to reduce file size.)

Also, you guys might not be able to see, but the tiling pattern has a slight white border where the tiles meet (the sprite it uses is only like 227x227 on "repeat"), does anybody know how to avoid that?

UPDATE @ 1:12am PST: upscaling turd texture to 256x256 eliminates white border, as suggested by trollingchar.


texts: I can't select my local package in Asset Store Tools

texts:
I made a local package and I'm trying to upload it to the AssetStore.
-My package is stored in the [root]/Packages folder.
-My Demo scene is stored in the [root]/Assets folder.
When I try to upload my package in the Asset Store Tools, I've an error if I select my sources in the Packages folder.
If i select my Demo scene folder instead, I have no error. But I don't want to upload only my Demo scene.
If I check 'include dependecies' it only add a json manifest file.
The error message is : The path selected must be inside the currently active project.
All answers about this error on google didn't helped me.
-Set the package as a Full project => I made a tool not a full project.
-The Project have to be in C:\ Hard drive => it is.
-The Project folder must have the package's name => it is. My project folder's name PropertyInterface as my asset.
I'm using Unity 2019.1.0f2.
It's the first time i try to upload my work in the Asset store. I'm pretty confused.
Thanks for your help.


texts:
I am having some trouble peforming an overlap test on a axis aligned bounding box.

Here is my code

public boolean overlapps(AABB other) {
    return false;
   }

}

I don't know how to implement this method.

Here is what I tried

public boolean overlapps(AABB other) {
    if(min.x <= other.max.x && max.x >= other.min.x) {
        if(min.y <= other.max.y && max.y >= other.min.y) {
            if(min.z <= other.max.z && max.z >= other.min.z) {
                return true;
            }
        }
    }
    return false;
}


texts:
In my game, the only chunks (4x4 areas of tiles) in memory are the ones that the player is in.  However, chunks need to have updates applied to them over time.  A (likely) well-known example would be MineCraft: even if the player isn't in a chunk, the wheat still needs to grow over time.

My current solution is to call a method and pass in the time since the chunk was active.. but what if the chunk depends on nearby chunks for information, i.e. vines spreading or similar?  Is there any reasonable solutions to this problem, or should I simply not depend on nearby chunks?


texts: Low FPS on Java drawing in BufferStrategy

texts:
I ran into a very strange problem while using BufferStrategy, I've tried searching for an answer but all I have found are non-relevant threads and discussions. So here is my query.

for (int i = 0; i < 10; i++){
    for (int x = 0; x < 10; x++){
        g.drawImage(enlImg(getImg(terrain, x), 4), i*40, x*40, null);
    }
}

(The parameter 'terrain' is a BufferedImage pre-loaded, which will be used to get a sub image from it.)

I'm trying to draw images to a Canvas, where 'g' is the buffer strategies, 'getDrawGraphics()' because that's how I am drawing to the BufferStrategy.
Anyway, straight to the point. I'm only getting ~3fps.

I know this is only drawing 100 images, but other games draw hundreds of thousands with no lag... Any ideas?

Is it maybe because of trying to enlarge, draw and get a sub image all at once, or is it because of my computer?

Extra

enlImg() code

public BufferedImage enlImg(BufferedImage image, int x){
    BufferedImage enlargedImage = new BufferedImage(image.getWidth() * x, image.getHeight() * x, image.getType());
    for (int a = 0; a < enlargedImage.getHeight(); a++) {
        for (int b = 0; b < enlargedImage.getWidth(); b++) {
            enlargedImage.setRGB(a, b, image.getRGB(a / x, b / x));
        }
    }
    return enlargedImage;
}

getImg() code

public BufferedImage getImg(BufferedImage img, int x){
    int y = 0;
    if (x >= 10){
        x=x-10;
        y++;
    }
    return img.getSubimage(x*10, y*10, 10, 10);
}

Computer Specifications (Windows):

AMD Athlon II X2 250 - 3.00GHz
 OS: 32bit
 4GB RAM,
 256GB HHD


texts: Is there a good alternative to a world state data structure?

texts:
How do you avoid one big data structure containing all the current world state ?

Let's pretend we're in a real-time strategy game, how would you code a skill that decrease mana of units around it ?

With a world state it would look like that :

class MySpell : ISkillWithoutTarget
{
  void Cast(Unit caster, World world)
  {
    foreach (Unit target in world.Units)
    {
      if (target.distanceWith(caster) <= N)
      {
        target.Mana -= X;
      }
    }
  }
}

So my question is : Does a good alternative to "world object" exist ? Or world object is the best way to deal with these kind of interactions ?

I'm not looking for a way to organize/optimize my big data structure, but how to avoid it.
I would prefer not using this architecture because almost every piece of code can touch every game object. I'm looking for decoupling to avoid ending with bug almost untraceable.


texts: How can I draw a ray from the camera in world space?

texts:
How can I construct a ray from the camera position to where it looks at, in world space. My previous method is draw a line by using two points. The first point is the camera position, and the other is calculated like camera position + lookdirection. And then I draw the line using GL_LINE_LOOP. But using 'lookdirection' of the camera is wrong, since the result is supposed to be a line that extends from the camera and extends forward.

My method in my program is use the camera position pos (0,10,0) and face a certain direction. Then the endpoint is calculated as (pos+direction) * 100.0f, and the starting point is pos. I used glDrawArrays(GL_LINE_LOOP,0,2) to draw the ray. But this produces the wrong result.

What's the correct way to draw a ray from the camera position to where it looks at in world space?


texts: What language was used to write Starcraft II?

texts: Total newbie question , but what language was used by blizzard to crate the Starcraft II game play? I've been playing it for the last couple of days , and I'm constantly astonished by the complexity and the performance of the game. Is it an in-house language , or do they use some flavor of a know language?


texts: Xcode workspace with Unity3D as a sub-project?

texts:
Let's say we're developing a 2D game with Cocos2d-iPhone and UIKit and CoreAnimation. But we're also considering leveraging the 3D capabilities of Unity 3D.

Is it possible that we add the Unity3D-generated Xcode project as a sub-project into the workspace and expose the 3D UI element as some kind of UIView subclass so that the native UIKit and CoreAnimation code could use them without the need to mess up with their underlying Unity3D implementation?


texts:
I have created a progress bar inside Unity for one of my energy systems. The bar progression works fine. Its just a plane pivoted on one of the faces so scaling it in x axis makes it progress further as seen in the image below
Now I am trying to implement a feature where when the bar stops progressing I would want to show a red bar indicating that it has stopped like in the image below

To implement this I would need to know somehow that the bar has stopped scaling and not progressing any further so that I can put the red bar at the position where it stops scaling.

But how do I know when the yellow progress bar stops progressing as its position stays the same throughout and its just scaling in the x direction.

I hope my question makes sense. Please help me out if it does. Thanks :)


texts: .dat files in 2D Games: Spritesheets vs Individual Images

texts:
I've been doing some research and I found that the game RollerCoaster Tycoon uses .dat files to store all the animations/images for each ride. Basically we're talking hundreds of images (per ride even), that are separate .bmp files inside this .dat file. This goes against the preaching of always using spritesheets... or maybe I misunderstand how the .dat file is being used? Using spritesheets are nice when the images and animation frames are all the same size, but when they vary so much (like varying ride sizes), it would be nice to use individual images. From my understanding, there's limits on image counts, and generally bad things when using tons of individual images... but ancient RoolerCoaster Tycoon seems to do just that with its .dat files.

What am I missing? What is the best way to store a massive amount of images?


texts:
I've been considering a segmented market for an MMO:

There is a different market for each in-game level (Level 1 players can only buy/sell items from the Level 1 market)
If a player levels up with items still in the market, they remain there, but can be removed if the player wishes.
The levelled market is the only way to trade items between players.

A few things I expect to happen:

The market won't be completely segmented.  If the Level 2 market's price for X is higher, then I'll just keep it to sell (and vice versa).
However, despite the above, there will still be X sold, as buying/selling makes it easier for the player to level up.
Therefore, there will be an inflation curve, where gold will be worth less and less on each level.
Inflation over time will occur faster at level 20 than at level 1.

Are my assumptions above correct?


texts: Why is my DX9 render target restricted to 512×512?

texts:
When I use a render target higher in resolution than 512×512, I receive an image with black borders, depending on how big this texture was.

Why is this? How can I fix it?

Here's how I create the texture and render target surface:

p_Device->CreateTexture(512, 512, 1, D3DUSAGE_RENDERTARGET,
    D3DFMT_A16B16G16R16, D3DPOOL_DEFAULT, &p_renderTexture, NULL);
p_mainRenderTexture->GetSurfaceLevel(0, &p_renderSurface);

And this is the main render-to-texture function:

void RenderSceneToTex(LPDIRECT3DDEVICE9 p_Device, D3DCOLOR clearColor,
        LPDIRECT3DSURFACE9 p_renderSurface, D3DXMATRIX matView,
        D3DXMATRIX matProjection, bool drawWater, bool drawTransparent,
        bool drawSkybox, LPSTR renderTech) {
    p_Device->SetTransform(D3DTS_VIEW, &matView);
    p_Device->SetTransform(D3DTS_VIEW, &matProjection);
    effect->SetMatrix("matView", &matView);
    effect->SetMatrix("matProjection", &matProjection);
    p_Device->SetRenderTarget(0, p_renderSurface);
    p_Device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
        ((clearColor != NULL)?clearColor:D3DCOLOR_XRGB(0, 0, 0)), 1.0f, 0);
    p_Device->BeginScene();
    DrawSceneObjects(p_Device, drawWater, drawTransparent,
        drawSkybox, renderTech);
    p_Device->EndScene();
    p_Device->SetRenderTarget(0, p_dx_mainRenderSurface);
}


texts: How to call a method from another c# script using invoke?

texts:
I want to call a method from another script in my script using Invoke(),but unable to run it.How can i achieve this ?

Following is my code -

void Start () {

    int randNum;
    randNum = Random.Range(0,2);

    Debug.Log("random number == " + randNum);

    if(randNum == 0)
        Invoke("PositionScript.instance.MAttack",5f);

    if(randNum == 1)
        Invoke("PositionScript.instance.SAttack",5f);

}


texts: Equal objects with independent variables in Game Maker?

texts:
Think of a situation with two distinct runners with different speeds. They will have to walk a circuit in a straight line with two obstacles (police).

Below is an illustration of the situation:

The problem I'm having is the following:

Assuming that runner two is faster than runner one, it is certain that he will reach the first hurdle earlier. Upon reaching this obstacle (detection event) he will be stopped for five seconds, long enough for the runner to reach him.

However the runner one will go through this obstacle without any loss of time, since the policeman is already taking care of the runner two.

Runner one still manages to get to the second obstacle with runner two still standing ... Then the problem arises because as they are equal objects the game assumes that the policeman is already taking care of the runner two, so the runner one passes straight through.

I would like to know how to do each object independently (detection event).

Sorry for the translation errors! Thanks!!!

Codes:

Movement (obj_control) =>

move_towards_point(obj_runner_01.x,obj_runner_01.y-1,obj_runner_01.manSpeed);
move_towards_point(obj_runner_02.x,obj_runner_02.y-1,obj_runner_02.manSpeed);

Collision detection (detector) =>

event_colision...

if obj_detector.detector_runner_01==false{
    randomize(); //in the original case, there is a chance the runner will not be stopped
    numRandom=irandom(99)+1;
    obj_detector.detector=true;
}

if manColision==false{
    if numRandom<=manAtrat*0{ //test value
        manColision=true;
    }else{
        time_runner_01+=1;
        if time_runner_01<150{
            if obj_detector.stopped==false{ //variable that indicates that there is a stopped runner
                move_towards_point(x,y,0);
            }else{
                time=150;
            }
        }else{
            if pos==1{
                move_towards_point(x,y+1,manSpeed);
            }
            if pos==2{
                move_towards_point(x-1,y,manSpeed);
            }
            if pos==3{
                move_towards_point(x,y-1,manSpeed);
            }
            if pos==4{
                move_towards_point(x+1,y,manSpeed);
            }

            obj_detector.stopped=true;
            manColision=true;
        }
    }
}

OBS- THE ORIGINAL CODE DOES NOT AND SO, CONTAIN OTHER THINGS, I EDITED THE NAMES OF THE VARIABLES TO MAKE SIMPLES THE UNDERSTANDING

To see if it is possible to have independent variables between equal objects I did a test =>

obj_detector (box with star) create event =>

test=irandom(10);

obj_detector (draw event) =>

draw_self();
draw_text(x-10,y,test);

Three different values for the same variable in the same object!!!


texts: Triangle data structure not working for LoD algorithm

texts:
I would like to implement a LoD algorithm to my 3D game in order to simplify meshes at certain distances from the player. My meshes are created / loaded using a VBO, so the vertex data is stored in a very large float array as

float[] vertices = {x1, y1, z1, x2, y2, z2, x3, y3, z3 ... xn, yn, zn};

How would I use this data in something like edge colapse? Would I need to convert this data into a more usable data structure such as a list of faces, or would it be possible to use this directly?

I feel like it would be very difficult to use the vertex array directly, so I have a simple class to represent a triangle using a Vector3f for each vertex, and an Edge class for each edge. The data structure for these are pretty simple, I dont feel that I need to show the whole code, so just a simple overview:

The Triangle class stores

3 Vector3fs to represent each vertex
3 Edges to represent each edge
an equals and hashcode implementation to be able to compare

And the Edge class stores

2 Vector3fs to represent each vertex
a float representing the length of the edge: abs(magnitude(subtract(v1, v2)))
an equals and hashCode implementation to be comparable

I have a method to convert the vertex array into a list of triangles, but it isn't working properly.

public static List<Triangle> vertexArrayToTriangles(float[] vertices, int[] indices)
{
    List<Triangle> result = new ArrayList();
    Vector3f[] vertexList = new Vector3f[vertices.length / 3];

    for (int i = 0; i < vertices.length / 3; i++)
    {
        vertexList[indices[i]] = new Vector3f(vertices[i], vertices[i + 1], vertices[i + 2]);
    }

    int i = 0;

    while (i < vertexList.length / 3)
    {
        result.add(new Triangle(vertexList[indices[++i]], vertexList[indices[++i]], vertexList[indices[++i]], new Vector3f(0, 1, 0)));
    }

    return result;
}

This just makes a spiky jumbled mess of triangles that is extremely laggy to render. Also, during rendering, the triangles are converted back into a float array of vertices.

How would I convert the vertex array into a List<Triangle> and keep the indices in order?


texts: Isometric Tile Selection with rectangular bounding boxes

texts:
I am having problems trying to determine which tile I have selected with the mouse.

Currently it selects two tiles, rather than one. Producing the following results:

My tiles height, is half their width, and all tiles have the same dimensions.

The tiles are rectangles and their Cartesian position has been translated to a relative isometric position.

Because I am checking the mouse position with the sprites bounds, it will select two tiles, as demonstrated in the image below:

I suppose my question is, how to I determine that my mouse x/y is within the 'diamond' of the rectangle?


texts:
it's my first question on stack.
Is it possible to infer length of the half angle vector for specular lighting from N·L and N·V without the whole view and light vectors?
I may be completely off-track, but I have this gut feeling it's possible...
Why? I'm working on a skin shader and I'm already doing one texture lookup with N·L+N·E and one texture lookup for specular with N·H+N·V. The latter one can be transformed into N·L+N·E lookup if only I had the half vector length.
Doing so could simplify the shader a bit and move some operations into the pre-computed lookup texture.
It would make a huge difference since I'm trying to squeeze as much functionality as possible to a single pass mobile version so instruction count matters.

Thanks.

Edit, for clarity, I'm doing something like this:

float NdotL = dot(s.Normal, lightDir);
float NdotE = dot(s.Normal, viewDir);

fixed3 diffAndTransl = 2.0 * tex3D(_Lookup3d, half3(diffNdotL, NdotE * 0.5 + 0.5, depth)).rgb;

now we have diffuse with SSS and backscattering from lookup
everything below could be just a lookup if I had length(h) information when calculating the lookup

float3 h = lightDir + viewDir;
float hLen = length(h);
//float3 H = normalize(h);
float3 H = h/hLen;
//float NdotH = dot(s.Normal, H);
float NdotH = (NdotL + NdotE)/hLen;
float EdotH = dot(viewDir, H);

fixed ph_by_fresnelReflectance = tex3D(_Lookup3d, half3(NdotH* 0.5 + 0.5, EdotH * 0.5 + 0.5, s.Gloss)).a;
half spec = saturate(NdotL) * max(ph_by_fresnelReflectance / hLensq, 0 ); // this could go into lookup as well

I was thinking I could infer length(h) from NdotL and NdotE when generating the specular lookup to reduce above code.
In my mind I was imagining something like a triangle on the plane made by lightDir and viewDir vectors could be thought of in 2D space. Don't the two dot products give me the (half?) angle and since both vectors are of length one, wouldn't it be possible to infer the length of the last side?
I tried some trigonometric voodoo programming but with no luck (chord of theta inferred from dot products?).
Does anybody have any idea if it's at all possible?
Maybe I just need to sleep more.

ps.: I know tex3D won't work well on mobile, just testing the grounds...


texts: Fixed Function vs Programmable Pipeline performance with many batches

texts:
In OpenGL 2.0 I can easily make 10,000 draw calls per frame (with state changes in between each call).  However, if i try to do this in either OpenGL ES 2.0 or DirectX9 with shaders, my peformance is 1Hz.  Is there an inherent different between fixed function and programmable pipeline rendering that requires programmable pipeline to require much fewer draw calls per frame, or is it more likely that I'm just doing something stupid in my code? I thought that most fixed function pipelines were implemented in shaders nowadays anyway, so if it is the case that I have to batch, then how does the fixed function implementation get away with not batching if its really using shaders?

Any "official" resources you could point me to would be great.


texts: How should I store game data in a game server?

texts:
I'm new to game server development. I'm facing this issue:

I want to develop a card game server, but I'm not sure about the solution to hold the game data while playing.

Example:
In a poker game, when a player makes a move, the server will process the request and send it to all other players. But how will the game server know what the current state of the game is to do subsequent actions? Should I save all moves into database and server will look into it to know the current state?


texts:
this is my jsfiddle : http://jsfiddle.net/seekpunk/ek6ub4u5/1/

i don't understand what i am missing it's been three days now working and trying to do the animation but i am stuck

 Crafty.sprite(128, "https://0.s3.envato.com/files/42440549/1_Ninja.jpg", {
               idle: [1, 0]
           });

i've loaded the spriteseet image and declare idle

 Crafty.c("animation", {
               init: function () {
                   this.requires("SpriteAnimation");
                   this.animate("run", 1, 1, 4);
                   this.bind("enterframe", function () {
                       if (!this.isPlaying("run")) {
                           this.animate("run", 20);
                       }
                   });
               }
           });

then i have declared the animation component and the bindframe function

var player = Crafty.e("2D,Canvas,idle, animation")
                        .attr({ x: 0, y: ch - 128, w: 128, h: 128 });

then i've declared the player ,but sadly the animation is not working .. can anyone tell me what i am missing please


texts: Making a Box2D ball bounce to constant height

texts:
I want to create a game like Doodle Jump. I'm using libgdx and Box2d. I needadvice  on how to make my ball bounce constantly and with the same height.

I've tried setting the ball's body restitution to 1 so it can jump constantly, but when I jump on a block the "impulse" is smaller. I also tried to detect the collision, then apply an impulse but it didn't work either.

How can I make the ball bounce to the same height every time?


texts: What approaches are there to re-designing 8/16-bit sprites for HD?

texts:
I'm new to game development, and my skills with Photoshop are not that great.

I was planning to try to convert a old game to HD, but for this I need HD sprites. What is a good way to approach converting 8/16 bit sprites into something like HD? I mean something like this:


texts: Should I create generic bitmap/sound/et cetera wrappers for Allegro?

texts:
Basically, I have been writing a game in C++ using Allegro.
I mostly just use the library to draw bitmaps, draw text, and play audio.

My main concern as the game continues to grow code-wise, is that with all the places I use al_draw_bitmap, al_play_sample, etc it becomes harder and harder to ever switch libraries if I so desire.
Aka all the places in code I would have to change the function calls and data types (ALLEGRO_BITMAP, ALLEGRO_SAMPLE, ALLEGRO_COLOR, etc).

I was wondering if it is a good idea to make a class (or classes) with generic mappings so that my code calls my own DrawImage(), PlaySound(), etc and then maybe typecast the data types (ALLEGRO_BITMAP, etc)?

This way its much less to change in the long run. I understand there would still be work involved and obviously I could only switch to another C++ library.

I'm not sure if there is a reason why this would be a bad idea, or if its actually a good idea, whats the best way to go about it.


texts:
I am writing a planet renderer and have come across a problem that is really limiting the usability of the program. When I am on the planet (anywhere but the north pole) I cannot rotate the camera to the left or to the right as I would if I was on a flat plane. Instead I can only move as if I were aligned to a regular flat plane. This gives me awkward viewing as seen here:

This limits me to only really looking straight ahead of the camera and straight behind the camera.

I drew this to try to illustrate the problem:

Will setting the up-vector of the camera to be the the point on the sphere where I am located normalized alleviate this problem?
I am at a dead-end here and any ideas would be greatly appreciated.
Thanks.


texts:
I'm working on a 2D fighting game (using SDL) much like the original Killer Instinct on SNES. I want the camera to keep both players an equal distance from the left and right sides of the viewport. When either player moves, the camera adjusts to keep this equal distance and both players in view, except for when both players are at either end of the stage, during which the camera remains still. Here is an example of how the original KI camera works: http://youtu.be/eFgfaP7f7Rs?t=8m22s

I will provide a diagram of what I am trying to achieve.

The red box is the viewport (camera) which slides over the background image file to display the portion of the stage the players are currently in.

Goal: Each frame the player positions are checked and an algorithm is used to calculate the src.x clipping position for the camera. The midpoint, I believe, in addition with the distance between the players can be used to calculate this value. The viewport width and image width are stored in memory and can also be used. If one player moves, the camera moves at the same velocity, and if both are moving in the same direction, the camera should double its velocity to keep up, all whilst keeping both player's distances from the left and right sides in sync.

Currently, I am using integer math for all positions. I specify the clipping width on the image file using configuration files, so for example, my current background is 768 pixels wide and I clip it to 425 pixels wide, which is displayed in the viewport. The fighters have basic acceleration and max velocity. I use a Camera class to logically represent its x value from 0 to the right edge. The camera's x position is subtracted from the player's x position before rendering. Before rendering the background, I add the camera's x value to the clipping x value (src.x).

I have tried many silly things such as using the ratios of the image and clipping widths to get weird x values. I've tried simply using the midpoint and modifying it with whatever I could think of using the distance, but no luck. I do have semi correct movement by setting the camera x position to the midpoint - (image width - clipping width). However this of course does not keep the players at equal distances.

I've been trying to figure this out for a while and it seems so simple, yet the solution continues to elude me (I'm probably exhausted at the moment). It is possible there are some strange architectural decisions in my code that are making this needlessly difficult. If someone could help me figure out an algorithm, that would be all I need. I can provide more information as needed.


texts: Looking for articles/books on: How do games make money? What models do they use?

texts:
I'm trying to research the ways in which games make money. I want to know more about the models they use (free/premium, trial/subscription, free-to-play with micro-transactions, etc.). In addition, I want information on which models work for which games, what models are best for which age groups, etc.

I've tried my best to find information, and Google hasn't turned anything up at all. I think I'll stop by my University's library and see if there's anything there.

This may seem like a broad question, but I'm looking for links and titles of books, not typed-out answers.


texts: Unity – How to keep sprites sharp and crisp, even while rotating

texts:
How can I maintain crisp, sharp edges on sprites, while avoiding the aliasing caused by rotation?

None of the things I've tried produce a pixel-perfect non-rotated block, while allowing rotation without aliasing

Click here for the sample project, which also has some extra images in it.

Click here for my Unity Forums Thread

Ideally, this is what it would look like

From Photoshop, not Unity.

Flawless edges, smooth corners, and very faint aliasing when rotated.

Screenshot from Github project:

Row 1

Non-rotated: Perfect edges, pixelated corners

Rotated: Pixelated everywhere

Row 2

Non-rotated: Perfect edges, smooth corners.

Rotated: Pixelated edges, smooth corners

Row 3

Non-rotated: Blurry everywhere.

Rotated: Blurry everywhere

Row 4

Non-rotated: Not quite perfect edges, pixelated corners

Rotated: Blurry everywhere

Row 5 (MY BEST SOLUTION SO FAR)

Non-rotated: Semi-blurry everywhere.

Rotated: Semi-blurry everywhere

Texture for "no border padding" texture:

Texture for "with padding" texture:

Shader Method

(Note: I'm a total shader newbie)

I created a fragment shader to draw the block.

It has AA (via smoothstep) built in, and throttles it on as block is rotated (so that there is no AA when it's not rotated)

This has some problems:

A (geometry) shader doesn't seem like the correct solution for this problem at all, since I'd have to make a shader for all the geometry that has this problem.

But maybe there is a shader that can apply AA to a texture, that doesn't do anything for vertical or horizontal (non-rotated) edges?

Corners of block with AA turned off are pixelated

This doesn't seem too difficult to fix
I'd probably want it to work identically to row 2 (non-rotated)

Not sure how much AA to apply (when rotated) so that it's as sharp as possible for a given screen DPI.

I thought this is what mip maps were good for, since the highest possible res texture should be chosen. (Another reason why a texture-based solution seems best)

Other things I've tried:

Vector graphics (per Unity's vector package)

Unity's vector package required 4x MSAA to look right, which was too intensive for mobile devices

MSAA

Creates blurry graphics (is there a way around this?)


texts: Unity3D mobile 4G internet web request is very slow

texts:
I have a windows VPS server and i have installed an Apache server on it. in my server I only have a simple text file that contains some few words.

My problem is that when I'm trying to sending a web request to my server by (4G sim card internet service ) for accessing to getting data from the text file , It works very slow .

Something about 30 or 50 secound ! but after first request if I try again there is no problem ! It works very fast !!!   It seems This slowdown will only occur in the first connection .

But in other hand if I use WI-FI internet , there is no problem and every time I try to get data it works fast.

MY problem is only with sim card internet !

This is part of my code :

    IEnumerator Get_Data()
        {
            UnityWebRequest www = UnityWebRequest.Get(servers_Address + "file.txt?t=" + UnityEngine.Random.value);

            yield return www.Send();
            string the_Data = www.downloadHandler.text;
}

Is there any problem in my code ?

My unity version is 2017.1.1

How can i solve this issue ?


texts: Gravity stops when side-collision detected

texts:
Please, look at this GIF:

The label on the animation says "Move button is pressed, then released". And you can see when it's pressed (and player's getCenterY() is above wall getCenterY()), gravity doesn't work. I'm trying to fix it since yesterday, but I can't.
All methods are called from game loop.

public void move() {
    if (left) {
            switch (game.currentLevel()) {
            case 1:
                for (int i = 0; i < game.lvl1.getX().length; i++)
                    game.lvl1.getX()[i] += game.physic.xVel;
                break;

            }
        } else if (right) {
            switch (game.currentLevel()) {
            case 1:
                for (int i = 0; i < game.lvl1.getX().length; i++)
                    game.lvl1.getX()[i] -= game.physic.xVel;
                break;
            }
        }
    }

    int manCenterX, manCenterY, boxCenterX, boxCenterY;
//gravity stop
    public void checkCollision() {
        for (int i = 0; i < game.lvl1.getX().length; i++) {
            manCenterX = (int) game.man.getBounds().getCenterX();
            manCenterY = (int) game.man.getBounds().getCenterY();
            if (game.man.getBounds().intersects(game.lvl1.getBounds(i))) {
                boxCenterX = (int) game.lvl1.getBounds(i).getCenterX();
                boxCenterY = (int) game.lvl1.getBounds(i).getCenterY();
                if (manCenterY - boxCenterY > 0 || manCenterY - boxCenterY < 0) {
                    game.man.setyPos(-2f);
                    game.man.isFalling = false;
                }
            }
        }
    }
//left side of walls
    public void colliLeft() {
        for (int i = 0; i < game.lvl1.getX().length; i++) {
            if (game.man.getBounds().intersects(game.lvl1.getBounds(i))) {
                if (manCenterX - boxCenterX < 0) {
                    for (int i1 = 0; i1 < game.lvl1.getX().length; i1++) {

                        game.lvl1.getX()[i1] += game.physic.xVel;
                        game.man.isFalling = true;

                    }
                }
            }
        }
    }
    //right side of walls
    public void colliRight() {
        for (int i = 0; i < game.lvl1.getX().length; i++) {
            if (game.man.getBounds().intersects(game.lvl1.getBounds(i))) {
                if (manCenterX - boxCenterX > 0) {
                    for (int i1 = 0; i1 < game.lvl1.getX().length; i1++) {

                        game.lvl1.getX()[i1] += -game.physic.xVel;
                        game.man.isFalling = true;
                    }
                }
            }
        }
    }
public void gravity() {
    game.man.setyPos(yVel);
}

 //not called from gameloop:    public void setyPos(float yPos) {
        this.yPos += yPos;

}


texts: Synchronizing input, update and rendering threads

texts:
How do you synchronise the input-handling, state-updating and rendering threads?

If a sprite position is modified due to input, the wrong position of the sprite might be drawn to the screen if the render thread draws the sprite before the update thread finishes its collision resolution routine.

How can this be done?

(The only solution I can think of would be to store input events as they are created and consume them in the update/render threads.)


texts: How do I flip Player in 2D Touch Movement?

texts:
How do i flip my Player in 2D when i got touch movement?
I got Buttons to move but how do I flip the player now if i walk to the right cause my player faces to the left..?

here is my Player Script:

using System.Collections;

public class PlayerController : MonoBehaviour {

    public float speed = 10, jumpVelocity =  10;
    public LayerMask playerMask;
    public bool canMoveInAir = true;
    Transform myTrans, tagGround;
    Rigidbody2D myBody;
    bool isGrounded = false;

    // Use this for initialization
    void Start ()
    {
        myBody = this.GetComponent<Rigidbody2D>();
        myTrans = this.transform;
        tagGround = GameObject.Find (this.name + "/tag_ground").transform;
    }

    // Update is called once per frame
    void FixedUpdate ()
    {
        isGrounded = Physics2D.Linecast (myTrans.position, tagGround.position, playerMask);

        #if UNITY_ANDROID && !UNITY_IPHONE && !UNITY_BLACKBERRY && !UNITY_WINRT
        Move(Input.GetAxisRaw("Horizontal"));
        if(Input.GetButtonDown("Jump"))
           Jump();
        #endif
    }

    public void Move(float horizontalInput)
    {
        //Er klebt nicht mehr an den Waenden
        if (!canMoveInAir && !isGrounded)
            return;

        Vector2 moveVel = myBody.velocity;
        moveVel.x = horizontalInput * speed;
        myBody.velocity = moveVel;

    }

    public void Jump()
    {
        if(isGrounded)
            myBody.velocity += jumpVelocity * Vector2.up;
    }

}


texts: Why does the triangle rendered by OpenGL ES 2.0 , with SDL 2.0 context, vanishes after a single render, if events are not polled?

texts:
I was experimenting with OpenGL ES 2.0 and being new to OpenGL, I was trying to render a simple triangle. But I was shocked to see that, if I do not call SDL_PollEvent(...) after glDrawArrays(...) in the game loop, I see the triangle render on the screen for a split second and then it vanishes altogether ! But, if I call SDL_PollEvent then everything is fine ! Can anyone explain to me the reason for this abnormal behavior???
However, this is the interesting part of my code:
This code works perfectly, if I uncomment the commented block of code:
uint32_t vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(pos);
glVertexAttribPointer(pos, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), (void*)0);

bool run = true;
SDL_Event e;
while (run)
{
    glDrawArrays(GL_TRIANGLES, 0, 3);
  SDL_GL_SwapWindow(window);

/*while(SDL_PollEvent(&e))
{
      switch(e.type)
      {
           case SDL_QUIT:
                run = false;
                break;
      }
} */

}
Vertex Shader:
precision mediump float;
attribute vec3 pos;
void main()
{
    gl_Position = vec4(pos.xyz, 1.0);
}

Fragment Shader:
precision mediump float;
void main()
{
      gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0);
}

Every help will be greatly appreciated, Thankyou everyone in advance !


texts:
I've been working on an saving system for my 2D RPG game, and I recently encountered an issue: my saving system uses PlayerPrefs, which I heard is supposed to be used for things such as settings. I've also heard that it isn't very secure and that people can exploit it. I was wondering whether there was a way to make my saving system more secure. Here's my inventory script that also holds the save function:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ItemInformation : MonoBehaviour
{
    // These are the assets for the item to change
    public Text nameText;
    public Text descriptionText;
    public Text regenText;
    public Text amountText;

    // This is the identifier for each item
    public string identifier;

    // These are the variables that change with the different items
    public string itemName;
    public string itemDescription;
    public float itemRegeneration;
    public int itemAmount;

    // Starts on awake
    void Awake()
    {
        // Function to change the object's information and such
        nameText.text = itemName;
        descriptionText.text = itemDescription;
        regenText.text = "HEALS " + itemRegeneration + "HP";

        // Loads game data
        LoadDataIfNeeded();
    }

    // Function to save game data
    public void SaveData()
    {
        string jsonString = JsonUtility.ToJson(this);
        PlayerPrefs.SetString(identifier, jsonString);
        PlayerPrefs.Save();
    }

    // Loads data if needed
    public void LoadDataIfNeeded()
    {
        if (PlayerPrefs.HasKey(identifier))
        {
            string jsonInstance = PlayerPrefs.GetString(identifier);
            JsonUtility.FromJsonOverwrite(jsonInstance, this);
        }
        else
        {
            SaveData();
        }
    }

    // Updates on every frame
    void Update()
    {
        // Shows amount of item left
        amountText.text = "HAVE:" + itemAmount;
    }
}


texts: How can I solve for the game's world coordinates?

texts:
I've used 3DReaperDX to get a obj file, the header information are shown as follows:

#AR=2.00606, FOV=45.09583(height), Xscale:0.83290, Yscale:0.41519, Zscale:1.0
#**************************************************
#ALPHABLENDENABLE: No
#ZENABLE: Yes
#ZWRITEENABLE: Yes
#TWOSIDED: No
#INVALID: No
#THIN: No
#RENDERTARGET_IS_BACKBUFFER: Yes
#WIDTH_DO_MATCH: Yes
#RGBWRITEDISABLED: No
# object DrawCall_0 to come ...
g
v 2143.35547 6654.99023 25835.37109
v 2243.17773 6296.61523 25957.53906
v 2343.00000 5856.84473 26093.97656

How can I get the game's world coordinates.

For example: I can map the scaleTransform to the VertexData

scaleTransform={X1scale,Y1scale,Z1scale}
{0.8329,0.41519,1.}

Is the obj file enough to get the game's world coordinates?
I want to put a object in this ground, and the coordinates is the same to that in the Game Engine,

And I can place something(with some fixed coordinates) in the Game and then to use 3DReaper to get the obj file.  If the file is not enough itself to get the game world coordinates.


texts: How do I get the source code from a Google Code game project?

texts:
I'm trying to get the Hedgewars source code.  When I went to the downloads tab, it doesn't specify which is the actual game.  I tried downloading it using the SVN Checkout on Tortoise, but it seems like it doesn't work on the browse section of Source.

(Hg>project_files>Android_build>SDL-android-project)

I then proceeded to the wiki but I got stuck at step two because I don't know anything about Mercurial.
Some other things I don't know from the wiki is "FreePascal" "Android NDK" and "Tar" files.  They are new to me so I am really confused.

So my question is, how can I download the source code from Hedge Wars for Android without having to browse the source code inside the source tab?


texts: I have a Group object comprised of 2 actor members. Each member in the group can have their height, width, and positions scaled and set independently with no issues. However, attempting to utilize setRotation() or rotateBy() on an individual member of the group does not cause the member to rotate. The entire group can be rotated at once, but not an individual member in the group. Is there a way to rotate a single actor member that is part of a group?


texts: Calculate the direction, From Outer Polygon Point to Inner Polygon inside Point

texts:
I was able to find the co-ordinates of inner Polygon using this trick.

Need the co-ordinates of innerPolygon

But, I have some problem in getting the direction from Outer Polygon Point to Inner Polygon inside Point? See this image, I need to make sure that the direction should be from inner to outer.


texts: How to optimize my random terrain generation and usage?

texts:
I'm new to Unity. I've created an algorithm to procedurally generate a circle-shaped tunnel made of primitive cubes GameObjects. The problem is that the game is very laggy and I can understand why: there are thousands of objects to render.

What I'd like to know is if there's a better approach to this. For example, would be better if instead of rendering the single cubes I create a ring custom component and use that instead?

Are there any other solutions?

I'm using Unity 5.3.4f1.

EDIT

Here's what I've done so far. This works the way I want but the game is really laggy because (I assume) there are lots of objects to render.

public class TerrainGenerator : MonoBehaviour {

private static int MAX_RING_NUMBER = 1000;

private static int TUNNEL_SLOPE = 5;

// Use this for initialization
void Start () {
    int y = 0;
    for (int z = 0; z < MAX_RING_NUMBER; z++) {

        createRing(0, y, z, 10);
        // Every TUNNEL_SLOPE cubes the tunnel goes down a block.
        if (z % TUNNEL_SLOPE == 0)
            y--;
    }
}

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

}

private void createCube(int x, int y, int z){
    GameObject cube = GameObject.CreatePrimitive (PrimitiveType.Cube);
    cube.transform.position = new Vector3 (x, y, z);
    cube.GetComponent<Renderer>().material.color = new Color(Random.Range(0,255),Random.Range(0,255),Random.Range(0,255));
}

// Midpoint circle alghoritm.
void createRing( int x0, int y0, int z, int radius){
    int x = radius;
    int y = 0;
    int decisionOver2 = 1 - x;   // Decision criterion divided by 2 evaluated at x=r, y=0

    while( y <= x )
    {
        createCube(x + x0,  y + y0, z); // Octant 1
        createCube(y + x0,  x + y0, z); // Octant 2
        createCube(-x + x0,  y + y0, z); // Octant 4
        createCube(-y + x0,  x + y0, z); // Octant 3
        createCube(-x + x0, -y + y0, z); // Octant 5
        createCube(-y + x0, -x + y0, z); // Octant 6
        createCube(x + x0, -y + y0, z); // Octant 7
        createCube(y + x0, -x + y0, z); // Octant 8
        y++;
        if (decisionOver2<=0)
        {
            decisionOver2 += 2 * y + 1;   // Change in decision criterion for y -> y+1
        }
        else
        {
            x--;
            decisionOver2 += 2 * (y - x) + 1;   // Change for y -> y+1, x -> x-1
        }
    }
}

}


texts:
I want to add explosions to my 2D game, but im having a hard time with the architecture. Several game elements might be responsible for explosions, like, lets say, explosive barrels and bullets (and there might be chain reactions with close barrels). The only options i can come up with are:

1 - Having an array of explosions and treat them as a game element as important as any other

Pros: Having a single array which is updated and drawn with all the other game element arrays makes it more organized and simple to update, and the explosive barrels at a first glance would be easy to create, simply by passing the explosion array as a pointer to each explosive barrel constructor

Cons: It might be hard for the bullets to add an explosion to the vector, since bullets are shot by a Weapon class which is located in every mob, so lets say, if i create a new enemy and add it to the enemy array, that enemy will have a weapon and functions to be able to use it, and if i want the weapon (rocket launcher in this case) to have access to the explosions array to be able to add a new one, id have to pass the explosion array as a pointer to the enemy, which would then pass it to the weapon, which would pass it to the bullets (ugly chain).
Another problem I can think of is a little more weird: If im checking the collisions between explosions and barrels (so i create a chain reaction) and i detect an explosion colliding with a barrel, if i add a new explosion while im iterating the explosions java will trow an exception. So this is kinda annoying, i cant iterate through the explosions and add a new explosion, i must do it in another way...

The other way which isnt really well thought yet is to just add an explosive component to every element that might explode so that when it dies, it explodes or something, but i dont have good ways on implementing this theory either

Honestly i dont like either the solutions so id like to know how is it usually done by actual game developers, sorry if my problem seems trivial and dumb.


texts: Level up increases to stats in rpg games?

texts:
I have decided on the stats being vitality, strength, intelligence, speed and endurance.

While HP and MP are decided by vitality, both physical attack and defence are derived from strength.

Intelligence decides both magic attack and magic deffense while speed changes how fast the character is and endurance increases things like equip load burden.

In rpgs I have played different characters depending on how the designer wanted them to feel (i.e. a muscular brute may have a higher strength but lower intelligence) the character may have higher stats in a certain area.

While I can understand that I do not understand how I should structure stat increases that happen when leveling up. For a test character I set all of their stats equal to 10 (I decided to start all characters with a base 50 stat total for now) the characters stats should move up anywhere from 0 to lets say 9 at most when leveling up.

So what is a way to decide which stats go up and by how much when the character levels?


texts: How to implement an intelligent enemy in a shoot-em-up?

texts:
Imagine a very simple shoot-em-up, something we all know:

You're the player (green). Your movement is restricted to the X axis. Our enemy (or enemies) is at the top of the screen, his movement is also restricted to the X axis.
The player fires bullets (yellow) at the enemy.

I'd like to implement an A.I. for the enemy that should be really good at avoiding the players bullets. My first idea was to divide the screen into discrete sections and assign weights to them:

There are two weights: The "bullet-weight" (grey) is the danger imposed by a bullet. The closer the bullet is to the enemy, the higher the "bullet-weight" (0..1, where 1 is highest danger). Lanes without a bullet have a weight of 0. The second weight is the "distance-weight" (lime-green). For every lane I add 0.2 movement cost (this value is kinda arbitrary now and could be tweaked).

Then I simply add the weights (white) and go to the lane with the lowest weight (red). But this approach has an obvious flaw, because it can easily miss local minima as the optimal place to go would be simply between two incoming bullets (as denoted with the white arrow).

So here's what I'm looking for:

Should find a way through bullet-storm, even when there's no place that doesn't impose a threat of a bullet.
Enemy can reliably dodge bullets by picking an optimal (or almost optimal) solution.
Algorithm should be able to factor in bullet movement speed (as they might move with different velocities).
Ways to tweak the algorithm so that different levels of difficulty can be applied (dumb to super-intelligent enemies).
Algorithm should allow different goals, as the enemy doesn't only want to evade bullets, he should also be able to shoot the player. That means that positions where the enemy can fire at the player should be preferred when dodging bullets.

So how would you tackle this? Contrary to other games of this genre, I'd like to have only a few, but very "skilled" enemies instead of masses of dumb enemies.


texts: Cube doesn't render as expected when rotated (representing 3D in 2D)

texts:
Cube.

When I rotate the object around OZ moves to the left.

Rotation around OX - the cube rises up.

Rotation around the OY-the cube is compressed.

The function I use for rotation:

void rotation(double angleX, double angleY, double angleZ, int x, int y, int z)
{
    angleX = angleX * M_PI / 180;
    angleY = angleY * M_PI / 180;
    angleZ = angleZ * M_PI / 180;

    double cX = cos(angleX);
    double sX = sin(angleX);
    double cY = cos(angleY);
    double sY = sin(angleY);
    double cZ = cos(angleZ);
    double sZ = sin(angleZ);

    double x0 = x;
    double y0 = y * cX + z * sX;
    double z0 = z * cX - y * sX;

    double x1 = x0 * cY - z0 * sY;
    double y1 = y0;
    double z1 = z0 * cY + x0 * sY;

    double x2 = x1 * cZ + y1 * sZ;
    double y2 = y1 * cZ - x1 * sZ;

    SDL_RenderDrawPoint(ren, x2, y2);
}

Used matrices. However, the result was the same.


texts: 2D game libraries that support positional stereo sound?

texts:
I would like my game to have semi-realistic sound, where the left/right channel volume depends on the position of the sound source within the world.

I've looked and it seems that it's not possible with Löve2d or pygame. They modify the volume of a sound based on distance, but the left and right channels are identical.

Am I wrong?
Are there any other 2d game libraries that make this possible?


texts:
In unity 2019.1.3f I want to implement google admob ads in that game but after importing GoogleMobileAds-v3.18.0.unitypackage in to my project I got a porblem.

when I hit play button

this window poped up.

Please help me regarding the problem

Thank you


texts: How to prevent a hacked-server from spoofing a master server?

texts:
I wish to setup a room-based multilayer game model where players may host matches and serve as host (IE the server with authoritative power). I wish to host a master server which tracks player's items, rank, cash, exp, etc.

In such a model, how can I prevent someone that is hosting a game (with a modified server) from spoofing the master server with invalid match results, thus gaining exp, money or rankings.

Thanks. -Cody


texts: Space Invaders: Getting the aliens to move as one

texts:
I'm having issues getting my invaders to move together. Currently they hit the edge of the screen and then go crazy.

Here is the code for the Alien:

#include "Alien.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
Alien::Alien()
{
}

void Alien::Init(ISprite * a,  float hp, float vp, int sValue)
{
    srand(time(NULL));
    alien = a;
    horizontalPos = hp;
    verticalPos = vp;
    rev = false;
    bombInterval = float(rand() % 10 + 1);
    lastDropped = 0;
    scoreValue = sValue;
    alive = true;
}

bool Alien::testCollision(Rocket R)
{
    if(R.getX() >= horizontalPos &&
       R.getX() <= (horizontalPos + 32) &&
       R.getY() >= verticalPos &&
       R.getY() <= (verticalPos + 32)) {
           return true;
}

    return false;
}

void Alien::Update(float move, DResourceManager& drm)
{

    if(rev){
            horizontalPos -= (move);
    }
    else{
        horizontalPos += (move);
    }

    if(horizontalPos >= (640-32))
    {
        drm.alert();
    }
    if(horizontalPos < 32)
    {
            drm.alert();
    }
        // Check to see if we are colliding with any rockets.
        if(drm.getRocketCount() > 0)
        {
            for(std::vector<Rocket>::iterator roit = drm.getRockets().begin(); roit != drm.getRockets().end(); ++roit) {
            if(roit->alive){
                if(testCollision(*roit))
                {
                    setDead();
                    roit->setDead();
                    drm.getRockets().erase(roit);
                    return;
                }
            }
        }

    }
}

int Alien::getScore()
{
    return scoreValue;
}

void Alien::reverse()
{
    rev = !rev;
}

bool Alien::isAlive()
{
    if(alive){
        return true;
    }

    return false;
}

void Alien::setDead()
{
    alive = false;
}
float Alien::getX()
{
    return horizontalPos;
}

float Alien::getY()
{
    return verticalPos;
}

void Alien::setPosX(float x)
{
     horizontalPos += x;
}

void Alien::setPosY(float y)
{
     verticalPos += y;
}

void Alien::draw()
{

        alien->draw(int(horizontalPos),  int(verticalPos));
}

void Alien::destroy()
{
    alien->destroy();
}

Alien::~Alien(void)
{
}

And the update and draw functions of my DResourceManager class.

void DResourceManager::update(float time)
{
    player->update(time, this);
    int direction = 1;
    float max = 0;
    float min = 0;
    for(std::vector<Alien>::iterator it = aliens.begin(); it != aliens.end(); ++it)
    {
        if(it ->isAlive()){
            it->Update(time, *this);
        }
    }
    if (rev)
    {
        for(std::vector<Alien>::iterator it = aliens.begin(); it != aliens.end(); ++it)
        {
            it->setPosY(5);
            it->reverse();
            rev = false;
        }
    }

    // Update rockets if we have any.
    if(rocketCount > 0){
        for(std::vector<Rocket>::iterator roit = rockets.begin(); roit != rockets.end();     ++roit) {
            if(roit == rockets.end()){
                return;
            }
                if(roit->alive){
                    roit->update(time);
                }
            }
    }

}

/* Draw all objects to the screen */
void DResourceManager::draw()
{
    player->draw();

    for(std::vector<Alien>::iterator it = aliens.begin(); it != aliens.end(); ++it) {
        if(it->isAlive())
            it->draw();
    }

    for(std::vector<Rocket>::iterator it = rockets.begin(); it != rockets.end(); ++it) {
        if(it->alive)
            it->draw();
    }
}

Your help with getting these aliens to move as one would be much appreciated.


texts: I have been studying SDL for a few weeks and I have succeeded in making a 2D Ping-Pong game, but  I want to get started in 3D development, and I'd like to know if SDL is capable (and suitable) for 3D game development, or I must use OpenGL?


texts: Unity 2d overlapCircle melee combat issue

texts:
I have an issue with my overlapCircle melee combat in the game. I'm not good at such things, so I just copied that code from some YouTube tutorial. But the thing is that if the enemy is behind the collider, I can still damage and kill him. And I don't want this. Is there a solution to this problem except recreating the melee combat system from the ground up? Maybe changing circle radius when close to collider?...
Here's a video clip that may help show the situation.
void Attack()
{
    Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, whatIsEnemy);
    foreach (Collider2D enemy in hitEnemies)
    {
        Debug.Log("Melee hit: " + enemy.name);
        if (enemy is BoxCollider2D)
        {
            CinemachineShake.Instance.ShakeCamera(3f, 0.2f);
            SoundManager.PlaySound("Knife_kill");
            if (enemy.tag == "Melee enemy")
                enemy.GetComponent<enemy_melee>().TakeDamage(attackDamage);
            else if (enemy.tag == "Gun enemy")
                enemy.GetComponent<enemy_gun>().TakeDamage(attackDamage);
        }
    }
    animator.SetTrigger("Melee_attack");
    animator.SetBool("IsCrouching", false);
    animator.SetBool("IsJumping", false);
}


texts: ID3D10Device creation failure in release mode

texts:
My ID3D10Device creation works fine in debug mode but I throws an error in release mode:

DXGI_SWAP_CHAIN_DESC scDesc = {0};
    scDesc.BufferDesc.Width = desc.width;
    scDesc.BufferDesc.Height = desc.height;
    /*scDesc.BufferDesc.RefreshRate.Numerator = 60;
    scDesc.BufferDesc.RefreshRate.Denominator = 1;*/
    scDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    scDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
    scDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

    scDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    scDesc.BufferCount = 1;
    scDesc.OutputWindow = desc.hWnd;
    scDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
    scDesc.Flags = 0;

    scDesc.Windowed = true;
    scDesc.SampleDesc.Count = desc.sampleCount;
    scDesc.SampleDesc.Quality = desc.sampleQuality;

    // Create the device.
    UINT createDeviceFlags = 0;
#if defined(DEBUG) || defined(_DEBUG)
    createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG;
#endif

    HRESULT hr;
    hr = D3D10CreateDeviceAndSwapChain(
        nullptr,
        D3D10_DRIVER_TYPE_HARDWARE,
        NULL,
        createDeviceFlags,
        D3D10_SDK_VERSION,
        &scDesc,
        &g_Renderer.m_DxCore.pSwapChain,
        &g_Renderer.m_DxCore.pDevice);

    std::tcout<<hr;

//////RUNTIME ERROR HANDLING
    if(FAILED(hr)) {
        throw std::runtime_error("ERROR: Failed to create ID3D10Device and IDXGISwapChain");
    }

I've already checked each of these options, but none of it triggers.
http://msdn.microsoft.com/en-us/library/windows/desktop/bb205278(v=vs.85).aspx

The value of the hr seems to be -2005270527, after checking it with std::cout<<hr
My debugger also can't show the value of hr when hovering over it, for some reason. :(

What could the problem possibly be?


texts:
i'm developing a android project for school and i'm currently using libgdx for rendering. It performs quite well, but it lacks a 3d physics library. So i searched and found that Bullet physics engine was ported to android through NDK (c++). Did anyone try to connect this two libs together?

I've never used a physics engine/library before (i've mainly developed 2d games so i've made one my self) and wanted to ask if any one had any previous experiences with implementing bullet and libgdx? To be more precise i need to simulate a jump and implement physics like: wind/drag, friction, lift, gravity; during the jump.

Does bullet calculate the gravity and other forces by it self (if so can i implement other forces easily?) or can i control which element gets updated (mainly re transformed) and when? How does collision detection work (is there some kind of collision world/collection)? Can i handle collision detection on my own or does bullet take care of this as well?

Thanks for the reply's!


texts:
I discovered VBO's recently and changed my code to use them instead of immediate mode. Now I'm rendering 25000 squares and it's really slowing down my FPS.  If I drew all the squares VBO's to an FBO,  then bound it to a single VBO, would it increases performance?
The 25000 squares is more of a stress test,  im trying to optimize my rendering code for snow.
Edit : Each snow particle draws one of three static VBO's,  this helped performance.


texts: Jump when the screen is tapped, rather than when the space key is pressed

texts:
I am trying to make my character jump when the player taps the screen.

At the moment it jumps when I press space bar, but how can I change the code to make him jump when the screen is tapped?

This code works as the character then jumps up:

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        rb.gravityScale *= -1;
    }
}

This code using touch does not work: the character just stays where he is when I click the screen on my computer.

public void Update()
{
    if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);
        rb.gravityScale *= -1;
    }
}


texts: JavaFX AnimationTimer VS Swing Game Loop

texts:
After looking at some code sources out there I noticed Java Swing Games usually create a class implementing Runnable, create a new Thread and set up the game loop in the run() call.

But JavaFX games seem to simply extend from Application and run the game loop in a  new AnimationTimer() { ... public void handle() ... }

What gives?


texts:
I'm getting near the point where I'm going to be ready to release an alpha of my game. I'm curious as to how to implement a system where the game is un-launchable if a user name and password haven't been entered and verified. I plan on having an authentication server setup for verifying user credentials. I'm not concerned about making the game pirate proof, because that'll happen. I just want to make it more difficult for the casual user to share. What needs to be in place for such a system to work? My thoughts are to implement a system similar to this:

The first time the user logs in, have the users computer generate unique value based on their system attributes (not the actual attributes, I'm not collecting that). Logging in to the server sends username/pass and unique value, the server then attributes that username with that unique value and those are checked when the user logs in.

I don't plan on limiting the amount of computers a user can install on, but I want to be able to disallow obvious abuse of an account, i.e. it's being used on dozens of computers.

Is this system reasonable for a free-time sole developer? Or what kind of system would make sense for my requirements?

EDIT

Let me elaborate a little on why I want to use the system unique ID. I think that having a key like that is what would enable me to have an offline mode. I guess I wouldn't need to send the key to the server. But once a user name and password have been authenticated by the server, I can instruct the game to generate that unique ID and pair it with the user name. Then when the user tries to launch the game in offline mode, I can check to see if that computer has been authenticated online before. This would disallow people copying a verified copy of the game to a different computer to use offline mode.


texts: Unity Proximity Warning System Trigger issues

texts:
I'm trying to set up a proximity warning system but I'm having some trouble.

To simplify things as much as possible:

I have two game objects in a scene (Object1 and Object2). Object1 has a large child object (twice as large as Object1 or Object2) which has no mesh renderer, but has a box collider (with the Is Trigger box ticked). Object 2 has a rigidbody component.

When Object1 gets close enough that it's child's Box Collider overlaps with Object2's rigidbody, a script on Object1 should Debug.Log the name of the object it's close to once a frame until Object1 moves away.

My code is as follows:

public Collider objectCollidedWith;

void OnTriggerStay(Collider other)
{
objectCollidedWith = other.transform.GetComponent<Collider>();
}

void Update()
{
Debug.Log(objectCollidedWith);
}

Unfortunately, something about my setup isn't working. The console just shows "null" once a frame and the objects getting close doesn't change this.

Can you tell me what I'm doing wrong?

Many thanks for your time.


texts: What is the lowest-level way of making graphics from scratch?

texts: I am currently trying to get into game development and trying to understand 3D games. I would like to learn to code from scratch without any 3D engines. Some of the things I found was libraries like SDL and graphics.h in C. How does a game actually access the screen at the lowest-level? So how would one move a square rightwards on the screen on say Windows. Is the lowest level OpenGL and Direct3D or is there lower-level ways of doing it?


texts: Quaternion Slerp and Lerp implementation (with overshoot)

texts:
I am working with Unity (C#) and was looking for an implementation of Slerp and possibly Lerp that allow overshoot (progress not strictly limited to 0..1 range).  I want to do some tweening animation using an elastic ease-out function.  My ease-out function returns values slightly outside the 0..1 range in order to get an oscillating-around-the-target effect.  The problem is that Unity's Quaternion Lerp and Slerp functions appear to clamp the progress input in the 0..1 range.

Implementation code in any language would be helpful.  I don't know enough about Quaternion math to write this myself.


texts: 2D game with angled top-down camera perspective

texts:
I want to create a game similar to binding of isaac, a slightly angled top-down 2D game. In binding of isaac, the character moves and shoots along a 4-way path, so when he is shooting towards East, the character is facing East, same for North, West and South. In my game I need to shoot at any given angle, so it will look pretty bad if the character is facing East but the bullet is going North-East, I considered creating 8 or even 16 sprites with the character facing at different at different angles. But I don't know if it will look good either.

I would like to know if anyone encountered this problem and if there is any solution beside switching to 3D, because is not a solution at this moment.

In this image(Binding of Isaac) it may look like the player shoots at any given angle but it's not, he moved to the left immediately ofter shooting.


texts: My game engine is done, how can I get ideas of a game to make with it?

texts:
I read at many places how people have this GREAT ideas but are not able to program themselves. I have quite the opposite problem. I have developed game engine, level editor, embedded Lua scripting language, I have even made wrapper for Android and it all works well. But I have no good idea about how to proceed with actual levels; I have no good ideas. The engine itself is very generic and can be used in many game concepts, but I just cannot think of anything useful. Do you have any thoughts on how to proceed? Where should I seek ideas? Who should I ask?
I am sorry if this question is a duplicate.

EDIT: Thank you all for your responses. I see now in FAQ that indeed my question was misplaced. I just saw this thread and people were advising that ideas are worthless and execution is what counts. So I wondered where all the "worthless" ideas are, because I cannot seem to find any when I need it.

Yes, the engine was targeted at one particular game, but I always envisioned it like "based on game X with additional features". So I added additional features but now I don't know how to use them in a funny and entertaining way. I could still finish the original game X, but it would only be unoriginal copy of the game X, which is just pointless.

Anyway, thanks again for your responses, wish you happy coding.


texts:
I just finished coding a generic Behavior Tree structure for my games.  My question is, when creating behaviors for enemy AI's, do I create one large behavior tree with every possible configuration as a node or do I create many multiple Behavior Trees and simply swap them in and out as I need them?

To better understand my question here are some examples:

One large Behavior Tree might look something like this:

Multiple smaller Behavior Trees might look like this:

In the second tree I would simply swap out different trees depending on when I need them.  This is more apparent for things like evading and backing away from obstacles, I feel like that would need to be done alongside many other behaviors like chasing and evading.

I hope that made sense.


texts:
the issue i am having is rpg maker is installed onto my computer as well a rgss-rtp standard and when i go to run RPG maker it says RGSS-RTP STANDARD not installed?
how can i get it to run?


texts: Possible to test a game on multiple machines without owning multiple machines?

texts:
I'm working on a small PC game (Uses custom engine written in C++) that I would like to test. Not as much the gameplay but the engine itself. See if there are any crashes, errors, glitches or missing library files. I'm using OpenGL for graphics and that always does unexpected things with a different driver / GPU.

At the same time I don't yet want to give out the half-finished game for public testing. Is there such online service that allows you to upload a program to run and gives you back the result of the run. A log file or a screencap or what not. Or is it possible to do such testing with VirtualBox?


texts: How to stretch and rotate an image between two points in cocos2d?

texts:
I have an arrow image. I want to stretch this image between two given points. I'm retrieving the points from touch locations, so they aren't fixed. When the user touches the iPad, the arrow image should appear and be shown until the touch ends. So if the user touches point A and is moving his finger to point B, the arrow image will be stretched from point A to point B and so on.

How can I achieve that?


texts: character movement data passing on server

texts:
I am trying to build my first online game using unity with photon, the data transfer between server and clients is implemented but I am facing a great problem; How/What should be transferred to synchronise the movement data?

My game has a lobby and may have as many as 20 people online at the same time if I pass the position of every players to server and then server to clients, I believe the server would be overloaded, wouldn't it?

Hence I think an other way is to pass the movement of characters:
1) only when a player presses a movement key, then pass it to server and other clients,
2) if the player releases the key, then pass the position for validation.
It is workable?
Will there any inconsistency between the clients?

I Hope someone can give me some advice, Thank you!


texts: Artifacts on crosshair in game view with FXAA

texts:
I have a transparent grid texture that I am displaying on a quad using the URP's built in unlit/Transparent Shader. The intersections render as desired in the scene view, but have artifacting in the game view (even after play is pressed).
Scene View:
As you can see, the scene view renders clean intersections

Game View:
The intersections display some artifacting. (This screenshot was taking after zooming in the game view panel, but the artifacts are still visible at 100% zoom)

Note: I do not think that this is related to PNG transparency. I have written a custom procedural grid shader that exhibits similar artifacting in the game view:

The problem seems to be due to my enabling FXAA, which is smoothing the sharp corners. Disabling FXAA immediately solves the problem.
However, this is somewhat of an inconvenient solution, because anti-aliasing is nice to have enabled. Is there a way to make the artifacts disappear without disabling AA completely?
How do I configure the URP/anti-aliasing to render my grid texture as it does in the scene view? I have tried changing the compression level and the filtering algorithm, to no avail.


texts:
I'm undecided on a design decision. Now for my game I was thinking on splitting components into separate dlls. This would allow for a more modular approach, especially when in need of updates. On launch it [the game] could swap out newer versions of the dll coming from a centralized server. This would allow us to provide updates to each component separately and also allow us to quickly swap dll's for different implementation.

Now is this design used, and how effective is it?

I started implementing it, and loading a dll through run-time ads a lot of complexity (unless i'm doing it wrong). Another problem that could arise is some components are optional. So it would ad additional complexity.

So what i'm trying to get to is: Is splitting separate components and subsystems in dll's?

This would allow the exe to be a lot smaller, and possibly make the whole system a little more organized.


texts: What to send to server in real time FPS game?

texts:
What is the right way to tell the position of our local player to the server? Some documents say that it is better to send the inputs whenever they are produced. And some documents say the client sends its position in a fixed interval.

With the sending the inputs approach: What should I do if the player is holding down the direction keys? It means I need to send a package to the server in every frame. Isn't it too much? And there is also the rotation of the player from the mouse input. Here is an example:

  http://www.gabrielgambetta.com/fpm_live.html

What about sending the position in fixed interval approach. It sends too few messages to the server. But it also reduces responsiveness.

So which way is better?


texts: FPS drop when detecting collision (sfml, c++)

texts:
So, I have this small class with a collision detection function in it, it's called every frame.

When I run the game I get around 8000 FPS, but when the collision function gets called it drops to 2000.

This is what the function looks like (only called 1 time per frame)
The second one is just for overriding.

bool DetectCollision(sf::RectangleShape other)
{
    if (entityRect.getGlobalBounds().intersects(other.getGlobalBounds()))
    {
        // Handle collision here
        return true;
    }
    else
    {
        return false;
    }
}

bool DetectCollision(sf::Sprite other)
{
    if (entityRect.getGlobalBounds().intersects(other.getGlobalBounds()))
    {
        // Handle collision here
        return true;
    }
    else
    {
        return false;
    }
}

Not sure why the FPS drops that much, is this way of detecting collisions heavy for the pc? I'm running a pretty high-end pc.


texts:
I am writing an Android game right now and I would need some help in the collision of the Pawns on screen. I figured I could run a for loop on the Player class with all Pawn objects on the screen checking whether or not Width*Height intersects with each other, but is there a more efficient way to do this?

And if you do it this way, many of the transparent pixel inside the rectangular area will also be considered as collision as well. Is there a way to check for collision between Bitmap on a Canvas that disregard transparent pixels? The class for player is below and the Pawn class uses the same method of display.

Class Player {
  private Resources res; // Used for referencing Bitmap from predefined location
  private Bounds bounds; // Class that holds the boundary of the screen
  private Bitmap image;
  private float x, y;
  private Matrix position;
  private int width, height;
  private float velocity_x, velocity_y;

  public Player (Resources resources, Bounds boundary) {
    res = resources;
    bounds = boundary;
    image = BitmapFactory.decodeResource(res, R.drawable.player);
    width = image.getWidth();
    height = image.getHeight();
    position = new Matrix();
    x = bounds.xMax / 2; // Initially puts the Player in the middle of screen
    y = bounds.yMax / 2;
    position.preTranslate(x,y);
  }
  public void draw(Canvas canvas) {
    canvas.drawBitmap(image, position, null);
  }
}


texts: Unity | Camera - Follow target with view port point's offset from center

texts:
Some additional remarks before I address the issue:

How Viewports work in Unity:

Whatever the dimensions of the screen's rect, the viewports coordinates are mapped in normalized coordinates, where 0 represents left and bottom, for x and y respectively, and 1 right and top, for x and y respectively (image below).

Follow a Target (Easy implementation for the sake of demonstration):

Consider this following simple algorithm to follow a target:

CameraFollowExample : MonoBehaviour
{
    public Transform target;
    public bool relativeToTarget;
    public Vector3 followOffset;

    private void LateUpdate()
    {
        if(target != null) FollowTarget();
    }

    private void FollowTarget()
    {
        transform.position = target.position + (relativeToTarget ? target.TransformDirection(followOffset) : followOffset);
        transform.Lookat(target);
    }
}

Issue:

The following works as expected, but the target will always be at the viewport's center ({ 0.0, 0.0 })

What I am trying to Achieve:

This is what I am trying to achieve: make camera follow a given target, with an additional offset from the viewport's center. This offset being additional to the following offset applied to the target.

So for example, if I define two ranged floats, centerX and centerY respectively, I'd like the camera to be positioned with an additional offset, so the defined offset is at the target. As an example, on the image below, I have centerX and centerY on { 0.2, 0.25 } respectively, so the target should be at that viewport's point.

Having a resulting (partial) script:

CameraFollowExample : MonoBehaviour
{
    public Transform target;
    public bool relativeToTarget;
    public Vector3 followOffset;
    [Range(0.0f, 1.0f)] public float centerX;
    [Range(0.0f, 1.0f)] public float centerY;

    private void LateUpdate()
    {
        if(target != null) FollowTarget();
    }

    private void FollowTarget()
    {
        Vector3 destination = target.position + (relativeToTarget ? target.TransformDirection(followOffset) : followOffset);
        transform.position = destination + GetCalculatedOffset();
        transform.Lookat(target);
    }

    private Vector3 GetCalculatedOffset()
    {
        // interpret the Vector { centerX, centerY } to return an offset.
        // return (interpretedOffset - target.position);
    }
}

What I have already tried:

Make the camera position to the destination plus an offset of the center [{centerX, centerY} - {0.5, 0.5}], the direction is ok, but obviously, the target is not positioned at the expected viewports' point coordinate.
Have a global vector that is the custom center point relative to the camera's transform and the nearPlane, and then make an offset between that point and the target, ignoring the z. The camera gets away from the target.

What I am not trying to achieve:

Something like following example (define an additional offset vector, and position the camera with the additional offset):

CameraFollowExample : MonoBehaviour
{
    public Transform target;
    public bool relativeToTarget;
    public Vector3 followOffset;
    public Vector3 additionalOffset;

    private void LateUpdate()
    {
        if(target != null) FollowTarget();
    }

    private void FollowTarget()
    {
        Vector3 destination = target.position + (relativeToTarget ? target.TransformDirection(followOffset) : followOffset);
        transform.position = destination + additionalOffset;
        transform.Lookat(target);
    }
}

I mean, this technically works, since the target won't be at the center of the viewport. But the intention is for the target to be positioned at the defined viewport's point.

Any additional information you may need, let me know. Thank you beforehand, and Happy New Year.


texts: Sliding DOOM style collision resolution against arbitrary 2D geometry

texts:
I've been working on a HTML5 canvas raycasting engine for the web browser, with the end goal of making a simple FPS game in the style of the early 90s. The engine sits somewhere between Wolfenstein 3D and Doom in terms of complexity and capabilities - there are fixed-height floors and ceilings, skies, and wall geometry made using line segments, which can be non-orthogonal.

Development was going fairly well until I started trying to implement a simple 2D collision system. The collision detection itself is not a problem - I've written collision and vector maths modules which I've tested and have confidence in. The issue is resolving the collision in an acceptable manner. What I'm trying to make is a basic collision resolution algorithm which will detect when the player collider (circle) is colliding with one or more walls (line segments), and resolve the collision so the player slides along the wall(s) they are colliding with. Basically I want the exact same collision behaviour as DOOM has.

Some googling around led me to the following tutorial:

http://peroxide.dk/papers/collision/collision.pdf

This seemed to describe a method for achieving the desired collision response in a robust and pleasing way, but after a couple of weeks of trying various approaches, mostly following this tutorial's method, I'm still no closer to having a working implementation.

Rather than asking for code-specific advice on one of my failed implementations, I'm here looking for guidance from someone experienced in this sort of programming. I need to learn "The Right Way" to approach the problem, from someone who has got similar systems working before, and knows how it's meant to be done.

Any help is sincerely appreciated.

Here is a stable build of the game from just after I got the first basic collision resolution system working:
http://188.226.167.230:346/raycaster.html

(Shrink your browser window to see the 2D map below the main game canvas. WASD and arrow keys, mouse support is dodgy at best, I think this build has 360 controller support but I can't remember.)


texts: How to do Decal Clipping with OpenGL using Depth Buffer comparison?

texts:
Basically I'm already drawing decals on top of various flat surfaces and that works great.

As soon as the decal approaches the edge of a surface, naturally it doesn't get clipped.

Is there a way to add simple clipping by comparing the value in stored depth buffer, with the depth value (Z) of the decal pixel to be written?

If the depth value about to be written is ~about the same (is within a range), the decal pixel gets drawn, otherwise discarded. Decals don't write to depth-buffer themselves.

Example scene:


texts: Phaser game is not registering collisions and input - but only on my machine

texts:
I was developing a game with Phaser and the Zenva Phaser Tutorial. I did some work on it last night, checked it was working, and went to bed. This morning, it isn't working! Input (either touch or mouse click) is not working, and the player no longer collides with the floor, but rather he sinks to the bottom.

Here is my game, and here is my git source. I have given a GitHub link, because I'm not receiving an error, and I can't pinpoint the issue.

Other users have confirmed that my game works, but when I run it, it is not the case.


texts: Things that make a game more interesting for kids

texts:
What makes a game more interesting or fun to play for children ages 8 to 14+?

Does the age of the consumer play an important role in his/her interest in the game?

What can I put in a game to make it more fun, educational, and interesting to play?


texts: 2D player controller moves to the left, but not to the right

texts:
I wrote a C# script to control a 2D player, but the script is not fully working. When I press the right arrow/d key to move the player is not moving in the right direction, but I have done the same exact thing for left key which works fine.The script shows no errors too.Kindly help me to solve the issue.The code is:

using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [SerializeField] private Rigidbody2D _rb2d;
    [SerializeField] private float _speed;
    [SerializeField] private float _jump;
    private static float _tempspeed;
    private static float _tempjump;
    private bool _isRight;
    private bool _isLeft;
    private bool _isSpace;

    private void Start()
    {
        _isLeft = false;
        _isRight = false;
        _isSpace = false;
        _speed = 5f;
        _jump = 7f;
        _tempjump = _jump;
        _tempspeed = _speed;
    }

    private void Update()
    {
        ReadInput();
    }

    private void FixedUpdate()
    {
        Move();
    }

    private void ReadInput()
    {
        if (UnityEngine.Input.GetKey("d") || UnityEngine.Input.GetKey("right"))
        {
            _isRight = true;
        }else {
            _isRight = false;
        }
        if (UnityEngine.Input.GetKey("a") || UnityEngine.Input.GetKey("left"))
        {
            _isLeft = true;
        }else {
            _isLeft = false;
        }
        if (UnityEngine.Input.GetKey("w") || UnityEngine.Input.GetKey("up"))
        {
            _isSpace = true;
        }else {
            _isSpace = false;
        }
    }

    private void Move()
    {
        Vector2 speedVectorRight=new Vector2(_tempspeed,_rb2d.velocity.y);
        Vector2 speedVectorLeft=new Vector2(-_tempspeed,_rb2d.velocity.y);
        Vector2 jumpVector=new Vector2(_rb2d.velocity.x,_tempjump);

        if (_isRight)
        {
            _rb2d.velocity = speedVectorRight;
        }else {
            speedVectorRight.x=0f;
            _rb2d.velocity = speedVectorRight;
        }
        if (_isLeft)
        {
            _rb2d.velocity = speedVectorLeft;
        }else {
            speedVectorLeft.x=0f;
            _rb2d.velocity = speedVectorLeft;
        }
        if (_isSpace)
        {
            _rb2d.velocity=jumpVector;
        }
    }

When I tried to print debug statements in different parts of if statements, they work fine. The problem in my observation is in :

if (_isRight)
        {
            _rb2d.velocity = speedVectorRight;
        }else {
            speedVectorRight.x=0f;
            _rb2d.velocity = speedVectorRight;
        }

The _rb2.velocity is not accepting speedVectorRight I guess.Thanks in advance!


texts:
After looking into optimization a bit, I have discovered (literally everywhere) that it seems to be a universally recognized sin to optimize a game too early.

I really don't understand this, would it not be incredibly difficult to change some of the core structures of the game at the end, rather than developing them the first time with performance in mind?

I get that waiting until the game is finished will tell you if you even need optimizations, but shouldn't you do it anyway, after all, it could widen the variety of devices the game could run on, which would increase the number of potential players.

Could someone explain to me why it's such a bad idea to optimize too early?