texts: what options do I have for rendering "large" terrains?

texts:
I am trying to design a game with some interesting features but one question I have is regarding terrain. I want a terrain that will make for a very large game world, and I want to be able to have such features as "roads" and "rivers".

What options do I have in terms of terrain and what will give me the best result in terms of best looking, obviously I want to also keep the game playable with a reasonable frame-rate, but this game will specifically target higher end hardware.


texts: Unity's Box Collider isn't preventing an object from falling through the floor

texts:
I'm working on a little "Tower of Hanoi" AR game in Unity using Vuforia, where the game is projected onto an image target.
Now I wanted to make the rings "fall" into place, so I added an invisible ground floor plane, with a box collider, and added mesh collider and rigid body to my ring.

Here are the settings:

Now there are quite a few questions about objects falling through the floor around and I tried many of the different suggestions (thickness of box collider, continuous instead of discrete collision detection,...) but none of them solved my issue.

Since this is my second little Unity project, I guess the issue is obvious (maybe my ring is too small (few centimeters) or something, but I'm not sure.

The problem is also, that I can't really see what is happening during runtime, since the camera has to find the image target first, after that the ring (currently testing only the bottom one) is gone and I just see the y-value of it's position changing.

Any help is much appreciated!


texts:
I'm trying to apply a DuDv Map effect (distortions) on my water.

My texture is 512x512 in size.

I'm using the following code:

(Vertex Shader)

out vec2 texCoord0;

void main()...
{

texCoord0 = vec2(position.x / 2.0 + 0.5, position.y / 2.0 + 0.5) * 6.0;
}

(Fragment Shader)

in vec2 texCoord0;

void main()
{
    ...

        vec3 ndc = (clipSpace.xyz / clipSpace.w)/ 2.0 + 0.5;

    vec2 reflectTexCoords = vec2(ndc.x, -ndc.y);
    vec2 refractTexCoords = vec2(ndc.x, ndc.y);

    vec2 distorsion1 = (texture(dudvMap, vec2(texCoord0.x, texCoord0.y)).rg * 2.0 - 1.0) * waveStrength; // waveStrength = 0.02;

    refractTexCoords += distorsion1;

    reflectTexCoords += distorsion1;

    vec4 reflectColor = texture(reflectionTexture, reflectTexCoords);
    vec4 refractionColor = texture(refractionTexture, refractTexCoords);

      outColor = mix(reflectColor, refractionColor, 0.5);
}

As you can see when I add my distortion to my reflection and refraction texture coordinates, it seems that something is wrong and can't figure what, because I get this effect:

Do any of you have any idea how can I fix this? Thanks for your time!


texts:
We are three people who are going to make a simple game in Java as a school project (University, first year). The game has to be object oriented. We don't have much time, 10-20 hours tops. None of us has any experience in game development, but we all have fair skills in Java.

We can choose exactly what kind of game, and that is where the problem lies. How high should we aim? There is a competition involved, so we do want to make the best game in the time we have. Is a 3d game unrealistic? Should we use any game-engines/libraries? What kind of functionality should we avoid?


texts: LibGDX, BitmapFont strange position behavior

texts:
I'm using a Stage of LibGDX to draw a text, in my case the FPS. But after resizing, the position of the text does not behave properly.

As you can see in the attached gif:

The resizing function does work correctly. Also here is my code of the UI-renderer:

GameScreen screen;
BitmapFont font;

FreeTypeFontGenerator generator;
FreeTypeFontGenerator.FreeTypeFontParameter parameter;

private Texture map;

public UIStage(GameScreen screen) {
    this.screen = screen;
    generator = new FreeTypeFontGenerator(Gdx.files.internal("font/acknowtt.ttf"));
    parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
    parameter.size = 24;
    parameter.borderWidth = 2;
    parameter.borderColor = new Color(0, 0, 0, 1F);
    parameter.borderStraight = true;
    font = generator.generateFont(parameter);
    this.map = new Texture(Gdx.files.internal("levels/map/" +
        screen.map.getLevel().getName() + ".png"));
    generator.dispose();
}

@Override
public void draw() {
    this.getBatch().setColor(1F, 1F, 1F, 1F);

    this.getBatch().begin();
    this.font.draw(
        this.getBatch(),
        "FPS: " + GameScreen.fpsLogger.getFPS(),
        10,
        this.getViewport().getScreenHeight() - 44);
    this.getBatch().end();
}

How can I make my text behave properly?


texts: How can I put Google Ads in a flash game?

texts:
What I want to do is put Google Ads in my flash game.

The first question is how can I do that?

The second question is the best place to put it; while loading, after finishing the game?


texts: how to avoid circular references between objects and map

texts:
I've been working on a turn based tactics game on a grid.  I've been trying to figure out how to store and relate the grid and the objects on it.  Essentially, my question boils down to how to ask these two questions without violating the DRY(Don't Repeat Yourself) principle.

Given a object, how to get it's position? object.get_pos()
Given a cell, how to find out what object is in it?  grid.get_cell(cell)

One particular thing I was thinking is that it doesn't make sense to talk about a object independently of the grid it is on.  Therefore it seems like each object should have a reference to the grid.  But having a grid doesn't make sense unless it has cells that contain objects. Is this just a place where things are tightly coupled enough that this kind of circular reference is acceptable?


texts: Is Unreal engine or Unity better for high graphics low file size mobile games?

texts: My objective of learning game development is to make a 3d relatively high graphics mobile game but that should be in 150 mb. I don't know should I start with unity or unreal engine. I found that people say unreal engine is better for 3d games and unity is better for mobile game development. As I have no experience, can anyone suggest me an engine with some reasons?


texts: Simple Stupid Funnel Algorithm (SSFA) for 3D Navigation

texts:
tl;dr I need an algorithm similar to SSFA except for portals with 4 vertices (or n vertices if an algorithm like that exists).

I'm working on a game that requires pathfinding in 3 dimensions. By this I mean agents have full control over their position as opposed to many games where agents only control forward, back, left, right, and need to walk up stairs or ramps to go up and down.

To do this I made a "nav-mesh" using an octree that checks for collision at each region, and subdivides if there is a collision (until a certain cube size limit). So I now have a graph where each node is a cube with some size based on the octree. Using this I can run the A* algorithm for pathfinding on the graph.

Unfortunately, just moving towards the center of each node looks bad, and even moving towards the center of each connecting face of the node (the smaller of the two connected node's adjacent faces) looks bad.

In the past, I've used the SSFA for path simplification, but it only applies to situations with an edge as a portal, not a face. Is there an algorithm for this, or is there a way to make my pathing look better?

Ninja-edit: I'm already somewhat using steering behaviors, but since the center of nodes can vary wildly, based on the complexity of the octree, it still doesn't look nice.


texts: Choosing the correct normal for a collision

texts:
I have taken the task of building a basic impulse physics engine. Circle vs Circle collision resolution has been done and I moved onto Line vs Circle. I can detect a collision and know that the normal should be perpendicular to the line which can be calculated easily (2d physics engine). However it's the direction of the normal that I cannot work out.

From the image you can see there are 2 possible normals, one upwards (the correct one) and one downwards. How do I choose the correct normal?


texts: Calculating the geometry of a thick 3-way miter joint

texts:
Following a very helpful post on another forum I've found a simple algorithm that takes an array of 2D vectors and creates a triangle strip.
I've modified the source code for my purposes. I haven't tested it yet, but it should do the trick.

public static void PolyLineToTriangleStrip(Vector2[] pts, bool closed, float thickness, List<Vector2> vertices, List<int> indices)
    {
        var numPts = pts.Length;
        vertices.Clear();
        indices.Clear();
        for (int i = 0; i < numPts; ++i) {
            int a = ((i - 1) < 0) ? 0 : (i - 1);
            int b = i;
            int c = ((i + 1) >= numPts) ? numPts - 1 : (i + 1);
            int d = ((i + 2) >= numPts) ? numPts - 1 : (i + 2);
            var p0 = pts[a];
            var p1 = pts[b];
            var p2 = pts[c];
            var p3 = pts[d];

            if (p1 == p2)
                continue;

            // 1) define the line between the two points
            var line = (p2 - p1).normalized;

            // 2) find the normal vector of this line
            var normal = new Vector2(-line.y, line.x).normalized;

            // 3) find the tangent vector at both the end points:
            //      -if there are no segments before or after this one, use the line itself
            //      -otherwise, add the two normalized lines and average them by normalizing again
            var tangent1 = (p0 == p1) ? line : ((p1 - p0).normalized + line).normalized;
            var tangent2 = (p2 == p3) ? line : ((p3 - p2).normalized + line).normalized;

            // 4) find the miter line, which is the normal of the tangent
            var miter1 = new Vector2(-tangent1.y, tangent1.x);
            var miter2 = new Vector2(-tangent2.y, tangent2.x);

            // find length of miter by projecting the miter onto the normal,
            // take the length of the projection, invert it and multiply it by the thickness:
            //      length = thickness * ( 1 / |normal|.|miter| )
            float length1 = thickness / Vector2.Dot(normal, miter1);
            float length2 = thickness / Vector2.Dot(normal, miter2);

            if (i == 0 && !closed) {
                vertices.Add(p1 - length1 * miter1);
                vertices.Add(p1 + length1 * miter1);
            }

            vertices.Add(p2 - length2 * miter2);
            vertices.Add(p2 + length2 * miter2);

            if (closed && i == numPts-1) {
                indices.Add(i * 2);
                indices.Add(i * 2 + 1);
                indices.Add(0);
                indices.Add(i * 2);
                indices.Add(0);
                indices.Add(1);
            } else {
                indices.Add(i * 2);
                indices.Add(i * 2 + 1);
                indices.Add(i * 2 + 2);
                indices.Add(i * 2);
                indices.Add(i * 2 + 2);
                indices.Add(i * 2 + 3);
            }
        }
    }

Feeding it a sequence of vectors would produce something a bit like this:

However, I want to complicate matters by introducing another problem - 3 way joints (or rather n-way).

It must be possible to do this by building on the algorithm, but I'm not sure how I would modify the above algorithm to draw an n-way miter joint with perfect angle distribution like so:

The highlighted lines represent the source lines that would be fattened up by the algorithm.

I calculated and drew these in blender, unfortunately I'm at a bit of a loss to do it programmatically.

Obviously this cannot be achieved with simple line sequences, but that's beside the problem. All that' needed is a central point and n-ammount of points that represent the ends of outcropping lines, and then an algorithm to calculate the outer edges of the required shape.


texts:
I am implementing the shadow map in opengl with opentk everything works fine except I have a peter panning effect that I can't solve it by changing the face culling to front then render to the depth buffer.

the model is large so I scale it to  small value to render it to the shadow map.

what is the reason that may cause this problem?


texts: How to calculate shot angle and velocity to hit a moving target?

texts:
I am developing a 2D Android game and I am making an aiming algorithm for AI projectiles to hit enemies either following a path, or free moving. At the moment it just calculates where the target will be after a distance and fires a projectile to meet it at that distance. Of course this means varying the projectile speed to meet the target.

Does anyone have any tips for a simple-ish algorithm (optimal-ish) to calculate when the projectile needs to fire and where it needs to aim if it can only travel at a constant velocity? Say the projectile goes twice the speed of the target?

The only way I can think of involves searching and seems quite large.


texts: How to Calculate Velocity in a 2D space game

texts:
I am currently using

screenpos.X = (float)(screenpos.X + velocity * Math.Sin(r));
screenpos.Y = (float)(screenpos.Y - velocity * Math.Cos(r));

For my Movement with r being the Rotation in Radians. However, I want to know how I can calculate my velocity realistically based on values of Thrust and Mass.

Any Idea's?


texts: What is the easiest way to make an online high scores table?

texts:
I made an 2d Android game with using Libgdx library. This game like Flappy Bird. And every user have a highscore. I want to store this highscores respectively to an online database and return the rank of the user in the world ranking.

How to do this? In backend ,which architecture should I use? Is there a tutorial for this?


texts: glViewport() Win10 doesn't draw new parts

texts:
I've been steadily working through building a basic 2D tile framework in python.

I'm trying to use modern openGL so I have a simple shader and some vertex buffers and it's mostly doing what I want so far. I have a Scene with a method for centering the viewport on a Sprite:

def centre_viewport(self, x, y):
    x = -x+self.viewport_width//2
    y = y-self.viewport_height//2
    if x > 0:
        x = 0
    if y < 0:
        y = 0
    if x - self.viewport_width < -self.width:
        x = -self.width + self.viewport_width
    if y + self.viewport_height > self.height:
        y = self.height - self.viewport_height
    self.viewport_x = x
    self.viewport_y = y
    glViewport(x, y, self.viewport_width, self.viewport_height)

self.viewport_width and _height are set when a scene is added to the window, so they have the same dimensions as whatever window is created.

In my test game, the scene width and height are twice the window dimensions of 704x512. Everything works fine on my main mac development machine. On my work windows machine though, when the sprite moves and causes the scene to scroll, the previously hidden parts of the scene are not drawn:

My draw loop is very simple:

def _draw(self):
    glBindBuffer(GL_ARRAY_BUFFER, self.sprite_vertex_buffer)
    glVertexAttribPointer(self.vertices, 3, GL_FLOAT, GL_FALSE, 0, None)

    glBindBuffer(GL_ARRAY_BUFFER, self.sprite_texture_buffer)
    glVertexAttribPointer(self.tex_coords, 2, GL_FLOAT, GL_TRUE, 0, None)

    glDrawArrays(GL_TRIANGLES, 0, self.sprite_vertex_count)

    glBindBuffer(GL_ARRAY_BUFFER, self.tile_vertex_buffer)
    glVertexAttribPointer(self.vertices, 3, GL_FLOAT, GL_FALSE, 0, None)

    glBindBuffer(GL_ARRAY_BUFFER, self.tile_texture_buffer)
    glVertexAttribPointer(self.tex_coords, 2, GL_FLOAT, GL_TRUE, 0, None)

    glDrawArrays(GL_TRIANGLES, 0, self.tile_vertex_count)

and as mentioned, it works fine on my mac.

Is glViewport() the appropriate way to be doing this, and why isn't it working properly on windows?


texts: Alpha blending not rendering properly XNA 4.0

texts:
I'm trying to render a tree made out of 2 rectangles intersecting in the center at a 90degree angle. The texture has an alpha channel but which ever rectangle gets rendered second causes a weird problem with the transparency.

Here is my rendering code:

public override void render(GraphicsDevice gd, Camera camera)
{
    RasterizerState rs = new RasterizerState();
    rs.CullMode = CullMode.None;
    gd.RasterizerState = rs;
    gd.BlendState = BlendState.AlphaBlend;

    effect.CurrentTechnique = effect.Techniques["TexturedNoShading"];
    effect.Parameters["xWorld"].SetValue(Matrix.CreateTranslation(position));
    effect.Parameters["xView"].SetValue(camera.getViewMatrix());
    effect.Parameters["xProjection"].SetValue(camera.getProjectionMatrix());
    effect.Parameters["xTexture"].SetValue(m_texture);

    foreach (EffectPass pass in effect.CurrentTechnique.Passes)
    {
        pass.Apply();

        gd.Indices = m_indexBuffer;
        gd.SetVertexBuffer(m_vertexBuffer);
        gd.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, m_vertices.Length, 0, m_indices.Length / 3);
    }

    rs = new RasterizerState();
    rs.CullMode = CullMode.CullCounterClockwiseFace;
    gd.RasterizerState = rs;

    gd.BlendState = BlendState.Opaque;
}


texts: Are there any game engines in C# or Java that are cross-platform and support multitouch input?

texts:
I'm looking for game engines (particularly 2D) that can run/create games for Windows, Mac, and Linux, and support multitouch inputs and gestures. I'm able to find many that meet the first two criteria, but don't mention anything about multitouch.

I know that Qt is an existing non-game framework that supports multitouch and is cross-platform. Unfortunately it doesn't seem to be geared for hardware-accelerated games.


texts: Discover x,y coordinates given set arc distance and rotation

texts:
I have a turn-based car simulation.  My vehicles have a maximum speed they can travel in a round, as well as a maximum amount they can change their heading over the course of a round.  Say, 20 meters and 45 degrees.

Knowing the starting position of a car (x,y coordinates), and its starting heading (orientation), I want to find the end-of-round coordinates for the car turning its maximum amount and moving its maximum speed.  (And values in-between, as well!)

There has to be some simple math formula for this, but I haven't found it yet.  I also happen to be working in Unity.


texts:
I'm creating an html5 multiplayer game and am looking at how to create a websocket server.

I've been looking at various libraries and one thing I noticed is that each one will create a new thread for every client that connects. Now I'm fairly new to websockets, but I know that in the past when it came to game server design that a thread per connection was bad practice.

Is that true for websockets? Why is there a need to a new thread for every connection?


texts: Can't find out why aren't those collisions framerate independent

texts:
I'm making a 2D Platform game and I'm having trouble with my collision detection. It doesn't seems to be framerate independent even though I used deltatime there.

The problem is that at 60fps, a collision is sometimes detected too early whereas at 500fps there's no problem (so it really seems like this isn't framerate-independent but I don't know why).

Here's a video of the game running at 60fps
https://www.youtube.com/watch?v=P0hRJbw_gcw

And here's the code which is moving my character (I inspired myself about 2D Collision detection from the youtuber dermetfan):

/// Makes the entity jump
void Entity::jump()
{
    m_onGround = false;
    setVelocity(sf::Vector2f(getVelocity().x, -500));
}

/// What to do at each frame
void Entity::update(sf::Time dt)
{
    if (getVelocity().y > 800)
    {
        setVelocity(sf::Vector2f(getVelocity().x, 800));
    }
    else
    {
        setVelocity(sf::Vector2f(getVelocity().x, getVelocity().y - m_map->getGravity()*dt.asSeconds()));
    }

    checkCollisions(dt);
}

/// Collision functions
void Entity::checkCollisions(sf::Time dt)
{
    float oldX = getPosition().x;
    float oldY = getPosition().y;

    bool collX = false;
    bool collY = false;

    setPosition(getPosition().x + getVelocity().x*dt.asSeconds(), getPosition().y); // Setting the position on x

    m_collisionIncrement = (getSize().x < getMap().TILE_SIZE) ? getSize().x / 2 : getMap().TILE_SIZE / 2;

    if (getVelocity().x < 0)
        collX = collidesLeft(); // Using collision tests
    else if (getVelocity().x > 0)
        collX = collidesRight();

    if (collX){ // Testing if there was a collision
        setPosition(oldX, getPosition().y); // Correct position
        setVelocity(0, getVelocity().y*dt.asSeconds());
    }

    setPosition(getPosition().x, getPosition().y + getVelocity().y* dt.asSeconds()); // Setting the position on y

    m_collisionIncrement = (getSize().y < getMap().TILE_SIZE) ? getSize().y / 2 : getMap().TILE_SIZE / 2;

    if (getVelocity().y > 0)
    {
        collY = collidesBottom();
        m_onGround = collY;
    }
    else if (getVelocity().y < 0)
    {
        collY = collidesTop();
    }

    if (collY){ // Testing if there was a collision
        setPosition(getPosition().x, oldY);
        setVelocity(getVelocity().x*dt.asSeconds(), 0);
    }
}

bool Entity::collidesRight()
{
    for (float step = 0; step <= getSize().y; step += m_collisionIncrement)
    {
        if (getMap().isCollideable(getPosition().x + getSize().x, getPosition().y + step))
            return true;
    }
    return false;
}
bool Entity::collidesLeft()
{
    for (float step = 0; step <= getSize().y; step += m_collisionIncrement)
    {
        if (getMap().isCollideable(getPosition().x, getPosition().y + step))
            return true;
    }
    return false;
}
bool Entity::collidesTop()
{
    for (float step = 0; step < getSize().x; step += m_collisionIncrement)
    {
        if (getMap().isCollideable(getPosition().x + step, getPosition().y))
            return true;
    }

    return false;
}
bool Entity::collidesBottom()
{
    for (float step = 0; step < getSize().x; step += m_collisionIncrement)
    {
        if (getMap().isCollideable(getPosition().x + step, getPosition().y + getSize().y))
            return true;
    }
    return false;
}


texts:
Imagine a mobile phone game that is meant to be played in short sessions (5-10 mins). You can choose one out of many characters, and each character slightly alters the way the game plays.

Those characters are all locked and have to be unlocked by purchasing them with in-game money.

Should the player be able to choose which one to unlock?

Besides the obvious benefit of being able to choose who you want to unlock, the downside of this method is that players often end up having choice paralysis: With tons of characters to choose from, the player will just not bother reading every character's pros and cons and make a choice.

Should the player just be able to unlock a random character?

This is a more casual friendly method, as the player will just spend their in-game money without thinking because there's no other options. The downside of this is that paying for a character that doesn't suit your playstyle may feel bad.

Other solutions?

Maybe you have another solution on your mind? Note that some characters make the game more high risk/high reward, aimed for veteran players, while other characters just make the game easier to play.


texts: In gamemaker studio, how do I make text boxes?

texts: How to make text boxes in gamemaker studio?


texts:
So I decided on using OBB as the main collision detection in my 3D game but I started to wonder how OBB can be used to detect collisions if a player is in a building, an object you can walk into. Should the building object be broken up into dozens of OBBs or is there like an OBB to mesh check I can do. Or maybe there's some other better way of doing this.

Thanks for the help guys.


texts:
Well I've finnaly decided to start Android game dev, and my first project will be simple 2d canvas based game.
I have some experience in game developing with C# and XNA, and I'm a bit confused now.
Back in XNA we have Game class with Initialize, Update and Draw methods.

In Android I have to extend SurfaceView class, run draw and update in their own thread, and receive touch input from user.

I'm looking for a proper way to structure my code.

Some of my questions are :

How to deal with Activities (Should I run everything in one activity, or split whole game in 2 or more) ?
Where should I run game loop ?
Where to put Draw and Update methods ?
How to respond to touch events ?

Hope I came to the right place for answers...


texts:
I recently found these two gems:

http://powdertoy.co.uk/

http://dan-ball.jp/en/javagame/dust/

My question is: How are the physics with so many elements efficiently handled? Am I just severely underestimating modern computing power or is it possible to 'just' have a two-dimensional array, each cell of which describes what is placed at the according position and simulate each cell in every step. Or are there more complex things being done like summarising large areas of the same kind into a single data set and separating said set as needed?

Are there any open-source games like this I could look at?


texts: Player movement vs world movement in infinite runner game?

texts: Well I'm developing a Temple Run or Subway Surfer style infinite runner game. Which is more good? -Moving the player and make the Main Camera follow, or keep the player in one position and move the generated worlds? And the generated paths or worlds will have many animations in it. So which choice ouuld be good and why?


texts: Realtime fisheye to cubic or spherical panorama transformations with OpenGL or pixelshaders

texts:
I'd like to transform a sequence of circular fisheye-images to cubic or spherical panorama images to be used in a panorama-viewer based on OpenGL. The viewer-part is nemas problemas but the transform from fisheye to panorama is not my usual cup of tea. I was kind of expecting a google would solve this, but so far I have come up with next to nothing. What would the preferred method be? OpenGL or pixelshaders?

The image sequence is coming from a camera so it has to be done in realtime (or as fast as possible). I have used PanoTools for Photoshop before so I know a little about the process, but not much about the math behind. Any kind soul out there who could get me started? Any resources that could be useful? This can't be something new but I guess it's not that common either. Anyway it's a fun project ... =)

Update:

Found this awesome online shader-laboratory: https://www.shadertoy.com

Just too bad I can't add my own image-inputs here...


texts: What is "simulated human operator" cutscene camera movement called?

texts:
I have some questions related to the non-smooth camera movement in cutscenes of quite a few games which appears to try and simulate the nervousness of a human operator holding it. This is opposed to camera shake in general gameplay when some event takes place, i.e. explosions, though they do also occur in the cutscenes I'm talking about.

Examples of this effect are in many games, but the best example I have seen of what I am trying to describe is the opening cutscene (and many cutscenes) of Metal Gear Solid V: Ground Zeroes. Be sure to choose 60 FPS to make the effect clearer.

Is there a name for this "simulated human operator" effect, and do you know how this may have been achieved?

My guess would be that the camera is being offset in both axes by some kind of random deviation function, which is always slightly elastically moving towards the origin to stop it wandering off wildly. Perhaps Brownian motion?


texts: Calculate needed speed and object's position in Unity3d

texts:
So I'm trying to calculate an object's future position so my enemy can land to it safely. Idea is that using the future position I can calculate the angle and convert it to a direction vector and also using distance I can calculate the speed necessary to reach its target. I'm still kind of stuck with this idea.

Here is code which I'm using at the moment.

// Find the close platform to land
Transform _tmp = GetClosestPlatform(SpawnerNew.Platforms);
// Hard coded time, should be time which enemy should take to reach position
float _constNeededTime = 3f;
// As my game's speed always increasing every frame so I need to calculate it also how it's in future (GameManager.Instance.OverAllSpeedModifier is called 10x times / sec)
float _anticipatedLevelSpeed = GameManager.Instance.CurrentLevelSpeed + (GameManager.Instance.OverAllSpeedModifier * _constNeededTime * 10);
// trying to calculate the future postion of the platform
Vector3 _anticipatedLoc = _tmp.transform.position - new Vector3((_platformSpeed * _anticipatedLevelSpeed) + _constNeededTime, 0f, 0f);
// Calculate angle
float _angle = Mathf.Atan2(transform.position.y - _anticipatedLoc.y, transform.position.x - _anticipatedLoc.x) * 180 / Mathf.PI;
// Convert angle to vector direction
_nearestPlatformDir = new Vector3(Mathf.Cos(_angle * Mathf.PI / 180f), Mathf.Sin(_angle * Mathf.PI / 180f), 0);
// Trying to calculate speed needed to reach platform
_neededSpeed = Vector3.Distance(_anticipatedLoc, transform.position) / _constNeededTime;


texts: When doing network programming, is it always a good idea to optimize packet size as much as possible?

texts:
My question is relatively straightforward, but I haven't been able to find a concrete answer yet.

I'm programming a real-time networked multiplayer game, and I'm finding many examples of places where I could optimize packet size (i.e. minimize packet size) in small ways. As an example, one packet type stores player input (running, jumping, firing a weapon, etc.) along with an integer ID for that player. In practice, there will never be more than four players in a single game, meaning that ID could be represented with only two bits (four possible values) rather than the full 4-byte integer.

My question is, should I send only those two bits across in a network message or just send the full integer?

To clarify, I'm not referring to storing the ID in the main code itself. For that, I'm just using an int. I'm only curious about what I should be sending in a network packet. That's also just one example of a few I've run into.

The reason I ask is that this feels like a "don't prematurely optimize" scenario. Ordinarily, I know to not worry about optimization (within reason) until I've run profilers, but I'm less familiar with networking than "normal" programming. Is it better to optimize packet size as much as possible, or would that be overkill?

Thank you.


texts:
I have some code that uses GetSpectrumData from an AudioSource playing a song to create a level layout for the player to play. I want to add a functionality where the players can upload their own songs and play the levels created with the data from these songs. Unfortunately, when comparing different audio files, I encountered this:

As you can see, the amplitude differs drastically from clip to clip, subsequently creating levels that are trivial to complete or almost impossible. I want to find a way to determine this "loudness" so I can tone it down or amplify it with a multiplier after getting the data from the song. Also, is there a way to extract this data without playing the song?


texts: Is an array in Gamemaker infinitely expandable?

texts:
Arrays in Gamemaker Studio seems to not need to have its size be declared, and infact it doesn't seem to be possible to declare a finite array.

Instead, it seems it just keeps indexing for each declaration....at least as far as I can tell. Obviously, this is limited by memory, I would presume.

Question: So, can I have a loop that says something like array[i] = 0, while increasing i for each loop through?


texts: Libgdx, Gradle, android package naming problem

texts:
I'm upgrading my libgdx project to make use of all the new Gradle stuff.

However I changed the package namespace from the default generated by gdx-setup but that hasn't worked: when I debug to my phone Gradle is still trying to launch the default activity using the old namespace, hence it fails. But I can't figure out where Gradle is getting this from - I've searched the entire folder tree for the offending old namespace string and can't find it anywhere.

Details:

So gdx-setup generated the android project with namespace "com.wibble.mygame.android"

To match the namespace of my already-published game, I edited that to "com.wibble.mygame_a". I did this in the Android.manifest and the source code. Also noticed that the android build.gradle file has a line that generates the am start command so corrected that as well.

But when I debug with my connected Android device, it tries to launch the app with a command like:

am start -n "com.wibble.mygame.android/com.wibble.mygame_a.AndroidLauncher"
   -a android.intent.action.MAIN -c android.intent.category.LAUNCHER

the old namespace is still there but I can't figure out where its getting it from because I can't find any mention of 'mygame.android' anywhere in the whole project tree. Is there some cache of stuff hidden somewhere that I need to delete?


texts: How to decide to use OpenGL ES 1.0 or 2.0 for Android?

texts:
I started learning some Android development and one of the first things I thought I could make is a simple game. However, I'm faced with one difficult question right off the bat. Should I use OpenGL ES 1.0 or 2.0?

The game I have envisioned will be pretty simple graphically, utilizing 2D(tiled top-down type graphics) and fixed-camera isometric views. I've never used OpenGL in a desktop environment, so I'm oblivious on if shaders will be something I'll use, etc.

According to this page I should use OpenGL ES 2.0 generally for new development. My own phone however just recently(past year) got an update to get it to the required Android 2.2. (I don't even know if it has OpenGL ES 2.0 support)

So basically my question is, will I benefit from any of OpenGL ES 2.0's features over 1.0 and/or is it worth it in terms of compatibility?


texts:
I use dynamic vertex lighting on 2D sprites. On larger sprites the lighting is uglier than on smaller ones. This is because every sprite is just a quad of two triangles. Not enough vertices there for lighting on larger areas.

Is there a way to use more triangles on a sprite? Maybe even depending on how much screen space they cover?


texts:
I'd like to slowdown music playback, say at half speed. I'm currently using SDLmixer. I assume I'd need to tell SDL that I have a 44KHz music and want to stream it at 22KHz, but when I pass in 22Khz it seems it re-samples my audio and plays at normal speed.

Does anyone know how to do that, or any lib that supports it? I'm looking for free libs that allow me a commercial license (so no FMOD)

Thanks in advance.


texts: XNA- Add a content reference to a library?

texts:
Making a Game library with XNA, and I'd like to bundle it with some stock effects, if possible.  But I'm having no luck attaching a Content project to the Library, so is it possible to use the Content Processor to load effects this way?

If not, how should the bundling be done?  I would like the "user" (that is, someone building something with the library) not to have to deal with loading the effect, other than calling some library function with no arguments.


texts: Wait until continuing inside a function with a coroutine in Unity

texts:
I have a base class called Ability and then children classes for each ability like BasicMeleeStrike. I have a turn based game so the Do() method of each ability does it's logic sequentially. I'm trying to make coding a little nicer looking in each child ability class and I want to not have to yield out from in them but call base class functions that will do the operations over time but I want them to wait until they come back to the child class Do() function but what I have doesn't work. Is this possible?

class Ability{
   public virtual IEnumerator Do(Actor target){}
   protected IEnumerator JumpToTarget(Actor target){
      yield return StartCoroutine(_JumpToTarget(target);
   }
   private IEnumerator _JumpToTarget(Actor target){
      // inside here I tween to a location so it's yielding return null until it's done
   }
}

class BasicMeleeAttack : Ability{
   public override IEnumerator Do(Actor target){
      JumpToTarget(target);
      anim.Play("attack");
   }
}

No jumping happens but the attack animation plays. When I put a breakpoint on anim.Play() it's hit right away. Is there a way to make it stay inside JumpToTarget(target) until it's finished without having to do a yield inside BasicMeleeAttack's Do() function? I just think it's much friendlier to not have to code that for all my actions.


texts: Unity Editor - Adding Object Fields on button click

texts: So I am trying to make a button that will spawn an object field and a float field when clicked. Each object field being unique, so I can add gameobjects to it. I can’t think of a way to do this. This is purely Editor Scripting. Also, if there is an option to delete a row (the object field and the FloatField) that would be amazing


texts:
Please, help me with my problem.
The character is rendering incorrectly.
R symbol looks like N. Also, the symbol ! is not drawn. But this problem was found only on Xiaomi Mi A1. On other devices, such a problem is not detected.

Font generates like so:

public enum Font {

    FONT_REGULAR (Res.FONT_REGULAR_PATH),
    FONT_LIGHT (Res.FONT_LIGHT_PATH),
    RUSSO_ONE_REGULAR (Res.RUSSO_ONE_REGULAR),
    ;

    BitmapFont font;
    String path;

    Font (String path) {
        this.path = path;
    }

    public BitmapFont get (float size) {
        final String FONT_CHARACTERS = "абвгдеёжзийклмнопрстуфхцчшщъыьэюяєїіАБВГДЕЁЖЗИЙКЛМ" +
                "НОПРСТУФХЦЧШЩЪЫЬЭЮЯЄЇІáabcdeéfghiíjklmnoópqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123" +
                "456789][_!$%#@|\\/?-+=()*&.:;,{}\"´`'<>°©™";
        FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal(path));
        FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
        parameter.size = (int) size;
        if (size < 1) parameter.size = 1;
        parameter.characters = FONT_CHARACTERS;
        BitmapFont font = generator.generateFont(parameter);
        font.setColor(Color.WHITE);
        generator.dispose();
        return font;
    }

}

I use this font.

How can I fix it?


texts: Why some audio files are not working in Unity?

texts:
I am making a 2D game in which I wanted to attach audio file to a button. I was able to do this successfully. But later I felt like changing that sound. So I simply replaced it with another audio file. Then it stopped working! When I again attached the first audio file instead of second one, it worked again.

My setup is as follows: The file format is wav. I created an empty gameobject and attached an Audio Source component to it. Assigned an audio clip to it. Unchecked "Play on Awake". Went to the OnClick() section of the UI Button. Clicked the plus sign to add an item to the list. Assigned the Audio Source object to the object field. Chose AudioSource.Play in the dropdown.

I wanted to know why is my second audio file of the same format not working!


texts: What file types should I exclude from my game's source control repository?

texts:
I have started working on a personal project using Unity with a friend and we've set up our own source control system.

I am aware of the fact that there are many types of files, namely those that are generated locally when you build (for example, Visual Studio files) and those that are specific to your particular machine that should not be added to source control, but I'm not exactly sure what these file types are.

I don't want to exclude any generated files I should be including, such as .meta files.

Would someone be able to list all, or at least all of the common file types that should not be added to version control, specifically for a Unity project?


texts: Sorting a vector using array version of quick sort

texts:
I'm coding  a simple rendering engine using OpengGL and I wrote a class that manages a particle system. The class creates the particles and pushes them into a vector to be used by a renderer to draw them on screen. I need to order the particles from the farthest to the nearest to the camera (in order to solve problems with alpha blending and depth, having disabled depth testing for transparency), so I tried with the following code:

void ParticleRenderer::render()
{
    // prepare renderer
    .....
    // update particle state (position,ecc..) and remove it if necessary
    // update returns a bool indicating if particle is still alive
    while (it != mParticles.end())
    {
        if (!(*it)->update())
        {
            delete *it;
            it = mParticles.erase(it);
            if (it == mParticles.end())
                break;
            else
                continue;
        }
        it++;
    }
    if (mParticles.size() > 0)
        sortParticles(&mParticles[0], 0, mParticles.size() - 1);
    for (Particle *particle : mParticles)
    {
        .....
        // render particle
        .....
        std::cout << getCameraDistance(particle) << std::endl;
    }
    std::cout << "*************************************" << std::endl;
    mShader.unuse();
    glDisable(GL_BLEND);
}

void ParticleRenderer::sortParticles(Particle **particles, int low, int high)
{
    if (low >= high)
        return;
    Particle *temp = particles[low];
    while (true)
    {
        while (compareParticles(temp, particles[high]) >= 0 && low < high)
            high--;
        if (low == high)
            break;
        else
            particles[low++] = particles[high];
        while (compareParticles(temp, particles[low]) < 0 && low < high)
            low++;
        if (low == high)
            break;
        else
            particles[high--] = particles[low];
    }
    particles[high] = temp;
    int middle = high;
    sortParticles(particles, low, middle - 1);
    sortParticles(particles, middle + 1, high);
}

double ParticleRenderer::compareParticles(Particle *particle1, Particle *particle2)
{
    return  getCameraDistance(particle1) - getCameraDistance(particle2);
}

double ParticleRenderer::getCameraDistance(Particle *particle)
{
    glm::vec3 distance = mCamera.getPosition() - particle->getPosition();
    return glm::length(distance);
}

but what I get on the console are all unsorted particles (the cout statement) and of course I have problems when the particles are rendered on screen.
Am I missing something?

I know I could use std::sort and the STL algorithms, but since I'm learning I would like to know what I am doing wrong.


texts: Why does my gameobject fly of into the air when the screen is touched?

texts:
I am encountering a peculiar problem when updating a piece of code that translates my gameobject left and right based on mobile touch input.

To provide context, the platform upon which the gameobject, which is a sphere in my case, translates, is this:

The platform is 10 units wide, with the sphere in the center.

In its original form, the code looks like this:

void FixedUpdate () {
    if(Input.touchCount == 1) {
        float touchXComponent = Input.GetTouch(0).deltaPosition.x;
        transform.Translate(Vector3.right * Time.smoothDeltaTime * touchXComponent * 0.5f);
    }
}

It provides the desired left and right movement, but it has a tendency to allow the ball to leave the platform, and then start moving up and down in the air with each further touch.

To combat that, I tried editing the code as follows:

void FixedUpdate(){
    if (Input.touchCount == 1){
        float touchXComponent = Input.GetTouch(0).deltaPosition.x;
        transform.Translate((Vector3.right * Time.smoothDeltaTime * touchXComponent * 0.5f).x, transform.position.y, transform.position.z);
    }
}

This, however, causes the ball to fly of the screen the second it is touched, leaving me with this error in the console:

Assertion failed: Invalid worldAABB. Object is too large or too far away from the origin.

I would have thought that the update I made to the code would keep the ball stationary on the y and z-axes, while allowing it to translate freely on the x-axis. Why is that not the case?

Thank you.


texts: How to connect to a socket.io server from a Cocos2d-x game?

texts:
The question can also be asked more specifically as; How do I connect to a socket.io server with C++ from a mobile game?

I am aware of Boost (and Socket.io C++ client libraries using Boost) but compiling them for iOS and Android is beyond me. So what do you guys recommend?


texts: beginContact triggered more than once on some objects

texts:
Short version: It looks like beginContact is detecting continuous collisions. I'd like to avoid that.

Long version : I use Box2Dweb to write a 2D platformer. It's my first game using this lib, and, to be honest, my first game ever.

I've read almost everything on collision detection (with contactListener), but I must have understood something wrong.

When the game starts, my player is spawned a little above the ground. It falls due to gravity, and an event is triggered once when it touches the ground (and my player.canJump property is set to true).

I also added "Bricks" (aka platforms) on the Stage. They are "simple" Polygon shapes (rectangle) attached to staticBodies.

Whenever my player touches a brick, the beginContact event is fired many times, and contact.IsTouching() is true for each instance.

edit: endContact seems to be fired too, the same amount of times.

Here is the (relevant part of the) code that I'm using to instantiate Bricks (it's inside a class "Brick") :

var bodyDef = new box2d.b2BodyDef()
bodyDef.type = box2d.b2Body.b2_staticBody;
bodyDef.userData = this;
bodyDef.position.x = x / SCALE;
bodyDef.position.y = y / SCALE;
bodyDef.fixedRotation = true;
this.view.body = world.CreateBody(bodyDef);

var fixDef = new box2d.b2FixtureDef();
fixDef.density = 1;
fixDef.isSensor = false;
fixDef.friction = 0.5;
fixDef.restitution = 0.2;
fixDef.shape = new box2d.b2PolygonShape();
fixDef.shape.SetAsBox((this.width/2) / SCALE , (this.height/2) / SCALE);
this.view.body.CreateFixture(fixDef);

In my init function (called only one), I'm setting up some listeners :

var b2Listener = Box2D.Dynamics.b2ContactListener;
var listener = new b2Listener;

listener.BeginContact = function(contact) {
    var userDataA = contact.GetFixtureA().GetUserData() || contact.GetFixtureA().GetBody().GetUserData();
    var userDataB = contact.GetFixtureB().GetUserData() || contact.GetFixtureB().GetBody().GetUserData();
    console.log('beginContact fired!');
}

If I jump on a platform, the event is triggered multiple times (something like 30). If I fall back on the ground, it's triggered only once (which is what I want).

(If you need to see what's happening, please have a look at the console there : http://www.enpause.com/plates-formes/ )

Could you please correct my mistake ? Thank you very much!


texts: Update function in html5 canvas game isn't working properly

texts:
Jsfiddle :  http://jsfiddle.net/seekpunk/6eeKH/15/

the code :

if (this.collection.length > 0) {
    if (((this.collection[0].blockX + this.collection[0].blockW) >= cw)
       || (this.collection[0].blockX <= 0)) {
        this.collection[0].blockSpeed *= -1;
    }
    this.collection[0].blockX += this.collection[0].blockSpeed;
}

the first block from top is drawn twin and i can't figure out why i guess the  problem is in drawing the levels can someone please help me figure out what i did wrong in my code


texts: In a 2D game with an isometric camera (like Bastion) do I need to create a new animation for every angle the player is facing?

texts: For different actions like jumping, attacking, moving etc,  do I need to make new animations for every angle I am doing the action? Or is there a way to somehow run around that requirement?


texts: How can I repeat / scroll a tile which is part of an texture atlas?

texts:
I would like to scroll a tile which is part of a texture atlas like it can be done with a single quad and texture wrap mode set to repeat.

Can this be done? I hope it's clear what I would like to achieve.

Here is my shader code which I use to sample tiles from my texture atlas, but I can't figure out how to do the wrapping so that one tile repeats itself over time.

uniform float time
void main() {
  float texId = textureId/32.0;
  vec2 tileOffset = vec2(fract(texId)*32.0,floor(texId));
  vec2 offset = invTileCount * tileOffset;
  vec2 texCord = fract(vUv) * invAtlasSize + offset;
  vec4 texelColor = texture2D( uTex, texCord );
}


texts:
I'm really new at XNA. I've been following some tutorials at gameprogrammingadventures.org but when it comes to conversations I don't really like how the author does it so I've been trying to understand how to create a rectangle over the game and writing text inside it.
This is done very poorly but I just wanted to understand how to do the basics first and perfect it later. This is what I have so far:

public void CheckConversation(GameTime gameTime)
    {
        if(Xin.CheckKeyReleased(Keys.Space) || Xin.CheckKeyReleased(Keys.Enter))
        {
            foreach (string s in map.Characters.Keys)
            {
                ICharacter c = CharacterManager.Instance.GetCharacter(s);
                float distance = Vector2.Distance(player.Sprite.Center, c.Sprite.Center);

                if (Math.Abs(distance) < 72f)
                {
                    DialogueBox dialogue = new DialogueBox(gameRef, "Text here");
                    dialogue.Draw();
                }
            }
        }
    }

The "game" itself runs on a GamePlayState class. And this is some code for the DialogueBox class:

public DialogueBox(Game1 game, string text)
    {
        TextBox = new Rectangle(1, 1, 300, 200);
        Text = text;
        gameRef = game;
        background = gameRef.Content.Load<Texture2D>(@"Scenes\scenebackground");
        font = gameRef.Content.Load<SpriteFont>(@"Fonts\scenefont");
    }
public void Draw()
    {
        SpriteBatch spriteBatch =gameRef.SpriteBatch;
        spriteBatch.Begin(
            SpriteSortMode.Deferred,
            BlendState.AlphaBlend,
            SamplerState.PointClamp,
            null, null, null,
            null);
        spriteBatch.Draw(background, TextBox, Color.White);
        spriteBatch.DrawString(font, text, new Vector2(1, 1), Color.White);
        spriteBatch.End();
    }

But I can't get it to draw anything on screen. I know for sure the dialogue.Draw call is executed (game crashes if I load a non-existing texture) and I'm going crazy. Like I said, this is probably some stupidly easy question but I can't really figure it out.
Thanks for any help!


texts: Decoupling Input from Update/Physics Movement in a Game Engine

texts:
I have some troubles figuring out how to decouple the input handling from the physics part (includes movement).

My Game loop looks like this

while GAMEISRUNNING
    HandleInput()
    Update()
    Render()

From what I have found on the internet I can do something like this in the HandleInput method

HandleInput()
{
    if A key is pressed
        MOVEFORWARD = true
    ...
}

and then in the Update I can just check the boolean flags and update properly. The problem is that my Update method uses the Physics Engine to iterate over the entities and call their Integrate method. This means that I cannot just adjust the position because the integrate method is the same for all the entities.

Integrate(float deltaTime)
{
    #position and velocity are vectors
    position += velocity * deltaTime
}

Where can i actually perform the update to movement in this scenario? I was thinking that in the global Update method I can iterate over all the entities before the physics engine and adjust their velocities. That means that every GameObject will have GameObjectUpdate method and there I can  adjust the velocities accordingly. This means that the global Update method will iterate over all the entities twice. Generally O(n) is pretty good, but I am not sure if this is the optimal way to do it.


texts: How can I protect beta test versions of my game from piracy?

texts:
I want to open my game for public feedback and testing quite early as such certain features like steams coming soon might not be available.

How could I protect my game against being pirated around from testing?

Even if we dis-regard piracy I'd not want the testers running random copies of the game whenever etc.


texts: Cannot load png images to textures with SDL2 in Visual Studio 2015

texts:
I'm learning SDL2 with Visual Studio 2015 and I'm trying to draw a 16x16 level with a .map file and 32x32 .png images for tiles (that's 256 tiles) on a 512x512 window. I have both SDL2 and SDL2 Image set up.

I'm attempting to turn the .png image into a texture using IMG_LoadTexture, but it never succeeds.

Here's the code for the structure for a single tile:

struct Tile
{
    int tileType; //a range from 1-12 that determines what kind of tile it is.
    SDL_Texture *texture = NULL; //The texture for the tile that comes from a .png file
    SDL_Rect texture_rect; //Rectangle for rendering the texture with SDL_RenderCopy
};

I successfully read the tileType from a .map file and use it in a function to give a tile in an array of tiles the right texture. Here is the code for the function :

void get_textures(Tile a[16][16])
{
    for (int i = 0; i < 16; i++)
    {
        for (int k = 0; k < 16; k++)
        {
            cout << a[i][k].tileType << ", ";
            switch (a[i][k].tileType)
            {
            case 1:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\1.png");
            break;
        case 2:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\2.png");
            break;
        case 3:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\3.png");
            break;
        case 4:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\4.png");
            break;
        case 5:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\5.png");
            break;
        case 6:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\6.png");
            break;
        case 7:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\7.png");
            break;
        case 8:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\8.png");
            break;
        case 9:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\9.png");
            break;
        case 10:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\10.png");
            break;
        case 11:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\11.png");
            break;
        case 12:
            a[i][k].texture = IMG_LoadTexture(renderer, "Sprites\Tiles_png\12.png");
            break;
        }
        if (a[i][k].texture == NULL)
        {
            cout << "Failed to load texture from file." << endl;
        }
        a[i][k].texture_rect.x = k*TILE_WIDTH; //defined as 32
        a[i][k].texture_rect.y = i*TILE_HEIGHT; //defines as 32
        a[i][k].texture_rect.h = 32;
        a[i][k].texture_rect.w = 32;
    }
}
}

Every time this runs I get a tileType and a "Failed to load texture from file." for every one of the 256 tiles. I have re-checked the file paths multiple times, made sure the "Sprites" folder is in the same folder as the project's .vcxproj file and that the folders and images are included in the project in Visual Studio and it still doesn't work (I only get a black SDL window).

Any help would be appreciated.


texts:
I have been struggling with this problem for a while.
In my project (RTS in space) I have a ship moving on a 2D plane. I want to make the right movement in space so that when I click somewhere in space:

The ship began the movement by constantly turning its nose towards the destination point. It will turn out some kind of curve;
or turned around its axis while standing still and then moved to the point if this happens faster than in the first version.

For the first version i came with this pseudocode (assume that Z component always 0, and assume that moveTo is called every tick)

int moveTo(vector3 &position, float deltaTime)
{
    float forwardSpeed = 10;
    float forwardTurningSpeed = forwardSpeed * 0.5;

    // Find direction to destination point
    vector3 direction = position - GetActorLocation();
    direction.normalize();

    // Find on which angle to rotate the actor
    float angleBetweenDirectionAndWorldRightVector = getAngleBetweenVectors(direction, GetRightVector());
    float angleBetweenActorForwardVectorAndWorldRightVector = getAngleBetweenVectors(GetActorForwardVector(), GetRightVector());
    // This subtracion is the root of all problems
    float angle = angleBetweenDirectionAndWorldRightVector - angleBetweenActorForwardVectorAndWorldRightVector;
    // When finding angle between direction vector and actor`s forward vector the value is from 0 to 180
    // and there is no difference when direction is to the left by say 10 degrees or to the right
    // I thought that by subtracting angle between actor`s forward vector and world`s right
    // vector i could decide whether direction is to the left or to the right from actor`s forward vector
    // but its not working in this way

    if(angle < 10 || angle > -10)
    {
        // If actor looking at target position nearly straight then move forward
        vector3 newPosition = GetActorLocation() + GetActorForwardVector() * forwardSpeed * deltaTime;
        SetActorLocation(newPosition);
    }
    else
    {
        // Rotate actor while moving around Z axis (on a plane XY)
        if (angle < 180)
        {
            // Rotate counter-clockwise
            SetActorRotation(0,0,GetActorRotation().Yaw() + angle * deltaTime);
        }
        else
        {
            // Rotate clockwise
            SetActorRotation(0,0,GetActorRotation().Yaw() + angle*(-1) * deltaTime);
        }
        // Move forward after rotation
        vector3 newPosition = GetActorLocation() + GetActorForwardVector() * forwardTurningSpeed * deltaTime;
        SetActorLocation(newPosition);
    }
    // Stop if reached destination
    if((position - GetActorLocation()).LenghtSquared() < 100) return 1;
}

float getAngleBetweenVectors(vector3 &first, vector3 &second)
{
    // Find angle using dot product
    float dotProduct = dotProduct(first, second);
    float cosinus = dotProduct / (first.length() * second.length());
    return acosd(cosinus); // returns angle in degree
}

This is what I`ve got.

The second variant is quite simple by using standard MoveComponentTo unreal function twice. First apply to rotate around Z axis while standing still and second apply to move straight to destination.

I don`t know how to prebuilt path to avoid obstacles so this is next step.


texts:
IEnumerator MoveBack()
{
    yield return new WaitForSeconds(3f);

    float t = 0;
    float duration = 30f;
    while (t < duration)
    {
        t += Time.deltaTime;
        player.rotation = Quaternion.Slerp(player.rotation,
           Quaternion.Euler(player.rotation.x, player.rotation.y + 90f, player.rotation.z),
           t / duration);
        yield return null;
    }
}

If I set the duration to 0.1f, it will rotate too fast to see.
But also if I set duration to 30 it's still not rotating that slow.
Should a lower duration value rotate more slowly, or more quickly?
30 seems almost fine, but is it sensible to set the value so high to make it rotate a bit slower?


texts: Eliminate isolated cave in procedural cave generation

texts:
I've got an algorithm that generates a cave procedurally, the map is modeled in the data as a 2d array of 0s (empty space) and 1s (wall). The algorithm works just fine, but I've got quite some isolated small caves on the scene, which I would like to avoid.

That's how the map looks that gets generated. Is there some efficient algorithm to remove the black holes in the white wall sections? I was thinking of something like:

For every closed cave, check if there is a bigger cave and if so, close it.

But that seems insanely inefficient since I'd have to loop over the map a lot in order to do this for all small caves.


texts:
How do I flip a texture in modern OpenGL (3.1+)?

This is the unflipped render, keep in mind it is drawn with 8x8 tiles from a texture atlas, so I edited green squares below him into the image to represent it. Rendered without horizontal flip:

I have tried doing 1-texCoord.x in my vec2 texCoord in my vertex shader.
It gave me... this result:

This is how texture atlas is laid out, if it matters:

Attempting other methods such as inverting texture coordinates of the VBO gave me similarly garbled results. What should I actually be doing, to flip the texture, or more accurately each individual tile? I know I would also have to change each tile's coordinates, but that's for after.


texts:
I'm developing a library ( i.e. a JAR file that you put into the libs folder in eclipse ) which would extend surfaceView, which other people would hopefully use to make games.

I guess the best way to make any money off it would be to show banners on that surfaceview, right?

Maybe someone had similar experience? What advertising company would you suggest? admob, leadbolt? would they agree that I would integrate their sdk into my library ( not a finished app )?

Thanks!


texts: Best resources for Canvas Html 5 development

texts:
I am at a competition at work for who can make the best canvas game.  Theme is a top down shooter... Winner gets dinner for free.

Anyways I have been looking around looking for some good resources on game deving on the canvas.  Any body got any good ones?


texts:
I am searching for a simple framework like http://getmoai.com where you can simply code a game in lua for iOS. I want to build it along with a friend. I am using a Mac, he prefers windows so the fw needs to be used in Windows 7. Preferably something like LOVE2D but then offcourse also for iOS!

Thanks in advance


texts: How do I create a simple RPG game server?

texts:
I'm working on a Sprite Kit game. I'd like to make it a true multiplayer game, by which I mean that each person joining the game has their own camera. I've seen tutorials on multiplayer games where the players share the same game screen, but that's not what I want.

I understand there needs to be a server that players connect to, which means the "world" that players connect to should be running on the server. Is this correct?

How do I have a server running the 'world' for this game? Does it have to be a specific type of server, or can I use Node.js or whatever else I want?


texts: Bright lights produce strange artifacts on Android

texts:
I'm testing lighting on Android and I'm getting strange artifacts when the light is increased. I'm not sure if this is normal with Unity or a setting somewhere is unchecked.

The only light in my scene is a spot light. I have to increase the brightness of it so that it illuminates everything in the scene properly.

On Windows 10 (in the editor), it displays just fine. You can turn the brightness up all day long and everything will just appear whiter. On Android, however, once you reach a certain threshold (a really low threshold), the colors turn to an abrupt magenta, then dark cyan, and eventually black. Because I'm using a spot light, these colors appear as a radial gradient.

Here's what I've tried so far:

Turning the brightness down. Unfortunately, I have to decrease it a lot to avoid the artifacts meaning my scene doesn't get illuminated in the way that I need it to be.
Changing Lightmapper from Enlighten to Progressive in the Lighting window. But what I think this actually indicates is compression and so is unrelated.
Not specifying a Skybox material and using Custom environment reflections.
Tweaking Graphic settings for each tier (I have double checked HDR is enabled both here and on the camera present in each scene).
Switching to Linear color space (I was originally using Gamma). The idea was maybe the color space was too small so really, really bright colors couldn't be represented; however, it is my understanding that Gamma is much larger than Linear so I'm admittedly confused.

I have Googled this issue quite a bit and all I get are issues with emissive materials not emitting light and other unrelated light issues.

Here is what my scene looks like when a spot light faces a rectangular mesh.

When the threshold is exceed initially, it looks like this:

If you continue to increase the Intensity, it eventually looks like this:

Of course, the exact colors you see vary based on the actual color of the mesh being illuminated. In the pictures above, the mesh is supposed to be a medium-dark green.

Could this be a color space issue? Perhaps a device limitation? My device isn't exactly a super computer, but it isn't bottom-grade either.


texts: Update and Render logic with interpolation

texts:
I am working with C and SDL2 and just wanted some insight as to how to properly apply interpolation to the rendering.

EDIT - some clarification, update() input() and render() are just hypothetical stubs, the real code is messy and long as I learn SDL2.

while (!quit) {
    current = SDL_GetTicks();
    elapsed = current - previous;
    previous = current;
    lag += elapsed;

    input();

    while (lag >= ms_per_update)
    {
        update();
        lag -= ms_per_update;
    }

    interpolation = (float)lag / (float)ms_per_update;

    printf("Interploation: %f\r\n", interpolation);

    render(interpolation);
}

This is something that has always kind of baffled me -

lets say that in update() if SPACE pressed we start a jump animation and movement. So sprite.y += 2 to move it.

Where does that movement of one pixel happen? Does it happen in update()?

If the movement happens in update() then how do i properly apply the interpolation in render() since my item has already been moved (during the update)?

Lets say i have a bullet at (x=10, y=10)
It's velocity is 10 pixels per update.
use clicks button to shoot
first update bullet is moved to (x=20, y=10)
render(interpolation) // lets say it is 0.5) // lots of on screen lag from awesome effects
second update bullet is moved to (x=30, y=10)
third update bullet is moved to (x=40, y=10)
render(interpolation) // lets say it is .09 from lots of lag

How is the interpolation value applied to the bullet so that it appears to pass smoothly across the screen.
What information is known during render to apply the interpolation? Would a struct containing the origin point, current velocity (or amount moved since last render), and current location suffice?


texts: How to create an OpenGL texture using primitives?

texts:
I'm currently rendering a large proportion of the graphics of my game using custom OpenGL primitive functions (e.g. DrawCircleFilled(), DrawPolygonFilled(), etc) drawing procedurally generated objects (e.g. trees). Typically the core of these functions is a glBegin and glEnd loop, and use GL_TRIANGLE_FAN, GL_LINE_LOOP, GL_LINES, or GL_POLYGON. While this generally works, I'm seeing some performance issues if I have too many objects using these functions on screen at once.

For instance, I could render a brick wall by drawing 128 small brick-coloured rectangles with an outline. Alternatively I could render a single OpenGL texture with these bricks pre-drawn, which takes up more video memory but seems to be less processor intensive.

With this in mind, my question is: how do I take the output of the primitive functions and store them in an OpenGL texture at runtime? I'm aware of how to do with with an SDL_Surface, but I don't have access to the primitive drawing functions in SDL and SDL primitive drawing is very slow (one of the reasons why I switched to raw OpenGL in the first place).

Advice appreciated.

Thanks,
Nathan


texts: What is the most efficient method to load 2D dynamic chunks?

texts:
Information/context

I'm writing a 2D sandbox game - similar to Terraria. The world is made up of many chunks, in a variable like this:

vector<Chunk> chunks;

There's no need to go too in depth about the Chunk class, but each chunk has these members:

int x, y;
Block blocks[256];

When a chunk is initialized, the blocks are all set (with a Perlin noise based algorithm.) There are 256 blocks per every chunk because a chunk is a 16x16 area filled with blocks. To the loading of the chunks, the members of the Block class are irrelevant.

Question

As the player walks around the world, I obviously need new chunks to load for them to explore. I don't think it needs saying but I shouldn't load every chunk in the world at once because:

It would be incredibly inefficient to render (even with my current system of block culling,) and
I don't know how many chunks will be in the world - there can be a huge amount, basically as many as the player wants to load.

I've tried a few different (but similar) ways to load and unload the chunks, but none of them worked very well. The main problem with both was that they sometimes gave segmentation faults.

What's the best way to dynamically load and unload chunks in a world?

By "best", I mean the most performance-efficient method.

Keep in mind I can easily load a chunk at any position - this isn't the problem. I just want a way of deciding which chunks to load.


texts:
I've run into the situation where the size of my mesh with all its vertices and indices, is larger than the (optimal) vertex buffer object upper limit (~8MB). I was wondering if I can sub-divide the mesh across multiple vertex buffers, and somehow retain validity of the indices. Ie a triangle with a indice at the first vertex, and an indice at the last (ie in seperate VBOs).

All the while maintaining this within Vertex Array Objects.
My thoughts are, save myself the hassle, and for meshes (messes :P) such as this, just use the necessary size (> 8MB); which is what I do at the moment.
But ideally my buffer manager (wip) at the moment is using optimal sizes; I may just have to make a special case then...

Any ideas? If necessary, a simple C++ code example is appreciated.

Note: I have also cross-posted this on stackoverflow, as I was not sure as to which it would be more suitable (its partly a design question).


texts: Translate object in world space usings it's local rotation

texts:
I'm using Three.JS to render some objects. I'm struggling with some very simple object rendering and translation.

The scenario is that I spawn an object at 0,0,0 in world space with 0,0,0 rotation.

var scene, camera, cube;

...

function change() {
  var degrees = 90
  var zTranslation = 5;

  cube.rotation.y = degrees * Math.PI / 180;
  cube.rotation.z = zTranslation;

  var newCubeMatrix = cube.matrix;
  newCubeMatrix.identity();
  newCubeMatrix.multiplySelf(THREE.Matrix4.rotationYMatrix(cube.rotation.y));
  newCubeMatrix.multiplySelf(THREE.Matrix4.translationMatrix(cube.position.x, cube.position.y, cube.position.z));

  cube.updateMatrix();
}

function loop() {
  renderer.render( scene, camera );
}

...

What now happens is that the cube is rotation 90 degrees and translated 5 points on the Z axis in world space, not 5 points on the Z axis in the cube's local space.

How do I make the cube translate 5 points in it's local space?


texts:
I'm currently using a simple implementation of  linear to sRGB transform:

float sRGB(float x) {
    if (x <= 0.00031308)
        return 12.92 * x;
    else
        return 1.055*pow(x,(1.0 / 2.4) ) - 0.055;
}
vec3 sRGB_v3(vec3 c) {
    return vec3(sRGB(c.x),sRGB(c.y),sRGB(c.z));
}

Possibly, that the correction for small values (x <= 0.00031308) will not matter in practice.

I considered to just let ´pow(x, 1.0 / 2.4) but I'm not sure how much impact it will have.

Is there any way to optimize it?
Can be vectorization help?
Can some polynomal fitting be better?


texts: Separate "Battle Character" class from "Character" class?

texts:
So I have a Class called Character which represents all the player, his companions, and all enemies.  This class does a lot of things including performing actions upon other characters, and upon the environment, and so on.

I'm about to start work on a battle system for this RPG, and there will be the player controlled (and enemy controlled) units which will have a location on the screen, and a delay since their last action, and a ton of other properties and methods that apply entirely to the battle.  But, this thing will also be associated in a one-to-one relationship with a Character which exists separate from a battle.  It will need to access that characters stats for it's battle actions as well as some of it's methods.

So the root of my question is, is it better to create a new "Unit" class, which references the character it's associated with, or should I just expand upon the existing Character class with functions and properties that relate only to a battle?  If it matters I'm writing this in C#.


texts: In my work I analyze and design Evolutionary Algorithms (EAs), but for fun I'm learning game design, and, of course application of EAs in games. So I'm wondering if there have been any games where AI actually works as AI, i.e. learns from past solutions to develop new ones. I suspect it should be something like tic-tac-toe or chess.


texts: How to implement the light trails for a tron game?

texts:
Well I was creating a TRON style game, but had an issue with creating the actual light trails for the game. What I'm doing currently is I have an array the same size as my window in pixel size, implemented like this:

int* collision[800][600];

Then when the bike goes on a certain pixel, it is marked with a 1 for traveled on. However what is the most efficient way to create a working light trail display?

I tried to do something like this:

int i, j;
for(i=0; i<800; i++)
    for(j=0; j<600; j++)
        if(*collision[i][j] == 1)
            Image::applySurface(i, j, trailSurface, gameScreen);

But it isn't working properly? It just fills the whole screen with a sprite instead.
Whats a better/faster/working way to do this?


texts:
So I've reached the point in my exploration of gaming where I'd like to implement the concept of time into my little demo I've been building.

What are some common methodologies for creating the concept of time passing within a game?

My thoughts so far:

My game loop tends to spend a fair amount of time sitting around waiting for user input so any time system will likely need to be run in a separate thread.

What I've currently done is create a BackgroundWorker passing in a method that contains a loop triggering every second. This is working fine and I can output information to the console from here, etc. Inside this loop I have a DateTime object that is incremented by 1 minute for every realtime second. (the game begins in the year 01/01/01)

Is this a standard way of achieving this result or are there more tried and tested methods?

I'm also curious about how to go about performing time based actions (reducing player energy, moving entities around the game board, life/death etc).

Thanks for any pointers or advice. I've searched around, however I'm not familiar enough with the terms and so my searches are yielding little result on this one.


texts: Which collider to use on "island" situation?

texts:
I have a 2d-top-down-unity game where the player is on an island. The shape of the island is random generated and he is not able to "escape" from the island.

So which Collider should I use for realizing this?

Is there some form of an "inverted" collider? Are colliders able to have a hole in them? Or should I create a polygon collider with a small gap (This could be quite difficult if the polygon bends the wrong way)?


texts:
Develop a timer script, the idea of this script is that after an amount of time has passed, a button that I have in the scene is activated, this script also uses this script uses DontDestroyOnLoad, but I cannot activate it because of the following error:

"MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
DigitalRubyShared.Timer.Update () (at Assets / DIC / Scripts / Timer.cs: 53)) "

From what I understood is that this button object is destroyed when I change scenes, so how can I keep this object?

 public static float currentTime;
        public static float endTime = 0f;
        public static bool startTime = false;
        public static string recibir;
        public static Timer estadoTimer;
        public string tiempoEscena;
        public string nombreEscena = "Mapa_Izquierdo";

        public GameObject aceptar;
        [SerializeField] Text Contador;

        void Start()
        {
            currentTime = 0f;
        }

        void Awake()
        {
            if(estadoTimer == null)
            {
                estadoTimer = this;
                DontDestroyOnLoad(gameObject);
            }else if(estadoTimer != this)
            {
                Destroy(gameObject);
            }

        }

        void Update()
        {

            if (startTime != false)
            {
                currentTime += 1 * Time.deltaTime;
                Contador.text = currentTime.ToString("0");

                if (Contador.text.Equals(tiempoEscena))
                {
                    //SceneManager.LoadScene(nombreEscena);
                    aceptar.SetActive(true);
                    currentTime = endTime;
                    stopTiempo();
                }

            }
            else
            {
                Contador.text = currentTime.ToString("0");
            }

    }


texts: Where to put the screen dimensions to make it accessible for all on screen objects?

texts:
I'm starting game development to learn a new language (SDL2, C++) and would like some opinions on the best way to handle a probably very basic problem.

I don't want my player to go off screen, so I have something like this now:

void Player::sanitizePosition() {
    if ( m_xpos < 0 ) {
        m_xpos = 0;
    }

    if ( m_ypos - m_height < 0 ) {
        m_ypos = m_height;
    }

    ...
}

For the other two sides I would need the screen dimensions. Now I'm wondering what the best way to give them to the object would be?

Global variables are bad, but a Singleton with the screen information seems like the same thing to me.

Another idea would be to have a GameObject base class, that has the screen dimensions as static members, which Player would inherit from.

Of course I could put them into the constructor of every game object, but that just screams code smell.

This is such a basic problem, I'm sure there is a consensus on how to do it.


texts: Making a pixel-perfect viewport in LibGDX

texts:
My game that uses LibGDX as the graphics library, should be playable with every display. Here's the problem: It have to be pixel-perfect. That means, the scale factor must be an integer value, so that my pixels do not stretch over two physical pixels - resulting in flickering pixels which I obviously do not want.

The player should see a constant amount Y of vertical space. The width is calculated by the screen resolution. My game field is designed for 4:3. Therefore a player with 16:9 or even 21:9 should see more in the horizontal space. Best example: An usual Pong field. The field is 4:3. A player with 16:9 should see the same field size, but with more "empty" space on the sides.

I've tried various approaches to achieve this.
The first was the ScreenViewport, provided by LibGDX. Problem: Adjusting the unitsPerPixel would result in a smaller playfield. Or even mirroring it. I could provide a high-res playfield and scale it down with unitsPerPixels, but it is not very future-proof (Think of providing a 4k field for a future 512k monitor).

My second approach was a custom viewport. (No worries! It is written in Kotlin)

worldWidth *= (screenHeight/worldHeight).toInt()
worldHeight *= (screenHeight/worldHeight).toInt()

setScreenBounds(
    screenWidth/2 - worldWidth.toInt()/2,
    screenHeight/2 - worldHeight.toInt()/2,
    worldWidth.toInt(),
    worldHeight.toInt() )

It tries to scale up the field by a integer number (making it pixel-perfect).
Problem: The unscaled zones (that would be normally covered by the non-integer-scaling) are black. Black bars. Instead, I want to show the game world.

Any ideas how to achieve this? Thanks!


texts:
This might be a basic question but googling isn't turning out anything useful:

How are we supposed to use TTF_SetFontOutline ? I know we're able to create an outline (and it looks alright) but since it's the same colour as the main font I don't see any practical usage for it.

I can't find any way to set the colour separately and rendering two font instances makes it very hard to line up.

So what is a typical usage case for it?


texts: Unity shaders: best way of handling data structures

texts: I'm working on a shader in Unity that uses a Binary Tree to store some precomputed values, this binary tree should be available to the shaders and would ideally also be constructed on the graphics card (each node in this tree is based on 1 pixel) is there a good way of doing this?


texts:
I'm looking into making 4 types of cubes; grass, stone, dirt, and empty. I have a cube class that is just for storing the location of the cube.

    public Cube(GraphicsDevice Device, Vector3 Position, Texture2D Texture)

I want the Texture2D to be changed to something like CubeType. In my cube class, I have a grass and stone class which both inherit cube, but I don't know how to make that work for what I want.

    public class Grass : Cube
    {
        public Grass()
        {
            isMineable = false;
        }
    }

    public class Stone : Cube
    {
        public Stone()
        {
            isMineable = false;
        }
    }

The only thing that makes each cube differ from each other is the texture and if theyre mineable or not.
What's the easiest way to implement what I want? I guess one way of doing it is just adding another parameter to Cube(bool isMineable), but for learning purposes I want to see if there's a better way to do it.


texts: How do you set multiple collision rules with Swift and SpriteKit?

texts:
So basically I've got 2 types of balls and 2 types of enemies. Green can delete red only, red can hit delete only. Here's what I have for the first collision test:

 func didBeginContact(contact: SKPhysicsContact) {

        // 1. Create local variables for two physics bodies
        var firstBody: SKPhysicsBody
        var secondBody: SKPhysicsBody

        // 2. Assign the two physics bodies so that the one with the lower category
        // is always stored in firstBody
        if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
            firstBody = contact.bodyA
            secondBody = contact.bodyB
        } else {
            firstBody = contact.bodyB
            secondBody = contact.bodyA
        }

        // 3. react to the contact between ball and bottom
        if firstBody.categoryBitMask == RedBallCategory &&
           secondBody.categoryBitMask == GreenBarCategory {

            (secondBody.node!.removeFromParent())
            score++
            scoreLabel.text = "\(score)"
        }
    }

This works as expected, red ball hits the green bar and it deletes him.

You can't just make a func didBeginContact 2 and change the bit masks as far as I'm aware..or at least it didn't work when I tried it, so how do you handle multiple rules for collision? All of the basic tutorials I've seen handle something like one bullet hitting one type of enemy. What if you have 2 "bullets" and 2 enemies?


texts: How to attach main camera to script component of a prefab?

texts:
So I have a prefab which is an item drop and a timer attached to the main camera. When the player collides with the item, I need the item to destroy then add time to the timer.

The itemdrop handling script looks like this:

   public LifeTimer LifeTimer;

   // Destroy sprite once player collides into it
   void OnCollisionEnter2D(Collision2D col){
       if(col.gameObject.name=="Player"){
           Destroy(gameObject);
           LifeTimer.currentTime += 10;

       }
   }

The life timer is a reference to my script as follow which is attached to the main camera.

public class LifeTimer : MonoBehaviour
{

    // Once level initializes, start current time to starting time
    public float currentTime = 0f;
    public float startingTime = 10f;

    [SerializeField] Text lifeTimerText;

    void Start(){
        currentTime = startingTime;
    }

    void Update(){

        // Decrement time per second every second
        currentTime -= 1*Time.deltaTime;
        // Set currentime to text on screen
        lifeTimerText.text = currentTime.ToString ("0");

        // Load Game Over Screen when time goes to 0
       if(currentTime <= 0){
            Application.LoadLevel(0);
        }
    }
}

I realized I can't attach the main camera to the life timer component of the item drop script because the item prefab is not instantiated yet. What would be the best way to do what I'm trying to do, which is to add time to the timer. The on collision and destroying aspect works perfectly.

Thank you for any guidance


texts: Do editor errors affect device performance?

texts: Do errors that come up in the Unity editor affect a game's performance on a device (on Android in particular)?  I'm talking about errors that keep coming continuously during Update() such as NullReferenceException  and "Debug.Log".


texts: Pygame Surfaces: which (and when) do I need to .convert()?

texts:
I'm a bit puzzled about pygame's Surface.convert():

It's common sense that I should convert a surface after loading an image to it (presumably a jpg/png/etc file), but what about surfaces that I only use pygame's "primitives" like pygame.draw.circle() or Surface.fill()?

Official documentation is very vague about it: it says "fastest format for blitting. It is a good idea to convert all Surfaces before they are blitted many times".

Consider this simple ball-bouncing code:

import pygame

position = [100, 200]
velocity = [7, 17]
radius = 50

pygame.init()
clock = pygame.time.Clock()

screen = pygame.display.set_mode((800, 600))
background = pygame.Surface(screen.get_size())
screen.blit(background, (0,0))

ball = pygame.Surface(2*[radius*2])
pygame.draw.circle(ball, (0, 255, 0), 2*(radius,), radius)
bounds = (screen.get_size()[0] - 2 * radius,
          screen.get_size()[1] - 2 * radius)
rect = ball.get_rect()
rect.x = position[0]
rect.y = position[1]

done = False
while not done:
    for event in pygame.event.get():
        if event.type in [pygame.QUIT, pygame.KEYDOWN]:
            done = True

    for i in [0, 1]:
        position[i] += velocity[i]
        if position[i] < 0 or position[i] > bounds[i]:
            velocity[i] *= -1

    screen.blit(background, rect)
    rect.x = position[0]
    rect.y = position[1]
    screen.blit(ball, rect)
    pygame.display.update()
    clock.tick(60)

pygame.quit()

It has 3 surfaces: screen, background and ball. They are blitted a lot, as source or dest. Would any of these surfaces benefit from a .convert()?

If yes, then should I simply append a .convert() when creating any surface? Like

surface = pygame.Surface(...).convert()

A lot of pygame tutorials do that, even for a background that is just .fill()'ed. But this feels so... redundant. Why isn't the so called "fastest pixel format" the default when creating new surfaces?

And if such surfaces would benefit from a convert, when should I do so? After a .fill(), before, or it doesn't matter? Is once enough or should I "reconvert" after each draw? What if I load an image?

References and sources about proper .convert() usage are highly appreciated, thanks!


texts: Does distant and large objects use up a lot CPU usage?

texts:
Okay I'm new to Unity, and I'm making a space sim pc game. You know, space is huge, light years of distance between stars. Even if I set 1 AU (150,000,000 KM) as 1 unit, 1 light year will be 63,000 units, that's far far away from one another. Let say planet Earth's scale is 1, then the Sun will be 110x times the size of the Earth. This is big, because if the player's scale is 1, then we need to rescale the planets, the stars. I don't know whether or not Unity will handle large objects or far objects nicely, what I mean here is if a planet is, for example 10000 units, will the objects stop being processed by cpu? And does large objects use more cpu performance, if it does, how much it use?

What I want to know
1. Does far far away objects use up more cpu usage?
2. Does gigantic objects use up more cpu usage? I know it sure does, but how much? Is it 2x scale = 2x cpu usage on that object?
3. Do you have a way to minimize the usage of cpu, or more efficient way to do with large and distant objects?

I'm just started Unity last month, and get excited about how much could Unity do, but i always concern about how much cpu usage does this task use up. Any ideas?


texts: Collision with walls in a completely tile based game

texts:
I am making a tile based game, in which also the player movement is completely snapped to the grid. Imagine sokoban.

I basically have a 2d array for the layout of the level (walls / not walls), and the player can check is there's a wall where he is going.

My question is, when the player is trying to move into a wall, should I:

Let it move into the wall, then later check if it's in a wall and if needed revert it's movement?
Check whether it is going to move into a wall and prevent it beforehand?

I understand the answer may heavily depend on the structure of my code, but I'd still like to hear some opinions about how it was done in the past. What do you think? which of the two is better? (or is there a third option)


texts:
Let's say I have min (0,0,0) and max (1,1,1).
If I have 3 points, lets say

a (0.2,0.4,0.2)
b (-0.5,0.8,0.2)
c (2,0.3,0.1)

How would I go about calculating it those points are within the coordinates of min and max?
Note that I am using simple shapes such as Cubes and that I am going to use this for optimizations with octrees


texts: How do I linearly interpolate between two vectors?

texts:
I have a velocity vector where my client is at and where its going, and I have the same vector that comes from the server telling where the client should be. Sometimes its a bit different, so I want to interpolate between my current position to the server correct position.

The black arrow is the client velocity vector, the red arrow is the client velocity  vector on the server and the blue arrow is the one that I want to calculate and interpolate to.

How do I calculate the blue vector? Then, how can I linear interpolate between them?


texts: how can i make my game more intuitive without a tutorial?

texts:
i am currntly working on a mobile game app. the game details a tree with several branches on which diffrent types of birds fly and land on. every bird has a diffrent weight and the purpose of the user is to balance the weight on each side of the tree before the branches break. i attached a screen shot of the game, and i hope someone will have a suggestion on how to make the concept of the game more understandable to users without having to let them do a tutorial. second, what would be your guess about the purpose of the game when you look at the screen shot? and third, i was hoping to add a bending feature to the tree that will enable the user to save the tree by actually moving his phone but it is problematic when the design is made with pixel art - any other thoughts?
thank you,


texts:
I would like an advice about some real-time rendering optimization.
I'm rendering a BSP level, by only using the mesh, textures, entities, and lightmaps, not using VIS at all.

I'm trying to make my own Cell/Portal rendering system, a very basic one, but here is the problem, since Ogre uses a basic frustum culling (as I've heard), I think it would render everything behind the walls if every portals are in the field of view :

Do you have some better ideas to implement this ?

I am getting 650 FPS at a resolution of 1920x1080 if I render only zone only. I can get 1300 FPS if I see nothing.

Is 300 FPS good for a complex scene like this one?

I would like to make a lot of basic things clear for me.


texts:
This question is asked in the context of image effect shader implementations in Unity.

Looking through the scripts for image effects in the standard assets package, I notice that initialization is generally done in the CheckResource() function.

The following is a snippet of code from the BloomAndFlares image effect.

public override bool CheckResources()
{
    CheckSupport(false);

    screenBlend = CheckShaderAndCreateMaterial(screenBlendShader, screenBlend);
    lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader, lensFlareMaterial);
    vignetteMaterial = CheckShaderAndCreateMaterial(vignetteShader, vignetteMaterial);
    separableBlurMaterial = CheckShaderAndCreateMaterial(separableBlurShader, separableBlurMaterial);
    addBrightStuffBlendOneOneMaterial = CheckShaderAndCreateMaterial(addBrightStuffOneOneShader, addBrightStuffBlendOneOneMaterial);
    hollywoodFlaresMaterial = CheckShaderAndCreateMaterial(hollywoodFlaresShader, hollywoodFlaresMaterial);
    brightPassFilterMaterial = CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial);

    if (!isSupported)
        ReportAutoDisable();
    return isSupported;
}

I am probably wrong in assuming that this is essentially the Start() or Awake() functions for PoseEffectsBase, but I decided to try implementing something simillar.

public override bool CheckResources()
{
    saturationPassMat = CheckShaderAndCreateMaterial(saturationPassFilter, saturationPassMat);

    if (!isSupported)
        ReportAutoDisable();
    return isSupported;
}

Unlike the standard asset scripts, CheckResources() does not seem to be called consistently for me. Unity console throws UnassignedReferenceExceptions every frame, for the object saturationPassMat.

When is the CheckResources() function called? Should it be used for initialization just like Start()?


texts:
I'am starting to develop a 2D game with motorbikes.

My Question now is:
When my bike reaches the right edge the world should move. (Like in that game: Game example) My first thought was to implement a camera and to create a huge image for the world. (e.g 4096 x 512).
So I only have to move the camera to solve the problem.

Is that a good solution?!

Thank your.

Regards,
Matthias


texts: Cocos2dx- Draw primitives(polygons) on Update

texts:
In my game I'm trying to draw polygons on on each step i.e. update method. I call draw() method to draw new polygon with dynamic vertices. Following is my code:

void HelloWorld::draw ()
{
    glLineWidth (1);

    CCPoint filledVertices[] = {
        ccp (drawX1, drawY1),
        ccp (drawX2, drawY2),
        ccp (drawX3, drawY3),
        ccp (drawX4, drawY4)
    };

    ccDrawSolidPoly (filledVertices, 4, ccc4f (0.5f, 0.5f, 1, 1));
}

I call the draw() method from the update(float dt) method. The engine is behaving inconsistently i.e. sometimes it displays the polygons and on other occasions it does not.

Is it the right approach to do such a task? If not what is the best way to display large number of primitives?


texts: Is it possible now to make something for android in Unity3d without buying any licenses?

texts:
I was just talking to a game dev who said its possible, that it involves downloading the android sdk and few other things. If this is possible can someone tell me how?

Also is it possible to build a .apk file and install on your device? Is it possible to release something developed this way on the play store?


texts: How to check if objects are hidden in godot

texts:
I have multiple objects, each has area2d and collision shape, I click it, I hide it.

Now, I create script and attach it to the main Node2d with the following

extends Node2D

func _ready():
    if (get_node("matchbox_closed").hide() && get_node("oil").hide()):
            get_node("match").show()

it hides the first object in the list automatically, what I want is to check not to hide, but I can't see any boolean that check that or any isvisible getter like Libgdx


texts:
I am working on a cheat analysis system using data from Steam. From this page, we can get the last 20 checked Steam IDs. Is there a way to get the last 20 banned Steam IDs?
VacList has a section with the last banned accounts, but I don't know how to extract the data. A solution like that provided by vacbanned.com would be much better.


texts: What is the better approach to redraw a static background scene for game?

texts: Take for an example I have the background scene of a game which should remain static for an interval.Then for every time redrawing the scene,is it better for me to store the color buffer for every pixel on the viewport and redrawing using the stored color buffer or to applying a texture to the whole background or to draw the triangular,quad meshes?


texts: Saving settings when exiting the application

texts:
I created a static class CustomPlayerPrefs, it has a WriteToDisk() method that writes the saves to disk.
For saving I am using Application.quiting event:
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]
static void Init()
{
    Application.quitting += WriteToDisk;
}

But on android it never works. I know that applications are not closed but paused, but it doesn't even work when I restart the device or force the application to stop.
How to fix this or how to make it better?
Need IOS and Android support.


texts: Pyglet: How to use second screen's vsync

texts:
does anybody know if it's possible to use the vsync of the second monitor instead of the first one with pyglet?

I have 2 monitors, one running at 60Hz and the other at 120Hz. I want to be able to set my application on whatever monitors I have, and have the application use the monitor's rate to swap the buffers.

This needs to be cross platform.

I found this information...
pyglet.window

But I was wondering if anybody knows a way...

Thanks for your help.


texts:
When in my game i move my character, the camera follows it. I have no problem drawing this char when it is moving or moving another char when the camera is still. Now, when i move both of them, the texture position of the second character is wrong, you can see it here:

Under the hood i round the values before moving the viewport and drawing textures, and i had no problems except in this case. How can i fix this?