texts: Hybrid App - Game Encyclopedia Image Asset

texts:
An in-game encyclopedia usually consists of entries and images for things related to the game. For example, pokemon's pokedex. Image of Pokemon, text description and so on.

I've happen to encounter a road block of sorts making a game with an "encyclopedia". From my database, each row is one object with several columns as the different property of the objects. (I know that might sound like redundant information to some devs. Don't kill me pls. I'm just trying to be clear.)

It goes somewhere along the lines of:

Name | Rarity | Pattern | Collected
Ramen | Rarity 1 | 1 | Yes
Ramen | Rarity 1 | 2 | Yes
Ramen | Rarity 2 | 3 | Yes
Udon  | Rarity 5 | 1 | No

So the issue here is this: Game Encyclopedias tend to have a black silhouette for items you have yet to collect and it's colored in after you've collected it. Each item can have a 'pattern' on it, making it either differently colored or sparkling. Though, the shape remains constant.

Basically, the silhouettes can just be repeated for each item that is of the same type, for example, all "Ramen" items have the same silhouette so if they aren't collected yet, reuse same image. I thought I could probably tint the images and have a base image (light gray of sort), but if I did that, the entire image tints, even the parts I wouldn't want it to, which includes but is not limited to: white spaces (or transparent), the "bowl" part of the ramen image, possibly added on "sparkle effects" for even rarer items.

I'm currently attempting to achieve this in a game using the Ionic Framework because I recently got into hybrid apps; I think they are pretty fun to develop! And has since learnt angularjs and js in general. No idea the exact process that Cordova (phonegap) uses to convert all of this into android and iOS so I'm sort of looking out for three things:

1) How to link/pair/associate my database with my image asset?
2) How do I specifically tint certain parts of an object/Or overlay two objects over each other, one tinted and one base coloured.
3) Does it work on the mobile platform AFTER it compiles from js to Java. (Only working on android at the moment).


texts: Aligning rotation from a imu9250 to a game object

texts:
I am experimenting with interfacing unity with real world inputs, specifically I have an imu9250, connected to an arduino clone providing rotation inputs ( either quaternion or pitch/yaw/roll) to unity.   (I’m using the DMP functionality of the 9250 to calculate orientation).

The connectivity (over serial for now) works fine, rotating my sensor rotates my game object but I can’t work out how to align my input (programmatically) so that the rotation of the game object rotates in the same direction (in game space).

Any tips/pointers appreciated.

Additional information:

My understanding is that the DMP only uses the Gryo and Accelerometer, not the magnetometer.

I can’t find any other references to the coordinate system used outside of the images above. Not mentions in the data sheet as far as I could see
http://www.invensense.com/wp-content/uploads/2015/02/PS-MPU-9250A-01-v1.1.pdf


texts: What is the Shannon rule/law when talking about game physics?

texts:
I've been reading some articles on game physics and came across subjects such as fixed timestep (article). Some of the articles I read mention the "Shannon rule" or "Shannon law" in relation to the length of the timestep. Example quote:

  Your timestep should be at least 1 / 120 seconds or smaller because of the Shannon rule [...]

Here's an answer here on Gamedev that mentions it. Some quick google searches for "Shannon's law" doesn't seem to yield much result except for this wikipedia article but I'm not sure if that's what is being talked about here.

So what is the Shannon rule / Shannon law?


texts: Does it make sense to use both TCP and UDP at once?

texts:
After reading Is UDP still better than TCP for data-heavy realtime games?, I'm wondering if it makes sense to use both TCP and UDP at the same time, but for different things:

TCP for sending information that is sent infrequently, but should be guaranteed to arrive reliably.
Such as score updates, a player's name, or even the on/off state of a light in the game world.
UDP for transmitting information that is updated constantly and can be lost occasionally, since newer information is always on the way.
Such as position, rotation, etc.

Is this a reasonable idea?
What are the possible drawbacks?
Are there better ways to handle this?


texts: Instantiate Prefab From Script Inside A Canvas

texts:
I am trying to instantiate a Prefab inside a Canvas. Right now, it keeps appearing behind the canvas. I was reading online and it said to set the parent of the GameObject you are trying to instantiate. However, I can't figure out how to get the Canvas component.

My hierarchy looks like this:

My EnemyFormation object has this script attached to it:

public class EnemySpawner : MonoBehaviour {

    public GameObject enemyPrefab;

    void Start () {
        Instantiate(enemyPrefab, new Vector3(0, 0, 0), Quaternion.identity);
        Debug.Log("Spawning enemy");
    }
}

I attach the prefab inside Unity editor. I tried adding this line under Instantiate():

enemyPrefab.transform.SetParent(GameObject.FindGameObjectWithTag("Canvas"), false);

However, I get an error saying it can't convert from Unity.GameObject to Unity.Transform.

How do I make the prefab appear inside the Canvas instead of behind it? Thanks in advance!

This is what it looks like when it creates it in-game: Enemy_Orange3(Clone) is created outside of the canvas and at the bottom left instead of the center. My camera is in the same position and is the same size of the canvas.


texts: Libgdx: How to leave the dialog visible?

texts:
setBtn.addListener(new ClickListener() {
    @Override

    public void clicked(InputEvent event, float x, float y) {
        final Dialog dialog = new Dialog("Settings", skin, "dialog") {
            public void result(Object obj) {
                Preferences prefs = Gdx.app.getPreferences("My Preferences");

                if (obj.equals(2))
                    muteMusic = true;
                if (obj.equals(3))
                    muteMusic = false;

                prefs.putBoolean("music", muteMusic);
                prefs.flush();

            }

        };
        dialog.text("Do you want to play music");
        dialog.button("Yes", 2); //sends "true" as the result
        dialog.button("No", 3); //sends "false" as the result
        dialog.button("Ok", false);

        dialog.show(stage);
    }

});

I want the ok button to be on an another row but if I do dialog.row() like with tables, it won't work, I can't add an empty row
I want the dialog to stay visible on the screen until the ok button is touched, only then I want to call dialog.hide()

I can't do

if (obj.equals(false))
dialog.hide(); // IDE will suggest that i create a local variable called dialog


texts: Change key setting from qwerty to azerty in Unity

texts: How can I change the default key for walking with the player in Unity. At this moment I can do this with A, W, D and S (or something). But because I work with an azerty keyboard, I'll change it to Z, Q, S and D. How can I do this (only for the game)?


texts: Cocos2D - How to move sprite on the X axis, using the accelerometer

texts:
I'm trying to make a vertical shooter, using Cocos2D and a few tutorials. Unfortunately, most tutorials only show how to make an horizontal shooter.

Still, I tried to adapt the code from a horizontal shooter to a vertical one, but am having a few problems. Mainly, my ship keeps moving right, even when the iPhone is sitting perfectly still.

Seeing as I'm a beginner, I'm having trouble pinpointing the exact issue and I'd love if anyone could help me.

Here's my accelerometer method:

-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {

    define kFilteringFactor 0.1

    define kRestAccelX -0.6

    define kShipMaxPointsPerSec (winSize.width*0.5)

    define kMaxDiffX 0.2

    UIAccelerationValue rollingX;

    rollingX = (acceleration.x * kFilteringFactor) + (rollingX * (1.0 - kFilteringFactor));

    float accelX = acceleration.x - rollingX;

    CGSize winSize = [CCDirector sharedDirector].winSize;

    float accelDiff = accelX - kRestAccelX;
    float accelFraction = accelDiff / kMaxDiffX;
    float pointsPerSec = kShipMaxPointsPerSec * accelFraction;

    _shipPointsPerSecX = pointsPerSec;

}

And my update method:

-(void)update:(ccTime)dt {

    CGSize winSize = [CCDirector sharedDirector].winSize;
    float maxX = winSize.width - _ship.contentSize.width/2;
    float minX = _ship.contentSize.width/2;

    float newX = _ship.position.x + (_shipPointsPerSecX * dt);
    newX = MIN(MAX(newX, minX), maxX);
    _ship.position = ccp(newX, _ship.position.y);

}

What could be causing this?


texts: Why are modern open world games so quiet?

texts:
When I first got Skyrim, my friends kept ranting about how great the music was. I found this odd, since I only remembered the same old music only popping up during random encounters. After awhile I just assumed that my installation was broken (for some reason the music files were corrupted or something). Then I saw my one of my friends playing their copy, and lo and behold, their game was just as quiet—with only footsteps sound effects.

Now my roommate's version of Breath of The Wild shows up, and even Legend of Zelda games are following this trend?! What happened? What happened to the obnoxious Morrowind music? The ambient musical feel of each region in Ocarina of Time? Why would game developers eliminate such a powerful tool for creating atmosphere?


texts: Texture2D can't find my sprite - how to setup the content directory in XNA

texts:
So I keep getting told that spr_lives can't be found.  I'm working out of a book and using the samples given to me (have not changed the code or folder structure, so it /should/ work) but nothing's working unfortunately.  I know it's a directory issue but I'm unclear on how to remedy it.

Picture of both code and folder structure:


texts:
Whenever I drag a sprite sheet into unity, it, for whatever reason, distorts. Is there any way to remedy this?
Original

Distorted


texts: Entity Component System - How to implement an object's Transform?

texts:
In designing an entity-component system for my engine, I've come across a little snag in the way of storing and retrieving a particular type of component.

First, let me set clear up a bit of terminology I'm going to use in this question:

I call "Component" a data structure that stores relevant data for a particular system.
I call "System" an aggregation of methods and data structures that makes use of Components to update game state/interface with the user.
An "Entity" is basically just an ID used to retrieve specific components and modify their data in game logic.

Each system owns an (ID-mapped) array of its type of Component (E.g Physics->PhysicsComponent, AI->AIComponent, Rendering->RenderingComponent), so that it can iterate efficiently over data.

Not all components are specifically owned by a system, however. For example, a Transform component stores an object's position, rotation and scale. It's one of the most important parts of an entity (Unity makes it mandatory, even), since it is used by a lot of systems, e.g. Physics, AI, Rendering etc.

This is pretty much the problem I'm facing. Since Transform is used by a lot of other systems, how should I go about retrieving one to use for each Component? One possible solution I see is to make each Component store its own Entity ID. It would be easy to retrieve any component like this, but it wouldn't be that efficient, and it also would go against the concept of a Component as an isolated and independent bundle of data, that isn't aware of any other.

Is there a proper way to solve this problem? Should Transform even be a component?


texts:
I have a cube which I select on mouse and point out the location to throw the cube with trajectory dots.

The code is working fine, but I need to restrict the trajectory dots position on z axis so the user could not be able to throw it towards z axis.

Here is my code

   if (cubePlane.Raycast(camRay, out enter))
            {
                cubeisClicked2 = true;
                fingerPosition = camRay.GetPoint(enter);

                cubeFingerDiff = cubePosition - fingerPosition;
                ShotForce = new Vector3(cubeFingerDiff.x * shootingPowerX, cubeFingerDiff.y * shootingPowerY, 0);
                if (cubeFingerDiff.magnitude > 0.4f)
                {
                    trajectoryDots.SetActive(true);

                }
                else
                {
                    trajectoryDots.SetActive(false);
                }

                for (int dotNumber = 0; dotNumber < NumberOfDots; dotNumber++)
                {
                    x1 = cubePosition.x + ShotForce.x * Time.fixedDeltaTime * (DotSeparation * dotNumber * dotShift);
                    y1 = cubePosition.y + ShotForce.y * Time.fixedDeltaTime * (DotSeparation * dotNumber * dotShift) + (Physics.gravity.y / 2f * Time.fixedDeltaTime * Time.fixedDeltaTime * (DotSeparation * dotNumber + dotShift) * (DotSeparation * dotNumber + dotShift));
                    z1 = cubePosition.z + ShotForce.z * Time.fixedDeltaTime * (DotSeparation * dotNumber * dotShift);
                    Dots[dotNumber].transform.position = new Vector3(x1, y1, 0f);
                }
            }
        }

I set the z axis to zero every where but still able point towards z axis.

Note: It is 3D game not 2D


texts: What's the reasoning behind using "redistributable" packages?

texts:
On Windows, many if not all games require some DirectX package and some VC++ runtime. Others also need OpenAL, wmfaredist, nvidia physx, windows live and probably others.

I'm trying to figure out why do game developers use them. Like what problems are they trying to fix by using them, and how are those problems bigger than the problems they are creating by using them, like the compatibility issues of the VC++ packs, or inconveniencing players.

I'm thinking that it's because these are libraries developed by others, thefor they can save game developers some coding time. That's fine I guess, but then why aren't they including the .dll files directly into the game?


texts: Stencil buffer VS conditional discard in fragment shader

texts:
I have a continuous height-mapped mesh to represent landscape. I also have 1 to let's say 10 wells on this landscape represented by additional models. What I want to achieve is to create an illusion of an actual hole in landscape at the place where the well sits.

I see the solution in two ways:

Draw holes to stencil buffer an then use it in fragment shader to discard landscape fragments.
Send an array of uniforms (vec2) and then conditionally discard fragments if they are near those hole-points.

The question is what way should I prefer if I'm good with rectangular holes and want to get best performance?


texts: Unity 5: Downloading Standard Assets won't work

texts:
I am watching a tutorial on using Unity 5 to make a simple RPG. I need to download Standard Assets. I download Standard Assets from the Asset Store and it wants me to import it into my project. I'm like, 'Fair enough.'
So, in the middle of importing, it crashes and tells me to send a report to Unity, so I do.
I delete it from both my project and Unity itself and try again. IT FAILS.
What is wrong?


texts: Is it possible to construct a cube with fewer than 24 vertices

texts:
I have a cube-based world like Minecraft and I'm wondering if there's a way to construct a cube with fewer than 24 vertices so I can reduce memory usage.

It doesn't seem possible to me for 2 reasons: the normals wouldn't come out right and per-face textures wouldn't work.

Is this the case or am I wrong?  Maybe there's some fancy new DX11 tech that can help?

Edit: Just to clarify, I have 2 requirements:  I need surface normals for each cube face in order to do proper lighting and I need a way to address a different index in a texture array for each cube face


texts: How to move Character according to Camera's look direction?

texts:
Vector3 newPosition = new Vector3(-horizontal, 0.0f, -vertical);
    transform.LookAt(newPosition + transform.position);
    transform.Translate(newPosition * MoveSpeed * Time.deltaTime, Space.World);

I'm developing 3d mobile game, you can look around with hold&sliding the right side of the screen and move with virtual joystick.

Goal;

Moving character to camera's lookDirection

Issue is;

When i push joystick up, character moves to the same direction (world related)

And I'm not good at coding that's why i can't solve the problem myself, i would be glad if you help me


texts: Is studying Alternate Coordinate System required game development?

texts:
I don't know whether or not this question is fit for Gamedev.Stackexchange, but I would like to know :-

I am new to Linear Algebra. I only want to study those parts of Linear Algebra which would be required for making games. Alternate Coordinate System, is it required for making games, or should I just study Vector Spaces and Matrix Transformations?


texts: Change alpha value of the Standard Shader

texts:
I want to edit the Standard shader provided by Unity in order to change the alpha value of a fragment (pixel) according to given parameters I pass to the shader.

For now, thanks to this link, I have been able to :

Retrieve the standard shader,
Retrieve a custom Core.cginc I included in the DEFERRED pass of the custom shader,
Create a custom Editor script to handle the Shader and my custom parameters,
Selecte Fade as the rendering mode of the shader to handle transparency, using the custom editor script,
Create a custom file replacing UnityStandardInput.cginc and changed the references in the Core.cginc file.

But now, I can't seem to figure where to change the alpha value of the fragment. I've tried a ton of possibilities in the Core.cginc file. Changing the color and the map of the Albedo works, but I can't find where the final alpha value is set.

I've browsed the files in the CGIncludes folder in the builtin shaders of Unity.

UnityStandardCore.cginc : Already tried many possibilities (including the returned value of Alpha declared in UnityStandardInput.cginc
CustomInput.cginc : Alpha function, no effect

Since the files are huge, I don't feel it will be useful to copy-paste them here.

Thanks for your help in advance.


texts: How to add Collider to a Line Renderer in unity?

texts:
I have created a semicircle using a line renderer, I need to add a collider to this so whenever enemy objects hit this they get destroyed, how do I do this.
Current Code

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

public class CreateCircle : MonoBehaviour
{
    // Start is called before the first frame update

    public float radius;
    void Start()

    {
        int segments =60;
        int pointCount = segments+1;

        Vector3[] points = new Vector3[pointCount];

        LineRenderer line = gameObject.GetComponent<LineRenderer>();
        line.positionCount = pointCount; //line.SetVertexCount(pointCount);

        for(int i=0;i<pointCount;i++)
        {
            float Deg = (i*60 / segments);
            float Rad = Mathf.Deg2Rad *Deg;

            points[i] = new Vector3 ( Mathf.Sin(Rad) * radius,Mathf.Cos(Rad)*radius,0);
            // Debug.Log(" Point: "+i+" Deg: "+Deg+" Rad: "+Rad+" Vector 3:"+points[i]);
        }
        line.SetPositions(points);

        Mesh lineMesh = new Mesh();
        line.BakeMesh(lineMesh,Camera.main,true);

        MeshCollider lineCollider = line.gameObject.AddComponent<MeshCollider>();

    }

    void OnColliderEnter(Collider col){
        Destroy(col.gameObject);
    }

}
```


texts: Is clipping done before or after projection?

texts:
Is clipping applied after projection or before?

How can it be applied after projection when a vertex is behind the camera and projected therefore mirrored?

At this time I clip the triangle before projection.
For this I create _ a plane which represents the screen and check whether the sides of a triangle intersect with the plane (Basically a ray plane intersection test).

If true then I calculate the intersection point between side and plane and project this new point instead of the vertex behind the plane.
This works though but I just wanted to know whether this is a wrong or right method to do it.


texts: ETC1 Support on android alpha problem (GLSL cocos2d-x)

texts:
I want to support etc1 in my game, but somehow it doesn't work
(I'm using cocos2d-x

C++

 GLProgram* glp = new GLProgram();

glp->initWithVertexShaderFilename("testv.vsh", "test.fsh");
glp->addAttribute(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION);
glp->addAttribute(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR);
glp->addAttribute(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORD);
glp->link();
glp->updateUniforms();

Texture2D* tex = Director::getInstance()->getTextureCache()->addImage("MenuButton_alpha.pkm");

GL::bindTexture2DN(1, tex->getName());
GLuint t1Location = glGetUniformLocation(glp->getProgram(), "tex1");
glp->setUniformLocationWith1i(t1Location, 1);

MySprite->setShaderProgram(glp);

.vsh

attribute vec4 a_position;
attribute vec2 a_texCoord;
attribute vec4 a_color;

varying vec4 v_fragmentColor;
varying vec2 v_texCoord;
varying vec2 v_texCoord2;

uniform sampler2D tex1;

void main()
{
    gl_Position = CC_MVPMatrix * a_position;
    v_fragmentColor = a_color;
    v_texCoord = a_texCoord;
    v_texCoord2 = v_texCoord;

}

.fsh

varying vec4 v_fragmentColor;
varying vec2 v_texCoord;
varying vec2 v_texCoord2;

uniform sampler2D tex1;

void main()
{
    vec3 tex = texture2D(CC_Texture0, v_texCoord).rgb;

    float alpha = texture2D(CC_Texture1, v_texCoord2).a;

    gl_FragColor = vec4(tex.rgb,alpha);
}

Somehow it shows my sprite in the middle but the transparent part is black.
can anyone help me?


texts: Time complexity of solving constraints in physics engine

texts:
Erin Catto mentioned in a talk that solving constraints precisely requires cubic time and quadratic space. What algorithm is he talking about when he mentions cubic time?

pdf of slides with following quote:

  We can model and program our constraints perfectly. Good enough to drive a robot arm on an assembly line or
  launch a satellite into space. Unfortunately for games, we do not have enough cycles to solve constraints accurately.
  Solving constraints precisely requires cubic time and quadratic space. For games we make due with linear time and
  space, so we are constantly wrestling with our solvers. The better you understand constraint solvers, the better
  chance you’ll have of creating robust simulations in your game.


texts:
I am working on cropping a texture in Unity. I have a button, when I click on the button, it takes the photo and the photo gets saved to a folder in the phone. But when taking the picture, I want to provide image cropping functionality for the user.

Here is the sample code to select the particular area for crop.

private Vector3 startPoint, endPoint;
private bool isMousePressed;

private LineRenderer leftLine, rightLine, topLine, bottomLine;

void Start ()
{
    isMousePressed = false;

    leftLine = createAndGetLine("LeftLine");
    rightLine = createAndGetLine("RightLine");
    topLine = createAndGetLine("TopLine");
    bottomLine = createAndGetLine("BottomLine");
}

private LineRenderer createAndGetLine (string lineName)
{
    GameObject lineObject = new GameObject(lineName);
    LineRenderer line = lineObject.AddComponent<LineRenderer>();
    line.SetWidth(0.03f,0.03f);
    line.SetVertexCount(2);
    return line;
}
void Update ()
{
    if(Input.GetMouseButtonDown(0) || isSpriteTouched(spriteToCrop))
    {
        isMousePressed = true;
        startPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }
    else if(Input.GetMouseButtonUp(0))
    {
        if(isMousePressed)
            //cropSprite();
        isMousePressed = false;
    }
    if(isMousePressed || isSpriteTouched(spriteToCrop))
    {
        endPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        drawRectangle();
    }
}

private void drawRectangle()
{
    leftLine.SetPosition(0, new Vector3(startPoint.x, endPoint.y, 0));
    leftLine.SetPosition(1, new Vector3(startPoint.x, startPoint.y, 0));

    rightLine.SetPosition(0, new Vector3(endPoint.x, endPoint.y, 0));
    rightLine.SetPosition(1, new Vector3(endPoint.x, startPoint.y, 0));

    topLine.SetPosition(0, new Vector3(startPoint.x, startPoint.y, 0));
    topLine.SetPosition(1, new Vector3(endPoint.x, startPoint.y, 0));

    bottomLine.SetPosition(0, new Vector3(startPoint.x, endPoint.y, 0));
    bottomLine.SetPosition(1, new Vector3(endPoint.x, endPoint.y, 0));
}

How can save the particular area of rectangle to gallery?


texts: How do I get GL.IssueRenderEvent to work on iOS with Unity 5?

texts:
I'm trying to get GL.IssuePluginEvent to work, according to this: http://docs.unity3d.com/Manual/NativePluginInterface.html

I have a plugin made with this code:

extern "C"
{
    void UnityRenderEvent (int eventID)
    {
        NSLog(@"Got render event.");
    }
}

I can call that function directly from Unity, and it works; I'm sure I've built the plugin correctly, and included it in the project correctly. But when I do GL.IssuePluginEvent(0), nothing happens. Some idea what I could be doing wrong? According to Unity's demo, this is all that has to be done. I think.

I know that in their example, they have it defined as void EXPORT_API, but I found this in their code example:

// Attribute to make function be exported from a plugin
#if UNITY_METRO
#define EXPORT_API __declspec(dllexport) __stdcall
#elif UNITY_WIN
#define EXPORT_API __declspec(dllexport)
#else
#define EXPORT_API
#endif

So on iOS, EXPORT_API becomes "".


texts: Is there a 2d animation authoring GUI for creating C++ games?

texts:
I'm moving from Flash to C++, and am wondering if there are any tools out there that would let me author animation much like Flash does.

Basically I want a GUI that lets me layout sprites and specify keyframes + easing for position, size, rotation, etc., then later be able to load and play these animations from my own code.

I've found a couple promising projects for UI interface animation, but I suspect since they're built for UI they're not optimized for game playback.

I've also found a bunch of animation libraries, but nothing that also provides a GUI for creating the animations.

Being able to animate textures would also be a plus.


texts:
Considering that I have a vector A, and after an arbitrary rotation I get vector B. I want to use this rotation operation in others vectors as well, but I'm having problems in doing that.

My idea do that is to calculate the perpendicular vector C of the plane AB (by calculating AxB). This vector C is the axis that I'll need to rotate. To discover the angle I used the dot product between A and B, the acos of the dot product will return the lowest angle between A and B, the angle ang. The rotation I need to do is then:
-rotate *ang*º around the C axis.

The problem is that I dont know if this rotation is a CW or CCW rotation, since the cos of the dot product does not give me information of the sign of the angle. There's a tip discover that in 2D ( A.x * B.y - A.y * B.x) that you can use to discover if the vector A is at left/right of vector B. But I dont know how to do this in 3D space. Can anyone help me?


texts: How exactly can I calculate time until a ball fall if I know initial and final x and y position of a ball, gravity, delta time, initial dx and dy of a ball and its speed calculated from the formula sqrt(dx ** 2 + dy ** 2)?


texts: Best Way to allow players to "Dye" images without losing color quality?

texts:
I am creating a 2.5D isometric (2D images) game.

I want the players to be able to "dye" their armor, clothes, and other things. I find that grayscaling everything leads to losing out on some of the more "natural" coloring. For example, making a dragon with red/yellow grayscale and then applied overlay color, leads to a purely red dragon with all loss of the secondary color. Meanwhile, dying that same Red/Yellow Dragon Blue, makes it Blue/White which looks great.

The characters in my game do not have a huge variety of equipment. The game is closer to how League of Legends handles characters and graphics. There may be a single type of character (ex. Hero) but multiple outfits for the character as options. I want players to be able to have as much customization as possible in the limited number of "outfits" and characters.

So I want players to be able to select a character, pick one of several weapons, alternate between a handful of costume choices (layered onto the characters), and then dye most of everything (pick a specific metallic color for weapons, pick any color at all for clothing).

If I were to be able to use grayscale without losing some of the coloring, I would.

Here is an example as to what I am talking about:

It is not even possible to "dye" the Dragon, no matter what I use in Photoshop's "Color Overlay" options. Obviously, I am doing it wrong if it is possible to color it better using grayscale. For a color like Green or Yellow or a Lighter Purple, this works okay. For any other color, it destroys the art.

However, it looks much better if I do NOT grayscale it, and instead simply apply a "HUE" color to the original (Red/Yellow) image.

Red Hue

Purple Hue

Now the players could dye the Dragon ANY color, and it would still look great! (The yellow turns white, while the red turns to any color of the rainbow.)

Does this mean that WHITE or BLACK is the best secondary color? Then use some sort of method or shader to change white (secondary) color to something different?

Are there any articles on this complex method of taking a single image, and based on the coloring, dye different pixels?

For the Dragon, would it work best as a White/Black high Contrast Dragon? Is Red/Yellow the best color set? It turns out a lot better for images than a few other colors I tried. Is Grayscale still superior?

Does Photoshop's "Blending Options" not include the method to appropriately "dye" images for a video game? Are there complex Shaders/Methods that allow me to achieve better success?

Note: If GrayScale allows me to reduce the RAM consumption of my images, or prevent loss of quality during lossy compression, that would be something I would seriously consider.


texts:
I'm writing a mobile game where the player has

a limited number of clicks to direct their avatar to the bottom of the map
into a bronze, silver, or gold basket
land on his/her feet, head, or side.

I'd like to take each of these into consideration when determining the score.

On level 231, the lowest possible clicks to get into the bronze is 2, silver is 4, and gold is 7, with a limit of 10 clicks.

So let's say the score is calculated like so:

Basket: 1 point for bronze, 2 for silver, and 3 for gold.
Landing: 3 for feet, 2 for head, and 1 for side.

That means the possible outcomes are:

Bronze: 1, 2, 3, or 4
Silver: 2, 3, 4, or 5
Gold: 3, 4, 5, or 6

Now that's all good because I can make a 1 star 3, a 2 star 4, and a 3 star 5 or 6.

But now, the remaining clicks come into play: I originally wanted them to multiply the score. 2x for 1 click left, 3x for 2, and so on. That means getting a fast bronze is better than getting the harder-to-reach gold. Raising the base scores to 1, 2.5, and 6.25, respectively, messed up the other levels.

Does anybody has a solution I could try? I don't care if the points go into the hundred thousands. I want to reward players more for gold, with other elements to keep them interested and feeling accomplished after player a level.

Thanks!


texts: Does the Facebook app need to be installed to use Facebook for Game Developers?

texts: I just learned about Facebook for Game Developers. I would like to know if I need to have the Facebook app installed in my phone to use Facebook for Game Developers (like I need to install Google play games services in android).


texts: In Godot, how to make a Kinematic body affectable by rigid bodies?

texts:
Background Info

I'm currently following the FPS tutorial from the official site. By the end of Part 1, there is a Player object implemented as a KinematicBody and controlled by player input, and a few cubic blocks scattered around, implemented as RigidBodies. The KinematicBody is moved with the move_and_slide function that takes static colliders into account, so the player is able to stand on the floor and bump into walls.

However, the player can't bump into or stand on the cubes. If you attempt to jump onto a cube, it will slide from under you. If you try to push a cube into a wall, it will glitch around a little, then slide away, without even slowing you down. The cubes have no power to stop the KinematicBody from moving through them.

Question

How can I change the behaviour to make it possible for a KinematicBody to stand on a RigidBody?


texts: Deal with double coordinates and graphics

texts:
I want to draw some vectors and few sprites in a 2D world.Problem is that they should be precise.
For example a vector has position (5000000.65,556666).
That depends on user. He might want to add something at 10,5 or 5000000.65,556666 !

Using a viewport with proper transform I can draw these on screen.
However GDI+ I use works with floats. In case I zoom eg: 2x viewport's translate will be 5000000.65 *2 which wont fit into a float. It gets worse with larger zooms.

Approach 1
One solution seems a write custom matrix with doubles to perform transform from and to screen coords. The downside is that when panning/moving I have to recaclulate all vectors positions

Approach 2
Divide the world in smaller parts. However this complex to me and seems to not take care of all cases.
Is there any better solution ?


texts:
I keep getting this error now in Game Maker:

  FATAL ERROR in
  action number 1
  of  Step Event0
  for object base_enemy:

  Variable base_enemy.hp(100013, -2147483648) not set before reading it.
  at gml_Object_base_enemy_StepNormalEvent_1 (line 2) - if(hp <= 0){

I understand that it's not finding the variable hp in the object base_enemy during Step Event, but I'm not sure why. I think that the parenting I did has something to do with it, because it found hp before further edits to the code. It's set up like this:

base_enemy (top parent);
base_grunt (first child);
obj_grunt (second child)

The hp variable is set in the Create Event of the second child of each unit. Is it possible that the Step Event is checking for hp before the variable is declared?


texts: If I create a pygame, can I later convert it to a .exe for everyone to use?

texts: I was told if I create a pygame, other people would need python/pygame to actually run it. Is that true? Or is there a way I can later convert it to a .exe?


texts: Combine a light and water shader in libgdx glsl

texts:
I am trying to combine a light shader with a water shader in libgdx. Shader programming is not one of my strengths at all.

This is the water effect rendering nicely:

And when I have added the flickering light code I am getting this:

The light is meant to be a flickering white circle and the water should show up. It doesn't.
What I have done so far is try to re-arrange texture binding, combine drawing in one pass. I can render the other scene content on top of the water but the water has to be the top-most item. That is what I am failing to do,

Here is my wall of code (just the render function):

public void render() {
    float dt = Gdx.graphics.getDeltaTime();

    // water
    time += dt;
    float angle = time * (2 * MathUtils.PI);
    if (angle > (2 * MathUtils.PI))
        angle -= (2 * MathUtils.PI);

    // light
    zAngle += dt * zSpeed;
    while (zAngle > PI2)
        zAngle -= PI2;

    fbo.begin();
    batch.setProjectionMatrix(cam.combined);
    batch.setShader(defaultShader);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.begin();
    float lightSize = 140.75f + 0.25f * (float) Math.sin(zAngle) + 27.2f * MathUtils.random();
    batch.draw(lighttex, 400 - lightSize * 0.5f + 0.5f, 300 + 0.5f - lightSize * 0.5f, lightSize, lightSize);
    batch.end();
    fbo.end();

    // draw the actual scene
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.setProjectionMatrix(cam.combined);
    batch.setShader(finalShader);
    batch.begin();
    fbo.getColorBufferTexture().bind(1);
    lighttex.bind(0);
    batch.draw(map1BgTex, 0, 0, 960, 540);
    batch.setShader(waterShader);
    waterShader.setUniformMatrix("u_worldView", cam.combined);
    batch.end();

    Gdx.gl20.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
    Gdx.gl20.glEnable(GL20.GL_BLEND);
    watertex.bind(1);
    waterdisptex.bind(2);

    defWaterShader.begin();
    defWaterShader.setUniformMatrix("u_worldView", matrix);
    defWaterShader.setUniformi("u_texture", 2);
    defWaterShader.setUniformi("u_texture2", 3);
    defWaterShader.setUniformf("timedelta", -angle);
    waterMesh.render(defWaterShader, GL20.GL_TRIANGLE_FAN);
    defWaterShader.end();

    }

I uploaded a more complete source file and the shaders to my server, I hope it's not too inconvenient - http://agexdev.com/files/shaders.tar.xz


texts: Do I need a server if I only want to upload data to a DB?

texts:
I'm currently creating a game where people get some kind of reports for their game performance on a website. Let's say, you log-in, play the game, the system gathers your performance data and this is being sent to a database so that it can be read and interpreted by an external website later. For this, I'm using a firebase real-time database and it's working fine by now.

I'm pretty noob with unity and I have read and watch tutorials on the internet where people actually create a server to achieve this but do I really need a server when the only thing I need to do is to post data to a database based on users?
This isn't really a multiplayer game, but there is some kind of information which is shared for example sometimes I need to get those data in order to get high scores and that kind of small information, but that's it.

I'm using unity webgl and firebase for the moment, and everything is working fine, but then why people always create a server for this?

PS: sorry for my bad english


texts: Generating Realistic Looking Wire in Unity

texts:
I'm designing a game that involves the simulation of a breadboard. I would like some advice on the best way to simulate jumper wires used to connect various places on the breadboard together. I have provided a picture below for those unfamiliar with electronics.

These are the wires I would like to simulate. I would like them to dynamically adjust in length based on the distance of the connection points, and with some randomness (so hopefully wihout a perfect curve from point A to B). To be clear, the wires to not need to move dynamically, they just need to generate once.
If realistic randomness is not possible, what would be the best way to achieve even something like a smooth curve of wire from point A to B?


texts: How to rotate a sprite in 2D with LWJGL3 and GLSL

texts:
I have all the basic rendering already set up, with translation, scaling etc. What matrix(s) and/or vector(s) do I need to multiply/add with my existing code to rotate an object.

Preferably around a point given by a vector2fa, also only in degrees because quaternions aren't implemented and its only 2D not 3D.

Snippet of the vertex shader:

gl_Position = transformation * vec4(position, 1.0) + translation

Where transformation is done in java as (Note not actual code as * is replaced with .mul()):

Matrix4f transformation = ortho * scale

And translation is given by a method:

Vector4f translation = new Vector4f(x , y , 0f, 0f).mul(gc.getOrtho());

All the code listed before works as expected. It is just lacking the rotation feature mentioned at the top.

How can I add rotation to my code?


texts: Client/Server state synchronization for RTS

texts:
How can I perform state synchronization using client/server networking in an RTS similar to Starcraft 2 and Planetary Annihilation?
I'm assuming the server has to do some sort of rewinding time to apply the updates received by each of the clients. But for an RTS game, that sounds like a lot of separate copies of the game world. How do you resolve interactions between units belonging to different players who have different latencies?
For the clients, do they need to use their latency (RTT) in order to know how far behind the server they are, to apply future updates that arrive from the server at the right time?
How do you keep time in sync when latency could fluctuate and server updates may not arrive at fixed intervals?


texts:
I have the following class:

public class AnimationDemo implements ApplicationListener {
    private SpriteBatch batch;
    private TextureAtlas textureAtlas;
    private Animation animation;
    private float elapsedTime = 0;
    private OrthographicCamera camera;
    private int width;
    private int height;
    private int texturewidth;
    private int textureheight;

    @Override
    public void create() {
        width = Gdx.graphics.getWidth();
        height = Gdx.graphics.getHeight();
        camera = new OrthographicCamera(width, height);
        camera.position.set(width / 2, height / 2, 0);
        camera.update();

        batch = new SpriteBatch();
        textureAtlas = new TextureAtlas(Gdx.files.internal("data/packone.atlas"));

        textureAtlas.getRegions().sort(new Comparator<TextureAtlas.AtlasRegion>() {
            @Override
            public int compare(TextureAtlas.AtlasRegion o1, TextureAtlas.AtlasRegion o2) {
                return Integer.parseInt(o1.name) > Integer.parseInt(o2.name) ? 1 : -1;
            }
        });

        animation = new Animation(1 / 15f, textureAtlas.getRegions());

    }

    @Override
    public void dispose() {
        batch.dispose();
        textureAtlas.dispose();
    }

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

        batch.begin();
        elapsedTime += Gdx.graphics.getDeltaTime();
        batch.draw(animation.getKeyFrame(elapsedTime, true), 0, 0);
        batch.end();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }
}

In the above I am using the Animation class to simply draw from a texture atlas. I am following an example from another SO question which is here but the co-ordinates don't fit my equation. How should I set these:

private int texturewidth;
private int textureheight;

Any help would be great :)


texts:
I am working on a game based around Newtonian physics. Therefore there is no drag and therefore a ship will keep accelerating indefinitely if there is no counter-force acting on it. This is being built within Unreal Engine and it is entirely based on physics thrusters (i.e. "Add Force at Location").

For gameplay purposes I'd like to implement a "speed limit". Consider a simple seek steering behaviour. Ship A is pursuing Ship B. Ship A reaches the "speed limit" at time t0. Ship B changes direction at time t1.

If I calculate the new direction at t1, and then "cap" the speed at time t1 + 1 frame, Ship A will continue on its original direction, because accelerating towards another direction would make its total linear velocity greater than the speed limit.

If instead of calculating the "global" instantaneous velocity I only calculate the projection of the velocity vector along its forward axis, then it works.

However, there are some fringe cases. For example if the new direction is almost orthogonal to the velocity vector, then that means that its projection on the forward axis will be very small in magnitude. The ship will thus reach speeds well above the limit, only to have a "hard brake" when the velocity projection reaches the limit on its forward axis.

Which other methods could I use to limit speed? I thought about removing a software-based limit altogether and just make sure that the ship is braking whenever it is close to the limit. While more realistic, I'm afraid it might look less interesting.


texts:
I have like hunderd of isometric objects. One example:

I'm trying to find a way to automate creation of shadow they're casting. I ended up with following transformation:

   matrix.Shear(-0.25f, -0.25f, MatrixOrder.Append);
   matrix.Translate(0.5f * source.Width, 0.125f * source.Height, MatrixOrder.Append);

Whole algorithm:

  string sourceFileName = @"c:\in.png";
  string targetFileName = @"c:\out.png";
  using (var source = (Bitmap)Bitmap.FromFile(sourceFileName)) {
    using (Bitmap target = new Bitmap(source.Width * 2, source.Height, PixelFormat.Format32bppArgb)) {
      using (var g = Graphics.FromImage(target)) {
        GraphicsPath gp = new GraphicsPath();
        gp.AddPolygon(new Point[] { new Point(0, 0), new Point(source.Width, 0), new Point(0, source.Height) });
        var matrix = new Matrix();
        matrix.Reset();
        matrix.Shear(-0.25f, -0.25f, MatrixOrder.Append);
        matrix.Translate(0.5f * source.Width, 0.125f * source.Height, MatrixOrder.Append);
        gp.Transform(matrix);
        g.DrawImage(source, gp.PathPoints);
      }
      var grayscale = new Bitmap(target.Width, target.Height, PixelFormat.Format32bppArgb);
      for (var x = 0; x < target.Width; x++) {
        for (var y = 0; y < target.Height; y++) {
          var pixel = target.GetPixel(x, y);
          if (pixel.A != 0) {
            pixel = Color.FromArgb(255 / 3, Color.Black);
          }
          grayscale.SetPixel(x, y, pixel);
        }
      }
      for (var x = 0; x < source.Width / 2; x++) {
        for (var y = source.Height - 1; y >= 0; y--) {
          var pixel = source.GetPixel(x, y);
          if (pixel.A != 0) {
            break;
          } else {
            grayscale.SetPixel(x, y, Color.FromArgb(0, 0, 0, 0));
          }
        }
      }

      grayscale.Save(targetFileName, ImageFormat.Png);
    }
  }

Which produces something like:

It kind of works - but not 100% - the angle of shadow is changed according to proportion of the source object. Is there a way or algorithm that will work 100% or be closer to real ?

(Edited to explain more detaily).


texts: How to spawn an object on collision in box2d + love2d?

texts:
I'm trying spawn collidable debris from a ship when it explodes in love2d/box2d, however,  World:isLocked() is true when collision callbacks are called:

  This will return true inside the callbacks from World:setCallbacks.
  (source)

So creating a new body throws an error. Are there any workarounds for this?


texts:
I am writing a game in C#/XNA. Often, it's useful to have a function like this in a game engine:

   Entity CreateEntity(string id, Vector3 location)
   {
       ...
   }

So that, for instance, you can do something like this:

   List<string> entitiesToSpawn = { "Tree", "Bird", "Flower", ... }

   foreach (string entity in entitiesToSpawn)
   {
       CreateEntitiy(entity, location);
   }

Or else you can easily store the ids in data files, or populate generic GUI elements with them, for instance. What, in your opinion, is the best way to implement CreateEntity in such a way that is scalable and preserves this kind of interface? Right now, I have a gigantic static switch statement, which is obviously not sustainable. Perhaps I can create a big static map of strings to functions? Or is there an easier way to get this kind of functionality out of my engine?


texts: Determing an object's position along a curve over time

texts:
I have some objects in my game which are "thrown". At the moment I am trying to implement this by having these objects follow a parabolic curve. I know the start point, the end point, the vertex and the speed of the object.

How can I determine at any given time or frame what the x & y co-ordinates are?
Is a parabolic curve even the right curve to be using?


texts: alpha test shader 'discard' operation not working - GLES2

texts:
I wrote this shader to illustare alpha test action in GLES2 (Galaxy S6).
I think is not working at all cause I don't see any change with or without it.
Is there anything Im missing?
Any syntax error?
I know its better not using if in shader but for now this is the solution I need.

precision highp float;
precision highp int;
precision lowp sampler2D;
precision lowp samplerCube;

        //0 - CMPF_ALWAYS_FAIL,
        //1 - CMPF_ALWAYS_PASS,
        //2 - CMPF_LESS,
        //3 - CMPF_LESS_EQUAL,
        //4 - CMPF_EQUAL,
        //5 - CMPF_NOT_EQUAL,
        //6 - CMPF_GREATER_EQUAL,
        //7 - CMPF_GREATER

        bool Is_Alpha_Pass(int func,float alphaRef, float alphaValue)
        {
            bool result = true;
            if (func==0)
            {
                result = false;
                break;
            }

            if (func==1)
            {
                result = true;
                break;
            }
            if (func==2)
            {
                result = alphaValue < alphaRef;
                break;
            }
            if (func==3)
            {
                result = alphaValue <= alphaRef;
                break;
            }
            if (func==4)
            {
                result = alphaValue == alphaRef;
                break;
            }
            if (func==5)
            {
                result = alphaValue != alphaRef;
                break;
            }
            if (func==6)
            {
                result = alphaValue >= alphaRef;
                break;
            }
            if (func==7)
            {
                result = alphaValue > alphaRef;
                break;
            }
            return result;
        }

void FFP_Alpha_Test(in float func, in float alphaRef, in vec4 texel)
{
    if (!Is_Alpha_Pass(int(func), alphaRef, texel.a))
        discard;

}


texts:
See also: same question on Math.SE

How can I find the arclength of a Bezier curve? For example, a linear Bezier curve has the length:

length = sqrt(pow(x[1] - x[0], 2) + pow(y[1] - y[0], 2));

But what about quadratic, cubic, or n-degree Bezier curves?

(My goal was to estimate a sampling resolution beforehand, so I don't have to waste time checking if the next point is touching the previous point.)


texts: "Pixel-perfect" camera positioning in 2d game

texts:
I am writing a 2d game using LibGDX. The view to the game world is top-down. The game shows a grid of lines, which looks nice when the camera is at its initial position (0,0).

The problem is now that when I move (shift) the camera left/right/up/down this grid sometimes becomes a bit blurry, so the lines do not look perfectly sharp any more.

I assume this is because in these cases the grid lines are not exactly on screen pixels, but somewhere in between. Is this correct?

In any case: Are there any "best practices" how to address this problem (not necessarily LibGDX-specific)?


texts:
I've been planning for a long time to mix data from OpenStreetMap, some digital elevation model (heightmap), satellite imagery for textures, and cook a racing/cruising game where I could drive around familiar parts of the city.

OpenStreetMap contains very nice and detailed maps of all the locations I've checked, so I imagine it won't be so hard to download data for a specified region, like Boone County, Nebraska and stuff them into the game. I could generate buildings in 3d somewhat, as they have defined contour in OpenStreetMap. Roads would be the easiest thing to do as they are the core part of OSM.

What I'm worried about is the game/"simulator" part. I don't know where particularly to start. I suppose I would have to generate a lot of this world during the loading / on the fly. I don't even know if there is anything racing/vehicular-like out there available to use, except for the XNA Racing Game. I'm employed as C# developer, so I'm skilled in that language, but I'd be willing to venture into Python or something similar, if it would increase productivity in this hobby project.

Can you recommend me some engines worth looking into?


texts: FPS Android game that moves the gun as user swipes the screen

texts:
I am Making a First Person shooter game for android. Gun moves in all directions I swipe left right up or down. But the speed is so slow. How can i increase it's Speed.Here is my code.

void FixedUpdate ()
{
    foreach (Touch t in Input.touches)
        if (t.phase == TouchPhase.Began)
        {
            initialTouch = t;
        }
        else if (t.phase == TouchPhase.Moved && !hasSwiped)
        {
            float deltaX = initialTouch.position.x - t.position.x;
            float deltaY = initialTouch.position.y - t.position.y;
                //distance formula
            distance = Mathf.Sqrt((deltaX * deltaX) +(deltaY * deltaY));
            bool swipeSideways = Mathf.Abs (deltaX) > Mathf.Abs (deltaY);
            if (distance > 100f)
            {
                if (swipeSideways && deltaX > 0) {
                    this.transform.Rotate (new Vector3 (0, 30f, 0), rotationSpeed * Time.deltaTime);
                }

                else if (swipeSideways && deltaX <=0)// swipe right
                {
                    this.transform.Rotate (new Vector3 (0, 30f, 0), -rotationSpeed * Time.deltaTime);
                }

                hasSwiped = true;
            }

        }

        else if (t.phase == TouchPhase.Ended)
        {
            initialTouch = new Touch ();
            hasSwiped = false;
        }

}


texts: How can I disable Spring joint in unity 3d, since disabling feature only available in 2d mode, I am not able to find any way to disable it via script


texts: Will Unity automatically scale everything?

texts:
I don't have a GUI or anything. Just a bunch of game objects with pictures on them.

I want everything to scale with the size of the screen. So if it's a small screen, the character will take up less of the screen, instead of the screen just cutting off at the edges. If the screen is larger, everything is larger.

Is this something I should do? Will Unity automatically do this?

I've been told that the project should have the following specifications:

"The app should be appropriately scaled to fit the device screen to avoid letterboxing"

Use bg.png as the background of the app. Ideally, the background should be centered to the
app such that the left and right edges go off the screen if the device aspect ratio is less than 16:9.

Is what I'm describing fitting the specifications here? What will Unity do for me? I don't have a phone to actually test this on so I don't know what the app will end up looking like.


texts: When a Render Pass decides what textures it needs, how are shaders written?

texts:
I am studying render graph architectures (I've seen the Frostbite presentation).
A RenderPass has outputs (i.e. textures you draw to) and inputs.
How are these inputs bound to the internal pipeline ?
Lets say I have an AO Pass and it has Normals and Depth as the input.
Do I just bind the texture to a register and that's it and sample it?
What about the actual shaders (for drawing geometry) that also use textures?


texts:
I'm building a 2D space game where the player uses a chain to grab on to nearby asteroids. The asteroids move along a specific path with a constant velocity.

The chain has a maximum length L and doesn't break.

The player has an update function where it checks if the chain is attached to a asteroid. If it is attached it should make sure that the distance between the player and the specific asteroid should never exceed the maximum length L.

This is what the function looks like:

Player.prototype.update = function() {
    // ...

    if (this.grabbed) {
        var asteroid = this.grabbedAsteroid();
        if (this.distance(asteroid) > this.chain.length) {
            // Pull player
            // ...
        } else {
            this.position += this.velocity;
        }
    }
}

My question is how do I (realistically) simulate the chain pulling on the player?

The game uses the Euler method to calculate the velocity and position of the player. The velocity and position of the asteroid are given by an arbitrary function.


texts: C++ and SDL resource management for 2D game

texts:
My first question is about stateManagers. I do not use the singleton pattern (read many random posts with various reasons not to use it), I have gameStateManager which runs the pointer cCurrentGameState->render(), etc. I want to make a transitioning game, this engine should ideally cover both a platformer and a bird's eye RPG (with some recoding, I just mean the base engine), both of which will load different levels and events, such as world map, dungeon, shops, etc. So I then thought, rather then having to store all this data within all the states, I would break the engine into gameStates, and playStates... when gameState reaches gameStatePlay(), gameStatePlay simply runs the usual handleInput, logic, and render for the playStates, just as the low level gameStateManager does. This lets me store all the player data within the base playstate class without storing useless data in the gameStates. Now I have added a seperate mapEditor, which uses editorStates from gameStateEditor. Is this too much usage of the gameState concept? It seems to work pretty well for me, so I was wondering if I am too far off a common implementation of this.

My second question is on image resources. I have my sprite class with nothing but static members, mainly loadImage, applySurface, and my screen pointer. I also have a map pairing imageName enums with actual SDL_Surface pointers, and one pairing clipNumber enums with a wrapper class for a vector of clips, so that each reference in the map can have different amounts of clips with different sizes. I thought it would be better to store all these images, and screen within one static body, since 20 different goblins all use the same sprite sheet, and all need to print to the same screen, and of course, this way I do not need to pass my screen reference to every little entity. The imageMap seems to work very well, I can even add the ability to search through the map at creation of entity type to see if a particular image at creation, creating if it doesnt exist, and destroying the image if the last entity that needs it was just destroyed. The vectored clip map however, seems to take too long to initialize, so if i run past the state that initializes them to fast, the game crashes ><. Plus, the clip map call is half of this line =P

SPRITE::applySurface( cEditorMap.cTiles[x][y].iX,
    cEditorMap.cTiles[x][y].iY,
    SPRITE::mImages[ IMAGE_TILEMAP ],
    SPRITE::screen,
    SPRITE::mImageClips[IMAGE_TILEMAP]->clips.at( cEditorMap.cTiles[x][y].iTileType ) );

Again, do I have the right idea? I like the imageMap, but am I better off with each entity storing its own clips?

My last question is about collision detection. I only grasp the basics, will look at per-pixel and circular soon, but how can I determine which side the collision comes from with just the basic square collision detection, I tried breaking each entity into 4 collision zones, but that just gave me problems with walking through walls and the like ><. Also, is per-pixel color collision a good way to decide what collision just occured, or is checking multiple colors for multiple entities too taxing each cycle?


texts:
I am looking into how to design an instance system for the game I am working on.
I have always wondered how these are created in games like World of Warcraft, with its instances (dungeons/raids/etc). Areas that are separated from players other than those in your group, but have specific logic to them.

Specifically how can you reuse your existing code base and not have a bunch of checks like the following

if (isInstance) do x; else do y;

I don't know if this will make too much of a difference on any answers, but we're using a pretty classic "Object as pure aggregation" component system for our entities.


texts: Making a physics body so that another body passes through

texts:
Basically I "think" I want a static body that does not have any density so another body can "pass through it" without getting slowed down. I tried this and it doesn't seem to work. What would be the proper way to do this?

Any version (C,C++, Java) would be fine for an answer.


texts: How can I read from multiple textures in an OpenGL ES 2 shader?

texts:
How can I enable more than one texture in OpenGL ES 2 so that I can sample from all of them in my shader? For example, I'm trying to read from two different textures in my shader for the player's car.

This is how I'm currently dealing with the texture for my car:

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, this->texture2DObj);
glUniform1i(1, 0);
glBindBuffer(GL_ARRAY_BUFFER, this->vertexBuffer);
glEnableVertexAttribArray(0);

int offset = 0;
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, this->vertexBufferSize,(const void *)offset);

offset += 3 * sizeof(GLfloat);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, this->vertexBufferSize, (const void*)offset);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->indexBuffer);
glDrawElements(GL_TRIANGLES, this->indexBufferSize, GL_UNSIGNED_SHORT, 0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);


texts:
This is my first post in GameDev StackExchange, so please excuse me if I make any mistakes on best practices here (if I do, please refer me so I can learn).

I'm making a prototype where I have 2 types of enemy units: Uninfected and Infected. The Uninfected are to seek out Infected via AI pathfinding. However, I came across an issue when implementing the NavMesh in the scene. If the Player collides with an Uninfected, they go flying backwards. If they hit the walls, the walls collectively get hit. Here's some screenshots.

Example 1:
http://s7.photobucket.com/user/Korudo/media/GameDev/RoboInfect%20Scene%20-%20WallWeirdness1_zpsg0k2wbyk.png.html

Example 2:
http://s7.photobucket.com/user/Korudo/media/GameDev/RoboInfect%20Scene%20-%20WallWeirdness1_zpsg0k2wbyk.png.html

Thanks in advance.


texts:
I have a simple question. what are the meaning of :

half4 myHalf;
myHalf.yyyy;
myHalf.xxzz;
// or
myHalf.yw

Thanks a lot !


texts: Memory is not getting freed on Destroy()

texts:
Manager script(simple script attached to an empty GameObject on scene) on Start() instantiates 1000 default cubes with rigidbody component added and gravity check ticked.

public class SpawnScript: MonoBehaviour {

    public bool MakeInstances = false;
    public bool GC = false;
    public GameObject instance;
    public int numberOfInstances = 1;

    void Start() {
        if (MakeInstances)
            for (int i = 0; i < numberOfInstances; i++)
            {
                Instantiate<GameObject>(instance);
                //GameObject tempInstance = Instantiate<GameObject>(instance);
                //GameObject.Destroy(tempInstance);
                //tempInstance = null;
                //Debug.Log("obj is " + tempInstance);
            }
    }

    private void Update()
    {
        if (GC)
        {
            GC = false;
            System.GC.Collect();
            Resources.UnloadUnusedAssets();
        }
    }

Cube prefab have self destruction script like this

public class SelfDestruct : MonoBehaviour {
    public float seconds;

    IEnumerator DestructIn(float time)
    {
        yield return new WaitForSeconds(time);
        Destroy(gameObject);
    }

    void Start () {
        StartCoroutine(DestructIn(seconds));
    }
}

Profiler "simple" shows memory usage around 0.7gb after instantiating is done. I expect it to get freed after destroy, but it does not. Tried to apply GC and UnloadUnusedAssets, did not help. Tried to destroy them all right after instantiating, still no luck.
Is it a bug or am I doing something wrong?
This is definitely not a real world example, just wanted to study memory management in Unity and got stuck here.

P.S.A few more strange points I have noticied with profiler:

In Editor/"Detailed" mode it would not notice that I have 1000 cubes on
a scene, while in Build/"Detailed" it did
In "detailed"(both
editor and build) data usage is around 200mb which is definitely not
true(broken?), because Windows Task Manager shows me that build is
using around 0.9gb. Bigger than what "simple" tells me, guess some
overhead is present

EDIT:
Thanks to @Candid Moon for performing a test, he did confirm that software won't eat all the memory. Guess I should add screenshots with my observations
Here we have no instantiation, simple clean scene with a plane, eats around 100mb

Now let us go wild and make that instantiation on a startup

Alright, we did instantiate a lot of objects, they collided and flew away in outer space, in 5 seconds they were destroyed. We are back to clean scene with plane, just like the one with 100mb. Except for now it eats up 0.75gb. Left it hanging for half an hour to see if memory gets freed, nothing happened.
Is it a usual behavior? Is there any way to free all the used memory and go back to 100mb? Can/Should programmer do anything on his side to deal with such situations?


texts: What happenes if you leave out buffers for the inputassembler that the vertex shader expects?

texts:
I'm working through my first attempt at a "graphics engine" (I use the term loosely as I'm not aiming for much more than something that will display a few meshes).  I want to leave my classes as extensible as possible and am currently working on my mesh class.

I want my mesh class to be able to have optional UVs and optional normals, although I generally expect to use these.  As I'm new to Direct3d I'm curious if I still have to define matching "zeroed" buffers for the missing normals and UV data if the vertex shader and input assembler is otherwise expecting this data?  Should I have my mesh class assemble the missing data zeroed out and declare empty buffers or does Direct3d know to pass null arguments for missing data?

EDIT: I guess zeroed normals wouldn't work as any shader expecting normals would produce bad/bizarre results, but the question regarding texture coords still stands.


texts: MMORPG - Auction House and Bank Primary Keys

texts:
On to the next... So I've been sitting with the idea of how to better future proof my database tables when it comes to things like auction houses, inventories and banks.

Q: Is it really necessary to have a primary key value in an auction-house / bank tables? I've already got a link going to the characters ID as well as the item ID.

The reason I'm asking this is because if I use a primary key value of type int or long, what will happen if there are too many entries for type int or long to handle? I'm planning on removing the DB entry as soon as the item is sold, but wouldn't "auto increment" just carry on from the last ID value used?

In short, what would be the down side to not using primary keys in those tables?


texts:
I'm looking for a solution for moving a variety of objects over the uneven surface of my planet. The idea is that I will have a number of objects that follow the planetary landscape moving about in random directions.

The planet surface is made up of 6 sphere projected planes, all have been displacement mapped to create a "bumpy" surface. A grid based movement system would be ideal as it lends itself to a lot of pathfinding solutions. I am also using Unity, so leveraging the Physics engine is an option, but past experience hasn't yielded very good results.

I'm having trouble understanding the best approach for realistic movement, would it be a matter of calculating gravity and then translating the object along its forward, right etc. Or on the other hand would It be more a case of pre-calculating the path from A to B and applying that movement.

I've looked all over for some ideas on this subject but have found nothing. A few suggestions would be greatly appreciated.

Thanks.


texts: How to convert screen space into 3D world space?

texts:
I am trying to make a 3D model to look at the mouse position. Currently I have this code:

MouseState mouseState = Mouse.GetState();

Matrix world = Matrix.CreateTranslation(0, 0, 0);

Vector3 source = new Vector3((float) mouseState.X, 1f, (float) mouseState.Y);
Vector3 mousePoint = GraphicsDevice.Viewport.Unproject(source, this.game.Camera.Projection, this.game.Camera.View, world);

System.Console.Out.WriteLine("x: " + mousePoint.X + ", Y: " + mousePoint.Y + ", Z: " + mousePoint.Z);

I get output such as this in the console:

x: 0.1787011, Y: 999.7204, Z: 299.7723
x: 0.08917224, Y: 999.8602, Z: 299.8862
x: 0.05908892, Y: 999.9069, Z: 299.9241
x: 0.04422692, Y: 999.9302, Z: 299.9431
x: 0.03303542, Y: 999.9477, Z: 299.9573
x: 0.03109217, Y: 999.9508, Z: 299.9598
x: 0.02930491, Y: 999.9535, Z: 299.9621
x: 0.02770578, Y: 999.9559, Z: 299.9641
x: 0.0263205, Y: 999.9581, Z: 299.9659

The player is positioned at Vector3.Zero. The camera is positioned at new Vector3(0.0f, 1000.0f, 300.0f).

I would like to get output such as X: -300, Y: 0, Z: -300 when moving the mouse to screen top left and when moving the mouse to screen center where the model is located I want to have X: 0, Y: 0, Z: 0. So I want the world coordinates of the mouse so that I can make the player rotate towards the mouse.

Basically I want to map mouse X into world X, mouse Y to world Z and the world Y coordinate can be 0 at all times.


texts:
I want to use a HashMap to dynamically create objects based on the key.

I have a Random Map Generator that stores the maps in 3D Arrays of Type Integer[][][]. Upon creation of the actual map I iterate through this array and based on the Integer I want to create the right block.

Example: Integer[][][] map ... map[6][6][6] = 3; 3 is a Earth-Block and now I want to initialize a new Block of this type and give it the right coordinates.

Currently I store my Bindings from Integer to Class in a HashMap(Integer, String) and create my objects like that:

int id = array[x][y][z];
String block_name = Blocks.map.get(id);

Block block = (Block) Class.forName(block_name).newInstance();
block.setPosition(x,y,z);

But I want to avoid newInstance() if possible.

I've never worked that dynamically with Java before and I couldn't find a solution like changing the HashMap to (Integer, Class) or something. I just need to create a new Object based upon the Integer.

Any ideas/solutions? Thanks in advance and have a wonderful day!


texts: How to combine Actor.setPosition and Actor.hit?

texts:
Why after using Actor.setPosition, input coordinates in Actor.hit come with a shift in the values specified in setPosition?

Create scene:

public class MyActor extends Actor {
...
    int width = 70;
    int height = 70;

    public MyActor(Texture img, int x, int y, int realX, int realY) {
...
        sprite = new Sprite(img, x, y, width, height);
        this.setPosition(realX, realY);

Standard search Actor:

public class GameScreen implements Screen, InputProcessor {

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        Vector2 coord = stage.screenToStageCoordinates(new Vector2((float)screenX,(float)screenY));
        Gdx.app.log("touchDown", "" + coord.x +","+ coord.y);

        selectedActor = (MyActor)stage.hit(coord.x,coord.y,false);

...

public class MyActor extends Actor {

    @Override
    public Actor hit(float x, float y, boolean touchable) {
        if(!touchable)
            Gdx.app.log("Actor.hit:", "" + x +":"+ y);
        return x < getX()|| x >= getX() + width || y < getY()||  y >= getY() + height ? null : this;

But come the distorted values.

Coordinates Click:  touchDown: 26.25,81.250015.

MyActor in the values obtained from the offset, the multiple of 70:

Actor.hit: -43.75:11.250015
Actor.hit: -43.75:81.250015
Actor.hit: 26.25:11.250015
Actor.hit: 26.25:81.250015

Why? How to fix?

UPDATE

public class MyStage extends Stage {
...
    @Override
    public Actor hit(float x, float y, boolean touchable) {

        return super.hit(x,y,touchable);


texts:
I have two objects that should collide. My player should stand on a ship. The position where my player stands, is exactly on the edge of two adjacent triangles (in the ship's model). To Check for collision, I'm using ray picking. I cast a ray from the player's hips downwards. This intersection tells me if the player should be falling (no collision), or if there is a floor under his feet (collision).
In some occasions, the ray is fired exactly between two triangles, causing the ray to not collide, causing the player to fall through the floor.

I've solved this in my "RayIntersectsTriangle" function by slightly increasing the triangle's size. It feels hacky, and like it's bad practice.

I realise I could also solve this by casting multiple rays from the player downwards, and check if at least one collides. But obviously, this consumes more operations, and also feels like it should not be the way to do it.

FYI: The RayIntersectsTriangle function definitely works, no question. I'm just wondering if floating point precision is messing this up.

Is there a way to make sure that a raycast can never pass between two triangles in a mesh due to floating point errors, or should I make a workaround like I did?


texts: How to collapse a structure after procedural destruction

texts:
When considering this temple structure with procedural damage in pink:

How can I efficiently determine the collapse of such structure as below?

Even if the model is defined on a voxel grid, it would still require possibly wide-ranging searches for connected-ness?

In the 2D case, flood-filling and labeling disconnected components is probably doable, but what about the 3D-case?

Can this be done without traversing the entire world space, every frame -- which I imagine, wrecks havoc to a data cache?

Lastly, what is the technical term for this problem of "making stuff fall down after procedural damage?"


texts: How can I change the path a sprite is following in real time?

texts:
Is there a common way to implement a character following path that is issued and replaced in real time?

For example: the character follows a path issued, and while it's on that path, if a new path is issued, the character abandons the existing one and follows the new path from where it is currently located.

Here's a more detailed explanation:

I am trying to make a real-time action game, like Diablo, but in 2D and tile-based. The player can issue new destinations on the map and the in-game character should walk towards that destination in real time.

I got the path finding part all worked out, but I am having issues with getting the character to smoothly abandon an existing path, and follow a new path (when a new destination is issued).

The character sometimes flickers when a new path is issued while it's following an existing path. If the character sprite is not at the centre of a tile, it will "teleport" to the centre of the tile it's on and follow the path from there on smoothly.

I tried to get around this problem by first checking if the player is on at the centre of a tile, and if not, I amend a node in the front of the new path to get the player to move to that tile. But this still doesn't get me the desired effect, because if the same destination is issued over and over, the character will just keep walking to the same tile instead of walking towards that destination.


texts: How do you create an input layout for passing a uint4 to a vertex shader in D3D10?

texts:
I am trying to pass in a uint4 into the shader but my input layout keeps failing when trying to load the shader.

shader.fx

uint4  values : UINT4_0;  // VertexInput

Input layout

{ "UINT4", 0, DXGI_FORMAT_R32G32B32A32_UINT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }

Does that seem right?

I am a bit confused why there is an error here.


texts:
I have set up a class for input handling that allows me to create key bindings with different key behaviours such as single press action bindings where the action will only happen once if the key is held, and state like actions to make things happen more than once.

In the constructor of the key handler class I pass in the value of the key to bind to and a pointer to a callback function to be called as necessary. My problem comes when I try to pass the pointer to the function in to the constructor since the method I am trying to pass is a member function of my main game class.

I know of solutions that involve making the members static but my problem here is that doing so would require for me to change the signature of every method which has to take the pointer as a parameter and doing so would impact upon the re-usability of my input class for other projects.

Are there any other solutions to this problem that wouldn't involve changing the signature of the methods to accommodate the member function?


texts: What other components would one have to combine with Ogre 3D render engine to make a full fledged custom game engine?

texts:
I have heard that Ogre 3D is not actually a game engine, rather it is a 3D render engine. I have also heard people claim that one can piece it together with other components (engines?) to create a full featured game engine. So my question is:

What are the other types of
components/engines one would have to
add to Ogre 3D to create a game
engine?
Also, what are the most popular and
powerful examples of these other
components/engines?


texts: What direction is forward when the rotation is (0, 0, 0)?

texts:
I'm representing the rotations of my actors (or gameobjects) with euler angles (one float for each axis). And I've always considered the vector (1,0,0) (x,y,z) to be the actor's direction if all angles are 0. So if an actor don't have any rotation, and walks forward, he will be walking down the positive x axis.

However, I was implementing a camera today that's supposed to display the view from the actors perspective. If I use the actor's rotation, that is (0, 0, 0), the camera will be looking down the -z direction (straight into the monitor), but the actor is actually looking to the right.

If, instead, -z would be considered the direction when the rotation is (0, 0, 0), then the camera would be facing the correct direction. Is that how this is normally handled? Or am I thinking of this the wrong way?

To clear things up, I'm using a right handed coordinate system with y as the up axis.


texts:
I am beginner to Unity and need some help about the code below. I want to pass the array with into second script. But I got only Object reference not set to an instance of an object What is the problem with the code ?

---- First Script

using UnityEngine;
using System.Collections;

public class PlayableCells : MonoBehaviour {

    public static PlayableCells Instance;

    public int[][] moves;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    public int[] PossibleMoves(int cell_id) {

        int[] cell_0 = new int[] {2, 11, 20};
        int[] cell_1 = new int[] {3, 10, 12, 21};
        int[] cell_2 = new int[] {0, 4, 11, 13, 22};
        int[] cell_3 = new int[] {1, 5, 12, 14, 23};
        int[] cell_4 = new int[] {2, 6, 13, 15, 24};
        int[] cell_5 = new int[] {3, 7, 14, 16, 25};
        int[] cell_6 = new int[] {4, 8, 15, 17, 26};
        int[] cell_7 = new int[] {5, 9, 16, 18, 27};
        int[] cell_8 = new int[] {6, 17, 19, 28};
        int[] cell_9 = new int[] {7, 18, 29};

        int [][] moves = {
            cell_0,
            cell_1,
            cell_2,
            cell_3,
            cell_4,
            cell_5,
            cell_6,
            cell_7,
            cell_8,
            cell_9

        };

        return moves [cell_id];
    }

    void Awake(){
        Instance = this;
    }
}

-----Second Script

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

public class Cell : MonoBehaviour {

    public int cell_id;
    public int[] pscell;

    // Use this for initialization
    void Start () {
        SetCell();
    }

    // Update is called once per frame

    void Update () {

    }

    void SetCell() {
        string btnName = this.gameObject.name;
        cell_id = Int32.Parse(btnName.Substring(btnName.LastIndexOf('_') + 1));
        pscell = PlayableCells.Instance.PossibleMoves (cell_id);

    }

    public void TaskOnClick()
    {

        GameController.Instance.checkMove(cell_id,pscell);
        int score = GameController.Instance.getScore();
        this.GetComponentInChildren<Text>().text = "" + score;

    }

}


texts: Strange issue with bool comparing ToString always false - unity c#

texts:
I have another problem with my code that I can't fix :\

Basically i have an enum called 'type' in my Item class, which tells me if the item is consumable, or equipment, etc.
In the database script I have made, it sets the type for each item (5 in total). So basically I have an inventory UI, with 5 items (inc. 2x consumables, 3x Equip)

After much debugging/checking things, I've found that the boolean prior to "sortedItems.Add(i);" is always FALSE. But it shouldnt be, BOTH VALUES ARE THE SAME as per the console log.
I have input a print() line to check whats going on because my items are'nt sorting by type when I expect them to.

public void SortItemsByType(string type)
{
    sortedItems.Clear();
    foreach (Item i in allItems)
    {
        print("is the following true or false" + i.type.ToString() == type);
        print("this is iToString= " + i.type.ToString());
        print("and this is type: " + type);
        if (i.type.ToString() == type)
            sortedItems.Add(i);
    }
}

and (please note the 3 print lines, here is their output in the console:
(sorry but the dumb IDE won't let me copy-paste the console, here is image):

Im still very much a noob to this, so I am sure there is something I have missed. But for the life of me i cannot figure out why that bool is always resulting in FALSE?

Any help is massively appreciated. Thanks


texts: Rotating an object at the user specified speed in corona

texts:
I am developing a globe animation, in which the speed of the rotation changes with the length of the user's drag event.The globe when touched and moved attains positive acceleration,reaches maximum value,rotates there for sometime and starts retarding and comes back to its original position.Can anybody tell me how to do this in corona.A sample code will be really helpful.

Thanks.


texts:
I'm using Box2d as my physics engine and I'm trying to solve what would normally be a simple problem but what has become a nightmare for me and preventing me from finishing my app. (6 months work)

I've tried implementing this: (Example of implementation below)
http://box2d.org/forum/viewtopic.php?f=18&t=7306 but it's got three problems.
1: When reaching the top angle it stops and goes the other way. (Example in logs)
2: Limited speed, some objects need turn fast.
3: Large objects with moving joints spaz out rocking all over the place.

I have a desired angle and I want my body to rotate at different speeds (depending on turn speed setting as I want large slow turn objects).

Problems with current code.
1: Large object with a moving joint either spin very fast or rock constantly.
2: The rock effect exists on everything.

Edit
This is within a game loop, so have access to delta.

Code 1: Box2D attempt:

//Testing speed.
float tempSpeed = MathUtils.PI;

float currentAngle = getBody().getAngle() % MathUtils.PI2;

float nextAngle = getBody().getAngle() + (getBody().getAngularVelocity() * update);
float totalRotation = getDesiredAngle() - nextAngle;

//Assuming this tries to prevent the switch angle problem but limits the speed??
while ( totalRotation < -MathUtils.PI * tempSpeed ) totalRotation += MathUtils.PI2 * tempSpeed;
while ( totalRotation >  MathUtils.PI * tempSpeed ) totalRotation -= MathUtils.PI2 * tempSpeed;

float desiredAngularVelocity = totalRotation;
float change = 1f * tempSpeed; //allow 1 degree rotation per time step
desiredAngularVelocity = Math.min(change, Math.max(-change, desiredAngularVelocity));
float impulse = getBody().getInertia() * desiredAngularVelocity;
getBody().applyAngularImpulse(impulse, true);

//Below shows an example of the top angle being switched.
if(getFocus()){
    Functions.log("currentAngle: " + getBody().getAngle() + " | nextAngle: " + nextAngle + " | totalRotation: " + totalRotation + " | desiredAngularVelocity: " + desiredAngularVelocity);
}
/*
Log: nextAngle: -0.1850999 | totalRotation: 6.400846 | desiredAngularVelocity: 3.1415927
Log: nextAngle: -0.02812685 | totalRotation: 6.2195992 | desiredAngularVelocity: 3.1415927

Example of top angle being reached and switching back.

Log: nextAngle: 0.21522963 | totalRotation: 5.948592 | desiredAngularVelocity: 3.1415927
Log: nextAngle: 0.45278195 | totalRotation: 5.6859627 | desiredAngularVelocity: 3.1415927
 */

Code 2: My warped attempt

//Keep the angle within range.
float currentAngle = getBody().getAngle() % 6.283185f;

//Get the next angle. Use angle in next time step
float nextAngle = currentAngle + (getBody().getAngularVelocity() * update);

float totalRotationAngle = getDesiredAngle() - nextAngle;

//Keep the total rotation within range, so we don't spin all the way around when reaching the other side.

while (totalRotationAngle < -MathUtils.PI) {
    totalRotationAngle += (MathUtils.PI2);
}
while (totalRotationAngle > MathUtils.PI) {
    totalRotationAngle -= (MathUtils.PI2);
}

//Do some other stuff.
float desiredAngularVelocity = totalRotationAngle * getRotationSpeed();

//Inertia is the amount of force required to rotate the object, without it it rotates really fast.
//If we introduce it, we get more realistic results but the horrible rock.
//float torque = (getBody().getInertia() * (desiredAngularVelocity * this.turnSpeed)) * update;

//Need inertia otherwise it can spins things right out the way.

//float turnSpeed = (this.turnSpeed * (4f * (getDesiredAngle())));

float torque = (desiredAngularVelocity * (this.turnSpeed));
torque *= (getBody().getInertia());
torque *= update;

//Apply torque.
getBody().applyTorque(torque, false);


texts: How can i change transform position only on the x each time by gap of 50?

texts:
Global variable gap:

public int gap = 10;

Then:

clone.position = new Vector3(transform.position.x, 0,0);

clone is Transform

I want to use the gap variable to make spaces between each clone:

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;

public class ClickOnKeys : MonoBehaviour
{
    public GameObject[] prefabs;
    public int gap = 10;

    private GameObject go;

    void Start()
    {
        prefabs = Resources.LoadAll("Prefabs", typeof(GameObject)).Cast<GameObject>().ToArray();

        foreach (GameObject prefab in prefabs)
        {
            if (prefab.name == "Test")
            {
                go = prefab;
            }
        }
    }

    void Update()
    {
        if (Input.anyKey)
        {
            foreach (Transform child in go.transform)
            {
                if (Input.inputString == child.name)
                {
                    Transform clone = Instantiate(child);
                    clone.parent = transform;
                    clone.position = new Vector3(transform.position.x + gap += 50, 0,0);
                }
            }
        }
    }
}

I tried to make:

clone.position = new Vector3(transform.position.x + gap += 50, 0,0);

But getting error on the part: transform.position.x + gap

The left-hand side of an assignment must be a variable, property or indexer The

This is what i tried now:

Transform clone = Instantiate(child);
clone.parent = transform;
gap += 50;
clone.position = new Vector3(transform.position.x - gap, 0, 0);

But the result is that the space/gap between the clones is not equal and also it seems the clones that each one is a letter looks rotated like mirror:

Each clone present a letter so it should show the word Hello
But the letter e is on the H and the gap/space between the first l and second l not equal and the l is on the o:


texts: Who know how to implement the 2D bone animation showed in the game?

texts: I wonder how do they implement the bone animation in the flash game http://www.foddy.net/athletics.swf Do you know any study materials which I can start to learn 2D bone system from? I just implemented a avatar system by compose multiple bitmaps in each frame(similar with maple story), but some guys tell me that, a bone system can save more art resources, so I want to learn some thing about that.


texts: Calculating framerate-independent values, for linear, quadratic, and exponential functions

texts:
There are a few similar posts, but they only deal with one of the three components I'm looking for, and none seem to handle the case of using a fixed step size (they're all about simulations which use a variable deltaTime).
I'm using a fixed step simulation, and my lifelong (bad) habit has been to eschew units and just directly use parameter values which have deltaT "baked in". Now that I'm trying to add support for different fixed rates, it's biting me in the ass! :/
Here's a simplified example of my code, covering all three cases:
run_speed = 2;      //velocity, linear
brake_decay = 0.95; //viscous damping, exponential
gravity = 1;        //acceleration, quadratic

if(button_pressed)  vel_x = run_speed;
else                vel_x *= brake_decay;

vel_y += gravity;

pos_x += vel_x;
pos_y += vel_y;

I would like to support different fixed timesteps by scaling my existing parameters:
run_speed = 2 * A_to_B_vel;
brake_decay = 0.95 * A_to_B_damp;
gravity = 1 * A_to_B_acc;

My question is: if my fixed timestep is currently A ms/tick, and I want to switch to a fixed timestep of B ms/tick, how do I calculate these three new scaling factors, such that the object follows the same curve through space and time?
(I realize that the actual positions will vary between A and B since we'll be sampling the trajectory curve at a different rate, I just want the underlying curve itself to be identical regardless of how we sample it.)
A_to_B_vel: this is the case which has been covered by many other "framerate independent" questions, and it's relatively trivial because the relationship is linear: A_to_B_vel = B/A
A_to_B_damp: this seems to have been answered here Frame-rate independant movement with acceleration via the Pow() function. This makes sense since it describes an exponential curve; I'd still appreciate someone breaking down the formula though, because the answer given there involves "referenceFPS" and I'd prefer to stick solely to units of time, ie ms/frame, not frame/sec. (and it's not clear that I can simply substitute one for the other into the formula they give)
A_to_B_acc: this is where it gets confusing! According to the above answer, this should be treated similarly to A_to_B_vel (ie scale by the frame duration), however this is definitely wrong, since I've implemented it and it doesn't work. i.e A_to_B_acc = B/A doesn't work. My calculus is very rusty, but I would imagine that the scaling factor needs to involve a dT*dT term somewhere, since acceleration changes position quadratically.
Additionally, if anyone could point me towards a resource which explained the underlying calculus here, I would really appreciate it.
Thanks for your time! :)
Raigan


texts: is there any different solution for different buildings different behaviours

texts:
I'm trying to make different behaviours for workers of different buildings, let's say an agricultural worker would need to sow wheat seed and collect the wheat grain when it's grown. let's call that Behaviour0
For carpentry a worker would get wood and make arrows.
I have 2 different behaviours and I would like to implement them all in the simplest way possible.
 class agricultural{
     Workr Work
     void Working(Work W){
         Behaviour1();
     }
 }
 class Carpentry{
     Workr Work
     void Working(Work W){
         Behaviour2();
     }
 }
 template <tipename T> class BuildWork{
     T BW
     Work(){
         BW.Working();
     }
 }

I tried doing it with template so the behaviour would be inside agricultural and carpentry but problem occurred when I tried to declare template as only 1 can be inside it and getting it with ifs would make it the same as a non-templated version.
 class Workr{
     // here I would need to make it only for 1 is possible
     BuildWork <agricultural> BW
 }

So is this how I should use it?
The next thing occurred to me is this
 class Building{
     bool beh[2];
     void Work(Workr W){
         if beh[0]{
             if (beh[1]){
                 behaviour0(Workr W);
             }
             else{
                 behaviour1(Workr W);
             }
         }
         else{
             if (beh[1]){
                 behaviour2(Workr W);
             }
             else{
                  behaviour3(Workr W);
             }
         }
     }
 }

The last code is workable but I wonder if there is a better solution for this? here I can just change the bits in the beh[ ] and it's working
Each building has different behaviours and each worker in that specific building has same behaviour. Specific behaviour is always in the same building type.


texts:
(I've split this question into two. For 2D, see: 2D collision-detection middleware)

Are there any recommendable middleware available for 3D collision detection?

I believe I've heard Bullet has a pretty good 3D collision detection that can be used without the physics engine. I'd like to hear if people have any experiences on Bullet or other libraries for 3D collision detection specifically.


texts: How much to pay for artwork in an indie game?

texts:
I am an indie developer and I need some detailed artwork. How much is reasonable to pay an artist for say 20 character designs? I know it depends on the artist's skills, etc, but I am wondering what to expect so that I can budget it.

Edit:

Let's say cartoon-ish art (Example - not necessarily in that level of detail but that kind of cartoony-art style). No 3-d modelling - The art will be used as still images in game and for promotional reasons. I'd provide a base sprite design for them to expand on and detail.

Also, some numbers would be nice - I like numbers. Even a range is helpful.

Like: expect to spend $x2 ~ $x1 for top-notch and $y2 ~ $y1 for decent quality.

I understand I can ask at some indie-help site but, if an artist says something like $1000 for 20 designs, I wouldn't have any idea if it's reasonable / good deal / bad idea etc.


texts:
Lets say I want to blend two textures together:

A texture containing the result of the SSAO calculation.
A texture containing the rendered scene.

I could do it in two ways:

Use a shader that samples both the SSAO and scene textures, blends them together and outputs the final color to a render target.
Render to the texture containing the scene and use a blending mode to blend the SSAO texture on top of it. Only the SSAO texture will be sampled inside the shader.

Is it possible to give a general answer about which version is faster, or is it highly hardware dependent?


texts: Unity: how intercept Mouse Click on UI and not fire "shoot"?

texts:
I've a classic

void Update() {
   if(Input.GetMouseButtonDown (0))
      Fire();
}

What i want to do is that if I click on a UI button , the Fire() routine not will be called.

How to do to say Unity if InputGetMouseButtonDown(0) && !UI clicked ?


texts: How can Highscores be more meaningful and engaging?

texts:
I'm developing a casual Android game in which the player's success can very easily be represented by a number (I'm not more specific because I'm interested in the topic in general).

Although I myself am not a highscore person at all, I was thinking of implementing a highscore for that game, but I see at least 2 problems in the classical leaderboard approach:

very soon the highscore will be dominated by hardcore players, leaving no chance for beginners, who are then frustrated. This is very severe especially in casual games.
there is no direct reward for being a loyal player who plays the game over and over again

My current idea is to "reset" the highscore every 24 hours (for example) and each day nominate the "player of the day" who then gets a "star".
Then there would be some kind of meta-highscore of players with the most stars.

That way even beginners might have a chance to be "player of the day" once and continued or repeated play is rewarded much more.

The idea is still very rough and there are many problems in the details and the technical implementation but I have a feeling it is a step in the right direction.

Do you have creative and new ideas on how to implement highscores?

Which games are doing this well / what types of highscores do you find most engaging?