texts: Unable to find good parameters for behavior of a puck in Farseer

texts:
EDIT:

I have tried all kinds of variations now. The last one was to adjust the linear velocity in each step: newVel = oldVel * 0.9f - all of this including your proposals kind of work, however in the end if the velocity is little enough, the puck sticks to the wall and slides either vertically or horizontally. I can't get rid of this behavior. I want it to bounce, no matter how slow it is. Retitution is 1 for all objects, Friction is 0 for all. There is no gravity. What am I possibly doing wrong?

In my battle to learn and understand Farseer I'm trying to setup a simple Air Hockey like table with a puck on it.
The table's border body is made up from:

    Vertices aBorders = new Vertices( 4 );
    aBorders.Add( new Vector2( -fHalfWidth, fHalfHeight ) );
    aBorders.Add( new Vector2( fHalfWidth, fHalfHeight ) );
    aBorders.Add( new Vector2( fHalfWidth, -fHalfHeight ) );
    aBorders.Add( new Vector2( -fHalfWidth, -fHalfHeight ) );

    FixtureFactory.AttachLoopShape( aBorders, this );
    this.CollisionCategories = Category.All;
this.CollidesWith = Category.All;
this.Position = Vector2.Zero;
this.Restitution = 1f;
this.Friction = 0f;

The puck body is defined with:

FixtureFactory.AttachCircle( DIAMETER_PHYSIC_UNITS / 2f, 0.5f, this );
this.Restitution = 0.1f;
this.Friction = 0.5f;
this.BodyType = FarseerPhysics.Dynamics.BodyType.Dynamic;
this.LinearDamping = 0.5f;
this.Mass = 0.2f;

I'm applying a linear force to the puck:

this.oPuck.ApplyLinearImpulse( new Vector2( 1f, 1f ) );

The problem is that the puck and the walls appear to be sticky. This means that the puck's velocity drops to zero to quickly below a certain velocity. The puck gets reflected by the walls a couple of times and then just sticks to the left wall and continues sliding downwards the left wall. This looks very unrealistic.

What I'm really looking for is that a puck-wall-collision does slow down the puck only a tiny little bit. After tweaking all values left and right I was wondering if I'm doing something wrong. Maybe some expert can comment on the parameters?


texts: How can I compensate for camera rotation changing PCSS penumbras?

texts:
I am implementing PCSS and I am using a directional light. The directional light volume is clamped to the camera frustum (as is typical with directional lights). So when the camera rotates, the directional light volume can find a tighter bound on the camera frustum in some cases, and then all of the depth values can increase/decrease.

This causes the blocker search to find different blocker distances from the light source, and so the penumbra sizes change based on the camera rotation.

Has anyone dealt with this problem before? How can I compensate for changes to the light depth map (aka shadow map) when the camera rotates?

Here are some images demonstrating two camera views, visualizing the penumbra values (brighter indicates where a larger penumbra should go) and the corresponding light depth maps (shadow maps):


texts: Use depth bias for shadows in deferred shading

texts:
We are building a deferred shading engine and we have a problem with shadows.

To add shadows we use two maps: the first one stores the depth of the scene captured by the player's camera and the second one stores the depth of the scene captured by the light's camera. We then ran a shader that analyzes the two maps and outputs the third one with the ready shadow areas for the current frame.

The problem we face is a classic one: Self-Shadowing:

(source: microsoft.com)

A standard way to solve this is to use the slope-scale depth bias and depth offsets, however as we are doing things in a deferred way we cannot employ this algorithm. Any attempts to set depth bias when capturing light's view depth produced no or unsatisfying results.

So here is my question: MSDN article has a convoluted explanation of the slope-scale:

bias = (m × SlopeScaleDepthBias) + DepthBias
Where m is the maximum depth slope of the triangle being rendered, defined as:
m = max( abs(delta z / delta x), abs(delta z / delta y) )

Could you explain how I can implement this algorithm manually in a shader? Maybe there are better ways to fix this problem for deferred shadows?

Update: trying to implement normal-offset shadows. Current state:

Image with no bias applied:

Normal offset bias applied, it works with the teapot, but look what it does with all the other shadows:

I even tried adding the NDotL term, it does not help:

float4 worldPosition = mul(input.Position, World);
float nDotL = dot(input.Normal,(shadowCameraPosition - worldPosition));
worldPosition.xyz += input.Normal*NormalBias*(1-nDotL);


texts: How can I draw multiple lines connected via "nodes" with SlimDX?

texts:
I currently read out XML data with the following scheme: Position x,y,z

I try to add one new Vertex for each position node and add it to a Vertex array.

Then I try to render this list of vertices so I get all those lines connected to represent a "path" through space.
(Space is 3D)

What I tried so far:

    [STAThread]
    static void Main()
    {
        var form = new RenderForm("SlimDX - MiniTri Direct3D9 Sample");
        var device = new Device(new Direct3D(), 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters()
        {
            BackBufferWidth = form.ClientSize.Width,
            BackBufferHeight = form.ClientSize.Height

        });
        form.Height = 900;
        form.Width = 900;

        LineVertex[] waypoints = new LineVertex[1024];

        XmlDocument paths = new XmlDocument();
        paths.Load("data.xml");
        XmlNode rootNode = paths.DocumentElement;

        int index = 0;
        foreach (XmlNode waypoint in rootNode)
        {
            foreach (XmlNode position in waypoint)
            {
                Console.WriteLine(position.ChildNodes[0].InnerText);
                float b = 1000.0f;
                float x, y, z;

                x = (float.Parse(position.ChildNodes[0].InnerText) / (b * b));
                y = (float.Parse(position.ChildNodes[1].InnerText) / (b * b);
                z = (float.Parse(position.ChildNodes[2].InnerText) / (b * b));

                Console.WriteLine(x.ToString() + " / " + y.ToString() + " / " + z.ToString());

                if (index % 2 > 0)
                    waypoints[index].Color = Color.Yellow.ToArgb();
                else
                    waypoints[index].Color = Color.Red.ToArgb();
                waypoints[index].Position = new Vector3(x, y, 0.0f);
            }
        }

        MessagePump.Run(form, () =>
        {
            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.CornflowerBlue.ToArgb(), 0f, 1);
            // Since we don't have any lights in our scene, our lines won't receive
            // any light and will therefore be black...
            // ...but we want them golden as an asinus aureus, so let's disable lighting.
            device.SetRenderState(RenderState.Lighting, true);
            device.BeginScene();

            // Our struct was meant to describe a position and a color,
            // let's tell the device about it.
            device.VertexFormat = VertexFormat.Position | VertexFormat.Diffuse;

            // In this particular case SlimDX does not need the
            // vertex stride, it will be automatically calculated.
            device.DrawUserPrimitives(PrimitiveType.LineList, 0, waypoints.Length / 2, waypoints);

            device.EndScene();
            device.Present();

        });

        foreach (var item in ObjectTable.Objects)
            item.Dispose();
    }
}

But this does not work, and I am sure it is the complete wrong approach!

EDIT: So far one solution worked out, but not very well.
And I also need the Vertices to be changeable at runtime, so I locked at the documentation and samples, they always use VertexBuffer() to make it possible to dynamically change the Vertices by using a DataStream as Input for the VertexBuffer.

A question still open to me is, since I am used to "Update(Time time)" formats the procedural still of DX/OpenGL oftens confuses me.
So I assume that MessagePump.Run() represents the drawing call that's repeated each frame.
So if some values before the drawing call change like a Vertex, that's put into the datastream, I can instantly see the updated result on the screen.
Is that assumption right?


texts: How to generate .sln files manually in Unity

texts:
I'm using git with a Unity project of mine. I'm working on my home machine and also on one at school.
I started it at home and it works perfectly on my machine.
Once I cloned it at school it opened fine and everything still worked. Only problem was VS did not generate a project. At home I have 2019 and school has 2017.

If I generate a new Unity Project at school it has the .sln and I can open it using Assets -> Open C# Project. There is no such project generated when opening the cloned project.
I need get around this as it's near impossible for me to code efficiently at school.
Because it is an EDU machine I have very limited access to certain things. Can I create a project by hand or run a command to generate one?


texts: How do I know if I've gone too far with processing things in a game?

texts:
A common programming quote I see every day is:

  Premature optimization is the root of all evil!

I admit I'm one of those guys that like to do premature optimization in a pretty obssessive manner but that's probably because I'm not aware how powerful modern processors are. I can think of lots of sollutions for a problem, but all of them are tough on the memory side, and I keep thinking "This will hurt me more in the future when I'll have to re-do it because it's bad performance-wise."

How do you know when the code you are thinking of is going too far and is not a case of premature optimization? How much can your game handle at a time before performance becomes a problem?


texts: Agent trying to reach same position as other agents, instead start spinning in place

texts:
I create units in my game and have a rally point where they should walk to when created, like Age of Empires.

My problem is that since they compete for this position after a while, sometimes they end up doing this:

https://gfycat.com/decentquestionableandeancondor

https://gfycat.com/densehonoredgalapagosalbatross

As you can see one of the guys cant reach the rally point, so he starts rotating.

I realize this has to do with stopping distance, but no matter how high I set the stopping distance this eventually becomes a problem when there are many enough units. And if I set it too high they dont walk to the rally point at all, since its not THAT far from the building they spawn from.

Is there any way to manage this scenario? i.e just making him go as close as he can, and then stop?

My AI Script:

using UnityEngine;
using UnityEngine.AI;

[RequireComponent(typeof(NavMeshAgent))]
public class BaseAi : MonoBehaviour
{
    [HideInInspector]
    public NavMeshAgent agent;

    [HideInInspector]
    public NavMeshObstacle obstacle;

    float sampleDistance = 50;

    Transform mTransform;

    private void Awake()
    {
        agent = GetComponent<NavMeshAgent>();
        obstacle = GetComponent<NavMeshObstacle>();
        mTransform = transform;
    }

    private void Start()
    {
        agent.avoidancePriority = Random.Range(agent.avoidancePriority - 10, agent.avoidancePriority + 10);
    }

    void LateUpdate()
    {
        if (agent.isActiveAndEnabled && agent.hasPath)
        {
            var projected = agent.velocity;
            projected.y = 0f;

            if (!Mathf.Approximately(projected.sqrMagnitude, 0f))
                mTransform.rotation = Quaternion.LookRotation(projected);
        }
    }

    /// <summary>
    /// Returns true if the position is a valid pathfinding position.
    /// </summary>
    /// <param name="position">The position to sample.</param>
    public bool SamplePosition(Vector3 point)
    {
        NavMeshHit hit;
        return NavMesh.SamplePosition(point, out hit, sampleDistance, NavMesh.AllAreas);
    }

    public bool SetDestination(Vector3 point)
    {
        if (SamplePosition(point))
        {
            agent.SetDestination(point);
            return true;
        }

        return false;
    }

    public void Teleport(Vector3 point)
    {
        agent.Warp(point);
    }

    /// <summary>
    /// Return true if agent reached its destination
    /// </summary>
    public bool ReachedDestination()
    {
        if (agent.isActiveAndEnabled && !agent.pathPending)
        {
            if (agent.remainingDistance <= agent.stoppingDistance)
            {
                if (!agent.hasPath || agent.velocity.sqrMagnitude == 0f)
                {
                    return true;
                }
            }
        }

        return false;
    }

    public void ToggleObstacle(bool toggleOn)
    {
        agent.enabled = !toggleOn;
        obstacle.enabled = toggleOn;
    }

    void OnDrawGizmos()
    {
        if (agent == null) { return; }
        if (agent.path == null) { return; }

        Color lGUIColor = Gizmos.color;

        Gizmos.color = Color.red;
        for (int i = 1; i < agent.path.corners.Length; i++)
        {
            Gizmos.DrawLine(agent.path.corners[i - 1], agent.path.corners[i]);
        }
    }
}


texts: Is there a pattern for writing a turn-based server communicating with n clients over sockets?

texts:
I'm working on a generic game server that manages games for an arbitrary number of TCP socket-networked clients playing a game. I have a 'design' hacked together with duct-tape that is working, but seems  both fragile and inflexible. Is there a well-established pattern for how to write client/server communication that is robust and flexible? (If not, how would you improve what I have below?)

Roughly I have this:

While setting up a game the server has one thread for each player socket handling synchronous requests from a client and responses from the server.
Once the game is going, however, all threads except for one sleep, and that thread cycles through all players one at a time communicating about their move (in reversed request-response).

Here's a diagram of what I have currently; click for larger/readable version, or 66kB PDF.

Problems:

It requires players to respond exactly in turn with exactly the right message. (I suppose I could let each player respond with random crap and only move on once they give me a valid move.)
It does not allow players to talk to the server unless it's their turn. (I could have the server send them update about other players, but not process an asynchronous request.)

Final requirements:

Performance is not paramount. This will mostly be used for non-realtime games, and mostly for pitting AIs against each other, not twitchy humans.
The game play will always be turn-based (even if at a very high resolution). Each player always gets one move processed before all other players get a turn.

The implementation of the server happens to be in Ruby, if that makes a difference.


texts: Choosing 3D modeling software Maya or 3D max?

texts:
I've am a developer whose has spent most of my programming life developing web and business applications. I want to try my hand at something more challenging (but stay in the comfort of Visual Studio) ...perhaps XNA.

Want 3D modeling software would be best for someone developing XNA?
I have played with 3d MAX and Maya but never really did anything too involved.
What are the pros and cons between them (in terms of game development)?
Does one win out over the other for game development?
Or is it pretty much just preference?

I am new to game development and just trying to figure out the best tools to use before I really started. Any advice or other suggections would be greatly appreciated.


texts: Whats the best way to make my Unity game moddable?

texts:
Basically the title. I'm building a game with several NPCs and complex systems, and I want it to be nice and modular for modders right from the beginning. So far, I have looked into:

Asset Bundles, I don't completely understand these, probably will have to write some custom loading code? I don't know how/if this will let the modders write code.

Lua-Based Modding, I don't particularly like Lua, but I will fall back to it if I absolutely have to (The Unity-Lua Plugin makes this a seemingly very fast way.)

Exposed C# (original idea from this Question). But again, as stated in the question raw c# has a lot of disadvantages, not to mention the security risks and compatibility issues.

Minecraft-Style? Completely custom? Basically a lot of events and registries? I'm not sure about this option.
To give you an example, there are several Tribes in the game. Ideally, if a modder wanted to make a new tribe they would need to extend from some Tribe base class and then register/add their custom tribe to my AvailableTribes list. Not to mention the models, animations, and sounds for the Tribe NPCs and such.

Any help is appreciated!


texts:
My objects have a location in world coordinates (basically 1.0f is a meter).
If I simply draw my objects using their world coordinates, each meter will correspond to a pixel. Obviously that's not what I want.

Now, I don't want to have to apply a transformation to each and every object's position when I draw them. As I happen to be using XNA, and spritebatch allows a Matrix to be passed in as an argument in it's begin method, I was wondering if there is a way to pass the World to Pixel transformation in there. Any suggestions?

So far Matrix.CreateScale(new Vector3(zoom, zoom, 1)) puts the objects in their proper spot, but it also scales up the sprites. Is there a way to transform the position without enlarging the sprite?

Thanks


texts: How to share constant variables between Compute Shaders?

texts:
So, I have two compute shaders A and B (using unity and HLSL). Right now, before every dispatch, I send my mouse coordinates to both of them every update.
So, from my understanding, you can actually determine which register the mouse coordinates go to like so:
 float2 mxy :register(c1); // at the top of the shader

And by declaring this in both shaders, you can actually avoid sending the mouse coordinates twice.
The problem is, that this does not work! I've tried making cbuffers as well, but to no avail. (I don't actually know how to work with cbuffers on the CPU side that said)
TLDR: why can't I share variables between two compute shaders using float2 mxy :register(c1); ?


texts: Can I make a character solid but not lose non-physics behaviour?

texts:
My character can walk around in the world, but walks through other objects, for example a cylinder (stand-in for a cannon). To fix this I added a capsule collider to each of the character and cylinder, but that wasn't enough. Apparently I have to add a Rigidbody as well. [1] [2]

When I add a Rigidbody to either one, they collide as expected. However, when I add a Rigidbody to my character, it falls over when I move forward. When I add a Rigidbody to my cylinder, other functionality fails (it is supposed to shoot cannonballs, and they act strangely). If I enable Kinematics on either, they stop colliding.

Is there any other way to make the character and cylinder solid with respect to each other, without breaking existing non-physics functionality?


texts: Using Python what is the best way to perform heavy tasks in the background?

texts:
I'm generating large amounts of procedural map data on the fly, however my game engine doesn't rely on them to render the scene and I'd like to build it on in the background and pop it into the world when it's done (as seen in Minecraft).

I've tried using threadding.Thread but this seems to interfere with PyGame and the game-loop, even with a low amount of threads.

I'm currently trying to get everything happening using the multiprocessing module - although there's a fair amount of work here, and I don't want to find myself in the same case as with Thread.

Is this possible with python? Or should I stop rendering big chunks of data in one go, and rewrite my generation so that it can do lots of smaller jobs spread out over frames in the main thread?


texts:
i tried to look up my question but didn't really find an answer that works for my situation.

I'm using this unity asset called Dialoguer to create interactive dialogues.
What I'm trying to do is to pass a test in the asset, that test if a condition is true, then replace a specific part of the output text.

My problem right now is I can't find the right code to check for a specific string and replace it with another.

Please help


texts: How to enable IntelliSense for Unity scripts in Visual Studio?

texts:
I am using Visual Studio 2013 pro and Unity 4.6.

Whenever I write scripts (javascript or c#) for anything and open it up in Visual Studio, I don't get IntelliSense.

How to fix this issue?


texts: How to force XNA to render model very far away as a light dot?

texts: Making a space strategy game focusing on commanding a large fleet, with 1000+ ships per side.(I'm new in XNA 3D...below is a test screenshot. The ships will be scaled down another 2-5 times) When a unit is too far away, it's not rendered anymore.(obviously...when people get killed, they die) are there any way (as fast as possible) to force XNA to render the model into a 1-pixel dot if it's too far/smaller than 1 pixel? (I'm thinking about dynamic scaling, but that will probably drag down the performance severely)


texts: Is this a correct backward Euler implementation?

texts:
I want to simulate a mechanic object like this:

init acceleration a;
init velocity v;
init position x;
loop {
  get delta time dt;
  v = v + a*dt;
  x = x + v*dt;
}

I use the velocity (which is the derivative of position) at the end of each time step to approximate the new position. So this should be exactly what the backward euler method does.

Do I have an error in reasoning?


texts: Convert a modified Transform.forward to world space

texts:
I am trying to make an electricity system, where it is given the start and end points, and it works out a random sequence of points in the rough direction of the end point. These points are set as vertices on a line renderer, and it should end up joining up as a bolt of electricity. My problem is that it needs to move 'forward' from start to end. The easy solution is that the electricity comes from a game object, which is set to LookAt the end point. Then, every time it sets a 'nextPoint', it adds to the transform.forward.

nextPoint = new Vector3 ((startingPoint.forward.x + divergence.x),
        (startingPoint.forward.y + divergence.y), distance);

divergence is a Vector3 containing a random increase on the x and y axis, and 1 on the z axis.

This works, in a way. The problem is that it then assumes these are world-space coordinates. So the line will go from starting point, to (eg. 0.3, 0.75, 1), and then back to the end point. I can't find a localToWorld conversion for a vector though, so I am not sure how to get the transform.forward + whatever, converted from local to world space.


texts: I want to make a racing game.Can I have licensed cars without paying for licenses?

texts:
My idea was something similar to rFactor, but very easy to mod. There will be a step by step tutorial.

If I or somebody from the developers make the mods and publish them, do I still need licensing? Now it's just an idea, but I plan to make at least 1000-1500 cars from at least 150 manufacturers, and that would cost a fortune. A lot of the cars would be converted from other games like Forza or GT6 and others modeled by my team.


texts: Keeping over-shoulder camera view consistent at different screen resolutions

texts:
I have a player GameObject.
There is a character attached to it and a camera (both are children of the player GameObject).

The over-shoulder camera is positioned nicely.
The player should appear on the left edge of the screen.

Now when I change the viewport / screen size and make it larger, the camera doesn't keep it's view. I can see in the Inspector that the camera's view changes.

I don't understand in which way it does that.

What would I need to do to keep the player always on the left edge, no matter what the screen resolution is?

Thank you.

The upper image shows how I have planned / developed the camera view. This is what the camera view should look like.
The lower image shows how the camera changes at larger viewport.


texts: Batches Count increase when applying GPU instancing

texts:
I have camera across a very weird issue where my batches count significantly increase if I enable GPU instancing:
Before applying GPU instancing"

After Applying Gpu Instanching:

I have a pylon object where i am sharing the material with standar specular shader.


texts:
I am not sure how to go about what might be a simple task. I want directional arrow sprites to move along a curved path in 2d to show the player when to go.

I can use DoTween to create a path. But not sure if I should Instantiate a load of sprites(arrow) and move them along. Its seems wasteful.


texts: 1-bit game - How to change the palette for the entire game at runtime?

texts:
So I'm making a 1-bit color game, and would like to have an option in the menu to change what those two colors are so the player can adjust it to their liking. What is the simplest and/or best method to go about this? This would apply to the entire screen, not individual sprites/meshes, as I want to preserve the 1-bit color look.

Most of my assets are sprites, with a few flat meshes that are rendered without anti-aliasing so that they blend in with the sprites. They're all exported with the two standard colors I'm using (a yellow-ish off-white and a dark grey-ish-blue), but I can go back and re-export them in black and white if that is necessary for the suggested method.

My eventual plan is to support the basic black and white, a few monochrome monitor color schemes, and some color combinations that you'd see on 8-bit computers (C64, Apple, etc.).


texts: Changing a rotation and position of the camera smoothly when a button was clicked

texts:
How can I change a rotation and a position of the camera smoothly when a button is clicked in Unity?

I do not want to use Update function to implement this and I do not have a GameObject or Transform which it should look at, rather I want to tweak everything manually.

I would like to see the approach using C#.


texts: Microsoft XNA code sample wont work with blender model

texts:
I downloaded this code sample and integrated it into my game
http://xbox.create.msdn.com/en-US/education/catalog/sample/mesh_instancing

It works with the model that they supplied, but throws and exception whenever I use one of my models.

  The current vertex declaration does not include all the elements
  required by the current vertex shader. TextureCoordinate0 is missing.

I tried pluging my model into their original source code and same thing.
My model is an fbx from blender and has a texture.
This is the function that throws the error

GraphicsDevice.DrawInstancedPrimitives(
  PrimitiveType.TriangleList,
  0, 0,
  meshPart.NumVertices,
  meshPart.StartIndex,
  meshPart.PrimitiveCount,
  instances.Length
);


texts: How to stop my cube collider when it hits another collider using Transform.Translate?

texts:
As we know, Transform.Translate() ignores collisions. What functionality do I need to add to my code so that when my collider hits something, the physics system makes it stop?

Here is what I'm doing now:

void FixedUpdate()
{
    foreach (Touch touch in Input.touches)
    {
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
        {
            Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
            Vector2 pos = touchDeltaPosition;
            pos.x = touchDeltaPosition.x * speed;
            pos.y = touchDeltaPosition.y * speed;
            transform.Translate(pos.x,pos.y,0);

            Ray ray = Camera.main.ScreenPointToRay(touch.position);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, 1000))
            {
                if (hit.collider.tag=="Environment")
                {
                    Cubecall();
                }
            }
        }
    }
}
void Cubecall()
{
    anim.enabled = true;
}


texts: getting a black screen instead of the background image

texts:
Was creating a my first game in AndEngine and am only getting a black screen instead of getting the background image and play button..
Here the code
MainActivity

public class MainActivity extends BaseGameActivity {

private BoundCamera camera;
private float WIDTH = 800;
private float HEIGHT = 480;

@Override
public Engine onCreateEngine(EngineOptions engineOptions){
    return new LimitedFPSEngine(engineOptions,60);
}

@Override
public EngineOptions onCreateEngineOptions() {

    camera = new BoundCamera(0,0,WIDTH,HEIGHT);
    EngineOptions engineOptions = new
            EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new FillResolutionPolicy(),camera);
    engineOptions.getAudioOptions().setNeedsMusic(true).setNeedsSound(true);
    return engineOptions;
}

@Override
public void onCreateResources(OnCreateResourcesCallback pOnCreateResourcesCallback) throws IOException {

}

@Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) throws IOException {

}

@Override
public void onPopulateScene(Scene pScene, OnPopulateSceneCallback pOnPopulateSceneCallback) throws IOException {

}
}

BaseScene.java

public abstract class BaseScene extends Scene {

protected Engine engine;
protected Activity activity;
protected ResourceManager resourceManager;
protected VertexBufferObjectManager vbom;
protected Camera camera;

public BaseScene(){
    this.resourceManager = ResourceManager.getInstance();

    this.activity = resourceManager.activity;
    this.engine = resourceManager.engine;
    this.vbom = resourceManager.vbom;
    this.camera = resourceManager.camera;

    createScene();
}

public abstract void createScene();
public abstract void onBackKeyPressed();
public abstract SceneManager.SceneType getSceneType();
public abstract void disposeScene();
}

SceneManager.java

public class SceneManager {

private BaseScene mainMenu;
private BaseScene gameScene;

private BaseScene currentScene;

private static final SceneManager INSTANCE = new SceneManager();

private SceneType currentSceneType = SceneType.SCENE_MENU;

private Engine engine = ResourceManager.getInstance().engine;

public enum SceneType
{
    SCENE_MENU,
    SCENE_GAME
}

public void setScene(BaseScene scene){

    engine.setScene(scene);

    currentScene = scene;

    currentSceneType = scene.getSceneType();

}

public static SceneManager getInstance(){
    return INSTANCE;
}

public SceneType getSceneType(){
    return currentSceneType;
}
}

I have 2 more classes MainMenu and ResourceManager
What is the problem here?


texts: Is there a tool to help quickly define animation frames from non-uniform size sprite sheets?

texts:
Many of the sprite sheets online have non-uniform sized rectangles as the animation frames and often use a portion of the image for credits, etc., this makes it hard for a game engine to correctly clip the sheets.

Is there any tool that can help you quickly define frames in a sheet, export animation data which the game engine would use?


texts:
Assume we have a player on a map, whereby the grid is represented as a floating point.

When a player is moving, they have an x and y velocity.

How to do you properly apply their movement each gametic?

By that I mean: do you keep nudging the player forward by one map unit and repeat that by the velocity? Where is that fine line where I say "we don't go any smaller movements than this like 0.5, or 0.25, etc"

Further, is there a way to optimize this to be able to make movement fast computationally? I thought of having some kind of blocks where you can quickly check if you'd intersect anything and make some optimizations, but I have no idea if this is good, bad, or how it should be done.

Update: Suppose you have a projectile traveling 100 map units North, and it would collide with an object 50 map units North of it. In the period of one world 'ticking', would you just halt it in a dead on collision (assuming the line is impassible), or would you detect a collision and then do something after it since that remaining 100 map unit velocity (like maybe if it's on an angle then cancel its Northward momentum and continue trying to move it to the East/West.


texts: XNA: Networking, what is a good bytes per second sent/received number

texts:
I am working with XNA networking, on the XBOX.

I was wondering what is a safe number to stay under in the bytes sent and received when it comes to the xbox. Obviously various factors will effect the number, and you want as little packet data as possible to keep things smooth, but what is a good number for that?

(Using : networksession.bytespersecondsent and networksession.bytespersecondreceived to measure the number.)

A answer is found in the comment of the accepted post. Thanks!


texts: OnTriggerEnter / OnTriggerStay triggers multiple times and is not been call a second time

texts:
I am working on a feature that when the Player pass thru a door, a message will popup on the screen.
I'm having few problems: Debug.Log gives me from 2 to 6 logs when I pass thru the collider plane and when I come back to the same collider plane the script it is not been call a second time.
What I'm trying to achive is that Debug.Log gives me only one log and every time I pass thru the collider the script runs again.
so here is my code:

function OnTriggerEnter (other : Collider) { //OnTriggerStay gives the same result
    if (other.tag == "Player") {
    isColliding = true;
  } else {
    isColliding = false;
  }
}
function OnGUI() {
  if (isColliding) {
      Debug.Log(isColliding);
    //Application.ExternalCall('hive.OpenHiveAlert', 'test');
  }
}
function OnTriggerExit() {
    Destroy(this);
}

Any help would be appreciated, thanks.


texts: How should I generate and store the boundries of a cave?

texts:
I am making a small cave copter game (seriously, where did this type of game come from anyway) and I am trying to figure out how to make and store the procedural generated walls. I am thinking about creating the walls by randomly picking two points away from the center of the screen. They will be no closer than the height of helicopter and no further than the edge of the screen, weighted to prefer to go in the same direction as the point prior so I end up with stalactites and stalagmites and not just noise, at set intervals of distance. To store, perhaps parallel arrays/lists, one for distance from center to top screen and one for distance from center to bottom.

Am I way off base with my thinking? I just want the cave to be varied and challenging, I just have never worked with generating data like this.

Edit: Woah, I just realized that my idea would lead to a player being able to stay in the middle of the screen and win. That isn't right at all. So the very basis of how I was going to generate is wrong.

Edit 2: I also realized I left out a very crucial point. Part of the mechanics of the game will let the player go backwards therefor the data structure should be continuous.


texts: Activate object that have button component?

texts:
I'm trying to activate the array object that have button component.

 public GameObject[] weapon_carry_pistol = new GameObject[3];
 public int p1_carry,activeObjects;

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

  p1_carry =  weapon_carry_pistol[0].GetComponentsInChildren<Button>().Length; // 6 objects

        for (int i = 0; i < activeObjects; i++)
    {
        weapon_carry_pistol[0].GetComponentsInChildren<Button>()[i].enabled = true;
    }

}

This script do activate the button component but not the whole game object. If I change "Button" to "GameObject" I get error //.GetComponent requires that the requested component 'GameObject' derives from MonoBehaviour or Component or is an interface.//


texts: Adjusting a skeleton to a Specific Stance

texts: Imagine having a climbing wall and you take 4 adjacent handholds and footholds where  together they create a stance. Is there any algorithm or technique with which it would give you a realistic human pose? Currently im adjusting the skeleton by firstly finding the center of the 4 holds where then i construct the chest shoulder and pelvis accordingly. And by the use of IK i give position to the remaining limbs being which the arms and legs. Is there any other more elegant/better technique how to do such positioning of a skeleton ? As how i am adjusting the skeleton isnt so much of a realistic pose.All is done in 2D


texts: How can I make the switch from immediate mode to VBOs?

texts:
I've been using OpenGL for a short time now- and I'd like some clarification on VBOs.
As I understand it, a VBO is an object stored on VRAM. In immediate mode, to apply a texture we simply bind it and specify the texture coordinates before the vertex coordinates, however it doesn't seem that way with VBOs.

Question 1: Can I specify texture data in a VBO? What portion of the data?

Normally when I make a game in 2d I'd store all of my objects in instances of different classes, then when my drawing routine comes up- just draw the objects that are on screen. With a 3D environment it would be a bit more difficult to just draw the objects on the screen but with some math I'm sure it's doable.

Question 2: Once we figure out which objects need to be rendered, would it be acceptably fast to send those corresponding objects an "apply" request, and have them apply themselves? Or is there a better way?

Question 3: If I have a completely dynamic map, but with objects that won't change very often, are there any guidelines as to the performance differences between  GL_STATIC_DRAW and GL_DYNAMIC_DRAW?

Final Question: Should I even consider using vertex lists? Or are VBOs just a better option?


texts: How to approach players beeing overlapped by high isometric tiles?

texts:
I'm making a browser game wich is based on PHP, MySQL and Javascript. It has an isometric world where the player can move and see other players/NPCs. But if a tile in the foreground is so high that it overlaps the tile behind it (e.g. a building or a group of trees, etc.), how to approach players beeing overlapped as well? I don't wan't players to be able to "hide" behind high tiles so that the characters of other players or the own character is not visible.

I thought about involving transparency by "making a sandwich" with a tile layer at the bottom, then the player and then the same tile layer on top, but slightly transparent. But when I tried it, the player looked like some king of ghost floating around and it was not clear where the player stands exactly.

Other games (like Age of Empires) managed this by displaying overlapped characters as an outline but this is really complicated/CPU-intensive using PHP, as far as I know.

I have no idea on how to approach this problem. Any ideas?


texts: I am a beginning indie developer, and I want to get the word out about my game. What sites can I go to to ask about reviews of my game, and where might I be able to talk about and get feedback on my game from players?


texts:
I'm not making a game with portals in it (one way or bidirectional). These portals instantly teleport characters from one location to another. How would I implement pathfinding?

Here's an animation showing the portals in action, and different paths taken: http://www.makeitshareit.com/animation/86137

How do I perform pathfinding whilst taking in the possibility of using the portals as shortcuts? If I just use A*, the portals may wreak havoc with the admissibility requirement. How can I also make it reasonably efficient, such as avoiding quadratic complexity with respect to the number of portals?


texts:
I'm trying to make a button that plays a sound when hovering above it with the cursor

So far I created a class which extends the scene2d TextButton and I'm adding a FocusListener. The problem is that the sound is played a lot of times when hovering because this event fires not only once but as long as the button is focused.

//When button is hovered
this.addListener(new FocusListener() {

        public boolean handle(Event e) {

            SoundManager.play(hoverSound);

            return true;
        }
});

I also tried to make a variable soundPlayed which toggles if the sound is played once but this leads to the sound playing only one time because I don't know how to detect if the button is not focused anymore so i can reset the variable.

Thanks for the help.


texts: Simulating elastic ball collisions quickly escalates to disaster

texts:
I'm trying to learn HTML canvas and was working on a basic physical simulation, where a number of balls are drawn and set in motion, and the program simulates them colliding and bouncing off the walls and each other.

Here's the simulation.

Each ball is initially given a random position, direction, and a constant starting velocity. For simplicity, a ball's mass is simply equal to its radius. The velocity vectors are stored as (x,y) instead of polar coordinates to make the calculations simpler and the simulation faster, but this apparently has unintended consequences.

In the simulation linked above, I'm starting with ten balls, and each ball has an initial velocity magnitude of 3, so the total initial "speed" of the system should be 30 (= 10 * 3).  On each frame, I calculate the total speed of all the balls and read it out in a form field, and with uniform balls of size 10, the total speed seems to stay a few units under 30. The same is true of the min and max radius are decreased so all the balls are size 5, or increased to 20: the total speed stays relatively uniform.

However, interesting things happen when the balls vary in size. If the minRadius is changed to 5 and maxRadius to 15, for example, you'll notice that the total speed of the system starts climbing over time. The bigger the difference, the faster the speed grows out of control.

SO my first guess is that I screwed up the physics, but I can't figure out how. My other guess is that this is caused by accumulating floating point error, but it's interesting that it only grows upwards, and never towards zero. Also, it does seem to have a limit; while it constantly fluctuates, it seems to be capped at some value related to the delta between the minimum and maximum ball size.

My question is really to understand why this is happening?  Did I just screw up something simple, or is something more sinister going on?


texts: Delay/Pause game while displaying countdown 3,2,1 go

texts:
I have already a running script of countdown and it works fine , the problem is that I want to pause or delay the game while the countdown is displaying, the moment countdown finished the player is already dead. Here is my code

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

public class jb : MonoBehaviour {
    private string countdown = "";
    private bool showCountdown = false;
    public AudioSource noise1;
    public AudioSource noise2;
    public Sprite sprite2;
    public Vector2 jump = new Vector2 (0,300);
    private SpriteRenderer spriteRenderer;
    void Start () {
        //GetComponent<Rigidbody2D>().velocity = Vector2.right * speed;
        StartCoroutine(getReady());

        spriteRenderer = GetComponent<SpriteRenderer>();
        noise1.GetComponent<AudioSource>().Play();

    }

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

        if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
        {
           Vector2 touchPosition = Input.GetTouch(0).position;
            GetComponent<Rigidbody2D>().AddForce(jump);
            //noise1.GetComponent<AudioSource>().Play();
        }

        Vector2 screen_position = Camera.main.WorldToScreenPoint (transform.position);
        if(screen_position.y > Screen.height || screen_position.y < 0)
        {
            noise1.GetComponent<AudioSource>().Stop();
            noise2.GetComponent<AudioSource>().Play();
            StartCoroutine(Die());
        }

    }

    void OnCollisionEnter2D(Collision2D det)
    {
        noise1.GetComponent<AudioSource>().Stop();
        noise2.GetComponent<AudioSource>().Play();
        StartCoroutine(Die());

    }

    IEnumerator Die(){
        PlayerPrefs.SetString( "previousLevel", SceneManager.GetActiveScene().name );
        spriteRenderer.sprite = sprite2;
        yield return new WaitForSeconds (2);
        SceneManager.LoadScene("score");
     }

    IEnumerator getReady()
    {
        showCountdown = true;

        countdown = "3";
        yield return new WaitForSeconds (1);

        countdown = "2";
        yield return new WaitForSeconds (1);

        countdown = "1";
        yield return new WaitForSeconds (1);

        countdown = "GO";
        yield return new WaitForSeconds (1);

        showCountdown = true;
        countdown = "";
    }

    void OnGUI ()
    {
        if (showCountdown)
        {
            GUI.color = Color.red;
            GUI.Box ( new Rect (Screen.width / 2 - 100, 50, 200, 175), "GET READY");

            // display countdown
            GUI.color = Color.white;
            GUI.Box (new Rect (Screen.width / 2 - 90, 75, 180, 140), countdown);
        }
    }
}

what can I do to pause the game? I tried invoke (by creating another function and copying everything over there) in update call but it didn't work.


texts: calculate the offset between a quad and the mouse position Opengl

texts:
I am working on a very simple "GUI framework" for my game.

As you can see from the GIF, i have a window object that can be selected when the mouse is inside of it and dragged, when the left mouse button is being pressed.

I tried to solve the problem this way:

Basically i calculate the x and y component of the distance between the center of the window and the mouse cursor. I then add the component values to the window function, which looks something like:

//mousePosition is a Vector2() that stores the mouse position
//x_component is a float, calculated by doing:
//float x_component = mousePosition.x - window.getPosition().x;
//same for the y_component variable.

window.setPosition(Vector2(mousePosition.x + x_component, mousePosition.y + y component));//set position takes in a Vector2

But for some reason, this is not working. I think that it's because we are not taking in consideration the fact that the x or y component could be negative, in relation to where we press the mouse inside the window.

Can someone help me?


texts: First Person Shooter game agent development

texts:
I would like to apply (program) the Artificial intelligence methods to create game bots for first person shooter games. Do you have any knowledge from where can I start to develop as a Linux user? Do you have a suggestion for an easy-to-start game for which I can develop bots easily, caring more about the result of my algorithms rather than spending a lot of time dealing with the game code? I've read some publications about the applied methods to Quake 3 (c) and Open Arena. But I couldn't find the source codes and manuals describing how to start coding( for compiling, developing ai and etc.).

I appreciate your help.


texts: Unity access method from separate script

texts:
I'm learning Unity3D and I'm practising accessing game object scripts from other objects. For the most part I've got it down, but I've run into a weird issue causing a NullPointerException.

I've set up a GameObject, with the following script attached to it:

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {
public Player[] players;

// Use this for initialization
void Start () {
    players [0].currentPosition = 0;
    players [1].currentPosition = 1;
    players [2].currentPosition = 2;
}

// Update is called once per frame
void Update () {
    foreach(Player p in players)
    {
        if(p.mFormationType == Player.FORMATIONTYPE.ATTACK)
            p.transform.position = p.attackPositions[p.currentPosition];
        else
            p.transform.position = p.defensivePositions[p.currentPosition];
    }
}

public void swapPositions(Player selected)
{
    Debug.Log (selected.currentPosition);
    if(selected == null)
        Debug.Log("Balls - " + selected.gameObject);

    if(selected.currentPosition != 0)
    {
        int previousPos = selected.currentPosition;

        players[0].GetComponent<Player>().currentPosition = previousPos;
        selected.currentPosition = 0;
    }
}
}

And I've set the Player objects within the UI. I then later attempt to do this when I click on one of the Player objects:

void OnMouseOver()
{
    if(this.currentPosition == 0)
        return;

    if(Input.GetMouseButtonDown(0))
    {
        PlayerController pc = this.controller.GetComponent<PlayerController> ();
        pc.swapPositions (this);
    }
}

But it results in an NPE within the swapPositions method in the PlayerController class, when it attempts to access players[...]

I've stepped through and at the start of the PlayerController script they're all there and set up perfectly, but later on, they're null.

Can anyone explain why this is happening please?

Thanks in advance.


texts: Prefabs property is not overriding when changing from editor script?

texts:
In unity we can have different instances of a prefab with different properties.
Unity represents the overridden property with bold characters. This works fine when manually change the value of prefab instance. But when I do it using a editor script, it do not turn bold and the property value changes to the source prefab when I play the game.

Here is an example of the code:

using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(testScript))]
public class editor : Editor {
    public override void OnInspectorGUI(){
        DrawDefaultInspector ();
        testScript scrt= (testScript)target;
        if (GUILayout.Button ("button")) {
            scrt.test();
        }
    }
}

.

using UnityEngine;
public class testScript: MonoBehaviour {
   test(){
       gameManager  =GameObject.Find("GameManager");
       gameManager.GetComponent<gameManager>().arr = new GameObject[3];
   }
}

.

using UnityEngine;
public class gameManger:MonoBehaviour{
    public GameObject[] arr;
}

The arr array in gamemanager class is not overridden and it changes to the source prefab value on play.

  EDIT:

actual function called from editor script

    public void assignPortalPass(){
    GameObject gameManagerObj = GameObject.Find ("Game Manager");
    gameManager gameManagerScript = gameManagerObj.GetComponent<gameManager> ();
    Transform passed = GameObject.Find ("passed").transform;
    int noOfChild = passed.childCount;
    if (noOfChild != gameManagerScript.noOfPortals) {
        Debug.LogError ("Check passed objects and noOfPortals (class gameManager) because both values are different");
        return;
    }
    Undo.RecordObject(gameManagerObj, "Made some changes to gameManager");
    //as suggested by the answer

    gameManagerScript.portalPass = new GameObject[noOfChild];
    for (int i = 0; i < noOfChild; i++) {
        gameManagerScript.portalPass [i] = passed.GetChild (i).gameObject;

    }
}

}


texts: Getting the number of fragments which passed the depth test

texts:
In "modern" environments, the "NV Occlusion Query" extension provides a method to get the number of fragments which passed the depth test. However, on the iPad / iPhone using OpenGL ES, the extension is not available.

What is the most performant approach to implement a similar behaviour in the fragment shader?

Some of my ideas:

Render the object completely in white, then count all the colors together using a two-pass shader where first a vertical line is rendered and for each fragment the shader computes the sum over the whole row. Then, a single vertex is rendered whose fragment sums all the partial sums of the first pass. Doesn't seem to be very efficient.
Render the object completely in white over a black background. Downsample recursively, abusing the hardware linear interpolation between textures until being at a reasonably small resolution. This leads to fragments which have a greyscale level depending on the number of white pixels where in their corresponding region. Is this even accurate enough?
Use mipmaps and simply read the pixel on the 1x1 level. Again the question of accuracy and if it is even possible using non-power-of-two textures.

The problem wit these approaches is, that the pipeline gets stalled which results in major performance issues. Therefore, I'm looking for a more performant way to accomplish my goal.

Using the EXT_OCCLUSION_QUERY_BOOLEAN extension

Apple introduced EXT_OCCLUSION_QUERY_BOOLEAN in iOS 5.0 for iPad 2.

"4.1.6  Occlusion Queries

Occlusion queries use query objects to track the number of fragments or
samples that pass the depth test. An occlusion query can be started and
finished by calling BeginQueryEXT and EndQueryEXT, respectively, with a
target of ANY_SAMPLES_PASSED_EXT or ANY_SAMPLES_PASSED_CONSERVATIVE_EXT.

When an occlusion query is started with the target
ANY_SAMPLES_PASSED_EXT, the samples-boolean state maintained by the GL is
set to FALSE. While that occlusion query is active, the samples-boolean
state is set to TRUE if any fragment or sample passes the depth test. When
the occlusion query finishes, the samples-boolean state of FALSE or TRUE is
written to the corresponding query object as the query result value, and
the query result for that object is marked as available. If the target of
the query is ANY_SAMPLES_PASSED_CONSERVATIVE_EXT, an implementation may
choose to use a less precise version of the test which can additionally set
the samples-boolean state to TRUE in some other implementation dependent
cases."

The first sentence hints on a behavior which is exactly what I'm looking for: getting the number of pixels which passed the depth test in an asynchronous manner without much performance loss. However, the rest of the document describes only how to get boolean results.

Is it possible to exploit this extension to get the pixel count? Does the hardware support it so that there may be hidden API to get access to the pixel count?

Other extensions which could be exploitable would be debugging features like the number of times the fragment shader was invoked (PSInvocations in DirectX - not sure if something simila is available in OpenGL ES). However, this would also result in a pipeline stall.


texts: How to access network player from internet

texts:
I just followed a guide about basic UNet tut Here, Its spawning network car player which can be controlled by local player. I can make or join server through Network Manager HUD which is provide by the unity.

I am able to run and connect application on my LAN on different PCs but failed to connect it on other network. I don't know what are the reasons. Do I need to make or purchase a server for it or I am doing something wrong.


texts:
i wanna walk to terrain...
first i created the terrain

void desenha_terreno(float px, float pz){

for (int z = 0; z < iwidth-1; z++)
{
    glBegin(GL_TRIANGLE_STRIP);

    for (int x = 0; x < iheight-1; x++)
    {
        // for each vertex, we calculate the grayscale shade color,
        // we set the texture coordinate, and we draw the vertex.
        /*
           the vertices are drawn in this order:

           0  ---> 1
                  /
                /
             |/
           2  ---> 3
        */

        // draw vertex 0
        glColor3f(terreno[x][z][1]/255.0f, terreno[x][z][1]/255.0f, terreno[x][z][1]/255.0f);
        glTexCoord2f(0.0f, 0.0f);
        glVertex3f(terreno[x][z][0], terreno[x][z][1], terreno[x][z][2]);

        // draw vertex 1
        glTexCoord2f(1.0f, 0.0f);
        glColor3f(terreno[x+1][z][1]/255.0f, terreno[x+1][z][1]/255.0f, terreno[x+1][z][1]/255.0f);
        glVertex3f(terreno[x+1][z][0], terreno[x+1][z][1], terreno[x+1][z][2]);

        // draw vertex 2
        glTexCoord2f(0.0f, 1.0f);
        glColor3f(terreno[x][z+1][1]/255.0f, terreno[x][z+1][1]/255.0f, terreno[x][z+1][1]/255.0f);
        glVertex3f(terreno[x][z+1][0], terreno[x][z+1][1], terreno[x][z+1][2]);

        // draw vertex 3
        glColor3f(terreno[x+1][z+1][1]/255.0f, terreno[x+1][z+1][1]/255.0f, terreno[x+1][z+1][1]/255.0f);
        glTexCoord2f(1.0f, 1.0f);
        glVertex3f(terreno[x+1][z+1][0], terreno[x+1][z+1][1], terreno[x+1][z+1][2]);

    }
    glEnd();
}
}

I can move the camera with the functions:

void keyboard (unsigned char key, int x, int y) {
if (key=='w')
{
    float xrotrad, yrotrad;
    yrotrad = (yrot / 180 * 3.141592654f);
    xrotrad = (xrot / 180 * 3.141592654f);
    xpos += float(sin(yrotrad))*5;
    zpos -= float(cos(yrotrad))*5;
    ypos -= float(sin(xrotrad))*5;

}

if (key=='s')
{
    float xrotrad, yrotrad;
    yrotrad = (yrot / 180 * 3.141592654f);
    xrotrad = (xrot / 180 * 3.141592654f);
    xpos -= float(sin(yrotrad))*5;
    zpos += float(cos(yrotrad))*5;
    ypos += float(sin(xrotrad))*5;
}

if (key=='d')
{
    float yrotrad;
    yrotrad = (yrot / 180 * 3.141592654f);
    xpos += float(cos(yrotrad))*5;
    zpos += float(sin(yrotrad))*5;
}

if (key=='a')
{
    float yrotrad;
    yrotrad = (yrot / 180 * 3.141592654f);
    xpos -= float(cos(yrotrad))*5;
    zpos -= float(sin(yrotrad))*5;
}

if (key=='q')
{
    yrot += (float) -0.5*5;    //set the xrot to yrot with the addition of the difference in the x position
}

if (key=='e')
{
    yrot += (float) 0.5*5;    //set the xrot to yrot with the addition of the difference in the x position
}

if (key=='r')
{
    xrot += (float) -0.5*5;    //set the xrot to yrot with the addition of the difference in the x position
}

if (key=='f')
{
    xrot += (float) 0.5*5;    //set the xrot to yrot with the addition of the difference in the x position
}

if (key==27)
{
    exit(0);
}

glutPostRedisplay();
`

and, i change the position with the values of x,y,z positions

    // clear screen and depth buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();

//glTranslatef(0.0f, 0.0f, -cRadius);
glRotatef(xrot,1.0,0.0,0.0);
glRotatef(yrot,0.0,1.0,0.0);  //rotate our camera on the    y-axis (up and down)

glTranslated(-xpos,-ypos,-zpos); //translate the screen to the position of our camera

// set the camera position
//gluLookAt(cameraX, cameraY, cameraZ, lookX, lookY, lookZ, 0.0, 1.0, 0.0);

// set the current texture to the land texture
//glBindTexture(GL_TEXTURE_2D, land);

    desenha_terreno(xpos,ypos);
    glEnable(GL_BLEND);

// enable read-only depth buffer
glDepthMask(GL_FALSE);

// set the blend function to what we use for transparency
glBlendFunc(GL_SRC_ALPHA, GL_ONE);

// set back to normal depth buffer mode (writable)
glDepthMask(GL_TRUE);

// disable blending
glDisable(GL_BLEND);

    glFlush();

    glutSwapBuffers();

    angle++; //increase the angle
   }

well... i need to walk to the terrain, above the terrain, help me please!


texts:
After adding velocity to my game, I feel like my textures are twitching. I thought it was just my eyes, until I finally captured it in a screenshot:

The one on the left is what renders in my game; the one on the right is the original sprite, pasted over. (This is a screenshot from Photoshop, zoomed in 6x.)

Notice the edges are aliasing -- it looks almost like sub-pixel rendering. In fact, if I had not forced my sprites (which have position and velocity as ints) to draw using integer values, I would swear that MonoGame is drawing with floating point values. But it isn't.

What could be the cause of these things appearing blurry? It doesn't happen without velocity applied.

To be precise, my SpriteComponent class has a Vector2 Position field. When I call Draw, I essentially use new Vector2((int)Math.Round(this.Position.X), (int)Math.Round(this.Position.Y)) for the position.

I had a bug before where even stationary objects would jitter -- that was due to me using the straight Position vector and not rounding the values to ints. If I use Floor/Ceiling instead of round, the sprite sinks/hovers (one pixel difference either way) but still draws blurry.


texts: Good ways to implement cutscenes in 2d RPG

texts:
I want to know of some different ways to implement cutscenes in a 2D RPG game with SDL2 and C++.

My current idea is creating different functions in different files for different cutscenes and running them whenever I need to show a cutscene.

However, this doesn't seem like a very easy or simple way to render cutscenes. How would I effeciently implement cutscenes?


texts: Math: determining a proper procedural vector for sine-movement

texts:
My Problem
Suppose you have an object moving along the x-axis, wobbling up and down. Movement code might look like this:
x += 1;
y = Sin(x);
Move((x,y) * speed);

When I try to figure out a method to move my object along a sine wave, say diagonally, I run into trouble. I am not sure what kind of Vector math I use to calculate the appropriate Sine movement along a diagonal where both X and Y values must be altered.
The visual result would be the object bobbing up and down and sideways but still moving in its given direction.
How do I enable sine movement along a diagonal?


texts: Realtime multi-player game design principles for Node.js

texts:
I've been reading the Valve article on multi-player networking which has been adapted from Yahn Bernier's 2001 paper called Latency Compensating Methods in Client/Server In-game Protocol Design and Optimization. I'm making a realtime multi-player game using a node.js server connected to clients through socket.io and I have a few questions regarding the principles detailed below:

Entity Interpolation

  [Interpolation] prevents the jittery motion this would ordinarily lead
  to by buffering server updates then playing them back with the gaps
  smoothly interpolated between. It can also protect against glitches
  caused by packet loss.

Client-Side Prediction

  Prediction is the notion of the client predicting the effects of the
  local player's actions without waiting for the server to confirm them.
  An entity's predicted state is tested against server commands as they
  arrive until either a match or a mis-match is detected.

Lag Compensation

  Lag compensation is the notion of the server using a player's latency
  to rewind time when processing [user input], in order to see what the
  player saw when the command was sent. In combination with prediction,
  lag compensation can help to combat network latency to the point of
  almost eliminating it from the perspective of an attacker.

Do the principles apply to TCP as they do to UDP and would there be any differences in implementation? I can see that the entity interpolation would not need to protect against packet loss but thats about it.
Can I even communicate between a server and web-browser and vice-versa using UDP and Node.js?
Since the paper is over a decade old are these principles still in use or has other technology appeared?

Any help would be much appreciated.


texts: Have any video game designs used non-uniform random numbers in interesting ways?

texts:
A variety of video games use uniformly distributed numbers to decide the outcome of an event, such as a "50% chance to hit" almost always means to check if a random floating point number from 0-1 is greater than 0.5. Many games will layer a few of these uniform percentages on top of each other, for instance a D&D hit roll is a uniformly distributed number from 1-20, except that 1 and 20 have special outcomes. To my mind it seems like things like critical hits are added by designers to try and emulate the fact that in reality hitting/missing or winning/losing is not actually a binary outcome.

In many cases the real life amount of "damage" done by an attack would likely be closer to a gaussian/bell curve distribution, which many results in the middle but the occasional very exciting outlier and smooth curve connecting them. Dice games like Settlers of Catan emulate gaussian distributions by adding together multiple independent rolls, but I feel like I've almost never seen this mechanic in video games.

It seems like games like Civilization (Sid Meier talked extensively at GDC about player perception not matching the actual math used in the game) would benefit from results that matched how things work in the real world. Have any video games used a gaussian or otherwise non-uniform distribution of random numbers in interesting ways?


texts: How can I cause the latest touch event to interrupt a prior event in Cocos2D?

texts:
In Cocos2D for iPhone, I want the latest touch event to interrupt another and ignore the last touch. Let me know if I need to elaborate more, but basically my game consists of a lot of finger dragging, and if the player ever switched fingers, there may be some overlap, and for the way things are setup, it may detect it as a new touch.

I think I have things almost on the right track, but my third touch does not work correctly. For instance:

Touch A begins and held
Touch B begins and held
Touch A let go
Touch A begins and held <-This should
interrupt Touch B

In my delegate I put [glView setMultipleTouchEnabled:YES]; because I believe I need multiple touches enabled.

In my CCLayer class with my added map and sprite I am using targeted touch delegate (i.e. ccTouchBegan NOT ccTouchesBegan, etc)

I am accessing a touch object with touch = [[[event allTouches] allObjects] objectAtIndex:0];, however I don't have much understanding what index is considered the latest touch or even a process to always get the latest touch.


texts: Modifying A* pathfinding based on size of moving object

texts:
I've implemented basic A* pathfinding in my top-down 2D game, and I'm almost ready to test it, but I thought of something while adding the movement code to my enemies that I think could affect the pathfinding.

My tiles are 64x64 px, and most enemies are as well. However, I do have some boss monsters that are larger than that. My initial thought was that to move to their goal, they have to move toward each node in their path, and to determine whether they've arrived at that node and to start targeting the next node, I need to test the distance between the enemy and their current target node. So what happens if, for example, their next node is next to a wall, and because of their size, their center is too far to "reach" the node?

My solution to that would be to check if the distance between their center of mass and the next node location is less than half the enemy's width plus maybe 10 px. However, what if one of their movement nodes is in between two tiles, and they're too large to fit through the two objects the node goes between? Is there a simple way to modify A* that takes size into account?


texts: Unity3D - How to create flat map render based on endless noise data

texts:
The Project

I'm working actually on a Endless Map Generator (with chunks, height-map noise, threading system, etc..)
This is actually what "dev data display" look like:

The Goal

Now I want to create another flat rendering (for example the mini-map) with simple Sprite (I have some Photoshop Brush, or other images).

Example (from internet):

Questions

This post isn't really about seed data recovery but more How do I transform that data into nice map ?

Do I have to keep doing 3D or replace by a 2D Canvas ?
Do Texture is good for the job ? Or it will be easier to instantiate multiple sprite ? (Or maybe a shader ?)
I have a special question for Shapes (like actually water). I didn't found anything who can help me to transform a list of dots (like all coords next to the ground) into a smooth shape who can be used on shader or other display.

A already try to use plane (instead of generated mesh) and apply the texture with a Level Of Detail system to smooth the closest part of the map. But it's still very ulgy.


texts: Android LibGDX 1.9.6 Augmented Reality captured images are black

texts:
Using LibGDX for an AR application and capturing image and merging lines and texts on LibGDX with image with this code.

 private Pixmap merge2Pixmaps(Pixmap mainPixmap, Pixmap overlayedPixmap) {
    // merge to data and Gdx screen shot - but fix Aspect Ratio issues
    // between the screen and the camera
    Pixmap.setFilter(Filter.BiLinear);
    float mainPixmapAR = (float) mainPixmap.getWidth() / mainPixmap.getHeight();
    float overlayedPixmapAR = (float) overlayedPixmap.getWidth() / overlayedPixmap.getHeight();
    if (overlayedPixmapAR < mainPixmapAR) {
        int overlayNewWidth = (int) (((float) mainPixmap.getHeight() / overlayedPixmap.getHeight())
                * overlayedPixmap.getWidth());
        int overlayStartX = (mainPixmap.getWidth() - overlayNewWidth) / 2;
        // Overlaying pixmaps
        mainPixmap.drawPixmap(overlayedPixmap, 0, 0, overlayedPixmap.getWidth(), overlayedPixmap.getHeight(),
                overlayStartX, 0, overlayNewWidth, mainPixmap.getHeight());
    } else {
        int overlayNewHeight = (int) (((float) mainPixmap.getWidth() / overlayedPixmap.getWidth())
                * overlayedPixmap.getHeight());
        int overlayStartY = (mainPixmap.getHeight() - overlayNewHeight) / 2;
        // Overlaying pixmaps
        mainPixmap.drawPixmap(overlayedPixmap, 0, 0, overlayedPixmap.getWidth(), overlayedPixmap.getHeight(), 0,
                overlayStartY, mainPixmap.getWidth(), overlayNewHeight);
    }
    return mainPixmap;
}

In 1.9.6 Pixmap.setFilter(Filter.BiLinear); is not available and it does not merge 2 pixmaps correctly. I tried setting BiLinear filter for both pixmaps or one at a time but none works.


texts: How do I stop my player or camera from jittering during player movement?

texts:
In my game, I have a third person character. The player moves with a rigidbody and has isKinematic set off with interpolate on. In the script, it moves with Rigidbody.MovePosition with the y position froze. Here's my player script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
   public float speed;

   public Rigidbody rb;

   public Transform camPos;

   // Start is called before the first frame update
   void Start()
   {
       rb = GetComponent<Rigidbody>();
       camPos = Camera.main.transform;
   }

   private void FixedUpdate()
   {
       if (Input.GetKey("w"))
       {
           rb.MovePosition(transform.position + (camPos.forward * speed * Time.fixedDeltaTime));
       }
       if (Input.GetKey("s"))
       {
           rb.MovePosition(transform.position + (-camPos.forward * speed * Time.fixedDeltaTime));
       }
       if (Input.GetKey("d"))
       {
           rb.MovePosition(transform.position + (camPos.right * speed * Time.fixedDeltaTime));
       }
       if (Input.GetKey("a"))
       {
           rb.MovePosition(transform.position + (-camPos.right * speed * Time.fixedDeltaTime));
       }

       rb.velocity = Vector3.zero;
   }
}

For my camera, I have it lookat the player and lag behind smoothly. Here's that script:
//Hakeem Thomas
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CamPos : MonoBehaviour
{
    public Transform target;
    public float smoothTime = 0.5F;
    private Vector3 velocity = Vector3.zero;

    public GameObject player;

    private float mouseX, mouseY;
    public int mouseX_Speed, mouseY_Speed;

    //mouseSensitivity
    public int turnSpeed;

    void getMouseXY()
    {
        mouseX += Input.GetAxis("Mouse X") * smoothTime;
        mouseY -= Input.GetAxis("Mouse Y") * smoothTime;
    }
    void LateUpdate()
    {
        getMouseXY();
        // Define a target position above and behind the target transform
        Vector3 targetPosition = target.TransformPoint(new Vector3(0, 1.5f, -2.5f));

        // Smoothly move the camera towards that target position
        transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
        transform.LookAt(target);

        target.rotation = Quaternion.Euler((mouseY * mouseY_Speed), (mouseX * mouseX_Speed), 0);
        player.transform.rotation = Quaternion.Euler(0, (mouseX * turnSpeed), 0);

    }
}

My issue is that whenever the player moves either the camera/player jitters.
I have debugged the player transform y position to make sure it wasn't moving up or down (it doesn't). To help with this issue I have either turned down the Fixed Timestep under Time in the project settings or put the code in the camera script is fixed update instead of late update (which is an issue based on my research).
I know MovePosition for the player isn't the right way to move, but I don't know how to make the player move in the direction the camera is facing with rb.velocity. I suspect the issue may lay in the player script with variable camPos. Either way, I would like to stop the jittering.


texts:
Currently I use XML to store specific information to correctly load a few things such as a list of specfied characters, scenes and music, Once more I use JAXB in combination with standard compression/decompression(ZIP) functionality to store a list of extrenous data. This data is called to add functionality to the character, somewhat like Skills in an RPG. Each skill is seperated into its own XML file with a grandlist which contains the names of each file with their extensions omitted and zipped in folder that gets encrypted.

At first using xml was working fine however as the skill list grow i worry about its stability. I was wondering if I should begin storing the data in mySQL. Originally I planned to simply convert everything to JSON over xml but i think possibly mySQL would be a better move.

Can anyone inform me of the key difference and pros and cons of each
I guess i'm looking for the best way to store the data more conviently and would be easier to operate on. The data is mostly primatives and strings and the only arraylist of values i have i can just concat into a single field and parse later

Edit:

If I am going in the right direction with XML would it make sense to convert it to JSON and use maybe Kyro or EclipseLink JAXB (MOXy)


texts: ARBShaderObjects.glDeleteObjectARB vs GL20.glDeleteShader to remove shader?

texts:
I've created a shader object using ARBShaderObjects.glCreateShaderObjectARBand I'm wondering exactly how I'm suppose to remove said shader.

It seems both ARBShaderObjects.glDeleteObjectARB and GL20.glDeleteShader can do this.

I'm leaning towards ARBShaderObjects.glDeleteObjectARB since I created the shader using the ARBShaderObjects set of classes.

Do both of these work?

In this case is one prefered or different from the other?

Sorry for general LWJGL / OpenGL noobiness.


texts:
I'm just wondering what XNA is missing, to be considered as a game engine. It does all the things a game engine should do (except the physics part); it also has support for every aspect defined in the Wikipedia article on game engines.

Why is XNA not considered a game engine?


texts:
So I am making a pacman-like game. the game has tiles/grid. I keep the node data in a struct:

struct Node

{
    std::pair <int, int> node; // position of the node <x,y>
    float f = 0,
          h = 0,
          g = 0;
    std::pair <int, int> previous;
    bool iswall = false;
    sf::Vector2f rectCenter = sf::Vector2f(0, 0);
    sf::Vector2f position;

};

i use the struct to calculate a path, check if the cell is an obstacle (or not) etc.

now in the main I use the arrays and a for loop to draw the grid:

for (int i = 0; i<col; i++)
        for (int j = 0; j < row; j++)
        {
            /*default color is black*/
            box[i][j].setFillColor(sf::Color::Black);
            box[i][j].setOutlineColor(sf::Color::Yellow);
            box[i][j].setOutlineThickness(-1);
            box[i][j].setSize(sf::Vector2f(w, h));
            box[i][j].setPosition(sf::Vector2f(i*w, j*h));
            sf::FloatRect fbox = box[i][j].getGlobalBounds();
        }

[1

I also use the strcut to create specific nodes (current position, start node, end node)

and i draw it in the man like this:

        //displays the start node as green
        if (i == crntNodex && j == crntNodey)
        {
            box[i][j].setFillColor(sf::Color::Green);
                }

now the problem that I'm facing is making a function that can get the current node that the player (blue square on the green cell) is. My attempt for this was checking if the cell contained the player

std::pair<int, int> AIEnemy::getNodePosition(sf::RectangleShape * grid, int i, int j)
{

    if (box.contains(rect.getPosition().x, rect.getPosition().y))
    {
         return std::pair<int, int>(i,j);
    }
}

but It is not efficient (and also doesn't update). is there a way I can get game objects coord on a grid?


texts: Buttons implementation with regards to a basic Game Loop

texts:
As the title states I am creating a game with SFML being the only library used.

I am entirely unsure how to go about this.

I want the buttons to be activated by simple mouse clicks (when the mouse is within the defined area of the button).

My question however is how do I do this with regards to a standard Game Loop, with the following methods HandleInput(), Update() and Draw().

Should I implement it so that HandleInput() calls a function (on left
mouse click) which stores the mouse coordinates and in Update() every
button checks if it has been clicked on?
Or should I (attempt to) implement Observer pattern?
Or is there a method I haven't even covered?

I hope this question is relevant to GameDev I believe it is.


texts: (While using a cube map) box-like textures appearing around my scene whenever I move the camera

texts:
I've been learning about cube map and I implemented one into my program. It seemed to work well until I started moving the camera around the scene and zooming out. As you can see in the attached gif, there seems to be a problem with the cube map since this weird behavior is occurring:

https://gyazo.com/70ad4ce027d1e032bc19258e28def66f

Main program:

        unsigned int cubemapTexture = texo.loadCubeMap(faces);

        glDepthFunc(GL_EQUAL);
        bg.bind();
        skyBox.use();

        glm::mat4 projection = glm::perspective(glm::radians(fov), (float)scr_width / (float)scr_height, 0.1f, 100.0f);
        glm::mat4 view = camera.GetViewMatrix();
        skyBox.setUniformMat4("projection", projection);
        skyBox.setUniformMat4("view", view);

        glActiveTexture(GL_TEXTURE20);
        glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
        GLCall(glDrawArrays(GL_TRIANGLES, 0, 36));

loadCubeMap:

unsigned int Textures::loadCubeMap(std::vector<std::string> faces)
{
    unsigned int textureID;
    glGenTextures(1, &textureID);
    glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);

    stbi_set_flip_vertically_on_load(false);

    int width, height, nrChannels;
    for (unsigned int i = 0; i < faces.size(); i++)
    {
        unsigned char* data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0);
        if (data)
        {
            glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
                0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data
            );

            stbi_image_free(data);
        }
        else
        {
            std::cout << "Cubemap tex failed to load at path: " << faces[i] << std::endl;
            stbi_image_free(data);
        }
    }

    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

    return textureID;
}

Vertex Shader:

#version 330 core

layout (location = 0) in vec3 aPos;

out vec3 TexCoords;

uniform mat4 view;
uniform mat4 projection;

void main()
{
    vec4 pos = projection * view * vec4(aPos, 1.0);
    TexCoords = aPos;
    //Setting z value to w (1.0) so that the cube map is always in the background
    gl_Position = pos.xyww;
}

Fragment shader:

#version 330 core

out vec4 FragColor;

in vec3 TexCoords;
uniform samplerCube skybox;

void main()
{
    FragColor = texture(skybox, TexCoords);
}

The problem probably originates from one of these snippets, but if you have any other ideas I can provide more info.


texts: I have 2 textures in 2 different ShaderResourceViews. What's the fastest/least expensive way to merge them into one? I would use CopySubresourceRegion but copying a texture is quite a bit expensive. I'm using DirectXTex toolkit for loading textures.


texts:
I'm having a weird problem with the LibGDX ShapeRenderer where it draws everything rotated.
Here are some images to show you what i mean:
This is what it looks like in Tiled(Map Editor):

This is how it looks like in game:

As you can see, its rotated.
Heres the Code i use to render the mapobjects:
    shapeRenderer.setProjectionMatrix(cam.combined);
    shapeRenderer.setColor(1, 1, 0, 1);
    shapeRenderer.begin(ShapeType.Line);
    for (RectangleMapObject o : MovementSystem.objects.getByType(RectangleMapObject.class)) {
        Rectangle rect = o.getRectangle();
        shapeRenderer.rect(rect.x, rect.y, rect.height, rect.width);
    }

    shapeRenderer.end();

The rectangle is positioned at the right place and it is definitely NOT rotated!
I checked this with a small collision detection test where i moved another rectangle over this one.
So it just gets drawn like this and i have no idea why^^
Would be nice if anybody could help me :)
Thanks for your help in advance!


texts: How to preserve Arcball rotation in c++ OpenGL?

texts:
Firts of all want to say that I've already searched for other people's answers here as same as Google and didn't found anything about it there. Also tried some others arcball implementations but none of them worked as good as the one using at this moment or use older OGL versions.

So I'm following this github page code by subokita to implement an arcball camera myself and got to the point where it works and noticed that whenever you release the mouse and click again the view comes back to the start position.
I know that it happens because of the model rotation matrix obtained from prevPos and currPos comes back to the start whenever you click again since prevPos changes but can't see a clear solution to preserve the previous state without messing up the view.

I tried moving the model to the camera class and having two variables for it that gets exchanged depending on the mouse action as seen in the code below so that it calculate the state over a previous model value when dragging and use the result of it when no dragging being made. But even if it works it produces weird frames at the beggining of the cursor redrag(video) even though it success on preserving the previous state and I have no idea why.

Arcball.cpp

// Arcball.h > glm::mat4 model, smodel = glm::mat4(1.0);
glm::mat4 Arcball::createModelRotationMatrix(glm::mat4& view_matrix) {
    switch (mouseEvent)
    {
    case 0:
        return model = smodel;
    case 2:
        glm::vec3 axis = glm::inverse(glm::mat3(view_matrix)) * camAxis;
        return smodel = glm::rotate(glm::degrees(angle) * rollSpeed, axis) * model;
    }
}

main.cpp

glm::mat4 rotated_model = arcball.createModelRotationMatrix(view);
glm::mat4 mvp = projection * view * rotated_model;

How can I modify this arcball to preserve the rotation when a redrag occurs?

Thanks for your time.


texts: Is developing 2D sprites as projections of 3D models viable?

texts:
I am a solid programmer and have a strong desire to make a 2D top down game. My immediate stumbling block, however, is the art. I am currently using placeholder images, but I really want to develop my own IP. The problem is that I simply can't draw that well. However, I do have really great three dimensional reasoning, and I am rapidly improving in 3D modeling with Maya.

My hope is that I can develop models in three dimensions, and then generate sprites from cross sections, or use of those models. Is this a viable path of developing production quality 2D art?


texts: How can I have human-readable key names in a configuration file?

texts:
Given a file mapping keys to controls, such as this:

up         w
down       s
left       a
right      d
jump   space
run    shift
crouch  ctrl

The values need to be converted into game commands, and constants. The commands aren't so much a problem as the keyboard keys are; a keyboard can contain over 100 keys, so the last thing desired is this:

unsigned int pressedKey;
if (value == "a") {
    pressedKey = KEY_A;
} else if (value == "b") {
    pressedKey = KEY_B;
} else if (value == "c") {
    pressedKey = KEY_C;
} else if...

What comes to mind would be to build a map of key value pairs, something like this:

std::unordered_map<std::string, unsigned int> keyFinder;
keyFinder.emplace("a", KEY_A);
keyFinder.emplace("b", KEY_B);
keyFinder.emplace("c", KEY_C);
// and so on

This would allow for fast lookups, but on the downside it still has to be hardcoded, and it's not going to be a pretty segment of code.

I'd love to hear some good solutions for reading a file and using it to map controls! If it involves using some other file format, that's fine too, as long as it's human readable.


texts: Using an SDL_Renderer within a texture wrapper class in SDL2

texts:
I have a CTexture class which needs a renderer to create and show textures. I don't know the scope I should put the renderer in. I´ve got it to work as a global variable, but I don't know if it´s a good way.

CTexture instances will be created within other classes, so it seems to be a mess to pass the renderer as an argument.

What do you think I should do?


texts: How can I use a texture as a font in Unity3D

texts:
I am making a game in unity and I am trying to make a custom font for showing numbers. I created a png with the numbers, turned it into a material and added it to a custom font object. I set up the index so that it knows where the number are. I set it to a style and used the style with a label to print some numbers to the screen. The numbers printed but the detail from the texture disappeared and the numbers became a single color determined by the text color setting in the style. Is there a way for the text to just show the graphics from the texture.

The alpha is working but the non alpha parts are all set to the same color. I have multiple colors in the text but on the screen they just appear as one color. Also when I add the material to a plain it all shows up properly so I am assuming that it has something to do with the font settings or the style settings.

here's a screeshot http://imgur.com/a/rqAhd


texts:
Assume that this behavior has Separation behavior. I tried to implement the FollowLeader behavior from this article. In the code below is my working implementation. But there is a problem, when I convert the owner linear velocity to direction (North, South, East, West), it doesn't give the proper direction to achieve the correct facing of my animation.

    protected SteeringAcceleration<T> follow(SteeringAcceleration<T> steering, Steerable<T> leader) {
        T tv = leader.getLinearVelocity().cpy();
        // calculate the ahead point
        tv.nor();
        tv.scl(LEADER_BEHIND_DIST);
        ahead = leader.getPosition().cpy().add(tv);

        // calculate the behind point
        tv.scl(-1);
        behind = leader.getPosition().cpy().add(tv);

        if(isOnLeaderSight(leader, ahead)) {
            evade.calculateSteering(steering);
            force.add(steering.linear);
        }

        arrive(steering, behind);
        force.add(steering.linear);

        // separation(..) assume exists

        steering.linear.set(force);
        steering.angular = angular;

       return steering;
    }


texts: How should I handle the relationship between my Player and keyboard input classes?

texts:
Just a quick one really, as I can't find anything definative.

Started developing in Java, to learn and take on a bit of Game Dev. Have a PHP background, and I'm a massive sucker for best practices, etc.

Basically in my Game::update() method I can handle keyboard input and move the Player, this is what I want to avoid.

So should my Keyboard class have a dependancy of Player, or the other way around?
Also would the Keyboard class handle the management of Player states or would the Player class handle that itself.

OR...

Should I look into introducing an Event System to the Game Engine?

This is a very broad question and down to opinion. I'd just rather do things the right way, than end up with a steaming pile of mess.


texts: Render BitmapFont with size < 1 in Libgdx

texts:
My ingame camera has units that 25 times less than screen units so when I render BitmapFont generated for camera which used in non-game screens (settings, level choose etc.) it's even doesn't fit in camera.

I came up with some solutions:

Generate font with right size, but No cap character found in font exception caught.
Scale font with font.getData().setScale(float scaleXY) but got this:
Increase camera units but I'll need to rewrite a lot of code depending on camera combined matrix.

Is there any easier way to do this?


texts:
So, I'm making a sort of physics simulation in Unity involving a spinning ring to generate "gravity", and I have the ring and everything, but I've hit a snag: I have no idea how to make a character controller that can handle walking on spheres and in rings in about the same way.

My question is this: How do I create a character controller that walks equally well on a sphere and the inside of a ring? I don't need someone to write the whole thing for me, but if you could help me understand the logic behind it, or clue me into some of the methods that might be helpful, it would be really appreciated.

If it helps to know, I'm using Unity3D, and I write my code in C#.


texts: Optimizing a mesh for voxel cube landscapes

texts:
Playing around with creating minecraftish/lego world landscapes in Unity 3D (procedurally generated voxel landscapes with cubes), I'm finding that the meshes created for these landscapes take up a LOT of memory. The mesh currently only consists of vertices for visible sides of a cube. Memory usage for a complex terrain may take 6 or 7 hundred megs.

These meshes could be optimized, but I'm struggling to find a decent algorithm to do this.

The algorithm has to take into account that you don't want to "merge" blocks that are of different terrain types. I guess a really simple start might be to just process all blocks along one axis, and do extra sweeps for the other two axis.

I need to keep the mesh shape, that is no merging of vertices to the point that empty or solid space is changed. The reason is, there may be creatures/etc that still need to navigate around the mesh. So I can't just create a really low detail, distorted mesh.

Any thoughts/suggestions/tips on this?


texts: Difference between orthogonal map and isometric map

texts: I am laughing at myself ignorant on this. Google didn't produce an obvious answer. Could someone explain what orthogonal map and isometric map are, and how they are different?


texts: Unity UI Image Prevent Camera To Render All Object In Front Of It

texts:
i confused why is this happen , i know there's already available post that discuss this but i cannot find it at google. My problem is that my UI image with sprite hide rendering all object in front of it ( so the camera view only show the image ) .

Screenshot In 3D Mode :

I Put A Square Object Right In Front Of The Image

And This Is The Camera Position With Camera Preview

Sorry i only can put 2 screenshot because below reputation 10 i can't put more than 2 picture .

As you see , the camera should render the " StartBox " either " MenuBox " but none are rendered even it's in front of camera view


texts:
If you don't know what color switch is look here: http://poki.com/en/g/color-switch

I need a good way to detect the color collisions, one way would be to get the colors of pixels around the ball on the jpanel but I don't know how that would work. I can't use Shapes and Area intersections because some of the obstacle shapes have a hole in the center so I can't use the shape and area class to find collisions.

Any Ideas would be great.

All my Obstacles are made with A multiple Shape objects for different colors and holes.


texts: Should I store ads in the background or recreate them every time I need them?

texts:
I am developing an XNA game for Windows Phone 7 and 8. The game is level-based. After finishing each level a screen comes up with a bit of stats summary. I wish to embed an ad in this screen, on which I expect users to only spend a few seconds on after each level.

The ads I am using are Microsoft's pubCenter ads and AdDuplex as a backup.

Should persist instances of these ads throughout the game's operation and only make them visible on level completion? Or should I create new instances every time they are needed and destroy them once I don't want them anymore for each level?

My worry is that starting up an ad on a screen which is intermediate and lasts for a short while might not be enough time for an ad to download. On the other hand, having one or more ads running continuously in the background might not be a good thing for battery or performance.


texts:
I'm trying to move child of camera object smooth. To implement that, I need to know the movement of x and y axis, like Input.GetAxis in general PC platforms.

I saw the documentation and examples of Google VR, but there's not much explained well. One thing I found is GvrControllerInput.Gyro, but it's said it's deprecated and use GvrControllerInputDevice.Gyro instead, but there's no Gyro value in GvrControllerInputDevice.

Seems like basic usage is totally changed, so they are not providing static methods, and force to using internal method of the object, but couldn't find any related information about this.

So, how do I get gyro from GvrControllerInputDevice? Or is there an alternative way to make child object rotate smooth from their parent? Any advice will very appreciate it!


texts:
I am a total beginner in C++ and programming generaly.

I have watched a couple hours of C++ tutorials and read a lot about it (Can anyone recommend some tutorials?), but what I've come across and couldn't understand was Libraries.

I want to develop games in C++ (I think, it seems the most interesting at the moment). I can understand that I need a library for game programming in C++, but I don't know much about libraries, what specifically a library is, or where to find these libraries.

Thank you for your time. This is my first question here. I apologize if it wasn't a proper question for this website, or if the english was bad. I still hope you can give me some kind of answer and/or reponse.


texts: How to set a specific face's texture color in Unity?

texts:
First off, let me describe my situation...
So I'm building a voxel engine based on this tutorial. I'm using my own texture tilesheet. Most of the tiles have their own color except grass, leaves, and a few others. These specific ones are meant to be colored based on the temperature and humidity of the location.

AlexStv (the author of the tutorial linked above) said the mesh colors array could be set, but I tried that and nothing happened. I probably did it wrong though, not sure. But he also said "you may need a shader that render vertex colors, not sure if the standard shader does that anymore" so that could also be the issue.

So... Do I need a custom shader? If not how do set the face's colors?

EDIT, Note: I just tried a custom shader called UnityVC, it still didn't work so I guess I must be doing the color thing he suggested wrong.


texts:
I'm working on a project where I only have access to MP3s versions of audio tracks I'd like to use. Unity  is trying to be helpful and recompressing everything as Vorbis, which is not ideal due to quality loss. Even if I override the audio clip settings and set it to use MP3, Unity still transcodes the file for me, resulting in quality loss. I can set the clip to PCM, which would avoid re-encoding the file into another lossy format, but the resulting file size is too large to be practical.

In a perfect world I would have WAV versions of all the tracks I want to use, but that is not the case. Is there anyway to tell Unity to use the file the way it is and to leave it alone and not recompress it?

For the record I am using Unity 5.3.1 and my project target is iOS.


texts: Basic game loop, what does Update() and HandleInput() mean to you?

texts:
I have been developing a game and until now I have been handling input like so:

Player presses a key
HandleInput() acknowledges a key is pressed calls a function within the Player class which increments the Players position by a pre-determined amount.
Update() sets the players sprite to be at the players position.
Draw() renders the players sprite.
Return to Step 1.

Now my question is this, should I continue to run my loop in this way or should I implement the following:

HandleInput() sets a state within the Player class which when Update() is called the Player object checks if it is in a state of motion and updates its location appropriately, before updating the sprite to its new location.

This question arose within me while I was altering my loop so that only the Update() function had a maximum refresh rate (60 cycles per second) and I realized I was unsure how I should appropriately communicate events to the objects on how they should act.

I did not include any code as we're discussing in pseudo-code if you feel some is required let me know.


texts:
I am trying to set the rotation of a HingeJoint2D by code, but the 'rotation' property is get-only. I tried setting the limits to my current rotation, but that doesn't work either. What's the proper way of doing it?

bowJoint.limits = new JointAngleLimits2D() { max = rotation, min = rotation };