texts:
I have a question about proper ways to draw UI, since I've learned what I know from the internet and by experimenting I often dont code the "proper" way, instead I do it my own way, not knowing if it will have consequenses that Im unaware of. So, Is it "wrong" to draw your UI using density pixels?

For Example:

canvas.drawText(bullets, this.getWidth() - 134 * dp, 32 * dp, paint);

I try to use getWidth() and getHeight() as much as possible but sometimes I just need to use constants in my code to place stuff where I want it, is this ok as long as I use dp? or will this effect the layout on screens with different resolutions/performance? (Don't have anything except my own to run the game on)


texts: How reliable is glLineWidth() for parameters greater than 1?

texts: It says in the OpenGL ES specification that glLineWidth is only required to support values up to 1, but how many OpenGL drivers actually keep this function at the minimum requirement?


texts: Managing multiple animation files in a Unity project

texts:
I am on my project, but find it hard to understand what I'm missing from those few animation and rigging tutorials.
I have an FBX I modelled and rigged from blender... Or I could just take a model from Mixamo or other resources.
Is it possible to have loosely coupled .anim files which could be mix-matched at runtime with different FBXs?
It seems the Animator Controller can reference each .anim file independently if necessary, so I guess we can make one animation per fbx and split anim files in Unity project explorer... There must be a better way, right?


texts: How could I store different abilities in the player class?

texts:
So, I have a player class with basic actions.
During the gameplay he unlocks new abilities.
I don't know how to store new actions within the player class.
To be precise - I know how, but my method is too messy and i want to clean up code.
Also, I want to add to the enemies some of those abilities.
In other words, every game entity(expect walls, perhaps :D) should have a collection to which i can add methods that extend entity functionality. How do i make this?


texts: How do I allow a player to build a dedicated server, but prevent them from cheating?

texts:
Instead of maintaining a central server, many games allow players to build their own server, like Minecraft.

But if you give them the server-side program, how could you prevent them from cheating? I thought it's impossible, but Team Fortress 2 seems doing that. Usual TF2 servers are built by players. But Valve sells the items in TF2, so they must have a way to prevent server owner generating these items.


texts: GLSL Core Functionality Geometry Shader examples

texts:
I'm doing some research on geometry shaders and am having problems finding code examples/tutorials that does not use one of the extensions introduced before it was core functionality of OpenGL 3.2.

I'm looking for more modern approaches that doesn't use an extension.

Can anyone point me in the right direction?

I've already read the spec, but am looking for actually code examples.


texts: Error in DRAW GUI event on android. (GameMaker)

texts:
Image of the game on a mobile phone:

As you can see the maze (draw event) has been resized correctly.

But the yellow post-it (draw GUI event) has not been scaled or displayed in the correct location (center of the screen). Same thing with GUI layout (draw GUI event).

Because this is a small stage/room (size) I do not use the artifice of views, I thought that could be because of that the problem, but I enabled the views and did not get any different result.

Picture of the game on a computer (like it should be on the phone):

OBS - One information that can help you to help me solve the problem, is that to draw the post- it I use the following code: draw GUI event draw_sprite(spr_Post,0,640,360);.

640 is the half screen width of the game and also the room, 360 is half the height of the game screen and also the room.

It seems that somehow the room on the cell phone is different size than 1280x720.

I do not put the following code: draw GUI event draw_sprite(spr_Post,0,room_width/2,room_height/2), because there are much larger phases that need views, so the post-it needs to be in the center of the screen of the player, and with this code it ends up being in the center of the phase.

I tested the game on Bluestacks and it did not happen the same as on the phone.


texts:
Maybe it's a stupid question but I actually don't know - is it possible to change vertex buffer's size after it's been already created (with CreateBuffer())? If so, how do I update its data (with both Map() and UpdateSubresource()) when the new data contains more/less vertices?

I'm interested in vertex buffers and dx11 but the question probably applies also to index buffers and opengl.


texts: Mesh getting offset on combine because of worldmatrix

texts:
When I try to combine my mesh, it get offset to an other position, but the collider is still at the same place (because i dont delete and add it again). I saw a fix on internet that is to do:

Matrix4x4 myTransform = transform.worldToLocalMatrix;
combine[i].transform = myTransform*meshFilters[i].transform.localToWorldMatrix;

which worked in one of my script, but I just cant get it to work in this one. How can it be fixed ?

Vector3 cb = Vector3.zero;
Vector3 n = hit.normal;
Vector3 p = hit.point;

if(n == new Vector3(1.0f,0.0f,0.0f) | n == new Vector3(-1.0f,0.0f,0.0f))
{
    cb = new Vector3((n.x*0.5f)+p.x,Mathf.Round(p.y),Mathf.Round(p.z));
}
if(n == new Vector3(0.0f,1.0f,0.0f) | n == new Vector3(0.0f,-1.0f,0.0f))
{
    cb = new Vector3(Mathf.Round(p.x),(n.y*0.5f)+p.y,Mathf.Round(p.z));
}
if(n == new Vector3(0.0f,0.0f,1.0f) | n == new Vector3(0.0f,0.0f,-1.0f))
{
    cb = new Vector3(Mathf.Round(p.x),Mathf.Round(p.y),(n.z*0.5f)+p.z);
}
GameObject cub = Instantiate(cube,cb,Quaternion.identity);
GameObject dupli = Instantiate(hit.collider.gameObject,hit.collider.gameObject.transform.position,Quaternion.identity);
MeshFilter[] meshFilters = new MeshFilter[]{cub.GetComponent<MeshFilter>(),hit.collider.gameObject.GetComponent<MeshFilter>(),dupli.GetComponent<MeshFilter>()};
CombineInstance[] combine = new CombineInstance[meshFilters.Length];
Matrix4x4 myTransform = meshFilters[2].transform.localToWorldMatrix;
combine[0].mesh = meshFilters[0].sharedMesh;
combine[1].mesh = meshFilters[1].sharedMesh;
combine[2].mesh = meshFilters[2].sharedMesh;
combine[0].transform = meshFilters[0].transform.localToWorldMatrix;
combine[1].transform = meshFilters[1].transform.localToWorldMatrix;
combine[2].transform = meshFilters[2].transform.localToWorldMatrix;
meshFilters[2].mesh = new Mesh();
Vector3 sP = meshFilters[2].gameObject.transform.position;
meshFilters[2].gameObject.transform.position = Vector3.zero;
meshFilters[2].mesh.CombineMeshes(combine);
meshFilters[2].gameObject.transform.position = sP;
Destroy(meshFilters[0].gameObject);
Destroy(meshFilters[1].gameObject);


texts: Linker error while trying to extend and recompile irrlicht

texts:
I am trying to create a custom IGUIElement in irrlicht, for that I have included the sources from irrlicht and extended the CIGUIStatictext class.
Now whenever I try to compile my project, I get a host of linker errors, I must admit to ignorance of the compilation process and am not really able to figure out why this is happening.
I'm including the source for both my header and cpp class as pastebin.

sample of the linker errors:

1>graphNode.obj : error LNK2019: unresolved external symbol "public: virtual__thiscall irr::gui::CGUIStaticText::~CGUIStaticText(void)" (??1CGUIStaticText@gui@irr@@UAE@XZ) referenced in function__unwindfunclet$??
    0graphNode@gui@irr@@QAE@PAVIGUIEnvironment@12@PAVIGUIElement@12@HV?$rect@H@core@2@PB_W@Z$0 1>graphNode.obj : error LNK2019: unresolved external symbol "public:__thiscall irr::gui::CGUIStaticText::CGUIStaticText
    (wchar_t const *,bool,class irr::gui::IGUIEnvironment *,class irr::gui::IGUIElement *,int,class irr::core::rect<int> const &,bool)" (??0CGUIStaticText@gui@irr@@QAE@PB_W_NPAVIGUIEnvironment@12@PAVIGUIElement@12@
    HABV?$rect@H@core@2@1@Z) referenced in function "public: __thiscall irr::gui::graphNode::graphNode(class irr::gui::IGUIEnvironment *,class irr::gui::IGUIElement *,int,class irr::core::rect<int>,wchar_t const*)"
    (??0graphNode@gui@irr@@QAE@PAVIGUIEnvironment@12@PAVIGUIElement@12@HV?$rect@H@core@2@PB_W@Z)

1>graphNode.obj : error LNK2001: unresolved external symbol "public: virtual bool__thiscall irr::gui::graphNode::OnEvent(struct irr::SEvent const &)" (?OnEvent@graphNode@gui@irr@@UAE_NABUSEvent@3@@Z)
1>graphNode.obj : error LNK2001: unresolved external symbol "public: virtual void__thiscall irr::gui::CGUIStaticText::updateAbsolutePosition(void)" (?updateAbsolutePosition@CGUIStaticText@gui@irr@@UAEXXZ)
1>graphNode.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall irr::gui::CGUIStaticText::draw(void)" (?draw@CGUIStaticText@gui@irr@@UAEXXZ)
1>graphNode.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall irr::gui::CGUIStaticText::setText(wchar_t const *)" (?setText@CGUIStaticText@gui@irr@@UAEXPB_W@Z)


texts: How can I use the colours of a swatch in a script?

texts:
In Unity's editor I have set a swatch with some colours that are used throughout our game:

This swatch is saved in a file in the project's Assets folder:

\ProjectFolder\Assets\Editor\Main Colors.colors

I would like to use the colours in this swatch somewhere in a script:

GetComponent<Graphic>().color = SomethingHere.MainRed;

What is the best way to do this? Or is it not possible?

Reflection

I also think that I'm doing something really strange? I couldn't find any answer to this question online. But having the same colour library in the scripts as I use in the editor would be really nice.


texts: Texture becomes white box when drawing it?

texts:
My problem is that when I try to render my sf::Sprite it only renders a white box in my window.

I did some reading on this and couldn't really find anything that helped.

Some said that it's because of  the sf::Texture variable being in a local scope but mine is in a .h file, which isn't a local scope (I think, at least...)

Someone also mentioned std::vectors somehow destroying the sf::Texture 's,
but my sf::Texture is not in a std::vector.

However my class which contains sf::Texture is a object inside a std::vector but I don't know if that matters or not.

In my Sprite.h I have defined my sf::Sprite, sf::Texture and sf::Image like this :

sf::Sprite sprite;
sf::Texture texture;
sf::Image image;

and I load an image in like this :

if (!image.loadFromFile(PATH))
    std::cout << "Could not load image file : " << PATH << std::endl;

texture.loadFromImage(image);
sprite.setTexture(texture);

I render the sf::Sprite like this :

    for (int i = 0; i < entities.size(); i++)
    {
        entities[i].Draw();
    }

Lastly, here's my std::vector of my "sprite objects".

std::vector<Sprite>entities;
entities.push_back(Sprite(&window, sf::Vector2f(100, 100), 0, "Res/Images/Face.bmp"));

The picture file is a .bmp file, and the path to the file is valid.

(I did check both google and this forum for posts like this but none of them helped me.)


texts: Adding movement to a text-based rpg battle

texts:
Outline

I have the bones of a text-based RPG - the player can progress through a branching storyline and activate some simple events (recieivng/giving/trading items).

As I am designing the battle system (turn-based obviously) I decided it would be nice to have the player be able to "move" during battle - i.e. a heavy armour clad warrior would charge straight up to the foe but the ranger should pick his foes off from a distance and try to move to a better vantage point as the enemy approaches.

Main question

Rather than just giving the fleet of foot character a higher probability to dodge an attack (to compensate their lower defence) I wanted to give them the option to move to different points within the area of battle (jump on top of a rock, climb into that tree, etc) to make it more tactical but have become stumped.

Can anyone suggest a way to approach this (pseudo code would be nice)?

I am using C++ to write the program, if anyone wants to know.


texts:
I am trying to port a game I made using Flash/AS3, to the Windows Phone using C#/XNA 4.0. You can see it here: http://goo.gl/gzFiE

In the flash version I used a pixel-perfect collision between meteors (it's a rectangle, and usually rotated) that spawn outside the screen, and move towards the center, and a shield in the center of the screen(which is half of a semi-circle, also rotated by the player), which made the meteor bounce back in the opposite direction it came from, when they collided.

My goal now is to make the meteors bounce in different angles, depending on the position it collides with the shield (much like Pong, hitting the borders causes a change in the ball's angle).

So, these are the 3 options I thought of:

Pixel-perfect collision (Microsoft has a sample) , but then I wouldn't know how to change the meteor angle after the collision
3 BoundingCircle's to represent the half semi-circle shield, but then I would have to somehow move them as I rotate the shield.
Farseer Physics. I could make a shape composed of 3 lines, and use that as the collision  object for the shield.

Is there any other way besides those? Which would be the best way to do it(it's aimed towards mobile devices, so pixel-perfect is probably not a good choice)? Most of the time there's always a easier/better way than what we think of...


texts: How can I incorporate physics into a procedurally generated world from a geometry shader?

texts:
Essentially I want to remove the need for generating coherent noise from the CPU to the GPU. From there, I also want to generate the terrain for a three dimensional world using this noise as densities in voxel points. After this, I want to take those densities and polygonize (generate vertices) them representing the world's terrain.

This is fine and all. But, I also want to dynamically deform the world in real-time. Once I get to this point, I have a problem trying to get the vertices back to the CPU to do things like collision detection and all of the game computations that I want to involve on the CPU and not the GPU.

So the question is: how can I get a subset of the vertices back to the CPU for dealing with collisions among other things?

And one more question: is there an easy way to take a set of vertices and generate indices from them on the GPU?

I'm confused as well as to what kinds of shaders I should be using for these different things. I hear of people using a pixel shader for gathering densities and then using a geometry shader for dealing with the terrain generation from the vertices and then somehow incorporating a vertex shader to do the dynamic deformations.

I'm using C# 4.0, .NET 4.0, and XNA Game Studio 4.0.


texts: How to add a movieclip to the stage then make it move down?

texts:
I am making a game where i want to spawn zombies then make them move down the screen. I also want to have multiple on the screen at once. I have tried multiple ways now but none of them have worked.

Here is my code

if ((zombie == 1)||(zombie == 3)||(zombie == 5)||(zombie == 7))
{
    var Z = new Z;
    Z.x = 403.25;
    Z.y = -86.9;
    Z.rotation = 90;
    addChild(Z)
    zombie += 1;
}

//Functions
function startzombie(event)
{
    trace("start zombies")
    zombie = 1;
    addEventListener(Event.ENTER_FRAME,zombiemove)
}
function zombiemove(event:Event)
{
    Z.y += 1;
}

Z is the zombie


texts: Techniques for displaying vehicle damage

texts:
I wonder how I can displaying vehicle damage.
I am talking about a good way to show damage on screen. Which kind of models are common in games and what are the benefits of them? What is state of the art?

One way I can imagine is to save a set of textures (normal/color/lightmaps, etc.) to a state of the car (normal, damage, burnt out) and switch or blending them. But is this really good without changing the model?

Another way I was thinking about is preparing animations for different locations on my car, something like damage on the front, on the left side/right side or on the back, and start blending the specific animation. But is this working with good textures?

Whats about physics engines? Is it useful to use it for deforming vertex data? I think losing parts of my car (doors, sirens, weapons) can looks really nice.

My game is a kind of RTS in a top down view. vehicles are not the really most important units (its no racing game), but I have quite a lot in.


texts:
I'm creating a simple 2D game engine and I want to update and render the sprites in different threads, to learn how it is done.

I need to synchronise the update thread and the render one.
Currently, I use two atomic flags. The workflow looks something like:

Thread 1 -------------------------- Thread 2
Update obj ------------------------ wait for swap
Create queue ---------------------- render the queue
Wait for render ------------------- notify render done
Swap render queues ---------------- notify swap done

In this setup I limit the render thread's FPS to the update thread's FPS.
Besides I use sleep() to limit both render and update thread's FPS to 60, so the two wait functions won't wait much time.

The problem is:

The average CPU usage is around 0.1%.
Sometimes it's go up to 25% (in a quad core PC). It means that a thread is waiting for the other because the wait function is a while loop with a test and set function, and a while loop will use all your CPU resources.

My first question is: is there another way to synchronise the two threads?
I noticed that std::mutex::lock don't use the CPU while it is waiting to lock a resource so it isn't a while loop. How does it work?
I can't use std::mutex because I will need to lock them in one thread and unlock in another thread.

The other question is; since the program runs always at 60 FPS why does sometimes its CPU usage jumps to 25%, meaning that one of the two wait is waiting a lot? (the two threads are both limited to 60fps so they ideally won't need a lot of synchronisation).

Edit:
Thanks for all the replies.
First I want to say I don't start a new thread each frame for render. I start both update and render loop at the beginning. I think multithreading can save some time :
I have the following functions:
FastAlg()  and Alg().
Alg() is both my Update obj and render obj and
Fastalg() is my "send render queue to" renderer" ".
In a single thread :

Alg() //update
FastAgl()
Alg() //render

In two thread:

Alg() //update  while Alg() //render last frame
FastAlg()

So maybe multithreading can save same time.
(actually in a simple math application it does, where alg is a long algorithm amd fastalg a faster one)

I know that sleep isn't a good idea, although I ve never have problems.
Will this will better?

While(true)
{
   If(timer.gettimefromlastcall() >= 1/fps)
   Do_update()
}

But this will be a infinite while loop that will use all the CPU. Can I use sleep(a number < 15) to limit the usage? In this way it will run at, for example, 100 fps, and the update function will be called just 60 times per second.

To synchronise the two threads I will use waitforsingleobject with createSemaphore so I will able to lock and unlock in different thread (whitout using a while loop), won't I?


texts:
I'm resolving some collision between circles and I keep getting this problem.

Note: The rectangles are perfect squares fitting the circles so when I type rect.Width I mean the radius of the circle.

What I was trying to do was make it so that if it penetrated it would get pushed out and then the else if would take over and not call the if anymore. but the depth turns out to be a small number such as .6 and then since it's a float it rounds down and doesn't affect the rectangle at all. Even if I add a round function in there it just starts to jitter a bunch.

if (r < rect2.Width / 2 + rect1.Width / 2 && (fN + fG + fA).Length() != 0)
{
    // Resolve depth penetration
    float mDepth = rect2.Width / 2 + rect1.Width / 2 - r;
    Vector2 depth = new Vector2(mDepth * (float)Math.Cos(theta), mDepth * (float)Math.Sin(theta));
    rect2.X -= (int)depth.X;
    rect2.Y -= (int)depth.Y;

    // Apply an equal and opposite force
    fN = -fG

    // Stop the earth from moving
    v2 = Vector2.Zero;
}
else if(r == rect2.Width / 2 + rect1.Width / 2)
    fN = -fG;
else
    fN = Vector2.Zero;

I also tried changing depth penetration too this but the results are no different.

float mDepth = rect2.Width / 2 + rect1.Width / 2 - r;
Vector2 direction = rect1.Location.ToVector2() - rect2.Location.ToVector2();
direction.Normalize();
Vector2 depth = direction * mDepth;
rect2.X -= (int)depth.X;
rect2.Y -= (int)depth.Y;

The only solution we could think of is creating a range of 5 in which the object could be at rest.

if (r < rect2.Width / 2 + rect1.Width / 2 + 5 && r > rect2.Width / 2 + rect1.Width / 2)
    fN = -fG;
else if (r < rect2.Width / 2 + rect1.Width / 2 && (fN + fG + fA).Length() != 0)
{
    // Resolve depth penetration
    float mDepth = rect2.Width / 2 + rect1.Width / 2 - r;
    Vector2 depth = new Vector2(mDepth * (float)Math.Cos(theta), mDepth * (float)Math.Sin(theta));
    rect2.X -= (int)depth.X;
    rect2.Y -= (int)depth.Y;

    // Apply an equal and opposite force
    fN = -fG;

    // Stop the earth from moving
    v2 = Vector2.Zero;
}
else
    fN = Vector2.Zero;

Is there not a better way to do this?

Here is a video outlining the problem. https://www.youtube.com/watch?v=ZREQDA5BN0s Essentially since depth resolution isn't exact the == part of the if statement isn't used I know this because I placed a breakpoint in the first if statement it keeps going there with a depth of around .6. Then rounds down and doesn't move it at all. If I round it appropriately it just jitters a bunch.


texts:
I'm actually trying to generate a level with procedural generation using perlin noise.
So one chunk has a size of 30x30, it's a float 2d array and at first I'm filling it with values between 0 and 1. Next step is to calculate 7 octaves and merge them. In the end I normalize the values.
All this works quiet well if I only want to create one chunk but how can I create one more chunk beside my first so that they fit together smoothly?


texts: Find range between two signed 180° angles

texts:
How can I find the angle between two angles that go from -180 to 180 degrees?
I would like to do :
if (angleDiff > 90)
{
    // The angle is bigger than 90 degrees...
}

I tried subtracting them but that doesn't seem to work. Thank you


texts: Bullets and projectiles in component based entity systems

texts:
Currently one of my games engines written for a shooter seems to work correctly.

Currently projectiles are sparse, travel quite slowly and are synced over network they are generated as entities.

But in the future I'll have weapons generating very large amounts of much faster projectiles. So here I wonder if generating a system dedicated to projectiles would be a better idea. I currently want to generate projectile pools to manage the syncing of short lived projectiles without limiting the projectiles count.

Physics and collisions are managed by a physics engine where I can register any type of objects (server and client side).

Is there a better approach to the problem?


texts: How do I structure AI that uses both Behavior Trees and Pathfinding?

texts:
Architecturally, what are the best practices for how these two concepts interact with each other?

For instance, say I have an asteroids like game where the AI player must dodge floating asteroids while at the same time collecting powerups. If we want him to perform well we can't just have two separate behaviors for dodge and collect, he should consider everything on the screen.

Should the behaviors in the tree modify the weights of the pathfinding graph nodes (assuming using a graph based approach here)? Is A* like path finding even the best approach for this scenario?


texts: Logic / Render phases with a single thread

texts:
The question I have may generate different opinions from different developers, but I'd still like to have an answer on this.

Its all about the updating and rendering steps of the game loop, and their use under multi and single threaded environments.

Currently, there is one thread running, which takes care of sequentially executing events , logic and rendering. Sometimes, the logic part may wish to change the game state to something else, and in between do some loading of files.

The result is that the game hangs completely while loading, and then proceeds to normal rendering of the new state. To go around this, i could make another thread, do the loading there while the main thread renders a smooth loading animation, and then proceed normally.

The real question is about if i don't create another thread. I could refresh the screen from the logic thread, and provide some basic loading screen, which could be not so smoothly updated while the files load.

In fact, this approach is not loved by a lot of developers, as it scrambles render code in the logic step, which may cause problems of different sorts..

Hope its clear!


texts: Database structure for a trading cards video game (TCG)

texts:
Just started and after pondering with registered users' table everything came to a halt.

So far I've got:

+----------------------+
| tblUsers             |
+----------------------+
| userID(primaryKey)   |
| username             |
| password *           |
| accountStatus **     |
+----------------------+

* hashed
** 0=not activated, 1=activated, 2=suspended

Still haven't decided on each of the field's data type. But the question is: should I have one big massive table for all the cards or split them into say tblCreatures, tblSpells, tblTraps, tblQuests tables?

Plus, for example, some of the creatures have special abilities besides the usual strength and health stats. So I assume if there was tblCreatures, it would have  cardTitle, cardStrength, cardHealth, cardDescription and then it would have cardAbility0...4, because I doubt that a single creature card can have more than 2 abilities?

Also how would I contain each user's decks? A single user for example can have up to 10 decks created by themselves, which will be saved on the server.

Any suggestions/remarks?

The project will either be purely written in C# (both client and server) and XNA4, or maybe in the future the client will be ported to Flash+AS3 while server will be done in C#.


texts: Physics engine that can handle multiple attractors?

texts:
I'm putting together a game that will be played mostly with three dimensional gravity.

By that I mean multiple planets/stars/moons behaving realistically, and path plotting and path prediction in the gravity field.

I have looked at a variety of physics engines, such as Bullet, tokamak or Newton, but none of them seem to be suitable, as I'd essentially have to re-write the gravity engine in their framework.

Do you know of a physics engine that is capable of dealing with multiple bodies all attracted to one another?

I don't need scenegraph management, or rendering, just core physics. (collision detection would be a bonus, as would rigid body dynamics).

My background is in physics, so I would be able to write an engine that uses Verlet integration or RK4 (or even Euler integration, if I had to) but I'd much rather adapt an off the shelf solution.

[edit]: There are some great resources for physics simulation of n-body problems online, and on stackoverflow


texts: Should actors in a game be responsible for drawing themselves?

texts:
I am very new to game development, but not to programming.

I am (again) playing around with a Pong type game using JavaScript's canvas element.

I have created a Paddle object which has the following properties...

width
height
x
y
colour

I also have a Pong object which has properties such as...

width
height
backgroundColour
draw().

The draw() method currently is resetting the canvas and that is where a question came up.

Should the Paddle object have a draw() method responsible for its drawing, or should the draw() of the Pong object be responsible for drawing its actors (I assume that is the correct term, please correct me if I'm incorrect).

I figured that it would be advantagous for the Paddle to draw itself, as I instantiate two objects, Player and Enemy. If it were not in the Pong's draw(), I'd need to write similar code twice.

What is the best practice here?

Thanks.


texts: SDL Key Input previous and current key states not working as expected, how to fix?

texts:
Here is my code that's part of the main game loop:

  // ResetKeyState stores currentKeyState in previousKeyState
  // and then clears currentKeyState
  engine.ResetKeyState();

  // Fill currentKeyState
  while (SDL_PollEvent(&e) != 0)
  {
     // Call input to notify
     engine.Input(e);
     if (e.type == SDL_QUIT)
        engine.Quit();
  }

  // Return control to programmer for implementation
 engine.EngineUpdate();

  // Draw a pretty picture
  engine.EngineDraw();

and then to handle the input I have Input(e)

void Engine::Input(SDL_Event e)
{
   switch (e.type)
   {
   case SDL_KEYDOWN:
      KeyIsDown(e.key.keysym.sym);
      break;

   case SDL_KEYUP:
      KeyIsUp(e.key.keysym.sym);
      break;

   default:
      break;
   }
}

KeyIsDown stores the boolean state in an array as a true value.

KeyIsUp stores a false value.

Then later, I thought I would be able to do this to get a single input.

if (IsCurrentKeyDown('a') && !IsPreviousKeyDown('a'))

IsCurrentKeyDown and IsPreviousKeyDown just get data from their arrays

bool currentKeyState[INPUT_SIZE];
bool previousKeyState[INPUT_SIZE];

This way if you've are currently pressing the key but the value hasn't yet been stored it takes input once.

IE: You press the key so currentKeyDown is true and previousKeyDown is false until next update where currentKey gets passed to previousKey and the statement is then false. It's how Monogame and XNA do it so I figured I'd implement it here.

But it didn't work. I put a break point with a hit counter on it and it would hit it more than once per press. What am I doing wrong?


texts: How can I clip my sprite as it passes through a portal in a 2D scenario, using OpenGL?

texts:
This is a very simple question, but after a brief search and reading through the "similar questions" I could not yet find an answer.

I'm creating a 2D game using OpenGL and came across a problem: Let's say I wanted to create portals. An Entity can move into a portal A and come out of the corresponding portal B. Transforming the coordinates and velocity of the entity is easy, but this would create "hard" texture-teleportation.
Which means: while half of the entity is in the A-portal, it won't be rendered on the corresponding B side.
How would I create a smooth transition?

My first Idea was: I define "exit"- and "entry"-zones containing the transformation function (Matrix). Now when an Entity enteres the exit-zone the entity is also drawn at the entry zone using the transformation-matrix relative the the entry/exit-zones. But drawing it twice would still give me the difficulty, that I need to clip the entity on the portals "backside". (The entity shall vanish behind portal A when entering).

So my second thought was, that there should be a solution using (vertex?) shader? But how would such a shader look like? (Example code would be nice, but not neccessary. I'd rather want to have a "what the shader would do" answer). Would I define Uniforms (exit- and entry zones) which the shader would clip/transform ("move") the vertexes from?

How does a typical solution for this clipping look like? Or where could I read some information about these kind of problems? I only found some to 3D versions, where the view of portal B should be rendered in portal A. But this does not solve the object-moving-through-it problem...I think
In my opinion changing the draw-order, or rendering something above the backside of the portals is not the right way to go, since this could create strange behavior in certain situations. (Portal B is just behind portal A for example. One of both would be overdrawn I think.)


texts: How to let players connect over the internet via TCP?

texts:
We are making a 2 player game, using a Client/Server architecture and need a way to connect over the internet.

Connecting in the same network is no problem and works flawlessly. Will it be a lot of work to implement a way to connect online, that players can use (so nothing where they need access to the router settings)? And how would it be done?

I couldn't find a single tutorial or thread talking about this. They all just connected to the localhost.

(using gamemaker studio 2 and it's built in tcp networking functions)

  edit:

  The server regularly sends broadcast packages to all ip's, while the
  client reads their origin ip and can then connect to said ip. They
  both are on the same subnet so the adrress is 192.168.0.xx.

  I also have a way to get the public ip (95.xxx.xxx.xx) using a http
  get from ipv4bot.whatismyipaddress.com. But when trying to connect to
  the server, using the public one, I't won't connect (doesn't matter if
  both are on the same network).


texts: Algorithm for game difficulty/pacing curve generation in single player RPG

texts:
I'm looking at this article about pacing in entertainment and games. It suggests that all good entertainment roughly follows a pacing/engagement curve like Star Wars(below).

I'm interested in how I can procedurally generate random-looking curve that would conform to the Star Wars engagement intensity pattern (linear increase and oscillating peaks-valleys). The simplest implementation I can think of is a rectified sine wave and a sloped line, but that would be very predictable. I have an algorithm for perlin noise already in the game and am interested if I can leverage perlin noise algorithm to procedurally generate a varying sequence of peaks and valleys on an increasing slope.

Here's my attempt so far:

Once I have an algorithm, I can reference it to get engagement difficulty in relation to game turn or progress through some level.

I will add my thoughts to this question in hopes that someone can correct or point out flaws in my approach below:

I get the basic XP system in place (previous level *1000 to advance to next level)
Decide on the level cap (lets say 20 levels)
Plot available equipment tiers vs 20 levels (regular at lvl 1, magical at lvl 10, epic at lvl 20)
Using the peak-valley graph decide how many fights are in each peak-valley cycle (5 to reach lvl 2, 12 to reach lvl 20).
estimate number of turns per fight, let's say 5 turns per fight
calculate xp needed and turns needed to reach to each new level
Plot turn number and hypothetical xp the party has at each level.

Now for each peak I have a number of turns and the amount of XP that the curve should have between two valleys.

Using whatever formula the curve follows at that peak (let's assume a bell curve), I can get the xp value of monsters I have to spawn during that turn. These monsters have their equipment adjusted according to the equipment vs tier/turn number that was calculated above.

Now I need to adjust monster XP and test it at different levels. A simple sanity check: a party of 6 players must kill:

750 xp of monsters in first fight in 5 turns, that is 30 actions.
1500 in second fight
1800 in third fight
1350 in fourth
555 in fifth


texts:
My fear is that XNA has reached the end of the road. To keep up with the latest technology a shift to another game framework might be needed. We have many games in a large codebase, all based on XNA. My question is, how much work would it be to migrate to SharpDX and are there other possibilities?

Our code base mainly uses basic 3D rendering and the SpriteBatch, no fancy shader stuff.

Update:

I should have mentioned we only use 2.5D, we have a simple engine that builds textured quads to render text and animated sprites. Also for sound we use XACT (what else..) with some effects.


texts: How to force Game Center submit score failure

texts:
What would cause a failure to report a score to a Game Center leaderboard?
Currently, score reporting succeeds almost all the time, so I'm trying to force failure so I can fix it.

The Game Center documentation says it would fail to report a score if there are network issues.  Are there any other scenarios where reporting a score would fail?

I'm using Prime31's Game Center plugin for Unity3D.


texts:
I have an sprite I want to use as a texture.
I want to create an area, defined by a polygon collider, where the sprite is drawn.
For example:

Having the following sprite

And the following polygon collider 2d:

I want to have the resulting sprite/mesh:

This way I would have an image that covers exactly the polygon collider area.
Having an sprite and modifying it's vertexes doesn't seem to do the trick, as they are only editable while loading the sprite into unity.
Is there a way to make it editable in the editor, so while I change my collider, the image is updated to fit inside of it?


texts: Compensate for animation time in multiplayer network game

texts:
I'm developing a multiplayer turn-based card game. In certain scenarios, the clients are required to perform an animation before moving on with the game. For example, the server informs the clients to animate dealing cards to all players. This animation takes around 5 seconds. Afterwards, the server informs a client to make a move, with a timer showing how long they have to play.

How can the server wait for the animation to finish before moving on and starting a timer and informing a client to play? The timer obviously needs to start after the animations are complete.

I've thought of the following:

1) Hardcode the animation durations on the server side and delay sending out the next message to the clients until after the duration of the animation.

2) Have the clients inform the server when an animation is complete.

..but I feel that there should be a better way.

Is there any other way to do this?


texts: Can a game world be made using a 3D editor?

texts: I'm just wondering it it's possible to create and render a game world in a 3D modelling program, such as Blender, with landscapes and trees and such, and then import it into a game engine? Is that how open world games make their worlds, or do they use another method?


texts:
I was reading some game's source code on Github and saw this game loop implementation for the first time:

var lastTime = 0;
var maxTime = 1/30;

/**
 * @param {DOMHighResTimeStamp} curTime requestAnimationFrame provides this value automatically
 */
this.loop = function(curTime) {
    requestAnimationFrame(Game.loop);

    // Same as division by 1000
    var dt = (curTime - lastTime) * 0.001;

    if(dt > maxTime) {
        dt = maxTime;
    }

    for(var i = 0, len = boards.length; i < len; i++) {
        if(boards[i]) {
           boards[i].step(dt);
           boards[i].draw(Game.ctx);
        }
    }

    lastTime = curTime;
};

The key thing: The game updates and draws at every step, but the delta time is capped at the desired maximum delta. That way, if a frame takes too long, the next frame steps with a constant delta.

What are the pros and cons of this approach? I imagine it's useful for preventing huge entity movements caused by a long timestep, but can it cause problems?

Edit

Use curTime as provided by window.requestAnimationFrame in order to simplify stuff and avoid comments that don't deal with my main question.


texts:
I'm trying to create a live minimap of the complete game world. In order to do that I'm taking a snapshot of the whole game world (not only the part that is displayed) every 100ms or so.

The code I've used to take the snapshot is this (called every update()):

if (game.time.time < this.nextUpdate) { return; }
{
    this.stage.drawFull(game.world);

    //  Draw our black border rect
    this.thumbnail.rect(0, 0, this.thumbnail.width, this.thumbnail.width, '#000');

    //  And copy the stage capture to our Thumbnail (offset by 2px for the black border)
    this.thumbnail.copy(this.stage, 0, 0, this.stage.width, this.stage.height, 2, 2, this.thumbnail.width - 4, this.thumbnail.width - 4);
    this.thumbnail.update();

    this.nextUpdate = game.time.time + this.updateRate;
}

The code that creates these variable is this (called in create()):

//  The Stage is a BitmapData the size of the Game window
this.stage = game.make.bitmapData(game.world.width, game.world.height);

//  Thumbnail will hold our scaled-down version (+4px padding for the black border)
this.thumbnail = game.make.bitmapData(150, 150);

//  And thumbContainer is a Sprite with the thumbnail for its texture
this.thumbContainer = game.make.sprite(game.width - 150, game.height - 150, this.thumbnail);

//  Note we add the thumbContainer to the Stage, not the World, to avoid it being captured itself
game.stage.addChild(this.thumbContainer);

This is the result:

As you can see in the bottom-right minimap - The bitmap is rendered but the background isn't rendered for the whole thing (I think it's only rendered properly for the first 800x600 pixels). Also, if the player goes further down to the bottom ledge the minimap messes up completely:

It seems like a render issue, or a bitmap copy issue, but I can't find the problem. Does anyone have any idea why is this happening?

Thanks!


texts: Correct velocity on collision between two rects

texts:
I have two moving objects. The objects consist of a velocity vector2, a Rectangle and a vector2 as position (origin in the middle of the rect).

Some rough pseudo code for my collision checking function:

foreach (object1 in objects)
  foreach (object2 in objects)
    intersectionRect = Rectangle.Intersect(object1.Rectangle, object2.Rectangle)
    if (intersectionRect != Rectangle.Empty) // If colliding
      ResolveCollision(object1, object2, intersectionRect) // does nothing currently
    object1.position += object1.velocity
    object2.position += object2.velocity

My problem now is how to do the collision resolution. I need help figuring out a formula to calculate the new velocities of the objects so that they only move as far as they need to not intersect anymore.

I have used google to find a solution, but the most stuff I found was how to do collisions and not how to resolve them.


texts: Opening an executable process in background from unity

texts:
I am trying to make a chess engine run in the background from an interface i designed

    Process stockfish;
        stockfish = new Process {
            StartInfo = new ProcessStartInfo {
                FileName = System.IO.Directory.GetCurrentDirectory () + "\\Assets\\Scripts\\Stockfish\\stockfish.exe",
                Arguments = "",
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardInput = true,
                RedirectStandardError = true,
                CreateNoWindow = true
            }
        };
        try{
            stockfish.Start();
        }
        catch (Exception e) {
            print (e);
        }

The code is throwing an exception

System.ComponentModel.Win32Exception: ApplicationName='E:\Narsun Projects\Ahmad's Projects\CoachChess\Narsun-CoachChess-Unity\Assets\Scripts\Stockfish\stockfish.exe', CommandLine='', CurrentDirectory=''
 at System.Diagnostics.Process.Start_noshell (System.Diagnostics.ProcessStartInfo startInfo, System.Diagnostics.Process process) [0x00000] in <filename unknown>:0
 at System.Diagnostics.Process.Start_common (System.Diagnostics.ProcessStartInfo startInfo, System.Diagnostics.Process process) [0x00000] in <filename unknown>:0
 at System.Diagnostics.Process.Start () [0x00000] in <filename unknown>:0
 at (wrapper remoting-invoke-with-check) System.Diagnostics.Process:Start ()


texts: Should enemies still attack if they cannot see the player?

texts:
This may seem like a silly question, but let me explain this further.

Consider a common stealth situation where the player is hidden from the enemy AI. The AI has vision and hearing and if they either see or hear the player they will move towards the player's last known position. However if the player is behind cover (therefore the enemy cannot see them) and they attack with a silent weapon (therefore the enemy cannot hear them either), how should the enemy react?

Realistically, the enemy should have an idea of the direction from which the attack struck them and therefore start moving in that direction. But I am wondering if this then would be detrimental to taking a stealth as oppose to offensive approach. If the enemy turns around when hit irrespective of whether they were hit with a loud or silent weapon, there is little benefit to using a silent weapon, since the loud ones will have more power anyway. On the other hand, if the enemy simply stands their while being hit several times by a silent pistol, it may make the AI seem a little stupid.

I suppose it comes down to balancing between rewarding stealth gameplay in a stealth game, but not making the AI seem silly at the same time. What should I do to balance this?


texts: Unity C# reference source code within VS Code

texts:
Is there a way to inspect Unity C# reference source for a particular Unity class/method within the IDE (vscode) itself, rather than having to search thorough source files in GitHub.

In VS Code I could check the documentation for a class/method, with 'jump to definition'. But it is useful if I could also see the complete source code.


texts: How do 3d game engines draw this pattern?

texts: I am doing a small project, where there is a 3d engine, however I do not know how to draw something if it is like the image below. Usually I would draw from farthest back to closest. But here there is no order? How would modern 3d Engines draw this?


texts: How do I set an object's speed to arrive in X seconds?

texts:
I want to move an object to a point in the game world, I have the distance value which is far the player should move. I want to complete the movement in X seconds.

I have tried many equations and formulas to no success.

Speed = Distance/Time

This one doesn't seem to give me the right result. Thing is the game is updated 60 times a second and the movement is affected by delta time.

I'm pretty sure I am not taking the framerate in consideration.

What am I doing wrong?

Edit:

This is how I calculate the speed:

int dst = 500;
int time = 2; // in seconds
float speed = dst / time;

Doing it this way is making the movement instant and the game object is not traveling the distance in 2 seconds.

Every frame each game objects gets updated this way:

p.x += dir.x * speed * deltaTime;
p.y += dir.y * speed * deltaTime;

The dir vector holds the direction of movement which is calculated on mouse click:

Vector2 dir = new Vector2(mouseX, mouseY).subtract(objectX, objectY).normalize();

Delta time calculation:

long time = System.nanoTime();
float deltaTime = (time - lastTime) / 1000000000.0f;
lastTime = time;

Please note: The game object stops upon arrival.


texts: How do "procedural" and "random" generation differ?

texts:
To my understanding, everything that isn't directly created by a human is called "procedural". Procedural generation systems have different complexities and may consist of various algorithmic processes, some of which may be "random".

Some games explicitly refer to their systems as "random", while others call them "procedural", as if indicating a distinct difference.

Is there such a distinct difference? Where do you draw the line?

For example, here are contrasting examples of RPG loot generation:

Type A: Loot generation is ultimately left to chance, but it's based on a large intial factor of deterministic, specifically encoded knowledge.

Boss characters drop loot, which type is determined by the boss' characteristics (e.g. species, character class, elemental affinity, …) and additionally influenced by the player's play-style, to create more enjoyable gameplay: For example, more likely drop a fire-damage sword to a player who prefers fire-based melee attacks, along with gold.

Type B: Loot generation is almost completely random, based on minimal explicit knowledge.

Bosses have a randomised loot table (e.g. 1 legendary, 2 epics, 5 blues). If the roll is right to drop a legendary, random attributes are generated for that legendary, which may be high in value. Stuff like character attributes, player behaviour and such don't matter.

Both designs qualify as procedural by the initial definition, since their output is automatic, but Type A is significantly more sophisticated in crafting player experience.

Must an algorithm seem as if a person had designed its output by hand, to qualify as "procedural" rather than "random"?


texts: I'd like to have as little portability issues as possible but supports hardware acceleration. The main priority is on PC and having a game run on Windows, Linux and MacOS. Porting to consoles would however be great, too.


texts:
Can anyone explain how I can create a mirror effect like the one in this YouTube video using Unity Pro?

I know that I need to use render textures to do it, but I am not sure how.


texts: How do I detect when an HTML 5 game has ended?

texts:
I'd like to embed HTML5 games in a website, but I need to be able to detect when the game has ended so I can run some of my own JavaScript.

Looking at the output of some game engines (Construct 2, for example) reveals a nightmare of code that I couldn't hope to tweak so that it fires off an event when done.

How can I detect when a game has ended?


texts: How to get Entitas components from gameObject.getEntityLink()

texts:
I'm new to Entitas. I have a DamageSystem that should Physics.Raycast() toward the target and if tag is enemy it should reduce enemy health.

I have HealthComponent:

public class HealthComponent: IComponent{

public float value;

}

In DamageSystem I wanna do something like:

if(Physics.Raycast(target, direction, out hit)){

     tag.gameObject.entity.health.value = currentHealth - damage ;

}

But after Physics.Raycast(), I have  only  the gameObject and getEntityLink() method that return EntityLink without actual components... I guess that getEntityLink() returns only abstract components, and there is no way to get HealthComponent from EntityLink?

Does someone know how to get components from EntityLink, in a clean manner?
 Thanks!


texts: How do I add AndEngine documentation in Eclipse?

texts: I am very new to AndEngine. I have just downloaded the full documentation file, but I can't attach it to Eclipse. How can I do that?


texts: Updating aiScene in ASSIMP with skeleton data

texts:
I am working on a project where I take an unrigged closed mesh, import it using ASSIMP, auto-rig it using the algorithm provided by Ilya Baran and Jovan Popovic and again export it using ASSIMP. I have the following code that updates the aiScene structure created by assimp inserting the new skeleton data into it. I does not seem to be working, it throws weird exceptions. Can anyone check whether I am updating the data correctly...

Update Code:

void setSkeleton()
    //Number of bones is 20
    const int num_bones = 20;
    string names[num_bones] = { "hip_center", "spine", "shoulder_center", "head"
        , "shoulder_left", "elbow_left", "wrist_left", "hand_left"
        , "shoulder_right", "elbow_right", "wrist_right", "hand_right"
        , "hip_left", "knee_left", "ankle_left", "foot_left"
        , "hip_right", "knee_right", "ankle_right", "foot_right" };

    //define nodes
    aiNode* nodes[num_bones];
    for (int i = 0; i < num_bones; i++) {
        nodes[i] = new aiNode(names[i]);
    }

    //define parents
    nodes[0]->mParent = NULL;
    nodes[1]->mParent = nodes[0];
    nodes[2]->mParent = nodes[1];
    nodes[3]->mParent = nodes[2];
    nodes[4]->mParent = nodes[2];
    nodes[5]->mParent = nodes[4];
    nodes[6]->mParent = nodes[5];
    nodes[7]->mParent = nodes[6];
    nodes[8]->mParent = nodes[2];
    nodes[9]->mParent = nodes[8];
    nodes[10]->mParent = nodes[9];
    nodes[11]->mParent = nodes[10];
    nodes[12]->mParent = nodes[0];
    nodes[13]->mParent = nodes[12];
    nodes[14]->mParent = nodes[13];
    nodes[15]->mParent = nodes[14];
    nodes[16]->mParent = nodes[0];
    nodes[17]->mParent = nodes[16];
    nodes[18]->mParent = nodes[17];
    nodes[19]->mParent = nodes[18];

    //set root node reference in the aiScene object
    aiscene->mRootNode = nodes[0];

    //create bones for the 0th mesh in the scene(assuming there is only one mesh)
    aiMesh* aimesh = aiscene->mMeshes[0];
    aimesh->mNumBones = 20;
    aiBone* bones[20];
    aimesh->mBones = bones;

    vector<aiVertexWeight> weightsOfBone[20];
    //This loop creates vertexWeight objects for all the vertices affected by each bone in the above array
    int numVertices = rigOut.attachment->getNumVertices();
    for (int i = 0; i < numVertices; i++) {
        vector<pair<int, double>> weights = rigOut.attachment->getNZWeights(i);
        int s = weights.size();
        for (int j = 0; j < s; j++){
            aiVertexWeight wght(i, weights[j].second);
            weightsOfBone[weights[j].first].push_back(wght);
        }
    }

    //define bones
    for (int i = 0; i < num_bones; i++)
    {
        bones[i] = new aiBone();
        bones[i]->mName = names[i];
        const int numWeights = weightsOfBone[i].size();
        bones[i]->mNumWeights = numWeights;
        if (numWeights == 0) return;
        aiVertexWeight* weights = (aiVertexWeight *)malloc(numWeights * sizeof(aiVertexWeight));
        for (int j = 0; j < numWeights; j++) {
            weights[i] = weightsOfBone[i][j];
        }
        bones[i]->mWeights = weights;
    }
}


texts: What is the purpose of these purple images in these sprite files of Super Mario Maker?

texts: I was looking at the Wii U's Super Mario Maker Sprites and noted that all of them have purple images that each correspond to one of the animation frames (see below). What could they have been used for? Why not simply using the finished colored ones?


texts:
I have a set of terrain sprites available to represent terrain:

Flat
North-South Straight Cliff (x 2 allowing for slope direction either way)
West-East Straight Cliff (x 2 allowing for slope direction either way)
Convex North West Cliff
Convex North East Cliff
Convex South East Cliff
Convex South West Cliff
Concave North West Cliff
Concave North East Cliff
Concave South East Cliff
Concave South West Cliff

There source for my terrain is a height map that I am looking to represent with contours made up from above sprites. The cliff tiles would be placed on the below-threshold tiles that border the above-threshold ones. However when I split the height map by threshold I get terrain features that are impossible to represent with the tile set, for example:

    .....
... 1 1 1 ...
... 0 0 0 ...
... 1 1 1 ...
    .....

Where 1's represent tiles that are above the threshold and 0-tiles are below. My sprite set lacks the tile to represent either immediate neighbors (in this case North and South neighbors) being above threshold.

I am looking for a good approach to get rid of these cases. I have already tried just looping through all columns/rows looking for 1 0 1 combinations and changing the height map value to be above the threshold. In the end, I don't really mind the way the "gaps" are filled in, as long as the end result can be represented with my tile set.

Remember cases with diagonal gaps must be considered. For example:

    .....
... 0 0 1 ...
... 0 0 0 ...
... 1 0 0 ...
    .....

Also cannot be represented with my tiles set.

Finally, I'm also looking for a scalable solution to this problem. If I require to use and even more restrictive tile set that requires 1 (0 x n) 1 gaps to be filled in, as in the two above-threshold tiles can be n below-threshold tiles away from each other.

P.S. Apologies for my previous poorly worded question.


texts: fish tank water distortion Shader for unity

texts:
I am working on unity and trying to make a fish tank water distortion Shader effect with the following requirement:

1.its a 2D top down prospective.

2.every object under/in the fish tank has to be distorted, game objects might pass trough/under the fish tank (distortion) and game object might pass over the fish tank (no distortion) as well.

3.the fish tank does not follow the main camera.

I try to search online and most of the solution I get is to apply the shader to an object or to the main camera which will not meet requirement 3 or 2, can someone give me an ideal on what is the best way to deal with this ? I am working on a mobile game so the solution has to be light weighted on processing power. Many thanks !


texts: Best way of implementing custom UI objects jawa.awt.Graphics

texts:
What is the best way to implement custom sliders (for volume), buttons normal, with images (icons) and with text, text boxes and other stuff with java.awt.Graphics?

Thanks,
Kerdo


texts: How to prevent clipping when moving through a tunnel?

texts:
I'm developing for Android using OpenGL ES 2.0.

It's going to be a game where you have to fly through a tunnel without hitting the walls.

However, the tunnel wall gets clipped as the player approaches. This is especially annoying with the rings as they suddenly disappear, causing an uncomfortable flashing effect.

How can I make sure that the tunnel fills the entire screen?


texts: LibGDX MainMenu with ScrollPane - Select Level and press Play

texts:
In my level Menu, I am using tables that have images and text to identify each game level.
Those tables are in a table that is inside a ScrollPane so the player can browse the levels available.

Here is how i've written the code:

//top of my show() method

    stage = new Stage();

    Gdx.input.setInputProcessor((com.badlogic.gdx.InputProcessor) stage);

    atlas = new TextureAtlas("levelsmenu/levelmenu.pack");

    skin = new Skin(Gdx.files.internal("levelsmenu/liststyle.json"), atlas);

//example of the tables with image and text identifying each level

    tableLevel1 = new Table();
    tableLevel1.add(new Image(skin, "rhlevelone"));

    tableLevel1.add(new Label("THE HOOD", skin));

//table with the levels available

    Table levelList = new Table(skin);
    levelList.add(tableLevel1);
    levelList.row();
    levelList.add(tableLevel2);
    levelList.row();
    // etc.

// ScrollPane

    scrollPane = new ScrollPane(levelList, skin);

//
table3.add(scrollPane).padLeft(220).expandY();

//
stage.addActor(table3);

On the stage I have a button to go back to the Main Menu and a button to play the level selected.

I would like to request help to figure out how to set the right listeners so a level can be selected in the ScrollPane and then played cliking the Play Button.

Should I use FocusListener or ClickListener?

Here is an illustration of what I want do do:

Thanks in advance for any help that may come!!!

Rich Days


texts: TMX crashes in Tablet 10″ Android 7.0 with Andengine

texts:
I've developed a video game that has worked fine so far. When testing it in a Samsung Galxy A6 tablet (10" resolution with Android 7.0), I get the following error and the map won't load:

  Blockquote
  12-09 12:49:20.940: E/AndroidRuntime(9369): Process: cam.main, PID: 9369
  12-09 12:49:20.940: E/AndroidRuntime(9369): java.lang.NullPointerException: Attempt to read from field 'org.anddev.andengine.opengl.texture.region.TextureRegion org.anddev.andengine.entity.layer.tiled.tmx.TMXTile.mTextureRegion' on a null object reference
  12-09 12:49:20.940: E/AndroidRuntime(9369):     at org.anddev.andengine.entity.layer.tiled.tmx.TMXLayer.drawVertices(TMXLayer.java:220)
  12-09 12:49:20.940: E/AndroidRuntime(9369):     at org.anddev.andengine.entity.shape.Shape.doDraw(Shape.java:102)
  12-09 12:49:20.940: E/AndroidRuntime(9369):     at org.anddev.andengine.entity.Entity.onManagedDraw(Entity.java:991)
  12-09 12:49:20.940: E/AndroidRuntime(9369):     at org.anddev.andengine.entity.shape.Shape.onManagedDraw(Shape.java:120)
  12-09 12:49:20.940: E/AndroidRuntime(9369):     at org.anddev.andengine.entity.Entity.onDraw(Entity.java:875)
  12-09 12:49:20.940: E/AndroidRuntime(9369):     at org.anddev.andengine.entity.Entity.onManagedDrawChildren(Entity.java:1008)
  12-09 12:49:20.940: E/AndroidRuntime(9369):     at org.anddev.andengine.entity.Entity.onDrawChildren(Entity.java:1000)
  12-09 12:49:20.940: E/AndroidRuntime(9369):     at org.anddev.andengine.entity.Entity.onManagedDraw(Entity.java:993)
  12-09 12:49:20.940: E/AndroidRuntime(9369):     at org.anddev.andengine.entity.scene.Scene.onManagedDraw(Scene.java:233)
  12-09 12:49:20.940: E/AndroidRuntime(9369):     at org.anddev.andengine.entity.Entity.onDraw(Entity.java:875)
  12-09 12:49:20.940: E/AndroidRuntime(9369):     at org.anddev.andengine.engine.Engine.onDrawScene(Engine.java:517)
  12-09 12:49:20.940: E/AndroidRuntime(9369):     at org.anddev.andengine.engine.Engine.onDrawFrame(Engine.java:509)
  12-09 12:49:20.940: E/AndroidRuntime(9369):     at org.anddev.andengine.opengl.view.RenderSurfaceView$Renderer.onDrawFrame(RenderSurfaceView.java:154)
  12-09 12:49:20.940: E/AndroidRuntime(9369):     at org.anddev.andengine.opengl.view.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:617)
  12-09 12:49:20.940: E/AndroidRuntime(9369):     at org.anddev.andengine.opengl.view.GLSurfaceView$GLThread.run(GLSurfaceView.java:549)
  12-09 12:49:21.531: E/ApplicationPackageManager(4011): checkSettingsForIconTray value : 0

Rest of screens that are Android native work well. Please help!


texts: Game loop delta, factoring execution time?

texts:
Was thinking this morning, I 99.9% of the time, only see a main game loop, looking like this, just as much so where the delta is passed into update():

while running
getDeltaTime()
...
f(deltatime)
---

Now the question I was thinking to myself was what if between getDeltaTime() and f(deltaTime), the code in the middle took 1 second (large value to be easy). That means f(deltaTime) would have moved whatever object less distance than it was supposed to. This would of course be solved by grabbing the delta time directly before it is used.

Should this be a factor to be concerned with in any case?


texts: LibGDX: Why won't certain actions work on my Actor?

texts:
In my GameClass, I called the Stage.act and Stage.draw methods in the right order accordingly.

I have actions set up so that the actor fades in/fades out, bounces down/up, and also rotate, like so:

Label.LabelStyle font = new Label.LabelStyle(new BitmapFont(), Color.BLACK);

    Table table = new Table();
    table.center();
    table.setFillParent(true);

    Label playLabel = new Label("Text", font);

    Action fade = new SequenceAction(Actions.fadeOut(1), Actions.fadeIn(1));
    Action size = new SequenceAction(Actions.sizeBy(-20,-30,1), Actions.sizeBy(10,20,1));
    Action rotate = new SequenceAction(Actions.rotateBy(20), Actions.rotateBy(-40));

    ParallelAction pa = new ParallelAction(fade, size, rotate);

    playLabel.addAction(Actions.repeat(RepeatAction.FOREVER, pa));

    table.add(playLabel).expandX();
    table.row();

    stage.addActor(table);

The thing is, everything works except for the rotate method.

Similarly, I have similar problem when I use an Actor with Texture regions.

This is an example from another class.

public ReadyText () {
    cam = GameClass.cam;
    viewport = GameClass.viewport;
    cam.setToOrtho(true, viewport.getWorldWidth(), viewport.getWorldHeight());
    region = new TextureRegion(GameAssetLoader.Ready);
    this.setX(28);
    this.setY(165);
    this.setWidth(80);
    this.setHeight(30);

    //fade = Actions.sequence(Actions.fadeOut(1), Actions.fadeIn(1));
    Action rotate = Actions.sequence(Actions.rotateBy(80, 1), Actions.rotateBy(-90,1));
    Action resize = Actions.sequence(Actions.sizeBy(10, 5,1), Actions.sizeBy(-10,-5,1));

    ParallelAction pa = new ParallelAction(rotate, resize);

    addAction(Actions.repeat(RepeatAction.FOREVER, pa));

}

@Override
public void draw(Batch batch, float parentAlpha) {
    super.draw(batch, parentAlpha);

    batch = GameClass.batch;
    batch.setProjectionMatrix(GameClass.cam.combined);
    batch.draw(region, this.getX(), this.getY(), this.getWidth(), this.getHeight());

}

In this example, the "sizeBy" method works fine. But for some reason, it will not rotate. I commented out the "fade in/fade out" line; it also wasn't working either.

I know people will usually use an Image Actor instead, which makes sense, but I don't think it explains why the rotation won't work, or at the very least, why the Label didn't rotate either.


texts: Unity why do all gameobjects not dissapear from view when I switch cameras?

texts:
I am having trouble with camera switching. I have  two cameras: "Camera1" and "Camera2". A "button script" attached to Camera1 allows a switch to Camera2. It also positions the cameras.

There is a gameobject called "Main Menu" that is meant to be a background image for the button ; it is a GUI texture background (a flat jpeg image) .

At game start, clicking the button causes "Camera" components to be enabled and disabled appropriately, and it changes the game view background. So the button works (sort of!). But my problem is that the GUI texture does not disappear from game view, and nor does the button!

When I click the button, I want a complete change of game view, i.e., I want both the button and its GUI texture background to disappear from game view. But I am not getting that.

How can I make a GUI texture visible ONLY because it is in front of Camera1? How do I make the button visible ONLY when Camera1 is active?

Here is my button script:

      using UnityEngine;
      using System.Collections;
 public class PageButton : MonoBehaviour
 {
 public GameObject MainMenu ;
 public Camera cam1, cam2 ;
 void Start() {
 // position the Main Menu
     MainMenu = GameObject.Find("MainMenu");
     MainMenu.transform.position = new Vector3 (0, 0, 0);
 // Setup Camera1
     cam1 = GameObject.Find("Camera1" ).GetComponent<Camera>() as Camera;
     cam1.transform.position = new Vector3 (0, 0, -10);
     cam1.orthographic = true;
     cam1.orthographicSize = 5f;
     cam1.enabled = true;
 // Setup Camera2
     cam2 = GameObject.Find("Camera2" ).GetComponent<Camera>() as Camera;
     cam2.transform.position = new Vector3 (100, 100, 10);
     cam2.enabled = false;
     cam2.transform.Rotate(0,270,0, Space.World);
     cam2.orthographic = true;
     cam2.orthographicSize = 5f;
 }
 public void OnGUI()
 {
     if(GUI.Button(new Rect(580,340,20,20), ">")) {
         Debug.Log ("Button pressed");
         cam1.enabled = false;
         cam2.enabled = true;
     }
 } // end OnGUI()

 } // end PageButton


texts: LibGDX transparent textures look weird for a brief moment during skeleton animation

texts:
So I have a stage with some characters (Spine2D Skeletons). Each character has a health bar/stamina bar texture above them. The textures are simple PNGs with some gradient on them and transparency too.

Sometimes, when I set an animation on one of the skeletons in the stage, some of the health/stamina bars textures look like they're color burned or the transparency doesn't work on them while the animation lasts.

I tried setting PremultiplyAlpha to true and to false on the skeleton renderer but it didn't help.

Do you have any idea why this could be?

Edit: Sample before and after images:


texts: Graphical quality of open source vs. commercial games

texts:
I'm new in Game development. I have researched many open source games. But I have not met any open source game which has high quality graphics, comparable to these found in commercial games.

What is the reason for this? Are open source game engines not advanced enough to support such graphics or is there just a lack of assets, textures and models?

I know that this question is very general, I would like to hear some points of view.


texts: 3D Collisions - Walking below a slope pushes me through the floor

texts:
Here's a really short video (less than 30s) of this issue : https://www.youtube.com/watch?v=JrKbpTY8cMU

When I move the player towards a slope (the player is below it), it pushes the player inside the floor Collider instead of blocking it.

I've searched the Internet for a while but haven't found anything about it

Do you have something in mind ?Thanks for your time

Info : I move the player using rigidbody.MovePosition()

The collision of the player is a Capsule.


texts:
I am trying to create a basic solar system in 2D. All space objects has CircleCollider2D on them (which are required for raycasting in another script). Currently planets are childs of stars, and satellites are childs of planets. This is the code I am currently using on planets and satellites:

void Update ()
{
    transform.localPosition = Quaternion.AngleAxis(speed*Time.deltaTime, -Vector3.forward) * transform.localPosition;
}

This code basically rotates the GameObject around it's parent on a fixed velocity while keeping the distance at the beginning.

This setup does exactly what I want, but the problem is this:

After some research, I learned this:

  When you move an object with a collider and without a rigidbody, the complete static collision data needs to be recalculated, which is slow.

So moving GameObjects that has colliders via transforms (which I do in code above) causes this horrible workload.

So I need to do the exact same thing with Rigidbody2D, but I have absolutely no idea how to, I have tried a few things but they either caused objects to move out of orbit or draw spirals going out of orbits.

Thanks in advance.

Note: It is not mandatory for me to parent planets to stars and satellites to planets. So if you have a solution that requires not to parent objects to each other, please don't hesitate to post them.

Edit:

First of all, I didn't manage to do what I want with physics engine.

But while experimenting, I discovered that, you don't necessarily have to "move" transform via Rigidbody to prevent collider re-creation; it is enough to have a Rigidbody attached to the GameObject. So if you have a Rigidbody attached to the GameObject, it doesn't matter if you use Transform or Rigidbody to move the GameObject, engine doesn't try to destroy and re-create Colliders.

So I think my problem is solved right now, but question still open for answers since the question itself is still unsolved.


texts: Cross-browser cross-platform web support for immersive/non-casual games

texts:
I have heard of many plugins/browser technologies that are useful for games, but I didn't dive into any of them yet because I've assumed that omni-support wasn't quite there.  By omni-support, I mean all browsers and all OSs.

Since we've recently had many new game-specific plugins pop up (e.g. Unity), new web standards pop up (e.g. WebGL), and existing standards gain better support in IE (e.g. SVG), I'm wondering if this has changed.

There are three fundamental requirements I see to making immersive games:

Solid mid-to-low level video/audio support (2D and 3D are both interesting)
Mouse capture
Full screen

Are there technologies out there that support all three of these, that are cross-platform and cross-browser (including all the big browsers)?

Standardized solutions are preferrable, but plugin-based solutions are okay, as long as they support free or very cheap development.

Edit

I realize I posed my question as "are there any such technologies".  I'm actually interested in all such technologies.  If there is only one, it may still be useful to list other technologies, what they lack, and when they might get there.


texts: Unity UV map, tint / change color of texture

texts:
I have an array of vertices with texture coordinates for a UV map in Unity:

newUV.Add(new Vector2 (0, 1)); // FACE 1
newUV.Add(new Vector2 (1, 1));
newUV.Add(new Vector2 (1, 0));
newUV.Add(new Vector2 (0, 0));

newUV.Add(new Vector2 (0, 1)); // FACE 2
newUV.Add(new Vector2 (1, 1));
newUV.Add(new Vector2 (1, 0));
newUV.Add(new Vector2 (0, 0));

mesh.uv = newUV.ToArray();

It textures my mesh just fine.

How could I go around tinting FACE 1 to a darker color? Let's say the texture is just plain green and I wanted to texture only on FACE 1 to be a darker shade of green.


texts: Moving a particle around an Archimedean spiral at a constant speed

texts:
I want to move a particle in a spiral at a constant speed. Note that that is not a constant angular speed. This is proving rather difficult, and I'll go through my method so far below.

The spiral in question is a classic Archimedean spiral with the polar equation r = ϑ, and the parametric equations x = t*cos(t), y = t*sin(t). This looks like this:

I want to move a particle around the spiral, so naively, I can just give the particle position as the value of t, and the speed as the increase in t. That way the particle moves round the spiral at a constant angular speed. However, this means that the further out from the centre it gets, the faster its (non angular) speed becomes.

So, instead of having my speed in the increase in t, I want my speed as the increase in arc length. Getting the arc length of a spiral is the first challenge, but due to the fact that the Archimedean spiral I am using isn't too insane, the arc length function is , where a = 1. This allows me to convert theta values to the arc length, but that is the precise opposite of what I need. So I need to find the inverse of the arc length function, and at that hurdle, Wolfram-Alpha has failed me.

So is it possible to find the inverse of the arc length function? The function is a one to one mapping, if you exclude negative values of theta.

Thanks,

Laurie


texts: What are the code structures for storyline based game?

texts:
I am curious about how storyline-based games are written.

For example: if the character done Event A, then he meets an NPC and result in Event B.

On the other hand: if the character didn't do Event A, then he meets an NPC and result in Event C.

From the code structure that I've thought up, the NPC should be an object of a class, and there should be a status variable that mark if character have done Event A or not.
However, what if there's thousand of similar type of Event as Event A? How'd I handle huge, complex storyline game in coding?

I just want to know exactly how the trick was done to keep in check of what Events have happened.

Another thing that I'm curious about is how Event is kept in. An object? or just a function?

For example:
Event A might have some flashy effect played in non-fmv ,while maybe Event B is an fmv, and Event C might be a battle.

and there may be variety of them. Therefore, how would I handle variety of Events with a consistence method? or maybe, at the very least, contain them in a consistence way (function? or Object?) I just want to know how the trick was done.


texts:
I would like to create a simple Android app using Opengl ES 2.0 that is showing a simple shape (like line or triangle) that is glowing and pulsing like Nexus X logo in this video : http://youtu.be/jBKVAfZUFqI?t=59s

What should I look for?

So far I googled around for glowing effects and found techniques like "bloom" or "additive blending". Are they relevant here? how I would implement pulsing glow with them?

Any links to relevant works very appreciated
Thanks!

P.S - I am very familiar with Android SDK; just started with OpenGL ES


texts: Best practice for organizing the physics of objects?

texts:
Apologies because this is a long post and I am inexperienced. I would really appreciate the input from some experienced developers.

These are my two goals for this project:

To learn the best method of managing the game loop and flow of the program so that it is easily understandable, clean, and reusable.
To learn about how to efficiently and cleanly handle the physics calculations of a game. I would like to learn the method that is implementable on a scale that can accommodate a lot of collisions.

The project will be written in using Javascript/HTML 5.

The way I was thinking about it is to include attach implement an physics object constructor that attaches a physics object to each class object that will have physics done to it.

For example:

var playerBullets = [];
playerBullets.push(Bullets()); //Bullets() is the constructor

//inside the Bullets() constructor I would have the following:
this.physics = Physics();  //where Physics() is the constructor for a physics obj

The physics object would be set up like the following:

{
  x: 0,
  y: 0,
  xVelocity: 0,
  yVelocity: 0,
  xAccel: 0,
  yAccel: 0,
  mass: 0,
  restitution: 0,
  angularVelocity: 0,
  linearDampening: 0,
}

Then from the gameLoop:

Function gameLoop() {
  ...
  update();
  draw();
}

Function update() {
  ...
  //code here to iterate through objects to update them individually
  handleCollisions();
  handlePhysics();
 }

Function handleCollisions() {
   ...
   //detect collisions between objects and mark which ones have collided with each other
}

Function handlePhysics() {
   ...
   //code to iterate through objects and update the velocities
   handleCollisions();
}

Questions

What might be some problems I would run into by doing it this way?
Should I include any methods in the physics object or should I handle all of my physics operations in a special function inside the gameloop?
Is it better to handle the physics together, or handle the physics of each object separately in its own update function?
What is the best practice way to handle physics in a game?

EDIT I learn better by seeing examples so it would be very helpful, and I'd really appreciate it, if I could see some accompanying pseudo-code.


texts: Why is quad rendered at the center (0,0) instead of top left when using orthographic projection

texts:
I have been trying to render a quad(containg a texture) using orthographic camera so that the quad can be rendered using the screen coordinates directly.

I started of by rendering just a triangle with a image. The triangle is rendered but it seems teh center of the screen is 0,0 but using the code below it should have been at top left of the screen.

Ortho camera matrix code:

// Set the camera position
        var cameraPosition = new Vector3(0.0f, 0.0f, 0.0f);
        var cameraTarget = new Vector3(0f, 0.0f, 1.0f); // Looking at the origin 0,0,0
        var cameraUp = new Vector3(0.0f, 1.0f, 0.0f); // Y+ is Up

        // Prepare matrices
        // Create the view matrix from our camera position, look target and up direction
        // direct X uses left hand co-ordinate system
        m_viewMatrix = Matrix.LookAtLH(cameraPosition, cameraTarget, cameraUp);

        // Initialize the world matrix
        m_worldMatrix = Matrix.Identity;
        var scalingMatrix = Matrix.Scaling(720, 576, 1);
        var translationMatrix = Matrix.Translation(new Vector3(0, 0, 0));
        var rotationMatrix = Matrix.RotationZ(0);
        m_worldMatrix = translationMatrix * scalingMatrix * rotationMatrix;

        m_worldMatrix = translationMatrix * scalingMatrix * rotationMatrix;
        var worlViewMatrix = Matrix.Multiply(m_worldMatrix, m_viewMatrix);
        m_projectionMatrix = Matrix.OrthoOffCenterLH(0, 720, 576, 0, 1f, 1000.0f);
        m_perObject.WorldViewProjection = Matrix.Multiply(worlViewMatrix, m_projectionMatrix);

Vertices code:

stream.WriteRange(new[]
            {
                new VertexPositionTexture(
                    new Vector4(720, 576, 0.5f, 1.0f), // position bottom-right
                    new Vector2(1024,576)
                ),
                new VertexPositionTexture(
                    new Vector4(0, 0, 0.5f, 1.0f), // position top-left
                    new Vector2(0, 0)
                ),
                new VertexPositionTexture(
                    new Vector4(720, 0, 0.5f, 1.0f), // position top-right
                    new Vector2(1024, 0)
                ),
            });

Shader code:

float4x4 WorldViewProj;

struct VertexShaderInput
{
 float4 Position : SV_Position;
 float2 TextureUV : TEXCOORD0;
};

VertexShaderOutput VSMain(VertexShaderInput input)
{
 VertexShaderOutput output = (VertexShaderOutput)0;
 //output.Position = input.Position;
 output.Position = mul(input.Position, WorldViewProj);
 output.TextureUV = input.TextureUV;
 return output;
}

Screenshot of image rendered:

Now I can't seem to figure out why the center of the screen is 0,0 and not top left ? Also as a part of this if I do not use a scaling matrix the triangle is not rendered.

The main reason behind the above attempt is to draw a quad/triangle using screen co-ordinates so that i can place exactly where i want without the need to calculate the vertices all the time when ever i wish to place my quad/triangle.

This issue has left me baffled for last couple days. Any help or suggestion would be really helpful.

Note:
I am using Directx11 with sharpdx and still learning directx learner.


texts: Filtering (e.g. Gauss blur) on seamless textures but without border artifacts?

texts: I am looking for a way to apply (Photoshop, Gimp etc.) filters to seamless textures without the usual border artifacts. The kernel of the Photoshop Gauss filter for example does not wrap around the image (which in non-seamless cases is surely also not wanted) but shows severe artifacts at the borders. Is there any way around this?


texts:
I'm writing a shooter (like 1942, classic 2D graphics) and I'd like to use a component based approch. So far I thought about the following design:

Each game element (airship, projectile, powerup, enemy) is an Entity
Each Entity is a set of components which can added or removed at run-time. Examples are Position, Sprite, Health, IA, Damage, BoundingBox etc.

The idea is that Airship, Projectile, Enemy, Powerup are NOT game classes. An entity is only defined by the components it owns (and that can change during time).
So the player Airship starts with  Sprite, Position, Health and Input components.
A powerup has the Sprite, Position, BoundingBox.
And so on.

The main loop manages the game "physics", i.e. how the components interact each other:

foreach(entity (let it be entity1) with a Damage component)
    foreach(entity (let it be entity2) with a Health component)
    if(the entity1.BoundingBox collides with entity2.BoundingBox)
    {
        entity2.Health.decrease(entity1.Damage.amount());
    }

foreach(entity with a IA component)
    entity.IA.update();

foreach(entity with a Sprite component)
    draw(entity.Sprite.surface());

...

Components are hardcoded in the main C++ application. Entities can be defined in an XML file (the IA part in a lua or python file).

The main loop doesn't care a lot about entities: it only manages components. The software design should allow to:

Given a component, get the entity it belongs to
Given an entity, get the component of type "type"
For all entities, do something
For all entity's component, do something (e.g: serialize)

I was thinking about the following:

class Entity;
class Component { Entity* entity; ... virtual void serialize(filestream, op) = 0; ...}
class Sprite : public Component {...};
class Position : public Component {...};
class IA : public Component {... virtual void update() = 0; };

// I don't remember exactly the boost::fusion map syntax right now, sorry.
class Entity
{
   int id; // entity id
   boost::fusion::map< pair<Sprite, Sprite*>, pair<Position, Position*> > components;
   template <class C> bool has_component() { return components.at<C>() != 0; }
   template <class C> C* get_component() { return components.at<C>(); }
   template <class C> void add_component(C* c) { components.at<C>() = c; }
   template <class C> void remove_component(C* c) { components.at<C>() = 0; }
   void serialize(filestream, op) { /* Serialize all componets*/ }
...
};

std::list<Entity*> entity_list;

With this design I can get #1, #2, #3 (thanks to boost::fusion::map algorithms) and #4. Also everything is O(1) (ok, not exactly, but it's still very fast).

There is also a more "common" approch:

class Entity;
class Component { Entity* entity; ... virtual void serialize(filestream, op) = 0; ...}
class Sprite : public Component { static const int type_id = 0; };
class Position : public Component { static const int type_id = 1; };

class Entity
{
   int id; // entity id
   std::vector<Component*> components;
   bool has_component() { return components[i] != 0; }
   template <class C> C* get_component() { return dynamic_cast<C> components[C::id](); } // It's actually quite safe
...
};

Another approch is to get rid of the Entity class: each Component type lives in its own list. So there is a Sprite list, a Health list, a Damage list etc. I know they belong to the same logic entity because of the entity id. This is simpler, but slower: the IA components needs access basically to all other entity's components and that would require searching each other component's list at each step.

Which approch do you think is better? is boost::fusion map suited to be used in that way?


texts: Unity. C# help with arrays and letter placement

texts:
Think about this like "Guess the word" game: W _ _ _ _

I have a word that i separate in index - letters like this:

public static string[] splitWord;
word = "WORLD";

string[] splitWord = new string[word.Length];
for(int i = 0; i < splitWord.Length; i++)
    {
        splitWord[i] = word[i].ToString();
    }

This way when i print the splitWord variable

for(int i = 0; i < splitWord.Length;i++)
    {
         print(splitWord[i] + " " + i);
    }

i get this;

 W 0
 o 1
 r 2
 l 3
 d 4

In my Ui i have letters, when i choose one i check if the letter is in the word, this part is done.

public static void SetWord (string letter)
{
    if (GameController.word.Contains (letter)) {
        word.text += letter; ------>setting the word NOT in order
    } else {
        Debug.Log("Letter is not in the word");
    }

}

What i´m having problems with is to place the letter in the correct place of the word.
What i want to do is, based on this:

 W 0
 o 1
 r 2
 l 3
 d 4

Is to check "ok this letter is on the word, what index in the Word does this letter has?, place the letter in the correct place". That is the idea. but because im pretty new to code in general i m having problems with this.
The idea is to convert that array of stings into a hole string and use Insert() to place the letter in the correct spot.

Any ideas?

Thanks in advance for the help.


texts: Isometric 2D game without tiles. Is there a solution?

texts:
Is it possible to create an isometric view of the game without the use of tiles?

I've already searched in stackoverflow.com and gamedev.stackexchange.com, but I could not find a simple solution for isometric maps using Corona SDK.

My goal is to create something like this picture:
KRu.jpg

Do you think the game is made with tiles or not? Is using tiles the only solution for this kind of game?

Problems that I do not understand:
– Overlapping objects that are farther
– Change overlapping sprite when it moves around the map. When an object moves, some of its facilities will be closed, others are not. What is the logic of such a task?
– The logic of the movement of objects along a path with no tiles

I do not want to reinvent itself what must have already decided.

If the tiles can not be avoided, I ask once again to leave links to materials that will solve the problem of isometry in the Corona SDK.


texts:
I don't seem to be able to find an answer to this one. I have a map of hex tiles. I wish to implement scrolling.

Code at present:

drawTilemap = function() {
    actualX = Math.floor(viewportX / hexWidth);
    actualY = Math.floor(viewportY / hexHeight);
    offsetX = -(viewportX - (actualX * hexWidth));
    offsetY = -(viewportY - (actualY * hexHeight));

    for(i = 0; i < (10); i++)
    {
        for(j = 0; j < 10; j++)
        {
            if(i % 2 == 0) {
                x = (hexOffsetX * i) + offsetX;
                y = j * sourceHeight;
            } else {
                x = (hexOffsetX * i) + offsetX;
                y = hexOffsetY + (j * sourceHeight);
            }

            var tileselected = mapone[actualX + i][j];

            drawTile(x, y, tileselected);
        }
    }
}

The code I've written so far only handles X movement. It doesn't yet work the way it should do. If you look at my example on jsfiddle.net below you will see that when moving to the right, when you get to the next hex tile along, there is a problem with the X position and calculations that have taken place.

It seems it is a simple bit of maths that is missing. Unfortunately I've been unable to find an example that includes scrolling yet.

http://jsfiddle.net/hd87E/1/

Make sure there is no horizontal scroll bar then trying moving right using the -> right arrow on the keyboard. You will see the problem as you reach the end of the first tile.

Apologies for the horrid code, I'm learning!

Cheers


texts: Does transparency work with SSS in Unity's HDRP Lit shader?

texts:
I am using Unity's HDRP Lit shader in Shader Graph (all are version 4.8.0-preview) on Unity 2018.3.0b12.

I am trying to use both transparency and subsurface scattering on the material. However, it appears that the visual appearance loses SSS when transparency is introduced.

Example: The cube on the left has transparency enabled, and has no visible SSS. The cube on the right has the same SSS settings as the left cube, however the right cube has no transparency enabled.

I need transparency to fade in the cube depending on its position, like this:

And here is my master node:

If anyone has an alternative solution that sidesteps this potential limitation, I am all ears. Cheers!


texts:
I'm new to LibGDX, my goal is to render a 3D pie chart, my idea is to draw a Cylinder and somehow define slices that can have different material and transformations.

I can render a cylinder already but I'm not sure how to do the slicing part.


texts: Game Make Studio 2 - Grid snap x, snap y

texts:
I'm following a GM tutorial that was given in 1.4 but I'm using 2, and there's a feature that I can't seem to get working. The developer is basically changing two settings (Snap X and Snap Y) which are located right on the top bar when editing a room. Changing them from 32 to 16 allows him to have a lot more precision when placing objects using grid snapping.

I can't make this work in GMS2. I have found the grid settings under Preferences and can turn grid snapping on and off from there. But the 'Grid Horizontal Spacing' and 'Grid Vertical Spacing' settings don't seem to do anything, I had assumed they would change the snap settings.

Am I doing something wrong or has this functionality changed?


texts:
the code below is the bullet class for my shooter game in pygame.  as you can see if you run the full game (https://github.com/hailfire006/economy_game/blob/master/shooter_game.py) the code works great to fire bullets at the cursor as long as the player isn't moving.  However, I recently added scrolling, where I change a global offsetx and offsety every time the player gets close to an edge.  These offsets are then used to draw each object in their respective draw functions.

unfortunately, my bullet physics in the bullet's init function no longer work as soon as the player scrolls and the offsets are added.  Why are the offsets messing up my math and how can I change the code to get the bullets to fire in the right direction?

class Bullet:
    def __init__(self,mouse,player):
        self.exists = True
        centerx = (player.x + player.width/2)
        centery = (player.y + player.height/2)
        self.x = centerx
        self.y = centery
        self.launch_point = (self.x,self.y)
        self.width = 20
        self.height = 20
        self.name = "bullet"
        self.speed = 5
        self.rect = None
        self.mouse = mouse
        self.dx,self.dy = self.mouse

        distance = [self.dx - self.x, self.dy - self.y]
        norm = math.sqrt(distance[0] ** 2 + distance[1] ** 2)
        direction = [distance[0] / norm, distance[1] / norm]
        self.bullet_vector = [direction[0] * self.speed, direction[1] * self.speed]

    def move(self):
        self.x += self.bullet_vector[0]
        self.y += self.bullet_vector[1]

    def draw(self):
        make_bullet_trail(self,self.launch_point)
        self.rect = pygame.Rect((self.x + offsetx,self.y + offsety),(self.width,self.height))
        pygame.draw.rect(screen,(255,0,40),self.rect)


texts: Crash when creating RenderTargetViews for Cubemap

texts:
I want to create a cubemap and I want to render to it and later sample from it for reflections.
However, It crashes when I try to create the faces for the cubemap.
Here is my code:
RenderTargetCube::RenderTargetCube(ID3D11Device* device, int resolution, DXGI_FORMAT format) {

    D3D11_TEXTURE2D_DESC desc = {};
    desc.Width = resolution;
    desc.Height = resolution;
    desc.MipLevels = 1;
    desc.ArraySize = 6;
    desc.Format = format;
    desc.SampleDesc.Count = 1;
    desc.SampleDesc.Quality = 0;
    desc.Usage = D3D11_USAGE_DEFAULT;
    desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
    desc.CPUAccessFlags = 0;
    desc.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE;

    HRESULT res = device->CreateTexture2D(&desc, NULL, &Texture);
    throwIfFailed(res);

    D3D11_RENDER_TARGET_VIEW_DESC viewDesc = {};
    viewDesc.Format = desc.Format;
    viewDesc.Texture2DArray.ArraySize = 6;
    viewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;
    for (int i = 0; i < 6; i++) {
        viewDesc.Texture2DArray.FirstArraySlice = D3D11CalcSubresource(0, i, 1);
        res = device->CreateRenderTargetView(Texture.Get(), &viewDesc, RenderTargetView[i].GetAddressOf()); // crash here
        throwIfFailed(res);

    }

and here is the message I receive:

D3D11 ERROR: ID3D11Device::CreateRenderTargetView: The Dimensions of the View are invalid due to at least one of the following conditions. MipSlice (value = 0) must be between 0 and MipLevels-1 of the Texture Resource, 0, inclusively. FirstArraySlice (value = 1) must be between 0 and ArraySize-1 of the Texture Resource, 5, inclusively. With the current FirstArraySlice, ArraySize (value = 6) must be between 1 and 5, inclusively, or -1 to default to all slices from FirstArraySlice, in order that the View fit on the Texture. [ STATE_CREATION ERROR #137: CREATERENDERTARGETVIEW_INVALIDDIMENSIONS]

I dont quite understand the error message, especially the last part about ArraySize, why does it want it to be between 1 and 5 and not 0 to 5?


texts: Unity% Mechanim animation does not move straight

texts:
I've imported a mixamo animation into unity5.
I've also set up a trigger to move the character forward, the wierd thing is that when the animation finishes his rotation is not perfectly straight.
So the next time he moves forward his rotation is a bit to the left so eventually he ends up running in a circle.

Is there a setting to assure that my character will only move forward when he during moving forward, or should I programatically change these parameters to assure that?


texts:
I'm creating an FPS game. I'm writing my own game engine. So far all the backend stuff is going great. I'd like to support md2 as the native file format for 3D Objects, but I also want to use skeletal meshes. Does anyone know if the md2 file format supports skeletal meshes?

In-case you need to know, I'm going to use blender as my Mesh creation tool and C++ as my programming language...

Thanks

For got to mention, the engine is based on OpenGL...

Alright, for anyone who is reading this, I just found the Doom 3 md5 specifications (http://tfc.duke.free.fr/coding/md5-specs-en.html). It gives you some help on writing a parser (see bottom of link), but the example doesn't support lighting and texture mapping (the second set of example code allows for animation). Thanks @Neverender for answering my question...


texts:
This is very simple, but I have spent nearly 6 months messing with this and it is always messed up.

This is a tile platformer, everything is "normal", x and y correspond to tile. Tiles are 32 x 32 pixels.

// Get all tile numbers, top left, top right, bottom left, bottom right
int X = 63; // and in this, say the player is moving right
int Y = 50;
int Width = 33; // This is the problem, if it is < 32, the collisions are all over the place, in the open, where there shouldn't be.
int Height = 50;

int tile_x = floor( (double) X/32);
int tile_y = floor( (double) Y/32);
int tile_x2 = floor( (double) (X + Width)/ 32);
int tile_y2 = floor( (double) (Y + Height)/ 32);
bool open = true;

// This is meant to catch cases where width < 32
if (tile_x == tile_x2) {
    if (IsOpenPt(tile_x, tile_y)) { return true; }
}

// loop through tiles
for (int y = tile_y; y < tile_y2; y++) {

    for (int x = tile_x; x < tile_x2; x++) {

        // this spot is not open
        if (!IsOpenPt(x,y)) { open = false; }

    }
}

return open;

This works if the width is greater than 32, but if it anything less, everything becomes random open point/ not.

See anything wrong with my formula? I have exhausted searches, nothing. Once again I emphasize, the entire project, I have been trying to get this part to work. I have literally a 100 page notebook of attempts at visualizing and grids to put it on paper.