texts: How to make and correctly use progress bar in cocos2d-iphone?

texts:
I have a game that uses a progress bar to inform player of level of certain stats of the player. For example hunger, when it starts at zero and slowly adds up to maximum bar. When he eats the hunger reduces.

I tried implementing as progressBar, but it works wrong, as the bar expands both ways, and I need it to grow one side only. Also I had hard time setting the bar, since it uses actions.

Is there an easy way to do it?


texts: How to rotate an object around one end of line till its lies on the line

texts: From the image below, I would like to rotate a game object C around a point A of a line (made using a line renderer) by an angle d to position p1 till C is on the same line joining points A and B over a given period of time. Preferably using a coroutine. Please note that the angle d is not known. How can I achieve this?


texts: A-Star Pathfinding Not Giving Shortest Path

texts:
I'm attempting to implement the A* pathfinding algorithm in Java. I thought it was working well, but then I found instances where it doesn't follow the shortest path

Green = start, red = target, black = walls (unwalkable), blue = path

Red # in top left is G value, green # in top right is H value, black # in middle is F value. Black lines show parents.

I have a Node class which has the following properties:
Integers x, y == 0
Integers f, g== -1
Node parent

H is calculated using the diagonal shortcut method described here

int xDist = Math.abs(end.x - x);
int yDist = Math.abs(end.y - y);
//end == target node
if (xDist > yDist) {
    h = 14 * yDist + 10 * (xDist - yDist);
} else {
    h = 14 * xDist + 10 * (yDist - xDist);
}

G is calculated as follows:

public int getG(boolean force) { //force == true will recalculate G
    if (g == -1 || force) {
        if (equals(start) || parent == null) {
            g = 0; //If its the start, g = 0
        } else {
            g = parent.getG(force) + (parent.x != x && parent.y != y ? 14 : 10);
            //10 for orthogonal moves, 14 for diagonal
        }
    }
    return g;
}

The path is calculated using this findPath method:

public static boolean findPath(Node start, Node end) {
    if (start.block || end.block) {
        //start or target has a wall on it
        return false;
    }
    Node.start = start;
    Node.end = end;
    LinkedHashSet<Node> open = new LinkedHashSet<Node>();
    LinkedHashSet<Node> closed = new LinkedHashSet<Node>();
    //open and closed lists, respectively
    boolean found = false;
    open.add(start);
    //add the starting node to open list
    while (open.size() > 0) {
        //while there is something in open list
        int lowF = Integer.MAX_VALUE;
        int curF = 0;
        Node curN = null;
        for (Node node : open) {
            curF = node.getF();
            if (curF < lowF) {
                lowF = curF;
                curN = node;
            }
        }
        //curN == lowest F value in open list
        if (curN == end) {
            //target has been found
            found = true;
            break;
        }
        open.remove(curN);
        closed.add(curN);
        //switch the lowest F value Node to the closed list
        for (Node node : curN.getAdjacent()) {
            //iterate over non-wall adjacent nodes
            if (closed.contains(node)) {
                //already on closed list
                continue;
            }
            if (!open.contains(node) || node.getG() < curN.getG()) {
                //not on open list OR it has a lower G cost
                node.parent = curN;
                //set node's parent to the lowest F cost Node from before
                node.getF(true);
                //recalculates the F (and G) values
                open.add(node);
                //add to the open list.
                //will NOT be readded if already present
            }
        }
    }
    return found;
    //loop is over, return true
}

I lead myself to believe that the issue was in my heuristic, however I'm not sure that's the case anymore: shouldn't the shortest path still be found eventually?

The path begins by approaching the target the fastest way because of the heuristic, but then seems to "change it's mind." I've been baffled for days.

When I remove the H value (i.e. set it to 0) I get the expected result.
When I remove diagonal movement I also get the expected result.


texts: Leaderboard Testing on Google Play Services

texts:
I have a shared Google Play Developer account so that he allowed me to publish a game app. Next, I want to know if in order to test the online highscore is to upload the APK and publish it first before adding a new game at the Game Services section.

One thing, according to this link and this link on setting up Google Play Services, these tutorials on implementing code for the leaderboard is possibly applied on the Manifest. Is it still the same in Unity if I added the lib folder onto the plugins folder of the Unity project and how?


texts: In JBox2d when dragging a Body, why is the direction is flipped vertically?

texts:
Why is it when I drag a JBox2d Body with the mouse, the vertical component is flipped?

e.g. If I drag down-right, the Body moves up-right.

Is this expected behaviour, a bug in JBox2D, a Mac incompatibility or something else?

I'm on a Mac (10.9.3) with Java 1.7.60, JBox2d 2.2.1.1.  I thought it might be Mac's "natural scrolling" but changing that setting didn't have any effect.


texts: I finished "Beginning Android Games", should I use its framework?

texts:
I've worked through Mario Zechner's "Beginning  Android Games" and have made my own pong and asteroids game using the framework used in the book. I have also downloaded the source code for Replica Island and am able to run that.

I like Replica Island's framework over the one I made from reading the book. Some differences are that Replica Island uses different activities for each screen instead of Zechner's Screen class and that Replica Island can use a lot of textures and isn't limited to textures with dimensions of powers of 2.

If I'm serious about writing games and apps for Android should I learn Replica Island's framework and use that instead of the one I made while reading Zechner's book?


texts:
I want to put Scrollable Text On Object / Mesh.
I looked after it on YT but I did not find anything useful.
How could I do this?


texts: How will Unity games work on Chrome now that NPAPI is disabled?

texts:
As expected, this September Google disabled NPAPI in Chrome, which Unity Web Player relies on. As far as I know, Chrome now has its own API plugin API.

Will the Web Player returning to Chrome without NPAPI?

If not, what is Unity's future on Chrome?


texts: How to get a texture from current point of view in OpenGL 2.0 ES?

texts: Probably the title is confusing, but I didn't know how to ask better, sorry about that. What I would like to do is get a bitmap texture that represents exactly what's rendered at one point in time and save it as a file (I know how to save it, I need only to find out how get the bitmap data form OpenGL) Like a screen shoot, sort of.


texts: Rotate bone on 1 axis to look at another object - Unity 3D

texts:
I'm new to game development and I'm trying to create a basic 3D Tower Defence game as my first project. I've created a basic turret in Blender and I'm now trying to rotate 2 different bones to make the turret follow the enemy. The first bone (which I have working) rotates the turret to face the direction of the enemy. The second which I can't get right needs to rotate the gun at the top of the turret to look down at the enemy. I need it to keep facing the same direction as the rest of the turret and don't want it to tilt to either side. So it needs to move on 1 axis only.

I have tried various things, including examples from the Internet but I can't figure it out. So far I've managed to get it to look down at its base, up at the sky and spin like a wheel. Basically everything except where it's supposed to be looking.

Here is the code I have at the moment:

if (enemiesInRange.Count > 0)
    {
        //Rotate Platform //#### This section works fine
        Transform platform = transform.root.Find("Armature/BaseBone/PlatformBone");

        Quaternion targetRotation; //Final rotation (I.e. facing the enemy)

        Vector3 turretPosition = platform.position; //Store the turrets current position
        turretPosition.y = 0; //0 the Y axis to stop the turret tilting up or down

        Vector3 targetPosition = enemyManager.activeEnemies[enemiesInRange[0]].transform.position;

        targetRotation = Quaternion.LookRotation(targetPosition - turretPosition);

        float rotateSpeed = 2.0f * Time.deltaTime;
        platform.transform.rotation = Quaternion.Lerp(platform.transform.rotation, targetRotation, rotateSpeed);

        //Rotate GunBox //####TO DO: This part is not working
        Transform gunBox = transform.root.FindChild("Armature/BaseBone/PlatformBone/LowerArmBone/UpperArmBone/GunBoxBone");
        Vector3 gunBoxPosition = gunBox.position;

        float angle = Vector3.Angle(gunBoxPosition, targetPosition);

        gunBox.RotateAround(gunBox.position, Vector3.left, angle);

        Debug.Log(angle);

    }

Here's a picture of the turret to give you an idea what I'm working with. You can see in the screenshot that the bone's default X rotation is roughly -50.

Enemies walk through the trench around the turret. The PlatformBone rotates everything from the silver platform upwards.

I also don't understand why the line below makes the turret rotate instead of tilting it. I would expect to rotate the turret around the Y axis to keep it flat on the floor and face another direction. Yet I seem to have to do the opposite (If I select the PlatformBone its Y axis is facing up as expected):

turretPosition.y = 0; //0 the Y axis to stop the turret tilting up or down


texts: What is the optimal way to handle internal matrix data storage for interop with native graphics APIs?

texts:
I'm writing a managed (c#) game engine and have stumbled on a bit of a crossroads in design/implementation regarding matrix types.

Matrix types need to be optimized for marshaling to native graphics api wrappers and shader compilers, etc and after viewing the way this is handled in various projects, I'm having a hard time deciding which route would be the optimal way to go.

The problem really arises with the internal storage of matrix data.

SharpDX (a very high quality managed DirectX wrapper) does so by explicitly defining each component as public fields such as:

public float M00, M01, M02, M03;
public float M10, M11, M12, M13;
public float M20, M21, M22, M23;

I'm assuming that this was done to simplify marshaling and also for faster access to fields during math operations and allows the type to be defined as a structure to be a true value type.

In Math.NET they store the internal representation as a one-dimensional array which still allows for rather simple marshaling but the definition becomes a reference type (class) using value-type semantics.

I also seen another implementation using a multi-dimensional array for the internal storage of data which makes performing operations on the field data more natural by using indexing by row and column but this would add overhead and would make marshaling a bit trickier due to the nature of interop with multi-dimensional arrays.

The SharpDX way seems ideal, as it makes the matrix types blittable and seems like it would be faster, however, being a value type would make it have a larger footprint (which I'm assuming is why most operations defined in SharpDX matrices have both pass-by-value and pass-by-ref functions defined).

In that light, it makes sense to define my matrix types as reference types so that only references are being passed, but then that makes interop a bit more challenging.

Being for a game engine, performance and memory footprint take priority over elegance though, so am I right in assuming SharpDX's approach would be best for my scenario?


texts: unity android output is about 120mb even with just an empty scene

texts:
there is a lot of content in my project but as a test I just chose a empty scene with one sprite to build but the apk output size is about 120mb.

I think there is an options or setting or platform support that makes it much big but I don't know what it is.

thank you for helping


texts: Box2D - Constant Movement without ignoring Physics

texts:
I am developing a small game with LibGDX and Box2D.

I want to move a body at a constant speed, lets say 2 m/s (meters per sec).
The body should accelerate to that speed immediately when pressing the respective key (e.g. Arrow Up) and also be able to stop or change direction instantly.

The code to start and stop such a movement should look like this:

public void onKeyPress(key){
    if(key == ArrowUp){
        currentMovement = new Vector2(0, movementSpeed);
        body.addConstantMovement(currentMovement);
    }
    //TODO: Remaining directions
}

public void onKeyRelease(key){
    if(key == ArrowUp || key == ArrowLeft || key == ArrowRight || key == ArrowDown){
        body.removeConstantMovement(currentMovement);
    }
}

The given Vector2 (movementSpeed) should be remebered and I should be able to remove it at any time.

However, he should still be affected by the physics of everything around him.
So if he moves towards a magnet that pulls him 1 m/s, he will move with 3 m/s, when moving away from it the speed should be down at 1 m/s.

Is it possible to do this in Box2D without manually moving it in every step of the world?
-If yes, how?
-If no, any libraries that can do this? I only need very simple physics, no density, friction etc.


texts: How can I improve my rendering performance in Java?

texts:
How can I improve the performance of my rendering? Currently, I'm rendering with java.awt.Graphics, but it seems to be starting to slow down since I'm adding new stuff to render.

My rendering setup:

Loading a spritesheet:
Spritesheet sheet = new Spritesheet(ImageLoader.loadImage("/textures/spritesheet.png"));

Loading sprites:
BufferedImage player = sheet.crop(5, 0, Spritesheet.DEF_WIDTH, Spritesheet.DEF_HEIGHT);

And then rendering it with java.awt.Graphics in my gameloop:
g.drawImage(player, x, y, Entity.DEF_WIDTH, Entity.DEF_HEIGHT);

Spritesheet.DEF_WIDTH and Spritesheet.DEF_HEIGHT refer to 32px for quick access since most of my sprites are 32x32px. Entity.DEF_WIDTH and Entity.DEF_HEIGHT refer to 64px to render the entity on the screen.

One way I know that could solve my problem is that I could use smaller sprites but scale them up while rendering, but let's see if it's possible without that first.


texts: For 2D tiled maps is all object and NPC data loaded into memory when the map is loaded?

texts: I'm creating a text RPG in Java, but I think this applies for a GUI as well with regard to the data structure. Each Level is a tiled map. Each Tile object has an (X,Y) coordinate, and references to adjacent tiles, but my question is with regard to storing object and NPC data on that Tile object. Depending on the size of the map I'm loading, this seems like a lot to load, but if that is the commonly accepted practice then I'll go with it.


texts: Is there any public in-game data mining/knowledge discovery repository?

texts:
I'm taking an Introduction to Data Mining course at the university and we have to work on a final project.

As you may already know, it's difficult to collect this kind of data manually (specially when you're not working for a company of have the proper contacts).

Is there any public collection of in-game data in order to apply data mining algorithms? The kind of data I'm looking for is the sort of data they used in this paper "Predicting Player Behavior in Tomb Raider Underworld".

Characteristics: playing time, number of deaths, causes of death, rewards, treasures. Other kind of in-game data (possible an MMORPG): race, level, equipment, guild, items usage, hp/mp rate, level-up mean time, hours played by day/week/month, log-in/log-off time, etc.

The kind of problems I'd like to tackle could be represented as questions like:

What are the chances a player is likely to pass the game [in X seconds]?
What are the best X guilds to be with in order to meet my expectations as a player and not end up being expelled?
What is the best world area in order to level-up faster now while minimizing death possibilities?


texts:
I'm working on a shader but it has a weird tint to it and I'm not sure why. Right now it's extremely simple, it just sets a rendertarget, draws to it, passes it as a texture to the shader then oututs the pixels to a fullscreen quad. If I remove the rendertarget/texture part and just directly pass it into the shader it comes out properly, but once I start including rendertargets the colors get a little weird.

Here are two images showing what I mean:

This is how it should look normally

This is how it looks with the rendertargets

I've included the code for the shader and the draw method below:

Shader:

float4x4 World;
float4x4 View;
float4x4 Projection;

Texture glowTexture;

sampler glowSampler = sampler_state
{
texture = <glowTexture>;
magfilter = LINEAR;
minfilter = LINEAR;
mipfilter = LINEAR;
AddressU = clamp;
AddressV = clamp;
};

struct VertexShaderInput
{
float4 Position : POSITION0;
};

struct VertexShaderOutput
{
float4 Position : POSITION0;
};

VertexShaderOutput VSOutline(VertexShaderInput input)
{
VertexShaderOutput output;

output.Position = input.Position;

return output;
}

float4 PSOutline(VertexShaderOutput input, float2 pixel:VPOS) : COLOR0
{
float2 uvPixel = (pixel + 0.5) * float2(1.0 / 1280, 1.0 / 770);

float4 finalColor = tex2D(glowSampler, uvPixel);

return finalColor;
}

technique Outline
{
pass Pass1
{
    AlphaBlendEnable = TRUE;
    DestBlend = INVSRCALPHA;
    SrcBlend = SRCALPHA;

    VertexShader = compile vs_3_0 VSOutline();
    PixelShader = compile ps_3_0 PSOutline();
}
}

Draw method:

            GraphicsDevice.SetRenderTarget(renderTarget);
            GraphicsDevice.Clear(Color.Black);

            scene.RenderGrid();
            playerList.Render();
            scene.RenderObjects();

            GraphicsDevice.SetRenderTarget(null);

            renderTargetTexture = (Texture2D)renderTarget;

            for (int l = 0; l < resourceLoader.GlowShader.CurrentTechnique.Passes.Count; l++)
            {
                resourceLoader.GlowShader.Parameters["glowTexture"].SetValue(renderTargetTexture);

                resourceLoader.GlowShader.CurrentTechnique.Passes[l].Apply();
                renderQuad.Render();
            }


texts: Can Inspector interactions be used with UNET

texts:
SyncVar and RPC calls allow a UNET server to send messages to clients, but these messages are not triggered if the server-side change comes from the inspector or a custom editor (and presumably any non-MonoBehaviour).

EG I use the inspector to change a SyncVar - only the server is updated.
Or press a CustomEditor button which calls a method marked with Target/ClientRpc - it will just execute that method on the server.

What is the best way to call UNET networking functions from Inspector GUIs and non-MonoBehaviour code?


texts:
I am using WinForms Sample downloaded from microsoft website. The problem is, that the model loading time is quite long, using:

contentBuilder.Add(ModelPath, ModelName, null, "ModelProcessor");
contentManager.Load<Model>(ModelName);

even a simple model, such as a cube with no textures, takes 4+ seconds to load. Now, I am no expert on this, but is there anyway to decrease loading time?

EDIT:

I've gone thru the code and found out that calling contentBuilder.Build(); ,which comes right after contentBuilder.Add() method takes up most of the time.


texts: Has "Killer Game Programming in Java" by Andrew Davison been rendered useless? What new tutorial should I follow?

texts:
Its pathetic how it was created in 2005 not so long ago when the Java 3D 1.31 API was released. Now after downloading the source code off the books website and implementing it onto my work-space it cant run. (The 3D Shooter Ch. 23) I downloaded Java 3D 1.5 API, installed it- went back to my source code and javax.media ect.., and EVERY imported class within the game simply couldn't be resolved... they are all outdated..

Please do not say how its meant for a positive curvature in your game development skills. No ~ I got the book to understand how to code 3D textures/particle systems/games. Without seeing results how can I learn?

If there is still hope for this book please tell me. Otherwise what other books match this one in Game Programming? This one was very well organized, documented and long. I am not looking for a 3D game prog. book on Java. Rather one that has the same reputation as this one but is a bit newer..


texts:
My camera looks like this:

I am trying to add 2D polygons to the screen based on the percentage that they take up of a 1920x1080 pixel canvas. Therefore, I calculate this and then use Camera.ViewportToWorldPoint() to determine the world point for the mesh vertices. Below you can see how I declare vertices and uvs (I am confident my triangles are correct) for the polygon.

foreach (var point in poly.path)
    {
        uv.Add(new Vector2((float)(point.X - envelope.left) / (envelope.right - envelope.left), (float)(point.Y - envelope.bottom) / (envelope.top - envelope.bottom)));
    }

I assume this is the correct way to calculate the uvs since they are basically the percentage that vertices lie within the bounds of the polygon's bounding envelope.

Here is what I am not so sure on. When I set the vertices like so (assume temp is the array of vertices used):

        var temp = new List<Vector3>();
    var envelope = GetEnvelope();
    foreach (var point in path)
    {
        var vect = new Vector3((float)(point.X - envelope.left) / (envelope.right - envelope.left),
            (float)(point.Y - envelope.bottom) / (envelope.top - envelope.bottom), 1.0f);

        temp.Add(camera.ViewportToWorldPoint(vect));
    }
    return temp.ToArray();

everything works and the polygon is displayed to my screen except it scales so that the polygon draws as though the viewport is the entire envelope. I expect this, however it is not the functionality I want. So instead I try and declare vertices like so in order to have the polygon displayed in its correct relative position on the screen:

var temp = new List<Vector3>();
    foreach (var point in path)
    {
        var vect = new Vector3((float)point.X/1920,
            (float)point.Y/1080, 1.0f);

        temp.Add(camera.ViewportToWorldPoint(vect));
    }
    return temp.ToArray();

however when I set the vertices this way, I no longer see the meshes being rendered. My goal with changing the code to this is to have the polygons be their true size on the screen as they are on the 1920x1080 canvas rather than being skewed as they are in the code that I said was working. Am I misunderstanding how vertices and uvs relate?

Thank for any help!


texts: Should I use threads to check sockets for multiplayer game?

texts: In a multiplayer game does the code to get/send info from/to sockets reside in the game loop or does it belong in its own thread?


texts: What is the license you need to publish to Xbox 360 from Unity3D?

texts:
I have a license for deploying and releasing games using XNA.
What is the license I need to deploy and publish games using Unity3D, and how do I get it?
I have found very little and unclear information about how to publish to Xbox360 from Unity3D, and I can't come up with search words to get this information.


texts:
I'm writing my own renderer in pure java without any external libraries. I'm using per-pixel rendering. I'm rendering an image with this method:

public void renderImage(int x, int y, RawImage image) {
        int[] img = image.getPixels();

        if (x >= surface.getWidth() || y > surface.getHeight())
            return;

        for (int i = 0; i < image.getWidth(); i++) {
            int xp = x + i;
            if (xp < 0)
                continue;
            if (xp >= surface.getWidth())
                return;
            for (int j = 0; j < image.getHeight(); j++) {
                int yp = y + j;
                if (yp < 0)
                    continue;
                if (yp >= surface.getHeight())
                    break;
                int pos = xp + yp * surface.getWidth();
                if (pos < 0 || pos >= pixels.length)
                    continue;
                pixels[pos] = blendMode.getColor(img[i + j * image.getWidth()], pixels[pos]);
            }
        }
    }

But if I render 500 images (with the size of 128x128) my FPS drops down to around 7. Is there anyway to make this more efficient?

The blendMode.getColor() is the blending I implemented. In this example I'm using additive:

public int getColor(int c1, int c2) {
        float a = (float) ((c1 & 0xff000000) >>> 24) / 255f;
        int red = (int) ((c1 & 0x00ff0000) * a + (c2 & 0x00ff0000)) + BlendMode.tint;
        int grn = (int) ((c1 & 0x0000ff00) * a + (c2 & 0x0000ff00)) + BlendMode.tint;
        int blu = (int) ((c1 & 0x000000ff) * a + (c2 & 0x000000ff)) + BlendMode.tint;
        return 0xff000000 + (red > 0x00ff0000 ? 0x00ff0000 : red) + (grn > 0x0000ff00 ? 0x0000ff00 : grn) + (blu > 0x000000ff ? 0x000000ff : blu);
    }

Thanks for any help!


texts: Implementing single and muliplayer without messing everything up

texts:
I don't know a good way to implement single and multiplayer in a game without messing up the whole project structure.

Should I create separate classes for single and multiplayer entities or is there a clever programming pattern I can't find for this situation?

Let's make a simple example of my problem.

Let's say I want to make a pong clone with single and online multiplayer, how should I go about this?
Make separate classes for both modes?

I read somewhere that the MVC pattern might be a good choice in this case but I'm not sure how to implement it correctly.

Should I create a Player data class and then multiple controller classes for example: PlayerControllerSingleplayer,
AIController,
PlayerControllerMultiplayerSelf,
PlayerControllerMultiplayerOpponent.

And then a PlayerRenderer view class?

I've read some articles about mvc previously but still don't know really much about it or how to do it correctly in my case.

I will be using libgdx and probably kryonet for the networking if that might be important.

Thanks for every piece of advice in advance!


texts:
I have a humanoid avatar and it's animation controller.
I also have two different human meshes, they're quite similar.
When I use the generic avatar and it's controller in the animator the meshes
shot out into the sky and perform their animation correctly.
The animations run normal they just move in weird directions and don't stay in their original locations.
How to fix it so the mesh doesn't move far away and retain original position?


texts: Find friend groups in a virtual social graph

texts:
In my game, "people" form bonds through common interests.  A person may have 1 or more interests, and a certain weight (0f - 1f) attached to it.  Every now again, when 2 people are close to one another, relationships are formed based on common interests.  E.g., if I have interests such as "Movies, Cheese, and Art", and you have "Movies and Cheese", then we have a pretty strong bond.

This is all working great, and over time, all the people in my game have some sort of bond with others.

What I'd like to do now, is construct social groups in a somewhat efficient manner (my game has an asynchronous task manager, so if the calculation is somewhat heavy, it's not a show-stopper).  My current theory is to pick a person, look at his or her relationships, and then try to slowly build a graph to match as much like-minded people as possible.

I'm not 100% sure how to do this.  I was thinking of comparing interests with common friends, but wondered if there was a better way?  Currently relationships are stored as a person identifier, and then a list of (up to) 5 relationships, which contain their identifier, plus the weight.

The end result that I'd like, is a bunch of "groups" of like-minded people, that have been fed from this initial map.

What I'm looking for needs to be quite performant (with the caveat that I do have an asynchronous task manager), but the end result is that over time, social groups are constructed within which are people best suited to "hang out" with one another, based on their shared interests.


texts:
I have a compound object, consisting of a b2Body, vector-graphics and a list polygons which describe the b2body's shapes. This object has its own transformation matrix to centralize the storage of transformations. So far everything is working quiet fine, even scaling works, but not if i scale around a point.

In the initialization phase of the object it is scaled around a point. This happens in this order:

transform the main matrix
transform the vector graphics and the polygons
recreate the b2Body

After this function ran, the shapes and all the graphics are exactly where they should be, BUT:
after the first steps of the b2World the graphical stuff moves away from the body.
When I ran the debugger I found out that the position of the body is 0/0

the red dot shows the center of scaling. the first image shows the basic setup and the second the final position of the graphics. This distance stays constant for the rest of the simulation.

If I set the position via

myBody.SetPosition( sx, sy );

the whole scenario just plays a bit more distant for the origin. Any Idea how to fix this?

EDIT::

I came deeper down to the problem and it lies in the fact that i must not scale the transform matrix for the b2body shapes around the center, but set the b2body's position back to the point after scaling. But how can I calculate that point?

EDIT 2 ::

I came ever deeper down to it, even solved it, but this is a slow solution and i hope that there is somebody who understands what formula I need.

assuming to have a set polygons relative to an origin as basis shapes for a b2body:

scaling the whole object around a certain point is done in the following steps:

i scale everything around the center except the polygons
i create a clone of the polygons matrix
i scale this clone around the point
i calculate dx, dy as difference of clone.tx - original.tx and clone.ty - original.ty
i scale the original polygon matrix NOT around the point
i recreate the body
i create the fixture
i set the position of the body to dx and dy

done!

So what i an interested in is a formula for dx and dy without cloning matrices, scaling the clone around a point, getting dx and dy and finally scale the vertex matrix.


texts:
I'm trying to get my .blend object into Unity but for some reason I see it differently in Unity than in Blender.

I was trying to solve the problem and someone said that I have to go to the edit mode, then mesh, then change the normals but that is not working for me.

Here is what I mean:


texts: Trivial and efficient sprite animation in Unity

texts:
I'm looking for an efficient way to create and use simple sprite animations in Unity.

My situation is the following: I have lots of entities (thousands) which need to be animated. These entities have the same (identical) animation running, which involves just sprite swapping. The animation loops endlessly. The following gif represents an example of what I need. In this example, a single animated object is placed on each tile.

Because of the number of objects, I would prefer to not have an animator-animation combo on each, and I would prefer not to have a MonoBehaviour on each. The overhead from both of these solutions will be way more than the game could handle. The required effect requires just a looping sprite-swapping animation, which can simultaneously run on thousands of objects. The gif above was made with animator-animation combos on each object.

The features offered by Unity's Animator component are great, however way beyond what I need here and thus the overhead is not worth it.

Optimisations I am aware of:

Disabling animators when zoomed out.
Disabling animators on objects which are out of view.
Merging multiple objects into a single one which spans multiple tiles (does not apply due to nature of game)
Writing my own sprite swapping animation component (not inherited from MonoBehaviour, similar in idea to this code), placing it on each item. Then creating an AnimationController object (inherited from MonoBehaviour), which updates all instances of my sprite swapping component at regular intervals. This is the solution I will likely go for if nothing else comes up, however involves hand-crafting animations, delays between sprites and such, which will be time consuming.

I feel as though others have surely come across this problem before, so I'm wondering how you solved it. Please also let me know if using Unity's built-in animator-animation system is in fact less resource intensive in this situation than I think.

Thank you!


texts: Player animation mismatches its movement input

texts:
I am using the code below to have the character's directional movement match its movement animations but when the player model has a non-zero y-axis rotation, the animations become mismatched.

Code:

    moveVector = new Vector3 (movX, 0, movZ).normalized * (movementSpeed * (1 - pInv.totalMass/20)) * (1 + bonusSpeed);

    animBector = pBody.transform.rotation * moveVector;
    moveVector = gameObject.transform.rotation * moveVector;

    pAnim.SetFloat ("moveSpeed", movementSpeed/2);
    pAnim.SetFloat ("Vertical", animBector.normalized.z);
    pAnim.SetFloat ("Horizontal", animBector.normalized.x);

Note that pBody is the mesh body of the playerObject and is a child of gameObject. The gameObject does not rotate since this is a top-down project & the moveVector = gameObject.transform.rotation * moveVector; part ensures the player moves towards its respective parts of the screen on pressing a directional button.

e.g.
forward input while facing North will display a forward animation;
forward+right input while facing North East will display a sideways (or strafe) animation, the correct one should be a forward animation.


texts:
I am building a pool game, and I want to make the cue rotate around the white ball.

Here is the live code:

http://199.26.84.223/nocol.html

Here is the code for the white ball:

balls = game.add.group();
balls.enableBody = true;
balls.physicsBodyType = Phaser.Physics.P2JS;
wball = balls.create(350, 240 , 'ballW');
wball.body.setCircle(15);
wball.body.setCollisionGroup(wballCollisionGroup);
wball.body.collides([wballCollisionGroup, ballsCollisionGroup , sidesCollisionGroup , holesCollisionGroup , playerCollisionGroup]);
game.physics.p2.setImpactEvents(true);

Here is the code for the cue, which I call player:

    player = game.add.sprite( 0   , 0   , 'player');
    game.physics.p2.enable(player , true );
    player.enableBody = true;
    player.body.setCollisionGroup(playerCollisionGroup);
    player.body.setZeroVelocity();
    player.body.createBodyCallback(wball, ballHit , this);
    player.anchor.setTo(-0.5, 0.5);
    player.pivot.x = wball.x +150;
    player.pivot.y = 0;

    player.body.x = wball.x  ;
    player.body.y = 240 ;

The problem is that all pivot or anchor does is change the sprite image position. I got the cue to appear in the right place by using both pivot/anchor and it seems to work fine... the cue was rotating around the ball, but after enabling debug mode here is what I saw:

Basically only the position of the image has been changed but the sprite still rotates around the center which is the red part. If I run this code, the ball and cue are already colliding and the ball jumps around without player doing anything.

How can I rotate the cue around the ball without them colliding?


texts: Verifying game completion knowing players id

texts:
I work at a school and I am producing a simple game for language learners via RPG Maker.

All students have a unique student # that their processor has access to.

At the moment, I am imagining an end-game NPC providing the successful student with a special number that they will then screen capture and submit to their teacher. The number is based on a secret algorithm that uses their student #, so each "end-game number" is unique. The teacher can then verify that each submitted number is the correct end-game number for any given student.

Is there a better way for me to verify whether or not each student has successfully played through the game?


texts:
I've been trying to develop shaders that would allow me to easily display text on screen using a font texture. I've previously written shaders that simply drew the text on screen and I passed the exact coordinates for the vertices and UV coordinates to the shaders. With my new shaders, I'm trying to pass just a single point for each letter, representing the bottom left corner each letter, as well as a single point for the UV coordinate of the letter, representing its location on the font texture. I then use a geometry shader to generate the triangles and UV coordinates necessary to draw the letters. Here is my code for the shaders:

Vertex Shader:

#version 330
layout(location = 0) in vec2 vertexPosition;
layout(location = 1) in vec2 vertexUV;
layout(location = 2) in float textSize;
uniform unsigned int textureX;
uniform unsigned int textureY;
out VertexData
{
    vec2 uv;
    float textSize;
} outputData;
void main()
{
    // Represents the bottom left corner
    gl_Position = vec4(vertexPosition, 0.0f, 1.0f);
    // Convert the UV coordinates from [0, textureX - 1] to [0, 1]
    outputData.uv = vertexUV / vec2(textureX, textureY);
    outputData.textSize = textSize;
}

Geometry Shader:

#version 330
layout(points) in;
layout(triangle_strip, max_vertices = 6) out;
uniform unsigned int textureX;
uniform unsigned int textureY;
in VertexData
{
    vec2 uv;
    float textSize;
} inputData[];
out FragmentData
{
    vec2 uv;
} outputData;
void main()
{
    float textureWidth = 1.0f / textureX;
    float textureHeight = 1.0f / textureY;
    // Calculate the vertices
    vec2 brCorner = vec2(gl_in[0].gl_Position) + vec2(inputData[0].textSize, 0.0f);
    vec2 tlCorner = vec2(gl_in[0].gl_Position) + vec2(0.0f, inputData[0].textSize);
    vec2 trCorner = vec2(gl_in[0].gl_Position) + vec2(inputData[0].textSize, inputData[0].textSize);
    vec2 uvBR = inputData[0].uv + vec2(textureWidth, 0.0f);
    vec2 uvTL = inputData[0].uv + vec2(0.0f, textureHeight);
    vec2 uvTR = inputData[0].uv + vec2(textureWidth, textureHeight);
    gl_Position = vec4(tlCorner, 0.0f, 1.0f);
    outputData.uv = uvTL;
    EmitVertex();
    gl_Position = gl_in[0].gl_Position;
    outputData.uv = inputData[0].uv;
    EmitVertex();
    gl_Position = vec4(trCorner, 0.0f, 1.0f);
    outputData.uv = uvTR;
    EmitVertex();
    EndPrimitive();
    gl_Position = gl_in[0].gl_Position;
    outputData.uv = inputData[0].uv;
    EmitVertex();
    gl_Position = vec4(brCorner, 0.0f, 1.0f);
    outputData.uv = uvBR;
    EmitVertex();
    gl_Position = vec4(trCorner, 0.0f, 1.0f);
    outputData.uv = uvTR;
    EmitVertex();
    EndPrimitive();
}

Fragment Shader:

#version 330 core
in FragData
{
    vec2 uv;
} inputData;
out vec4 color;
uniform sampler2D textureSampler;
void main()
{
    color = texture2D(textureSampler, inputData.uv);
}

When I call glGetUniformLocation for the textureSampler uniform in my fragment shader, I get a valid uniform location back. However, when I call glGetUniformLocation for textureX  and textureY, glGetUniformLocation returns -1. When I searched for what could cause this, the main cause of this issue is usually the compiler optimizing the variable out as it's not used. I don't believe this to be true in my case, but I have no idea what could be causing glGetUniformLocation to return -1 for this.

Edit: After reading Andon M. Coleman's excellent answer on how active uniforms are determined, I discovered the issue. The name of the struct the geometry shader outputs and the name of the struct the fragment shader accepts are different-

Geometry Shader:

out FragmentData
{
    vec2 uv;
} outputData;

Fragment Shader:

in FragData
{
    vec2 uv;
} inputData;

After changing the structs to share the same name, I am able to get a valid uniform location back.


texts: World & client listening, use multi-threading or multi-process?

texts:
My game is based on a client / server architecture where client only sends input and receives server output.

Server has to keep track of the game, updating the world etc. But also listen to clients and their input. The server accepts input for 100ms and then processes all the input,sending the result (the output) back.

What would be the most optimal in terms of performance. Have two processes, one for the game and one for listening to clients for input and sending output back. Or go full multi-threading.

I read on how to communicate between processes and it didn't seem very optimal (Sockets, RMI, file sharing).


texts: Camera (pole cam) implementation problem

texts:
In my project I have simple scene graph to render whole scene and Bullet physics SDK to provide physics simulation.

Each rendered object is represented as scene node. Camera always has target and located behind this target. Target can be any scene node.

First, I want to describe my rendering pipeline.

1)When time to render whole scene, we calculate view matrix from target's world matrix. We take offset vector in order to locate camera behind targeted scene node and transform it to scene node world's coordinate. Then add position of target with transformed offset vector. Finally, get inverse matrix of scene node. This method always is called before rendering whole scene.

HRESULT CameraNode::SetViewTransform(Scene *pScene)
{
    //If there is a target, make sure the camera is
    //rigidly attached right behind the target
    if(m_pTarget)
    {
        Mat4x4 mat = m_pTarget->VGet()->ToWorld();
        Vec4 at = m_CamOffsetVector;
        Vec4 atWorld = mat.Xform(at);
        Vec3 pos = mat.GetPosition() + Vec3(at);
        mat.SetPosition(pos);
        VSetTransform(&mat); // Set normal matrix and calculate inverse matrix
    }
    m_View = VGet()->FromWorld(); // Get inversed matrix
    pScene->GetRenderer()->VSetViewTransform(&m_View);
    return S_OK;
}

2)Then, when time to render particular scene node, we calculate projection matrix and send it to the vertex shader.

Mat4x4 CameraNode::GetWorldViewProjection(Scene *pScene)
{
     Mat4x4 world = pScene->GetTopMatrix();
     Mat4x4 view = VGet()->FromWorld();
     Mat4x4 worldView = world * view;
     return m_Projection * worldView;
}

I have next problem, when I calculate view matrix from target's world matrix and locate target on coordinate ( x = 0; y = 10; z = 1) it started to fall due to physics and jerk/twitch. [1]

When I set view/camera matrix only offset position. Scene node falls without jerking/twitching. [2]

How I can fix this jerking/twitching when camera is following the scene node ?

I suppose that it is problem of matrices multiplication, when Bullet SDK sets new coordinates to scene node. But I have no idea how it can be solved.


texts: Unity2D: Child class inheriting onCollisionEnter() methods

texts:
I may be an idiot for asking this but I can't seem to solve it myself, I have a GenericWeapon class which has a onCollisionEnter() method which I want applying to all child classes which inherit from it, here is the code:

public void onCollisionEnter(Collider target){
    Debug.Log("Collided with player!");
    if(target.GetComponent<Player>()){
        bc2d.enabled = false;
        rb2d.Sleep();
        equip(target.GetComponent<Player>());
    }
}

My child class is the following:

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

public class RangedWeapon : GenericWeapon
{
    // Start is called before the first frame update
    void Start()
    {
    }
    // Update is called once per frame
    void Update()
    {
    }
    public void attack(){
    }
}

and my in GameObject has the RangedWeapon class as a component however the GameObject does not seem to be picking up any collisions with the player. Could someone point out where I'm going wrong with this?


texts: Getting a 2D "pixel" cloud to follow a mouse

texts:
I'm working on a 2D game trying to get a "cloud" of a few hundred tiny cubes or discs to follow my mouse cursor without overlapping each other.

However, using the physics engine introduces performance sluggishness as the number of discs grows and the collision detection is generally wonky.

Is there an easy way to optimise the engine for this kind of thing? If not, would I be better off just switching the engine off and writing something of my own? (Clutching at straws here, but:) Are there any good resources or examples on how to do this?


texts:
I'm started a XNA project to make a game similar in gameplay to Super Spy Hunter on a NES, which is used as a feature reference. The first thing I thought of is how to store and display level. Currently I'm thinking of using some tile graphics editor and custom pipeline for drawing level. I'm not sure however, that all is possible to implement every feature of reference game, but at least it's a start.

Question is, looking at a given gameplay video, can you think of any possibly better approach then to design level using a tiles?

By "better approach" I mean which will be either easier to work with, which will be more "natural" for this kind of game. The doubt comes mainly from a huge technology gap between then (1990) and now. So there is possibility that using current cpu power this could be done easier.

Update 1. As I continue study reference game and @ashes999 correctly mentioned procedural generation also comes into my mind. I began to think game logic is something like (simplified):

while next road section exist:
    get road section data;
    set road generation options (borders type, road type, etc);
    set road section lenght;
    while not end of a section:
        generate road;
        apply pseudorandom eye candy stuff;

this all looks like a pretty good data driven algorithm.


texts: Achieve a red lighning effect in unity for a 2d game

texts:
Effect that im refering to:
http://youtu.be/jaBY83WvS3M#t=05m36s

How could I achieve this kind of red lightning/flashing/shadowy effect in Unity3D for a 2D game? I'm trying to think of a way but I'm not that good with shaders or the particle system if thats even the right way to do it.

So I'm looking for any advice on how to achieve this or point me to the right direction.


texts: In 2D, how can I improve character rotation using raycasts when dealing with sharp/convex edges?

texts:
Edit:

After making some edits to my polygon collider (based on @Alex F's suggestion), I can indeed confirm that sharp, convex corners are causing the buggy rotation. For now I've decided to only rotate my character if its moving, so standing on a corner when velocity.x = 0 won't cause my collider to rotate rapidly. However, this seems like a band-aid fix, and I'm still wondering if there's a better way to handle these edges. Resuming movement after idling on a corner still causes some buggy behavior, and I'm concerned that this will compound once my rotations become more complicated or frequent:

Original question:

I'm quite inexperienced with quaternions and rotating, so I'm not entirely sure if this issue has to do with my code, the collisions shown in this question, or my game design.

What I'm trying to achieve is "smooth" rotation of my character's collider based on  the normal of the current surface. I've been creating a custom raycast controller in 2D from the ground up, and already know how to find all kinds of information from rays, such as the current angle of a sloped surface. My controller is coming along quite nicely, and rotation is one of the last things I'd like to tackle. It should be able to handle sloped box colliders, but also irregular ground shapes that require something like a polygon collider.

I've been somewhat successful, having learned that I shouldn't set my character's z-rotation directly, but instead update my entire transform.rotation with a method like Quaternion.Lerp. This has worked generally well, but I'm running into issues on irregular ground, and on corners.

Notice the smooth transition from flat to sloped surfaces, but that my collider rotates rapidly when the raycast hits a corner:

Movement is still somewhat smooth on irregular terrain, but there is a noticeable shakiness at times. Sometimes my character's collider rotates rapidly as well (end of gif):

I suspect that the shakiness on the irregular terrain is just my collider getting "caught" on the many edges that the polygon collider creates. I just don't know if this is happening because I could be doing something differently in my code, or if I need to edit the polygon collider, or is caused by something else entirely. Perhaps raycasting isn't the best way to achieve my desired behavior.

[SerializeField]
private float speed = 5;
[SerializeField]
private float gravity = -20;
[SerializeField]
private LayerMask collisionMask;

private BoxCollider2D boxCollider;
private Vector2 velocity;
private Vector2 groundNormal;

private void Awake()
{
    boxCollider = GetComponent<BoxCollider2D>();
}

private void Update()
{
    float playerInput = Input.GetAxisRaw("Horizontal");

    velocity.x = playerInput * speed;
    velocity.y += gravity * Time.deltaTime;

    MoveCharacter(velocity * Time.deltaTime);
}

private void MoveCharacter(Vector2 velocity)
{
    //Rotate the character
    Quaternion targetRotation = Quaternion.FromToRotation(Vector2.up, groundNormal);
    transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, 0.5f);

    groundNormal = Vector2.zero;

    CollideBelow(ref velocity);
    transform.Translate(velocity);
}

private void CollideBelow(ref Vector2 deltaMovement)
{
    float rayLength = 1;
    Vector2 rayOrigin = transform.position;

    RaycastHit2D hit = Physics2D.Raycast(rayOrigin, -transform.up, rayLength, collisionMask);
    Debug.DrawRay(rayOrigin, -transform.up * rayLength, Color.red);

    if (hit)
    {
        velocity.y = 0;
        deltaMovement.y = -(hit.distance - boxCollider.size.y * 0.5f);

        groundNormal = hit.normal;
    }
}


texts:
So first of all, let me start off by saying that I am not in this to make money as of right now. I'm a novice - however I would like (in the frture) to be able to earn some extra cash on the side with my games.

I have several ideas for what my first game could be and then I started considering the platform on which my game should run.

So I started thinking

iOS & Android mobile devices already have a built-in store that everyone uses. This means that even if my game doesn't get a lot of attention (and doesn't reach the highest position on the market) everyone would still be able to find my game on the same platform.

How is this possible with games made for web or even desktop?

Are the chances of making money of web and desktop as big as on the mobile market?


texts: Simple way to post score from my game to Facebook and Twitter?

texts: What's the best and simple way to post score from my game to Facebook and Twitter with store link in cocos2d-x?


texts: Unity - Transforming horizontal distance between two spriteRenderers to set UnityEngine.UI.Button width to this distance

texts:
In my Unity scene, I have a couple of spriteRenderers and a UnityEngine.UI.Button called thisButton. The spriteRenderers are spread horizontally across my scene. I want to change the button width to span from the leftmost spriteRenderer to the rightmost spriteRenderer.
To do this, I have subtracted the x-Coordinate of the rightmost spriteRenderer (fRightEndingPosition) from the x-Coordinate of the leftmost spriteRenderer (fLeftStartingPosition).
float fLeftStartingPosition = leftmostSpriteRenderer.transform.position.x;
float fRightEndingPosition = rightmostSpriteRenderer.transform.position.x;
float fButtonTargetWidth = fRightEndingPosition - fLeftStartingPosition;

Then, I try to set the width of thisButton to the value of fButtonTargetWidth by doing
RectTransform buttonSize = thisButton.GetComponent<RectTransform>();
buttonSize.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, fButtonTargetWidth);

However, when I try to use this as the width of my button, the result is not correct. I am pretty sure this has something to do with different types of coordinates being used for the spriteRenderers and the button (world, screen, viewport, etc.), but I haven't been able to figure this out on my own.
In one specific example fLeftStartingPosition is -1.1, and fRightEndingPosition is 1.1. In my scene, a button that spans this distance has a width of roundabout 40 on its RectTransform. So clearly, setting the width of this RectTransform (buttonSize) to fButtonTargetWidth (2.2) in code results in a button that is way to narrow. In fact, after setting it's width to 2.2, it is not visible at all.
How do I transform this distance of 2.2 to the desired width of roundabout 40, in a way that this distance would be transformed correctly, no matter what the actual value of fButtonTargetWidth is?


texts: How can I implement a scrolling text ticker?

texts: How can I implement a right-to-left scrolling text ticker in libGDX (like stock tickers)?


texts: How can I save state from script in a multithreaded engine?

texts:
We are building a multithreaded game engine and we've encountered some problems as described below.

The engine have 3 threads in total: script, render, and audio. Each frame, we update these 3 threads simultaneously. As these threads updating themselves, they produce some tasks and put them into a public storage area. As all the threads finish their update, each thread go and copy the tasks for themselves one by one. After all the threads finish their task copying, we make the threads process those tasks and update these threads simultaneously as described before. So this is the general idea of the task schedule part of our engine.

Ok, well, all the task schedule part work well, but here's the problem:

For the simplest, I'll take Camera as an example:

local oldPos = camera:getPosition()  -- ( 0, 0, 0 )
camera:setPosition( 1, 1, 1 )        -- Won't work now, cuz the render thread will process the task at the beginning of the next frame
local newPos = camera:getPosition()  -- Still ( 0, 0, 0 )

So that's the problem: If you intend to change a property of an object in another thread, you have to wait until that thread process this property-changing message. As a result, what you get from the object is still the information in the last frame.

So, is there a way to solve this problem? Or are we build the task schedule part in a wrong way? Thanks for your answers :)


texts:
First of all, the XNA Framework works on my computer, but I do not wish to use it for reasons.  I am set with the task of coding my own sprite sheet class.  I do not know if a class is the best way to do it, but I have tried my best.  I am not an advanced C# user, but I know enough to have got this far with the class:

class Spritesheet
{
    //w: 50px h: 96px
    Bitmap sheet;
    int fWidth, fHeight;
    int framesPerRow, framesPerCol;
    int x, y;
    public Bitmap curState;

    public Spritesheet(string path, int width, int height)
    {
        sheet = new Bitmap(path);
        fWidth = width;
        fHeight = height;
        framesPerRow = sheet.Width / fWidth;
        framesPerCol = sheet.Height / fHeight;
        curState = new Bitmap(path);
    }

    public void playSprite(int frameSpeed, int endFrame, int row)
    {
        int curFrame = 0;
        int count = 0;
        bool play = true;

        while (play)
        {
            if (count == (frameSpeed - 1))
            {
                curFrame = curFrame++ % endFrame;
                Rectangle cloneRect = new Rectangle(row * fWidth, curFrame * fHeight, fWidth, fHeight);
                System.Drawing.Imaging.PixelFormat pFormat = sheet.PixelFormat;
                Bitmap curState = sheet.Clone(cloneRect, pFormat);
            }

            count = (count + 1) % frameSpeed;
        }
    }
}

I am aware that class variables should never be public, but this is just until I get it working.  My Form1 looks like this:

public partial class Form1 : Form
{
    Spritesheet player = new Spritesheet("Content/Sprite/charzera.png", 700, 270);

    public Form1()
    {
        InitializeComponent();
        pb_char.Image = player.curState;
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        player.playSprite(5, 13, 0);
        pb_char.Image = player.curState;
    }

}

The form builds but doesn't launch now.  I am just lost on where to go with this now.  I want a spritesheet to be created for the main character, and from there I want to be able to pick a row based on what action is happening and then the game to run along the row animating the PictureBox that I am using for the character.

I've never done this before, so its probably completely wrong.


texts:
How to make an object look at the target direction not at the target himself ?

public Transform target;

void Update() {

    transform.LookAt(target);
    float step = 2 * Time.deltaTime;
    transform.position = Vector3.MoveTowards(transform.position, target.position, step);

}


texts:
I'm creating a typing game where the words fall from the top of the screen to the bottom. How do I set the words to spawn so that they adjust to the screen size of the device. This is the code that I have:

Vector3 randomPosition = new Vector3(Random.Range(-2.5f,2.5f), 7f);
GameObject wordObj = Instantiate(PrefabWord, randomPosition, Quaternion.identity, Canvas);

But this doesn't scale properly with the size of the device.

Edit:

When I change the randomPosition to "new Vector3(Random.Range(0,Screen.width), 7f);", the words spawn all over the screen and not just within the bounds of the camera or canvas.

I have also switched the platform to android and selected 480x800 resolution. And in the old script where the random values were hardcoded from -2.5f to 2.5f, some of the words were getting clipped depending on the resolution selected.


texts:
This is less of a question aimed at developing a game and more about the technology behind it. A number of gaming journalists and pro gamers (both in the tournament and the home entertainment sector) often hammer on the matter that any first or third person game should have a way to change the field of view, and I agree with them. The main reason they mention this is because a pretty large number of players get motion-sickness related headaches and eyestrain if they play with an overly constrained field of view.

I can understand if an indie developer does not allow this due to budget constraints, because they need to add support to the engine for that. However, a number of developers use high profile third party engines like Frostbite, Unity, Unreal, or Cryengine, but don't offer an option for changing the field of view.

Why shouldn't I permit changing the field of view, if the technology allows for it?


texts: How could I format my C# code using Checkstyle?

texts: Is there any possible way to check my C# code with Checkstyle in the context of Unity?


texts: Can Java be used for developing games for Android in Unity3D

texts: I only know Java Programming Language and no other. Can I develop games for Android in Unity3D using Java?


texts:
I have a UI panel with a scollrect inside, which I fill dynamically. It can only be moved vertically.
When filling this scollrect, the content jumps up and down for one frame, creating a weird look. When I check for the VerticalNormalizedPosition of the scrollrect after each added GameObject, it always tells me, the position is 1. When I check for the position in an Update method, it sometimes gives me a small rounding error. Instead of 1 it's somewhere between 0.9999995 and 0.9999998. The height of the content holder is less trhan 2000 units, whereas the jumps seems to be more than 2000*0.9999998.

I tried to set the VerticalNormalizedPosition of the scrollrect to 1 every frame which didn't help. It also didn't help setting it after every newly added GameObject. Locking vertical scrolling also didn' help.
Is this soley a rounding error and I can't do anything about it, or is there a way to stop this jump from happening?
Here you can see the jump happening in 0.05 speed


texts: Resource loader for an HTML5 and Javascript game

texts:
I have made a type to shoot game using HTML5, Javascript and Ruby on Rails.
Here is the link for the game Tweetraitor

I wanted to make a loader for resources (sounds, images) when the game starts. Currently when the game starts the background image takes time to load and it does not look good. This loader should load all the assets those are used later in the game.

Code for the game is here: Tweetraitor on GitHub

In the current version, all the images are loaded using js in an erb file which controls the game logic. Is there a better way to do this?


texts: Search app store for similar games on pc

texts:
I want to search the app store for similar games so I can see how much competition there will be for any apps I am thinking of designing.

Knowing how many clones/similar games there are plus there prices and success rate would go a long way in deciding which ideas to take forward.

Is there anyway to do this easily on a pc (I do not have an iPhone)


texts: How can I position different size creatures in a group automaticly

texts:
I'm doing a game (in xna) on my free time, as I'm not in the game market, I'm pretty sure I'm missing something that would help me get this right.  Think of Ogre Battle. A group of unit moves, and when they cross enemy, a small automatic Final fantasy battle starts for 2 or 3 round.

I'm struggling on how I should place the creatures in the combat screen. A fight started. (final fantasy rpg battle ) The creatures part of this group needs to be positionned in a 16x16 grid. Some creatures are bigger and use larger than 1x1 square.

I create a class called group to represent groups of creature walking around. So far, I decide to put in an array of 4x4 representing the grid. How do I go around and position all the creatures on that grid and make sure they arent stepping on top of each other ?

some pseudo code I have right now :

 Class Group
  array(4,4) of rectangle
  array(4,4) of creature

  Public sub Update()
    adjustCreaturePosition
  end sub
End class

Class Creature
    CombatValue as List of Enum.Qualities
    PreferedPosition as Enum.Position
    Range as smallint( 1 = melee, 2 = small range, 3 = long range)
End Class

 Public Enum Position
  Front
  Middle
  Back
 End Enum

 Public Enum Qualities
    Melee
    Armored
    Strengh
    Dodge
    Siege
    SmallRange
    DPS
    Nuker
    Controller
    Buffer
    Dex
    Int
    Sick
    Weak
End Enum

In the update of the group class , I need to create a function to set the position of all creatures when the combat starts.

Private Sub AdjustCreaturePosition()
       ' check the "prefered position" of all creep ( front, middle, back).
       ' if there are no more spot left for a creature, I need to check which creature is moved to the middle row based on A. if one of the creature on the front row will be able to attack on middle row ( based on the range ). If no unit can attack from the middle row,  the weaker one is send on the back ( the sum of their combatValue list)
    Next
End Sub

I got no idea how I'll do the AdjustCreaturePosition in a smart way yet. but lets say it works.
Where I'm at a loss is how should I handle large creature who needs a 2x2 grid ?


texts: How do you rotate RigidBody2D along a given access using velocity and not transform?

texts:
I am trying to rotate my player along the centre of the world in Unity3D.
All the tutorials and references I have looked through till now have left me to this working code:

void MoveAlongCurve(bool moveClockwise) {
    if (!moveClockwise)
        timeCounter += moveSpeed*Time.fixedDeltaTime;
    else
        timeCounter -= moveSpeed*Time.fixedDeltaTime;

    float x = Mathf.Cos (timeCounter);
    float y = Mathf.Sin (timeCounter);

    transform.position = new Vector3 (distFromCentre*x, distFromCentre*y,0);
}

Also this seems to work fine as well:

transform.RotateAround (Vector3.zero,new Vector3(0,0,1),speed);

Now my question is how do i move my player using velocity? I was forced to keep my body as 'kinematic rigidbody2D' however I want my player to be a 'dynamic rigidbody2D'.

My reason for this is several:
1. Movement via velocity makes it independent of the timeCounter.
2. Dynamic Bodies enable collisionDetection. Hence it is basically a requirement for my game.

Thank you so much for taking the time to read this! Any suggestions or nudges in the right direction would be greatly appreciated and if you find anything wrong in my code or approach please comment!


texts: How can I make a global scoring system in C++?

texts: How do I make it so that in a multiple-level game the score will stay where it was from the previous level?


texts: Game-Design: Turn-based ship-to-ship combat with *simultaneous* movement

texts:
Im currently building a browser-based game, which basicly goes like:
2 Players place starships on a 2d plane, move them around and fire their guns at each other.
The game is divided by turns, each one has 2 phases
Phase 1 - Movement
Phase 2 - Firing

Summarized, it is basicly a table-top game played in the browser.

Due to earlier experience i want to avoid the issue of Players talking movement in turns, i.e. Player A moves ship 1, B moves 2, A moves 3, B moves 4. It makes for some awkward experience and delays the actual firing Phase too Long.

So instead im aiming for something along the lines of "Both Players move all their ships in one step and see the actual Resolution of ALL ships movement afterwards - they then can issue weapons fire".

The Problem is: Manovering ships in this game is Kind of important, because weapons have different arcs of fire and ships different parts of structure. So ideally i want to make "smart" movement choices in order to bring as many weapons as possible to bear while also protecting damaged parts of my fleet / ships.

However, with parallel, "blind" movement, i cant really make smart choices.

What would be a way, from a game-design Point of view, to allow parallel, blind movement while also ensuring impactful choices ?


texts:
I want to code a board game that name is Okey and mostly popular in Turkey. http://en.wikipedia.org/wiki/Okey

But i have got some problems about AI.

Firslty let me explain the game..

The game is played by 4 players.

In this game there are 106 tiles, 2 of them are fake joker. Other 104 tiles are divided 4 colours generally green, black, blue and red. All colours have two sets of tiles. A set ise contains 13 tiles that numbered sequentially 1 to 13.

Each player start 14 tiles (one is start 15 and starts first) and throws one of the most unwanted tile the next player. Next player can get this tile or can get another tile from stack in the middle of table. The game played in anti-clockwise..

The aim of this game is find the valid sequence of 14 tiles as soon as possible. Player can align tiles by sequential numbers in the same colour until 13. For examle Green 1, Green 2, Green 3. There is an exception here, 1 can be follow to 13. For example Red 12, Red 13 and Red 1 is a valid set. But Red 13, Red 1 and Red 2 is not valid.

Or player can align tiles by colors in the same number. For examle Green 1, Black 1, Red 1, Blue 1.

Each set need to be 3 or more tiles to be valid and each of this set named as "Per". Less then 3 tiles is not valid for the finish. A valid finish set can be like this. G: Green, B:Blue, R:Red, BL: Black G1|G2|G3 B2|R2|BL2 R9|R10|R11|R12 BL13|R13|G13

Last thing, when starting game a tile selected to determine joker (okey). For example if you select Blue 3; Blue 4 will be joker (okey) and player can use this tile instead of any tile that player needs to win or complete a set (per).

Of course these rules are general rules and summarized to explain question. If you can read English you can check this link for more information http://tr.wikipedia.org/wiki/Okey or translated page by Google Translate http://translate.google.com/translate?js=n&prev=_t&hl=en&ie=UTF-8&layout=2&eotf=1&sl=tr&tl=en&u=http://tr.wikipedia.org/wiki/Okey

So which AI algorithm that i can used? I searched for minimax theory and alpha beta pruning. But these theories are generally about 2 players game like chess or tic-tac-toe.

Original Question is at stackoverflow: https://stackoverflow.com/questions/4419628/creating-a-board-game-ai


texts:
We are working on a minecraft-like block-based engine/lib. Lately I've started working a blocky-clouds as in minecraft;

So it appers that in minecraft, clouds are not procedural. I'm still looking if it is viable to procedurally generate blocky-clouds.

I tried something like but it doesn't quite fit for clouds.

float octave1 = SimplexNoise.noise(x * 0.004f, 1000, z * 0.004f) * 0.5f;
float octave2 = SimplexNoise.noise(x * 0.003f, 1000, z * 0.003f) * 0.25f;
float octave3 = SimplexNoise.noise(x * 0.02f, 100, z * 0.02f) * 0.15f;
this.Clouds[x, z] = (octave1 + octave2 + octave3 > 0.6);

Any ideas or suggestions?


texts: fast 3d point -> cuboid volume intersection test

texts:
Im trying to test whether a point lies within a 3d volume defined by 8 points. I know I can use the plane equation to check that the signed distance is always -1 for all 6 sides, but does anyone know of a faster way or could point me to some code?

I should add that ideally the test would produce 3 linear interpolation parameters which would lie in the range 0..1 to indicate that the point is within the volume for each axis (since I will have to calculate these later if the point is found to be in the volume)


texts:
I am very new to python I started to make a pong game, but can't get it to let me hold down the buttons for the paddel to move, im using the turtle not pygame
 def paddle_a_up():
   y = paddle_a.ycor()
   y += 15
   paddle_a.sety(y)

def paddle_a_down():
    y = paddle_a.ycor()
    y -= 15
    paddle_a.sety(y)

def paddle_b_up():
    y = paddle_b.ycor()
    y += 15
    paddle_b.sety(y)

def paddle_b_down():
    y = paddle_b.ycor()
    y -= 15
    paddle_b.sety(y)

# binds
wn.listen()
wn.onkey(paddle_a_up, "w")
wn.onkey(paddle_a_down, "s")
wn.onkey(paddle_b_up, "o")
wn.onkey(paddle_b_down, "i")

also I cant seem to get my arrow up and down to work with the binds so thats why im using "o" and "i" if you have a solution for that too, I'm very grateful, take care!


texts: Rotation of a cylinder between to spheres in R3

texts:
I want to connect two spheres with the coordinates [ax, ay, az] and [bx, by, bz] with an cylinder which is placed in between the spheres an rotated.
For the placement I calculate the center of the two spheres and place the cylinder there.
The cylinder spawns parallel to the Z-Axis. Since I want to connect the spheres, I thought I first need to rotate either on the Y- or X-Axis and then on the Z-Axis.

I learned that combination of rotations is easiest with quaternions since you only have to multiply them, so I decided to use quaternions. So I get the angle of the first rotation(on Y- or X-Axis) and get the quaternion of this rotation, and then I get the angle of the second rotation on the Z-Axis and the quaternion of this rotation. Then I multiply them in order to get the combined rotation, and use the resulting quaternion on the cylinder.

This seems to work, but here is the problem: the more I get to the +-45° angle between the two spheres, the more I get something which looks like an offset to me. Furthermore, the greater the distance between the points is, the more offset I get. I checked the two quaternions which are multiplied, and both are indeed a +-45° rotation about the correct axis (in this example -45° in radians)

Since this is very hard to explain with words, here are some screenshots:

This is the 45° rotation:

This is with more distant points:

The red dot on the ground marks the x-axis, the blue dot marks the y-axis.The simulation was started without gravity.

So my question is, why is this happening? And if anyone knows why, how can I fix it? Since I am new to game development and orientation in R3, this could be something obvious to an experienced developer.

I am using c++ with the Open Dynamics Engine and the drawstuff library for my program.

EDIT:
This is the resulting quaternion

EDIT2:
I add the calculation of the angles. This whole thing is in an for-loop.

        /* lengths[i][j] is the distance between two points, taking the coordinates of point 1 minus the coordinates of point 0

        For example:
        lenghts[0][0] is the distance of the x-coordinates of the first two points which should be connected
        lengths[0][1] is the distance of the y-coordinates of the first two points which should be connected
        lengths[0][2] is the distance of the z-coordinates of the first two points which should be connected
        */
        angle = -pioff + atan(lengths[i][2] / lengths[i][1]); // pioff is M_PI_2 = pi/2 = 1.5708
        if(isnan(angle))
        {
            angle = 0.0;
        }
        dQFromAxisAndAngle(Q1, 1, 0, 0, angle); // get quaternion1 of angle
        cout << "   quat Q1: " << Q1[0] << " + i" << Q1[1] << " + j"  << Q1[2] << " + k"  << Q1[3] << endl;
        cout << "   angle Q1: " << angle << endl;
        cout << "   x axis: angle = -" << pioff << " + atan(" << lengths[i][2] << " / " << lengths[i][1] << ") = " << angle << endl;
        angle = -atan(lengths[i][0] / lengths[i][1]);
        if(isnan(angle))
        {
            angle = 0.0;
        }
        dQFromAxisAndAngle(Q2, 0, 0, 1, angle); // get quaternion2 of angle
        cout << "   quat Q2: " << Q2[0] << " + i" << Q2[1] << " + j"  << Q2[2] << " + k"  << Q2[3] << endl;
        cout << "   angle Q2: " << angle << endl;
        printf("   connect xyz1(%f/%f/%f) and xyz2(%f/%f/%f)\n", xyz1[i][0] + c[0], xyz1[i][1] + c[1], xyz1[i][2] + c[2], xyz2[i][0] + c[0], xyz2[i][1] + c[1], xyz2[i][2] + c[2]);
        cout << "   z axis: angle = - atan(" << lengths[i][1] << " / " << lengths[i][0] << ") = " << angle << endl;

This is the output I get. Lenght[][] output are the elements of lengths[i][j]


texts: How can I do fast Triangle/Square vs Triangle collision detection?

texts:
I have a game world where the objects are in a grid based environment with the following restrictions.

All of the triangles are 45-90-45 triangles that are unit length. They can only rotate 90°. The squares are of unit length and can not rotate (not that it matters)

I have the Square vs Square detection down and it is very very solid and very fast (max vs min on x and y values)

Wondering if there are any tricks I can employ since I have these restrictions on the triangles?


texts: Retrieve 3d models from a server in unity

texts: I have 10 3d models which are about 8mb each..Now, should I store these 3d models in my apk or will it be wise to store it in a server and then retrieve it?.If so, how can I do that?


texts: I'm making a Shooter game like "1943" and "Jamestown". I am Using Visual Basic 2010. I was wondering how I would make the  background scroll up to simulate moving forward. I would also like it to scroll slightly to the left and right when the player reaches the sides of the screen. Finally, how would I make this efficient? I was thinking about using a animated GIF or making a looping BitMap. Please could someone help me out?


texts: How do I access the "Ascii Start Offset" property of a Font at runtime?

texts:
When I create a "Custom Font" in Unity 4.6.1, I get this:

"Ascii Start Offset" indicates which character is first in the font. I've set it to 48 (the zero character) by hand, and my custom font works fine just for numbers.

But I'm creating these fonts at runtime as a build step. I access "Character Rects" through Font.characterInfo in code:

font.characterInfo = infoList.ToArray();

So the names don't necessarily align. But I can't figure out how to change "Ascii Start Offset" at runtime; none of the available members of Font class seem to be related. Is this possible?


texts:
I am working on a car race game and just implemented a ghost sprite for replaying past races.
I use a physics engine and after much reading I came to the conclusion that the best way to store the ghost data for replay would be to record the car's position and rotation at given timepoints, as for example described here: https://gamedev.stackexchange.com/a/8380/26261.

But what would be a good way to find those timepoints during replay?
An example would be a record with this data:

time: +3.19932 (seconds since race start)
position:  180,40 (position at that time)
rotation: 30.4 (rotation at that time)

But I have several problems with that:

When I replay, it's unlikely that I reach the exact timepoint at 3.19932 again - more likely, I will have a timepoint around 3.1 and have to find the closest matching record. When interpolating, even the closest matching above and below. This sounds very inefficient and time consuming?
In which list structure could I store these records for a later replay? An array? Doesn't that mean that search time for records matching a certain time will increase the longer the race is?
Which frequency should I use for timepoints? Each frame would be -I guess- overkill, rather I should save i.e. every nth frame and interpolate in between, which makes the storage questions in 2. even more difficult.

So is this idea even the right approach? If yes, how could I efficiently store and retrieve the data?
Please note that I generally would like to go with using the data structure above, not deterministic gamestates and recording user input etc.

Thanks for any help!

EDIT:
I realise I should describe the environment I use: Cocos2D for iPhone.
There is a method update:(ccTime)delta. Ideally, this method would be called every 1/60 seconds, but there is no guarantee - delta is the actual time passed since the last gametick and could be a lot more or less than 1/60.
It is in this method where I would like to store the current gamestate.


texts:
I'm trying to use arrax textures with opengl 3.3 since this the target version for my application. So I have to use the glTexImage3D() method instead of glTexStorage3D(). The problem is, if I use glTexImage3D() instead of glTexStorage3D() the screen is always black. The other way round, everything works. Here is how I create the array texture:

public ArrayTexture(int width, int height) {
    this.width = width;
    this.height = height;
    this.arrayTextureHandle = GL11.glGenTextures();
    GL13.glActiveTexture(GL13.GL_TEXTURE0);
    GL11.glBindTexture(GL30.GL_TEXTURE_2D_ARRAY, arrayTextureHandle);

        //Works perfect
        GL42.glTexStorage3D(GL30.GL_TEXTURE_2D_ARRAY, 1, GL11.GL_RGBA8, width, height, 10);
        //Doesn't work with these parameters
        //GL12.glTexImage3D(GL30.GL_TEXTURE_2D_ARRAY, 0, GL11.GL_RGBA8, width, height, 10, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer)null);

    GL11.glBindTexture(GL30.GL_TEXTURE_2D_ARRAY, 0);
}

public void addTexture(ScrollingSprite... sprites) {
    if(zLayerCounter + sprites.length <= MAX_LAYERS) {
        GL13.glActiveTexture(GL13.GL_TEXTURE0);
        GL11.glBindTexture(GL30.GL_TEXTURE_2D_ARRAY, arrayTextureHandle);

        Arrays.asList(sprites).forEach(sprite -> {
            sprite.getTexture().getTextureData().prepare();
            GL12.glTexSubImage3D(GL30.GL_TEXTURE_2D_ARRAY,
                0,                      //Mipmap number
                0, 0, zLayerCounter++, //xoffset, yoffset, zoffset
                width, height, 1,          //width, height, depth
                GL11.GL_RGBA,                 //format
                GL11.GL_UNSIGNED_BYTE,       //type
                sprite.getTexture().getTextureData().consumePixmap().getPixels()); //pointer to data

            GL11.glTexParameteri(GL30.GL_TEXTURE_2D_ARRAY, GL11.GL_TEXTURE_WRAP_S, sprite.getTextureWrapS());
            GL11.glTexParameteri(GL30.GL_TEXTURE_2D_ARRAY, GL11.GL_TEXTURE_WRAP_T, sprite.getTextureWrapT());
        });

        GL11.glBindTexture(GL30.GL_TEXTURE_2D_ARRAY, 0);
    } else {
        throw new IllegalArgumentException("Maximum number of textures reached!");
    }
}


texts:
In a gbuffer I store a diffuse color in following texture:

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);

I want to store an integer data which represents a pixel type in channel A.
Here is part of the fragment shader:

#version 420
in vec2 tCoord;
layout (location = 2) out vec4 diffuseColorData;
uniform sampler2D texture0;
uniform int pixelType;
void main(void)
{
    diffuseColorData.xyz = texture(texture0, tCoord).xyz;
    diffuseColorData.w = pixelType;
}

Is it possible ? How to decode a pixel type when reading from texture ?

Edit

I use a pixel type to choose a shading function (standard shading - int 1, shading with normal maps - int 2, shading with uniform color - int 3). I need to use additive blending because of multiple light sources (point lights).

I changed the code as you suggested:

diffuseColorData.w = pixelType / 4.0;

In the next fragment shader I read a data this way (I post only relevant part of the code):

uniform sampler2D texture2;
vec4 diffandPixelType = texture(texture2, texCoord);
vec4 diff = vec4(diffandPixelType.xyz, 1.0);
float pixelType = diffandPixelType.w * 4.0;

if(pixelType == 1)
{
    outColor = shadingfun1(/*arguments*/)
}
else if(pixelType == 2)
{
   outColor = shadingfun2(/*arguments*/)
}
else if(pixelType == 3)
{
   outColor = shadingfun3(/*arguments*/)
}

The code doesn't work properly and I don't know how to explain that. What is wrong ?

I found other solution which works perfectly, but it require extra integer texture in the gbuffer:

glTexImage2D(GL_TEXTURE_2D, 0, GL_R8I, width, height, 0, GL_RED_INTEGER, GL_INT, NULL);

//fragment shader
layout (location = 4) out int shadingData;
uniform int pixelType;
shadingData = pixelType;

//fragment shader
uniform isampler2D texture6;
int pixelType = texture(texture6, texCoord).x;

if(pixelType == 1)
{
    outColor = shadingfun1(/*arguments*/)
}
else if(pixelType == 2)
{
    outColor = shadingfun2(/*arguments*/)
}
else if(pixelType == 3)
{
    outColor = shadingfun3(/*arguments*/)
}


texts: Is there a way of moving the transform of an object relative to it's geometry

texts: I have a number of objects (mostly prefabs) that have their transform origin in inconvienient places such as about 1 unit to the left of the actual geometry or somewhere inside an object where it's hard to see. Is there any way to move these transforms without actually moving the object itself? This is in 3D.


texts: Variable timeStep not working as intended

texts:
I've been working on a game in javascript/html5 (through typescript) using my own little library. This library uses a variable timestep since I plan on using it on mobile devices, and I was under the assumption that this will help keep things roughly the same on both (I know there's probably a debate on that, but that's not what I'm asking).

The problem is, using my variable timestep, I'm getting wildly different entity speeds. I am working out how long in seconds the frame took to update and draw, then multiplying entity velocities by this.

I'm running the game loop using setInterval. It's set up to run at 60fps, so a 16(ish)ms interval.

var now: Date = new Date();
timeInterval = (now.getTime() - Engine.lastUpdate.getTime()) / 1000;
Engine.lastUpdate = now;
Input.update();
currentScene.update();
draw();

Player class:

        update() {

        //W:87 S:83 A:65 D:68

        this.velocity.y += this.gravity;

        if (SandLib.Input.isKeyJustDown(16)) {
            this.gravity *= -1;
            this.jumpPow *= -1;
        }

        this.velocity.x += this.accel;

        if (this.velocity.x > this.maxVel) {
            this.velocity.x -= this.decel;
        }

        if (this.x > this.cameraMoveZone) {
            SandLib.Engine.currentScene.camera.x = this.x - this.cameraMoveZone;
        }

        //Collision code here

        if (SandLib.Input.isKeyJustDown(32) && this.onGround) {
            this.velocity.y -= this.jumpPow;
            this.velocity.x *= this.jumpBoost;
            this.onGround = false;
            Main.jumpSnd.play();
        }

        if (this.y > 800 || this.y < -800) {
            this.die();
        }
        super.update();
    }

Any ideas why this gives a faster speed on lower fps devices.


texts:
I have battle effects that can be anywhere from 50-150 frames (running at 60fps). I need to be able to draw each frame of the battle effect as an additive layer onto my game.

A frame could look something like these:

What is the best way to store these and render these for performance and memory considerations?

Here is a sample battle animation. Warning it is a 1920x2720 texture:

http://i.imgur.com/pTf9TkY.png


texts:
I'm currently using SDL2 on Android and that's my first experience with that library (to be honest, mainly chosen because I'd like to learn it).
What is puzzling me is how to deal with different resolutions and density-independent pixels, for I cannot figure out which is the recommended approach to create images and let them look decently on screen on the most of the devices.

Unfortunately, googling around I've not been able to find a decent example or a bunch of information sufficient to clarify the doubts.
It seems that the most common suggestion is to choose a fixed size virtual resolution for the content rectangle, thus draw on top of it and finally resize it to the actual one, but it would be appreciated to know if this one is really a widely used approach and if there are some others that are more suitable.

Thank you.


texts: equivalent texture function to texture2D in OpenGL-ES?

texts:
I'm trying to figure it out how can implement the same result using texture2D. The result expected is a luminescence operation but I couldn't replicate the same functionality using texture2D for iOS. could you explain a little bit what the texture function does with the 20.0 value?

float logAvgLum = exp(texture(hdrSampler, texCoord ,20.0).a) ;


texts: Create a 2D spline-based Terrain in Unity3D

texts:
I want a 2d terrain in Unity that can be edited in Scene view. I have come across a github repository which nearly serves my requirements, but I am not sure what exactly I can do to make it have another texture on the top layer to create an illusion of the platform.

I have searched extensively and didn't find any methods to do this. I am not looking for Paid solutions like Ferr2D, Zippy Terrain 2D Terrain Creator etc.

I want the the terrain to be able to have curves and splines etc.


texts:
Other contexts in which this was done I'm sure have been answered for this kind of problem before. But this has thus far been a 2 week long impasse of wittling down all the other suggestions I've seen and not one has worked.

I've got a prefab GUI with a singleton instance based script, which automatically disables itself at the start (I've tried commenting that out to see if that was it). The gui has a title text, body text, and 8 buttons. The script is meant to allow other scripts for interactive objects to safely access it and "start a conversation", using a coroutine.

I created a script for the buttons that I attach to each, that when called should set a public bool to true, indicating it was clicked, this bool is polled among the buttons to see which button the user clicked. This is then return to the script which called the GUI, and the GUI closes or waits for the next piece of the conversation. I've set everything to be enabled, and removed anything that disabled the components. I've made sure that the buttons are higher in the hierarchy than everything else, to make sure nothing else was intercepting the clicks.

I'm unable to get OnClick, OnMouseOver, OnMouseDown to be called. Debug messages never show. I've tried setting OnClick as part of the GUI where you select a function from the list, and inside of the button's code by adding a listener manually to the button. I've tried IPointerExitHandler, IPointerDownHandler, etc, also never seen anything come back from the methods.

I've tried several other methods to date to get which button I clicked, such as ray casting when the mouse button is down and checking the name for the button's name, however it always passes through to the terrain. I've tried getting the button's rect and using Rect.contain with the mouse position to see if the mouse was over the button when clicked, but this never returns true.

I'm really interested in seeing a working example where something like this has been done, so that perhaps if that doesn't work, I could at least start hunting down what might be causing a functioning example to fail, as I've no idea what's wrong at this point. Not to vent but this is very frustrating, and I feel it could be made so much simpler.

Thank you all for any help you can give, you guys have been very wonderful with my short time here.


texts: Is Pushdown Automata better for user input than Hierarchical State Machine?

texts:
I saw an example of code using HSM for user input, but to me it seems that Pushdown Automata would be a better fit. I'm confused.

If I'm right, then after Hierarchical State Machine exits a superstate via substate, and comes back, it must start at a default state and cannot return to the substate it left earlier(unless of course, that default state is the substate). And then, if I'm right, Pushdown Automata could replace that need, as it can return to an older state via its stack and discarding of states.

Say I have an actor I control, and it has several states that use user input as transitions. It supports jumping, ducking, standing and walking. When you are standing or walking, you can jump or duck, after which you return to the state you were in, thus standing or walking. If I were to use an HSM to prevent the duplication of code, I could not return to the last state. But if I used a Pushdown Automata, I could put jumping or ducking on top of the stack and discard them after they are done, and that way I could return to the state I was in.

Correct me if I'm wrong, and suggest me better options for user input than these two, if there is. Also, please don't post options like duplicating the FSM as the amount of states could vary and my question is related exactly to how to prevent that duplication.

Thanks,

me.


texts:
Update: this question is general, not specific to Sprite Kit or a single language/platform.

I'm toying with Sprite Kit with an idea to make a 2D side-scroller. Now the backgrounds for the maps are going to be hand-drawn and surely bigger than retina display, so the maps could span more than 1 screen in both axis.

I imagine loading such a huge image could mean trouble and I don't plan to use tiling. I'm not sure how Sprite Kit splits images bigger than max texture size, if it does. I could split the images myself and use more sprites for each part of the background.

What is the usual way to handle this?


texts: Box2d stopping the movement of an object

texts:
I am in the process of making a game and I need an object to move only when the buttons are pressed. I have a method that begins the movement, and so far I am ending the movement of an object by having destroying the body of the object. The problem that I have is that every subsequent time that I try and move the ship the program crashes.

Here is my code.

Initializer method that contains the shipBody and its definition.

-(id) init
{
    if( (self=[super init])) {

        CGSize s = [CCDirector sharedDirector].winSize;

        //create spaceShip sprite and add it to the layer
        _ship = [CCSprite spriteWithFile:@"theShip.gif" ];
        _ship.position = ccp(s.width/2, 1.25*_ship.contentSize.height);
        [self addChild:_ship];

        //create the world
        b2Vec2 gravity = b2Vec2_zero;
        _world = new b2World(gravity);

        //create ship body
        b2BodyDef shipBodyDef;
        shipBodyDef.type = b2_dynamicBody;
        shipBodyDef.position.Set((s.width/2)/PTM_RATIO, (1.25*_ship.contentSize.height)/PTM_RATIO);
        shipBodyDef.userData = _ship;

        if(_shipBody == NULL){
        _shipBody =_world->CreateBody(&shipBodyDef);
        }

        //create ship shape
        b2PolygonShape shipShape;
        shipShape.SetAsBox(_ship.contentSize.width/PTM_RATIO/2, _ship.contentSize.height/PTM_RATIO/2);

        //create Ship definition and add to body
        b2FixtureDef ShipShapeDef;
        ShipShapeDef.shape = &shipShape;
        ShipShapeDef.density = 3;
        ShipShapeDef.friction =0;
        ShipShapeDef.restitution =0;
        _shipFixture = _shipBody->CreateFixture(&ShipShapeDef);

        ......
}

When the paddle is pressed and movement happens logic. THis is related to the problem since this is how movement of a sprite is achieved in the first place.

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //Set up a way for touches to be turned into locations onscreen
    NSSet *allTouches = [event allTouches];
    UITouch *touch = [allTouches anyObject];
    CGPoint location = [touch locationInView:[touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location ];

    //check to see if Left Paddle is being pressed
    if (CGRectContainsPoint([_paddle1 boundingBox], location)){
        b2Vec2 force = b2Vec2(-5,0);
        _shipBody->ApplyLinearImpulse(force, _shipBody ->GetPosition());
        }
    if (CGRectContainsPoint([_paddle2 boundingBox], location)){
        b2Vec2 force = b2Vec2(5,0);
        _shipBody->ApplyLinearImpulse(force, _shipBody->GetPosition());
    }
}

Logic for when touches stop. This is the problem area since destroying the shipBody stops all future movement as well.

-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    _world->DestroyBody(_shipBody);
 }
 @end


texts:
Obviously, lists automatically create their own index. So basically I wouldn't need this function at all. But I figured it was safer in case my list index ever changed (e.g. adding a new item at the beginning of the list, would shift the index numbers for all the other list items).

public EmpireAgentView ShowEmpireView(int eIndex)
{

    foreach (EmpireAgentView e in EmpireViews)
    {
        if (e.EmpireIndex == eIndex)
        {
            Debug.Log("Showing Empire for Agent: " + e.AgentName);
            return e;
        }
    }

    Debug.LogError("No EmpireAgentView Found for that empire: " + eIndex);
    return new EmpireAgentView(9999);
}

So in this case, I added the property "EmpireIndex" to the EmpireAgentView object. So now, whenever I need to access a specific EmpireAgentView from the EmpireViews list, I would use ShowEmpireView(1) instead of EmpireViews[1].

Each EmpireAgentView object has unique information about the same Agent object. For example, where the Agent is currently located. If we have 4 empires, than there will be 4 EmpireAgentView objects in the Agent class. Each empire has their own idea of where the Agent is currently located, so I need to be able to access the specific empires data on this agent. Right now, I assign a simple int called EmpireIndex to each EmpireAgentView, so that I can make sure I got the right view for the right empire. If i simply used EmpireViews[3], and that list rearranged itself somehow, (like adding an EmpireAgentView object to the beginning of the list, presumably) than all that information would be mixed up for the empires.

Is that the best way of doing that? is there a better way of finding it? Or am I being TOO careful, and just need to not add new EmpireView's to the beginning of the list? (I'm new to C#, is there anything else that would change the index of a list item?)


texts: Most efficient way of drawing a lot of cubes OpenGL ES

texts:
I have to draw a lot of cubes in my OpenGL programme for android. All the cubes have the same size but different colors. I know that calling glDrawArrays is expensive operation so I should call it less as possible. But as I know I have to call it 6 times (one per each side) and since I have more than 500 cubes it's not efficient at all. Does anyone have the idea what to do?

Btw, I am using OpenGL ES 1.0.

I saw that I can use one big VBO but I don't know how to do that.


texts: Required number of images for octagonal tiles

texts:
I'm planing to write a game based on octagon tiles. Currently I'm wondering how many images I really need. That is something about graph theory, I know that, but not only.

I want to connect each side of the eight sides, but in some cases I also want to connect all eight sides or just two so the complexity grows immense. If I'm not totally confused that ends in 88 which is 2048. Well of cause there are already many dublicated e.g. left to right is equal with right to left. When I'm very tricky I can rotate the image of left to right which I rotate by 90° to get top to buttom. I'm sure there are quiet more things like like mirroring.

My question is now how many images do I really need?

Here is my basic idea as image, of cause it still has some problems, as you can see on my image too but I think it should not be too hard to find a simple solution for such cases.