texts: Designing the main classes in a solar system simulation game in C++

texts:
If this is not the right place for this question, could you please direct me to a more suitable site/forum?

I'm a beginner in game development (and in the use of this site). I've worked with C++ only for rather small scientific simulations, so I can "code" but I've never done a full-blown design of an OO program, much less of a game. You can tell from what I'll write next :P

I've decided to write an open source educational game that simulates accurately the motion of the Sun, the planets and of one or more spacecraft controlled by the player. By "simulates accurately" I mean that I want to use a scientifically valid and precise algorithm to obtain the forces and thus the motions of the bodies.

The game will be in 3D and will use the Ogre3D engine for the graphics. Graphically it will look similar to Celestia.

The first difficulty is that I've never designed the structure and the classes of any game. By reading a few references and guides I think I have a vague idea of how the dynamics could work, but it's vague: each entity (planet or spacecraft) could store its own state information and then have an "update" function that updates the state based on some input (like user commands). There are probably many other ways to do this, I guess.

The main problem, however, comes from the particular needs of this project:

my objects must not only respond to user input, but also obey accurate physical laws, and the algorithm that computes them must be centralized. This is because it needs to know the positions of all the bodies at the same time to perform its computations;
I plan to add different kinds of spacecraft with different types of propulsion, and some of them would react to the other bodies in special ways (think antigravity).

The Question

Is there a design pattern or architecture suitable for this problem?

The best I can think of is to have a singleton Universe class containing the central algorithm for the dynamics. The various objects of the solar system then communicate with Universe. They would contain basic parameters like mass and size, and they would listen to Universe telling them where to stand.

However this doesn't sound right. Where do I put the ever-changing trajectory data of all the bodies, in Universe? What's the point of having all those objects then? Only for the graphical part of the game?

And what about the special dynamical properties of some spacecraft? I can't possibly include them all in the central algorithm from the beginning.

Ok, I think you can tell how confused I am about the matter much better than me. I would be grateful for any kind of input.


texts: Current performance analysis shows that D3DXCreateEffect is called many times with different shaders. Between each call, the D3DCompile DLL is being loaded and unloaded. Is there an easy way to keep that DLL loaded, i.e. by holding a CComPtr to some resource or something similar?


texts: Generate a large data structure using a compute shader

texts:
I know that
RWTexture2D Result;

void CSMain (uint3 id : SV_DispatchThreadID)
    {
        Result[id.xy] = float3(1,2,3);
    }

will result in an texture containing the numbers 1,2,3 however I'm now looking for a way to control a compute shader in such a way as to generate either a 3D texture with control over which order my operation occur or a way to fit a data structure in the return value of the compute shader.

For a simplified example let's say that I want to generate either a 2D array of linked lists with each value in the linked list being equal to 1+the next value so

9-8-7-6 , 11-10-9-8
8-7-6-5 , 6-5-4-3-2

from the input texture

6,8
5,2

or store the same in a 3D texture (the real version will be more complex so we will not be able compute that 5+2=7 but instead have to relly on the fact that 5+1=6 6+1=7)

Any idea how to do this?


texts: Trying to Draw a 2D Triangle in OpenGL ES 2.0

texts:
I'm trying to convert a code from OpenGL to OpenGL ES 2.0 (for the BlackBerry PlayBook). So far what I got is this (just the part of the code that should draw the triangle):

void setupScene() {
    glClearColor(250, 250, 250, 1);
    glViewport(0, 0, 600, 1024);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

void drawScene() {
    setupScene();

    glColorMask(0, 0, 0, 1);

    const GLfloat triangleVertices[] = {
        100,   100,
        150,  0,
        200,   100
    };

    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, triangleVertices);
    glEnableVertexAttribArray(0);
    glDrawArrays(GL_TRIANGLES, 0, 2);
}

void render() {
    drawScene();
    bbutil_swap();
}

The problem is that when I launch the app instead of showing me the triangle the screen just flickers (very fast) from white to gray. Any idea what I'm doing wrong?

Also, here is the entire code if you need: Full source code


texts: How can I simulate tapping on touch for Android?

texts: I'm searching on Input.Touch properties to find how can I simulate tapping on touch for Android. Something like Input.getmouseButtonDown() on mobile.


texts: How does interpolation actually work to smooth out an object's movement?

texts:
I've asked a few similar questions over the past 8 months or so with no real joy, so I am going make the question more general.

I have an Android game which is OpenGL ES 2.0. within it I have the following Game Loop:

My loop works on a fixed time step principle (dt = 1 / ticksPerSecond)

loops=0;

    while(System.currentTimeMillis() > nextGameTick && loops < maxFrameskip){

        updateLogic(dt);
        nextGameTick+=skipTicks;
        timeCorrection += (1000d/ticksPerSecond) % 1;
        nextGameTick+=timeCorrection;
        timeCorrection %=1;
        loops++;

    }

    render();

My intergration works like this:

sprite.posX+=sprite.xVel*dt;
sprite.posXDrawAt=sprite.posX*width;

Now, everything works pretty much as I would like. I can specify that I would like an object to move across a certain distance (screen width say) in 2.5 seconds and it will do just that.  Also because of the frame skipping that I allow in my game loop, I can do this on pretty much any device and it will always take 2.5 seconds.

Problem

However, the problem is that when a render frame skips, the graphic stutter.  It's extremely annoying.  If I remove the ability to skip frames, then everything is smooth as you like, but will run at different speeds on different devices.  So it's not an option.

I'm still not sure why the frame skips, but I would like to point out that this is Nothing to do with poor performance, I've taken the code right back to 1 tiny sprite and no logic (apart from the logic required to move the sprite) and I still get skipped frames.  And this is on a Google Nexus 10 tablet (and as mentioned above, I need frame skipping to keep the speed consistent across devices anyway).

So, the only other option I have is to use interpolation (or extrapolation), I've read every article there is out there but none have really helped me to understand how it works and all of my attempted implementations have failed.

Using one method I was able to get things moving smoothly but it was unworkable because it messed up my collision.  I can foresee the same issue with any similar method because the interpolation is passed to (and acted upon within) the rendering method - at render time.  So if Collision corrects position (character now standing right next to wall), then the renderer can alter it's position and draw it in the wall.

So I'm really confused.  People have said that you should never alter an object's position from within the rendering method, but all of the examples online show this.

So I'm asking for a push in the right direction, please do not link to the popular game loop articles (deWitters, Fix your timestep, etc) as I've read these multiple times.  I'm not asking anyone to write my code for me.  Just explain please in simple terms how Interpolation actually works with some examples.  I will then go and try to integrate any ideas into my code and will ask more specific questions if need-be further down the line. (I'm sure this is a problem many people struggle with).

edit

Some additional information - variables used in game loop.

private long nextGameTick = System.currentTimeMillis();
//loop counter
private int loops;
//Amount of frames that we will allow app to skip before logic is affected
private final int maxFrameskip = 5;
//Game updates per second
final int ticksPerSecond = 60;
//Amount of time each update should take
private final int skipTicks = (1000 / ticksPerSecond);
float dt = 1f/ticksPerSecond;
private double timeCorrection;


texts: How many textures can usually I bind at once?

texts:
I'm developing a game engine, and it's only going to work on modern (Shader model 4+) hardware. I figure that, by the time I'm done with it, that won't be such an unreasonable requirement.

My question is: how many textures can I bind at once on a modern graphics card? 16 would be sufficient. Can I expect most modern graphics cards to support that number of textures?

My GTX 460 appears to support 32, but I have no idea if that's representative of most modern video cards.


texts:
What is a target in OpenGL, actually? For example, in the function

void glBindBuffer(enum target, uint bufferName)

I know what the function does (more or less), but the target was only a copy/paste enum value from a modern OpenGL tutorial for me so far. Can you explain what it is, possibly with an example where it is not just a copy/paste value in object load method?

Should I think of it as a variable of that name with some semantics, in drivers where you can put reference to a buffer (regardless of the buffers previous binding)?


texts: Spherical harmonics lighting - what does it accomplish?

texts:
From my understanding, spherical harmonics are sometimes used to approximate certain aspects of lighting (depending on the application).

For example, it seems like you can approximate the diffuse lighting cause by a directional light source on a surface point, or parts of it, by calculating the SH coefficients for all bands you're using (for whatever accuracy you desire) in the direction of the surface normal and scaling it with whatever you need to scale it with (e.g. light colored intensity, dot(n,l),etc.).

What I don't understand yet is what this is supposed to accomplish. What are the actual advantages of doing it this way as opposed to evaluating the diffuse BRDF the normal way. Do you save calculations somewhere? Is there some additional information contained in the SH representation that you can't get out of the scalar results of the normal evaluation?


texts: Bringing over OpenGL code to unreal engine?

texts:
So I've been developing games and apps in C++/OpenGL for a while, and am thinking of starting to use Unreal Engine for many things.

I've built up quite the huge libarry for UI / rendering related code, but they rely on OpenGL for rendering. Will I have no choice but to reimplement these / use unreal engine's, or is there some way to integrate them together?


texts: How would one implement the effect of a sprite disappearing on one side of the screen and appearing on the other using AndEngine? Like in Kid Icarus, seen here at around 1:22.


texts: Mathf.Approximately: should I use it & for what cases?

texts:
For comparing floats they recommend using Mathf.Approximately
At the same time, they don't use it, for example, for comparing types such as vectors.
From Vector3.cs:

public bool Equals(Vector3 other)
{
    return x == other.x && y == other.y && z == other.z;
}

If I understand it correctly it wouldn't cause any problem when using == operator to compare floats that are formed the same way (or copied from the same source).  For example:

float x = 10f / 10f;
float a = x; // or `a = 10f / 10f`;
float b = x;
bool equal = (a == b); // always `true`

but it can cause a problem if floats are formed differently even if their results are supposed to be the same. For example:

float a = 10f / 10f;
float b = 11f - 10f;
bool equal = (a == b); // result is unpredictable

Is my understanding correct?


texts: How to achieve graphics like those in Spy Mouse

texts: I'm really interested in making a new application for iPhone, and I have some experience in objective-c. My main problem is the visual part. I want to have graphics like in Spy Mouse. Could this be achieved using simple 2D graphics? Or would I need to use 3D, and just show it from this perspective?


texts: Is a Computer Graphics book being outdated a problem?

texts:
Me and my friends decided to make a game engine as a graduation project and this summer we are dedicating ourselves to really get into the knowledge we need before actually starting the project.
We are starting by watching the UC San Diego CG course(s) (there is an advanced course now) and also read the Essential Mathematics for Games and Interactive Applications 3rd Edition book (we are a bit undecided about the book so if you have any comments about it we will greatly appreciate them).
Our problem mainly is that while googling for CG books, answers on this community and even on other sites seem to always suggest outdated books (like Computer Graphics C Version 2nd Edition).
Now, I personally don't think a book being outdated is necessarily bad, but it could be. Depends on how differently things in the 2020 are being done and as a beginner I am obviously ignorant of that aspect.
Is a book being outdated a problem?


texts: Determine if a set of tiles on a grid forms an enclosed shape

texts:
Given a set of tiles on a grid, I want to determine:

If the tiles make an enclosed figure
If the tiles make an enclosed figure when you count the sides of the board as an edge of the figure
If either of the previous two statements are true, which additional tiles fall inside the enclosed figure the initial tiles form.

The player will begin by pressing down on one tile, then dragging their finger to other tiles to create a chain of same-colored tiles. I will check as I go to see if the next tile is valid. Ex. If the player begins on a red tile, their only next valid move is to an adjacent red tile (diagonals do count). When the user lifts their finger, I need to be able to check for the 3 items above.

So my initial thought was that, since I was checking for the validity of the chain each time I went, when the player lifted their finger I could check if the first and last tiles were adjacent. (I already know they're the same color.) If they were adjacent I had a hunch that I'd made an enclosed figure, and I was going to come here to try and see if I was missing something big, and to get some kind of logical/mathematical proof that my hunch was correct (or an example proving it incorrect.)

But that's when I thought of item number 2: I also have to account for chains which use an edge of the board as a side of the enclosed figure. In that case, the first and last items in the chain would not be adjacent, but I would still have an enclosed figure. So now I'm back to square one, a bit.

What can I do with this chain of grid coordinates to figure out if they make an enclosed figure or not? And once I do know I have an enclosed figure, what's the best way to get an additional list of all tiles that fall inside its bounds?

Above I've drawn pictures of what I expect the 4 possible results of this test can be.

The chain does not make an enclosed figure.
The chain does make an enclosed figure.
If you count the sides of the board as an edge (or more than one edge) of the figure, the chain does make an enclosed figure.
The chain does make an enclosed figure, but there are extra data points (validly selected by the user as part of the chain) which are not a part of the figure that is created.

Case 4 is the trickiest, because you'd have to extract the "extra" chain links to find the enclosed figure and the pieces that fall inside it (but not around the "unenclosed" area).

So... Anyone have an idea of a good way to solve this, or just a starting point for me? I'm kind of going in circles at this point and could use another set of eyes.


texts: Suspend user interaction in unity during animation

texts:
What is the best way to suspend user interaction during an animation in Unity? Is there any standard technique that good games use.

E.g. In case of a card game, I am trying to flip a card. But if I click on the card in quick succession, it messes up the game.

Thanks!


texts:
I am trying to follow this tutorial to create a brushed metal "start" button. (I am very new to all of this) I want the button to look nice when rendered in a game engine.

For some reason I can not figure out how to get the texture to wrap cleanly without seams. I modeled the "pill" part of the button using mirror and subsurf modifiers. The texture is a free version from cgtextures that is supposedly ready to be tiled. I created the various textures (normal/specular/etc) using CrazyBump as mentioned in the tutorial.

But now I'm stuck! The seems are driving me insane


texts: When I press play in my scene, the camera turns in the opposite direction?

texts:
In my scene, I have my character facing a certain direction, with a camera attached. Now, when I press play, for some reason, the character immediately faces the other way. I've tried turning the model and camera to face the opposite way of that, to make up for it, but it still faces that same direction.

I've had a look at the script for the camera, but I'm not sure what could be causing this to happen. There's no target assigned that should cause that reaction, as the camera is a child of the player.

Below is a copy of my script:

public class FirstPersonCamera : MonoBehaviour
{
    Vector2 mouseLook;
    Vector2 smoothV;
    public float sensitivity = 5.0f;
    public float smoothing = 2.0f;

    GameObject character;

    void Start()
    {
        character = transform.parent.gameObject;

        Debug.Log("Camera is operating");
    }

    void Update()
    {
        var md = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));

        md = Vector2.Scale(md, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
        smoothV.x = Mathf.Lerp(smoothV.x, md.x, 1f / smoothing);
        smoothV.y = Mathf.Lerp(smoothV.y, md.y, 1f / smoothing);
        mouseLook += smoothV;

        transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
        character.transform.localRotation = Quaternion.AngleAxis(mouseLook.x, character.transform.up);

        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = true;

        if (Input.GetKeyDown("escape"))
        {
            Cursor.lockState = CursorLockMode.Locked;
        }

    }

}

Does anyone see what could be causing this issue? I've using Unity version 2019.2

I'm also including screenshots of the player's position, as well as the camera's.

Player:

Camera:

There's something in the script that is causing the character to turn around, as I placed the script on another model and it had the same effect P:


texts: Distinction between constant and changeable game objects in save/load game?

texts:
Do you distinguish constant and changeable game objects when you save/load game? If yes, how do you do it?

If not to save constant objects (for example, mountains and trees), we optimize memory usage and save/load time. But functional requirements for the game can change. Now you want trees to be mutable and destroyable. It can screw up all previous game states. Trees were not saved => saved game map is interpreted as the prairie without trees.


texts: How to make a cartoon like trail particle system?

texts:
I'm currently working on an little Android game, it's a reaction casual game. Because the user needs to tap some balls flying around at the right moment, I want to add some new effects to them.

So I looked at some other games and found this cool looking cartoon like effect.

As you can see the ball there has an cool tail.

So my question is, does anyone know how to recreate such a trail with the Unity particle effects or some other tools?


texts: is unity DOTS mature enough to build a whole project on it?

texts:
maybe you assume this question opinion based but its not. please read the whole question.
the question has 2 aspects.

are all features implemented? just better say, can i do everything or any gameplay i did on monobehaviours, on the DOTS? all are needed features implemented? including Ai, navigation, physics, animations and...

the bigger problem about DOTS and ECS is software engineering. DOTS gives us much better performance in memory and performance and parallel processing but it takes all good OOP practices from us.

as you may know, DOTS is not OO and uses its own architectures. most of references values are gone in dots to make data more compact. so there is no solid principles. dependency injections and all those OO design patterns. instead we have a hardly coupled code and entities.
the question is: does DOTS and ECS really lacks software engineering or its just we dont know enough about it and there are standards about it?
many people say that you should make all project on old monobehaviours and you can migrate section that are expensive to DOTS.
im not really sure what is the right approach for using with new technology.


texts: How do you handle pathfinding for non-tilemap 2d games?

texts:
What methods do you use to handle path finding in non-tiled 2D games?
Tilemap based methods can use A* and 3D has NavMesh available.
The only success I’ve had is with raycasts but it doesn’t seem like a great way to handle things with hand draw sprites or uneven terrain.


texts: Newton Game Dynamics: Making an object not affect another object

texts:
I'm going to be using Newton in my networked action game with Mogre.  There will be two "types" of physics object:  global and local.  Global objects will be kept in sync for everybody; these include the players, projectiles, and other gameplay-related objects.  Local objects are purely for effect, like ragdolls, debris, and particles.

Is there a way to make the global objects affect the local objects without actually getting affected themselves?  I'd like debris to bounce off of a tank, but I don't want the tank to respond in any way.


texts: Box2d Raycast C++. Always returning false? (trying to check if player is grounded)

texts:
I'm trying to add Box2d to my C++/SFML platformer game. I have my ground tiles with a b2staticBody. And the player character is b2_dynamicBody.

My usual method to check if player is grounded is to Raycast straight down from centre of sprite to just below the foot level. (NOTE: I do note that SFML is y-down).

For now, I just want the raycast to return true if it hits anything. But it always returns false. I watch the player land on the ground and can walk along the floor and fall off it (ie. The built-in box2d collision is working)

Here is my code (I am brand new to using Box2d in c++, so sorry if it's wrong. There aren't too many good examples to be found online)

void guy::update() {
bool bGrounded = false;
b2RayCastOutput output;
b2RayCastInput input;
input.p1 = bodyPtr->GetPosition();
input.p2 = bodyPtr->GetPosition() + b2Vec2(0, 1.f * Constants::PPU);
input.maxFraction = 1.0f;
b2Fixture* fixture = bodyPtr->GetFixtureList();
std::cout << "p1: " << input.p1.x << " , " << input.p1.y << " / p2: " << input.p2.x << " , " << input.p2.y << std::endl;
std::cout << "sprite pos: " << sprite.getPosition().x << " , " << sprite.getPosition().y << std::endl;
if (fixture->RayCast(&output, input, 0))
{
    bGrounded = true;
}
else
{
    bGrounded = false;
}
std::cout << "isGrounded: " << bGrounded << std::endl;
}

The console outputs seem ok (ie. p1 and p2 are where I expected them to be), but the bool always returns 0.

Of course I am very open to an improved jumping function. Eventually I want to be able to add the ability to hold the jump button for some time to get a bigger jump. But the only way I can think to start with is checking if the player is touching ground first.

NOTE: Here is the ground Tiles start function (at the bottom you see i CreateFixture():

void Tile::start(size_t x, size_t y, sf::Texture& texture, bool isSolid, b2World* world)
{
worldPtr = world;
bIsSolid = isSolid;
sprite.setTexture(texture, true);
sprite.setOrigin(sprite.getTextureRect().width / 2.f, sprite.getTextureRect().height / 2.f);
sprite.setPosition((float)x * Constants::PPU, (float)y * Constants::PPU);

if (isSolid)
{
    bodyDef.position.Set(sprite.getPosition().x, sprite.getPosition().y
    );
    bodyPtr = worldPtr->CreateBody(&bodyDef);
    b2Vec2 topEdge(-1, 0);

    box.SetAsBox(sprite.getTextureRect().width / 2.f, sprite.getTextureRect().height / 2.f);

    bodyPtr->CreateFixture(&box, 0.f);

}

}

Here is the player start() in case it will help:

void Guy::start(b2World* world)
{
worldPtr = world;
texture.loadFromFile("Textures/guy.png");
sprite.setTexture(texture, true);
sprite.setOrigin(sprite.getTextureRect().width / 2.f, sprite.getTextureRect().height / 2.f);
setPosition(4 * Constants::PPU, 10 * Constants::PPU);

bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(sprite.getPosition().x, sprite.getPosition().y); // TODO: Does this need to be offset?
bodyPtr = worldPtr->CreateBody(&bodyDef);

box.SetAsBox(sprite.getTextureRect().width / 2.f, sprite.getTextureRect().height / 2.f);

fixtureDef.shape = &box;
fixtureDef.density = 65.0f; // TODO Magic numbers
fixtureDef.friction = 0.05f;

bodyPtr->CreateFixture(&fixtureDef);
bodyPtr->SetFixedRotation(true);

}


texts: Converting hexagon grid coordinate system

texts:
I have been building a RTS game based on a hexagon grid in JavaScript and I stumbled across a problem regarding the coordinate system. I have been trying to implement an A-star system to find paths, but it seems that a horizontal hex grid could cause some problems so far when it comes to odd and even.

It was made horizontal as it is the way it is rendered to make all graphics not overlapping improperly.

So now to my question after some digging on the web. How do you convert between horizontal and 60 degrees coords?

I have tried this code, but it's not good enough, and I'm stuck at what I'm missing for my two functions GetWorldXpos and GetWorldYpos.

function DrawHex(context, hexagonData, isEven, x, y)
{
    var heightValue;

    heightValue =  GetIntNoDecimals(hexagonData.heightValue); //parseInt(hexagonData.heightValue, 10);

     //sets up so if the height of sea-levels is achived it should be equal level
    heightValue = CheckForLakeLevel(heightValue);

     //Gets color code depengin on height
     var colorCode = GetColorCode(heightValue, hexagonData.heightValue);

    if(isEven){
        //creates and draws object
        var hex = new HexagonObj(GetLargeMapXpos(x), GetLargeMapYpos(y), GetWorldXpos(x + 1, y), GetWorldYpos(x, y));
        hex.Draw(context, 0.99, lmapData.spaceing, colorCode, (heightValue), 0);

        //Adds data for usage how to draw other worl dependent objects
        lmapHeightData.push(new LargeGridData(GetLargeMapXpos(x), GetLargeMapYpos(y), GetWorldXpos(x, y), GetWorldYpos(x, y), heightValue));
    }
    else
    {
        //creates and draws object
        var hex = new HexagonObj(GetLargeMapXpos(x), GetLargeMapYpos(y) + lmapData.spaceing, GetWorldXpos(x, y), GetWorldYpos(x, y));
        hex.Draw(context, 0.99, lmapData.spaceing, colorCode, (heightValue), 0);

        lmapHeightData.push(new LargeGridData(GetLargeMapXpos(x), GetLargeMapYpos(y) + lmapData.spaceing, GetWorldXpos(x, y), GetWorldYpos(x, y), heightValue));
    }
}

//Gets what is the coordinate to be drawn on screen
function GetLargeMapXpos(x)
{
    var lgX = ((lmapData.posX + lmapData.spaceing) * x) + lmapData.areaPosX + lmapData.correctionX;
    return lgX;
}

//Gets what is the coordinate to be drawn on screen
function GetLargeMapYpos(y)
{
    return (lmapData.posY * y) + lmapData.areaPosY + lmapData.correctionY;
}

//Gets what is the coordinate for current hexagon
function GetWorldXpos(x, y)
{
    return (x + lmapData.cameraPosX) - ((y + lmapData.cameraPosY) * 2);
}

//Gets what is the coordinate for current hexagon
function GetWorldYpos(x, y)
{
    return y + lmapData.cameraPosY + (x + lmapData.cameraPosX);
}

Any suggestions?


texts: Objects desync position when speed is not multiple of 10

texts:
While finishing up game loop and rendering integration, i made some blocks move back and forth in the x axis to test things out. Their initial positions are as follows:

The first block starts at 0,0(Top-left) and subsequent ones add 40 to both x and y.

Move code

s16 speed = 10;

if(block->sprite->position.x >= viewportWidth - block->sprite->width)
{
    block->sprite->position.x = viewportWidth - block->sprite->width;
    block->dir = -1;
}
else if(block->sprite->position.x <= 0)
{
    block->sprite->position.x = 0;
    block->dir = 1;
}

block->sprite->position.x += speed * block->dir;

However, if i change the speed to a number not multiple of 10(or using deltaTime to influence the speed), the blocks will de-sync when changin directions, as shown bellow:

Result of using roundf(1000 * deltaTime) as speed

Result of using 13 speed and removing the clamping of position

I thought it was related to me using ints instead of floats for positions, tried to change but no luck. Looking at the game loop update, no block is being left out of any update phase either.

What bit of math an i missing? What causes this?

Thanks.


texts: I am new to game programming and am trying to make a basic 2d top-down space game with 2 space ships that fight each other.  I am doing well with the user controlled space ship, but have no idea how to even start programming an AI.  Are certain methods/patterns better for this situation?  Where would I even begin?


texts:
I'm trying to do collision detection between bullets and enemies in my game. But it's very unpredictable and sometimes it works, sometimes it doesn't (bullet goes straight through without doing anything) and sometimes it kills the script returning "Uncaught TypeError: Cannot read property 'x' of undefined".

The collision detection is just a trivial for loop like this:

if (enemies.length > 0 && bullets.length > 0) {
    for (a = 0; a < bullets.length; a++) {
        for (b = 0; b < bullets.length; b++) {
            if (bullets[a].x + 36 >= enemies[b].x && bullets[a].x <= enemies[b].x + 56 && bullets[a].y >= enemies[b].y && bullets[a].y + 6 <= enemies[b].y + 69) {
                bullets[a].Delete();
                enemies[b].Delete();
            }
        }
    }
}

The .Delete() function is just a reference to arr.splice(index, 1) in the objects. Of course I didn't expect this to be perfect, but I'm surprised by the random behaviour of it. What could cause this and how can I improve the collision detection?


texts: Texture Tiling and Texture Coordinates in Unreal Engine

texts:
I've just started to learn how to develop games and everything is new for me now.

I don't know where to start and I decided to start with Textures and there is something it is difficult to understand for me: Texture Tiling.

I'm not an English speaker and I have searched the meaning of tile and tiling on my own language (Spanish) and I think tile is a way to say repeat the texture across the model instead of stretching it.

I have found PolyCount Wiki and this is how they explain tiling:

  Textures can be repeated across a model, by Tiling the
  TextureCoordinates.

My problem here is that I don't understand the meaning of Tiling. Can I replace Tiling with Repeating without changing the meaning of the sentence?

I have another question is about Texture Coordinates. On PolyCount Wiki they say that:

  Texture coordinates are measured in a scale of 0.0 to 1.0, with 0.0
  and 1.0 at opposite sides of the texture. When a model has a UV
  distance greater than 1 (for example, UV goes from -1 to 2) then the
  texture will tile across the model.

How can I know if I model has a UV distance greater that 1?

By the way, I'm using Unreal Engine, and on its Texture Coordinate element I don't understand the meaning of amount of tiling in their UTiling and VTiling properties.


texts: how can this random scene code run well when it is reloaded?

texts:
I have a code for random scenes, the scenes that I have are 10 randomized scenes, but when I reload the scene there is only one scene.

public static int pointAdd;
// save numbers that will be random
private List<int> myNiceNumbers = new List<int>();
// the name of the scene will appear
private List<string> sceneNames = new List<string>() { "GameDD10", "GameDD20", "GameDD30", "GameDD40"};

private void Awake()
{
    // the object goes on while changing the scene
    DontDestroyOnLoad(this.gameObject);
}

private void Start()
{
    for (int i = 0; i < 5; i++)
    {
        myNiceNumbers.Add(i);
    }
}

public void NextScene()
{
    if (myNiceNumbers.Count != 0)
    {
        int randomIndex = Random.Range(0, myNiceNumbers.Count);
        int randomNumber = myNiceNumbers[randomIndex];

        myNiceNumbers.RemoveAt(randomIndex);

        SceneManager.LoadScene(sceneNames[randomNumber]);
    }
    else
    {
        SceneManager.LoadScene("GameDDComplete");
    }
}


texts: How do I make an object move to certain point?

texts:
I'm trying to force an object to move to a certain point, and stay there, without using LookAt.

This is what I've got, so far. I am trying to move my object to the position of wak.

public Transform airEye;
public Transform airship;

public float move_speed;
public Vector3 wak;

// Update is called once per frame
void Update ()
{
    wak = new Vector3(
        airEye.transform.position.x,
        airEye.transform.position.y + 3,
        airEye.transform.position.z );
    // airship moves smoothly to wak point ?
}

How do I make an object move to a certain position?


texts:
Ok, bear with me, I am a beginner with Google Cardboard programming.
What I have been doing is looking at the TreasureHunter sample app from Google's page and (with the help of documentation and other sources) have been trying to create a simple cube floating in space.
 I have also been trying to avoid making everything as bare bones as the sample, so I have been trying to object orient things such as lights and the meshes.

I am pretty sure that my matrices and methods are correct, but I think there could be something wrong with my shaders.

When I compile the app and install it, no errors are thrown, but I am given just my white screen (set with glClearColor) with the Cardboard binocular UI/view; no cube is rendered, tilting/looking around has no effect.

I am using the colors, verticies, and normals from the Treasure Hunter sample, so those should be correct.

Full source code (Java) is here.

uniform mat4 u_Model; // model position in world space
uniform mat4 u_MVP;  // model in projection space
uniform mat4 u_MVMatrix; // model in view space
uniform vec3 u_LightPos; // Light position in eye/camera space (projection space)

attribute vec4 a_Position; // vertex in local space
attribute vec4 a_Color; //Vertex colors
attribute vec3 a_Normal; //vertex normal

varying vec4 v_Color; // color
varying vec3 v_Grid;
varying vec3 v_Normal;
varying vec3 v_Position;

void main() {
   v_Grid = vec3(u_Model * a_Position);
   v_Normal = vec3(u_MVMatrix * vec4(a_Normal, 0.0));
   v_Position = vec3(u_MVMatrix * a_Position);
   vec3 modelViewVertex = vec3(u_MVMatrix * a_Position); //Vertex position in view space
   vec3 modelViewNormal = vec3(u_MVMatrix * vec4(a_Normal, 0.0)); //Normal in view space

   float distance = distance(u_LightPos, modelViewVertex);
   vec3 lightVector = normalize(u_LightPos - modelViewVertex);
   float diffuse = max(dot(modelViewNormal, lightVector), 0.5);

   diffuse = diffuse * 1.0/(distance * distance);
   v_Color = a_Color * diffuse;
   gl_Position = u_MVP * a_Position;
}

My vertex shader:

My fragment shader:

precision mediump float;

varying vec4 v_Color;

void main()
{
    gl_FragColor = v_Color;
}


texts:
I recently created a tournament system that will soon lead into player rankings. Basically, after players are done with the tournament, they are given a rank based on how they did in the tournament. So the person who won the tournament will have the most points and be ranked #1, while the second will have the second most points  and be ranked #2, and so on...

However, after they are ranked in the new rankings, they can challenge other members and have a way to play other members and change their rank. So basically (using a ranking system), if Player A who is ranked #2 beats Player B who is ranked #1, Player A will now become #1.

I've also decided that if a player wants to compete in the rankings but was not present during the tournament, they can sign up after the tournament, and will be given the lowest possible rank with the lowest score (but they have a chance to move up).

So now, I am wanting to know which way should I go about planning this. When I convert the players from tournament to match rankings, I have to identify them with points. I decided I can do this 2 ways:

1  1000
2  900
3  800
4  700
5  600
6  500
7  400
8  300
9  200
10 100

Or I can have it set up in a exponential type of system where the points will be greater in between the players that are ranked higher.

After looking on the internet I've decided it would be wise to use ELO to give players their new rank after they players have matched against each other.. I went about it on this page: http://www.lifewithalacrity.com/2006/01/ranking_systems.html

So if I go about this my first way, and lets say I have rank #10 facing rank #1. My formula is:

R' = R + K * (S - E)

and the rating of #10 only has 100 points where #1 has 1,000.
So after doing the math rank #10's expected value of beating #1 is:

1 / [ 1 + 10 ^ ( [1000 - 100] / 400) ]
= 0.55%

So
     100 + 32 * (1 - 0.52)
     = 115.36

The problem I have with ELO is it makes no sense. After A rank such as #10 beats #1, he should not only gain something as low as 15 points. I'm not sure if i'm doing the math wrong, or if I'm splitting up the points wrong. Or maybe I shouldn't use ELO at all?


texts: C++: Smart pointers, Raw pointers, No Pointers?

texts:
Within the scope of developing games in C++, what are your preferred patterns in regard to use of pointers (be it none, raw, scoped, shared, or otherwise in between smart and dumb)?

You might consider

object ownership
ease of use
copy policy
overhead
cyclic references
target platform
use with containers


texts: How to make the character move along the axis using touch?

texts:
I have the following code it works, but I don't know how it works.
This is the code I found:
void Update()
{
#if UNITY_ANDROID

    if(Input.touchCount>0 && Input.GetTouch(0).phase == TouchPhase.Moved )
    {
        Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
        float offset = touchDeltaPosition.x * 40f / 18 * Mathf.Deg2Rad;
        transform.position += new Vector3(0f, 0f, offset);
        transform.position = new Vector3(0f, 0f, Mathf.Clamp(transform.position.z, -7.1f, 7.1f));
    }
#endif
}

I need to move the player along the axis by touch, for example, like in the game Cube Surfer!
What I want to get (I used android emulator):

The code I wrote works well at 720x1280, but if you set the resolution to 1440x2960, the controls become too sharp. I know why this is happening because touch.delta is getting too big.
My code:
if (Input.touchCount > 0)
{
    var t = Input.GetTouch(0);

    var delta = t.deltaPosition;

    if (delta != Vector2.zero)
    {
        var offset = transform.position;

        offset.x += delta.x * Sensitivity * Time.deltaTime;

        offset.x = Mathf.Clamp(offset.x, -4f, 4f);

        transform.position = offset;
    }
}

How to fix it?
ScreenToWorldPoint this does not fit because the player moves along a spline.
Thank for help


texts: What's the proper way to use static objects and singletons in Unity?

texts:
I have a GameObject in Unity, which I've attached this script to, in order to make it function as a Static Singleton :

using UnityEngine;
using System.Collections;

public class SceneStatics : MonoBehaviour {

    private static SceneStatics instance;

    public static SceneStatics Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new GameObject ("SceneStatics").AddComponent<SceneStatics> ();
                DontDestroyOnLoad(instance);
            }

            return instance;
        }
    }

    public void OnApplicationQuit ()
    {
        instance = null;
    }
}

I have two other scripts that I'd like to be able to access from scene to scene. What's the proper way to do that?

Do I attach my Inventory and Room scripts to the same game object as the SceneStatics? If so, how do I access them? Can I go from SceneStatics.Instance to one of the other scripts directly via GetComponent?

Alternatively, what happens if I add two child gameObjects (each containing one of the other scripts) to the SceneStatics?

Or is the intended use that I simply make any other static items I need properties of the SceneStatics class? (I.e., add in a Public static Inventory and Public static Room attributes)?


texts:
Background

I've been making my own game from scratch.

I've made my own collision system and there's a situation I'm having an issue with.

Problem

Pictured:

a ball going in one direction and changing direction when it hits the green segment.

I have the trajectory's angle in correlation with [relative to?] OX axes and trajectory's angle (in correlation with)[relative to?] the green segment.

Question

How do I update the initial trajectory angle with the OX to produce the bounce behaviour?


texts:
I'm having trouble with Unity's basic character controlling. After i implemented the crouching in the code below the Input.GetAxis("Horizontal") does not update (while the left control is pressed (crouching), Input.GetAxis("Horizontal") is always set to zero even if left or right arrows are pressed.

The reason why this happens is not because of keyboard buffer etc. because horizontal input is working while jumping, which is implemented pretty much the same way the crouching is implemented in the code below. Btw. no root motion is used. Here's the code:

void HandleInput()
{
    currentBaseState = animator.GetCurrentAnimatorStateInfo(0);

    var deadZone = 0.1f;

    verticalVelocity = moveVector.y;
    moveVector = Vector3.zero;

    // print for testing
    print(Input.GetAxis("Horizontal"));

    if (Input.GetAxis("Horizontal") > deadZone || Input.GetAxis("Horizontal") < -deadZone)
    {
        yRotation += Input.GetAxis("Horizontal");
        animator.SetFloat("Direction", Input.GetAxis("Horizontal"));
    }

    if (Input.GetAxis ("Vertical") > deadZone)
    {
        speed += 0.1f;
        moveVector += new Vector3 (0, 0, Input.GetAxis ("Vertical") + speed);
    }
    else if(Input.GetAxis ("Vertical") < -deadZone)
    {
        if(speed >= 0)
            speed -= 0.1f;
        else
            speed += 0.1f;
        moveVector += new Vector3 (0, 0, Input.GetAxis ("Vertical") + speed);
    }
    else
    {
        moveVector += new Vector3(0, 0, Input.GetAxis ("Vertical") + previousSpeed);
        if(speed > 0)
            speed -= 0.1f;
    }

    animator.SetFloat ("Speed", Input.GetAxis ("Vertical"));

    totalRotation = yRotation * rotationMultiplier;

    transform.eulerAngles = new Vector3(0, totalRotation, 0);

    moveVector = transform.TransformDirection(moveVector);

    if (moveVector.magnitude > 1)
        moveVector = Vector3.Normalize(moveVector);

    Physics.Raycast (gameObject.transform.position, Vector3.down, out hitInfo, 0.5f);
    if(hitInfo.distance < 0.5f)
    {
        if (enableJump)
        {
            if (Input.GetButtonDown("Jump"))
            {
                animator.SetBool("Jump", true);
                verticalVelocity = jumpSpeed;
                skillSlider.value -= 1f;
                if(skillSlider.value == 0f){
                    enableJump = false;
                    bunnyImage.gameObject.SetActive(false);
                    skillSlider.gameObject.SetActive(false);
                }
            }
        }
    }

    if (Input.GetButtonDown ("Crouch")) {
        animator.SetBool ("Crouch", true);
        crouching = true;
    }

    if (Input.GetButtonUp("Crouch")) {
        crouching = false;
    }

    if (currentBaseState.fullPathHash == crouchState) {
        if(!animator.IsInTransition(0)){
            if(!crouching)
                animator.SetBool("Crouch", false);
        }
    }

    if (currentBaseState.fullPathHash == jumpState) {
        if (!animator.IsInTransition(0)) {
            animator.SetBool("Jump", false);
        }
    }

    previousSpeed = speed;

    moveVector = new Vector3(moveVector.x, verticalVelocity, moveVector.z);

    if (moveVector.y > -terminalVelocity)
        moveVector = new Vector3(moveVector.x, moveVector.y - gravity * Time.deltaTime, moveVector.z);

    if (characterController.isGrounded && moveVector.y < -1)
        moveVector = new Vector3(moveVector.x, -1, moveVector.z);

    characterController.Move(moveVector * Time.deltaTime);

}


texts:
I'm new to the Skyrim Creation kit but I've been through a few tutorials and looked through the documentation but I couldn't see a way to do this. Is it possible to display an HTML page within the game itself? Like a popup screen in-game that displays Google or other site? I've looked for a couple of days but feel I might be chasing something that's not possible.

Thanks


texts: Network latency compensation problem for laggy players with collision

texts:
Say there are two clients connected to an authoritative game server, using input + state synchronization strategy. Client 1’s has a round-trip latency of 100ms and client 2 with 400ms latency. For now just imagine each player controls a ball that can collide and bounch off each other.

Client 1 executes command at t = 100 ms, proceeds with prediction for next 100ms (however many steps depending on timestep and framerate)
Client 2 also executes command at t = 100ms,  proceeds with prediction for the next 400ms (or capped at some max prediction timestep)
Server receives client 1’s commands for the next t = 100ms + dt, simulates up to t = 100ms + dt
Say server’s simulation is now at t = 500ms, and client 2’s command for t = 100ms just arrived. In this case I can think of two things to do:

a.  Rewind simulation back t = 100ms and re-simulate back to t = 500ms, if client 1 was affected by client 2’s command (such as collision) send correction to client 1. The results are that:

To client 2, everything looks fine
To client 1, his movement constantly rewinds bottlenecked by client 2 as long as client 2 is affecting client 1

b.  Simulate client 2’s command as if it was executed at t = 500

To client 1, everything looks fine
To client 2, his motion is constantly corrected (either jerky or the interpolation creates strange movements)

With this method you can really only have smooth gameplay for one person. Are there better methods for smoothing out the gameplay for all players? I understand that for FPS you can easily compensate for the the bullet latency because you don't actually see the bullet. But in the case where physics collision can occur between players this becomes troublesome.

Another idea that I have is spawning of a lava pit that is instant death for players. Lava pit spawning done using client side predication can instant kill the player and sync the state later, resulting in smooth gameplay for the client. But if the other player is lagging it will appear as if he is still standing in the pit (or with full prediction will kill him but he’s not actually dead). How do games handle cases like this?


texts:
I always hear about aliasing and anti-aliasing and I know what it looks like but what I don't understand is what causes it. Is it a physical phenomenon? Or a numerical one?

If it helps to explain, I have some programming knowledge, but not in video games or graphics.


texts:
I am just starting to do some very very very basic game dev(in java), i'm trying to create a game of tic tac toe but i am having some trouble implementing an a computer opponent.I just wanted to know if there is anyway to do this other than check every possibility with if statements.This is my best attempt at this but it is kinda broken. ie if points (1,1) and (2,2) are equal to x then it will think that (0,2) is the "best" move but in that situation there would be no "best" move.

some background info on the code, board is a global 3,3 int array. x is just that value that would be inserted when that location is selected. Coor is a class that contain just 2 ints x and y. availableMoves is an arrayList of all the empty areas on the board.

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            if (i <= 1 && j <= 1) {
                if (board[i][j] == x && board[i][(j + 1)] == x && availableMoves.contains(new Coor(i, ((j + 2) % 3)))) {
                    idealMove = new Coor(i, ((j + 2) % 3));
                } else if (board[i][j] == x && board[i + 1][j + 1] == x && availableMoves.contains(new Coor(((i + 2) % 3), ((j + 2) % 3)))) {
                    idealMove = new Coor(((i + 2) % 3), ((j + 2) % 3));
                } else if (board[i][j] == x && board[i + 1][(j)] == x && availableMoves.contains(new Coor(((i + 2) % 3), j))) {
                    idealMove = new Coor(((i + 2) % 3), j);
                }
            }
        }
    }

Thanks in advance for the guidance


texts: Creating several instances of the same object, and selecting only one

texts:
I'm playing around with making a puzzle game, haven't done that much before I run into my first problem. I want to create a certain amount of the same object/function. But without hardcoding the different instances.

I think maybe an array is a good idea? and then a for loop to push the objects in? Then I need to be able to select one of these objects by clicking on it, how would I do that? How do I know which ball in the array was clicked? A loop again?

I made a jsFiddle example (you need to click the orange ball to select, then you can move it around by clicking the canvas). This is what I want to do, but with more balls. How would you solve this?


texts: Implementing AI to hide behind obstacles

texts:
I am developing an AI simulation of predator and prey. I would like to simulate the AI hiding behind obstacles, if it is being chased. But I am still trying to figure out the best way to implement this.

I was thinking along the lines of checking on which side of the obstacle the predator is on and trying to go on the opposite side. Maybe using the A* path finding algorithm to ensure that it gets there using the shortest path.

Now the main reason I am writing is in case somebody is able to point me in the right direction of implementing this (maybe somebody has done this before) or have any other good ideas how to implement it. I have never done anything like this before in terms of programming AI or making any game.

All the obstacles are either horizontal or vertical squares/rectangles.

Additional Info: The map is based on x,y positions with each agent moving at a set velocity.So the map is not entirely tile based, also for that reason I am unsure if A* would actually work in this situation for me.

Here is an image of the situation:

Please also note that the red circle is the predator while the green circle is the prey being chased by the predator.


texts: How to reposition a bouncing ball after it has passed through a surface

texts:
I have a bouncing ball which can collide with lines of a random slope. The ball passes through the lines a bit and I need to set the ball back some distance from the line.

The ball (defined by position and radius) travels according to a speed vector (obtained by multiplying a direction vector by a magnitude) and I want to find the distance between the center and the line so I know how many pixels the ball passed through the line.

In the example the ball passed 10 pixels (radius - dist) after the line, I need to move the center of the ball 10 pixels in the opposite direction.

How can I those pixels between x and y so I can subtract them from the center coordinates?

Thanks


texts: Rotating plane to face object while rotating around z axis. C++

texts:
I want to create a plane 2d sprite plane that looks at a 3d object and then rotates by its z axis.

So I have created a LookAt Function in my game which will make the object look automatically at the sphere, but it is executed every frame, I believe this is because it makes the rotations every frame, now if I want to rotate it again by its local axis, the LookAt() overwrites this because its matrix is being set the same each time and so cannot rotate.

I believe I will have to rotate manually, now I know this problem is easy on one axis of rotation.

My maths is rusty. So I don't think I could just do this for a 3D rotation but I'm not sure. If so do I require quaternions?

Step by step desired action

Rotation on the z axis to make the plane face on the right x angle of sphere ignoring its y position.
Rotate on its x ais to make the plane face the y angle between sphere and 2d plane.
Rotate around the z axis each second, while remaining faced at the object.

@Jay

Here is the code related to the first answer which makes my model dissapear.

selec->SetPosition(a->unit_x, a->unit_y, a->unit_z);
selec->GetMatrix(&rotmatrix[0][0]);
CMatrix4x4 crotmatrix{ &rotmatrix[0][0] };
crotmatrix.RotateLocalZ(0.025);

selec->GetMatrix(&lookatm[0][0]);
CMatrix4x4 clookat{ &lookatm[0][0] };
clookat.FaceTarget(CVector3{ 0,0,0 });

clookat.MultiplyAffine(crotmatrix);
convertmatrix(clookat);

selec->SetMatrix(&lookatm[0][0]);

This does multiply the matrices, but it keeps multiplying and creating a crazy motion, then causes a crash, maybe from gimbal lock?


texts: Resuming swapped out RenderTarget2D in XNA

texts:
Hopefully this will be a simple answer, but as RenderTarget2Ds are Texture2Ds under the hood I was wondering how it handles swapping in and out.

Lets say you create a default one and assign it as the render target at the start of your Game.Render(). Then at a few points during your render process a new RenderTarget is swapped in, rendered to and then kept as a texture for later and the original one is then put back in. Some more rendering occurs and another entity swaps in its own RenderTarget, puts it in another texture and then swaps back to the default RenderTarget, and finally everything is rendered and done.

Now as the RenderTarget2D is a Texture2D without setting preserve mode on the RenderTarget will you be able to swap it out and swap it back in without losing your current contents of the RenderTarget?

I know there are some issues with the Preserve settings for RenderTargets on the Xbox, but if the render targets are being stored as a class member somewhere, are they subject to different rules?

I am sure the answer is, they obey the RenderTargetUsage behaviour, and will be subject to the same rules regardless of how they are stored in the game, but I just wanted to be sure.


texts: Interpolating positions in a multiplayer game

texts:
In order to save bandwidth in my multiplayer game, I do not update every object every server tick, instead each object has an updateRate which tells the game that this object is expected to be updated every X server ticks.

When I receive an update message for an object I calculate the time I expect the next update to come in:

origin = serverCurrentPosition
diff = serverNextPosition - origin
arriveTime = now + timeBetweenTicks * updateRate

When I draw the object I calculate the time that's left till the next update and interpolate the position accordingly:

step = 100 / timeBetweenTicks * updateRate
delta = 1 - step * ((arriveTime - now) / 100)
position = origin + diff * delta

It works... but there's still a bit of jitter in the drawing, although in my theory every thing should work out fine, since the scaling should take care of some amount of lag, should it?

So the question here is, is this the best approach? Should I put actual lag into the computation? If so, how would I do that? I did some experiements, but the jitter only got worse.


texts: How to convert screen space to world space?

texts:
I have a shader that should do raymarching.
But I have problems converting the fragment's position to a worldspace coordinate.
This is my vertex shader:
VertexShaderOutput VS(VertexShaderInput input)
{
    VertexShaderOutput output;
    output.Position = float4(input.Position.xy*2,0.0, 1.0);
    float4 worldPos = output.Position;
    output.WorldPos = mul(worldPos, InverseViewProjection);
    output.UV = input.UV;
    return output;
}

input.Position in this case is a quad from -0.5 to 0.5, hence why I multiply it by 2.
In my pixel shader, I want to get the ray start position from output.WorldPos.
However, the shader outputs WorldPos as this:
x = -118.943700000, y = -25.704420000, z = 23.763410000

This is wrong, because the camera is at around
x = -3846 y = -810 z = 734

What am I doing wrong? I expected a world position, but it seems to be a screen space position?
Here is how I create my matrices (DirectX SimpleMath):
View = Matrix::CreateLookAt(WorldPosition, target, up);
Projection = Matrix::CreatePerspectiveFieldOfView(fov, w / (float)h, n, f);
ViewProjection = View * Projection;
ViewProjection.Invert(InverseViewProjection);
Projection.Invert(InverseProjection);
View.Invert(InverseView);

The game renders perfectly fine, So I am certain The View/Projection Matrices are not wrong.


texts: Which algorithm used in Advance Wars type turn based games

texts:
Has anyone tried to develop, or know of an algorithm such as used in a typical turn based game like Advance Wars, where the number of objects and the number of moves per object may be too large to search through up to a reasonable depth like one would do in a game with a smaller search base like chess?

There is some path-finding needed to to engage into combat, harvest, or move to an object, so that in the next move such actions are possible.

With this you can build a search tree for each item, resulting in a large tree for all items. With a cost function one can determine the best moves.

Then the board flips over to the player role (min/max) and the computer searches the best player move, and flips back etc. upto a number of cycles deep.

Finally it has found the best move and now it's the players turn. But he may be asleep by now...

So how is this done in practice?

I have found several good sources on A*, DFS, BFS, evaluation / cost functions etc. But as of yet I do not see how I can put it all together.


texts: Is It More Efficient To Make Games In Languages I Like?

texts:
Is it more "efficient" to develop games with languages you're good with and like best rather then the "best" language?

For example: I like C# (It's My First Language) and I'm really good at it and used to how it works. I'm not as good with C++; I'm kinda slow at it because I don't prefer how the systems work, like I think int a[] is not as good as int[] a.

Would it be better to go with what I know best or what's the "best" available?


texts: Array of script class references in inspector

texts:
I'm trying to remove the Reflection part of one of my scripts so it works in WebGL, however I am having some trouble.

Basically I need a way to store references to classes in an Inspector array so that I can then use AddComponent() to add them to an object I spawn.

The code I'm using uses arrays to hold different types of AI modules and then chooses a random set of modules and add them to an base enemy prefab. Previously I was using Reflection to create the array and add the modules but that doesn't seem to work in WebGL. Currently the modules are Monobehaviours but it is possible for me to make them normal classes.


texts: Unity / How to Hide "Editor Script" in the Inspector?

texts:
I want to hide the "editor Script" in the Unity Inspector, so it doesnt show up with all the other components (transform/other scripts etc.)
It works with every other "normal" component like this:

component.hideFlags = HideFlags.HideInInspector;

but when it comes to the Editor Script- it just doesnt hide.

EDIT:
My Custom Editor Script:

using UnityEngine;
using System.Collections;
using UnityEditor;

[ExecuteInEditMode]
[CustomEditor(typeof(DetailCamContScript))]

public class CamEditor : Editor
{

    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        DetailCamContScript myScript = (DetailCamContScript)target;
        if (GUILayout.Button("Set Camera Active"))
        {

            myScript.setCamActive();

        }

    }

}

EDIT: Problem solved.

the problem was: The editor-script was attached to a Gameobject.
It doesnt needs to be attached.


texts: How do you create a VR game for a personal VR headset you're making?

texts: If you were to create a whole new VR headset and want to put a game on it, how would you? I know that you you could use Unity and UE4 to create games but those are for stuff like the Rift and Vive. I might be mistaken, but does anybody know the answer to my question?


texts: How to preserve topology for penetration correction?

texts:
I have a sorted list of blocks - some may overlap some may not.
Each block has an ideal starting position and may be constrained to one axis.
There are no velocity or acceleration or other forces involved - just the position.
Some blocks are totally fixed and can never be moved (boundary blocks).

How do I solve the penetrations in a way that the blocks don't overlap anymore, but stay in the initial order?

I can easily solve the penetrations with normal position correction methods, like Baumgarte's stabilization in combination with separation axis theorem. The problem though, a separation normal might be found which pushes the block in a way that the order is changed, which is not what I want, because the application I am writing is a numerical simulation with some visualizations.

I created a simple javascript sample to show what I mean:
http://jsfiddle.net/358hra2j/1/


texts: Does the Maya FBX 2013.3 exporter write tangent and binormal data?

texts:
I'm making an XNA game at the moment and I'm trying to knock out my bump map shader right now. However when I compile the game crashes at the mesh.Draw() line and tells me TANGENT0 is missing. Apparently the FBX 2012 exporter didn't export tangent and binormal data properly, and I'm still having this problem despite installing the most recent exporter for Maya 2012.

For the record the plug-in readme tells me that bug is fixed and I am checking 'Tangents and Binormals' when I export.

What am I doing wrong?


texts: HTML5 platformer collision detection problem

texts:
I'm working on a 2D platformer game, and I'm having a lot of trouble with collision detection. I've looked trough some tutorials, questions asked here and Stackoverflow, but I guess I'm just too dumb to understand what's wrong with my code.

I've wanted to make simple bounding box style collisions and ability to determine on which side of the box the collision happens, but no matter what I do, I always get some weird glitches, like the player gets stuck on the wall or the jumping is jittery. You can test the game here: Platform engine test. Arrow keys move and z = run, x = jump, c = shoot. Try to jump into the first pit and slide on the wall.

Here's the collision detection code:

function checkCollisions(a, b)
{
    if  ((a.x > b.x + b.width) ||
        (a.x + a.width < b.x) ||
        (a.y > b.y + b.height) ||
        (a.y + a.height < b.y))
    {
        return false;
    }
    else
    {
        handleCollisions(a, b);
        return true;
    }
}

function handleCollisions(a, b)
{
    var a_top = a.y,
        a_bottom = a.y + a.height,
        a_left = a.x,
        a_right = a.x + a.width,
        b_top = b.y,
        b_bottom = b.y + b.height,
        b_left = b.x,
        b_right = b.x + b.width;

        if (a_bottom + a.vy > b_top && distanceBetween(a_bottom, b_top) + a.vy < distanceBetween(a_bottom, b_bottom))
        {
            a.topCollision = true;
            a.y = b.y - a.height + 2;
            a.vy = 0;
            a.canJump = true;
        }
        else if (a_top + a.vy < b_bottom && distanceBetween(a_top, b_bottom) + a.vy < distanceBetween(a_top, b_top))
        {
            a.bottomCollision = true;
            a.y = b.y + b.height;
            a.vy = 0;
        }

        else if (a_right + a.vx > b_left && distanceBetween(a_right, b_left) < distanceBetween(a_right, b_right))
        {
            a.rightCollision = true;
            a.x = b.x - a.width - 3;
            //a.vx = 0;
        }
        else if (a_left + a.vx < b_right && distanceBetween(a_left, b_right) < distanceBetween(a_left, b_left))
        {
            a.leftCollision = true;
            a.x = b.x + b.width + 3;
            //a.vx = 0;
        }

}
function distanceBetween(a, b)
{
    return Math.abs(b-a);
}


texts:
How can I create a health bar in JMonkey? Is there some documentation that can help?

I am working on a game, specifically “Battleship”, using the JMonkey Engine (JME3). I want to add health bars on each ship. For the main ship, “the player”, I want to have a fixed-place health bar in the top-left corner of the screen. For the enemy ships, I want to add a health bar that moves with each enemy ship.

While trying to figure out a solution to this idea, I found that everyone was talking about using “BillboardNode”, to create a health bar. On knowing this, I started to search on what a “Billboard Node” means and tried to find any documentation that can explain how to use it. But, with no luck.  I don’t know if I’m missing something, but I can’t find any documentation to help.

I did find a code that creates a health bar:

https://code.google.com/p/jme-simple-examples/source/browse/JMESimpleExamples/src/com/robotfight/Main.java?spec=svn5a70b9fc75bde6b7213e0d098e263660b5db290a&r=5a70b9fc75bde6b7213e0d098e263660b5db290a

But when I try to use it in my code, it doesn’t work. So there must be something that I am missing!

This is the code that I tried to use in my game:

        BillboardControl billboard = new BillboardControl();
        Geometry healthbar = new Geometry(“healthbar”, new Quad(4f, 0.2f));
        Material mathb = mat.clone();
        mathb.setColor(“Color”, ColorRGBA.Red);
        healthbar.setMaterial(mathb);
        Ship.attachChild(healthbar);
        healthbar.center();
        healthbar.move(0, 7, 2);
        healthbar.addControl(billboard);


texts: How are 2D transformation matrices applied to their targets?

texts:
I understand mathematically how transformation matrices work, in that a transformation matrix multiplied by a vector results in a new vector, and we use the matrices for rotation, translation, etc. I also understand that in 3D, the transformation matrices are applied to every vertex of each model in order to transform them, although that's basically the extent of my understanding vis-a-vis 3D transforms, and maybe even that understanding is a little wrong/simplistic.

However, many game engines/graphics rending libraries are designed with the intention of rendering 2D graphics (ex: Flash, XNA, SDL, Allegro), although I know at least some of them are really 3D under the hood. These engines allow the programmer to use transformation matrices to manipulate 2D entities, to do something like implementing a camera, for example. But I don't understand what the transformation matrices I'm plugging in to the engine are being multiplied by in order to perform the transformation. For a while I assumed it was applying the transformation matrix to each pixel of the original image, but that doesn't seem right to me.

So what vectors are the transformation matrices being multiplied by in the 2D transformations? Was I right, and it's really a per-pixel operation? Or does it do some kind of 3D magic under the hood?


texts:
I have just recently started some experiments with game development in Javascript/HTML5, and so far it has been going pretty well.  I have a simple test scene running with some basic input handling, and a hundred-ish drawImage() calls with a few transforms.  This all runs great on Chrome, but unfortunately, it already chugs on Firefox.  I am using a very large canvas ( 1920 x 1080 ), but it doesn't seem like I should be hitting my limit already.  So on that note, I was hoping to ask a few questions:

1) What exactly is done on the CPU vs. the GPU in terms of canvas and drawImage()?  I'm afraid the answer is probably "it depends on the browser", but can anybody give me some rules of thumb?  I naively imagined that each drawImage call results in a textured quad on the GPU with the canvas effectively being a render target, but I'm wondering if I'm pretty far off base there...

2) I have seen posts here and there with people saying not to use the translate(), rotate(), scale() functions when drawing on the canvas.  Am I adding a lot of overhead just by adding a translate() call, as opposed to passing in the x,y to drawImage()?  Some people suggest using "transate3d", etc., which are CSS properties, but I'm not sure how to use them within a scene.  Can they be used for animated sprites within a single canvas?

3) I have also seen a lot of posts with people mentioning that pre-building canvases and then re-using them is a lot faster than issuing all the individual draw calls again.  I am guessing that my background should definitely be pre-built into a canvas, but how far should I take this?  Should I maintain an individual canvas for each sprite, to cache all static image data when not animating?

Thank you much for your advice!


texts: How can I fade a game object in and out over a specified duration?

texts: I would like to know how I can fade a game object in and out. I would like to achieve this using a C# script. As I am quite new to Unity I've read about coroutines but still haven't fully grasped the concept. I would appreciate some assistance.


texts: Finding it difficult getting to grips with LibGDX

texts:
So I have spent about a week now learning libGDX and have made very little progress.

I started small and wanted to make a strategy game where there is a tiled map of squares and you control a ship, move it from tile to tile to take out enemy ships. After a week of troubleshooting I have only just managed to import and render the map and can barely get sprites to render in the right places. Having read the libGDX wiki multiple times I can still find very little documentation online about making strategy games with libGDX and I'm pretty stuck.

Did I pick the wrong framework ? or am I just not looking in the right places?

From what I have read online libGDX is not the best on documentation so is it right for a beginner like me or would something else be better? Thanks :)


texts: Why is my gravity script repelling and not attracting?

texts:
I'm currently working on a small simulation of Newton's Law of Gravitation in Unity3d, and it seems to be working pretty well, except, it's doing the opposite of what I expected. Instead of attracting as it should, this script is repelling objects instead:

using UnityEngine;

/// <summary>
/// Gravity component.
/// </summary>
public class GravityComponent : MonoBehaviour
{
    public float gravityConstant;
    public Vector3 startingForce;
    public GameObject twinObject;

    /// <summary>
    /// Applies attraction to the object.
    /// </summary>
    public void ApplyAttraction()
    {
        Vector3 currentForce = this.transform.position - this.twinObject.transform.position;
        float attraction =
              ((this.gravityConstant * this.rigidbody.mass * this.twinObject.rigidbody.mass)
            / (Mathf.Pow(currentForce.magnitude, 2)));
        this.rigidbody.AddForce(currentForce * attraction);
    }

    public void Start()
    { this.rigidbody.AddForce(this.startingForce); }

    public void FixedUpdate()
    { this.ApplyAttraction(); }
}

While it is possible to "fix" this by making the result of the attraction calculation negative as seen below, this solution feels "dirty", as it's not truly following Newton's Law of Gravitation.

float attraction =
      -((this.gravityConstant * this.rigidbody.mass * this.twinObject.rigidbody.mass)
    / (Mathf.Pow(currentForce.magnitude, 2)));

What's the issue here? Is there a way to solve this issue without the above "dirty" fix?


texts: Rotating Object parallel to other object

texts:
I try to rotate objects in the same direction as a reference object.

Normaly this would be easy:

object1.rotation = reference.rotation

But the same rotation can be expressed with different vectors:

(0, 45, 270) is the same as (0, 225, 90)
(0, 0, 270) is the same as (0, 180, 90)

In my case the final rotation should account for this.

The reference object has a rotation of: (0, 45, 270)

Object1 Should Rotate from (0, 45, 270) to (0, 0, 270)

Object2 Should Rotate from (0, 225, 90) to (0, 180, 90)

How can i calculate this?
Im using unity if this is any help.


texts: How can I use Rectangle.Intersect() to resolve collisions in XNA?

texts:
I have a 2D game written in XNA, and I've been trying to fine-tune my collision resolution. All of my game objects are squares, which means detecting a collision is easy - use the position and the size of each entity (which is already known) to craft a corresponding Rectangle, then compare the two with Rectangle.Intersect().

This works fine for the most part, but has been running into weird corner cases where the collision resolution doubles an entity's jump height, or gets caught between tiles when moving horizontally across a flat surface.

I have recently expanded my code to include a velocity for each game entity, and I thought it would be possible to avoid some of these problems by preventing the need for these resolutions in the first place.

The idea would be to use an entity's position + velocity to predict a collision, then reduce the velocity to prevent a collision from occurring in the first place.

I can still use Rectangle.Intersect() to determine if the entity is in a collision, but I'm horribly confused on how to go from the Rectangle returned by Rectangle.Intersect() to an appropriate velocity counter-vector to avoid the collision.

Is there a straightforward way to go from the intersection Rectangle to an appropriate counter-velocity?


texts:
I'm using RayCast node to check the object is grounded. Here's the setting:

RayCast node is placed near by ground and the length enough to collide with ground. Also RayCast node is enabled.

RayCast node is child node of FPSController node, and here's the code of FPSController that processing grounded logic:

onready var ground_check_raycast: RayCast = $GroundCheckRayCast

func _physics_process(delta):
    process_grounded(delta)

func process_grounded(delta):
    var hit_collider = ground_check_raycast.get_collider()
    print(hit_collider)

When I run the game, first few times it return floor, and then immediately return false and never return floor back.

** Debug Process Started **
OpenGL ES 3.0 Renderer: GeForce GTX 1070/PCIe/SSE2
[StaticBody:1140]
[StaticBody:1140]
[StaticBody:1140]
[Object:null]
[Object:null]
[Object:null]
[Object:null]
...

I have no idea why this won't work. Is there a something that I missed?

P.S. Floor object has static body and CollisionShape.
P.P.S. Using Godot 3.1.1


texts:
While I have a lot of experience with coding SW&HW 3D rasterizers across multiple platforms and eras, I never got to coding a 2D renderer for a non-polygonal racing game with multiple rolling hills (with correct perspective and occlusion). Say, something like a Lotus from 1990.

Of course, the roadside props and cars are all sprites, but I'm curious as to how the road, especially with rolling hills is done.
My uneducated guess is that it's composed from separate horizontal lines (that have the terrain and road texels), which are simply stacked above each other with zero horizontal offset (for the straight road) and once you approach the curve, the horizontal offset for the given scanline is taken from a look-up table (for a given curve). Given enough RAM we could have a lot of different curves. Or perhaps if the curve equation is simple (not some Bezier stuff), then it could be even calculated at run-time (integer / fixed-point, of course).
This should supply the illusion of curved road.

Now, for the single rolling hills, we would probably merely introduce a vertical offset to our road scanlines, so this could give an illusion of going up/down the rolling hills, as all scanlines would move up/down on the screen.

What I don't quite understand is how the multiple rolling hills with a perspective are done, especially if they are overlapping correctly. This is probably hard to visualize, but imagine there is a second hill in the distance, and you are climbing up the hill in front of it. While climbing up, you can see it in the distance, and when you get to the top of the hill, the valley between two hills appears. With polygonal gfx, this is super easy and you don't even think about it - the valley is just back-face culled polygons, so it's obvious they did not get rendered when climbing up the first hill. Meaning - the valley is transformed, clipped and discarded thanks to back-face culling.

But how would you do that with the 2D horizontal scanlines ? Perhaps using SW Z-Buffering on each scanline ? One idea could be that you separate the scanlines for the hill up and the hill down - e.g. you only start rendering those scanlines when you get to the top of the hill- but I doubt it would work flawlessly.

I suspect, as with everything in game coding, once you start prototyping it, a solution would simply be reached by multiple iterations/prototypes. I'm in the middle of some other project now, so I don't want to distract myself with another project, hence this question.

EDIT: StackOverflow supplied few links, right before I submitted the question, and one of the threads contained this link:
http://www.extentofthejam.com/pseudo/
It explains in a great amount of detail various techniques for this type of rendering. I am in the middle of it right now. From what I can see, the early games did actually use the FOV projection! That explains why their 'feeling' of perspective was so exact, as you can't really hack it properly (especially for a 3D-trained eye).


texts:
I am looking for an engine or library to develop a game for iOS on Linux.

High level, low level, GUI, no GUI, does not matter too much. I am really looking for anything.

I'm not actually talking about deploying to iOS from Linux or anything like. I just want to do the bulk of the work on Linux, with minimal changes required to run it on iOS.

Edit: YES, I do have access to a Mac, but it is limited. So I want to be able to work on the project on my regular Ubuntu box.

Also, I am in the paid developer program, so I can deploy to iOS devices from the Mac.


texts:
I am a beginner. I created a 3D project with a cube object, and I am getting this pink display, in the camera view.

Why is the camera view pink?


texts:
I am having trouble with making a Breakout Clone using JavaFX. I have almost everything working, but I have a problem with the physics of the ball after it bounces off of the paddle. I used this question to get the physics working with the paddle, but only slightly. Instead of working nice and clean after switching around x and y values, the ball will sometimes end up getting stuck inside the paddle and jittering back and forth very rapidly instead of bouncing off. I have tried getting a "future version" of the ball, by checking where it would be on the next frame, but it still ends up doing the same thing. My code is here for anyone who is interested (it is all one class file, so I figured I would just use a pastebin).

Thanks in advance for any help!

EDIT: If anyone needs a video of what is happening, I will post one.


texts: How to use XML files as content files in XNA?

texts:
I have an XML file representing different car manufactures that will be available in my game. The file looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<XnaContent>
  <Asset Type="List[string]">
    <car>Audi</car>
    <car>BMW</car>
    <car>Nissan</car>
    <car>Volvo</car>
  </Asset>
</XnaContent>

When adding it into my content folder, the compiler return this error:

There was an error while deserializing intermediate XML. Cannot find type "List`1"

How can I create a list of strings, put it into XML and read it from XNA?


texts:
Lets say you are playing Starcraft 2 melee map. The game loads the map.
Melee maps have the following dependencies:

Liberty (Mod)
Liberty Multi (Mod)

I think the game engine will load the data from Liberty (Mod) first, then from Liberty Multi (Mod). For data that exists in both dependencies, the engine will use the one from
Liberty Multi (Mod). Is this correct?

Liberty Multi (Mod) is updated with each patch of Starcraft 2.
Does the game engine load just the latest version of Liberty Multi (Mod)?
  or
Does the game engine load all the versions and overwrite duplicate data with the latest version?


texts: Three.js— how to rotate sphere without moving light (using OrbitControls)?

texts:
Okay, I think the problem that I'm having is that when I create my DirectionalLight with three.js, when I then rotate my object with OrbitControls the entire scene is rotating, not just the sphere I have in the middle of it ( the only object I have in my scene ).
I want to make it so that I can rotate my sphere with my mouse like OrbitControls does, but not have the camera move. Or have the light not move with the camera? Here's a gif of my scene so far that might better explain my dilemma—

I want the light to be.. y'know.. more like the sun, coming from one point in space and shining at (0,0,0) in my scene, while still being able to rotate the sphere independently. Am I using OrbitControls wrong here? Here is what I have to get to the point I have in the gif above:
var width = section.offsetWidth,
height = section.offsetHeight;

var topOfElement = section.getBoundingClientRect().top - height;
var bottomOfElement = section.getBoundingClientRect().bottom;

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
camera.position.z = 10;
camera.position.x = -2.5;

const controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.enableZoom = false;
controls.maxPolarAngle = Math.PI;

const renderer = new THREE.WebGLRenderer( { alpha: true } );
renderer.setClearColor( 0x000000, 0 );
renderer.setSize(width, height);
section.appendChild(renderer.domElement);

const onEverythingLoaded = () => {
    render();
};

const loadingManager = new THREE.LoadingManager(onEverythingLoaded);
const loader = new THREE.TextureLoader(loadingManager);

const earthGeomerty = new THREE.SphereGeometry( 5.5, 32, 32 );
const earthDiffuse = loader.load('assets/drought_earth_texture.png');
const earthSpec = loader.load('assets/drought_earth_texture_bump.png');

const material = new THREE.MeshPhongMaterial( {
    specular: 0xffffff,
    map: earthDiffuse,
    specularMap: earthSpec,
    normalScale: new THREE.Vector2( 1, 1 ),
    shininess: 30,
    transparent: true,
    depthTest: true,
    depthWrite: false,
    polygonOffset: true,
    polygonOffsetFactor: - 4,
    wireframe: false
} );

const sphere = new THREE.Mesh( earthGeomerty, material );
const ambientLight = new THREE.AmbientLight( 0x667777 );

const directionalLight = new THREE.DirectionalLight( 0xffffdd, 2 );
directionalLight.position.set( 4, 0, 0 );
scene.add( sphere );
scene.add( ambientLight );
scene.add( directionalLight );

const render = () => {
    animationFrame = requestAnimationFrame( render );
    sphere.rotation.y += 0.001;
    renderer.render( scene, camera );
};

For further clarification, I want to have my light work like this:

while still being able to rotate the earth with my mouse like with OrbitControls. But the light doesn't move.
Is OrbitControls the wrong tool here? Any documentation / helpful links would be appreciated I am so, so lost.
(I cross-posted this from stackoverflow because I thought maybe the people over here would know more about this, hope that's ok!)
Update
After much fussing about with the OrbitControls functions I realised that what I'm trying to do isn't what OrbitControls is for, because "orbiting" isn't what I'm trying to do— I'm trying to rotate the actual sphere with my mouse, which is entirely different. Welp.


texts: Is this equivalent to D3DXVec3TransformNormal?

texts:
I was porting some code from DirectX to OpenGL.
I have the following code:

glm::mat4 rotation(1.0f);
rotation = glm::rotate(rotation, degrees, m_up);
m_look  *= rotation;

where rotation is a mat4 and m_look is a vec3. I wanted to know if the last line here,

m_look  *= rotation;

has the same effect as

D3DXVec3TransformNormal( &m_look, &m_look, &rotation );

in DirectX? If not, then what would be the correct alternative?


texts: Rendering everything with a shader when only squares are needed?

texts:
I am building a game that is tile-based (filled with glowy vector squares). Right now, I am considering using instancing for drawing these, but I would like to know if there is a faster approach.

The squares are all of the same size. They should be rendered in a rectangular grid, and I know exactly how many of them I should render. The squares are also made with linelists (so 8 vertices for a single rectangle).

Knowing all this, is instancing still the best approach? Or can I utilize the GPU more here? (in my game, I only utilize 1% of the GPU, but 100% of the CPU).


texts: Let's say I have Rotation(0, 0, 180) [pitch, yaw, roll]. How to do it that I would have Rotation(180, 180, 0) which is exactly the same?


texts: I'm writing a game and map editor using Java and jMonkeyEngine. In the map editor, I've got a brush done by wireframed sphere. My problem is: I want to make it visible everywhere, so I want to invert color of the pixel "behind" this brush. I wanted to do it with fragment shader (GLSL), but I don't know how to get color of this pixel.


texts: Replacing all objects in scene with another object

texts:
I have around 100 objects (prefab A) in my scene, all in different positions.

Is it possible to replace all of these objects with another object (prefab B), so that the prefab B objects are placed in the same position as the prefab A objects were?

I want this done in the editor, not in game.


texts: problem with SCNTransaction in Scene Kit

texts:
I'm trying to move an object over a period of ten seconds from y coordinate 0 to y coordinate 10.  the object is created at y coordinate 0.  The problem is when the animation starts, the object pops to the end position for like one second or so then pops back down to the starting position and begins the animation properly.  Why is the object ending moving to the end location instantly, and how can I prevent this from happening?

//create box bottom
func createGrabBox() {
    grabbottom = grabBox.rootNode.childNodeWithName("grabbottom", recursively: true)!
    grabbottom.position.y = 0
    grabbottom.geometry!.firstMaterial!.transparency = 0.5
    grabbottom.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.Dynamic, shape: nil)
    grabbottom.physicsBody!.restitution = 0.0
    grabbottom.physicsBody!.friction = 1.0
    grabbottom.physicsBody!.categoryBitMask = ColliderType.grabBottomCatagory.rawValue
    grabbottom.physicsBody!.collisionBitMask = ColliderType.diceCatagory.rawValue
    scene.rootNode.addChildNode(grabbottom)

    //animation snippet
    SCNTransaction.begin()
    SCNTransaction.setAnimationDuration(10.0)
    SCNTransaction.setCompletionBlock() { }
    grabbottom.position.y = 10
    SCNTransaction.commit()

    //physics field for this object
    let field = SCNPhysicsField.linearGravityField()
    field.strength = 0
    field.direction = SCNVector3(x: 0, y: 0, z: 0)
    field.categoryBitMask = ColliderType.grabBottomCatagory.rawValue
    //only things with categories that match the field's will be affected by it
    let fieldNode = SCNNode()
    fieldNode.physicsField = field
    scene.rootNode.addChildNode(fieldNode)
}


texts: How to get tilemap transparency color working with TiledLib's Demo implementation?

texts:
So the problem I'm having is that when using Nick Gravelyn's tiledlib pipeline for reading and drawing tmx maps in XNA, the transparency color I set in Tiled's editor will work in the editor, but when I draw it the color that's supposed to become transparent still draws.

The closest things to a solution that I've found are -

1) Change my sprite batch's BlendState to NonPremultiplied (found this in a buried Tweet).

2) Get the pixels that are supposed to be transparent at some point then Set them all to transparent.

Solution 1 didn't work for me, and solution 2 seems hacky and not a very good way to approach this particular problem, especially since it looks like the custom pipeline processor reads in the transparent color and sets it to the color key for transparency according to the code, just something is going wrong somewhere.  At least that's what it looks like the code is doing.

TileSetContent.cs
    if (imageNode.Attributes["trans"] != null)
        {
            string color = imageNode.Attributes["trans"].Value;
            string r = color.Substring(0, 2);
            string g = color.Substring(2, 2);
            string b = color.Substring(4, 2);
            this.ColorKey = new Color((byte)Convert.ToInt32(r, 16), (byte)Convert.ToInt32(g, 16), (byte)Convert.ToInt32(b, 16));
        }
        ...

TiledHelpers.cs
    // build the asset as an external reference
            OpaqueDataDictionary data = new OpaqueDataDictionary();
            data.Add("GenerateMipMaps", false);
            data.Add("ResizetoPowerOfTwo", false);
            data.Add("TextureFormat", TextureProcessorOutputFormat.Color);
            data.Add("ColorKeyEnabled", tileSet.ColorKey.HasValue);
            data.Add("ColorKeyColor", tileSet.ColorKey.HasValue ? tileSet.ColorKey.Value : Microsoft.Xna.Framework.Color.Magenta);
            tileSet.Texture = context.BuildAsset<Texture2DContent, Texture2DContent>(
                new ExternalReference<Texture2DContent>(path), null, data, null, asset);
       ...

I can share more code as well if it helps to understand my problem.  Thank you.


texts: Procedural generation of stars in the background with given random seed

texts:
I want to generate stars (actually a 2d vector) in the background. The player is moving left and right endlessly. When the player moves the stars, which aren't in sight anymore, should be deleted from the ArrayList to keep things small. But when the player turns back in the other direction again, the same star(coordinate) should be there again. But the random generator gets a different number, which is normal. How can I do something like lastInt() like I do with nextInt() ? Or what is the proper way to do something like this?
Thank you very much.


texts: What is the proper use of CADisplayLink, and where do I put game logic?

texts:
I have an iOS OpenGL ES 2.0 game and currently have a CADisplayLink with a :render method. In this render method I do all the game's logic updates and drawing.

Is this correct? Or should my game logic go somewhere else - and if it should go elsewhere... where?

The reason I'm asking is that I've been writing a game and it's starting to exhibit strange behaviour which I suspect is related to the game logic taking longer than a frame to compute, and after following a few different 'fix your timestep'/framerate independent drawing type posts I can't quite match it to how iOS handles things since in iOS there isn't a 'main' style loop.


texts:
I'm trying to make a board game, there the player has to press four buttons to make the L. It can be mirrored or rotated, it just has to be an L.
But if the player press four buttons and make another shape, like a line or a Z, the system must recognize it and alert the player.


texts: How to get display resolution (screen size)?

texts:
How to get display resolution in XNA/Monogame ?
I tried these on my monitor (1600x900):

The below give me 800,600

//1.
GraphicsDevice.DisplayMode.Width
GraphicsDevice.DisplayMode.Height

//2.
GraphicsDeviceManager graphics = new GraphicsDeviceManager(this);
graphics.GraphicsDevice.DisplayMode.Width
graphics.GraphicsDevice.DisplayMode.Height

//3.
GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width
GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height

//4.
foreach (DisplayMode dm in GraphicsAdapter.DefaultAdapter.SupportedDisplayModes)
{
    Console.WriteLine(dm.Width);
    Console.WriteLine(dm.Height);
}


texts: Converting to LWRP in unity leads to everything being purple

texts:
I was trying to use Unity's shader graph which leads me down the path of needing to convert to lightweight render pipeline. When I did I found everything is now pink, not just one or two assets like everything in the scene but the terrain. I have tried a few things that have been suggested such as changing to a pipeline asset in graphics and reimporting all but no luck.
It did ask me if I wanted to convert to LWRP materials and I said yes for the project.  I can't imagine everyone rewrites every single one of their legacy shaders into LWRP or just throws them all out to only use new assets that are lwrp compatible. Even fairly basic particle effects are purple, I also tried adding all the built-in pipeline shaders in the include section.
Also, most of the docs I am reading keep saying go to create < rendering pipeline < LWRP but I don't see that as an option I see Universal Rendering pipeline instead.
Any ideas?


texts: Vertical Camera Movement in a 2D Platformer

texts:
I would like to ask about how vertical camera movement should be handled in a platformer in which the player changes his Y position frequently. For the past two days I've tried to adjust the camera movement and I haven't made any satisfying progress.

In principle, the camera's height should change as infrequently as possible, to avoid causing nausea. It also has to react quickly enough to the player's change in direction so he could see where he's going. An example of vertical camera movement done very, very well is in Rayman: Origins or Rayman: Legends.

How did you think vertical camera movement should be done in a platformer?


texts: Emissive material not casting light on itself in Unreal

texts:
I have a static mesh that has an emissive material applied to part of the mesh. The emissive material successfully cast light to surrounding objects. However, the face of the mesh with the emissive material fails to cast light on the rest of the mesh.

This is how the unlit scene look:

The parts circled blue has the emissive material, and the sphere and cube are both lit by the emissive material. However, the part of the stairs (highlighted in red) does not get lit.

The lit scene:

Is there a way for the stairs to be lit by itself?


texts: Why would an online MMO throttle actions per day?

texts:
I started playing Die2Nite and was surprised that it has such a strict limit on the number of actions per day. After a while, I figured it was just part of the charm.

I also started playing Magic Duel and it has a similar mechanic that limits the amount of actions per day.

Is there a game design principle behind a decision to limit actions per day in an MMO?


texts:
I have working omnidirectional shadow maps for point lights. Rendering a shadow map for one point light consists of rendering the scene to 6 separate rendertargets, then send those render target textures (shaderresourceviews) to a pixel shader which will shadow the scene by projective texturing. Switching rendertargets 6 times for each point light however is quite costly, and so does sampling from those in the pixel shader later.
My question is how would I access a face of the cubemap to render to? Now I am doing Id3d11devicecontext::omsetrendertargets(1,NULL,&depthtarget) . My depthtarget is a texture2d which is bound to a depthstencil view and a shaderresource which is set up to be a cubemap. Can I even set an individual face to render to or is the process completely different?


texts: How to combine the camera that follows the player and the camera shake effect in Unity?

texts:
I need to combine both camera that follows the player and the camera shake effect in the same moment. The problem is in that, if I make the shake effect for the camera, then the camera doesn't follow the player and if I make the camera follow the player, then the shake effect doesn't appear. The basic idea of my script is next:`

Vector3 originalPos;
GameObject targetPlayer;
bool canShake;
void OnEnable()
 {
     originalPos = camTransform.localPosition;
 }

 void Update()
 {
         // Camera shakes
     if (CanShake)
     {
         transform.localPosition = originalPos + Random.insideUnitSphere * shakeAmount;
     }
         // Camera follows the player
     else
     {
         transform.position = new Vector3(targetPlayer.transform.position.x, transform.position.y, transform.position.z;
     }
 }

Does anyone have ideas how to combine these two things (camera shake effect and camera that follows the player) at the same moment?


texts: How to Stop Background Music When The Game is Over?

texts:
I am working on a 2D Angry Birds type Unity game. I Created Menu Scene and Level One Scene and all the required scripts are added. After adding background music to Level One, when the game is over and return to Menu I can't stop the music. The Menu scene has its own music and when the level one is over, it continues with its own music and gets mix with the menu scene music. I tried to add Destroy() function to level one GameObject but Level One music became silent after I restart with my menu scene. Here is my code for the attached music game object:

public class background_sound : MonoBehaviour {
    public static bool soundBreaker = false;

    public void Start () {
        if (!soundBreaker) {
            AudioSource myAudio = GetComponent<AudioSource> ();
            myAudio.Play ();
            DontDestroyOnLoad (myAudio);
            soundBreaker = true;
        }
    }
}

And here is the Menu Script:

public class MenuScript : MonoBehaviour {

    public void StartGame () {
        SceneManager.LoadScene ("Level One");
    }
    ...

Here is the code that loads the Menu Scene..

public void GameOver() {
    musicObject.setActive(false);
    startCoroutine(restTime());
}

IEnumerator restTime() {
    yield return new WaitForSeconds (3);
    SceneManager.LoadScene("Menu");
}