texts: How can I end my game when the right character statistics get to 0?

texts:
I'm creating a text-based RPG game.  In my game, a player has five different stats, which might decrease over time as the player does certain things.

public static int HP = 100;         //CHARACTER STARTING VITAL HIT POINTS
public static int food = 100;       //CHARACTER STARTING FOOD
public static int water = 100;      //CHARACTER STARTING WATER
public static int sanity = 100;     //CHARACTER MENTAL SANITY
public static int stamina = 100;    //CHARACTER STARTING STAMINA

I'm not sure how I can implement the logic to end the game when any of those stats reaches zero. My main game loop looks like this:

public static void main(String args[]){
    Map mainMap = new Map(10, 10);
    Character hero = new Character(mainMap);
    Main.start();

    while (true) {
        printmap(hero, mainMap);

        // Ask the player what direction to move, move the player.
        Character.moving();

        // ...
    }
}

The Character type has instances of all the players stats (as well as methods to increase or decrease them). How can I accomplish ending the game when a stat hits zero?


texts: 2D camera perspective projection from 3D coordinates -- HOW?

texts:
I am developing a camera for a 2D game with a top-down view that has depth.
It's almost a 3D camera. Basically, every object has a Z even though it is in 2D, and similarly to parallax layers their position, scale and rotation speed vary based on their Z.

I guess this would be a perspective projection.

But I am having trouble converting the objects' 3D coordinates into the 2D space of the screen so that everything has correct perspective and scale. I never learned matrices though I did dig the topic a bit today. I tried without using matrices thanks to the Wikipedia article on perspective projection but every attempt gave awkward results.

I'm using ActionScript 3 and Flash 11+ (Starling), where the screen coordinates work like this:
Left-handed coordinates system illustration

I can explain further what I did if you want to help me sort out what's wrong, or you can directly tell me how you would do it properly. In case you prefer the former, read on.

These are images from the Wikipedia article linked above, showing the formulas I used:

The long formula is greatly simplified because I believe a normal top-down 2D camera has no X/Y/Z rotation values (correct?). Then it becomes d = a - c. Still, I can't get it to work.

Maybe you could explain what numbers I should put in a(xyz), c(xyz), theta(xyz), and particularly, e(xyz)? I don't quite get how e is different than c in my case.
c.z is also an issue to me. If the Z of the camera's target object is 0, should the camera's Z be something like -600? ( = focal length of 600)
Whatever I do, it's wrong.

I only got it to work when I used arbitrary calculations that "looked" right, like most cameras with parallax layers seem to do, but that's fake! If I want objects to travel between Z layers I might as well do it right.


texts:
in libgdx there is a lot of audio classes but i haven't seem to of found anything relating to balancing sound in one speaker and or the other to get surround sound

say you check if an object is more to the left or to the right of the screen, is there anything or any classes relating to something like set speaker balance by percent like 50% would be default audio on the left and right side equally where you can change the balance, 50 - 100 percent is right side, 0 - 50 percent would be left

if this isn't possible, would it be possible two have 2 different audios (Left Explosion sound & Right Explosion sound) with each being 100 percent on the left or right side then change the volume percent of either one to get a surround sound feel?


texts: DX11 render 800x600 scene without a window

texts:
Normally I would create a hidden overlay window and render my DX scene into that, but I think it is possible to render without a window at all as well, is this true? The goal for me is to render on top of all running Windows applications without using a TOPMOST window.

Does someone know how this would approximately be achieved? Thanks!


texts:
I have tried to change the title with this source:

http://msdn.microsoft.com/en-us/library/ff966436.aspx

but this isn't working!? Help preciated!


texts:
I am busy working on a full solo project with no assistance from tutorials or guides. But I have created a monstrosity of an If statement. How could I clean this up and save on memory since I'm calling this in my Update() method and the game is for android?

the hp1 to hp5 are images used as health bars on the hud, I need to deactivate the ones that are not in use when the hp value decreases.

if(hp >= 81)
    {
        hp1.enabled = true;
        hp2.enabled = true;
        hp3.enabled = true;
        hp4.enabled = true;
        hp5.enabled = true;
    }
    else if(hp >= 61)
    {
        hp1.enabled = true;
        hp2.enabled = true;
        hp3.enabled = true;
        hp4.enabled = true;
        hp5.enabled = false;
    }
    else if(hp >= 41)
    {
        hp1.enabled = true;
        hp2.enabled = true;
        hp3.enabled = true;
        hp4.enabled = false;
        hp5.enabled = false;
    }
    else if (hp >= 21)
    {
        hp1.enabled = true;
        hp2.enabled = true;
        hp3.enabled = false;
        hp4.enabled = false;
        hp5.enabled = false;
    }
    else if (hp >= 1)
    {
        hp1.enabled = true;
        hp2.enabled = false;
        hp3.enabled = false;
        hp4.enabled = false;
        hp5.enabled = false;
    }
    else if(hp < 1)
    {
        hp1.enabled = false;
        hp2.enabled = false;
        hp3.enabled = false;
        hp4.enabled = false;
        hp5.enabled = false;
    }


texts: Algorithm for procedural city generation?

texts:
I am planning on making a (simple) procedural city generator using Java. I need ideas on whan algorithm to use for the layout, and the actual buildings. The city will mostly have skyscrapers, not really much complex stuff.

For the layout I already have a simple algorithm implemented:

Create a Map with java.awt.Point keys and Integer values. Fill it with all the points in the city's bounds with the value as -1 (unnassigned)
Shuffle the map, and assign the 1st 10 of the keys IDs (from 1-10)
Loop until all points have IDs:
Loop though all points:
Assign points next to an assigned point IDs of the point next to them, if 2 or more points border the point, then randomly choose which ID the point will get.
Stop looping #3-5 when all points have ids
You will end up with 10 random regions. Make roads bordering these regions.
Fill the inside of each region with a randomly spaced and randomly rotated grid

PROBLEM: This is not the fastest way to do it.

What algorithm should I use for the layout. And what should I use to make each building's design? I don't even know how I'm going to do that yet (fractals maybe). I just need some ideas, not actual code.


texts: Where should I place input/output console for server?

texts:
I'm developing a simple 2d online game and now I'm designing my server. The server will be run on linux vps and I need a way to communicate with it (for example to close it, and as it will be run on vps, simply closing terminal won't work). So I think there are 2 options:

1) Write 2 apllications - server which doesn't say anything and doesn't accept console input and the second application is console which sends commands to server (like exit, get online players etc).

2) Have 2 threads on the server appplication - one is the real server, the second thread will be used for cin and cout. However I'm not sure if this will work on vps...

Or maybe there is better aproach? What is the usual way of doing this?


texts: Using Standard Asset RBFP Controller for Universal Windows Platform

texts:
I was using the rigidbodyfirstperson controller, and it stopped working when I changed the build settings to UWP. Any body know the reason for this or how to solve it? Thanks...

Rik


texts: Retrieving shared video memory using SharpDX

texts:
I am trying to retrieve the total available video memory using SharpDX via DXGI, using the Description of the best available adapter.

The DedicatedVideoMemory is correct (1GB in my case), but the SharedSystemMemory value is wrong - and in fact is a negative number (-1073549312, in case that's of interest). The correct value should be 3072MB, as reported by my system information and when running the Microsoft VideoMemory_2012 example application (which also queries DXGI).

Any ideas what might be going on? Or is there another way to get this information using SharpDX? I need to scale some textures according to the available resources, and I need to know the shared component as well as the dedicated.


texts:
I'm implementing a basic skill and attribute system, though I'm having second thoughts about how I should go about it.

For example, I could use a Dictionary/HashMap which uses SkillType enums to represent keys, and integer values representing the values. But should I do this?

public class Skills
{
    public IDictionary<StatType, Int> skills; //StatType is enum, being the key; the int //is the value.

}

vs.

public class Skills
{
    public int LongBlade, Armor, Marksman; //...etc
}

I'd like to know the benefits of type safety here, as opposed to just using basic integers. Any recommendations?


texts: How does pixel shading work for ambient occlusion volumes?

texts:
I'm trying to understand the ambient occlusion technique described here, but I've trouble comprehending what exactly is the pixel shader doing.

Is the pixel shader invoked on points that belong to the surfaces of occlusion volumes? Can  anyone explain on a simple scene (like a cube corner seen from inside) how pixels get their AO values?


texts: Very simple open source games in various languages?

texts:
Are there any very simple open source games available just to demonstrate the basics of the programming techniques?  Preferably something which fits in to a couple hundred lines of actual code.  Specifically, I'm looking for an open source game written in Objective-C and Cocoa.

I would also appreciate one written in C.

All the projects that I find online are relatively complicated.


texts:
I am a mildly experienced programmer who has created several game engine templates and small 2D games in Java. I am currently expanding to 3D game engines and I am re-writing a previous engine to be more adaptive and Object-oriented.

My issue is, and has been periodically, that the objects are only sometimes rendered. This causes me to have to constantly re-run the program just to display any images.

I have not found any direct answers to this question, and nobody else seems to have this same issue (even when observing sources with the exact same code setup). The problem apparently lies within the render() method sometimes not properly creating or utilizing the Graphics & BufferStrategy objects while inside a thread called from the main method.

Here is some code of the 'Main' class:

public Main() {
    addScreenAndFrame();
}

public static void main(String[] args) {
     main = new Main();
     frame.add(main);
     thread =

new Thread(main);
         running = true;
         thread.start();
     }
public void run() {
    while (running) {
        render();
        tick();
    }
}
public void tick() {
    screen.tick();
}
public void render() {
    bs = getBufferStrategy();
    if (bs == null) {
        createBufferStrategy(3);
        return;
    }
    g = bs.getDrawGraphics();
    screen.paintComponent(g);
    g.dispose();
    bs.show();
}

Here is some code from the Screen class:

public Screen(int width, int height) {
    this.width = width;
    this.height = height;
    addEntities();
}
public void paintComponent(Graphics g) {
    p.render(g);
}
public void tick() {
    KeyInput.tick();
    renderInput();
}
public void addEntities() {
    p = new PolygonObject(new double[] {50,200,50}, new double[] {50,200, 200} );
}

And finally here is the PolygonObject class:

    public PolygonObject(double x[], double y[]) {
        Screen.polygonSize ++;
        polygon = new Polygon();
        for (int i=0; i < x.length; i++) {
            polygon.addPoint((int)x[i], (int)y[i]);
        }
    }
    public void render(Graphics g) {
        g.fillPolygon(polygon);
        g.setColor(Color.black);
        g.drawPolygon(polygon);
    }

I don't know why calling render() while within a thread would yield inconsistent results when drawing images to the screen. I have seen many source codes for game templates and tutorials with the exact same code without any rendering issues. The only way rendering works consistently is when I draw images with the paintComponent() method of the Canvas class outside of a thread which limits my program functionality and is poor design of a game engine.

I would like an explanation of this and any possible solutions. There is NO accurate way for me to build the game engine without the use of a thread in order to have controlled time-based functionality.


texts: Java - Best Implementation KeyListener For Games

texts:
I am working on a game using only the swing and awt packages. Note I can only use the default Java libs. Meaning I have to use KeyListener. I have imported KeyListener properly, however, it is still relatively buggy. Here is a snippet of my code.

p is for Player class, I am going to set x and y to private, however, this is for simplicity

public void keyPressed(KeyEvent e) {
    keys[e.getKeyCode()] = true;

    if(keys[KeyEvent.VK_W] || keys[KeyEvent.VK_UP]){
        p.y += 5;
    }

    if(keys[KeyEvent.VK_S] || keys[KeyEvent.VK_DOWN]){
        p.y -= 5;
    }

    if(keys[KeyEvent.VK_A] || keys[KeyEvent.VK_LEFT]){
        p.x += 5;
    }

    if(keys[KeyEvent.VK_D] || keys[KeyEvent.VK_RIGHT]){
        p.x -= 5;
    }
}

public void keyReleased(KeyEvent e) {
    keys[e.getKeyCode()] = false;
}

public void keyTyped(KeyEvent e) {
}

Sadly this code has a lag to it. Of a second... Also, the motion is not a fluid... However, I don't want you to fix my code. Rather, what other methods are more clean? As well, I have worked with engines, they all seem to have an: isDown, PressedOnce, Released(However, I know how to implement this), ect.


texts: Should I implement Entity Component System in all my projects?

texts:
I'm not here to ask for any specific code implementation, I'm here just to make my ideas clearer. But let me explain the situation:

I have already developed some little and amatorial game projects (never published tho) but I recently found some interesting articles about ECS and I began to read more about it. I found the whole ECS concept every interesting and I thought I could implement it in a very tiny game I'm working on in my free time.
The problem is: should I implement this pattern on a every little project with simple game mechanics and poor gameplay ?
The 2D game I'm working on will be entirely developed by me, so I do not actually need to make the code easier to mantain by other people. This game will basically have just 2 players, some weapons and a large variety of bullets and superpowers. No IA enemies, no vehicles, static and tiny maps and.. Just that.
It will have, of course, a simply physics system (just to make players fall and bullets move, for example), and a tiled but very little map which is editabile by players (destroying tiles).

So the point is: why should I actually write an ECS for such a basic game ? Do I really have any real advantage considering the game design ?
I mean, I know it is very good to make your code very flexible and easy to mantain even in the future, but I also know that this pattern was invented to avoid some limitations and the code duplication which the old hierarchical game structure provides, but this game doesn't have a wide hierarchical structure, as far as I can see.

I started coding it, but I discovered some aspects which, to be honest, scare me. Like having all the components talking to each other through a reference of their owner (the entity they are bound to), which as far as I know, is not very good to avoid cache misses.
The last thing is that I have the feeling that I won't write more than 2 components of the same type, and this would make the ECS less useful.

I know I don't have the whole ECS concept really clear in my mind, this is the first time I implement it, by the way, but I hope you got the point of my problem.


texts: Formula for three competing heroes, each has one they can beat and one they're beaten by

texts:
I am trying to design a game for a project I have, The main idea is:

3 Types of heroes
3 Stats per hero

There are no levels involved so the differences must be located on stats.

Fight logic - The logic of fight is that type1hero has good chances winning type2hero, type2hero has good chances type3hero and type3hero has good chances winning type1hero.

For over a week I am trying to find a stats based formula that will allow me to fix this but I can't, I was meddling with numbers yesterday and it was decent but I can't extract the formula out of it.

Could you please guide me or give me hints on how should I start creating formulas on a Non lvl game that fulfills the fight logic?


texts: A* Implementation Produces zig-zag in positive directions

texts:
I have an implementation of A* in Java. I followed this guide http://www.policyalmanac.org/games/aStarTutorial.htm.

But I noticed that the paths generated where the goal is in the positive X and Y direction, I get this zig-zag phenomenon.

Let me demonstrate with these two images (top left area is the origin [0,0]):

Here I generate a path where the goal is farther away from the origin than the start:

And here I generate a path where the goal is closer to the origin than the start:

I have tried to manipulate the heuristic algorithm I use, to no avail.

Here's the code:

public List<Vector3f> find(Vector3f startLocation, Vector3f goalLocation, NodeValidator validator) {
    start = nodes.get(grid.getNode(startLocation).index);
    goal = nodes.get(grid.getNode(goalLocation).index);

    if ( ! validator.validate(goal.node)) return null;

    open.clear();
    closed.clear();

    open.add(start);

    start.movementCost = 0;
    start.heuristic = 0;

    while(open.isEmpty() == false) {
        NodeProxy q = null;

        for(NodeProxy node : open) {
            if (q == null || node.getCost() < q.getCost()) {
                q = node;
            }
        }

        //did we get the goal?
        if (q == goal) {
            List<Vector3f> path = new ArrayList<Vector3f>();

            //get goal node
            NodeProxy nodeProxy = goal;
            while(nodeProxy != start && nodeProxy != null) {
                if (nodeProxy != null) {
                    path.add(nodeProxy.node.center);
                }

                if (nodeProxy.parent == null) {
                    break;
                }
                nodeProxy = nodeProxy.parent;
            }

            Collections.reverse(path);
            return path;
        }

        open.remove(q);
        closed.add(q);

        float g;
        for(Compass direction : Compass.values()) {
            Node n = q.node.neighbours.get(direction);
            if (n == null) continue;

            NodeProxy successor = nodes.get(n.index);

            g = direction.cost;

            if (validator.validate(successor.node) && closed.contains(successor) == false) {
                if ( ! open.contains(successor)) {
                    open.add(successor);
                    successor.movementCost = q.movementCost + g;
                    successor.heuristic = getHeuristic(successor.node, goal.node);
                    successor.parent = q;
                }else if (q.movementCost < successor.movementCost + g) {
                    successor.movementCost = q.movementCost + g;
                    successor.heuristic = getHeuristic(successor.node, goal.node);
                    successor.parent = q;
                }
            }

            closed.add(q);
        }
    }

    return null;
}

Some notes regarding the code: The validator object is simply an object tasked with checking if a node is "walkable".


texts: When attaching AI to a vehicle should I define all steps or try Line of Sight?

texts:
This problem is related to an intersection simulation I am building for university. I will try to make it as general as possible.

I am trying to assign AI to a vehicle using the JMonkeyEngine platform. AIGama_JmonkeyEngine explains that if you wish to create a car that follows a path you can define the path in steps. If there was no physics attached whatsoever then all you need to do is define the x,y,z values of where you want the object to appear in all subsequent steps. I am attaching the vehicleControl that implements jBullet. In this case the author mentions that I would need to define the steering and accelerating behaviors at each step.

I was trying to use ghost controls that represented waypoints and when on colliding the car would decide what to do next like stopping at a red light. This didn't work so well. Car doesn't face right.

public void update(float tpf) {
    Vector3f currentPos = aiVehicle.getPhysicsLocation();
    Vector3f baseforwardVector = currentPos.clone();
    Vector3f forwardVector;
    Vector3f subsVector;

    if (currentState == ObjectState.Running) {
        aiVehicle.accelerate(-800);
    } else if (currentState == ObjectState.Seeking) {

        baseforwardVector = baseforwardVector.normalize();
        forwardVector = aiVehicle.getForwardVector(baseforwardVector);
        subsVector = pointToSeek.subtract(currentPos.clone());
        System.out.printf("baseforwardVector: %f, %f, %f\n", baseforwardVector.x, baseforwardVector.y, baseforwardVector.z);
        System.out.printf("subsVector: %f, %f, %f\n", subsVector.x, subsVector.y, subsVector.z);
        System.out.printf("ForwardVector: %f, %f, %f\n", forwardVector.x, forwardVector.y, forwardVector.z);

        if (pointToSeek != null && pointToSeek.x + 3 >= currentPos.x && pointToSeek.x - 3 <= currentPos.x) {
            aiVehicle.steer(0.0f);
            aiVehicle.accelerate(-40);

        } else if (pointToSeek != null && pointToSeek.x > currentPos.x) {
            aiVehicle.steer(-0.5f);
            aiVehicle.accelerate(-40);
        } else if (pointToSeek != null && pointToSeek.x < currentPos.x) {
            aiVehicle.steer(0.5f);
            aiVehicle.accelerate(-40);
        }
    } else if (currentState == ObjectState.Stopped) {
        aiVehicle.accelerate(0);
        aiVehicle.brake(40);

    }
}


texts:
Learning & Implementing an ECS system for my game, I'm wondering how I am supposed to parallelize the systems on multiple threads. Different systems can't run at the same time (unless they operate on completely different set of components), so I guess the most common option is to run each system sequentially and parallelize the iteration they do on components, in a parallel_for fashion. The problem with this is that parallel_for assumes each iteration is self contained, which is not always true. In case an entity needs to access the component of another entity, and maybe modify it (very common in gameplay programming), we cannot really run a parallel_for as often we don't know what entities will want to access (through the system) what other entities.
How is this handled in ECS?


texts: How to convert screen to world coordinates while using gluLookAt / gluPerspective or similar matrix transforms?

texts:
I am just starting an adventure in looking under the hood of graphics for a game project I've been working on for a while, and I could use some guidance.

I am using Python/Kivy (though that is not part of the concern), and am trying to use projection and modelview matrices to perform screen-to-world coordinate conversion.   I am using something similar to gluLookAt and gluPerspective matrix transforms for those.

The issue I'm running into, is that the coordinates I get out of multiplying the mv and p matrices together and inverting them, then multiplying by NDC screen coords, the resulting coordinates are only either a fraction of a pixel away from the world position look_at is currently centered on, or a max of a few pixels +/- that point.

I know I'm missing something, and I would love if someone could help me understand.  I wrote a standalone example gist, and made a short youtube video showing what problem I'm having.

https://youtu.be/UxbWQO9e0NE
https://gist.github.com/spinningD20/951e49cb836f08c434a0e9ab0e90c766

The code in question, is the screen_to_world method in the gist, when using the camera_look_at_perspective method to create the MVP, which I will list here:

p = Matrix()
p.perspective(90., 16 / 9, 1, 1000)

self.canvas['projection_mat'] = p
self.canvas['modelview_mat'] = Matrix().look_at(w_x, w_y - 30, self.camera_scale * 350, w_x, w_y, 0, 0, 1, 0)

That is for creating the matrices, and...

def screen_to_world(self, x, y):
    proj = self.canvas['projection_mat']
    model = self.canvas['modelview_mat']

    # get the inverse of the current matrices, MVP
    m = Matrix().multiply(proj).multiply(model)
    inverse = m.inverse()
    w, h = self.size

    # normalize pos in window
    norm_x = x / w * 2.0 - 1.0
    norm_y = y / h * 2.0 - 1.0

    p = inverse.transform_point(norm_x, norm_y, 0)
    # print('convert_from_screen_to_world', x, y, p)
    return p[:2]

Was originally written to convert coordinates when using the previous projection matrix built using translate and creating a clip space (also included in the example).

While the implementation appears to be specific to Kivy, it is just a modelview matrix and projection matrix being used, and their Matrix.transform_point method used above is the same as multiplying a vec against the matrix in question.  It can also include what appears to be the W part of a vec4, which I have also experimented with, with no apparent change.

Here is a screenshot of the standalone example, painting where I have moved the mouse on the screen (red) and where the resulting world coordinate ends up being (green).  The goal is for the converted coordinates in the world to fall directly under the red.


texts: Unity 5: Check if an object's collider contains the mouse click point

texts:
I am building a 2D turn-based RPG battle scene with Unity 5. The enemies are represented as 2D sprites with box colliders. In my script, the relevant enemy class is defined as:

public class EnemyView : MonoBehaviour {

    public SpriteRenderer _renderer;
    public BoxCollider2D _collider;

    void Awake() {
        _renderer = gameObject.GetComponent<SpriteRenderer>();
        _collider = gameObject.GetComponent<BoxCollider2D> ();
    }
}

And I have the following code grouping the enemy sprites together:

public class MainGUIView : MonoBehaviour {
    public EnemyView[] _enemyViews;
}

When a player clicks on an enemy, I would like to know the index of that enemy within the _enemyViews array. I thought of implementing this within EnemyView class but that class has no information about its index, so I am thinking of implementing OnMouseDown() within MainGUIView where I could iterate through _enemyViews to find the one whose collider contains the mouse click point, but I don't know how to write the code. Anyone can point me to some useful code snippet?


texts: How does one avoid the "staircase effect" in pixel art motion?

texts:
I am rendering sprites at exact pixel coordinates to avoid the blurring effect caused by antialiasing (the sprites are pixel-art and would look awful if filtered). However, since the movement of the objects involves variable velocity, gravity, and physical interactions, the trajectory is computed with subpixel precision.

At large enough screenspace velocities (vΔt larger than 2 or 3 pixels) this works very well. However, when velocity is small, a noticeable staircase effect can appear, especially along diagonal lines. This is no longer a problem at very slow screenspace velocities (v << 1 pixel per second) so I am only looking for a solution for intermediate velocity values.

On the left is the plotted trajectory for a large velocity, obtained by simple rounding of the object coordinates. In the middle you can see what happens when velocity becomes smaller, and the staircase effect I am talking about. On the right, the locus of the trajectory I would like to get.

I am interested in algorithm ideas to filter the trajectory in order to minimise the aliasing, while retaining the original behaviour at large and small velocities. I have access to Δt, instant position and velocity, as well as an arbitrary number of previous values, but since it is a realtime simulation, I do not know about future values (though if necessary, an estimation could be extrapolated under certain assumptions). Note that because of the physics simulation, sudden direction changes can also happen.


texts:
I am converting a particle emitter from 2d to 3d.

In the 2d system the original coder used a random angle variance and added it to the angle.  So it would be something like:

thisAngle = emitterAngle + angleVariance * RANDOM_MINUS_1_TO_1();

I want to do the same thing in 3d using an emission vector (vec3) and again an angleVariance.  My specific variance for this particle will still be angleVariance * RANDOM_MINUS_1_TO_1().  But how do I apply that angle a 3d vector so that the new vector could be any value X degrees off of center.  So if the original vector is straight up (0,1,0) the new vector could be off in the X or the Z and still normalized to 1.

Any hints?  I have all the matrix and vector functions at my disposal.

=====

Thanks to nathan I was able to write this code. Not sure if I've over complicated it somewhere. Once I test it I'll checkmark his answer:

    // first pick a random Z from [cos(angleVariance), 1]
    GLfloat varianceZ = [self randomFloatBetween:myCosf(angleVariance) andLargerFloat:1.0];
    // and a random angle for the azimuth
    GLfloat rndA = [self randomFloatBetween:0.0 andLargerFloat:360.0];

    // then calculate the X & Y to make this a vector off of the +Z axis with a max width of angleVariance
    GLfloat varianceX = sqrt(1 - varianceZ*varianceZ) * myCosf(rndA); // my functions input degrees not radians
    GLfloat varianceY = sqrt(1 - varianceZ*varianceZ) * mySinf(rndA);

Up to here the above code works.  It makes a variance angle off center but it is aligned to the +z axis.  The next part is supposed to rotate/transform the angle to my emissionVector angle so it's a variance off of that.  But so far this part isn't working.

    // next find an axis to rotate the point around to put it in line with the emmissionVector
    vec3 rotationAxis = normalizeVec3(crossProduct(vec3Make(0.0, 0.0, 1.0), emissionVector));
    GLfloat rotationAngle = acos(degreesToRadians(emissionVector.z));

    // make a quaternion out of the rotation axis and angle
    vec4 q = quaternionVector(rotationAxis, rotationAngle);
    // turn the quaternion into a matrix
    mat4 rotMat4;
    mat3 rotMat3;
    matrixQuaternion(q, rotMat4);
    getMat3FromMat4(rotMat4, rotMat3);
    // multiply the variance vector by the matrix to get a resulting vector with the variance added
    vector = matrixTransformVec3(rotMat3, vec3Make(varianceX, varianceY, varianceZ));

=====

The above code doesn't appear to be correct. I'm still working on the solution and will fix the above code when I get it working.


texts: What GPU culling techniques are appropriate for voxel spheres other than octrees?

texts:
I'm creating a dynamic smooth-voxel based world in the shape of a sphere. Right now my current approach is to spherize a cube, generate voxel terrain on each of the six patches, and then use octrees to cull the data further.

Octree's are best served with cubes. Is there a better system for storing/accessing data in a sphere? I've heard some talk of Octree's not being the best way to store voxel data, even for cube worlds. How can this be? What would be better? A Hash Table?  Surely multidimensional arrays wouldn't be faster? Perhaps it's just more of a design decision than performance? As in, maybe someone didn't like chunks popping in so they would rather load individual rows and columns?

If it matters, I'm probably going to keep relevant geometry in GPU memory and stream in the surrounding area over time as the player gets closer to it from main memory. I bring this up because I'm really not sure if GPU memory benefits from any particular structure. All I really know is that the parallel powers of the GPU are, well, unparalleled (I had to). How can I tap into that?


texts:
I'm having an issue with my tilemap renderer, with small maps (like 40*40 tiles) it works fine but with maps that have 400*400 tiles the framerate becomes really slow when I try to move the camera.

Here are my rendering methods

/// Renders the map
void Map::Map::render(sf::RenderWindow& window)
{
    for (auto c : m_tiles)
    {
        for (Tile& tile : c)
        {
            m_renderer.render(tile);
        }
    }
}

And for the TileRenderer

void Renderer::TileRenderer::render(const Map::Tile& tile) const
{
    try
    {
        if (m_previousType != tile.getType())
            m_sprite.setTextureRect(getTypeTextureRect(tile.getType()));

        m_sprite.setPosition(tile.getAbsolutePosition());

        m_renderWindow.draw(m_sprite);
        m_previousType = tile.getType();
    }
    catch (ETileTypeUndefined e)
    {
        Logger::getInstance().log(e.what());
    }
}

Any idea to solve that poor framerate ?
It doesn't seems to be a memory issue.
Visual Studio debugger tells me that external code spend a lot of time in the renderer's render function (calls to sf::RenderWindow::draw(sf::Drawable) I guess).


texts:
I'm developing a lighting system for my voxel game, and I have to send multiple (alot, say up to 200) lights to my shader program. Those lights contain the following data:

Position (vec3)
Color (vec3)
Radius (float)
Strength (float)

What is the most efficient way to send alof of those light structs to my shaders? I would like it to work with lower versions of OpenGL, like 2.1.


texts: There is something wrong (2D car sprite changes after moving right or left)

texts:
this is car controller

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

    public class CarController : MonoBehaviour
    {
        public float acceleration;
        public float steering;
        private Rigidbody2D rb;

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

        void FixedUpdate()
        {
            float h = -Input.GetAxis("Horizontal");
            float v = Input.GetAxis("Vertical");

            Vector2 speed = transform.up * (v * acceleration);
            rb.AddForce(speed);

            float direction = Vector2.Dot(rb.velocity, rb.GetRelativeVector(Vector2.up));
            if (direction >= 0.0f)
            {
                rb.rotation += h * steering * (rb.velocity.magnitude / 5.0f);
                //rb.AddTorque((h * steering) * (rb.velocity.magnitude / 10.0f));
            }
            else
            {
                rb.rotation -= h * steering * (rb.velocity.magnitude / 5.0f);
                //rb.AddTorque((-h * steering) * (rb.velocity.magnitude / 10.0f));
            }

            Vector2 forward = new Vector2(0.0f, 0.5f);
            float steeringRightAngle;
            if (rb.angularVelocity > 0)
            {
                steeringRightAngle = -90;
            }
            else
            {
                steeringRightAngle = 90;
            }

            Vector2 rightAngleFromForward = Quaternion.AngleAxis(steeringRightAngle, Vector3.forward) * forward;
            Debug.DrawLine((Vector3)rb.position, (Vector3)rb.GetRelativePoint(rightAngleFromForward), Color.green);

            float driftForce = Vector2.Dot(rb.velocity, rb.GetRelativeVector(rightAngleFromForward.normalized));

            Vector2 relativeForce = (rightAngleFromForward.normalized * -1.0f) * (driftForce * 10.0f);

            Debug.DrawLine((Vector3)rb.position, (Vector3)rb.GetRelativePoint(relativeForce), Color.red);

            rb.AddForce(rb.GetRelativeVector(relativeForce));
        }

    }

and this is camera controller

using UnityEngine;

public class CameraController : MonoBehaviour {

    public Transform player;
    public Vector3 offset;

    void Update()
    {
        transform.position = new Vector3(offset.x + offset.x, player.position.y + offset.y, offset.z); // Camera follows the player with specified offset position
    }
}


texts: Is there a way to build asset bundle that exclude texture2d from an image?

texts: In unity 4.x, I can archive this because I can select my resource type directly as Sprite variable before putting it into the bundle via BuildAssetBundle. However, in Unity 5.x, I need to put the name in the Editor can I cannot choose my resource type as Sprite only in the Editor. When I make the bundle, bundle will have both Texture2D and Sprite which I only want Sprite to save the memory and disk space. The bundle will exclude Texture2D only if I create the bundle from Prefab not the image itself but I want only the raw image. What should I do?


texts: Calling out stored variables in class all at once?

texts:
I have a class PlayerStatistics that doesn't sit on a monobehaviour:

public class PlayerStatistics
{
    public int currentHealth;
    public int maxHealth;
    public bool hasWeapon;
    public Collider weapon;
    public Transform weaponChild;
    public Animator weaponAnim;
    public GameObject droppedWeaponObject;
    public DialogueManager DM;
}

and I have PlayerController script that contains those variables shown above as well as a Save and Load function:

    public int currentHealth;
    public int maxHealth = 100;
    public bool hasWeapon;
    public Collider weapon;
    public Transform weaponChild;
    public Animator weaponAnim;
    public GameObject droppedWeaponObject;
    public DialogueManager DM;

    public PlayerStatistics localPlayerData = new PlayerStatistics();
    public void LoadPlayer()
    {
        localPlayerData = GlobalControl.Instance.savedPlayerData;
    }
    public void SavePlayer()
    {
        GlobalControl.Instance.savedPlayerData = localPlayerData;
    }

And a GlobalControl to store values for said variables across scenes:

    public class GlobalControl : MonoBehaviour {
    public static GlobalControl Instance;
    public string savedJson;
    public PlayerStatistics savedPlayerData = new PlayerStatistics();
    void Awake()
    {
        if (Instance == null)
        {
            DontDestroyOnLoad(gameObject);
            Instance = this;
        }
        else if (Instance != this)
        {
            Destroy(gameObject);
        }
    }
    private void Update()
    {
        Debug.Log(savedJson);
    }
}

I can get each value by doing:

GlobalControl.Instance.savedPlayerData.<variablehere> = variableNameHere;

but the question is, if I have a lot variables, how do I get all of it at once. I followed a tutorial that thought me this and it was like:

GlobalControl.Instance.savedPlayerData = localPlayerData;


texts:
I have a conceptual question:
In the case of Tile Map, each block has the information from the enemies who are going about it. But what if some of these enemies are far greater than the block?
I have to have the same element in each of the information blocks?
And updating the position must clear each block?
If I have large and small enemies, it means that each block will have a list of enemies?

Now, in the case of Voxel Map:
In Minecraft, for example, its character and most enemies x and z dimensions is smaller than one block, but its height (y) is greater than one block.
This means that these elements will record information in two blocks? and in the case of a "Gast," which is much larger?

I'm using Google Translate, so sorry if my english is very bad.
Thanks in advance.


texts: Gamemaker - Maintain relative position between objects during rotation

texts:
I have a large object and a small object - the small object updates its x and y position every step to match the x and y of the larger object. It is easy to keep it in the same position on the larger object without any rotation, as follows (in this instance, slightly above and to the right of the centre of the larger object, here called Owner:

x = Owner.x + 50
y = Owner.y - 50

However, this all goes pearshaped if the larger object is rotated from its sprite's initial position!

How can I maintain the relative position of the two objects even when rotated?


texts:
I have 2 quarternians (Q1 & Q2), I'd like to apply a coefficient to each Quaternian, where the sum of both coefficients = 1.  As far as I'm aware, multiplying a quaternian by another is equivalent to adding them together.

In linear mathematics, this would as simple as:

AC + B(1-C) = Y

and

A.C = S, B*(1-C) = T

so

S + T = Y

I would be lerping C from 0 to 1.  Q1 is dynamic, while Q2 is a fixed target, so for this reason, I don't think Quarternian.Lerp is a practical solution.

How do I mutliply a quaternian by a coefficient, as Q1 * Q1 is equivalent to adding them together, which would be suitable for calculating the final product, ie S+T.

I'm unsure how to go about this.


texts: Closest distance from 3D point to vector line

texts:
First let's have a look at my little drawing:

I have an origin point p1 defined by x, y and z co-ordinates, and a vector v given by x, y and z magnitude.

I also have an arbitrary point, p2, given by x, y and z co-ordinates, in the direction of the vector v from the origin point.

I need to calculate the closest distance d from the point p2 to the line determined by the vector v. Put simply, I have no idea how to do this.


texts: Sorting armor sprites over body sprites in 3D

texts:
I'd like to use sprites for my characters in a 3D game world, but I'm having issues getting them to cooperate.

I want to have my characters to have outfit/appearance customization options, and so to me the solution is to sprite my characters as individual pieces (torso, head, upper arm, forearm, hand, etc) and then animate those pieces within unity. The armor and other customization objects would then be parented to a body part, rendering over top of the body and moving along with it. Such a design would allow me to essentially drag-n-drop different armor pieces without any extra work required to make them fit, so long as the sprites themselves line up correctly.

However, when looking at the character from an odd angle, the sprite ordering goes out the window. I understand this is due to z-sorting, and to try to combat this, i tried editing the sort order so that armor always appears on top of the body. The problem with this is that the armor of characters in the background would then render over the body of characters in the foreground.

Does anyone have a solution that could work for my situation?


texts: Stitching multiple meshes and aligning vertices

texts:
I am generating a map in unity, and i am stuck with a specific issue.

Due to the 64xxxk vertices restriction on unity I need to generate a map in sections.

I generate a noisemap of x times the 240x240 as seen below:

I then generate 9 tiles, and i grab the height from the noise map, based on the position of the tile, but for some reason the edges does not align properly.

The spacing is correct, if you view it from top you will see they fit snug.

I believe this could be due normalizing, but i am not sure.


texts: How to create polygonal or elliptical colliders by python tkinter?

texts:
I am developing a primitive game by python tkinter (I use canvas). It's not a big project. It's only my own self-challenge to create a game using only tkinter and standard python libraries.
My problem is colliders. I need to detect collisions of game objects. First I used a circle collider (it's easy). But using only circles in a game is not good, so I decided to use polygonal or elliptical colliders, but I don't know how to do it without external libraries such as pygame. Could anyone help me?

My question shorter:

How to detect polygons' or ellipses' collisions in python tkinter canvas using only standard libraries?

P.S. And how to detect collisions of an inclined rectangle?


texts: SDL - Limiting loop with timer? Not polling

texts:
I am using SDL/Glew to create an engine for a game I want to make. I am trying to set a constant framerate of like around 60 (once every 17ish ms). I don't know the best way to do this so I do attempted to do it with a timer.

//Main Loop
int EngineLoop(int interval, CEngine* engine)
{
    Input->Poll();
}
//---------

void CEngine::Start()
{
    _running = true;

    SDL_AddTimer(17, (SDL_TimerCallback)EngineLoop, this);
}

The input poll is this:

void CInput::Poll()
{
    SDL_Event evnt;

    while (SDL_PollEvent(&evnt))
    {
        switch (evnt.type)
        {
        case SDL_MOUSEMOTION:
            *(Rect*)(&MousePosition) = Rect(evnt.motion.x, evnt.motion.y);
            *(Rect*)(&MouseDelta)    = Rect(evnt.motion.xrel, evnt.motion.yrel);

            break;

        case SDL_MOUSEBUTTONDOWN:
            _mouseButtons[evnt.button.button - 1] = true;
            break;

        case SDL_MOUSEBUTTONUP:
            _mouseButtons[evnt.button.button - 1] = false;
            break;
        }
    }
}

This system works perfectly when I put it in some random class function to pump as much as it'd like. But when I introduced the timer, nothing works, no input is taken and the window freezes up. Is it because I am not Polling the events quick enough or?

I tried using a separate timer function that called the class function to poll the input because maybe having it on a different thread is the reason, that didn't work either.

So why didn't this work?
What other approach should I take if necessary?


texts: how to 'Scale up' my procedurally generated island/continent without losing its uniqueness?

texts:
Currently I am trying to make a procedural terrain generator. When I first started creating my terrain generator I decided to use a radial mask to generate my islands/continents like so:

But as time went along, I decided that these islands were way too small and I needed the islands to be much larger almost like continents than islands. So what I did was simply make the radial mask bigger. Which did overall result in bigger islands but my islands were now very much 'centered-based' with each island generating roughly the same except for the very outer extremities:

Here is the code I used to generate the procedural island. I included a comment on what value I changed to make the island larger. I used Libnoise for the perlin noise.

 void createRadiIsland(int centerX, int centerY)
{
    Perlin perlin = new Perlin();
    perlin.OctaveCount = 8;
    perlin.Frequency = 0.1;
    int seed = 50;
    float BiasX = 7f;
    float BiasY = 7f;
    for (int x = 0; x < grid.columns; x++)
    {
        for (int y = 0; y < grid.rows; y++)
        {

            float distanceX = (centerX - x) * (centerX - x);
            float distanceY = (centerY - y) * (centerY - y);

            float distanceToCenter = Mathf.Sqrt(distanceX * BiasX + distanceY * BiasY);
            distanceToCenter = distanceToCenter / 500; //<-- larger the value the bigger the island
            grid.FindTile(x, y).elevation = Mathf.RoundToInt(((float)perlin.GetValue(x - 0.98 + seed, y - 0.98 + seed, .1) - distanceToCenter * 10));

        }

    }
}

How should I modify my code so that it generates islands/continents that have the general uniqueness of the first island but at a much greater scale? Would I even be able to use a mask anymore? Would I have to use a completely new approach to generating my terrain?

side note:

I thought about solving my problem by using multiple radial gradients instead of just one but I am afraid that it will end up making my islands too blobby looking and not very realistic. Is that true?


texts: What is the process for getting a dev-kit for Xbox 360 to allow native coding

texts:
I'm curious about the process of getting a Xbox 360 dev-kit.

What are the requirements? Do you have to have a track record in game development. Can indie gamers get one. How much does it cost? Is there special hardware?


texts:
I own the servers of hokuco.com, I am wondering why my test build(not a development build) is not working in webgl I tried a test run as a .exe and it works fine. here is the url to my webgl project, can you determine what is wrong?
http://hokuco.com/test/index.html
(no files on my server are blocked, feel free to view the .htacess, js and other files) the screen is black and nothing is happening.
.htacess:

Options +FollowSymLinks
RewriteEngine on

RewriteCond %{HTTP:Accept-encoding} gzip
RewriteRule (.*)Release(.*)\.js $1Compressed$2\.jsgz [L]
RewriteRule (.*)Release(.*)\.data $1Compressed$2\.datagz [L]
RewriteRule (.*)Release(.*)\.mem $1Compressed$2\.memgz [L]
RewriteRule (.*)Release(.*)\.unity3d $1Compressed$2\.unity3dgz [L]
AddEncoding gzip .jsgz
AddEncoding gzip .datagz
AddEncoding gzip .memgz
AddEncoding gzip .unity3dgz

all my js files seem to be blocked.(but not jsgz...)


texts: Was C++ designed for speed, and is it better to not use high level features when teaming with inexperienced programmers?

texts:
I have read some optimisation guide for C++, and it seems it requires more knowledge to have a fast C++ code, than using C++ without the high level features of C++ (classes, templates, inheritance, etc.).

C++ is a powerful language, and will be the one used in game programming for a long time, and is still fast because it is a C subset, but as John Carmack said, it has to be used correctly: when dealing with programmers who can't guess alone how to make fast C++ code, isn't it a good idea to force them not to use high level features which can me more delicate to optimise ?

I know compilers do a very good job at optimizing the code they are being given, but they can't change it, or do they compilers that feature some sort of warnings that encourages a good use of OOP, or can compilers automatically optimize OOP code even if it is a slow one ?

EDIT:
I'm not bashing C++ high level features bere, I'm just talking about some of the very high level stuff like multiple inheritance and abstract classes.
Classes are awesome when just compared to struct's, but multiple inheritance is not that much a universal solution to all software problems.


texts: How to create a texture SRV with different sRGB format from a render target in DX11?

texts:
Is it possible to bind a texture with a different format as render target and as shader resource view?
Specifically with a different _SRGB suffix. My goal is to render a shader into an R8G8B8A8_UNORM texture but read the render target in another shader as R8G8B8A8_UNORM_SRGB, or the other way around. Basically controlling on the read and write side whether automatic sRGB conversion should happen. There is no window or swap chain involved.
So far, I get an invalid args exception when I try to create a texture view with a different format. I am using the Stride game engine set to Directx 11 graphics API, which uses SharpDX.


texts:
I have an "Item" class here that is used to create items.

public class Item {
    private String name;
    private int id;
    private int worth;

    //constructor
    Item(String _name, int _id, int _worth) {
        name = _name;
        id = _id;
        worth = _worth;
    }

    public String getName() {
        return name;
    }
}

This works fine and dandy.. but I don't know how to give them unique ID's, I thought about using

private static Item[] items;

and then when they're created add them to this array, but is that the only way? Also where do I put my code to initialize all the various items in the game? Should it be in the main method, or have a loader of some sort, or have them declared straight away in the Item class using

private static Item apple = new Item("Apple",0,3);

?


texts: Scene2D set table cell size in percentage of tables ´s size

texts:
Is it somehow possible to set Scene2D table cell´s size in percentage of the table?

I would like to have orientation independent menu, with buttons filling let´s say 75% percent of the screen, and also to respond on window resizing (desktop version). I have tried several methods, for example using Value

table.add(button).width(Value.percentWidth(.75F));

but when value.get(actor) is called inside cell, it is supplied with inner button actor not its container (table).

I have also tried to set it in fixed fashion

table.add(button).width(Value.percentWidth(.75F).get(table));

This works fine, but since I set pixel value insted of Value object it is not recalculated upon resizing.

Is there any way to achieve this?


texts: How can I efficiently render a large, zoomable world map?

texts:
We are looking to develop a grand strategy PC game in Unity with a world map similar in scale to Crusader Kings 2 and Europa 4.

We want to add more details to the map so that we can stand out visually, but we are worried that such a large zoom-able map, rendered in 3D, will cause performance issues.

How can we deal with efficiency problems related to rendering such a large map at various levels of zoom?


texts: Make a variable go down as another goes up?

texts:
I am making a JavaScript game called "Spoop: The Clicker", and I have a variable shown by text:

stroke("blue");
fill("purple");
textSize(30);
text("Spoop Cash: §" + spoopCash, 130, 10);

This is inside the draw loop, as it is always shown.

The thing is, I need textSize to be set shrink as my other variable spoopCash increases. How could I do that? If you can, please include a way to stop it from going too small (such as size 10 being the smallest allowed.)


texts:
Children learn through play, which by it's core nature is subversive. In digital games we can enforce and feedback any arbitrary rules and do not require "conceptual rules" like don't step outside the white lines.
Have we started using tutorials as a crutch rather than keeping our mechanics consistent and self-explanatory?

So I was listening to Another Castle interview the extremly interesting Eric Zimmerman. They were talking about the subverssive nature of play when my brain started drifting to tutorials, thinking about Limbo. Then I realised that not once on Glo did we ask, do we need tutorials?
Now I know the indie and art games scene has been promoting this concept of subversive play for a long time but I ask you how many developers question the need for a tutorial?
- Blog Post


texts: Recursive dungeon maps as represented by an elastic 2d array

texts:
I came up with a method for recursively generating simple dungeon maps by starting with one room and recursively connecting new adjacent rooms randomly to it.

Maps are represented as two dimensional arrays where each cell contains a value of 0-15. 0 represents no room while each direction is represented by north=1, east=2, south=4, west=8.

I wanted to start with a single non room ([[0]]) and then expand the 2d array as necessary to fit the generated map. The difficulty I face with this tree like recursion is that if the arrays have to be unshifted to add rows and columns to the left and top of the map, I have to adjust the current position of the function, what row and column it is at. This makes it so that separate branches are not aware of array index adjustments from other branches, only their child functions will know because they have the adjusted position passed to them as their row and column arguments.

Is there a way to do this? I tried storing row and column offset values outside of the recursion, but it did not work for some reason.


texts: I'm new to making minecraft mods and I'm wondering what I need to do to get started.


texts: Bounding Box not rotating based on draw rotation (Java)

texts:
In the process of developing a 2D game and am having some issues with translating coordinates on rotation. The object being rotated is a sword that is attached to the player. The player currently points towards a Point (mouse pointer). I am having no problems drawing the rotation, but am a bit confused on how to update the local coordinates so that the bounding box will follow also, around the player.

The weapon (coordinates) is just stuck on the left side of the player(invisible), but the drawing of the weapon is rotating around the player. The bounding box is working fine, but who wants invisible collision detection. It basically just isn't following the draw rotation.

Here is my basic draw implementation for rotating this weapon around the player.

WEAPON CLASS:

/**
* Updates child weapon
*/
public void Update(Point mp)
{
    this.boundingBox = new BoundingBox(startX,startY,width,height);
}

/**
 * Draws weapon to player
 */
public void DrawTo(Graphics2D g2d,Player p)
{
   AffineTransform backup = g2d.getTransform();
   AffineTransform trans = new AffineTransform();
   trans.rotate(Math.toRadians(getRotation()), p.getCenterX(), p.getCenterY() );
   g2d.transform( trans );
   g2d.drawImage(this.getImg(), startX, startY,null);
   g2d.setTransform( backup );
}

GAME LOOP:

/**
 * Player collision with weapons
 */
for(int l = 0; l < weaponManager.getDroppedWeapons().size(); l++)
{
    Weapon w  = this.weaponManager.getDroppedWeapons().get(l);

    if(player.Collision(w))
    {
        //If player already has a weapon, update that weapons position, add others to list that are picked up later
        if(player.getWeaponEquipStatus() == true)
        {
            //Sets the picked up weapon to the left side of the player
            player.getCurrentWeapon().setX(player.getX()-player.getCurrentWeapon().getWidth());
            player.getCurrentWeapon().setY(player.getY()+((player.getHeight()-player.getCurrentWeapon().getHeight())/2));
        }
        else if(player.getWeaponEquipStatus() == false)
        {
            player.setCurrentWeapon(w);
            w.isPickedUp = true;
        }
    }
}

I am aware of the AfflineTransform's getTranslateX and Y() methods.  I have tried assigning these returned values to my x and y weapon values in the update method, but that is definitely not the solution.

Main issue: weapon coordinates aren't rotating, but the drawing is successful.

If anyone has any advice on where to start, based on my problem, it would be greatly appreciated.


texts:
I'm searching any way to render with ffmpeg, an opengl texture that contains the video frame.

Actually, I am not good with ffmpeg... Is there any library/documentation or something?
How can I render a video with ffmpeg to opengl?

Thanks


texts: Efficiently separating Read/Compute/Write steps for concurrent processing of entities in Entity/Component systems

texts:
Setup

I have an entity-component architecture where Entities can have a set of attributes (which are pure data with no behavior) and there exist systems that run the entity logic which act on that data. Essentially, in somewhat pseudo-code:

Entity
{
    id;
    map<id_type, Attribute> attributes;
}

System
{
    update();
    vector<Entity> entities;
}

A system that just moves along all entities at a constant rate might be

MovementSystem extends System
{
   update()
   {
      for each entity in entities
        position = entity.attributes["position"];
        position += vec3(1,1,1);
   }
}

Essentially, I'm trying to parallelise update() as efficiently as possible. This can be done by running entire systems in parallel, or by giving each update() of one system a couple of components so different threads can execute the update of the same system, but for a different subset of entities registered with that system.

Problem

In the case of the shown MovementSystem, parallelization is trivial. Since entities don't depend on each other, and don't modify shared data, we could just move all entities in parallel.

However, these systems sometimes require that entities interact with (read/write data from/to) each other, sometimes within the same system, but often between different systems that depend on each other.

For example, in a physics system sometimes entities may interact with each other. Two objects collide, their positions, velocities and other attributes are read from them, are updated, and then the updated attributes are written back to both entities.

And before the rendering system in the engine can start rendering entities, it has to wait for other systems to complete execution to ensure that all relevant attributes are what they need to be.

If we try to blindly parallelize this, it will lead to classical race conditions where different systems may read and modify data at the same time.

Ideally, there would exist a solution where all systems may read data from any entities it wishes to, without having to worry about other systems modifying that same data at the same time, and without having the programmer care about properly ordering the execution and parallelization of these systems manually (which may sometimes not even be possible).

In a basic implementation, this could be achieved by just putting all data reads and writes in critical sections (guarding them with mutexes). But this induces a large amount of runtime overhead and is probably not suitable for performance sensitive applications.

Solution?

In my thinking, a possible solution would be a system where reading/updating and writing of data is separated, so that in one expensive phase, systems only read data and compute what they need to compute, somehow cache the results, and then write all the changed data back to the target entities in a separate writing pass. All systems would act on the data in the state that it was in at the beginning of the frame, and then before the end of the frame, when all systems have finished updating, a serialized writing pass happens where the cached results from all the different systems are iterated through and written back to the target entities.

This is based on the (maybe wrong?) idea that the easy parallelization win could be big enough to outdo the cost (both in terms of runtime performance as well a code overhead) of the result caching and the writing pass.

The Question

How might such a system be implemented to achieve optimal performance? What are the implementation details of such a system and what are the prerequisites for an Entity-Component system that wants to use this solution?


texts:
I was starting make my awp skin, but I was wondering that my skin at CS:GO looks bit different than on photoshop. So I came here for help. I will show just a test skin (fully red).

First I was save my skin with photoshop to .tga format (32 bits/pixel).

Then importing to VTF editor, but not changing any of these settings, they are default.

After that I checked only "No Level Of Detail", "No Mipmap" and "SRGB".

Opening CS:GO and workshop, awp is not fully red, there is some scrambles.

I hope for solution. :)


texts: 3D collision detection with meshes using only raycasting?

texts:
I'm building a game using WebGL and Three.js, and so far I have a terrain with a guy walking on it. I simply cast a ray downwards to know the terrain height.

How can I do this for other 3D objects, like the inside of a house? Is this possible by casting many rays in every direction of the player?

If not, I would like to know how I can achieve the simplest collision detection possible for other meshes. Do you have to cast a ray to every triangle in every mesh nearby?


texts: How can I apply different actions to different parts of a 2D character?

texts: I am developing a 2D platform game in Java. The player has a gun in his hand every time. He needs to walk and shoot with the gun(arrow keys for walk and X key to shoot). The walk cycle takes 6 frames and i am able to import the sprite sheet and animate the sequence when I press arrow key. But i need to add the gun motion. The player holds the gun upwards and when X key is pressed he brings it straight and shoots. How to implement the walk + shoot action?


texts: Is there a way to use an arbitrary number of lights in a fragment shader?

texts:
Is there a way to pass an arbitrary number of light locations (and colors) for the fragment shader, and loop over them in the shader?

If not, then how are multiple lights supposed to be simulated? For example with respect to diffuse directional lighting, you can't just pass a sum of the light weights for the shader.


texts: Debugging .FX files in Visual Studio not working

texts:
So I have been learning how to use DirectX 11 for a while now and I have chosen to use the .FX framework rather than seperate .vs & .ps files. (I know it's deprecated but I found it a little easier to use for learning, I will use in seperate .vs and .ps files in the near future).

In order to get my engine to compile I have to keep the effects.fx file in the same file directory as the engine project but I cannot include it in the VS2015 project directly (This works fine). At the moment whenever I am writing some code in my .FX file and it creates an error I get an error from the C++ side of things and nothing from my shader. Which leaves me clueless on what is causing the issue.

How can I get the HLSL compiler error/warning output to the debug window?


texts: Calculate shadow map to overlay hidden line-of-sight things in 2d?

texts:
Given a 2D sideview with even-sized grid squares and our hero in a known center-ish position like this

... and imagining this hero's line of sight like this...

how could one get the point values needed for the black overlay polygons as shown here? Thanks!


texts: How to program dynamic touch events that scale according to device?

texts:
When using openGL to build a UI for my prototype I find that that I am still required to use pixels to capture touch events. To make matters worse the Android Docs make this subject slightly confusing. http://developer.android.com/guide/practices/screens_support.html specifically states:

  You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.

Yet

MotionEvent event = new MotionEvent();
event.getX();

returns pixels when used to locate the touchscreen event.
http://developer.android.com/reference/android/view/MotionEvent.html#getX()

To make matters even more confusing,

public final float getRawX ()

  Added in API level 1
  Returns the original raw X coordinate of this event. For touch events on the screen, this is the original location of the event on the screen, before it had been adjusted for the containing window and views.

Seems to imply that there are alterations being made to adjust for the window and views when using

event.getX()

My last bit of confusion comes in when trying to tie both of these concepts together. I see all the moving parts I am just unable to make them connect.

How to convert openGL vertices into terms that work with pixels or dp.
How to program for dynamic touch events using MotionEvent when pixel location will change by scale according to device density.


texts: Best technique for drawing isometric tiles

texts:
I'm thinking about making a simple isometric game with HTML5 Canvas, and wondering what's the fastest way to render the tiles.

Since the tiles are diamond shaped, but drawImage draws rectangles, I have to leave out the corners (the black parts in the following):

I think that leaves me with three options:

Use Image objects with alpha channels (.png). I'm afraid this might kill performance.
Use a clipping path.  If the renderer is optimized this could be pretty fast.
Prerender square tiles, like this:

I'd have the black square as one actual tile in memory, and I'd draw such a tile for the green field, and all fields next to it, or above and below. The diagonal (blue) fields would be make up of the corners of the rectangular tiles. This would avoid clipping or alpha channels, but I would have to prerender all possible combinations of tiles, and it seems like overkill.

What's the best or fastest way to do isometric tiles? What do other games, like FarmVille, use?


texts: Why does releasing a pressed "f" key not prevent the coroutine from spinning?

texts:
I am learning Unity and the following is my simplification of the code presented on Coroutines.

My expectation is that the Fade() just spins in a very very short period of time because the GetKeyDown("f") is true only at the transition from "unpressed" to "pressed" states.

However in the following code, the Fade() spins from f=0 to f=999 continuously (non stop in one go) rather than for example, from f=0 to f=100 at the first key press and from f=101
to f=159 at the second key press, etc.

IEnumerator Fade()
{
    for (int f = 0; f < 1000; f++)
    {
        Debug.Log($"{f}");
        yield return null;
    }
}

void Update()
{
    if (Input.GetKeyDown("f"))
    {
        StartCoroutine("Fade");
    }
}

Question

What causes this unexpected result and how to solve it?


texts: How should I learn about collision detection?

texts:
If I want to use physics engine for my game then how should I go to learn collision-detection algorithms?

When I read AI book for games, the book talks about collision detection, so I want to learn it, but what kind of book would be best?

If I had to choose to go and learn it what would you advise me to read?

A physics book. (Game physics H.Ebrely)
A real-time collision detection book. (Same author)

I don't know much about algorithms, some people say it's better to start with a physics book, because real-time collision detection book depend heavily on algorithms.


texts: I create a Smoke Effect in my Game Scene using Particle system. it works Perfectly in unity Editor, but when I run Game in Android Device it hangs. I search about that but not getting any right solution. Any one can know how to optimize the particle system and run smoothly in device? thanks in advance.  Here is the Snapshot of Particle system.


texts: How to keep hands on weapon during scripted recoil?

texts:
I have a rapid fire weapon that I made in blender, along with a FPS mesh and rig. I'm currently at the stage when I'm creating animations (idle, aim, etc), and had this question: Should recoil be an animation or script?. I decided to go with scripted recoil as originally planned, but see one potential problem going this route that I don't know how to solve.
If I were to use scripted recoil, how do I keep the hands on the gun?
The rig in blender is as follows:
An "arms mesh" (consists of the left and right arm)
An "FPS armature" (Typical rig for an arms only armature, upper hand bone, lower hand bone, fingers, etc)
An rifle mesh (broken down into different parts, ie,  barrel, body, stock, magazine, etc)
A rifle armature (gun bone, magazine bone)
A "weapon holder" empty
The FPS armature has Inverse Kinematics on the bone that controls the palm/hand area of the mesh. The weapon holder has a child of constraint that makes it a child of the "hand bone". The "gun bone" on the rifle armature, has a child of constraint that makes it a child of the "weapon holder". The left hand Inverse Kinematic target also has a child of constraint that makes it a child of the weapon holder, so that the left hand follow the barrel of the gun.
The FPS armature has different animations like an idle animation, weapon draw animation, etc. I'm also considering adding a "fire animation", since I figured I'd need an animation where there is no hand movement at all so that I can have the gun be steady while the recoil script rotates the gun over in unity.
The only animation the gun would have is the reload animation where the magazine floats out of the gun and goes back in.
I plan to export the gun and FPS armature separately into unity, and have this weapon, along with a few others I created, be a child of the hands.
Is there any way I can keep the hands on the weapon when I have scripted recoil in Unity?
I haven't actually encountered the problem yet, since I'm still making the animations, but going the route I'm taking, I'm fairly sure I'm going to come across it later on. Since I'm still at the early stages, if anyone has critique or advice on how I set my rig and stuff, I can still change it, so any input is apreciated.


texts: I'm making a board game: who should manage the player move if the board has specific locations for the players?

texts:
I know this is very specific question but imagine I have a board with spaces (like Monopoly) and a player that must go from one space to another after the dice are thrown.

So my workflow:

Player roll dice
After the player rolled dice

(from player class) space = board.getNextSpaceFromPlayer(player)
Move the player each step until it reach the destination

board.movePlayerToNextSpace(player);
OR
player.moveToSpace(space);

But how exactly do I move the player?

The board must move the player or the player move itself?

I'm trying hard to reflect how the things are in the real world but I find very hard to do so in this context.

Thanks for your help.


texts: Using NumPy arrays as 2D mathematical vectors?

texts: Right now I'm using lists as position, velocity, and acceleration vectors in my game.  Is that a better option than using NumPy's arrays (not the standard library's) as vectors (with float data types)?  I'm frequently adding vectors and changing their values directly, then placing the values in these vectors into a Pygame Rect.  The vector is used for position (because Rects can't hold floats, so we can't go "between" pixels), and the Rect is used for rendering (because Pygame will only take in Rects for rendering positions).


texts:
I am a beginner at libGdx.

I am building a board game (the Fanorama game). I would like to use a pic as the board and place the pieces on the board on top of the board sprite. Is there a nice way to pre-determine what (x,y) co-ordinate locations on the board sprite are valid for placing a piece. Later on, when the game is being played I would like to move the pieces from location to location.

Right now, the only way I can think of is to calculate each piece location pixel co-ordinates and hard-code it in an array. I am not sure if there is a better way to do this and a best practice way for me to learn. I am also concerned if this will be affected when the user resized the screen or uses a different sized device (mobile).

How to solve this problem?


texts:
I am using GLKit in order to show textures on my project. The code is like this:

-(void)setTextureImage:(UIImage *)image {
  NSError *error;
  texture = [GLKTextureLoader textureWithCGImage:image.CGImage options:nil error:&error];
  if (error) {
      NSLog(@"Error loading texture from image: %@",error);
  }
}

effect.texture2d0.envMode = GLKTextureEnvModeReplace;
effect.texture2d0.target = GLKTextureTarget2D;
effect.texture2d0.name = texture.name;

glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, 0, self.textureCoordinates);

Now I want to repeat this texture on a rectangle. Is there any way use GLKit for this behavior? I've tried to use opengl function in addition to the glkit ones, but it raises errors:

glEnable(GL_TEXTURE_2D);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
glBindTexture( GL_TEXTURE_2D, texture.name );

  2011-11-09 20:10:28.614 **[16309:207] GL ERROR: 0x0500

  2011-11-09 20:10:30.840 **[16309:207] Error loading texture from image: Error Domain=GLKTextureLoaderErrorDomain Code=8

  "The operation couldn’t be completed. (GLKTextureLoaderErrorDomain error 8.)" UserInfo=0x68545c0 {GLKTextureLoaderGLErrorKey=1280, GLKTextureLoaderErrorKey=OpenGL error}


texts: How do I get started making Android games?

texts: I am new to game development. I am interested in developing 2D games for the Android platform. What is the best place to start with (i.e) What are the basics and how to proceed? I already have programming experience in Java but don't have any experience with graphics or animation.


texts: Real cost associated with Firebase or AWS game project back ends

texts:
I have been looking for answers to how much does it really cost for using systems such as Firebase or AWS for deployment. We have several games apps and web games we want to deploy this year. Some will have a shared/global high score system, Name storage, achievement storage etc... and we believe Firebase or AWS is a better and secure solution than just our server which we will use for serving the projects (for now).

I want to present a realistic budget. I have used the "estimate" function, but that doesn't feel real. Sometimes it is too good to be true, other times its like "ooohhhh!" I never used these services for production before and would appreciate any guidance and experience someone has had before when it comes to cost.

I sincerely apologize if this is not the proper forum for this question.


texts: Point in Polygon, Ray Method: ending infinite line

texts:
Having a bit of trouble with point in polygon collision detection using the ray method
i.e. http://en.wikipedia.org/wiki/Point_in_polygon
My problem is I need to give an end to the infinite line created.
As with this infinite line I always get an even number of intersections and hence an invalid result.
i.e. ignore or intersection to the right of the point being checked
what I have

what I want

My current code based of Mecki awesome response

for (int side = 0; side < vertices.Length; side++)
        {
            // Test if current side intersects with ray.

            // create infinite line
            // See: http://en.wikipedia.org/wiki/Linear_equation
            a = end_point.Y - start_point.Y;
            b = start_point.X - end_point.X;
            c = end_point.X * start_point.Y - start_point.X * end_point.Y;

        //insert points of vector
            d2 = a * vertices[side].Position.X + b * vertices[side].Position.Y + c;
            if (side - 1 < 0)
                d1 = a * vertices[vertices.Length - 1].Position.X + b * vertices[vertices.Length - 1].Position.Y + c;
            else
                 d1 = a * vertices[side-1].Position.X + b * vertices[side-1].Position.Y + c;

            // If points have opposite sides, intersections++;
            if (d1 > 0 && d2 < 0 )
                intersections++;
            if (d1 < 0 && d2 > 0 )
                intersections++;

        }
//if intersections odd inside = true
    if ((intersections % 2) == 1)
        inside = true;
    else
        inside = false;


texts: Can A* path finding cost functions allow for path following shapes?

texts:
Recently I begun developing a game prototype which could create procedural generated dungeons using a collection of room types. To ensure the hallway paths between these rooms would always be connected I implemented a A* path finding algorithm following along the tile map of randomly placed rooms.

The problem with doing this however is I was not necessarily trying to find the shortest path between rooms which in most cases would be a diagonal. Since being thematically a 'dungeon' I wanted them to twist and turn at 90 degree angles. By using a Manhattan distance for the heuristic I managed to get the intended shape but I've ended up with one final problem which I come to you kind people to help me with :).

Though now using 90 degree angles to move the path, its saves doing the run till the end of path(See picture below). This makes the whole thing at a distance feel cramped in places instead of using all the space effectively. Seeing how simply changing the heuristic from distance to Manhattan distance has made a difference my question is, is there a cost function I could implement that would give the desired results of this non conventional path? Any answers would be appreciated, thank you.

Note: The algorithm also has access to the normal direction of the start and end goals.


texts: Calculate the displacement of device in unity

texts:
I'm making a 3D game in unity where the object should move forward and backward as the android device moves/accelerates in the Z axes. ie. When the player moves the devise in the direction of the +ve Z axis, the object should move forward, and when the player moves the devise in the direction of the -ve Z axis, the object should move backward.

This game is a multiplayer game, and the players will move in a large football field.

My idea to do this is using the accelerometer to calculate the acceleration of the device, then integrate the data of acceleration to get the device speed in the Z axis. and use the speed to move the device.

Using this equation

  V2=V1 + ΔA . ΔT
  Where
  V2 : final velocity.
  V1 : initial velocity.
  ΔA : difference between the initial and final acceleration.
  ΔT : difference between the initial and final time.

At first I tried to use kinematic equations to calculate the final speed, but I realized then that it can be only used when acceleration is constant. So a friend of me who studies physics differentiated this equation for me to use it when acceleration is variable.

I know that there will be some error in calculating the accurate displacement, and that the error will increase after the integration of acceleration, but this small percentage of error is okay for my application; I thought at first in using GPS instead of accelerometer but I found that GPS accuracy will be less than the sensors.

I know also that the error will be incredibly high after some time, so I reset the values of acceleration and velocity every 10 seconds. I'm also using a low-pass filter to reduce the noise of the sensor.

public class scriptMove : MonoBehaviour
{
    const float kFilteringFactor = 0.1f;

    public Vector3 A1;
    public Vector3 A2;
    public Vector3 A2ramping; // for the low-pass filter
    public Vector3 V1;
    public Vector3 V2;

    public int SpeedFactor=1000; //this factor is for increasing acceleration to move in unity world

    void resetAll()
    {
        Input.gyro.enabled = true;
        A2 = Vector3.zero;
        V1 = Vector3.zero;
        V2 = Vector3.zero;
        A2ramping = Vector3.zero;
    }
    // Use this for initialization
    void Start()
    {
        InvokeRepeating("resetAll", 0, 10);
    }

    //http://stackoverflow.com/a/1736623
    Vector3 ramping(Vector3 A)
    {
        A2ramping = A * kFilteringFactor + A2ramping * (1.0f - kFilteringFactor);
        return A - A2ramping;
    }

    void getAcceleration(float deltaTime)
    {
        Input.gyro.enabled = true;

        A1 = A2;
        A2 = ramping(Input.gyro.userAcceleration) * SpeedFactor;

        V2 = V1 + (A2 - A1) * deltaTime;

        V1 = V2;
    }

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

        getAcceleration(Time.deltaTime);

        float distance = -1f;
        Vector3 newPos = transform.position;

        transform.Translate(Vector3.forward * Time.deltaTime * V2.z * distance);
    }
}

The problem:

My code doesn't work always as expected when I move with the device;

Sometimes when I move forward (in the +ve Z axis of the device) the object moves forward also, but sometimes it doesn't move at all.
Sometimes when I'm still in my position the object moves alone by itself.
Sometimes when I move forward and suddenly stop, the object does not stop.

My questions:

Are those strange behaviors because of the accuracy of the device, or is there something I'm missing in my code.
If I'm missing something in my code, What is it?
I searched a lot about methods to get the most accurate position of the device, and I found that I can integrate GPS with accelerometer, how can I do this with my code in unity?


texts: How to draw lines in screenspace like grids in a perspective world?

texts:
In my Geometry shader this is what my line shader looks like

PSInput output = (PSInput) 0;

// Bring A and B in window space
float2 AWidth = projToWindow(input[0]);
float2 Bwidth = projToWindow(input[1]);

float2 lineStrip = Bwidth.xy - AWidth.xy;
float2 normal = normalize(float2(-lineStrip.y, lineStrip.x));
float2 width = vObjectParams.x * normal;

// Compute the corners of the ribbon in window space
float2 Top1 = (AWidth + width);
float2 Top2 = (AWidth - width);
float2 Bottom1 = (Bwidth + width);
float2 Bottom2 = (Bwidth - width);

float Z  = input[0].z;
float Z1 = input[1].z;

//Bring the computed x and y back to world space
output.p = windowToProjection(Top1, Z, input[0].w);
outStream.Append(output);

output.p = windowToProjection(Top2, Z, input[0].w);
outStream.Append(output);

output.p = windowToProjection(Bottom1, Z1, input[1].w);
outStream.Append(output);

output.p = windowToProjection(Bottom2, Z1, input[1].w);
outStream.Append(output);

outStream.RestartStrip();

Basically, I bring the vector into the screen space first then add the required width then push it back to the world space.

Everything works fine when I am zoomed out but perspective geometry comes into play when I am zoomed in. That is, my line width increases as I zoom in closer


texts:
I am trying to create a horizontal line at the center of the screen that goes infinitely. I could make the line short and move it with the camera but the shape of my line actually changes as you progress. I am using a line renderer and I am not sure what is the best way to achieve this?

Secondly, the camera keeps moving to the right so I would like those parts of the line that are not visible anymore to get destroyed. I am also not sure how to achieve this since this is one big line I assume?


texts: What's the term for the "vertical looking angle" in FPSs?

texts:
I guess the "vertical angle" of looking in an FPS could be called the pitch of the camera, but surely there is another term for it?

(I'm trying to mod ArmA II, but I can't find anything in their documentation and forums about the camera pitch or whatnot. The ArmA people call the horizontal angle "direction.")


texts:
I'm making a game that uses an Entity/Component architecture basically a port of Artemis's framework to c++,the problem arises when I try to make a PlayerControllerComponent, my original idea was this.

class PlayerControllerComponent: Component {
public:
    virtual void update() = 0;
};

class FpsPlayerControllerComponent: PlayerControllerComponent {
public:
    void update() {
        //handle input
    }
};

and have a system that updates PlayerControllerComponents, but I found out that the artemis framework does not look at sub-classes the way I thought it would.
So all in all my question here is should I make the framework aware of subclasses or should I add a new Component like object that is used for logic.


texts:
I'm making a map editor for further RTS game (2D), something like the first StarCraft Editor. Terrain tiles will be a rhombuses. So I'll probably just make an 2D array with intigers, that corresponds proper tiles. Then, after creating the terrain, you'd probably like to add some units and structures to map (especially if you're making a scenario). I'm not sure how do I check if the unit can be placed somewhere. I decided to make units almost independent from terrain tiles like in StarCraft (1), so the units are not placed in any grid.
I'll give a simple image:

As you can see, those green tiles represent a passable area (grass, let's say), and a blue one impassable (for example water). That stickman in a box is our unit. You can place it only in green area. That means the box can't go outside the green rhombuses.

I have some ideas how to achieve this, but I'm not sure which one would be the most optimal.

1) Since I work in Unity, I could add a collider to every tile. That will be very simple to do and will probably have terrible optimalisation in maps 256x256.

2) Math. I can calculate if any of those boxes crosses tile's borders. If so, I'll have to check if all those tiles are passable. It won't be that easy to programme (well, for me at least) and... yeah, here comes my dillema. Am I right that it would have much better optimalisation? Is it worth the effort?

What about saving this map? I can easily save the array with tiles, but how can I do it with units? Just save their positions or is there a better way to do it?

EDIT: I've tested the first idea (I've written script to create 256x256 map - that will be probably the biggest, and to move a camera). The map generates quite long (comparing to tiles without collider), but after that there isn't much difference in performance (it doesn't mean it won't cause problems when I add more features than moving a camera ;)). I can also attach colliders only to impassable tiles, not all. This should improve the performance even more. Still not sure if that's a good idea.

EDIT 2: I've just realised how bad my idea was. Let me visualise this:

So if you consider not the whole rectangle, but only a circle, it's not only easier to implement, but also more reasonable. You can now convert rhombus' vertices' position from isometric to cartesian like Bálint said:

CartX = ( 2 * IsoY + IsoX) / 2
CartY = ( 2 * IsoY - IsoX) / 2

You can also do it with circle's center point. Radius is equal to half of square (rhombus) side length OR sqrt(2) * square side length (when square is inscribed in circle).

So now I have a square grid and a circle. How can I check if all squares that this circle lays on are passable? What's the most optimal way to do it?


texts: How can I make sure the rotation has finished or the transform is facing the target?

texts:
void FixedUpdate()
    {
        LiftProcess();
        MoveProcess();
        TiltProcess();

        if (hasRotate == true)
        {
            Vector3 targetDirection = helicopterPlatform.transform.position - transform.position;
            Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetDirection, lookAtSpeed * Time.deltaTime, 0.0f);
            transform.rotation = Quaternion.LookRotation(newDirection);
        }
    }

I want ot make a check IF transform.rotation has finished and the transform is facing the newDirection then change the flag hasRotate to false. What check and how should I apply ?


texts:
I am working on a 2D RPG, which will feature the usual dungeon/town maps (pre-generated).

I am using tiles, that I will then combine to make the maps. My original plan was to assemble the tiles using Photoshop, or some other graphic program, in order to have one bigger picture that I could then use as a map.

However, I have read on several places people talking about how they used arrays to build their map in the engine (so you give an array of x tiles to your engine, and it assemble them as a map). I can understand how it's done, but it seems a lot more complicated to implement, and I can't see obvious avantages.

What is the most common method, and what are advantages/disadvantages of each?


texts: Drawing many separate lines using mouse OpenGL(GLFW/glad)

texts: So, in order to draw a line, I track the coordinates of the mouse, then I add them to the array and capture it as GL_LINE_STRIP_ADJACENCY. However, for example, I completed drawing a line1 at P1 and decided to start drawing a different line at P2 as shown in the figure, but my two points P1 and P2 joined together, how to fix it? Need to clear the array after drawing at the point P1, actually it doesn't help if I use glClearColor and glClear(GL_COLOR_BUFFER_BIT).. Is there any other way?


texts:
I'm working on a 2D rpg-style game and I'm currently rewriting my game to get a more clean and structured code. Some thing that has been bugging me is that I have no idea how unit scales work with the OrthogonalTiledMapRenderer, it's kind of like a "Hey it works, I don't know how, but it works" solution. Basically to scale my map up, since it's a pixel game I use

renderer = new OrthogonalTiledMapRenderer(map, 4);

which seems completely wrong since I've seen other examples using things such as 1/32f. However using that makes me unable to even find my map in game when moving the camera.

I've looked up on unit scales but I have a hard time grasping why and how I should use them and if they are really necessary. And by using the code above, which I'm guessing I use the wrong way, does that bring any problems?

Thanks in advance!


texts: Realistic 3D Collision Detection Implementation

texts: I understand how box collision, sphere collision, and other such collisions work. However, how would one implement realistic 3D collisions? That is, objects would interact with one another as they would in real life. For example, take a rod and a torus. Assume that the thickness of the rod is smaller than the hole in the torus. With simple collision systems, as far as I know, inserting the rod into the hole of the torus would result in a collision detection. In reality, no collision would take place. Hopefully, that explains what I am looking for.


texts: How can I apply effects to a character based on the tiles it occupies?

texts: A mechanic of my game is that when a Character (Actor) steps on some specific tiles, they should be affected by status effects like slow, poison, burn, etc. These effects lasts only while the Character is on the effect tile. The character may be a lot larger than the tile. How can I achieve this?


texts: Set custom Yaw Pitch and Roll in Three.js

texts:
So I have the following struct in C++, it gets updates with the values of an program that uses a camera in spectator mode:

struct SCameraInfo
{
    Utils::Vector3 Position;
    float Matrix[3][3];
    float FieldOfView;
};

I'm sending these values through websockets to an HTML5 app running on my iPhone. I want to set these values in a Free Camera mode of a Three.js scene but don't know how to do it. As far I can tell I know the Position, View Matrix and Fov, but not sure of how to apply them to the three.js camera.

The problem is that I don't know which methods call or how to apply the lookAt for example.

This is a kind of yaw pitch and roll camera and not Quaternion based.

Here is and example of the values:

position 2721.35 -390.34 107.15
view mat 0.47 -0.67 0.57
view mat 0.82 0.57 0.00
view mat -0.33 0.47 0.82
FOV      0.10

I've been searching for the most easiest example but all of them seem to use Quaternions.


texts: Slick2D How to add a method from a diffrent class to a method

texts:
I am trying to get keyboard input in a separate class so everything doesn't look as messy. I get the following error message

Exception in thread "main" java.lang.NullPointerException
    at com.****.****.Menu.init(Menu.java:33)
    at com.****.****.Main.initStatesList(Main.java:35)
    at org.newdawn.slick.state.StateBasedGame.init(StateBasedGame.java:164)
    at org.newdawn.slick.AppGameContainer.setup(AppGameContainer.java:393)
    at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:317)
    at com.****.****.Main.main(Main.java:27)

This is what I tried:

Menu Class where I load the methods

public class Menu extends BasicGameState{

KeyboardInput kbi;

public Menu(int state) {

}

@Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {

    kbi.init();

}

@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
    kbi.render();
}

@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
    kbi.update();
}

@Override
public int getID() {

    return 0;
}

}

KeyboardInput class

public class KeyboardInput {

public KeyboardInput() {

}

public void init() {

}

public void render() {

}

public void update() {

}
}


texts: Objects appear invisible to camera during animation

texts:
Depending on the camera angle and the distance of the animated Objects to the camera they flicked in and out of view.

Since I have no idea what could be causing this and didn't manage to limit the problem other than moving the camera please state what valuable information I should supply.

The Model is parented to a camera which is parented to a character controller. The Animation is undisrupted during scene view. If I move the camera further away from the model, or look in a different direction the models remain visible throughout the entire animation.

I have recordet the incident: https://youtu.be/b66N80_Fg_g

As you can see the right hand, the magazine and at one point even the weapon disappears from view.


texts: In general how often and when should I optimize my code?

texts:
In 'normal' business programming optimization step is often left until really needed.  Meaning you should not optmize until it is really needed.

Remember what Donald Knuth said "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"

When is the time to optimize to make sure I am not wasting effort.  Should I do it a method level?  Class level?  Module level?

Also what should my measurement of optimization?  Ticks?  Frame Rate?  Total Time?


texts: How to manage enemy movement and shoot in a shmup?

texts:
I'm wondering what is the best (or at least a good) way of managing enemies in a shoot-em-up.

Basically, what I'd do would be a class that manages displaying and updating positions of all the enemies.
But how to create good deplacements for enemies?  A list of where-to-go points? gravitating around some fixed points (with ponderation, distance evaluation etc.)?

Same question for the shoot patterns?

Can you please put me on a track?


texts:
I am currently making a browser-based game and I would like to integrate micro-transactions. However I would prefer not to have to implement my own storefront. Does anyone know of an available framework/API? I've been looking at commonly used ones and most of them seem to be in-house work, i.e. EA's FTP games use http://www.play4free.com/en/
I'm looking for something like this but available to third parties.

The project is built on the python framework Django with a heavy Javascript frontend if that helps.

Thanks in advance.