texts:
I'm making a Flash game (ActionScript 3) and for dynamics I'd like to make the background change colour depending on the clients' time of day.

I have a rough idea on how I want to do this,

At sunrise, I want the background to be yellow-orange
In the middle of the day, I want the background to be cyan/clear sky colour
At sunset, a reddish-orange
During the night, a navy blue.

I will be using this method to change the colour of the symbol, which is at default a dark grey colour. (unless someone points out a better way to do this). This means I have access to the red, blue and green components of the background.

On implementing the system itself;
I suppose I could simply get the client time and do

if (hour > 9) and (hour < 18)
{
    colour = SKY_BLUE
}

and similar for the other times of day, but I'd like it to tween slowly between colours as time progresses. For example, if 6AM is yellow-orange and 9AM is blue, 7:30AM would be yellow moving towards blue. I have a feeling I need to come up with an algorithm to link time to the RGB components of the colour, but I've always been terrible at maths and I can't think of how to do this, so that's why I'm asking.

Please tell me how I would do this, both concept outlining and sample code, or even just tips are welcome. :)


texts: I exported the rig from 3ds Max as a FBX file and opened it with Cinema 4D. Everything works great, but the model and a different look to it. Also the mask on her head has a different texture, but it was imported with only 1 object. Just wondering if it can be fixed, if not its ok.


texts: How can I improve on this engine design?

texts:
I am trying to come up with a terrain visualization system and I am writing a simple graphics engine for this. For some reason, I wanted to try a new idea. Rather than using dynamic polymorphism and derive from a GameObject like class for all the entities in the screen, I go for something like this.

First, I want to have a very simple scene graph, very non-sophisticated. For this, I am using a heterogeneous vector like given here. My scene graph will be just a heterogeneous vector of possible renderable items. I will iterate through each item using visitors.

For example my Terrain class looks like following

template <typename RenderAPI>
class HeightmapTerrain
{
public:
    // constructor like things
    void render();
    void input();
    // imagine the rest
private:
    Heaightmap hm;
    Transformation tm;
    TerrainInputHandler tih;
};

Then I will have a specialization of this for OpenGL as follows

template <> class HeightmapTerrain<OpenGLAPI> {
public:
    // as an example
    void render()
    {
        BasicTerrainGLSLShader ts;
        ts.bind();
        hm.generateVBO();
        // etc.
    }
private:
};

typedef Terrain<OpenGLAPI> HeightmapOpenGLTerrain;

Assume all of these are in a file called Terrain.h. I am planing to include that file and I will add an instance of HeightmapOpenGLTerrain to my scene graph. This way, I can call render_visitor() in the render function of my scene graph and since it is a heterogeneous vector all will work, I hope.

The reason I am doing this is because if I want to extend the system with new graphics APIs, I will just create a new specialization and implement render etc. methods as

template <> class HeightmapTerrain<VulkanAPI> {
public:
    // as an example
    void render()
    {
        // Vulkan implementation
    }
private:
};
typedef Terrain<VulkanAPI> HeightmapVulkanTerrain;

With this, I can use same scene graph to render and input handle etc. but now using Vulkan. It feels like I can easily change the Input mechanism as well, with this system.

Now, what I am asking is this; I am not really that great at template programming. Is this approach feasible? What are the performance and design disadvantages compared to dynamic polymorphism approach we all know and love? Is this design downright obtuse? Lastly, can I have different private members for different specializations? Let's say I wanted to also have HeightmapTerrain<OfflineRendering> to render using path tracing. Can I add an extra private member to this specialization, like Canvas cs?


texts: difference between cocos2d-x vs cocos2d-js

texts:
I'm just moving towards native apps... A friend of mine told me to start with cocos2d, I'm good in javascript. While searching google for cocos2d, and within cocos2d-x.org I found

cocos2d-x
cocos2d-JSB
cocos2d-html5
cocos2d-Javascript

I know what cocos2d-x is for.. and what cocos2d-html5 is for.. but what is cocos2d-JSB and cocos2d-Javascript..
Can somebody please tell me.. what exactly these 2 things are..
My questions are:

Can we develop 100% pure native apps/games in cocos2d-JSB and or cocos2d-javascript.
I also know cocos2d-JSB is javascript bindings.. but what does that exactly mean?..
Last but not least question.. what is cocos2d-Javascript for?.. does that work alone or we need cocos2d-html5 to make it previewable in iOS/Android/WindowsPhone...

Please give me Details.. because i'm so confused... I want to develop native apps for iOS/Android and WindowsPhone.

Thank you


texts:
I'd like to use the function

int SDL_SetRenderTarget(SDL_Renderer *renderer, SDL_Texture  *texture)

in my 2D game. At this point I am using only the SDL 2.0 API, and using openGL seems overkill to me. Rendering to an intermediate texture would greatly simplify the programming of a camera system and split-screen support. However, the (sparse) SDL wiki documentation states:

  Before using this function, you should check the
  SDL_RENDERER_TARGETTEXTURE bit in the flags of SDL_RendererInfo to see
  if render targets are supported.

This raises the question wether or not can I rely on the availability of this function. I was unable to find any information on the subject on the web.


texts: How do I implement anti-aliasing in OpenGL?

texts:
I want to do full-screen anti-aliasing in OpenGL, and dont want to use the anti-aliasing that is provided by OpenGL itself, since I am building a game and want good effects in it.

How should I proceed?


texts:
I have a 2D RPG game written in Java using LWJGL. All works fine, but at the moment I'm having trouble deciding what the best way to do depth perception is. So , for example, if the player goes in front of the tree/enemy (lower than the objects y-coordinate) then show the player in front), if the player goes behind the tree/enemy (higher than the objects specific y-coordinate), then show the player behind the object.

I have tried writing a block of code to deal with this, and it works quite well for the trees, but not for the enemies yet. Is there a simpler way of doing this in LWJGL that I'm missing?


texts:
I had written a program using PyGame that should play sounds. I created sounds in Audacity, saved it as WAV (Microsost) signed 16 bit PCM. They are played well on Linux, but aren't loaded in Windows. There is exception:

    self.start_signal = pygame.mixer.Sound(open('start.wav'))
pygame.error: Unrecognized file type (not WAVE)

Same error if I try to use Ogg Vorbis:

    self.start_signal = pygame.mixer.Sound(open('start.ogg'))
pygame.error: OGG bitstream is not valid Vorbis stream!

But I can play sounds in both formats in Windows Media Player.

pygame-1.9.1.win32-py2.7.msi


texts: How do I create a curved line or filled circle or generally a circle using C++/SDL?

texts:
Hello I've been trying for ages to make a pixel circle using the putpixel function provided by SDL main website here is that function :

void putpixel(int x,int y , int color , SDL_Surface* surface)
{
    unsigned int *ptr = static_cast <unsigned int *> (surface->pixels);

    int offset = y * (surface->pitch/sizeof(unsigned int));

    ptr[offset + x] = color;
}

and my question is how do I curve a line or create an circle arc of pixels or any other curved shape then a rectangle or singular pixel or line.

for example here are some pictures

filled pixel circle below
enter link description here

now my idea was too

change the x and y value of the pixel position using + and -  to create the curves but in practice didn't provide the correct results

what my results are in this is to be able to create a circle that is made out of pixels only nothing else.

thank you for anyone who takes the time to read this question

thanks! :D


texts:
After a bit of research (And a bit of experimenting) I found that coding is quite fun. I've always wanted to try game development, but never really found a place to start. As well as this, this is my first time using Stack Exchange, so if this post is horrendously misplaced, I apologise. I don't want to go into professional game development, as I'm only 13, but I would like to try it. As I said before, I did try some programming (In Java), so I know the very basics of code-Java at least-so this is my question:
How would I go about building a simple platformer? I don't want fancy graphics, or multiple states. All I want to try is the code a simple engine that can use collisions and take keyboard input, and have a single level that can be changed within the code (By that I just mean drawing different sized rectangles). That is it.
How would I go about this, in the simplest way possible? Any help would be appreciated! :D


texts:
I have a generic state machine implementation like this:

public abstract class State<TOwner>
{
    public virtual void OnEnter(TOwner owner) { ... }

    public virtual void OnExit(TOwner owner) { ... }
}

public sealed class StateMachine<TOwner, TState>
    where TState : State<TOwner>
{
    public TState CurrentState { ... }
}

Usage looks a bit like this (more or less):

public abstract class SoldierState : State<Soldier>
{
    public abstract void Update(Soldier owner, GameTime gameTime);
}

public class RestState : SoldierState
{
    public static readonly RestState Instance = new RestState();

    private RestState()
    {
    }

    public override void Update(Soldier owner, GameTime gameTime) { ... }
}

public class Soldier
{
    private readonly StateMachine<Soldier, SoldierState> state = ...;

    public void Update(GameTime gameTime)
    {
        this.state.CurrentState.Update(this, gameTime);
    }
}

Importantly, notice how my state classes are singletons. This means every soldier will share the same SoldierState instances.

This is fine until I need to store state per soldier. For example, suppose I want to ensure that soldiers remain in the rest state for a minimum of 10 seconds. That means that any soldier that enters the rest state needs to have an associated piece of data tracked for it.

I could just use a dictionary:

public class RestState : SoldierState
{
    ...

    private readonly IDicionary<Soldier, TimeSpan> restTimes = ...;

    public override void Update(Soldier owner, GameTime gameTime)
    {
        TimeSpan restTime;
        restTimes.TryGetValue(owner, out restTime);
        restTime += gameTime.Elapsed;

        if (restTime > TimeSpan.FromSeconds(10))
        {
            soldier.State = FightingState.Instance;
            restTimes.Remove(soldier);
        }
        else
        {
            restTimes[soldier] = restTime;
        }
    }
}

However, I'm concerned about the efficiency (or lack thereof) here. Is there a better way to achieve what I want? Would I be better off having state instances per entity instead of trying to use singletons?


texts: Drawing a continuous line with onTouchMoved callback

texts:
i'm trying to draw a continues spline on every onTouchMoved call,
the functionality is supposed to be similar to the line drawing used in the iOS game - flight control.

i'm using it in the following manner:

constructor init:

conPointsArray = new PointArray();
conPointsArray->initWithCapacity(DEF_ARRAY_SIZE);
lineDrawer = DrawNode::create();

the onTouchMoved callback usage:

void line::onTouchMoved(cocos2d::Touch *Touch, cocos2d::Event *Event)
{
conPointsArray->addControlPoint(Touch->getLocation());
lineDrawer->drawCardinalSpline((conPointsArray), 0.5f, 100, Color4F::BLUE);
CCLOG("on touch moved x: %f y %f", Touch->getLocation().x, Touch->getLocation().y);
}

But the app is always crashing in a certain openGL function.

I assumed the reason for it is because the array is constantly changing and openGL is having trouble with it (and the fact i'm always sending the same array which is a bad idea, but just to see how things work), so i moved the drawing call to onTouchEnded, And indeed, The line was drawn, but only (as expected) after the onTouch action has ended.

What is the solution/best practice for this issue?

Cheers.


texts: Could neural networks be used in order to build a better AI system?

texts:
Currently, I am researching both about Finite State Machines and Neural Networks in order to design AI for my game. I have searched a lot and I see that people usually use FSM because they are predictable and easier to implement. But should one discard the power of neural networks at all in game development? I am well aware of the intelligent systems that are made with the help of neural networks outside the game development area and for me it raises a curios flag about whether these could be used in order to achieve a much more complex and challenging AI in games.

In my vision, this is how one could think about using them. The developer could create the neural network system and train the AI for a time in prototype project. Once the AI becomes good enough, the developer could move the system and its most recent network data ( for example the weights of the connections and the neurons themselves) into the main project.

I have not built any serious AI up to this moment, but I think this could an imaginative development exercise. So, what is your take on this subject? Are developers using neural networks at this moment or could these really yield some outstanding AI systems?


texts: unable to see sprite in scene Getting error as floating point precision limitation

texts:
I am trying to create game object by dragging image from project window to scene I am getting error as due to floating point precision limitation- it is recommended to bring the world coordinates of game object within smaller range
I am following ruby's adventure tutorial in unity learning


texts:
I am using Java and the Slick2D library.

I've been testing around with ways to develop a Player Graphical User Interface (GUI) (to show armour, items picked up, weapons equipped, etc). The one problem I am facing however is how to actually make such a system work.

I do not know if Slick2D has a system for creating a Player GUI. I have tried looking up resources on the internet with limited success.

Currently I am thinking of having a BasicGameState named StatePlayerInventory which is the Player Inventory for the player to interact with and I have another BasicGameState named GameState which is the Over-world map and whatever items the player gets from the over-world map, it will render in the Player Inventory GUI. I already have a functionable inventory class and an item class but it isn't able to be rendered because of I have no GUI for the Player currently.

My question is is what does if this kind of system I have is efficient/workable. If there are better ways of creating the Player Gui, I am open to suggestions. Also, if there are online resources on Player Inventories, it would be nice to have access to them.


texts:
im creating a platform shooter. the gun can be rotated using the thumbsticks. i want to use a line of fire newBullet.bulletVel variable as a Vector 2. this variable will be used to send the bullet in the direction that the barrel of the weapon is pointed at. How could i do this?

for gun rotation i have declared a float named rotation and use spritebatch.draw method to show that the variable is for rotation of the image.

public float WMrotation;

public void UpdateMe(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).ThumbSticks.Right.Y < -0.1)
        {
            WMrotation += 0.03f;
        }
        if (GamePad.GetState(PlayerIndex.One).ThumbSticks.Right.Y > 0.1)
        {
            WMrotation -= 0.03f;
        }
    }

public void DrawMe(SpriteBatch sb)
    {
        sb.Draw(WMtxr, WMpos, null, Color.White, WMrotation, WMorigin, 1f, SpriteEffects.None, 0);
    }

ive set the bullet position when fired to be at the tip of the gun.

newBullet.bulletPos.X = player1.playerPosition.X + 15;
newBullet.bulletPos.Y = player1.playerPosition.Y + 15;

i think i need to use newBullet.bulletVel to calculate the vector in which the bullet travels

newBullet.bulletVel = i don't know what to put in here

Any help would be appreciated.


texts: Determine terrain type and worldobject placement techniques

texts:
I'm currently researching the techniques of generating a procedural map. I've already found some methods regarding the mesh generation (e.g. variations of noise like perlin, simplex and cell, midpoint displacement and diamond square).

The next step for me is to determine the terrain type. The most easy way is probably matching a static value to the height value (e.g. everything below 0.2 is water, everything between 0.2 and 0.3 is sand, everything between 0.3 and 0.5 is grass, etc.). To make a more advanced version I can use temperature and moisture values for the biomes. I'd very much like to know other techniques to determine this.

I also want to place objects (like rocks, trees, plants) on the map, however I can not seem to find different techniques to research/implement this. I probably just don't know the name of the global technique to find specific techniques. I found the use of fractal noise with a variable for the probability, but I'd like to know more techniques.

So, let me know some of your techniques.


texts: How do you decide when your feature list is long enough?

texts:
I know a bit about this question but I find that there are quite a lot of diverse opinions on the subject?

I know from a players perspective that more options is almost always good. But on the other hand if it has multi-player more means higher complexity (meta game) both for the developers as well as players.

On development complexity and time constraints always go hand in hand. Another would be  resource and platform constraints. Possible economic ramifications of holding back for later is sometimes a reason as well.

So from people experience here aside from the above when should features be cut or be for later release?


texts: Armature rest matrix - why does this exist?

texts:
I'm not sure I have a clear idea on what purpose the rest matrix/bindpose is supposed to serve in skeleton animation. If it is supposed to transform a bone into the rest pose and the mesh itself is always exported in the rest pose then shouldn't the rest matrix always be the identity matrix? But then why is it not the identity matrix in Blender?

I also find that if I transform my mesh (exported in the rest pose) by the rest matrix for each bone then it is very incorrectly deformed (it was after all already in the rest pose).


texts: How to make an object towards the mouse on one Axis - Gamemaker Studio 2

texts:
I am trying to have my "obj_playership" move towards the Cursor on a single Axis.
Prefer it to be the Vertical Axis.
I tried doing this is an "Execute Code Box" in a step event

"direction = mouse_x"
"speed = 1          "
but the movement looks weird and does not do what I am trying to do.

To better refine my question I'm trying to have my "obj_playership" move just up and down in relation to the mouse, so if I'm moving my mouse up or down the obj_playership" will follow towards the mouse either up or down.


texts: Trade offs of linking versus skinning geometry

texts:
What are the trade offs between inherent in linking geometry to a node versus using skinned geometry?

Specifically:

What capabilities do you gain / lose from using each method?
What are the performance impacts of doing one over the other?
What are the specific situations where you would want to do one over the other?

In addition, do the answers to these questions tend to be engine specific? If so, how much?


texts: What are the pros and cons of these voxel data file formats?

texts:
.VXL
.VOX
.KVX
.KV6
.V3A
.V3B

I am trying to decide whether it's worth going with any of the above, or some other, or if I should roll my own. The deciding factors in order of importance are:

Animation support (I am aware this is a difficult aspect when it comes to voxels), using voxel deltas or numerical transform descriptions.
Simplicity (or at least a concise format)
Compression

From what I can tell, the Tiberian Sun VXL format is the only one which is designed for animation, but Ken Silverman of Voxelstein3D fame claimed that VXL does not support animation (in a single file, were his words). So I wonder if maybe there are not two different .VXL formats, since it seems an obvious choice of file extension for voxel data... could be from a medical imaging context.

I do need someone with solid experience of voxel formats to come and comment on the practical pros and cons, in their experience. Consider this question in the same way you might compare JPG to PNG to GIF.


texts:
For n points moving in 1 dimension.

Position and velocity are known for each point.

Each frame a basic integration is done for each point:

velocity += forces * timestep;
forces = 0;
position += velocity * timestep;

Each point (except for the first one) is attached to the point following it (e.g to its right) with a distance joint of the form

point2 - point1 < distance
&&
point2 - point1 > 0

Which means that the points shouldn't be further appart than distance or closer than 0.

Energy should be conserved, i.e a point should be able to push/pull another.

I tried to solve every constraints with impulses, but it messes with velocities. (at least the way I did it..)

Searching around, I found a lot of resources but I'm unfortunately not able to understand all of it.

If anyone can give me a general idea / starting point ?


texts: How are bullets simulated in video games?

texts:
I have been playing games like MW2 recently and, as a programmer, I tend to ask myself how do they make the game so immersive. For example, how to they simulate bullet speed.

When an NPC fires a bullet from his gun, does the bullet really travel from his gun to the given target or do they they completely ignore this part and just put a bullet hole on the target?
If the bullet is really travelling from the gun to the target, at what speed is it actually travelling?


texts:
I'm trying to determine whether what I'm attempting to achieve is even possible mathematically. I'm obviously not a seasoned game developer so I'm having trouble even coming up with the terminology to pose this question.

My 2D game (and I must stress that it is 2D) has a perspective such that the "camera" looks down at the game world from 45 degrees. Here's a rough sketch describing the look I'm trying to achieve:

As objects move from foreground to background (such as the red box pictured), they not only get smaller but are moved towards the center of the screen. So whilst the on-screen representation is rectangular, the actual game world has this shape:

Now I suspect I can do all this without using a matrix. I've already got the scaling working and don't think it would be too difficult to offset on the x axis objects according to their distance from the camera.

However, what I'd really like to know is whether I can encompass this perspective inside a simple matrix. I've had a look around the web but have got lost in a sea of nomenclature that I don't understand and information that doesn't appear to be relevant to me (such as 3D camera positioning, etcetera).

Can anyone tell me whether I'm barking up the wrong tree? If it is possible, can someone point me towards some articles or blog posts that describe this in detail?


texts: Implement spherical mapping for texture coordinates

texts:
I am using a texture of a world map and I am trying to put that image on a sphere made up of many triangles. Each triangle has points a,b,c with their own (x,y,z) coordinates.

I am trying to use the coordinate system conversions formula from Wikipedia. This is my world to spherical coordinates function:

function worldToSpherical(p) {

  const r = Math.sqrt(Math.pow(p[0],2)+ Math.pow(p[1],2) + Math.pow(p[2],2));
  const u = Math.atan2(p[1],p[0]);
  const i = Math.atan2(Math.sqrt(Math.pow(p[0],2)+Math.pow(p[1],2)),p[2]);

  const s =  r * Math.sin(i) * Math.cos(u);
  const t =  r * Math.sin(i) * Math.sin(u);
  return [s, t];

}

But this is what my output looks like:

It seems to be wrapping around twice. Am I using the wrong formula, or using it wrong?


texts: I have got a sphere in my world space. I don't understand how can i find my sphere using my X and Y on my screen, because i don't understand what the value Z of my ray assuming the fact that we use world coordinate system.


texts: render() can't seem to reference my sprite properly

texts:
This is driving me a little crazy. We use libGDX, working on making a simple side scroller for fun. I've got it switching from screens alright, loading from my main menu into my level one class, which implements screen.

public class levelOne implements Screen

Don't know if that effects this. When I try to initialize my sprite, my editor (AIDE) highlights it. Gives me an error saying that there is no access to the variable, as it does when you declare something but don't use it.

Texture faceTexture = new Texture(Gdx.files.internal("faceSprite.png"));
faceGuy = new TextureRegion(faceTexture, 50, 50, 95, 95);
Sprite player = new Sprite(faceGuy);

I do actually call up the sprite in render() though,

batch.begin();

// Background
batch.draw(backGround,0,0,2900,800);

// Player
player.draw(batch);

// Enemies
batch.draw(faceGuy, baddieOnePosition.x, baddieOnePosition.y, 150, 150);

batch.end();

It doesn't generate an error there, but trying to run it generates a crash. I can do a batch.draw of the texture, but every attempt at doing it as a sprite fails. I have it being initialized in show(), thought maybe making a new method to do so would help, but had the same result. The only way I've managed to make it work was to initialize it in render(), but that not only resets the sprites position multiple times a second, but I expect is also a memory hog. Help!


texts: Import from mesh vs hardcoded vertices performance

texts:
Which brings better performance at run-time: a cube imported from a mesh, or a cube made from hardcoded vertices?

Are there limitations to a certain method? Is one of them better architectural-wise?


texts: How to load large arrays to gpu and render with OpenGL?

texts:
I am trying to make a volumetric rendering of a cloud. I have been defining the cloud density functions on the glsl shaders and performing ray-marching methods successfully. But now I would like to render a 3D grid (100x100x100) representing the density of a cloud that I calculated using the cpu. The idea that I was trying was to make use of the storage buffer objects, but when I access the array to get the density value and render it, it doesn't work.

This is at the beginning of the glsl fragment:

#version 440 core
layout(std430, binding = 3) buffer layoutName
{
    float data_SSBO[100*100*100];
};

And the density function definition is:

float density(vec3 position, float t){
    const float dx = 1./100., dy = 1./100., dz = 1./100.;
    int i, j, k;
    if( (position.x >= 0.)&&(position.y >= 0.)&&(position.z >= 0.)&&(position.x <= 1.)&&(position.y <= 1.)&&(position.z <= 1.)){
        i = int(position.x/dx);
        j = int(position.y/dy);
        k = int(position.z/dz);

        return data_SSBO[i*100*100 + j*100 + k];
    }
    else
        return 0.;
}

And in the c code there are the buffer creation, bindings, etc:

    glGenBuffers(1, &ssbo);
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo);
    glBufferData(GL_SHADER_STORAGE_BUFFER, 100*100*100*sizeof(float), grid, GL_STATIC_DRAW);
    glBufferSubData(GL_ARRAY_BUFFER, 0, 100*100*100*sizeof(float), grid);

and in the rendering function there is:

    glClearColor(1.f, 1.f, 0.f, 1.0f);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);

    glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo);

    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, ssbo);

//  glBufferSubData(GL_ARRAY_BUFFER, 0, 3*2*2*sizeof(float), buffer);

    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2* sizeof(float), (void*)0);      // coordenadas

    glEnableVertexAttribArray(0);

    glUseProgram(shaderProgram);

I believe the problem has to do with the binding, I have been trying different combinations, like binding after and before glUseProgram, etc.
I literally have no idea what is wrong, I see this is really confusing.


texts: Get intersection of vector in the middle of the screen

texts:
My screen resolution is 640x480 and I have two Vector2 objects located at (10,10) and (600, 320).

How can I connect these two objects and extend the line to encompass the whole screens width, how can I get the Y for the intersection at the center of the width (320)?


texts: LibGDX Letter spacing is reduced if I use GlyphLayout to draw a bitmap font

texts:
I need to use glyphlayout so that I can centre the text, but I found if I do the text gets distorted due to the spacing being incorrect.

public SimpleButton(String text, float x, float y, float w, float h, BitmapFont font) {
    pos = new Vector2(x, y);
    this.w = w;
    this.h = h;
    this.text = text;
    this.font = font;
    glyphLayout.setText(font, text);
    hitbox = new Rectangle(x, y - h, w, h);
}

public void render(SpriteBatch batch) {
    font.draw(batch, text, pos.x, pos.y);
}

Like this it displays fine:

But using glyphlayout to draw it the spacing for some reason is different:

public void render(SpriteBatch batch) {
    font.draw(batch, glyphLayout, pos.x, pos.y);
}

Glyphlayout seems to be changing the spacing here, but I couldn't see any options for setting the spacing with it.

These are the settings for the Bitmap font in Hiero. No special fx, padding and spacing set to zero:


texts: Is it possible to use plugins like Admob when creating a UDK game for Android or iOS?

texts:
Is it possible to use plugins like Admob or Chartboost for iOS and Android when using UDK?

I am interested in an official or unofficial source where it's mentioned that the plugins are possible or not with UDK or if anyone have ever made plugins without using the original Unreal Engine Source?


texts: Unity3D: How to play 360 video without VR mode?

texts:
i followed the official Unity tutorial to make an inverted sphere and play a 360 video inside it and i managed to do it but the problem is i can't build the project to my phone because it says i have to turn on virtual reality support from player settings but the thing is i don't want to because when i do that it also turns on VR mode(that split screen view).

what i want is to play a normal 360 video(full screen) and navigate using the gyro of phone just like Youtube. Youtube provides a button to toggle between headset and non-headset mode.


texts:
So I've got Bullet 3D controlling the motion of objects rendered with DirectX.
In the clipping below I've got 2 identical rectangles & 5 balls.
The lowest rectangle has a mass of 0 and doesn't move (as expected).  All other objects have a mass of 1 and fall as expected.

There are two issues that I'm seeing:
1. When the balls land on an angled surface (not shown) they don't rotate, but they do move 'down hill'.
2. Pictured below you see that the top rectangle is perched on the bottom rectangle when it should've rotated a bit and kept falling.

What do I need to do in Bullet to enable object rotations? I'm not a physicist so I suspect my google-fu is lacking, also the Bullet docs are painfully inadequate.

This code here is how I initialize my rigid bodies:

RESULT_CODE ubAddRigidBody(HANDLE collisionShape, float mass, ubVector3 position, ubVector4 orientation, HANDLE* rigidBodyHandle)
{
if (rigidBodyHandle == nullptr)
{
    return INVALID_PARAM;
}

if (_world->isValidCollisionShapeHandle(collisionShape) != SUCCESS)
{
    return INVALID_HANDLE;
}

auto transform = btTransform(btQuaternion(orientation.x, orientation.y, orientation.z, orientation.w), btVector3(position.x, position.y, position.z));
auto collisionShapeObject = _world->m_collisionShapes[collisionShape].get();

auto motionStateObject = new btDefaultMotionState();
motionStateObject->setWorldTransform(transform);

auto rigidBodyInfo = btRigidBody::btRigidBodyConstructionInfo(btScalar(mass), motionStateObject, collisionShapeObject);

// Enable rotations for the object

collisionShapeObject->calculateLocalInertia(mass, rigidBodyInfo.m_localInertia);
rigidBodyInfo.m_linearDamping = .2f;
rigidBodyInfo.m_angularDamping = .2f;

auto rigidBody = new btRigidBody(rigidBodyInfo);
auto uniqueHandle = _world->getUniqueHandle();

rigidBody->setFriction(.5f);
rigidBody->setRollingFriction(.5f);

_world->m_world->addRigidBody(rigidBody);
_world->m_rigidBodies[uniqueHandle] = unique_ptr<ubRigidBody>(new ubRigidBody(rigidBody, collisionShapeObject, motionStateObject));

*rigidBodyHandle = uniqueHandle;

return SUCCESS;
}


texts:
I'm reading through the OpenGL documentation for version 3.3 core. I'm having issues understanding proper buffer deletion.

At the moment I have an object that loads itself into OpenGL memory in the constructor and only exposes a VAO with the attribute pointers and a bound element array ready for rendering. When it stops existing it deletes all the buffers and sets pointers to NULL.

How do I properly delete OpenGL data? I'm going to assume that the object doesn't stop existing while it's being rendered. Do I have to do something more than just delete the VAO and then delete the buffer objects? Does that leave anything out? Should I bind the VAO disable the attributes, unbind it and then delete it?


texts: algorithm for Shooting objects that bounce off the wall

texts:
I'm trying to make a 2D game where my Hero is standing in a 2D plan and surrounded by enemies(highest 3) that throwing balls. and my hero have a shield in hands and and will stop the balls...

well the problem is i'm not able to found the direction on which enemy shoot the ball to reach to the Hero...
i want to make enemy little bit smarter so they don't just shoot straight

as in picture the ball can bounce of the wall same as light bounce off wall, the indecent angle and refractive angle will be same(sorry image angles not perfect. i draw them in paint) so i know that slop of this path line will be same in whole path just interchange in negative and positive.

now i want to find the directions in which i can shoot like 2 coordinates of x,y or something where i can shoot and the ball reaches to the hero.

i not want just one direction... i want the all possible directions where my enemy can shoot and that hit to the hero

and also the ball will be gone after 4-5 times bounce

there is an android game "Stupid zombies" that have exactly this kind system in game

any algorithm and solution to archive this....i'm working in java so later i can port my game to android easily

i also tried below link but my ball hitting more then 2 times and i'm not able to find solution
https://softwareengineering.stackexchange.com/questions/290628/algorithm-for-calculating-a-bullet-path-to-a-target-with-max-2-ricochets

please edit if you found anything not properly asked ...i tried to make as simple as possible, but its my first time here.


texts: How do I allow clients to move a GameObject that exists on the server?

texts: I started to delve into the UNet system for the first time the other day and I've run into a bit of an issue while testing on a localhost server. In the scene there is a Rigidbody ball that I want every player to be able to pick up and move around. So on each player there is a script where every time they right click, a raycast is sent out, and if it hits the ball, then a [Command] is sent to run a method on the ball called RequestNewHandler(), what this does is check to see if the ball is currently being held by someone, and if not, it attaches itself to the player object that issued the [Command]. So far the script works very well... if you are the localhost. I can't seem to get any clients to be able to pick up the ball. The only thing I can think of is that it may have something to do with my NetworkPlayerInitialization() script, which is just a script that enables all of the required components for each local player that connects to the server, like the camera, movement scripts and this script. But I'm unsure of what I need to do to fix this issue. If anyone needs any clarifications just let me know, thanks.


texts: Open GL perspective projection vs orthographic projection

texts:
I am trying to build an engine using OpenGL however I have a question about the kind of projection to use.

For a 2D game should I use a perspective projection or an orthographic projection?
If I wanted to have the ability to use 3d in a 2d oriented game, which one should I use?


texts:
I have an issue with my EventHandler for Key events in my game.

The specifics are in this forum thread: http://www.java-gaming.org/topics/problems-with-key-event-handling/37998/view.html

Basically, the issue is that a KeyReleasedEvent is fired in a very inconvenient way. I recently switched from polling to interrupting to take key input, so I'm hoping somebody has had this problem before and knows an elegant way to solve it.

I can provide more code and details if needed. Thank you for any help!


texts: Black screen when switching from fullscreen to windowed mode with libgdx

texts:
I have just started working with libgdx, and have run into my first problem. I have a simple program that switches a desktop application from windowed mode to fullscreen and back again. If I start the program in windowed mode, it initially displays fine. When I toggle to full screen it is also OK.

However, when I toggle back to windowed mode the screen goes completely black. The application remains responsive though, and if I toggle again it will go back to fullscreen and display correctly.

I am using 64-bit Windows 7 with the IntelliJ IDEA IDE.

Any help with working out why it is doing this would be greatly appreciated.

A minimal example that displays the issue is shown below:

public class MyGdxGame extends ApplicationAdapter {

    @Override
    public void create () {
        fullScreen = false;
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        if (Gdx.input.isKeyPressed(Input.Keys.TAB)) {
            fullScreen = !fullScreen;
            DisplayMode currentMode = Gdx.graphics.getDesktopDisplayMode();
            Gdx.graphics.setDisplayMode(currentMode.width, currentMode.height, fullScreen);
    }
}

private boolean fullScreen;
}


texts: How do you create an over world styled like Pokémon Black and White, with both 2D and 3D elements?

texts:
The over world of Pokémon white uses 3D models for objects like houses, and 2D sprites for characters like the player.  What would I have to do to create an over world styled like this?

Here is an example:


texts: What is the cost of distributing through Google Stadia?

texts:
Stadia's business aspects are really scarce to find.

What will the revenue models look like?
Traditional video game model (royalties) or app store model (%)?


texts:
I'm attempting to improve the performance of a shader that changes the colour of a region of the world that is inside a "zone".

I am using a deferred lighting system, so the colour and world-space position of each pixel on the screen are stored in two separate textures, gColor and gPosition.

The zonePos uniform stores the two corners of each zone.
The zoneColor uniform stores the colour of each zone.
The totalZones uniform stores the amount of zones in the current game.

Here is the fragment shader:

out vec4 FragColor;

in vec2 texCoords;

layout (binding = 0) uniform sampler2D gColor;
layout (binding = 1) uniform sampler2D gPosition;

uniform vec3 zonePos[10];
uniform vec3 zoneColor[5];
uniform int totalZones;

void main()
{
    vec3 FragPos = texture(gPosition, texCoords).rgb;
    vec3 Albedo = texture(gColor, texCoords).rgb;

    vec3 j;
    vec3 k;

    for (int i = totalZones; i > 0; i--)
    {
        j = zonePos[i * 2];
        k = zonePos[i * 2 + 1];

        if (FragPos.x >= j.x && FragPos.x <= k.x &&
            FragPos.y >= j.y && FragPos.y <= k.y &&
            FragPos.z >= j.z && FragPos.z <= k.z)
                Albedo += zoneColor[i];
    }

    FragColor = vec4(Albedo, 1.0);
}

The changes I have made so far are:

Using j and k, rather than accessing zonePos 6 times in the if statement
Looping down from totalZones to 0, as a comparison against 0 is faster

Any suggestions are greatly appreciated.


texts: Formula to calculate the changes in the fortunes of a stock based on how many shares are bought or sold

texts: I am creating a stock market simulator for an event in my college. Supposing I have 20 companies in it all starting with a common base price, I need a formula to calculate the changes in the fortunes of a stock based on how many shares are bought or sold.


texts:
I'm currently developing a simple breakout/arkanoid mobile game. Now, I noticed that my ball movement is noticably stuttering. I've read various approaches about how to make the ball move and decided to go for AddForce so I don't have to do any physics calculations myself.
The only thing im currently doing is using AddForce on my ball's rigidbody2D and have it collide with the walls and blocks. There's nothing done manually in Update or FixedUpdate and there are no other scripts running while the ball is moving. The scene is pretty empty actually.

Things I have tried so far without success:

Disable V-Synch
Increase the velocity iterations (I tried values 15-500)
Set the RigidBody2D's interpolation mode to: Interpolate/Extrapolate
Using different mass values and force values in AddForce
Checking, whether it's just an optical illusion (it seems to run more smoothly in editor and other breakout/arkanoid games don't have that problem on my Galaxy S7)

RigidBody settings of the ball:

Body Type: Dynamic
Material: Friction: 0 | Bounciness: 1
Mass: 0.025
Linear Drag: 0
Angular Drag: 0
Gravity Scale: 0
Collision Detection: Continous
Sleeping Mode: Start Awake
Interpolate: Interpolate

The walls and blocks are simple BoxCollider2D components. And I'm calling AddForce(new Vector2(0f, GameConstants.DESIRED_BALL_SPEED)) on the ball's RigidBody2D.

Edit:

public void OnPointerUp(PointerEventData eventData) {
    if(!_ballStarted) {
        PaddleController.ShootStickingBalls();
        _ballStarted = true;
    }
}

public void ShootStickingBalls() {
    int stickyBallsAmount = _stickingBallsRigidBody2D.Count;
    for (int i = 0; i < stickyBallsAmount; i++) {
        _stickingBallsRigidBody2D[i].AddForce(new Vector2(0f, GameConstants.DESIRED_BALL_SPEED));
        _stickingBallsRigidBody2D[i].transform.SetParent(_nonStickyBallsTransform);
    }
    Sticky = false;
}


texts: Can't change materials of model from FBX

texts:
I was used 5.x before, and that version when I loaded FBX, Unity generated each material automatically, so I can change them like assigning textures or change shader.

And now I switched to 2017.3, and when I imported FBX, now Unity didn't generate materials anymore. I can see the properties of each material but every parameter is locked. It seems materials are inside of model and can't change like animation clips.

Some of model has multiple materials, so I can't generate manually and assign them. I'm creating mobile game so I really need to change the shader to mobile shader, not standard(PBR).

How to change materials of model from FBX in Unity 2017.3? Note that model created from Blender 2.7c and exported as FBX.


texts:
I am trying to create a simple game on android but I am unsure the best way to do the game loop.  Looking at the LunarLander sample the game loop just loops like a variable time step loop (elapsed = now-lastupdate).  I tried using this method to draw a circle that grows in size to a max radius then shrinks to a min radius and repeats.  However, when I run the program the growing stage is very choppy and slow (it takes longer than it should to get to max radius).

My Code:

    public void updateSize(double elapsed) {
        if (mGrowing == true && mRadius > mMaxRadius) {
            mGrowing = false;
        }
        if (mGrowing == false && mRadius < mMinRadius) {
            mGrowing = true;
        }

        if (mGrowing == true) {
            mRadius += mDRadius * elapsed;
        } else {
            mRadius -= mDRadius * elapsed;
        }
    }

mDRadius is the number of pixel the radius should change per second and elapsed is the number of seconds that has passed.

I tried putting in a sleep of 2ms and 5ms in my game loop and I get the same result.

I converted my loop to a fixed time step (only run physics update if now-lastupdate > TIME_STEP) and the animation was a lot smoother.

UPDATE: I change the sleep to 15ms and it's a lot smoother.  Every other example I've seen of an android game does not have a sleep in the main loop.  Is this because my sample is just so simple that it takes virtually no time to update and all other examples just have a longer update time or am I missing something?


texts: Multiple clicks required before listener is called

texts:
I have a screen with multiple stages (pre-game, game, pause) and on the game stage I have a pause button. This is implemented as:

public class PauseButton extends Actor {
    private NumberzGame m_game;
    private TextureRegion m_pauseButton;
    private int m_buttonSize;

    public PauseButton(NumberzGame game, Stage stage, int size) {
        super();

        m_game = game;
        m_buttonSize = size;
        m_pauseButton = createPauseButton();

        setWidth(m_buttonSize);
        setHeight(m_buttonSize);
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        Color color = getColor();
        batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
        batch.draw(m_pauseButton, getX(), getY());

        super.draw(batch, parentAlpha);
    }

    private TextureRegion createPauseButton() {
        Pixmap map = new Pixmap(m_buttonSize, m_buttonSize, Format.RGBA8888);
        map.setColor(ColorUtils.colorFromHex(NumberzGame.COLOR_BACKGROUND));
        map.fill();

        int radius = (m_buttonSize / 2) - 4;
        map.setColor(ColorUtils.colorFromHex(NumberzGame.COLOR_SOUND_BUTTON_BACKGROUND));
        map.fillCircle(m_buttonSize / 2, m_buttonSize / 2, radius);
        map.setColor(ColorUtils.colorFromHex(NumberzGame.COLOR_SOUND_BUTTON));

        int width = 2 * radius - 10;
        int height = width;
        int xpos = (m_buttonSize - width) / 2;
        int ypos = (m_buttonSize - height) / 2;

        Pixmap pause = m_game.getAssets().get(NumberzGame.ID_PAUSE_PIXMAP, Pixmap.class);
        map.drawPixmap(pause, 0, 0, pause.getWidth(), pause.getHeight(), xpos, ypos, width, height);

        TextureRegion result = new TextureRegion(new Texture(map));
        map.dispose();

        return result;
    }
}

In the screen class I have the following code to add the pause button to the game stage:

m_pauseButton = new PauseButton(getGame(), m_gameStage, NumberzGame.PLAY_BUTTON_WIDTH);
m_pauseButton.setX(width - NumberzGame.PLAY_BUTTON_WIDTH - NumberzGame.MARGIN);
m_pauseButton.setY(height - NumberzGame.PLAY_BUTTON_WIDTH - NumberzGame.MARGIN);
m_pauseButton.addListener(new ClickListener() {
    @Override
    public void clicked(InputEvent event, float x, float y) {
        m_state = GameState.PAUSED;
        getGame().getWorld().pauseWorld(true);
    };
});
m_gameStage.addActor(m_pauseButton);

When I run the application the first click on the pause button properly pauses the game and after I resume the game, I need to press the pause button twice to have it trigger.

What am I missing here?


texts: What causes a blocky texture pattern on models

texts:
I have been playing with some shaders and materials included in Libgdx demos, and I noticed that models which I've created for my game have a strange issue. I have created them in blender and UV unwrapped. What could be causing this? Is it because I used material with a texture which was not prepared for this model or botched UV unwrapping on my part?

I haven't seen the problem with models included with the demo (e.g. a teapot and the blender's Suzanne model)


texts: What programming language was Super Mario Bros. written in?

texts:
Super Mario Bros. is definitely the most famous videogame created yet, selling a scorching 40.23 million copies. http://en.wikipedia.org/wiki/List_of_best-selling_video_games

What programming language was it written in? Does anyone have some original code reference?


texts: If fixed timesteps are unreliable across web platforms, what can I use in my game loop?

texts: As I have found out in my previous question, window.setInterval is not the best choice for a cross-platform game loop. What is my alternative for a game loop in Javascript that will (attempt to) run at the same speed on all devices?


texts: If I embed the V8 JavaScript Engine in my game is it still possible to distribute it in the Mac App Store?


texts: 3D World coords to on-screen coords in an ancient engine

texts:
I've been googling for past 2 hours and I couldn't find a satisfying solution that wouldn't require you to use Unity, OpenGL or Unreal Engine.

My issue is, I was given a task to make a game on an ancient 3D engine built purely from scratch (no OpenGL etc.).

The task I was given is - draw text above every chest the player can see.

In OpenGL I would do a simple transformation seeing how I've got all what I need built in, but in here I have to do the math myself.

The game from top-down looks like this:

Hearts represent chestboxes, the rest is marked.

So here's what I know for sure that might be useful:

I know XYZ positions of these hearts
I know the maximum angle after which chest disappears fully from my sight is -32.5 for the left edge and 32.5 for the right screen edge - which made me conclude that FOV is 75.
The game window (viewport dimensions) is 1024x768
I can calculate pitch/yaw easily for any two vectors, be it player->camera, player->chest, camera->chest etc.

What I don't know is - where do I go from there?

Any help appreciated, thanks!

PS: The language I'm allowed to write in is C#, but I'm only looking for help with formula so.


texts:
I've started working on a demo for my 2.5D game. For a basic scene I figured I would just use the good old fashioned doom sprites textured to a double sided plane. Simple enough. But I've been scratching my head as to how to display the proper sprite animation relative to the player viewing the sprite...if that makes since.

For example suppose I have three players in the scene Players A, B, and C as such:

Player C should see player A as:
Here's an example of what I think player A should look like from C's perspective:

While player B would see player A as follows:

My current idea is that for any given player, I will need to know the current direction of each other player, and where they are located/moving to relativly. From this, I could calculate which sprite image is required.

Is this correct? What improvements/optimizations could be made?

** EDIT **
Total number of directions will be 8 as depicted below:

For each direction there are two sprites (to show walking movement, sprites for the right hand directions are mirrors of the left):

** EDIT 2 **
Got this working and have a simple javascript/threejs example for anyone interested: https://github.com/commanderZiltoid/threejs-2.5d-fps


texts: Calculating a circle or sphere along a vector

texts:
Updated this post and the one at Math SE (http://math.stackexchange.com/questions/127866/calculating-a-circle-or-sphere-along-a-vector), hope this makes more sense.

I previously posted a question (about half an hour ago) involving computations along line segments, but the question and discussion were really off track and not what I was trying to get at. I am trying to work with an FPS engine I am attempting to build in Java.

The problem I am encountering is with hitboxing. I am trying to calculate whether or not a "shot" is valid.

I am working with several approaches and any insight would be helpful. I am not a native speaker of English nor skilled in Math so please bear with me.

Player position is at P0 = (x0,y0,z0), Enemy is at P1 = (x1,y1,z1). I can of course compute the distance between them easily. The target needs a "hitbox" object, which is basically a square/rectangle/mesh either in front of, in, or behind them.

Here are the solutions I am considering:

I have ruled this out...doesn't seem practical. [Place a "hitbox" a small distance in front of the target. Then I would be able to find the distance between the player and the hitbox, and the hitbox and the target. It is my understanding that you can compute a circle with this information, and I could simply consider any shot within that circle a "hit". However this seems not to be an optimal solution, because it requires you to perform a lot of calculations and is not fully accurate.]
Input, please! Place the hitbox "in" the player. This seems like the better solution. In this case what I need is a way to calculate a circle along the vector, at whatever position I wish (in this case, the distance between the two objects). Then I can pick some radius that encompasses the whole player, and count anything within this area a "hit".
I am open to your suggestions. I'm trying to do this on paper and have no familiarity with game engines. If any software folk out there think I'm doing this the hard way, I'm open to help!

Also - Anyone with JOGL/LWJGL experience, please chime in.

Is this making sense?


texts: In Unity, why does my IndexOutOfRange exception disappear when trying to debug it?

texts:
I don't get errors when playing from Unity "Game" tab. But when I build an executable (development or not) it stucks. I get "IndexOutOfRange" exception.
Which also magically disappears (yes) when I add some debug lines:

This does not work:

for (int i = x1; i <= x2; i++)
for (int j = y1; j <= y2; j++)
{
    int a, b;
    a = 7 + i; // Out of range
    b = 7 + j; // Out of range

    submap[a, b] = world.WalkableMap[(int)CurrentWalkableTile.x + i, (int)CurrentWalkableTile.y + j];
}

This works:

for (int i = x1; i <= x2; i++)
for (int j = y1; j <= y2; j++)
{
    int a, b;
    a = 7 + i;
    b = 7 + j;

    if (a < 0 || a > 15) // now with this never gets out of range
        Debug.Log("A out of range: " + a);

    if (b < 0 || b > 15) // now with this never gets out of range
        Debug.Log("B out of range: " + b);

    submap[a, b] = world.WalkableMap[(int)CurrentWalkableTile.x + i, (int)CurrentWalkableTile.y + j];
}

I can't find any sense. The exception literally hides from me

Additional info maybe is useful:

x1 = (CurrentWalkableTile.x - 7) >= 0 ? -7 : -(int)CurrentWalkableTile.x;
x2 = (CurrentWalkableTile.x + 7) < world.wmap_x_size ? 7 : (world.wmap_x_size - (int)CurrentWalkableTile.x - 1);

y1 = (CurrentWalkableTile.y - 7) >= 0 ? -7 : -(int)CurrentWalkableTile.y;
y2 = (CurrentWalkableTile.y + 7) < world.wmap_y_size ? 7 : (world.wmap_y_size - (int)CurrentWalkableTile.y - 1);

I'd like to post more information, but I can't even debug to find the problem.


texts: 2D destructable terrain with collisions in MMO

texts:
Task

What I want is to create destructable terrain (like in Worms) and collisions with this terrain (with calculated normals) that will be fast enough to work on server machine.

Basically lets say that I want to make Worms Online (I don't really) using model CLIENT-SERVER, not peer2peer.

Approaches I read about

People in other threads were suggesting using bitmaps and perpixel collisions, but is it fast enough to handle i.e. 100 games simultaneously?
Another approach is using vectors to track outline of terrain, but it seems also really CPU heavy and I didn't find any good example of that.

So guys what is your proposal?


texts: What is the best way to animate a jumping motion in Unity 3D?

texts: I am creating a a simple 3D game in Unity with a character who runs, walks, jumps, swims, shoots etc. I am pretty satisfied with my results in all the motions except jump. I need to know at what height my character is at in relation to the ground at all times (The height of my terrain varies) in order for me to be able to tell the Animator Controller when to transition. I have done some research on the matter and I found out about Raycast but I'm not sure how to use it. Any help would be great, thanks!


texts: Custom Tile Collision Detection Has Trouble With Edges

texts:
So, I'm writing my own game to expand on my abilities as a programmer. However, I have come to a writer's-block of sorts. The game I am building uses tile collision, but allows the player to be in an unaligned space (like at the edge of a tile rather than directly above it).

The code I have written to determine which tile the player is standing on is failing. On certain edges, when standing on top of the tile, the player will fall through the tile. Here is an example of this occurrence: http://i.imgur.com/CACfhIP.gifv

I have narrowed this down to this specific segment of code:
(Please note that SPRITE_WIDTH is 20, which also means 20 pixels)

BOOL changePos(Player* player, Level* level, int newX, int newY)
{
    int roundedY;
    int roundedX;

    if (newX <= player->pos.x)
        roundedX = roundDownTo(newX, SPRITE_WIDTH); //round down to a multiple of SPRITE_WIDTH
    else if (newX > player->pos.x)
        roundedX = roundUpTo(newX, SPRITE_WIDTH); //ditto but up

The problem seems to be that both parts of the if...else if... statement require the equality symbol to work correctly. Meaning that in the provided example, the fall-through glitch will happen to the tile on the left instead if I move the equality symbol to the else if portion.

I attempted to fix this issue by adding an else clause and removing the equality from the if...else if... parts. My method was to determine which half of the tile the player was on and determine if it required them to fall. So, my code became this:

BOOL changePos(Player* player, Level* level, int newX, int newY)
{
    int roundedY;
    int roundedX;

    if (newX < player->pos.x)
        roundedX = roundDownTo(newX, SPRITE_WIDTH);
    else if (newX > player->pos.x)
        roundedX = roundUpTo(newX, SPRITE_WIDTH);

    else
        if (newX%SPRITE_WIDTH >= SPRITE_WIDTH / 2)
            roundedX = roundDownTo(newX, SPRITE_WIDTH);
        else
            roundedX = roundUpTo(newX, SPRITE_WIDTH);

But this created an even stranger case where the middle part of the tile would cause a fall-through but the edges would work correctly on both the left and the right tile. This can be seen here: http://i.imgur.com/lTaUuzh.gifv

I've been at this all day (literally), I appreciate any help you can provide.

If I have not provided enough information, please let me know and I will do my best to provide it.


texts: How do I make a scrolling background out of a sequence of images?

texts:
I am new to AndEngine and trying to code a basic sidescroller game using the ParallaxLayer class from this example. (I followed the example and it works.)

How would I display multiple images sequentially? For example, I'd like 3 images (Sun_Stage.png, Moon_Stage.png and Dark_stage.png) to form the scrolling background. (First the background scrolls through Sun_stage.png then when it's finished scroll through Moon_Stage.png, et cetera.)

I basically just want to code a never-ending sidescroller with a changing scrolling background.


texts: Unity3D HTC Vive graphical bug when making builds

texts:
Recently I noticed that my builds seem to have a weird graphical bug. This only occurs when I play a build. Running the game in VR in unity play mode doesn't show this bug.

I am not sure what is causing this or what it is even called. I do remember in the old days windows having a similar bug where you could draw on your screen basically by dragging an interface. I have an older build where this glitch didn't occur and checked the settings I had then and now and nothing changed.

Developing in VR is still fairly new to me so if it is anything basic I might not be aware of it.

My Unity version is 2017.2.0f3 with the latest SteamVR version using the HTC Vive, which has been running on the same version as when the bug didn't occur.

This link is a video of the bug occurring during the play mode in a build (in the menu the bug didn't occur strangely enough).

This link is a video of it being run in play mode. This is what I would expect in a build as well.

Just watching the first few seconds of both videos is plenty to understand the issue I am experiencing.

Thanks in advance.

Edit:
I have discovered that this issue is called ghosting. I hope this helps anyone.


texts: OpenGl: Error, The loaded object takes the same colors and style of the Texture?

texts:
I'm new to OpenGl Faced this problem:

Draw function:

void Renderer::Draw()
{

    glUseProgram(programID);
    shader.UseProgram();

    mat4 view = mat4(mat3(myCamera->GetViewMatrix()));
    glm::mat4 VP = myCamera->GetProjectionMatrix()*myCamera->GetViewMatrix();
    shader.BindVPMatrix(&VP[0][0]);

    glm::mat4 VP2 = myCamera->GetProjectionMatrix() * myCamera->GetViewMatrix() * floorM;
    model13D->Render(&shader, scale(100.0f, 100.0f, 100.0f)); // scaling the skybox

    t2->Bind();
    model3D->Render(&shader, scale(2.0f, 2.0f, 2.0f)); //scaling aircraft

    glUniformMatrix4fv(VPID, 1, GL_FALSE, &VP2[0][0]);

    mySquare->Draw();

}

The code of loaded:

    shader.LoadProgram();
    model3D = new Model3D();
    model3D->LoadFromFile("data/models/obj/Galaxy/galaxy.obj", true);
    model3D->Initialize();
    myCamera->SetPerspectiveProjection(90.0f, 4.0f / 3.0f, 0.1f, 10000000.0f);

    model13D = new Model3D();
    model13D->LoadFromFile("data/models/obj/skybox/Skybox.obj", true);
    model13D->Initialize();
    // Projection matrix :
    //shader.LoadProgram();

    // View matrix :
    myCamera->Reset(
        +0.0f, +0.0f, 5.0f,// Camera Position
        +0.0f, +0.0f, +0.0f,// Look at Point
        +0.0f, +1.0f, +0.0f // Up Vector
        );
    //////////////////////////////////////////////////////////////////////////
    std::string Images_names[6];

    Images_names[0] = "right.png";
    Images_names[1] = "left.png";
    Images_names[2] = "top.png";
    Images_names[3] = "bottom.png";
    Images_names[4] = "back.png";
    Images_names[5] = "front.png";
    t = new Texture(Images_names, 0);
    t2 = new Texture("arrakisday_dn.tga", 1);


texts: How to properly translate a point by a matrix?

texts:
I wrote a simple Matrix class and it has methods like rotate, translate, etc. They all seem to be working, but whenever I try to translate a rectangle using the matrix, the translation axis seem to be flipped. It doesn't appear to be the fault of the matrix, however, because if I do matrix.translate(50, 0), It gives me a matrix that looks like this:

$$
\begin{bmatrix}
1 & 0 & 50 \\
0 & 1 & 0 \\
0 & 0 & 1
\end{bmatrix}
$$
As expected. It appears that I am applying the matrix incorrectly instead. I am using this code to get the resulting X/Y axis for each point in the rectangle:

pointX = x * mat.row1.x + y * mat.row1.y + mat.translateX
pointY = x * mat.row2.x + y * mat.row2.y + mat.translateY

But when I call translate(50, 0), I get this:

Instead of this:

As you would expect. What am I doing wrong? Am I incorrectly calculating the points?


texts: How to make an object stay relative to another object

texts:
In the following example there is a guy and a boat. They have both a position, orientation and velocity.

The guy is standing on the shore and would like to board. He changes his position so he is now standing on the boat.

The boat changes velocity and orientation and heads off. My character however has a velocity of 0,0,0 but I would like him to stay onboard. When I move my character around, I would like to move as if the boat was the ground I was standing on.

How do keep my character aligned properly with the boat? It is exactly like in World Of Warcraft, when you board a boat or zeppelin.

This is my physics code for the guy and boat:

this.velocity.addSelf(acceleration.multiplyScalar(dTime));

this.position.addSelf(this.velocity.clone().multiplyScalar(dTime));

The guy already has a reference to the boat he's standing on, and thus knows the boat's position, velocity, orientation (even matrices or quaternions can be used).


texts:
Repost from my question on stack overflow, didnt know this site existed.

I have a 2d platformer and I need help with collision. To show you my current collision system, here is picture:

Top picture is how game looks normally, bottom picture shows highlighted collision rectangles. Black ones are horizontal (If player rectangle intersects them, move player on Y axis), blue are vertical (move player on the X axis) and red are corners.

I've implemented corner rectangles, after bit of testing after I found out, that when I had black and blue overlapping each other, this happened: Player jumped and intersected both rectangles at once, game would recognize that and resolve both intersection at the same time, cause the player to spaz around the map and ending up in a another rectangle, which would then cause another intesection and resolution until the chain reaction stopped, and player would end up somewhere where he should not have been.

So I added corner rectangles, they should resolve this situation like this: if player hits corner from the bottom, act like horizotal rectangle, if he hits from side, act like vertical.

Thing is, I have no idea how to make them work like that.

Here is my code so far:

        if (InputHandler.KeyDown(Keys.W))
        {
            player.MoveUp();
            Parallel.For(0, horizontalPlayerCollisionRectangles.Count, i =>
            {
              if (player.PlayerRectangleInWorld.Intersects(horizontalPlayerCollisionRectangles[i]))
                {
                    player.PlayerPositionY = horizontalPlayerCollisionRectangles[i].Y + horizontalPlayerCollisionRectangles[i].Height;
                }
            });
        }

        if (InputHandler.KeyDown(Keys.D))
        {
            player.MoveRight();
            Parallel.For(0, verticalPlayerCollisionRectangles.Count, i =>
                {
                    if (player.PlayerRectangleInWorld.Intersects(verticalPlayerCollisionRectangles[i]))
                    {
                        player.PlayerPositionX = verticalPlayerCollisionRectangles[i].X - player.PlayerRectangleInWorld.Width;
                    }
                });
        }

        if (InputHandler.KeyDown(Keys.A))
        {
            player.MoveLeft();
            Parallel.For(0, verticalPlayerCollisionRectangles.Count, i =>
            {
                if (player.PlayerRectangleInWorld.Intersects(verticalPlayerCollisionRectangles[i]))
                {
                    player.PlayerPositionX = verticalPlayerCollisionRectangles[i].X + verticalPlayerCollisionRectangles[i].Width;
                }
            });
        }

        if (player.Gravity)
        {
            Parallel.For(0, horizontalPlayerCollisionRectangles.Count, i =>
            {
                if (player.PlayerRectangleInWorld.Intersects(horizontalPlayerCollisionRectangles[i]))
                {
                    player.PlayerPositionY = horizontalPlayerCollisionRectangles[i].Y - player.PlayerRectangleInWorld.Height;
                }
            });
        }

Its pretty simple. Now that I think about it, my system is flawed, so thats why I'm asking this question. How to make collision work using collision rectangles?

P.S. I can't use any physics engine like Farseer, it's a school graduation project and I have to code as much as possible by myself.


texts: How do I make circles bounce off each other realistically?

texts:
I'm trying to create bouncing balls with realistic physics. At the moment, when the balls hit each other, they bounce back in the same direction they came from. How do I make them more realistic?

I don't know much about physics. What things should I be reading about?

Here's an image of how I imagine balls would bounce in real life:

how I think it should work (original source: http://thewombatguru.nl/Bouncing.png):

Is this how it works?


texts: Is it acceptable to buffer no data OpenGL?

texts:
Correct me if I am wrong, but if you call "glBufferData(...)" upon an existing buffer, it will resize the buffer to whatever data you upload.

Does that mean if I call something like

glBufferData(GL_ARRAY_BUFFER, 0, NULL, GL_DYNAMIC_DRAW);

it will keep the buffer in existence, but it will have size and no data?

In the description of glBufferData, it says it is acceptable to pass NULL as a data parameter, but it mentions nothing of the size parameter.


texts: SelectBox in LibGDX doesn't display and freezes the program after a click

texts:
I am currently trying to apply an overlay with LibGDX over my 3D ModelBatch. Everything works fine except for the SelectBox. Once instanciated, it shows up on my screen I can click on it once but then it freezes. The drop-down list is not displayed and the clicks are no longer registered by my application. However, if my second click is under the standard position of the list, that is where it should be drawn when it drops down, an item is selected but then any third click will just return the list to the original selected item and no click is registered by my application anymore. I am running the application on Desktop.

Using break points in the SelectBox.class I was able to notice that the third and other next clicks are registered by the SelectBox.class as part of the list in the Listener responsible for selecting an item.

selectBox = new SelectBox<Object>(skin);
selectBox.setItems(array);
selectBox.setSelected("Custom");
stage.addActor(selectBox);

array in this case is an instance of Object[] containing only Strings. This is the only part of code I have related to the selectBox.

I have tried using an array of String[] at first but then switched to Object as suggested on a LibGDX forum.

I am currently using the latest Nightly Build of 2014/04/11 as I also need TextArea which is not yet in the stable release. However, I have tried the stable release 0.9.9 and it doesn't work either.

Am I using the right code to declare my SelectBox, or what could I do to make the SelectBox behave properly that is display its list when clicked and return to a normal state after an item is selected?


texts: how to set image resource path for D3DXCreateTextureFromFileEx method?

texts:
I try to merge all the image resources to a folder called resource. So, set image path as "resource/" but my directX framework only works if I compile at VS 2010. If I run from the debug folder it cannot run.(I already copy all the image resources to debug folder)

http://i.stack.imgur.com/XRFLC.png

string folder = "resource/";

void setTexture(LPDIRECT3DTEXTURE9& texture, string imgName, int imgWidth, int imgHeight, D3DCOLOR TransparentColorKey)
{
    string path;

    path = folder + imgName;

    //  Create texture.
    hr = D3DXCreateTextureFromFileEx(d3dDevice, path.c_str(), imgWidth, imgHeight,
        D3DX_DEFAULT, NULL, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED,
        D3DX_DEFAULT, D3DX_DEFAULT, TransparentColorKey, NULL, NULL, &texture);
}


texts: How to implement marching cube algorithm for rendering clouds

texts:
I would like to render clouds using C#, directX9.0

using Microsoft.DirectX.Direct3D;
using Microsoft.DirectX;

Now I have roughly add and render the vertex as per below:

As you can see, the vertex is added in a cubic structure. And what I need to do now is to change the cubic structure to curve structure so that the whole cubic structure should looks like a cloud.

I am not using any graphic library but to build this structure solely using Microsoft.DirectX and DirectX.Direct3D

I did some Google search, and it seems the cube marching algorithm is a useful method to be implemented on these kind of 3D rendering.

From what I researched, there are no ready source for C#, but only for C++ for cube marching algorithm.

So, I would like to ask, if I only want to do the cloud rendering, is the marching cube algorithm a must? Or are there other options to align the structure to let it look like a cloud?

I totally have no idea at all, hope could look for some snipshot of source code or any good reference in C# using DirectX.dll


texts: How can I generate a lightning bolt effect?

texts:
Is there an algorithm to generate a lightning bolt?
I would like an algorithm that generates a list of segment or point objects specifying where the bolt will land. The method would need a start point parameter, along with an endpoint. The bolt should have random branches coming off it, and zig-zag at random intervals. The result will be a random lightning effect that would look somewhat like this

(source: wikimedia.org)
If anyone knows of an algorithm that this may work for, help would be greatly appreciated!


texts: How to make a triangle move and rotate using GDI in C++

texts: I want to make a triangle move from one place to another then rotate it 270 degrees using Polygon() function does anyone knows how to?? Just a simple one.


texts:
I have a delta in screen coordinates that I want to transform to a 3d delta in world space.

The delta is in this case a movement across the (x,y) coordinates in screen space on the near projection plane for a known z in the 3d space. The goal is to move an object in 3d space horizontally and vertically.

How would I do this?

I guess it has something to do with getting rid of the translation component in the world-view-projection matrix, as the delta is only influenced by the scaling and rotation part of the matrices.

I tried the naive approach by setting the translation component in the world-view-projection matrix to 0, but that did not work.

The only working solution i found so far is to unproject the (0,0,z) coordinate of the object to world space and then unproject the delta (x,y,z) to world space. The result of these 2 un-projections is then substracted to get the delta in world space.


texts: How to move vertices of matrix in order to cast a 2d shadow?

texts:
I am trying to add shadows to my 2D xna game. Currently I have created a "shadow" using the texture of the caster with a transparent gray color, rotated, and stretched using a matrix. This, though, does not look like a real shadow, obviously. What I'm pretty sure I have to do is individually move the vertices of the matrix somehow in order to create a parallelogram so that the top and bottom sides are always parallel to the ground.

So, here are my questions:

1) Is this the correct way to cast shadows in a 2D game?

2) If so, how do I make a parallelogram out of the matrix? I've tried a vertex shader but that didn't go very well. I've also seen some people talk about using bones and using DynamicVertexBuffer, but I have no clue how to use them and can't find a tutorial on them.

3) If it isn't the correct way of casting shadows, then how should I do it? I don't want shadows like in Catalin's method, I want them to look like the shadow caster.

EDIT: I also just learned that the transformation I think I need to do is skew the matrix. XNA unfortunately does not include methods to do that, though.

EDIT 2: Here's a picture of the type of affine transformation I want to do (skewing):

I have sort of solved the problem and in-case anyone else wants to know how to skew horizontally here is how:

Matrix skew = Matrix.Identity;
skew.M12 = (float)Math.Tan(Math.PI / 4); // replace Math.PI / 4 with the radian amount you want

I need to skew vertically (which I can do by rotating and rotating back, but is there a more efficient way?), though and would still like to know if this is the correct way of going about creating shadows in a 2D game, though

EDIT 3: Here's what I have done in my game, and this is how the shadows should look. I've used a bunch of math and transforming to achieve the matrix for the shadow. Hopefully I've done it the right way


texts: Mobile Game - Do I need visual feedback?

texts:
I am currently on a game for windows phone 8.1 where the user can use items. If the user tries to use a item which he doesn't own a sound gets played. If now a user plays without sound or listens to music it might be that he doesn't realize that he tries to use it without realizing why it won't work.

Should I make a visual feedback?


texts: Do you need resource manager for HTML5 games?

texts:
Usually, resource manager is needed for desktop/mobile games. But is it needed for HTML5 (browser) games?

Resource manager's main responsibility is to make sure there is no clone of a resource in memory. But in browser, when you request something, the request is usually cached. So when you make another request to the same resource, the resource is not loaded anymore. You immediately get it. (CMIIW).

So, do you need resource manager for html5 browser games?

Thanks.


texts: Unity Method count exceed the limit of 64K

texts: I just got an issue related to a 64k method in Unity so that's why I'm unable to build my project. It shows method limitation exceed the limit of 64k method count. So can anyone here help me out to resolve this issue?


texts:
Please take a look at the screenshot below, from the old classic Space Harrier.  My question regards the curved perspective on the chequerboard 'ground'.  It's got a strangely curved geometry (I remember seeing this in a few old games/demos).  I reminds me somewhat of a moire effect, and I think some of it (in the background) is just that - but I don't think its the full story.  Compare with the screen shot from the Sega version, which shows moire effects in the distance, but not the same curvature.

So...

Why the curvature?
Did they do this on purpose, or is it a side effect of some technique?
How is it achieved?


texts: How to detect which car T-boned the other in a collision?

texts:
Setup
The game has cars and collisions, and I'm trying to create the following system:

When a car T-bones another, the one getting T-boned is destroyed;
When the cars collide laterally (usually just bump into each other), a normal physics collision happens (and nothing is destroyed);
When the cars collide head-on, the lighter one is destroyed.

The cars are all instantiated from 1 prefab. This can't be changed.
Car Setup
The main body sans the bumper has a normal, non-trigger collider and the dynamic Rigidbody. It has the tag "Destructible".
A child object (which also houses the bumper model, but that shouldn't matter) has a normal, non-trigger collider for the bumper. It has no Rigidbody and reports to the parent's Rigidbody. It has the tag "Destroyer".
Attempted Solutions
1) The transform.forward solution
Get the transform.forwards of both cars and compute their dot product.

If the 2 vectors are opposite each other (or close to it), destroy the lighter car.
If the vectors are facing away from each other (or are close to parallel), let a normal collision happen.
If the vectors are perpendicular (or somewhere in that ballpark)... then I'm lost. How do I know which car T-boned which?

That brings us to the solution #2.
2) The 'multiple colliders' solution
Assign another collider to the bumper of the car and give it a separate tag (e.g. "Destroyer). As a consequence, give the other — main — collider a tag, too (e.g. "Destructible").

If a Destroyer collider hits a Destructible, the latter is destroyed.
If a Destructible hits a Destructible, a normal physics collision happens.
If a Destroyer hits a Destroyer, destroy the lighter one.

But here, I run into an issue.

You can't have multiple colliders on the same game object. Ergo, create an empty child and attach it there. I won't set it to Trigger, or otherwise it won't detect collisions with another of its type (i.e. Destroyer).
In order to destroy colliding objects, I need a script and an OnCollisionEnter() inside it.
OnCollisionEnter() won't run if neither of the game objects has a non-kinematic Rigidbody. This means I need to give the bumper colliders a non-kinematic Rigidbody.
But if I give them dynamic Rigidbodies, they'll just... float away from the car.

In other words, I need a way to create a 2nd collider but keep it firmly attached to the car. Furthermore, if the main collider covers it, then I need to exempt it from collisions with the 2nd collider (let's call it the sub-collider), and I can't use layers to do that or otherwise the sub-collider won't detect main colliders on other cars.
If I don't cover it, then I need the sub-collider to act as a normal physics collider, too, when it hits, for example, a wall, and not have the bumper sink into it. That means it needs a non-kinematic Rigidbody.
How can I solve this issue?


texts: Which nodes of the Collada DAE are most relevant for game object/character use?

texts:
I'm really new to game dev / D3D. And I was looking to choose an intermediary format to work with and convert to my internally used format. Collada DAE seems to be good as it can export animation too and it's XML. Kind of bloated but easy to parse.

My expertise is in reusable code writing, libraries, APIs and such. So my first impulse was to go an implement a FULL parser of the Collada format given the fact that I'm not 100% what I need or will need to extract from it.

As it seems Collada is trying to be everything and the kitchen sink, there's definitely stuff in there I don't think I need to be concerned about. So, sanity prevailed and decided to come here and ask the experienced people what are the important nodes for game characters and objects in the .DAE file? Or is there another format considered friendlier by game devs that can export animations too?

I've figured out the following are important:

geometries (mesh + triangles)
materials + images
animations + controllers
visual scenes + scene

What else am I missing from the top-level node list? I don't think lights are important as I deal with that in code. I just need to import meshes + textures + animations. At least for now, as I'm just starting out in D3D programming.

For a non-animated object I can get away with a .OBJ file but for a player with animations, I really don't think .OBJ supports them.

  So the question is: Which DAE nodes are relevant to game objects and animated characters?... and if someone experienced consuming this format could provide a few words describing them, in a more game-friendly way then that specification... would be great! Or should I use another intermediary format but .DAE?


texts:
I'm having trouble understanding why with this script, Vector3.Angle() sometimes will never reach 0.

This question comes from me trying to make a "turret" that rotates to face a target position. It was not quite working (the angle between the turret and target would get very close to 0 and start flipping between + and - values, and never actually 0).

So to debug it I stripped the script down, and used transform.LookAt(), trying to isolate the problem. However, even using LookAt(), the Vector3.Angle() method still -sometimes- refuses to report the angle as 0, and I'm not sure why.

                //Turret does not care about any Y position differences...
                Vector3 currCustom = currentTargetPosition;
                currCustom.y = transform.position.y; //ignore Y differences...
                Debug.Log("currCustom is: " + currCustom);

                Vector3 directionVector = currCustom - transform.position;
                Debug.Log("directionVector is: " + directionVector);

                float angle = Vector3.Angle(transform.forward, directionVector);
                Debug.Log("angle is: " + angle);

                transform.LookAt (currCustom);

The attached image should also help demonstrate what is going on (note that the object doing the checking is an empty GameObject located roughly where the orange square is).

Any ideas as to what I'm doing wrong are appreciated, thank you for reading.


texts: How many LoD versions of a model should I have?

texts:
Many games facilitate better performance by increasing/decreasing the number of triangles/polygons that are drawn, depending on how close the camera is to said object. Mountains, viewed from far away, could become literally flat. Models would steadily lose resolution as you walk further away from them, etc.

If I want to implement such a system, how many different permutations of the same model/models should I have? Suppose the model is 20,000 triangles when viewed up close, but then I halve that when the camera goes away, so now it is 10,000. Then again, when the camera is even further away, making it 5,000 triangles. Would three versions be enough? Or is this really just an arbitrary implementation? Does it depend on the game itself?


texts:
I am working on lens distortion correction in Unity. I created a new scene dragged the "Cardboard" prefab to the scene. In the cardboard setting I have set the Distortion correction as "Non". and I havent made  any changes to the CardboadDistortion.cginc shader code.  But still the performance is not clear.What will be the issue.How can I improve the performance.

I am using Unity 5.3.5
GoogleVRForUnity Package


texts:
first of all, sorry for the bad english.

I need to convert my mouse coordinates to world coordinates,
I'm trying to use the glm unproject method.
1280x720 is the size of the window, It's hard coded just for the test.
The View and Projection are my matrices, they're fine and are not related to the problem (or so I guess).

EDIT: Success. The solution is:

int x,y;
glfwGetMousePos(&x, &y);

GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);

y = viewport[3] - y;
float depth;
glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);

mousePos = glm::unProject(vec3(x, y, depth), View, Projection, vec4(viewport[0], viewport[1], viewport[2], viewport[3]));

This method seem to have worked.


texts:
My question is in about rotate methods in android.graphics.Camera. In Docs, I saw these comments:

  public void rotateX (float deg) Since: API Level 1
  Applies a rotation
  transform around the X axis.

  public void rotate (float x, float y, float z) Since: API Level 12
  Applies a rotation transform around all three axis.

There is my question:What is difference between using rotate (float x, float y, float z) and a sequence of rotate methods? For example what's the difference between these two snippets A and B?

A)

camera.rotate (x, y, z);

B)

camera.rotateX (x);
camera.rotateY (y);
camera.rotateZ (z);


texts: Simple Update loop to show questions one at a time

texts:
I have two lists which work with an XML file which holds questions and answers. At the moment the project displays all the questions at the same time so they "flicker" on the screen and iterate between each item in the list.

Whats the easiest way (coding) to pause the random generated list on any particular questions?

Question class:

class question
{
    public string questionString;
    public string apple;
    public string pear;
    public string orange;

    //the ? indicate the int can be nullable so it can accept the string item
    int? correctAnswer;

    public question(string newquestionString)
    {
        parseQuestion(newquestionString);
    }

    public void parseQuestion(string newquestionString)
    {
        List<string> questionComponents = newquestionString.Split('|').ToList<string>();

        questionString = questionComponents[0];
        apple = questionComponents[1];
        pear = questionComponents[2];
        orange = questionComponents[3];

        correctAnswer = Int32.Parse(questionComponents[4]);

    }

In Game1:

    Random q = new Random();
    int i = q.Next(questions.Count);

    spriteBatch.Begin();
    spriteBatch.DrawString(myfont, questions[i], new Vector2(100 + 100 *i, 100), Color.Black);
    spriteBatch.DrawString(myfont, myQuestions[i].questionString, new Vector2(100 + 100, 100), Color.Black);
    spriteBatch.DrawString(myfont, myQuestions[i].apple, new Vector2(100 + 100, 200), Color.Black);
    spriteBatch.DrawString(myfont, myQuestions[i].orange, new Vector2(100 + 100, 300), Color.Black);
    spriteBatch.DrawString(myfont, myQuestions[i].pear, new Vector2(100 + 100, 400), Color.Black);
    spriteBatch.End();


texts:
As of late I've been trying to implement Cubemaps in my engine, and have managed to get the rendering side of them working. Currently, I'm trying to implement a function for creating them, but I somehow hit a road block.

The way I'm trying to implement this is by rendering my scene once into an FBO from the perspective of the cubemap node (x6 times, one in each direction), and cycle the format of the texture bound to the color attachment as:

  GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, etc

For whatever reason, I haven't been getting any expected results.

All I want to do is take snapshots from the camera's perspective, but I need them in texture units I can use multiple frames over.

I've tried so many ways that I couldn't possibly recount them all here, but the general gist of how I've been trying to go about doing this, is this:

DTextureCubemapComponent *cubemap = getTexture(); // My Texture Component
GLuint target = cubemap->textureObj();            // CUBEMAP texture handle
glBindTexture(GL_TEXTURE_CUBE_MAP, target);       // Make cubemap active

for (int x = 0; x < 6; x++)                       // Render from 6 different angles
{
    gbuffercube->swapFinalFormat(GL_TEXTURE_CUBE_MAP_POSITIVE_X + x);
    gbuffercube->StartFrame();                    // my FBO Class, binds itself, etc

    /*... RENDER SCENE ...*/                      // Draw into my FBO, etc

    gbuffercube->BindForFinalPass();              // Read buffer == my FBO
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

Where "SwapFinalFormat()" is:

void GBuffer::swapFinalFormat(GLuint format)
{
    format = fmt;
    glTexImage2D(format, 0, GL_RGBA32F, size.width(), size.height(), 0, GL_RGBA,     GL_UNSIGNED_BYTE, NULL);
    glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT6, format, m_finalTexture, 0);
}

I know that my FBO class works (labeld GBufferCube above) , as it is the same class I use normally for my deferred shading system.


texts: How do I create a Button when I click another Button?

texts:
I need help. When I click a Button, I want to create a new Button. My code, however, creates four Buttons. What should I do?

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

public class AddButton : MonoBehaviour
{
    public GameObject prefabButton;
    public RectTransform ParentPanel;
    public Button saveButton;

    void Update()
    {
        if (Input.GetMouseButton(0))
        {
           // for (int i = 0; i < 2; i++)
            {
                GameObject button = (GameObject)Instantiate(prefabButton) as GameObject;
                button.transform.SetParent(ParentPanel, false);
                button.transform.localScale = new Vector3(1, 1, 1);
             }
        }
    }
}


texts: What math should all game programmers know?

texts:
Simple enough question: What math should all game programmers have a firm grasp of in order to be successful?

I'm not specifically talking about rendering math or anything in the niche areas of game programming, more specifically just things that even game programmers should know about, and if they don't they'll probably find it useful.

Note: as there is no one correct answer, this question (and its answers) is a community wiki.

Also, if you would like fancy latex math equations, feel free to use http://mathurl.com/.


texts:
Unity has a wonderful Tile Palette feature. However after I drag and drop the sprites to the Tile Palette, the tiles are off-centered like so (Notice the white square, it's the cursor):

I've tried fiddling with the Cell Size/Gap within the Grid object, and the Tile Anchor from the Tileset object with no difference.

Although I can place the tiles right in the scene, it's a headache to re-arrange and place the tiles within the Tile Palette with this off-center tile issue.

Did anyone of you faced and solved this issue before? Perhaps I overlooked something?


texts: I have tried using the automatic mapping in Mudbox and Maya, neither worked sufficiently, I was still experiencing polygon overlap. I tried mapping separate limbs but I came to the same problem, this is the very first model I made and as a result i didn't know to make the limbs separate layers / faces.


texts:
So, i'm developing a game in unity and avoided baking lightmaps untill now ( i just assembled my new workstation setup wich is capable of baking the lightmaps and not the computer ). And now i have opened my project, imported it nicely and all, went to the lightning tab and clicked generate lightning ( naturallly i had auto-bake disabled). And everytime i do that i get a billion errors, and they do not stop popping up even after i force stop & cancel, i have to clear baking data in order to do anything ( of course unity is laggy as hell when it's spitting out these errors ). I even tried just a simple scene with just a plane on it. It's the same.

I checked and it works fine on another empty project, wich lead me to the conclusion that some texture in my assets folder is causing the error even though it's not on the scene at all. In this case i'm kina doomed, i have absolutely 0 idea wich texture could this be ( i have quite a lot of them) and why would it even cause problems. Any way to check that? Or maybe does somebody know another possible reason for this problem? I tried to do research but found literally nothing. No thread about the issue, nothing. Not even the same errors.

Thanks in advance.

PS: i have baked & realtime GI disabled


texts: Converting heighmap coords to world coordinates, or Masking areas of terrain for object spawn systems

texts:
My terrain already exists, and has been painted.

I'm trying to mask out areas of my terrain so I can "zone" object spawns. For example, I want to spawn branches and logs randomly on a beach over time but I need to clearly identify "beach".

My best solution so far is to use a texture mask. I exported my heightmap to a PNG, filtered out areas I don't want, but I see no way to accurately find the exact terrain coordinate because my heightmap is 1024 resolution but my terrain is 400. Scaling the heightmap coords to terrain coords gets close but I can't tell what Unity does internally to match it.

Here's how I scale those heightmap array coords to world coords:

// Vector2 heightMap is a randomly chosen coord. I sample random coords
// of the texture looking for white (with a max number of tries)
// if I find a coord, I try to convert it...

var xScale = Terrain.activeTerrain.terrainData.size.x / TextureMask.width;
var zScale = Terrain.activeTerrain.terrainData.size.z / TextureMask.width;

var terrainPos = Terrain.activeTerrain.transform.position;

var scaledX = heightMap.x * xScale;
var scaledZ = heightMap.y * zScale;

var wx = scaledX + terrainPos.x;
var wz = scaledZ + terrainPos.z;

var y = Terrain.activeTerrain.SampleHeight(new Vector3(wx, 0, wz));

Are there better ways to mask our areas of my terrain, or is this mask system a good approach and I'm just missing details?


texts: Why do I get this warning when using a null conditional operator?

texts:
In the OnTriggerEnter2D function of my Bullet script, I have the following code:

private void OnTriggerEnter2D(Collider2D other)
{
     if (other.CompareTag("Enemy"))
     {
         var enemy = other.GetComponent<Enemy>();
         enemy?.Death();
     }
}

The reason for the null conditional operator (the question mark) in enemy?.Death() is because the Death function actually destroys the Enemy component script,
so it suppresses an error when the bullet hits the enemy again. It's supposed to be shorthand for:

if (enemy != null)
    enemy.Death();

The code works; the error is suppressed. However, the IDE that I'm using, Jetbeans Rider, gives the following warning:

  '?.' on a type deriving from 'UnityEngine.Object' bypasses the
  lifetime check on the underlying Unity object.

What does that mean exactly? Should I continue using the null conditional operator?


texts: Is Spine's XNA runtime missing an importer?

texts:
I'm writing an XNA 4.0 game and use Spine for animation. Until now, I've been making spritesheets with Spine and using them with a custom animation class. I recently discovered there is an official Spine runtime for XNA. I've been trying to use it but encounter an error.

The closest I've come (after adding the runtime's classes to my project) is this error:

  Cannot autodetect which importer to use for "data\goblins.atlas". There are no importers which handle this file type. Specify the importer that handles this file type in your project.

Is there such an importer in the runtime and I simply missed it? If so, how can I get XNA to recognize it? If not, is there an alternative?


texts:
I'm trying to achieve some neat 2d water reflection effect with Unity, something like this:

What I've managed to accomplish so far:

The problem is GrabPass captures the entire screen but I really want to control precisely what area of the screen will be captured.

Is it feasible with GrabPass? (I'd rather not use a new camera for a rendertexture).

Is that even the right approach?


texts:
I'm using XNA to create a simple block breaker game. At the moment I have controls set in the standard way:

if (keystate.IsKeyDown(Keys.s))

I've figured out the file handling problems involved and have taken in a string from a text box, for examples sake I'll have that string as "NumPad2". Now I need the game to take that string and somehow use "NumPad2" as the new control, instead of "s".