texts: How to keep the object rotation while using RotateAround in Unity?

texts:
I've got an object that has a comet-like sprite rotating around it. I'm using this code in LateUpdate() to make it rotate and keep the comet's tail at the right position:

transform.position = player.transform.GetChild(0).transform.position + (transform.position - player.transform.GetChild(0).transform.position).normalized * 2f;
transform.RotateAround(player.transform.GetChild(0).transform.position, Vector3.forward, 100f * Time.deltaTime);

It works fine until the object moves. After moving, the comet follows the object and goes back to the orbit, but its rotation gets messed.

I've got an image describing this problem:

The image on the left shows how the comet behaves at the beginning. On the right there's a sample of how the comet's position can possibly look after moving around. I want it to always look like on the left image.

Is there any way to stick the comet to the object's orbit? It can move as fast as the object, I don't need tealistic calculations of the position changing for the comet.


texts: Creating sideways friction in a 2D top down racer

texts:
I've been playing around with trying to create some kind of top down racer but I'm having trouble getting the car to turn properly. At the moment this is the code I have to update the position of the car:

var power;
    if (keyboard.upKeyDown) {
        power = 1;
    } else {
        power = 0;
    }

if (keyboard.leftKeyDown) {
    this.rotate -= 0.05;
} else if (this.keyboard.rightKeyDown) {
    this.rotate+= 0.05;
}

this.velocityX += Math.cos(this.rotate) * power;
this.velocityY += Math.sin(this.rotate) * power;

var cDrag = 0.98;
this.velocityX *= cDrag;
this.velocityY *= cDrag;

this.positionX += this.velocityX;
this.positionY += this.velocityY;

At the moment the code is very simple, you hold down UP and force is applied in the direction you're pointing which makes it feel like the ship in asteroids.

It seems to me the next thing I need to do is compare the direction the car is pointing with the direction it's actually travelling and apply some sideways force to make it slow down in the sideways direction but also transfer some of that force to the forward direction so it keeps going in the direction it's now pointing.

I'm a bit confused as to how I go about doing this so any advice would be most welcome.


texts: How can I attach a model to the bone of another model?

texts:
I am trying to attach one animated model to one of the bones of another animated model in an XNA game.

I've found a few questions/forum posts/articles online which explain how to attach a weapon model to the bone of another model (which is analogous to what I'm trying to achieve), but they don't seem to work for me.

So as an example: I want to attach Model A to a specific bone in Model B.

Question 1.
As I understand it, I need to calculate the transforms which are applied to the bone on Model B and apply these same transforms to every bone in Model A. Is this right?

Question 2.
This is my code for calculating the Transforms on a specific bone.

private Matrix GetTransformPaths(ModelBone bone)
{
    Matrix result = Matrix.Identity;
    while (bone != null)
    {
        result = result * bone.Transform;
        bone = bone.Parent;
    }
    return result;
}

The maths of Matrices is almost entirely lost on me, but my understanding is that the above will work its way up the bone structure to the root bone and my end result will be the transform of the original bone relative to the model.

Is this right?

Question 3.
Assuming that this is correct I then expect that I should either apply this to each bone in Model A, or in my Draw() method:

private void DrawModel(SceneModel model, GameTime gametime)
{
    foreach (var component in model.Components)
    {
        Matrix[] transforms = new Matrix[component.Model.Bones.Count];
        component.Model.CopyAbsoluteBoneTransformsTo(transforms);

        Matrix parenttransform = Matrix.Identity;
        if (!string.IsNullOrEmpty(component.ParentBone))
            parenttransform = GetTransformPaths(model.GetBone(component.ParentBone));

        component.Player.Update(gametime.ElapsedGameTime, true, Matrix.Identity);

        Matrix[] bones = component.Player.GetSkinTransforms();

        foreach (SkinnedEffect effect in mesh.Effects)
        {
            effect.SetBoneTransforms(bones);

            effect.EnableDefaultLighting();
            effect.World = transforms[mesh.ParentBone.Index]
                * Matrix.CreateRotationY(MathHelper.ToRadians(model.Angle))
                * Matrix.CreateTranslation(model.Position)
                * parenttransform;
            effect.View = getView();
            effect.Projection = getProjection();
            effect.Alpha = model.Opacity;
        }
    }
    mesh.Draw();
}

I feel as though I have tried every conceivable way of incorporating the parenttransform value into the draw method. The above is my most recent attempt.
Is what I'm trying to do correct? And if so, is there a reason it doesn't work?

The above Draw method seems to transpose the models x/z position - but even at these wrong positions, they do not account for the animation of Model B at all.

Note: As will be evident from the code my "model" is comprised of a list of "components". It is these "components" that correspond to a single "Microsoft.Xna.Framework.Graphics.Model"


texts:
I have a TIN (Triangle Irregular Network) that was created in CAD software packages from something called DTM (essentially each point represents the height of the ground for that specific point).

The result looks like a 'blanket' of triangle, so not closed in any way. I think that's a non-boundary manifold triangle mesh but not sure. More unclear is if it is a 2D mesh (like a polygon is a 2D surface in a 3D Cartesian space even if not all vertexes are the same z). Can someone please explain what kind of geometry is a TIN?

Example (the blue triangles are the TIN):


texts:
I'm currently trying to transform a system by scaling it on x and y axis and have some uncertainty. I have the general concept that scaling works as such:

My original box has corners at (0, 0) and (3, 2) and I'm asked to scale the x axis by 3 and the y axis by -2.

Is this what the correct solution would look like (with corners at (0,2) and (6,-2))?


texts: Why do modern games not feature extra lives?

texts:
In the late 80s and early 90s, most games had an extra life mechanic. The player started with limited lives (often three) and dying depleted one of them. If they still had some remaining, they would respawn at the last savepoint. The game would end once all lives had been used and they had to start from the beginning. Players could obtain additional lives during the game.

This mechanic was so widely used that it was rather the exception when games didn't use it. It was and still is one of the most recognized video game clichés (the above image has been printed on countless shirts).

Nowadays, this mechanic seems to have been forgotten.

Almost every modern game gives the player infinite retries from the last save. Many even let the player make their own savepoints with a quicksave mechanic. Those few that try to be different tend to go for the other extreme: The "roguelike" mechanic gives the player no retries.

What happened to the middle-ground of having extra lives? What game design revolution caused the game industry to abandon this feature?

When proposing an answer to this question, please try to back up your answer with citations and factual, objective evidence as much as possible so as to avoid dragging this post into the territory of being "too opinion-based." Focus on "what" happened and "when," which specific examples.


texts: Unity3D Drag Object with Mouse Gives Invalid Position

texts:
I am trying to implement a simple script to drag a GameObject with the mouse in Unity.
However, when the position of the object is updated with the following script, I get an error saying:

transform.position assign attempt for 'purpie_5' is not valid. Input position is { Infinity, 51351759646418134000000000000000.000000, -143589927261340110000000000000000000000.000000 }.
UnityEngine.Transform:set_position(Vector3)

I am not sure what I am doing wrong. This is the code I am using:

public class MouseInputInterface : MonoBehaviour {

#region PUBLIC MEMBERS
public Transform heldObject;
#endregion //PUBLIC MEMBERS

#region PRIVATE MEMBERS
private GameObject currTarget;
private Vector3 touchOffset;
private bool dragging = false;
#endregion //PRIVATE MEMBERS

// Use this for initialization
void Start ()
{

}

    void Update()
    {
    if(Input.GetMouseButton(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if(Physics.Raycast(ray,out rHit))
        {

            currTarget = rHit.transform.gameObject;

            if(currTarget != null)
            {
                if(!dragging && currTarget.transform.tag == "Moveable")
                {
                    dragging = true;
                    heldObject = currTarget.transform;
                }

            }

        }

        if(heldObject != null)
        {
            /*calculate offset*/
            Vector3 screenPoint = Camera.main.WorldToScreenPoint(heldObject.position);

            /*calculate offset from camera*/
            Vector3 offset = heldObject.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));

            //form the current position
            Vector3 curPosition = Camera.main.ScreenToWorldPoint(screenPoint) + offset;

            heldObject.transform.position = curPosition;
        }
    }
    else if(Input.GetMouseButtonUp(0))
    {
        //clear held object
        heldObject = null;
        //clear flag
        dragging = false;
    }

    }
}

Thanks for the help.


texts:
I've been struggling to get this working. I simply wish to take a surface normal and convert it to a screen angle.

As an example, assuming we're working with the highlighted surface on the sphere below, where the arrow is the normal, the 2D angle would obviously be PI/4 radians.

Here's one of the many things I've tried to no avail:

float4 A = v.vertex;
float4 B = v.vertex + float4(v.normal, 0.0);

A = mul(MVP, A);
B = mul(MVP, B);

A.xy /= A.w;
B.xy /= B.w;

o.theta = atan2(B.y - A.y, B.x - A.x);

I'm finally at my wit's end. Thanks for any and all help.


texts: Why does OnControllerColliderHit not work while Physics.CheckSphere() does?

texts:
Using the following code below, when my character hits a crate and goes over it, it ends up floating in the air, while jumping is no issue. That successfully lands on the ground.
using UnityEngine;

public class Testing: MonoBehaviour
{
    public CharacterController Controller;
    //speed of the character
    public float Speed = 12f;
    // earth gravitational value
    public float Gravity = -9.81f;
    Vector3 velocity;
    //hit point of character
    float hp = 90;

    bool Grounded = true;

    public void OnControllerColliderHit(ControllerColliderHit hit)
    {
        Grounded = true;
        hp -= velocity.magnitude;
        velocity.y = 0;
        Debug.Log(hp);
    }

    public void OnControllerColliderExit(ControllerColliderHit hit)
    {
        Grounded = false;
    }

    public void Checkstatus()
    {
        if (Grounded == false)
        {
            velocity.y += 0.5f * Gravity * Time.deltaTime;
        }
    }

    void Update()
    {
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");
        Vector3 move = transform.right * x + transform.forward * z;

        Controller.Move(move * Speed * Time.deltaTime);

        if (Input.GetKeyDown(KeyCode.Space) && velocity.y == 0)
        {
            velocity.y = 12;
            Grounded = false;
        }

        //check if it grounded
        Checkstatus();
        Controller.Move(velocity * Time.deltaTime);
    }
}

Here's an image showing the floating player:

And why does the code below (using Physics.CheckSphere()) have no issue? Feels like the above code is better (if working correctly), as it doesn't need to waste resource on checking the condition of Grounded (like in checkstate1()) every frame.
using UnityEngine;

public class NewPlayerMovement : MonoBehaviour
{
    public CharacterController Controller;
    public float Speed = 12f;
    public float Gravity = -9.81f;
    Vector3 velocity;
    public LayerMask groundmask;
    float hp = 90;

    bool Grounded = true;
    // Update is called once per frame

    void checkstate1()
    {
        Grounded = Physics.CheckSphere(this.transform.position, 0.85f,groundmask);
        if (Grounded==true)
        {
            hp -= velocity.magnitude;
            Debug.Log(hp);
            velocity.y = 0; }
     }

    public void Checkstatus()
    {
        if(Grounded==false)
        {
            velocity.y += Gravity * Time.deltaTime;
        }
    }
    void Update()
    {
        checkstate1();
        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");
        Vector3 move = transform.right * x + transform.forward * z;

        Controller.Move(move * Speed * Time.deltaTime);

        if (Input.GetKeyDown(KeyCode.Space)&&Grounded==true)
        {
            velocity.y = 12;
            Grounded = false;

        }

        Checkstatus();
        Controller.Move( velocity * Time.deltaTime);

    }
}


texts: Why the OnCollisionEnter is not working?

texts:
This script is attached to the wall(3D Cube) with a box collider :

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

public class LockedRoomTrigger : MonoBehaviour
{
    private void OnCollisionEnter(Collision collision)
    {
        Debug.Log(collision.transform.name);
    }
}

But when the player is moving and hit the cube it's not getting to the Debug.Log I used a break point on the Debug.Log line.

A screenshot of the cube wall with the box collider component and the script attached to it.
The problem is not with the player since if I'm moving with the player near doors they open so the player does trigger things and also not walking through walls.

This is a screenshot of NAVI.
NAVI is a bit in front of the player and moving with the player and part of the player in the game like a friend helper.

NAVI is the one that collide and hit stuff if doors walls not the player since the NAVI is a bit in front of the player.

NAVI have only a box collider :

And this is the Inspector screenshots of the player. I will add two screenshots since it's not getting inside in one screenshot :

The player is a first person view :


texts:
I have this script Gravity.cs

public class Gravity : MonoBehaviour
    {

        public float planetGravity = -10f;

        public void Attract(Rigidbody body)
        {
            Vector2 normalForce = (body.position - transform.position).normalized;
            Vector2 localUp = body.transform.up;

            body.AddForce(normalForce * planetGravity);

            body.rotation = Quaternion.FromToRotation(localUp, normalForce) * body.rotation;
        }
    }

In this script I make a "gravity field", for a 2D sprite of a planet, I then have my player walk around it.
My problem, I want multiple of these planets, all with different gravity fields, When the player is out of the sphere of influence (a trigger sphere collider in unity) the player should be attracted to the closest planet with the highest gravity eg. if the player is exactly between two  planets the player should fall to the planet with the highest gravity(or mass idk), how can I do this?


texts: In AS3, is it necessary to remove the children from a parent who is also being removed?

texts:
My point is this:

addChild(parentMC);
parentMC.addChild(child1);
parentMC.addChild(child2);

If I want to then remove parentMC from the current container, is it necessary to also remove child1 and child2 from parentMC in order to properly clean-up? Or is that handled automatically through removing parentMC?


texts: SharpDX Error 'The Parameter is Incorrect', how to debug from dx?

texts:
I have written some code to handle a DX device. When the code is finished and makes it's call to DX the DX engine is complaining. What I'm looking to understand is how one goes about debugging on the DX end or at most what parameter passed is trowing an error.

For reference this is my code. This is not the complete class but gives an idea of the code I'm attempting. Happy to share more if needed.

public void doFFBAPI(Joystick joystick)
        {
            var allEffects = joystick.GetEffects( EffectType.All );

            foreach (var ei in allEffects)
            {
                if (Convert.ToString((int)ei.Type & 7, 2) == "101")
                {
                    EffectParameters ep = new EffectParameters();
                    int xAxisOffset = 0, yAxisOffset = 0;
                    int nextOffset = 0;
                    foreach (DeviceObjectInstance d in joystick.GetObjects())
                    {
                        if (d.ObjectType.Equals(DeviceObjectTypeFlags.ForceFeedbackActuator))
                        {
                            if (nextOffset == 0)
                                xAxisOffset = d.Offset;
                            else
                                yAxisOffset = d.Offset;
                            nextOffset++;
                        }
                    }

                    int[] offsets = new int[2];
                    offsets[0] = xAxisOffset;
                    offsets[1] = yAxisOffset;
                    int[] coords = { 0, 0 };

                    ep.Flags = EffectFlags.Cartesian | EffectFlags.ObjectOffsets;
                    ep.Directions= new int[1]{0};//MaxValue
                    ep.Gain = 10000;
                    ep.Duration = int.MaxValue;
                    ep.SetAxes(offsets, coords);
                    ep.SamplePeriod = joystick.Capabilities.ForceFeedbackSamplePeriod;
                    ep.TriggerButton = -1;
                    ep.TriggerRepeatInterval = int.MaxValue;
                    ep.Envelope = new Envelope();
                    ep.Axes = new int[1] { 0 };
                    ep.StartDelay = 0;
                    CustomForce CF = new CustomForce();
                    CF.ChannelCount = 2;
                    CF.SampleCount = 12;
                    CF.SamplePeriod = 1000;
                    int[]  forces;
                    forces = new int[24];
                    forces[0] = 79;
                    forces[1] = 0;
                    forces[2] = 0;
                    forces[3] = 0;
                    forces[4] = 0;
                    forces[5] = 0;
                    forces[6] = 0;
                    forces[7] = 0;
                    forces[8] = 0;
                    forces[9] = 0;
                    forces[10] = 0;
                    forces[11] = 0;
                    forces[12] = 0;
                    forces[13] = 0;
                    forces[14] = 0;
                    forces[15] = 0;
                    forces[16] = 0;
                    forces[17] = 0;
                    forces[18] = 0;
                    forces[19] = 0;
                    forces[20] = 0;
                    forces[21] = 0;
                    forces[22] = 0;
                    forces[23] = 0;
                    CF.ForceData = forces;
                    ep.Parameters = CF;

                    Effect e = new Effect(joystick, ei.Guid, ep);//<-- trows the DX error.
                    effect = e;
                    e.Start();
                }
            }
        }

Here is the error

An unhandled exception of type 'SharpDX.SharpDXException' occurred in SharpDX.dll

Additional information: HRESULT: [0x80070057], Module: [General], ApiCode: [E_INVALIDARG/Invalid Arguments], Message: The parameter is incorrect.

I marked the section of code where the error occurs. I recall doing some debugging in IE once where I could attach a processes, can that be done with some DX dll of sorts? There must be a way to get more detailed info here. I tried contacting sharpDX but they don't seem to frequent the forums much.


texts: How do I keep my character centred on screen?

texts:
I am making a game similar to Legend of Zelda: Link to the Past (top-down 2D action-adventure). I want the character to stay centred on the screen when he moves.

Currently, whenever the player wants to move, I move all of the map in the opposite direction. This works, but as I add more objects to the world, moving them all gets more complicated.

Is there a better way of approaching this?


texts: Do Playfish and Zynga use COTS game engines?

texts:
I'm very interested to learn how to make 2D and 3D games, but I'm very new to this field so I am wondering if companies like Playfish, Zynga and other producer of games on Facebook are using publicly available game engines to make their games or if they're building their own game engine or what?

What game engines or technologies that are used in such games?

Are there any resources available that I can use to get started?


texts: In unity C#, why use the .SetBool(booleanname, boolean) command when you could just write 'booleanname = true'?

texts:
I noticed on a tutorial for unity someone used the code:

private Animator animator;
private bool isRunning = false;

While further on, did:

animator.SetBool("isRunning", true)

Why could you not just do

isRunning = true

if it is in the same class?


texts: How to initialize OpenGL context with PyGame instead of GLUT

texts:
I'm trying to start with OpenGL, using Python and PyGame.

I'm going to use PyGame instead of GLUT to do all the initializing, windows opening, input handling, etc.

However, my shaders are failing to compile, unless I specify exactly the version of OpenGL and profile.

They do compile with GLUT initialization from the book:

glutInit()
glutInitDisplayMode(GLUT_RGBA)
glutInitWindowSize(400, 400)

# this is what I need
glutInitContextVersion(3, 3)
glutInitContextProfile(GLUT_CORE_PROFILE)

glutCreateWindow("main")

But, with simple PyGame initialization like this:

pygame.init()
display = (400, 400)
pygame.display.set_mode(display, pygame.DOUBLEBUF|pygame.OPENGL)

which doesn't specify exact OpenGL version 3.3 and CORE_PROFILE,
the same program would fail when trying to compile shaders:

  RuntimeError: ('Shader compile failure (0): 0:2(10): error: GLSL 3.30
  is not supported. Supported versions are: 1.10, 1.20, 1.30, 1.00 ES,
  and 3.00 ES\n', ['\n    #version 330 core\n    layout(location = 0) in
  vec4 position;\n    void main()\n    {\n        gl_Position =
  position;\n    }\n    '], GL_VERTEX_SHADER)

My question is: how do I do this initialization with PyGame?


texts:
What is the usual method of storing 3D models, textures, sounds and scripts (e.g. Lua files) during development and in a release? I am developing a game with my friends in mainly C++; in the prototyping phase we only had a single texture that was saved as a C header with the GIMP, but of course, this approach does not scale well and increases compilation times greatly.

Under Windows, the usual practice is to just dump them to the %PROGRAMFILES% subdirectory in which the game executable resides, perhaps arranging them in an appropriate tree structure. However, on Linux the picture seems a lot more complicated. The executable usually resides in /usr/bin, whereas applications store their other files in /usr/share, and I think it would be an extremely bad practice to put non-executables in /usr/bin. However, the directory structure during development is totally different.

I could come up with two different possible solutions:

Let the executable find the asset files relative to itself, and install the game to /opt. Then place symlinks to /usr/bin. During development, the relative path of the assets to the binaries is the same as during deployment.
Access the files with an absolute path which is defined as a preprocessor symbol. Let the build process (in our case, raw Makefiles) take care of defining it as it is fit.

Both approaches seem somewhat inelegant to me in one aspect or another. Is there a common practice in the game development industry about this?

The only relevant questions I could find were Determining the location of installed/on disk game assets  and Directory paths for resources and assets, but those did not address the problem of running "from the source tree".


texts: How to throw a ball vive controller object in unity3d

texts:
I have this simple line of code that through the ball. Under arm throw is right while if i try through any else ways its through movement is weird like a curve from down to up. what i am doing wrong. how do i through the ball using controller (touchingObject) object direction correctly/realistically.
Additionally i am also encounter a problem that if i through one ball all the previous throw balls move in that direction also. what the heck is that?

gameObject.GetComponent<Rigidbody> ().AddForce(touchingObject.transform.forward * 1000);


texts: How can I plot points and generate a list of coordinates?

texts:
Is there a program that lets me draw, a la pixel art, a map, and give me a list of coordinates and their corresponding colors? For example, I'd like to use a point and click interface to draw this

and then "export" this somehow.


texts: THREE.JS: why is the rotation only applied on the last axis used?

texts:
my function:

    function rotateAroundWorldAxis2(object, radians1, radians2) {

        object.rotWorldMatrix.makeRotationX(radians1).makeRotationZ(radians2);
       // object.rotWorldMatrix;

        // old code for Three.JS pre r54:
        //  rotWorldMatrix.multiply(object.matrix);
        // new code for Three.JS r55+:
        object.rotWorldMatrix.multiply(object.matrix);                // pre-multiply

        object.matrix.copy( object.rotWorldMatrix );

        // old code for Three.js pre r49:
        // object.rotation.getRotationFromMatrix(object.matrix, object.scale);
        // old code for Three.js pre r59:
        // object.rotation.setEulerFromRotationMatrix(object.matrix);
        // code for r59+:
        object.rotation.setFromRotationMatrix(object.matrix);

    }

my object was initialized like this:
object.rotWorldMatrix = new THREE.Matrix4();


texts: Which game consoles can I target as an indie with C++ and OpenGL

texts: I am an indie game developer and I wish to build games using C++ and OpenGL for game consoles. I've read that there are strict requirements for developing games for some consoles. So does anybody know which consoles readily allow indie developers to build games for them using C++ and OpenGL?


texts:
I want to make a game loop that is deterministic sort of like a physics engine but it's for game update and rendering.

I've done a lot of reading and I still was a bit confused.

I've read these articles:

http://gameprogrammingpatterns.com/game-loop.html
http://www.koonsolo.com/news/dewitters-gameloop/
http://gafferongames.com/game-physics/fix-your-timestep/
http://www.bulletphysics.org/mediawiki-1.5.8/index.php?title=Canonical_Game_Loop
http://gamesfromwithin.com/back-to-the-future-part-1
http://gamesfromwithin.com/back-to-the-future-part-2
http://www.learn-cocos2d.com/2013/10/game-engine-multiply-delta-time-or-not/

The one that made the most sense was the final article about multiply delta time or not.

I want to have fixed time step so I will design my games to fit in either 30 or 60 fps. So if I target 60fps all logic needs to be done in 0.166ms on a pc but if I am making an app that runs on mobile 0.33ms.

With those ideas in mind how would I setup the game loop that's deterministic but also frees the renderer but I am unsure how to go about doing the rendering loop? Would I interpolate the position before rendering?


texts:
I am currently developing a relatively simple 2D, topdown oriented adventure game for the iPhone and was wondering what would be the easiest way to create the maps for my game. I figured I would need some kind of visual editor that would give me immediate feedback and would allow me to place all objects in the world exactly where I want them. I could then load the saved representation of the world I create in the editor in my game.

So, I am looking for a simple map editor that allows me to do this. All the objects in my game are simply textured rectangles build up from two triangles. All I need to be able to do is position different rectangles/objects in the map, and give them a texture. I am using texture atlases, so it would be useful to be able to assign portions of textures to the objects. I then need to be able to extract all the objects from the saved representation of my maps, together with the name/identifier of the texture(atlas) they use, and the area of the texture atlas.

I have looked at some tile-based map editors like Tiled and Ogmo, but they don't seem to be able to do what I want.
Any suggestions?

EDIT: a more concrete example: something like the GameMaker level editor, but then with added export functionality in a handy format.


texts: How would I abstract a newtork layer for a Java messaging system, and is it worth it?

texts:
I'm currently working on an online Java game.I am not an experienced game programmer, having only worked with web applications, so far. Currently, I am building the messaging system between the client and the server, and I came across a big "what if".

Currently, the messaging system uses a custom solution and Java NIO with sockets, but it got me wondering: what if it fails? What if I have to change it all to some other system?

I decided that I should abstract the network layer of my engine, and if someday I need to change it, I'll swap the adapter. Then came two more problems; how would I abstract a network layer, and of course, is it worth the trouble? Will it be a waste of time?


texts: Libgdx - multiple images in a group, best practices - also overdraw question

texts:
I am trying to right a card game, that will have an image in the middle, a coloured border and potentially a symbol in the top left. I am using libgdx and a stage/scene2d.
The image will change depending on the suit (these are not your normal 52 deck type of cards), the border colour will change to match the suit, though this colour can be pre determined by the user so I can't pre-save coloured images (though I guess I could pre save about 15 diff colours and give the user a choice of 15) and the symbol will only be on some cards and not others.

As you can see from the two images I've added I have two diff images, border colours and symbols.
My question is relating to groups and overdraw.

I presume I should set up a group with 3 images in, and I'm hoping having this won't slow my game down as I will have potentially 30 cards on screen at once and 30 groups with up to 3 images in each could be a lot to draw. Is this right and will LibGDX be able to handle it fine?

How should I do the coloured border? Should I have the entire card a coloured rectangle and the image drawn on top? Would the draw method be trying to draw the coloured section underneath the image and thus wasting GPU/CPU time?
A friend of mine said I could just have a white image, and then set the colour using RGB values in the code? Is this possible? That would mean I could only have a single jpg which would be much better for apk size.

Or should I ignore using a jpg image and try and draw the coloured square using ShapeRenderer?

Thanks, I hope these questions aren't too many in one post.


texts: What to replicate in a PvP online action game?

texts:
We're developing a 2D PvP online action game. You can think of it like Super Smash Bros. We have a function call tree for characters like below:

CharacterInput.Update()
|-- CharacterController.StartJump()
    |-- CharacterMovement.TranslateState( "Jump" )
        |-- CharacterJumpState.OnEnter()
            |-- CustomRigidbody2D.Move( delta )

I think the pseudo-code above is kinda straight forward. It's a typical Controller-Movement structure where the Movement part is made using several character states. Also, the Movement part is responsible for animations, physics, visual effects and sound effects.

So, to make this networked, we need to replicate some values over the network.

To make it clear, we're using Photon Bolt for Unity, which provide a ExecuteCommand way to deal with server authority and client prediction. You can check it out here.

So in terms of replication, we realized that according to the structure, we should decide which part to replicate. According to the call tree above, we can split our character logic into these layers:

Input Layer: LeftStick, RightStick, A, B, X, Y, ...
Controller Layer: MovementDirection, ShootDirection, IsJump, IsShoot, IsMelee, ...
Movement Layer: CurrentState and all of its member variables
Rigidbody, Animation Layer: Velocity, GravityScale, CurrentAnimationState

Theoretically, replicate any of these layers can make it work because the process of higher layer to lower layer is deterministic. Once the higher layer is replicated, lower layers should be the same across the network.

Sadly, this is just theory. In reality, you must deal with lag, and unreliable packet delivery.

For example, if you only replicate the inputs, an unstable network may make it out of sync because state A may transit itself to state B if animation ends, but actually it should be transitted to state C if player presses some button.

However, if you only replicate rigidbody and animation, all the visual effect or audio effect triggered by CharacterState can't work, because CharacterMovement
doesn't even know which state it is in...

So, my question is, how do other games replicate their character? Especially in a PvP game?


texts: Unity: running GPU intensive operations in editor mode

texts:
I have written an erosion simulator that I want to execute from the editor (for generating terrain and such outside of play mode). Unfortunately, when I crank the parameters on my simulation, unity hangs. The UI becomes unresponsive, none of the menus work anymore. However, the process is still running - windows doesn't claim that the program is no longer responding.

The weird thing is that task manager claims that the GPU is sitting at zero utilization while Unity hangs. My (CPU side) erosion code looks something like this (executed via editor script):

    HydraulicCompute.SetFloat("_ErosionRadius", ErosionRadius);
    HydraulicCompute.SetBuffer(_erosionId, "HeightMap", heightMap);
    HydraulicCompute.SetBuffer(_erosionId, "Droplets", _dropletBuffer);

    int threadGroupsX = Mathf.CeilToInt(mapSize / 8.0f);
    int threadGroupsY = Mathf.CeilToInt(mapSize / 8.0f);
    for (int i = 0; i < 100; i++) {
        HydraulicCompute.Dispatch(_dropletId, Mathf.CeilToInt(_dropletBuffer.count / 1024.0f), 1, 1);
        HydraulicCompute.Dispatch(_erosionId, threadGroupsX, threadGroupsY, 1);
    }

When the size of the _dropletBuffer is bigger than 12,000 (32 bytes per droplet), and the heightMap buffer larger than 1024x1024 (4 bytes per pixel), then I run into the aforementioned problem.

I would guess that the issue occurs either because there is a problem with the buffer sizes, or that the frame takes too long and Unity times out.

When I comment out the Dispatch calls Unity is able to allocate and populate the buffers instantaneously (at least it looks really quick). While that doesn't rule out the potential buffer problem, it certainly makes it seem less likely.

So what exactly is the problem here? Is it a memory problem? Or is the frame timing out? Or something else entirely?

Is there a prescribed way to doing this kind of intensive GPU work in the background in editor mode? I've looked at the Job system, but that seems to be CPU side only...

[EDIT]

I have managed to put together the following snippet which always crashes on my GPU (NVIDIA 980ti):

[numthreads(1,1,1)]
void CSMain(uint3 id : SV_DispatchThreadID)
{
    for (int i = 0; i < _NumIterations; i++) {
        HeightMap[1024*512 + 512] = 0;
    }
}

When executed as 1 thread group for 1 iteration (_NumIterations = 1), this crashes my GPU driver. I am running on the latest version. I have no idea as to what might be causing the problem, windows event viewer just lists a nvlddmkm error, which apparently means it could be just about anything. It's frustrating to say the least.


texts: Stop current animation and re-play immediately?

texts:
When the player hit something, I'm playing hit animation from animation_player. However when player hit something while hit animation is playing, it just ignored and play previous hit animation.

I need to stop the animation, but couldn't find any related information. How do I stop the animation and play again immediately?


texts: How can I implement a short-cut grass effect?

texts:
I've been looking at some screenshots from games like Rocket League and FIFA:

and I started wondering one would achieve the short-cut grass effect.

Is it a shader? Is it actual geometry? Or just textured quads? If anyone could point me in a direction, that would be greatly appreciated.


texts:
Is their a way to execute or call a random function in unity. Something like:-

  void Update(){random(func1(),func2())}

  void func1(){print("func1")}

  void func2(){print("func2")}


texts: Minecraft Forge 1.8 Custom Recipe Manager, need help

texts:
sorry for asking this question. Some of you will probably find it very easy but I just can't figure out how to do it.

I want to write a custom Recipe Manager. It has to check the recipes. Therefor I create an ArrayList<Item[]> recipes = new ArrayList();

The Item Array store 4 items(3 inputs and one output):Item[] items = {Item1, Item2, Item3, Item4};

I want to get a function that does this:

I give it a Item and it gives me an ArrayList containing all the Item[]s containing that Item as the 0th index and a Boolean that is true when there is any Item[] containing the Item.
Then I give (if needed to another function) an second Item. It returns me a new ArrayList containing all of the previous Item[]s that containe the Item and a Boolean similiar to 1 but for the 1th index.
Analog to 2. (I think you get what I mean).

The 3 points have to be handled in another method call.
Thank you very much in advance
Nova


texts:
It is common knowledge that if the framerate of a game is over 25-30 fps, we humans perceive it as running smoothly. More is better, but if it is above that, it at least doesn't lag.

I have been looking for research as to how long  a mouse input can take to reach the screen, and still feel instantaneous to the average person, for example. I'm sure it may vary a little bit, from person to person, but I'm sure we all have a limit on how fast anyone can perceive small time differences between events.

I'm interested in this because I want to try and statically update the data for my game, for example every 0.05 seconds, instead of as soon as I get a new input. This will save computer power, while still not causing delay in the game.

What is an acceptable input delay?


texts: How can I maintain saved game backward compatibility?

texts:
I have a complex sim game I want to add save game functionality to. I'll be updating it with new features continually after release.

How can I make sure my updates don't break existing save games? What sort of architecture should I follow to make this possible?


texts: How do I handle rope physics with fixed ends and a sliding weight?

texts:
I've been interested in rope physics recently—I've successfully implemented a simple Verlet rope with moveable ends. Now I am trying something a little different: I want to start by recreating the mechanic from the game Sky Tourist (video here):

I assume Sky Tourist uses Verlet integration for its rope, but it also has the main character sliding along the rope as a moving weight. How can I recreate that?

Is it just done by applying different gravity to where the character is? Also, how is the collision detection handled between the character and the rope? If the game uses a physics engine like Box2D, how does it make it play nice with the rope, considering it's not a part of the Box2d world?


texts:
I'm making a game where the player controls a character. This character starts off bland & weak. But over the course of playing the game, picks up abilities which the character uses as attacks/magic/damage dealers during battles. There are many different types of abilities/powers. I want to allow the player to level up these abilities through whatever means I come up with (haven't done that yet).

How do I balance ability ATTACK power (damage dealt) for instance? I'm sure there's some kind of abstract way of approaching this but it's eluding me. I want to make sure that if I make a super overpowered ability that there is another ability out there that can at least counter act it.

So the question: how do I approach ability power upgrade balancing when designing my game? Is it an algorithm? Can it be done linearly? So that there is always an awesome new strong ability waiting around the corner for the player character?


texts:
I'm currently working on a OpenGl Project and I have alot of difficulty understanding how arcball camera work. From what I have read online, all I have to do is to rotate a camera around a target and I dont have to worry about any others things. This is my code.

glm::vec4 cameraTarget = glm::vec4(InPointToFix.x, InPointToFix.y, InPointToFix.z, 1.0);

const GLfloat x_Rotation = InPitchValue / 57.5829;
const GLfloat y_Rotation = InYawValue / 57.5829;

glm::mat4 tempoMatrix = InMatrix;
tempoMatrix = glm::rotate(tempoMatrix, x_Rotation, glm::vec3(1.0, 0.0, 0.0));
tempoMatrix = glm::rotate(tempoMatrix, y_Rotation, glm::vec3(0.0, 1.0, 0.0));

glm::vec4 cameraPosition = (tempoMatrix * glm::vec4(1,1,1,1));

InMatrix = glm::lookAt(glm::vec3(cameraPosition), glm::vec3(cameraTarget), glm::vec3(0.0, 1.0, 0.0));

So, in my code, I get my previous View Matrix from the function and my angle parameters, I create a new tempoMatrix by using my old Matrix, I rotate it by the Yaw and pitch I received by the function, I then transform my tempo matrix into a vec4 (to  be used as a vec3 later) and then I apply the change to my ViewMatrix I receive by reference.

What happen is that whenever I apply the change, the camera stays at the exact same position but just zoom out and out until I see nothing ...

It's been a while I'm trying to figure this out and I really need help with the ArcBall Camera.


texts: How to draw a circle with MonoGame Extended?

texts: I can not figure this out and have basically no idea. I have already installed MonoGame.Extended through NuGet. I have heard you can draw basic shapes like circles with it, but where can I find the method?


texts:
I am working on a 2D game, and my camera is a orthographic with a size of 320.

I want to display some text, but not with OnGUI(). Rather, with a GUI Text game object.

I couldn't help but notice that positioning my GUI Text object is a real pain: apparently, the onscreen coordinates where the text appears range from 0 to 1. That is, 0.5 is the center of the screen.

If I wanted to put my label at exactly (100,50) regardless of the screen size, I would have to calculate something like

(100f / Screen.width, 50f / Screen.height)

Is there a way to tell the GUI Text to appear at the actual transform position as it appears on the scene editor? Currently, if you move the GUI Text game object's transform slightly to the right, the rendered text will be displaced a LOT to the right instead...


texts: How can I get the color of a pixel in a SharpDX Direct2D bitmap or render target?

texts:
I am working on a simple drawing game and I need to get a Flood Fill algorithm working for a Paint Bucket tool.

I have the game running on WinForms at the moment which is extremely slow, but I have a working Flood Fill algorithm there, I could get the code to support SharpDX if I could get the color of a pixel (either from a SharpDX.Direct2D1.Bitmap or from a SharpDX.Direct2D1.RenderTarget), but I can't find a way to do so.


texts:
I'm looking do make an FPS-like camera, but I'm encountering some problems. If I'm first rotating and then translating the camera, everything works fine, but the coordinate system. For example, if I want to go backward with the camera, I have to set the Y coordinate positive. But when I'm translating a model matrix on the Y coordinate in a positive direction, it is moving forward. So somehow the coordinate system is flipped.

When I'm first translating the camera and then rotating, the coordinate system is the same, but now the camera is rotating around the origin, which makes sense, but when I'm looking at examples, everyone does that and no one is complaining about rotating around the origin.

I hope you understand what I mean and I hope you can give me some advice.


texts:
For an open source game I wanted to redesign the resource management system but got into a dead end and need some pointers to some reading material or where to go now.

Starting point was (mostly) a Loader class Header/Src

Format of the resources:

Resources are (usually) in archives, that consist of numbered files (no names) which can be of any type and may contain related meta data (size, draw offset, ...)
Often common formats (wav, midi, bmp) but custom formats possible, e.g. for textures:

2D Offset (model matrix translation)
Player color mask (extra greyscale bmp)
Partitioned bmps (e.g. links (indices) to body and head (bmps) to reuse bmps in the same file)

Extensions/Overwrites possible: Having 2 archives with the same name (different folders) will merge them (later loaded archive entries add or overwrite ones from the earlier ones)

The problems I wanted to solve are messy code (no SRP...), non-uniform handling of resources and a dynamic_cast for most accesses (basically: dynamic_cast<type*>(Get("foo", 42))). Having only 1 type of texture would also simplify rendering (maybe 2: One with player masks, and one without)

My approach (based on ENTT):

ResourceLocator: Given a name, returns the list of archives to load (handles extension/overwrites)
ResourceCache<Type>: Holds a loaded resource of a given type
ResourceLoader<Type>: Loads a resource
ResourceRegistry: Holds multiple caches, 1 locator and (maybe) loaders. Provides access to all resources by checking the cache first, and loading it on miss (adding it to cache)

This works well for sound effects and music:

SoundEffect& get(ResId id){
   if(id in soundcache) return it;
   archive& = get(id.name);
   SoundEffect* effect = load(archive)
   add to cache and return effect;
}

This is nice and generic. But I'm struggling on how to do this for textures for which I have different types:

"normal" textures (backgrounds, buttons...) -> easy
map-specific textures (e.g. trees with snow or w/o snow depending on map type. Previously the Loader stored a reference to the map archive and consumers simply called GetMapTexture(idx) -> might not be required for all maps, shall I unload all of them on map change and reload as required?
nation-specific textures (every nation has an archive and/or an offset in an archive) -> Using ("archive", number) as the key does not work anymore.

Additionally lots of textures may need to be combined (e.g. the split-bitmaps or shadow with buildings/people...) and there are animations. This led to having fixed size multi-D-arrays with many different indices where the meaning is contained in the Loader class.

So the "normal" textures are easy: Just load them into an OGL texture and use them. The others need (usually) multiple images combined into 1 texture. So I don't want to put those parts into the texture cache but only the combined one. But having those multi-D-Arrays also feels like a design flaw. And how would I reference/use them? How are others doing that?

Note: The indices of the images making up a texture/bld... can be (kinda) easily calculated from the nation index, building index, animation frame index, ...

Example usages (from current/old) code:

drawAnimal(int type, int dir, int animationFrame){animal_cache[type][dir][animationFrame].draw(pos...);}
drawCarrier(...){carrier_cache[carriedWare][dir][animationFrame][isFat].draw(pos, playerColor,...);}
drawBuilding(...){building_cache[nationIdx][bldIdx].draw(pos, playerColor,...);}


texts: How can I transform one triangle into another triangle with HTML5 Canvas?

texts:
Given a triangle I'm searching for the canvas transformation to transform it into an other Triangle with the corner coordinates (A,B,C)

Input triangle: Red Triangle: A'=(0,0) B'=(80,80) C'=(0,80)
Output triangle: Triangle with the coordinates A=(10,30), B=(150,110), C=(50,140)
I'm looking for the transformation that transforms the Input triangle into the output triangle where the points A, B and C should be parameters of the transformation.

The code that transforms the red into the green triangle can be found at http://jsfiddle.net/Tarion/mc9mT/ - yet it is obviously wrong because it does not fit the points A,B,C.

What I need is the code or at least the strategy to transform the red triangle it to the triangle that is defined by the given points A,B,C

The green triangle is not the solution but just an (almost) arbitrary transformation of the red one.


texts:
I am trying to create a waterfall that looks similar to the first image below (please check this video for a better idea of what I want to achieve) with physics properties so it can move or around objects with colliders on its course (similar to the second image below). Though the linked waterfall is 3d I am interested in a 2d implementation.

Note that the objects are dynamic and some move frequently hence the waterfall has to reshape every frame. The objects move slowly either moving to different positions or rotating. How can this be done?


texts: New clients don't see objects spawned before they connect

texts:
I'm making a game with UNet where the server must create some objects when he connects to the game, and all clients play with these objects that the server has created.

A server connects to the game
In his start method he calls a function CmdbuildEverything to spawn some objects to the game.
A local player connects to the game. The local player should be able to see the objects that the server player has created.

The code:

public class GameScript : NetworkBehaviour {
    void Start() {
        if(base.isServer)
            CmdbuildEverything();
    }
    [Command]
    void CmdbuildEverything() {
        GameObject ob1 = (GameObject)Instantiate(Resources.Load("Temple"), new Vector3(0, 0, 1), Quaternion.identity);
        GameObject ob2 = (GameObject)Instantiate(Resources.Load("Temple"), new Vector3(0, 1, 0), Quaternion.identity);
        GameObject ob3 = (GameObject)Instantiate(Resources.Load("Temple"), new Vector3(1, 0, 0), Quaternion.identity);
        NetworkServer.Spawn(ob1);
        NetworkServer.Spawn(ob2);
        NetworkServer.Spawn(ob3);
    }
}

The problem is that the objects are created only on the server player and don't appear on the clients payers.

How can I solve that?


texts: Tournament ranking for card game bot fights - how to try new bot against existing ranking?

texts:
Let's say we run a tournament for 10 bots playing 1-1 fights in card game with significant randomness influence. To measure bot skills level we run round-robin with 10k matches per each pair. Ranking shows that bots #3, #4 and #5 have very similar result.

Some time later 11th bot is developed. What is the best strategy to rank it honestly?

Re-run whole tournament? Bots with similar results can come out on different positions.
Run all ranked bots against new one? Again, those results could re-rank previous positions, if taken into account.
something different?

CPU time is not limited and tournaments are run offline.


texts: Is it possible to programmatically prevent a game from pausing when its window loses focus?

texts: I'm playing Skyrim in windowed mode and I am trying to create a bot for this game for personal use. I would like to have the bot play the game in the background, while I do other things, the only problem is that the game window pauses when it loses focus. Is there a way to make the Skyrim process think that it still has the focus, so it continues to run while I do something else on another window? I'm not a windows programming expert but would this be possible if I could somehow intercept the message that says unfocused or minimized to the process, and thus let the process think its still focused? I think Skyrim uses directx, so is it possible to come up with a solution from that end?


texts:
I'm a hobbyist and I've just finished implementing the "game" part of a game I'm developing, and I feel as if it finally matured enough to be worth adding a menu to start a new game, exit, edit options, etc., and so I tried to find sources online with tips for creating menus in XNA (first time creating a game in XNA).

So far, I haven't really found any good solutions.  I guess I'm looking for a solution that isn't ad hoc so that I could easily reuse it for future games I decide to make.  Is there any such built in XNA functionality I'm unaware of?  Any XNA libraries out there that would prove useful?  Or do you guys have any tips in general for easy/robust/reusable implementation of menus in XNA?

Thanks in advance!


texts:
I am in the process of developing my first game on android mobile platform, it’s a tower defence game and I am currently busy designing the scoring system.

At the end of the stage when the user has defeated all the waves of enemies I want to take his score and somehow calculate a rating out of 3 Stars.

What will the best way be to calculate a score?
When should I increment the score during gameplay for example when an enemy dies?
And how do I calculate if the score is worth 1-3 Stars at the end of the stage?

Basically I want help or any ideas on how the formula should look like and how to calculate if the user scored a 1.. 2... or 3 Stars.

My variables in game :

Every enemy has a value:   Example $5

The stage has a number of life’s before you are defeated: Example 20

Each stage starts with money that you buy your towers with: Example $120

Each towers costs money:  Example $30
A stage can consist of 1 or more waves of enemies.

Any help or ideas would be appreciated as I am new to game development….


texts: Bloom only colors with at least one value equal to 1,

texts:
I want to bloom/blur any color that has a 1 in it,

like (1,0,0) and (1,0,1) etc.

The script bellow blooms any color over a threshold,
but what I want blooms only specific colors.

'Selective bloom'

uniform sampler2D bgl_RenderedTexture;
const float BRIGHT_PASS_THRESHOLD = 0.55;
const float BRIGHT_PASS_OFFSET = 0.08;

#define blurclamp 0.002
#define bias 10.8
#define KERNEL_SIZE 6.0

vec2 texcoord = vec2(gl_TexCoord[0]).st;

vec4 bright(vec2 coo)
{
  vec4 color = texture2D(bgl_RenderedTexture, coo);
  color = max(color - BRIGHT_PASS_THRESHOLD, 0.0);
  return color / (color + BRIGHT_PASS_OFFSET);
}

void main(void)
{
  vec2 blur = vec2(clamp( bias, -blurclamp, blurclamp ));

  vec4 col = vec4( 0, 0, 0, 0 );
  for ( float x = -KERNEL_SIZE + 1.0; x < KERNEL_SIZE; x += 1.0 )
  {
    for ( float y = -KERNEL_SIZE + 1.0; y < KERNEL_SIZE; y += 1.0 )
    {
      col += bright( texcoord + vec2( blur.x * x, blur.y * y ) );
    }
  }
  col /= ((KERNEL_SIZE+KERNEL_SIZE)-1.0)*((KERNEL_SIZE+KERNEL_SIZE)-1.0);
  gl_FragColor = col + texture2D(bgl_RenderedTexture, texcoord);
}

is the script I was trying to edit, but I don't know GLSL (I know python)


texts: What are the disadvantages of using multiple inheritance to implement components?

texts:
I've been doing research on component-based game engines and would like to use that model for future game projects. From what I gather, objects in a component-based system are just collections of attributes and behaviors. The examples I've seen have a high-level interface such as Attribute<T> *Entity::getAttribute<T>(int id) but discussions about those systems often talk about performance problems. It seems like this could be implemented with greater efficiency in C++ using multiple virtual inheritance since the compiler could inline attribute accesses and behavior method calls:

// Layer 1: Base
struct Entity {
  virtual ~Entity() {}
  virtual void draw() {}
  virtual void update(float seconds) {}
};

// Layer 2: Attributes each extend from Entity
struct Position : virtual Entity { Vector3 pos; };
struct Velocity : virtual Entity { Vector3 vel; };
struct Health : virtual Entity { int health; };
struct Target : virtual Entity { Position *target; };

// Layer 3: Behaviors extend from the attributes they need
struct Renders : virtual Position {
  Model model;
  void draw() { model.draw(); }
};
struct Moves : virtual Position, virtual Velocity {
  void update(float seconds) { pos += vel * seconds; }
};
struct Seeks : virtual Moves, virtual Target {
  void update(float seconds) {
    if (target) vel = (target->pos - pos).unit();
    Moves::update(seconds);
  }
};

// Layer 4: Definitions extend from the behaviors they need
struct Rocket : virtual Health, virtual Renders, virtual Seeks {};

However, many component-based engine resources discount multiple inheritance without really saying why. I'm sure I'm missing something, but what are the disadvantages of using multiple inheritance like this over lists of components? I know calls to base classes when using multiple inheritance incur an additional constant offset, but that seems better than going through a run-time map for each attribute access. The only disadvantage that I can think of is not being able to swap out components at run-time.

Resources:

http://www.gdcvault.com/play/1911/ (PPT)
http://www.richardlord.net/blog/what-is-an-entity-framework


texts: Why is OpenGL using 100% CPU shortly after start up when wglSwapIntervalEXT is enabled?

texts:
I have a game which uses SFML, which in turn uses OpenGL.

When I run the game, it will use 100% CPU for (usually) about 24 seconds, and then immediately falls down to normal usage. I can't figure out what's going on during these 24 seconds. In some cases, it stays at 100% CPU usage forever, but it usually stops after 24 seconds.

I've attempted to profile it, but the most information I can get is that the time is all being spent in my OpenGL driver. Aside from this, I can't see any useful information. It's also unable to tell me who the caller of the offending OpenGL code is; instead, it just tells me that the caller is an 'Unknown Frame' called by main.

One interesting thing I've noticed is that although it's using 100% CPU, it has no negative effect on my game. It runs without any FPS loss or slow down. This makes me think that the problem may be in the code that's enforcing vsync.

Has anyone encountered this? Any ideas what it might be, or how I can go about figuring it out?

Also, to clarify, the game is single-threaded. The thread using 100% CPU is my game thread, not one of the background threads created by OpenGL.

EDIT : The problem is, in fact, vsync. It's enforced using OpenGL's wglSwapIntervalEXT function. If I disable it and use sleeps to limit my frame rate, CPU usage stays low. I still don't understand why it's behaving like this when vsync is enabled, though.


texts: lwjgl and slick util text over textured quad

texts:
So, I load a TrueTypeFont like this:

   private TrueTypeFont trueTypeFont;
   try {
        InputStream inputStream = ResourceLoader.getResourceAsStream("assets/fonts/main.ttf");

        Font awtFont2 = Font.createFont(Font.TRUETYPE_FONT, inputStream);
        awtFont2 = awtFont2.deriveFont(24f); // set font size
        trueTypeFont = new TrueTypeFont(awtFont2, true);

    } catch (Exception e) {
        e.printStackTrace();
    }

After that, I draw a textured quad, as one usualyy would and then, draw trueTypeFont.drawString(this.x, this.y, this.text, Color.white);
.
What this gives, however is far from text, this is what it does, the black is supposed to be text...

How to fix?


texts: What is the Basic Game Screen/Scene Life Cycle?

texts:
Question

What is the standard or basic game screen/scene life cycle used in most games?

What is Screen/Scene?

The term screen or scene refers to the current displayed entity holder where game entities or objects are placed. I personally call it scene because the term screen for me is the hardware screen, but I have read that others call it screen as denoted by Screen Manager classes (I call it Scene Manager).

Understanding Scene Management and Game Scene Life Cycle

Here is my current understanding of a simple scene management and game scene life cycle:

Assuming, we have 4 screens/scenes in a basic game:

Splash Scene - used to display the company logo, the game logo and loading of most of the game resources used by the menu scene and loading scene.
Menu Scene - used to display menus and buttons, referred to as the "main menu" and the gateway to other scenes especially the game scene (sometimes there are settings scene, help scene and about scene).
Loading Scene - used to display a progress bar or anything related that indicates the loading and unloading of the game scene.
Game Scene - used to display the game logic and implementation of the game itself.

  start application ---(load splash scene contents)---> splash scene ---(load menu scene and loading scene contents and unload splash
  scene contents)---> menu scene ("start game" pressed) --->
  loading scene ---(load game scene contents)---> game scene ("return to main menu" pressed) ---> loading scene ---(unload
  game scene contents)---> menu scene

Start Application
Load Splash Scene Contents
Show Splash Scene
Load Menu Scene and Loading Scene Contents
Hide Splash Scene
Show Menu Scene
Unload Splash Scene Contents
"Start Game" Button Pressed
Hide Menu Scene
Show Loading Scene
Load Game Scene Contents
Hide Loading Scene
Show Game Scene
THE GAME IMPLEMENTATION
"Return to Main Menu" Button Pressed
Hide Game Scene
Show Loading Scene
Unload Game Scene Contents
Hide Loading Scene
Show Menu Scene

Is this the right way to do it in most cases? I know that the screen/scene life cycle varies depending on the game you are creating. I just want to know if this is the right way to do it or am I doing things the wrong way?


texts:
I have a 3D volume where every voxel is 16 bits. Is there anyway I can use some kind of compression to store the data so I can use less video ram?
Webgl supported different compressiosn if you enable them with extension, but can I use them for a one channel data?

Like WEBGL_compressed_texture_s3tc only supports rgb and rgba data:

COMPRESSED_RGB_S3TC_DXT1_EXT
COMPRESSED_RGBA_S3TC_DXT1_EXT
COMPRESSED_RGBA_S3TC_DXT3_EXT
COMPRESSED_RGBA_S3TC_DXT5_EXT

If its not possible in webgl, is it supported in OpenGL to compress a 16 bit values with one channel?


texts: What is the difference between a game framework and a game engine?

texts:
What is the difference between a game framework (for example, XNA with C#, SDL for c++) and a game engine?

Do game frameworks use engines? Does a game engine encapsulate sub-engines like physics engines, particle engines etc? Should they be used together, or are they mutually exclusively?

I take it there are separate engines for both 2D and 3D?


texts: Can I create a Sprite Asset using a downloaded Texture at runtime?

texts:
I know that Asset Bundles exist, and I'm already taking a look at them. But I'm still interested in this particular approach:

I am interested in downloading a .png image from the Web, and then "consolidate" it as a Sprite asset. After doing so, I can display this sprite in my game in the future without ever downloading that image again.

I was able to download the image and use its texture to create a Sprite object and use it for my SpriteRenderer:

        WWW request = new WWW("www.example.com/image.png");
        yield return request;
        if (request.isDone) {
            ((SpriteRenderer)renderer).sprite = Sprite.Create(request.texture, new Rect(0,0,request.texture.width,request.texture.height), new Vector2(0.5f,0.5f));
        }

Is it possible to grab this texture and generate a Sprite asset? With all the properties like pivot, pixels per unit, packing tag, etc?

UPDATE

Alright, so turns out that Sprite.Create let's me set the pivot and pixels to units properties. No packing tag, though, but I guess that makes sense since packing should be done during development and not during runtime.

Given this, I suppose one could serialize the generated Sprite class.


texts:
I'm trying to figure out how to write a good AIManager class in Java in order to manage the AI of all the objects in my game.

From another post of mine, an user has suggested to do the following:

Your calculations should go into the update method. it's fine to have an AIManager class, that has an update() method itself which gets called in the main update loop.
this AIManager could hold a list of all the Objects that need to be updated. Since you're using java, you could use an interface to declare something to have an AI, and use this interface to iterate over your objects (which could then be completely different Classes) and have interactions managed by this AI manager.

It is not so clear to me.

If my Player class implements SeekArriveMovement (for instance), then it should implement the methods of this interface. And AIManager have to implement an update method. But... i don't know. I mean.. how the AIManager should be built and how it should interact with the objects?

Something like this.. ?

public class AIManager {

private List<Object> objects;

public AIManager() {
    objects = new ArrayList<Object>();
}

public void addObject(Object o) {
    objects.add(o);
}

public void removeObject(Object o) {
    objects.remove(o);
}

public void update() {
    for(Object o : objects) {
        if(objects instanceof SeekArriveMovement) { // ?
            RedEnemy re = (RedEnemy)o;
            move(re);
        }
    }
}

private void move(RedEnemy re) {
    // ?
}


texts:
Tutorials on the internet usually say to extract plane data from MVP (model view projection) matrix (or VP?) and then test the bouding volume against each of the frustum planes. I've thought of a different approach:

calculate model's bounding sphere (center + radius)
define point A = center, B = center + float3(radius, 0, 0) - some point on the sphere
multiply A and B by MVP matrix to get point coords in clip(?) space
calculate radius in clip space (distance from A to B)
check if sphere is in the frustum, sth like: A.x - radius < 1 && A.x + radius > -1

Would this work (it would be only an approximation but should be good enough)? In (5) what values should I test against? -1 and 1? Because I'm not sure if I'm not mixing up spaces.


texts: Is there a cross-platform special directory I can use for game save files?

texts:
I'm developing with LWJGL and Java on a Windows 7 laptop. I've successfully set up saving to the %appdata%\gamename\saves\ or long form c:\users\user\appdata\roaming\gamename\saves\ folder by using File dir = new File(System.getenv("APPDATA") + "\\gamename\\saves\\");.

I have hobbyist level experience with Linux, and zero experience with OSX. My game will be fully cross platform.

Is System.getenv("APPDATA"); cross platform? If so, where does it point to on Linux or OSX? Is there a best practices alternative that I should use?


texts: Keep 3d model facing the camera at all angles

texts:
I'm trying to keep a 3d plane facing the camera at all angles but while i have some success with this:

Vector3 gunToCam = cam.cameraPosition - getWorld.Translation;
Vector3 beamRight = Vector3.Cross(torpDirection, gunToCam);
beamRight.Normalize();
Vector3 beamUp = Vector3.Cross(beamRight, torpDirection);
shipeffect.beamWorld = Matrix.Identity;
shipeffect.beamWorld.Forward = (torpDirection) * 1f;
shipeffect.beamWorld.Right = beamRight;
shipeffect.beamWorld.Up = beamUp;
shipeffect.beamWorld.Translation = shipeffect.beamPosition;

*Note: Logic not wrote by me i just found this rather useful

It seems to only face the camera at certain angles. For example if i place the camera behind the plane you can see it that only Roll's around the axis like this:

http://i.imgur.com/FOKLx.png (imagine if you are looking from behind where you have fired from.

Any idea what to what the problem is (angles are not my specialty)

shipeffect is an object that holds this class variables:
public Texture2D altBeam;
public Model beam;
public Matrix beamWorld;
public Matrix[] gunTransforms;
public Vector3 beamPosition;


texts:
I have a vehicle that needs to move on a randomly generated terrain and handle slopes. I'm not using wheels, but instead moving the vehicle with velocity. The ideal case would be if I can make the vehicle rotate according to the terrain edges and move smoothly as shown here:

How can I accomplish this? Launching raycast from the bottom left angle and calculating the distance from the ground, then rotating according to that?


texts: Screen or World Coordinates to tile Coordinates

texts:
I have Plane made of tiles in opengl. I start drawing them at (0, 0, -20) after that i do my translations so that the view is rotated somewhat similar to an isometric (kind of) perspective.

I'd now like to know, how many tiles are visible in each direction. So what i need to know basicly is, which coordinates (int the "before translation" - space) are now visible in the translated view.

The "tiles" before the translations" (for example in x direction there are 14 tiles visible):

And after the translations ( now there are 28 tiles visible in "old" x direction):

I tried to get the visible area via gluUnproject with no success.

EDIT: I already asked this question when i was trying to build the exact same thing in 2D and i got a good answer:

Calculating the number of tiles shown on an isometric map

maybe this helps to describe my problem further.


texts:
I have a 2d game where I want to display UI element perfectly aligned to specific gameObjects.

I have an ortographic camera and I used to Camera.main.WorldToScreenPoint() function giving it the gameobject position modified, for instance, by +1 on X component to get the UI element on its perfect right.

My problem is that the element is not on the gameObject's perfect right, but sensibly above. See this schema:

Expectation:

G -> UI element

Reality:

---> UI element
G

I tried also to use the WorldToViewportPoint() but it's not giving the desired result.
So, I think this is the right way to go but I can't guess what I'm missing.
Any clue?

EDIT:
After a little bit more observations it seemed that the UI element alignment depends somehow on it's distance from the center of the screen (of the camera viewport I guess), so that if the gameObject is below half height the UI element y position won't be on the perfect right but slightly below it and if above half heigth will be slightly above the perfect right. Same for x coordinate. Is there a way I could control this?


texts: Can I use the free version of Construct 2 on Gamejolt?

texts: According to Scirra's website, I am not permitted to use the free version of Construct 2 for commercial purposes. If I host a game I created with the free version of Construct 2 on Gamejolt where I can earn money on the game, am I violating Scirra's terms?


texts:
Hi guys,

Could anyone kindly shows me a little bit of code about pick and paint color to the sprite?

here is my code that I have played around, but I still cannot find out and achieve it.

Thanks you in advance for your time and consideration.

preload: function() {
    this.game.load.image('test', 'test.png');
},

create: function() {

    this.color1 = this.drawRec('rgb(141,243,160)', 20, 20);
    this.color2 = this.drawRec('#6bd4e0', 100, 20);
    this.color3 = this.drawRec('#cb6be0', 20, 100);
    this.color4 = this.drawRec('#8df3a0', 100, 100);
    this.square = this.game.make.bitmapData();
    this.square.load('test');
    this.square.addToWorld(this.game.world.centerX, this.game.world.centerY, 0.5, 0.5);

    this.game.input.onDown.add(this.pickColor, this);
},

drawRec: function(color, x, y) {
    this.bmd = this.game.make.bitmapData(100, 100);
    this.bmd.ctx.beginPath();
    this.bmd.ctx.rect(0,0,50,50);
    this.bmd.ctx.fillStyle = color;
    this.bmd.ctx.fill();
    this.sprite = this.game.add.sprite(x, y, this.bmd);
},

pickColor: function(pointer, x, y) {
    console.log(this.bmd.getPixelRGB(x,y));
}


texts: What is the mathematical explanation behind this implementation of simulating eyeballs roll in eyes?

texts:
I want to simulate eyeballs roll in eyes and I have found and forked this implementation in codepen.io. This is exactly what I need.

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var border = 10;
var centerX = c.width / 2;
var centerY = c.height / 2;
var radius = 40;

var radiusEye = 12;

var faceCenterX = centerX;
var faceCenterY = border+radius + 60;

var radiusEyeIn = 6;

var eyeYPosition = faceCenterY-8

var reyedx = faceCenterX+(radiusEyeIn/2)+13;
var reyedy = eyeYPosition;

var leyedx = faceCenterX-(radiusEyeIn/2)-13;
var leyedy = eyeYPosition;

var eyesgap = 4;

var eyeXGap = (radiusEye/2)+9;

var reyedxafter = reyedx;
var reyedyafter = reyedy;

var leyedxafter = leyedx;
var leyedyafter = leyedy;

function drawscreen(){

  ctx.beginPath();
  ctx.arc(faceCenterX, faceCenterY, radius, 0, 2 * Math.PI, false);
  ctx.fillStyle = 'rgba(100,100,100,0.5)';
  ctx.fill();
  ctx.stroke();

  var radiusEye = 12;
  ctx.beginPath();
  ctx.arc(faceCenterX-eyeXGap, eyeYPosition, radiusEye, 0, 2 * Math.PI, false);
  ctx.fillStyle = 'rgba(255,255,255,1)';
  ctx.fill();
  ctx.stroke();

  ctx.beginPath();
  ctx.arc(faceCenterX+eyeXGap, eyeYPosition, radiusEye, 0, 2 * Math.PI, false);
  ctx.fillStyle = 'rgba(255,255,255,1)';
  ctx.fill();
  ctx.stroke();
}

function draweyes() {

  ctx.beginPath();
  ctx.arc(reyedxafter, reyedyafter, radiusEyeIn, 0, 2 * Math.PI, false);
  ctx.fillStyle = 'rgba(0,0,0,1)';
  ctx.fill();

  ctx.beginPath();
  ctx.arc(leyedxafter, leyedyafter, radiusEyeIn, 0, 2 * Math.PI, false);
  ctx.fillStyle = 'rgba(0,0,0,1)';
  ctx.fill();
}

//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

function mouseMove(e) {
        var mouseX = e.pageX - this.offsetLeft - faceCenterX;
        var mouseY = e.pageY - this.offsetTop - eyeYPosition;

        var ratioX = Math.abs(mouseX)/(Math.abs(mouseX)+Math.abs(mouseY));
        var ratioY = Math.abs(mouseY)/(Math.abs(mouseX)+Math.abs(mouseY));

        if(mouseX > 0){
          reyedxafter = reyedx + (ratioX*eyesgap);
        } else {
          reyedxafter = reyedx - (ratioX*eyesgap);
        }

        if(mouseY > 0){
          reyedyafter = reyedy + (ratioY*eyesgap);
        } else {
          reyedyafter = reyedy - (ratioY*eyesgap);
        }

        if(mouseX > 0){
          leyedxafter = leyedx + (ratioX*eyesgap);
        } else {
          leyedxafter = leyedx - (ratioX*eyesgap);
        }

        if(mouseY > 0){
          leyedyafter = leyedy + (ratioY*eyesgap);
        } else {
          leyedyafter = leyedy - (ratioY*eyesgap);
        }

        ctx.clearRect(0, 0, c.width, c.height);
        drawscreen();
        draweyes();
}

function init() {
    //c.addEventListener('mousedown', mouseDown, false);
   // c.addEventListener('mouseup', mouseUp, false);
    c.addEventListener('mousemove', mouseMove, false);
    drawscreen();
    draweyes();
}

init();
<canvas id="myCanvas" width="500" height="400" style="border:1px solid #000000;">
</canvas>

I can just use this one but I don't understand the mathematical explanation behind this solution. I can only think of limiting the movement of the eyeballs in the eyes. Why do I have to do it like this one? What is the purpose of calculating ratioX and ratioY? Is there a simpler way to do similar simulation?


texts: canvas not found in game view with unity

texts:
I am working on a GearVR app with Unity3D.I have an environement and I have placed a canvas in the scene.I have set the canvas Render mode to "World Space".But when I runned my project,the canvas is getting displayed on the scene view,but in the game view the canvas is not getting on the scene.But whereas in the camera view its showing the canvas.What will be the issue?.

When I set me canvas Rendere mode to Screen Space-Overlay the canvas is getting displayed in the scene but as the lookup change,the canvas is also moving along with the camera

Can anybody please help me out.


texts: I love game development books but they're so expensive!

texts:
What means do you use to get your game dev book fix? Do you pony up the big bucks for the thick books, or do you budget yourself and buy one at a time, or do you rent or limit yourself only to your library? Do you prefer to read them on your eBook reader?

How do you obtain your game development books?


texts: How can I Debug.Draw different shapes in unity?

texts:
I want draw new shapes in Sence for example I want Debug.DrawSphere can I Debug.DrawCollider?
Is possible that I Debug.DrawSphereCast


texts: Is a Masters degree in computer science beneficial over a Bachelors in the game industry?

texts:
Suppose a student (who is seeking to become a video game developer) is studying Computer Science at a state-level university, and is about to complete his or her bachelors degree.

Would the student stand a better chance to get hired as a game developer later if they proceeded to obtain their masters degree in Computer Science, or if they tried to instead obtain an internship or entry-level development position at a local software developer (not game development, but still software development)?


texts: How to access Unity Game Engine menu bar by keyboard shortcut?

texts: How to access Unity Game Engine top Menu bar by keyboard is there is any keyboard shortcut I could not find it on the internet


texts:
I Have image with a sprite and i want to change this image sprite to Texture so that I can assign it to the material And i don't want to keep multiple copies for each image as a sprite and texture.

Is there any way to change sprite to texture at run time?


texts: LibGDX Switching to fullscreen makes sprites blurry

texts:
I'm using LibGDX to develop/render my game and when I start the game in windowed mode, then switch to full screen, the sprites look blurry. Importantly(?), starting the game in full screen then switching to windowed mode doesn't have this problem.

Here's a section of a screenshot starting off windowed:

And after switching to fullscreen, the (roughly) same section of the screen:

The sprites are loaded from a TextureAtlas using LibGDX's TexturePacker. They're rendered using a normal SpriteBatch with the default settings/shaders.
These are my pack.json settings:

{
    "pot": true,
    "paddingX": 2,
    "paddingY": 2,
    "bleed": true,
    "edgePadding": true,
    "maxWidth": 4096,
    "maxHeight": 4096,
    "duplicatePadding": false,
    "filterMin": "MipMapLinearLinear",
    "filterMag": "Linear"
}

I wondered if the filterMin/Mag might be having some effect but trying different settings is giving the same results.

To switch between fullscreen and windowed, I'm using the following code:

public static void toggleFullscreen() {
    if (DisplaySettings.isGamefullscreen && Gdx.graphics.supportsDisplayModeChange()) {
        // Switch to windowed
        Gdx.graphics.setWindowedMode(DisplaySettings.windowedWidth, DisplaySettings.windowedHeight);
        DisplaySettings.isGamefullscreen = false;
    } else if (Gdx.graphics.supportsDisplayModeChange()) {
        // Switch to full screen
        Gdx.graphics.setWindowedMode(DisplaySettings.desktopWidth, DisplaySettings.desktopHeight);
        Gdx.graphics.setFullscreenMode(Gdx.graphics.getDisplayMode());
        DisplaySettings.isGamefullscreen = true;
    }
}

So in this case the game starts off windowed then toggles to fullscreen after everything has loaded/been set up.

I am using some FrameBuffers and TextureRegions to draw to, but these are disposed and recreated on a resize.

I feel like there's some problems perhaps with the mipmaps being created and used incorrectly in this case but I'm a bit stuck at this point, any help much appreciated!


texts: How do I make an object not appear grey regardless of distance?

texts:
My moon texture is on a plane 500m away and I would like to know if there is a way to keep displaying the texture:

As opposed to it turning grey as pictured here:
regardless of the distance it is from the camera. Any help is greatly appreciated,
Thanks.


texts: How to simulate a spinning helicopter rotor visual effect programatically?

texts:
I decided to display an animation that conveys to the viewer that a narrow flat surface is spinning really fast(such as an helicopter's rotor blade). Does anyone have any experience in implementing this effect and could provide an implementation?
Please remember a rotor on video looks different than it does in real life.
I need to make the rotor look like it does in real life and not on video.


texts: Scaling a GameObject for a progress bar representation

texts:
I am trying to implement a progress bar system for my game. I know that it could be done with Unity's OnGUI and scaling with width of the texture but I don't want it to be a GUI element because in my game we would have several progress bars for each specific item.

In the below image you can see two of the progress bars and they are textures mapped on to a plane.

The actual progress bar that needs to increase/ decrease in width is just a gameObject. I could just localScale and just scale it in the x direction of the gameobject but that scales in both directions. So scaling is not a solution. How do I make it work such that it I could control its width? Is there any other way I could implement this system? Or could I just use Unity's OnGUI for this purpose? Thing is this progress bars need to show up in the game on top of several gameOjects in the perspective camera view. So I am not sure if OnGUI would work for that. Any ideas?

I want something similar to what we see in games like LoL where they have health bars on top of the in game characters like in the image below


texts:
So I'm kind of new to programming and I'm trying to check collision using bounding boxes. I'm currently stuck as to how to call my bounding box within my bounding box function as shown below

 public BoundingBox BuildBoundingBox()
    {
        // Create initial variables to hold min and max xyz values for the mesh
        Vector3 meshMax = new Vector3(float.MinValue);
        Vector3 meshMin = new Vector3(float.MaxValue);
        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (ModelMeshPart part in mesh.MeshParts)
            {
                // The stride is how big, in bytes, one vertex is in the vertex buffer
                // We have to use this as we do not know the make up of the vertex
                int stride = part.VertexBuffer.VertexDeclaration.VertexStride;

                VertexPositionNormalTexture[] vertexData = new VertexPositionNormalTexture[part.NumVertices];
                part.VertexBuffer.GetData(part.VertexOffset * stride, vertexData, 0, part.NumVertices, stride);

                // Find minimum and maximum xyz values for this mesh part
                Vector3 vertPosition = new Vector3();

                for (int i = 0; i < vertexData.Length; i++)
                {
                    vertPosition = vertexData[i].Position;

                    // update our values from this vertex
                    meshMin = Vector3.Min(meshMin, vertPosition);
                    meshMax = Vector3.Max(meshMax, vertPosition);
                }
            }

            // transform by mesh bone matrix
            meshMin = Vector3.Transform(meshMin, meshTransform);
            meshMax = Vector3.Transform(meshMax, meshTransform);
        }
        // Create the bounding box
        BoundingBox box1 = new BoundingBox(meshMin, meshMax);
        return box1;

    }

I'm trying to call box1 (my bounding box) in my update method to check collision however I can't seem to call box1 as it's not in the context of my class.


texts: Shading Languages vs Materials in 3D editors

texts:
There are many 3d packages which are able to construct materials. Autodesk Maya, 3ds max, Houdini, etc.

There are languages which are able to construct materials as well, like GLSL and Cg.

How does first group correspond to the second? Are there workflows, where they are used simultaneously?

From my experience, constructing materials in 3d packages is way faster than writing code in GLSL. They also have scripting systems for more customization. Do shading languages have their own benefits?


texts: Game development for multiple Microsoft platforms

texts:
I intend to develop games for Microsoft's Windows Store, however, I'm confused between their platforms, so please clarify those questions:

Is there any technology (XNA, DirectX), so a game can be distributed to Xbox360, Windows Store, Windows Phone?
What are the differences between Xbox360 and Windows?
What is a good approach for 2D games?
Does a Windows Store game work for Windows Phone just by recompiling it?
Are the Windows Store and Windows Phone store separated?


texts: Difference between shader input element classification between D3D12 and Vulkan

texts:
I'm confused about the difference between the shader input element classifications in D3D12 and Vulkan. For example, in Vulkan I could have the following declarations:
struct vertex
{
    glm::vec3 pos;
    glm::vec3 col;
};

VkVertexInputBindingDescription input_binding_description
{
    .binding = 0,
    .stride = sizeof(vertex),
    .inputRate = VK_VERTEX_INPUT_RATE_VERTEX
};

std::array<VkVertexInputAttributeDescription, 2> input_attribute_descriptions {
    VkVertexInputAttributeDescription{
        .location = 0,
        .format = VK_FORMAT_R32G32B32_SFLOAT,
        .offset = offsetof(vertex, pos)
    },
        VkVertexInputAttributeDescription{
        .location = 1,
        .format = VK_FORMAT_R32G32B32_SFLOAT,
        .offset = offsetof(vertex, col)
    }
};

Here the input rate is specified per vertex and not per attribute. On the other hand, in D3D12, we would have
struct Vertex
{
    XMFLOAT3 pos;
    XMFLOAT3 col;
};

std::array<D3D12_INPUT_ELEMENT_DESC, 2> input_element_descs =
{
    { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,
    D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
    { "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12,
    D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }
};

And as you can see, the input rate is specified per attribute. Why is that? Is there a difference between the meaning of the input classification in D3d12 and Vulkan that I'm missing? I'm not familiar with D3D12, but at first glance, it doesn't make sense to me to have different input classifications for the attributes of a vertex.


texts: What component should hold the bool attack and vector target?

texts:
I am having trouble thinking of what component should hold the attack and target data. In the below code components are holding a redundant data which I want to eliminate.

public class PlayerComponent implements Component {
    public boolean attack = false;
    public Vector2 target = new Vector2();
}

public class PoliceComponent implements Component {
    public boolean attack = false;
    public Vector2 target = new Vector2();
}

public class CriminalComponent implements Component {
    public boolean attack = false;
    public Vector2 target = new Vector2();
}

I ended up creating an CombatComponent that holds the both attack and target, but I doubt there is more better way. The purpose is to have a weapon system the check if the player or enemy trigger attack and get its target.

private void processWeapon() {
    for (Entity weapon: weaponEntities) {
        AttachmentComponent attachment = Mapper.attachment.get(weapon);
        if(playerFamily.matches(attachment.owner)) {
            PlayerComponent player = Mapper.player.get(attachment.owner);
            CombatComponent combat = Mapper.combat.get(attachment.owner);
            if( combat.attack ) {
                WeaponComponent weaponComponent = Mapper.weapon.get(weapon);
                weaponComponent.use = true;
                weaponComponent.target.set(player.target);
            }
        }
    }
}

or the another way calling the WeaponSystem to use the owner weapon.

getEngine().getSystem(WeaponSystem.class).useWeapon(ownerEntity, targetPosition);


texts: How can I use a redundant axis of rotation to prevent gimbal-lock & calculate a position for that axis?

texts:
I have a theodolite-like device that is trying to track a point such that it's "Forward" is always facing that point.

Here is a GIF of it working as of now.

As expected, when the value of the Red Angle is near 90 or 270 it may approach a gimbal-lock situation.

How would I be able to calculate a position for the currently unused Blue axis to prevent the Red/Green axis's from aligning that way?

Main Loop:

    public void Main(string argument, UpdateType updateSource)
    {
        float pitch, yaw;
        GetOrientationTo(target, origin, out pitch, out yaw);

        UpdateSteeringVectors();
        // Update yaw to the Green rotor
        UpdateRotor(r_green_inner, yaw);
        // Update pitch to the Red rotor
        UpdateRotor(r_red_middle, pitch);

        float green = GetRotorAngle(r_green_inner);
        if (green == 0) green = 360;
        float red = GetRotorAngle(r_red_middle);
        if (red == 0) red = 360;
        float blue = GetRotorAngle(r_blue_outer);
        if (blue == 0) blue = 360;

        debugText = "Green Angle: " + green.ToString() + "\n";
        debugText += "Red Angle: " + red.ToString() + "\n";
        debugText += "Blue Angle: " + blue.ToString() + "\n";
        debug.WritePublicText(debugText);
        debugText = "";
    }

Tracking function:

    void GetOrientationTo(Vector3 Target, IMyTerminalBlock Origin, out float Pitch, out float Yaw)
    {

        // Origin point
        Vector3 OV = Origin.GetPosition();
        // Thrusters are two blocks long so we need to make it shorter
        OV = Vector3.Subtract(OV, Origin.WorldMatrix.Forward * 1.25);
        // Target point
        Vector3 TV = Vector3.Subtract(OV, Target);
        // Get reference directional vectors
        Vector3 FV = OV + Origin.WorldMatrix.Forward;
        Vector3 UV = OV + Origin.WorldMatrix.Up;
        Vector3 RV = OV + Origin.WorldMatrix.Right;

        double TVOV = (OV - TV).Length();  // Get magnitudes of vectors

        double TVFV = (FV - TV).Length();
        double TVUV = (UV - TV).Length();
        double TVRV = (RV - TV).Length();

        double OVFV = (FV - OV).Length();
        double OVUV = (UV - OV).Length();
        double OVRV = (RV - OV).Length();

        double ThetaP = Math.Acos((TVUV * TVUV - OVUV * OVUV - TVOV * TVOV) / (-2 * OVUV * TVOV));  //Use law of cosines to determine angles.
        double ThetaY = Math.Acos((TVRV * TVRV - OVRV * OVRV - TVOV * TVOV) / (-2 * OVRV * TVOV));

        double RPitch = 90 - (ThetaP * 180 / Math.PI);  //Convert from radians to degrees.
        double RYaw = 90 - (ThetaY * 180 / Math.PI);

        if (TVOV < TVFV) RPitch = 180 - RPitch;  //Normalize angles to -180 to 180 degrees.
        if (RPitch > 180) RPitch = -1 * (360 - RPitch);

        if (TVOV < TVFV) RYaw = 180 - RYaw;
        if (RYaw > 180) RYaw = -1 * (360 - RYaw);

        Pitch = (float)RPitch;
        Yaw = (float)RYaw;
    }


texts: How to make GameObject copy position of other GameObject but react to physics perfectly?

texts:
First GO moves by transform.translate (necessary).
Second GO needs to move by physics.
If I do rb.MovePosition on the 2nd GO like:
 private void FixedUpdate()
    {
        rb.MovePosition(targetTransform.position);
        rb.MoveRotation(targetTransform.rotation);
    }

then it stutters and blinks around crazily, even if I turn on Interpolate.
If I do
 rb.AddForce(targetTransform.transform.position - this.transform.position, ForceMode.Acceleration);

it moves smoothly and does interact properly physics-wise BUT orbits around the original GO's position rather than perfectly copying it.
If I do:
// Calculate your desired position however you like.
    Vector3 desiredPosition = targetTransform.position;

    // What velocity gets us there in one timestep?
    Vector3 desiredVelocity = (desiredPosition - transform.position) / Time.deltaTime;

    // Apply a sufficient impulse to hit reach that velocity.
    rb.AddForce(desiredVelocity - rb.velocity, ForceMode.VelocityChange);

then it DOES copy the original GO's position but then annoyingly clips right through other rigidbodies as if moving by transform.translate.
What is the perfect secret sauce to making a GO copy another GO's position, but respond to Physics properly? Namely, it needs to actually be stopped when colliding with a Rigidbody that has frozen position+rotation.


texts:
Good day all.

I have a 3d object with a random rotation.
I can express that object's rotation both through a quaternion or through an euler rotation.

Then I have a vector3 normal that I get from a raycast.

What I need, is to apply a rotation that will make a chosen axis of the 3d object, coincide with the normal vector3 from above.

The closest I got to the solution is this (trying to align the 'up' vector):

Quaternion q;
Vector3 a = Vector3.Cross(3dobject.up, varnormal);
q.x = a.x;
q.y = a.y;
q.z = a.z;
q.w = Mathf.Sqrt((3dobject.up.sqrMagnitude) * (varnormal.sqrMagnitude))
       + Vector3.Dot(3dobject.up, varnormal);

3dobject.rotation = q * 3dobject.rotation;

But when the normal is negative on the y (e.g. 0,-1,0), the object aligns with its y pointing up instead.

What's wrong with the formula? Is there a better solution maybe?

Thanks in advance.


texts: I have built an importer that retrieves necessary vertex data however I wish to be able to read texture file directories. How do I retrieve the texture file name?


texts: Unity 2D: Destroy object with dynamic collider after exiting object with static collider

texts:
I'm using the Unity5 game engine and am programming a 2D shooter in bird's eye view.

I have a static Box Collider 2D which covers the entire game area.

It has "Is Trigger" checked and contains a very simple script which should destroy every object that exits it.

 using UnityEngine;
 using System.Collections;

 public class DestroyByBoundary : MonoBehaviour {
     void OnTriggerExit(Collider other) {
         Debug.Log ("OnTriggerExit");
         Destroy (other.gameObject);
     }
 }

The player character shoots bullets which have a dynamic Circle Collider 2D.

However, the bullets are never destroyed when they leave the game area and just fly on indefinitely. The debug statement never gets executed either, of course. I have tried the same thing with OnTriggerEnter, which yields the same result.

If any more information should be needed, I'll be happy to provide it.


texts:
I am working on a game inside Flash with ActionScript 3.

I have a horse game object with different animations for Walk, Run and so on. I have never worked with different animation types with Flash timeline. I want to have all these animations setup on the timeline at different key frames with different labels for each animation.

After setting this up, how do I select a specific animation?

Currently what I have setup inside Flash does not seem to work. When the walk animation is about to end, I want it to loop and start from the beginning. Currently what it does is it plays all the animations set on the timeline and not just the walk animation.

horseOne.gotoAndPlay("startwalk");

if(horseOne.currentLabel == "endwalk"){
    horseOne.gotoAndPlay("startwalk");
}

Please refer to the image of my fla timeline.


texts: Dialogue Audio: Forming sentences using different recordings

texts:
I am working on a game where the exact dialogue to be spoken out depends on context. The most common use case is for scoring - The game keeps player score and I want the game to tell the player her current score using audio. For example, audio can be - "You've killed 10 enemies", or "You're score just crossed 100!". In both these sentences, the numbers 10 and 100 depend on the current game context.

What I would want to do is record the sentence "You've killed .... enemies", and then also record all the numbers separately, and then form a complete sentence when needed. Are there any solutions which can do this in a way that the dialogue sounds fairly natural?


texts: How does XNA's KeyboardState represent all keyboards?

texts:
I already understand how to work with Keyboard and KeyboardState, but when debugging I happened to take a look at the KeyboardState's non-public members via the VS debugger. I expected to see a large list of values, but instead, only saw 8 uints at a static level, and another 8 uints per instance:

Non-Public members  (static)
    stateMask0  uint    976757505
    stateMask1  uint    67108863
    stateMask2  uint    3221225470
    stateMask3  uint    4294967295
    stateMask4  uint    196863
    stateMask5  uint    4244635647
    stateMask6  uint    4160752641
    stateMask7  uint    1876688932

Non-Public members  (instance)
    currentState0   uint    0
    currentState1   uint    0
    currentState2   uint    0
    currentState3   uint    1048576
    currentState4   uint    0
    currentState5   uint    0
    currentState6   uint    0
    currentState7   uint    0

There are 32 bits per uint, so having 8 of them essentially acts as a field of 256 boolean values, which loosely corresponds with the Keys enum type, so I assume that the static values act as a way to test which buttons are present on a device. However, XNA supports up to 4 keyboards, so I'm not sure how it both translates this to a button state, nor how it can differentiate between different keyboards in this way.