texts:
I'm developing a 2D game using MonoGame. I've got a square on the screen I can move around. The problem is that about once a second, the square jumps a bit. Using a frame counter I found here I've concluded that my FPS drops from 59.9988 to either 59.3988 or 59.6988. It's skipping frames.

I've tried googling and searching forums for hours but can't find a solution. I've commented out everything in the Draw method of the Game class except for the frame counter and it still happens. I even tried creating an entirely new MonoGame project with nothing in it except the frame counter and still I would get the frame skips.

Setting IsFixedTimeStep = true does not fix the issue. I do get higher frame rate, but also not as high as I would expect (not higher than ~100). I've looked at the diagnostic tools and there is no garbage collection going on (no yellow triangles).

I am completely at a loss. If anyone has any insights to offer, it would be much appreciated.


texts: 8, 16, 32 bits consoles... what does it mean?

texts:
A number of bits is often used to qualify some video game consoles: Master System and NES/Famicon are 8 bits systems, Megadrive/Genesis is a 16 bits system, etc.
What do this number actually represent for those different hardwares?


texts: Limit Color Pallete Using Shader (Unity)

texts:
Basically, what I want to do is take a primary input image texture (which is a render texture in-game) and a secondary pallete texture (contains X number of colors, and is X by 1 pixels in size). What I want to do is replace all of the pixels in the image with the most similar color in the color pallete texture. I made a stab at producing the effect, but at the moment, it only seems to return the first color in the pallete. Below is my (nonfunctional) version. I'm new to shaders, so sorry for the potentially very sloppy/basic shader code.

Shader "Custom/Limiter" {
Properties
{
    _MainTex ("Texture", 2D) = "white" {}
    _PalTex ("Pallete", 2D) = "white" {}
}
SubShader
{
    // No culling or depth
    Cull Off ZWrite Off ZTest Always

    Pass
    {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag

        #include "UnityCG.cginc"

        struct appdata
        {
            float4 vertex : POSITION;
            float2 uv : TEXCOORD0;
        };

        struct v2f
        {
            float2 uv : TEXCOORD0;
            float4 vertex : SV_POSITION;
        };

        v2f vert (appdata v)
        {
            v2f o;
            o.vertex = UnityObjectToClipPos(v.vertex);
            o.uv = v.uv;
            return o;
        }

        sampler2D _MainTex;
        sampler2D _PalTex;

        fixed4 frag (v2f i) : SV_Target
        {
            float4 baseCol = tex2D(_MainTex, i.uv);
            float4 palCol = tex2D(_PalTex, 0);
            float palDiff = 1000;

            for (int p = 0; p < 37; p++) {
                float baseColDiff = abs(tex2D(_PalTex, p).r - baseCol.r) + abs(tex2D(_PalTex, p).g - baseCol.g) + abs(tex2D(_PalTex, p).b - baseCol.b);
                palDiff = min(palDiff, baseColDiff);
                palCol = (abs(palDiff - baseColDiff) < 0.001) ? tex2D(_PalTex, p) : palCol;
            }

            return palCol;
        }
        ENDCG
    }
}
}

Any help would be greatly appreciated! I feel like it's a relatively simple problem to solve, but I couldn't find any examples of existing shaders like it, or any resources describing it.

Edit: This shader works... sort of. It has been picking the nearest color, but it has only been picking two yellow colors out of the pallete. I tried removing those colors, and it then chose to use only an orange. I don't know if this will help anyone, but I thought it was at least mildly interesting.


texts: RevoluteJoint Stop Rotating when Some Physics Body Collide in Andengine + Box2d?

texts:
I am making a Game from andengine + box2d in Which i am using RevoluteJoint in that case i am facing some problem that when physics body or Sprite Collide with this Revolute joint body then Revolute body stop rotating then after some time it start rotating
I am using below code for this :

     this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(movingFace, movingBody, true, true));

         final RevoluteJointDef revoluteJointDef = new RevoluteJointDef();
         revoluteJointDef.initialize(anchorBody, movingBody, anchorBody.getWorldCenter());
         revoluteJointDef.enableMotor = true;
         revoluteJointDef.motorSpeed = 100;
         revoluteJointDef.maxMotorTorque = 200;

         this.mPhysicsWorld.createJoint(revoluteJointDef);

EDIT Here is a screenshot:


texts:
How can I implement a blizzard/snowstorm effect in a 2D platformer? I have a particle system for snow particles, but I need some kind of windblown texture similar to this as well: How do I create this windblown snow effect?

Could I generate a windblown texture using perlin noise in Photoshop or something and sample it similar to the answer in this question about fog? How to create a 2D fog shader?

In that case it would have to be more dense than the fog texture, so holes don't appear that you can peak through when sampling the texture.

BTW I have a wind speed variable for my snow particles, could that be used for the windblown texture as well somehow?


texts: Determining which point is further along a direction vector

texts:
I am attempting to write a frustum culling algorithm simply by testing axis aligned boxes against a plane, while researching this i came across an article here:
enter link description here
The trouble i am having is determining which points are furthest along the normal of the plane as illustrated here:

For each box i need to determine which corner or of the box is furthest along the direction normal of the plane. The pseudo-code on the website has no meaning to me as my box class is structured differently, any help would be appreciated.


texts:
I have free camera that move and rotate around the level. In this script if tb = true, I want my camera to rotate at target. Camera will show my character not rotate at character direction. image

public Transform avatar1; // character
public Camera cam;
public bool tb;

void Start()
{
    tb = false;
}

void Update()
{

    if (tb == true)
    {
        StartCoroutine(bu1());
    }

}

IEnumerator bu1()
{
    cam.transform.position = Vector3.Lerp(cam.transform.position, new Vector3(avatar1.transform.position.x + 6, 10, avatar1.transform.position.z + 7), 0.1f);
    cam.transform.rotation = Quaternion.Lerp(cam.transform.rotation, avatar1.transform.rotation, 0.4f); // here is my problem
    yield return new WaitForSeconds(2);
    tb = false;

}


texts: What is the difference between these options when saving an image as a PNG in Photoshop for my game?

texts:
I'm creating sprites and tilemaps for 2D games. I might just use Unity.

What is the impact of choosing different options when saving as a .png?


texts: What's the most efficient way to find the position of a point in relation to corners of a rectangle despite rectangle's scale

texts:
I am struggling to achieve the following with C# (in Unity). I need to find the position of the points that lay at a given distance (let's say 1m) from the corners of a rectangle, in a way that the segment between these points and the given rectangle corners form 135 degrees with the corresponding sides the of rectangle - no matter where the rectangle goes, what is its rotation or what is its size. Like the following:

So, using the picture above as reference, it means that the red dotted line has always the same length and divides the angle ABC in the middle. So, the angle of the line with AB is 135 and with BC is also 135.

One of the ways to achieve that is the following code:

    Vector3 dotpos = rectangle.transform.TransformPoint(rectangle.transform.localPosition.x+1.5F,0,rectangle.transform.localPosition.z+1.5F);
    bluedot.transform.position = dotpos ;

The problem is that in such solution the distance between the blue dot and the corner of the rectangle is not independent of the scale of the rectangle. It means, the greater the rectangle, the blue dot goes more distant from the corner.

Can anybody tell what is the most efficient way to achieve what I want, i.e. so the position of the blue dot is always at the same distance from the corner no matter the scale, position or rotation of the rectangle?

PS: blue dot is not an object that can be made child of the rectangle.


texts: Should I always be checking every neighbor when building voxel meshes?

texts:
I've been playing around with Unity3d, seeing if I can make a voxel-based engine out of it (a la Castle Story, or Minecraft).

I've dynamically built a mesh from a volume of cubes, and now I'm looking into reducing the number of vertices built into each mesh, as right now, I'm "rendering" vertices and triangles for cubes that are fully hidden within the larger voxel volume.

The simple solution is to check each of the 6 directions for each cube, and only add the face to the mesh if the neighboring voxel in that direction is "empty". Parsing a voxel volume is BigO(N^3), and checking the 6 neighbors keeps it BigO(7*N^3)->BigO(N^3).

The one thing this results in is a lot of redundant calls, as the same voxel will be polled up to 7 times, just to build the mesh.

My question, then, is:

Is there a way to parse a cubic volume (and find which faces have neighbors) with fewer redundant calls? And perhaps more importantly, does it matter (as BigO complexity is the same in both cases)?


texts:
XNA seems to be ignoring my Z coordinate. There is no form of Z-culling at all it seems. How come? I am doing an orthographic projection, and clearing the depth stencil buffer for every draw-call.

My elements rendered are quads with textures, through instancing. These elements have 1 difference in the Z-coordinate in order to eachother, based on theri Z-index.


texts: Producing a smooth mesh from density cloud and marching cubes

texts:
Based on my results from this question I decided to build myself a 3D noise map containing float values in place of my existing boolean point values. The effect I'm trying to produce is something like this, rather than typical rolling hills; which should explain the "missing cubes" in the image below.

If I render my density map in normal "minecraft mode" (1 block per point in the density map) varying the size of the cube based on the value in my density map (floats in the range 0 to 1) I get something like this:

I'm now happy that I can produce a density map for the marching cubes algorithm (which will need a little tweaking) but for some reason when I run it through my implementation it's not producing what I expect.

My problem is that I'm getting something like the first image in this answer to my previous question, when I want to achieve the effect in the second image.

Upon further investigation I can't see how marching cubes does the "move vertex along the edge" type logic (i.e. the difference between the two images on my previous link). I see that it does do some interpolation, but I'm not convinced I have the correct understanding of what I think it should do, because the code in question appears to give the same result regardless of whether I use boolean or float values.

I took the code from here which is a C# implementation of marching cubes, but instead of using the MarchingCubesPrimitive I modified it to accept an object of type IDrawable, containing lists for the various collections (vertices, normals, UVs, indices), the logic was otherwise untouched.

My understanding is that given a very low isovalue the accuracy level of the surface being rendered should increase, so in short "less 45 degree slows more rolling hills" type mesh output. However this isn't what I'm seeing.

Have I missed something or is the implementation flawed and need to be fixed?

EDIT:

A little more detail on what I am seeing when I "marching cube" the data.

Ok so firstly, ignore the fact that the meshes created by the chunks don't "connect" (i'll probably raise another question about this later).

Then look at the shaping of the island, it's too ... square, from the voxels rendered as boxes you get the impression there's a clean soft gradual hill and yet from the image there are sharp falling edges even in the most central areas where the gradient in the first image looks the most smooth.

The data is "regenerated" each time I run this so no 2 islands come out the same, and it's purely random so not based on noise, but still, how can it look so smooth in 1 image and so not smooth in the other?


texts: Looking for feedback on design pattern for simple 2D environment

texts:
I'm working in iOS.

I am trying to make a very simple 2D environment where there are some basic shapes you can drag around with your finger. These shapes should interact in various ways when dropped on each other, or when single-tapped versus double-tapped, etc.

I don't know the name for the design pattern I'm thinking of. Basically, you have a bunch of arrays named after attributes, such as "double-tappable" or "draggable" or "stackable". You assign these attributes to the shapes by putting the shapes in the arrays.

So, if there's a double-tap event, the code gets the location of it, then iterates through the "double-tappable" array to see if any of its members are in that location. And so on: every interactive event causes a scan through the appropriate array or arrays.

It seems like that should work, but I'm wondering if there's a better pattern for the purpose.


texts:
I'm making a card-playing game, similar to Magic Workstation. I've been looking into several options for networking. I have a working LAN version with the build in Unity networking, as well as Photon Cloud. Though I was now looking for a more decentralized way of doing multiplayer on the internet. It would be very very cool if there were no servers involved in finding other people. I would still let players host their own game-rooms others can join.

I Googled around for this, and everything I found was at least several years old. So I was wondering if anything new has popped up since then. I've seen several decentralized chat programs and even voice/video chat without any servers. But nothing for video games yet.

I did find some problems with this kind of networking. Mainly the lack of anti-cheat, but in my case the players check the moves themselves so this shouldn't be a problem. Other than that it's probably a bit slower, but card games are generally not very high-paced :P

Lastly, I'm making it in Unity using c#. I'll probably be running it in the webplayer (and later WebGL). So I'm mostly looking for c# library, or javascript. But any promising projects that do this are welcome.

Thanks a lot!


texts:
For a section of my game, instead of having a perspective projection, i would like to display an isometric view of an object.

So i don't want things to appear smaller if in a distance, etc.

Basically a proper isometric image.

Is there any way to do this in XNA?


texts: Image speeds up while moving and or rotating instead of constant speed

texts:
I'm having a problem with rotating/moving an image. I've set one of my images to rotate on it's z-axis buy updating the angle, but when I run my game, the image starts slowly starts to rotate from a stationary position as if to build up momentum. Once it reaches a certain speed, it begins to slow down to almost a stop, then repeats the process over. Furthermore, when it starts to rotate, it's rotating clockwise. But halfway before it stops, it's now rotating counter-clockwise.

If I were to only update it's x or y position or both, the image will move slow, then speed up to the desired speed, instead of moving at the desired speed at start.

Lastly, if I were to rotate AND move the image, the image shakes erratically while rotating. My suspicion is that I'm calculating something wrong.

Within Shader

uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;
....
gl_Position = projection * view * model * vec4(position, 1.0);

init()

        projection = glm::ortho(LEFT, RIGHT, BOTTOM, TOP, ORTHO_NEAR, ORTHO_FAR);

        mSprite.init("res/texture/foo.png", 1.0f);
        mSprite.setPosition(mPosition);
        mSprite.setRotation(rot, glm::vec3(0, 0, 1));

        glm::vec3 pos(1.5, 0.5, 0.0);
        mSprite2.init("res/texture/bar.png", 1.0f);
        mSprite2.setPosition(pos);
        mSprite2.setRotation(0.0f, glm::vec3(0, 1, 0));

update()

        mPosition.x += 0.000005f;
        mPosition.y += 0.000005f;
        mSprite.setPosition(mPosition);

        rot += 0.0005f;
        mSprite.setRotation(rot, glm::vec3(0, 0, 1));

render()

        mShader->start();
        mShader->LoadProjectionMatrix(projection);
        mSprite.draw(mShader, view);
        mSprite2.draw(mShader, view);
        mShader->stop();

draw(Shader* shader, glm::mat4& view) (mSprite)

        shader->LoadViewMatrix(view);
        shader->LoadTransformMatrix(mModel);
        shader->connectTexture(mTexture.id);
        // Draw image...

    void setPosition(glm::vec3 position)
    {
        mModel = glm::translate(mModel, position);
    }

    void setRotation(GLfloat angle, glm::vec3 axis)
    {
        mModel = glm::rotate(mModel, angle, axis);
    }


texts: How to compute the 2D equations of 3D circular arcs?

texts:
I'd like to obtain these equations for the ellipses produced by the perspective projections of (3-dimensionally transformed) circles.

This is useful for rendering in 2D contexts which provide curve primitives. I'm using HTML5's canvas, so I get Beziers, arcs, and quadratic curves.

See here:

The projection of a sphere outside of the plane of projection is an ellipse because the view is a cone (silhouette of a sphere is a circle).

However if I want to draw my sphere using circular wireframes, that projection-cone is no longer a circular cone. So it's not your traditional conic section anymore.

How to deal with this?


texts: Game Maker Studio: How to make Player Circular Movement

texts: I want to make a player move in circular but not that he move automatic but manual. Similar like in the game Zero Refelx.


texts: Gunfire Sound Gets Cut Off When I Release the Aim Button. Help?

texts:
So for my game you have to hold down right mouse click to aim and then simultaneously click the left mouse click to shoot. When the gun is fired, I'd like the gunfire sound to play. Currently, I have this working, but I have a problem. When I let go of the aim button, the gunfire sound immediately stops playing (if it hasn't already played through).

I understand this is happening because of the placement of my PlayShootSound method call, but what I can't figure out is where to put it so that I don't have this problem.

Any pointers/ideas?

public class Weapon : MonoBehaviour {

 public float fireRate = 0;
 public float damage = 10;
 public LayerMask whatToHit;

 public Transform BulletTrailPrefab;
 public Transform MuzzleFlashPrefab;

 float timeToFire = 0;
 float timeToSpawnEffect = 0;
 public float effectSpawnRate = 10;
 Transform firePoint;

 public AudioClip shootSound;
 private AudioSource gunFire;

 bool isShooting = false;

 // Use this for initialization
 void Awake () {
     gunFire = GetComponent<AudioSource>();

     firePoint = transform.Find("FirePoint");
     if (firePoint == null)
     {
         Debug.LogError("No fire point...Please make an empty object named FirePoint and attach to end of gun. :)");
     }
 }
 void Update () {
     CheckIfShooting();
 }

 void CheckIfShooting()
 {
     if (Input.GetButton("Fire2")) // Holding right click
     {
         if (fireRate == 0)
         {
             print("fire rate is 0");
             if (Input.GetButtonDown("Fire1")) // Left click while holding right click
             {
                 Shoot();
                 PlayShootSound();
             }
         }
         else
         {
             if (Input.GetButton("Fire1") && Time.time > timeToFire) // For automatic guns
             {
                 timeToFire = Time.time + 1 / fireRate;
                 Shoot();
                 PlayShootSound();
             }
         }
     }
 }

 void Shoot()
 {
     Vector2 mousePosition = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
     Vector2 firePointPosition = new Vector2(firePoint.position.x, firePoint.position.y);
     RaycastHit2D hit = Physics2D.Raycast(firePointPosition, mousePosition - firePointPosition, 100f, whatToHit);

     if (Time.time >= timeToSpawnEffect)
     {
         Effect();
         timeToSpawnEffect = Time.time + 1 / effectSpawnRate;
     }
     // Debug.DrawLine(firePointPosition, (mousePosition - firePointPosition) * 100, Color.cyan);

     if (hit.collider != null)
     {
         // Debug.DrawLine(firePointPosition, hit.point, Color.red);
         Debug.Log("We hit " + hit.collider.name + " and did " + damage + " damage.");
     }
 }

 void PlayShootSound()
 {
     gunFire.PlayOneShot(shootSound, 1f);
 }

 void Effect()
 {
     Instantiate(BulletTrailPrefab, firePoint.position, firePoint.rotation); // Fire Bullet

     Transform muzzleFlashClone = Instantiate(MuzzleFlashPrefab, firePoint.position, firePoint.rotation) as Transform;
     muzzleFlashClone.parent = firePoint;
     float size = UnityEngine.Random.Range(6f, 9f); // Randomize size of muzzle flash
     muzzleFlashClone.localScale = new Vector3(size, size, size);
     Destroy(muzzleFlashClone.gameObject, 0.05f);
 }


texts:
This is a question about the sebcrozet/kiss3d graphics engine for the Rust programming language. I have managed to create a mesh using group.add_mesh(). Now I want to colour my mesh with a specified colour for each vertex (or face). Does anyone know how I do this?

One possible approach seems to be to define a RgbImage with all my different colours somewhere in the image, turn that into a DynamicImage, turn that into a Texture, somehow associate the texture with the mesh, set up a UV map, and set the UV location for each vertex to map to the relevant colour.

The documentation does not go into enough detail or give a specific example. Does anyone have any example code that works?


texts:
Say I have a 2D surface defined with the use of bitmap.

I want to use this bitmap for collision detection (white color is where object can move freely, with black I mark the walls).

How can I numerically calculate the surface normal vector at given point?

For example, in the attached picture, how can I calculate the surface normal vector for the red point?


texts: What is a convincing Berserker enemy AI finite state machine for a Roguelike

texts:
I'm looking for a way to create a convincing Berserker enemy in a Roguelike I've been creating for some time. You may assume a game like NetHack for this when considering what kinds of actions can be taken and text messages that can be alerted.

I ask this for two reasons:

I've been trying to solve this problem for over a year and have failed. Examples to follow.
I see a general lack of examples on this SE that show what a mapping of an entity's states, in total, looks like. It would be helpful to the community to have such an example.

What I need:

When I say Berserker I mean an enemy that can swing into a blind rage and attack other entities that it is in conflict with with violence and bloodlust. Not simply switching to attacking targets randomly, as is done in many RPGs. To this end, feel free to assume the addition of any status effects or buffs you wish. Just make sure you detail the pertinent information for those states.

A berserk entity needs to express his rage in a way that isn't simply a status change with some strength increases. This is a very shallow solution to the problem. The entity doesn't end up feeling like a Berserker at all.

What I've Tried:

I've tried 3 different ideas over the last year. And none of them satisfy. A solution to the problem could be all new, or a 'fix' for one of these. I am mainly including them to get the juices flowing.

The first thing I tried was a simple Berserk state that increased the strength of the entity, randomized its target (from list of enemies), had him shout obscenities, so on. Once in this state, the enemy would remain in it until death.
The next thing I attempted was really a modification of the above. The enemy felt very flat, and there was no way to calm him or knock him out of his rage which seemed unrealistic. I added the ability to calm (with a spell and other effects) and also added a condition that would return the enemy to a normal state, from which he could transition to others such as fleeing. This created more depth, but made the Berserker state seem even more shallow and less destructive.
From here I scrapped it all and aimed for something more emergent. Essentially a buff that the enemy could cast on itself based on a transition state. Once cast, this would change the enemies behavior (for targeting) and increase their damage while randomly issuing insults from the enemy. Then, he could enter any other states and stay enraged. So he might flee, but still taunt. He might heal, but still be enraged and deal lots of damage. This is better, but the underlying issue still remains. He doesn't really seem berserked, just pissed. Mainly because you typically encounter the enemy alone, and not with other enemies the berserker doesn't like, so the randomization aspect is down played.

How else can I make the guy seem Berserked, and not just pissed/foul-mouthed?

I realize this is a borderline list question. So I impose these requirements: It must be a very detailed complete answer that shows all the states and conditions for transitioning. And it must be more than a guess. You should test this in your own roguelike, or it should otherwise be obvious why this is a probable 'best' solution at getting the idea of Berserk status across.

I also won't take offense if this is closed. I realized it dances the edge.


texts: Raycasting to AddForceAtPosition goes to the wrong direction

texts:
I'm trying to get my coin object's Rigidbody to move whichever way it was swiped on by the user through RayCast

void Awake()
{
    coinRigidBody = coin.GetComponent<Rigidbody>();
}

void Update()
{

    foreach (Touch touch in Input.touches)
    {
        if (touch.phase == TouchPhase.Began)
        {
            firstTouchPos = new Vector3(touch.position.x, touch.position.y, Camera.main.nearClipPlane);
        }
        if (touch.phase == TouchPhase.Moved)
        {

            lastTouchPos = new Vector3(touch.position.x, touch.position.y, Camera.main.farClipPlane);
        }

        if (touch.phase == TouchPhase.Ended)
        {

            Vector3 firstTouchWorldPos = Camera.main.ScreenToWorldPoint(firstTouchPos);
            Vector3 lastTouchWorldPos = Camera.main.ScreenToWorldPoint(lastTouchPos);
            Vector3 diffWorldPos = lastTouchWorldPos - firstTouchWorldPos;
            direction3D = diffWorldPos.normalized;
            power = diffWorldPos.magnitude * (force / Time.deltaTime);

            Ray firstTouchRay = Camera.main.ScreenPointToRay(firstTouchPos);
            Ray lastTouchRay = Camera.main.ScreenPointToRay(lastTouchPos);

            RaycastHit hit;
            Debug.DrawRay(firstTouchRay.origin, lastTouchRay.direction - firstTouchRay.direction, Color.red, 50.0f);

            if (Physics.Raycast(firstTouchRay.origin, lastTouchRay.direction * 100, out hit))
            {
                Vector3 hitLocation = hit.point;
                if (hit.collider.tag == "Coin")
                {

                    projectedVector = Vector3.ProjectOnPlane(direction3D, plane.normal);
                    coinRigidBody.AddForceAtPosition(projectedVector * power, hitLocation * 5);
                    throwCoinObject.throwWithForce(power, hitLocation, direction3D);
                }
            }
        }
    }
}

The Code is working but my only problem is that it goes only in a certain direction? And it seems that direction is manipulated by how the camera is facing the objects.
I just want it to hit the first touch origin then move to the direction the swipe was made.

Help would be really appreciated


texts: Check if .dds texture is gamma-corrected

texts: How can I check if .dds texture is gamma-corrected? It seems to be gamma-corrected since after manual gamma correction in fragment shader image is too bright. But I wanted to be sure.


texts: What is a better abstraction layer for D3D9 and OpenGL vertex data management?

texts:
My rendering code has always been OpenGL. I now need to support a platform that does not have OpenGL, so I have to add an abstraction layer that wraps OpenGL and Direct3D 9. I will support Direct3D 11 later.

TL;DR: the differences between OpenGL and Direct3D cause redundancy for the programmer, and the data layout feels flaky.

For now, my API works a bit like this. This is how a shader is created:

Shader *shader = Shader::Create(
    " ... GLSL vertex shader ... ", " ... GLSL pixel shader ... ",
    " ... HLSL vertex shader ... ", " ... HLSL pixel shader ... ");
ShaderAttrib a1 = shader->GetAttribLocation("Point", VertexUsage::Position, 0);
ShaderAttrib a2 = shader->GetAttribLocation("TexCoord", VertexUsage::TexCoord, 0);
ShaderAttrib a3 = shader->GetAttribLocation("Data", VertexUsage::TexCoord, 1);
ShaderUniform u1 = shader->GetUniformLocation("WorldMatrix");
ShaderUniform u2 = shader->GetUniformLocation("Zoom");

There is already a problem here: once a Direct3D shader is compiled, there is no way to query an input attribute by its name; apparently only the semantics stay meaningful. This is why GetAttribLocation has these extra arguments, which get hidden in ShaderAttrib.

Now this is how I create a vertex declaration and two vertex buffers:

VertexDeclaration *decl = VertexDeclaration::Create(
        VertexStream<vec3,vec2>(VertexUsage::Position, 0,
                                VertexUsage::TexCoord, 0),
        VertexStream<vec4>(VertexUsage::TexCoord, 1));

VertexBuffer *vb1 = new VertexBuffer(NUM * (sizeof(vec3) + sizeof(vec2));
VertexBuffer *vb2 = new VertexBuffer(NUM * sizeof(vec4));

Another problem: the information VertexUsage::Position, 0 is totally useless to the OpenGL/GLSL backend because it does not care about semantics.

Once the vertex buffers have been filled with or pointed at data, this is the rendering code:

shader->Bind();
shader->SetUniform(u1, GetWorldMatrix());
shader->SetUniform(u2, blah);
decl->Bind();
decl->SetStream(vb1, a1, a2);
decl->SetStream(vb2, a3);
decl->DrawPrimitives(VertexPrimitive::Triangle, NUM / 3);
decl->Unbind();
shader->Unbind();

You see that decl is a bit more than just a D3D-like vertex declaration, it kinda takes care of rendering as well. Does this make sense at all? What would be a cleaner design? Or a good source of inspiration?


texts:
So my problem is this:

I have a block, which is used as a "pointer block" to show where a block will be spawned. It will be green if it isn't colliding anyone, meaning you can spawn a block. It gets red when it's colliding with something.

The pointer block is a trigger.

OnTriggerEnter gets called when the collider touches another collider. I want to know when another collider is in my pointer block, not when something is just on the edge of the colldier.

https://www.youtube.com/watch?v=0yNqSJ3yAxA&feature=youtu.be


texts: Which pathfinding algorithm should I use for multiple enemies and tower placement?

texts:
I am new to game development and I am developing my first "Tower Defense"-type game.

I need a pathfinding algorithm to place my towers and to move enemies.

For tower placement case: I want the algorithm to run from entry to exit so that if it passes, the user can place tower and if fails user can't.
For the enemy case: it should help multiple enemies to find their shortest path by running it for each enemy's current position to exit.

Searching about path finding I have found some algorithms like Floyd–Warshall, A*, Breadth First, Dijkstra's and some others. Some answers give priority to Floyd's over it for path finding with multiple enemies. So what do you suggest that I use for my case?

My grid size is 17x23 and my game would have multiple entry and exit points in future.
I am using the Unity game engine and scripting in C#.


texts: How can I set the remaining distance of the nav agent?

texts:
I have an issue with the nav agent in my game. That I am using the remaining distance to determine the next state of the AI.

When the navagent is first given a destination it uses the previous distance until it is next updated.

So my plan is to find the memory of the remaining distance and alter it when I set the destination. Is that possible or is there a better way?


texts: Where can I find real-world map data for a game?

texts:
I want to build a game with a concept similar to Ingress, where the game map is overlaid on a real one.

Where can I find map data for an app like that? How (generally) do I integrate my own game objects into that map? Game objects need to move in real time, so having them as static markers on the map isn't sufficient.

I thought I could use Google Maps but as far as I can tell it would be impossible to create my own graphical style (like Ingress has done) with the official API provided by Google.


texts: Android device - C++ OpenGL 2: eglCreateWindowSurface invalid

texts:
I am trying to debug and run OGLES on Native C++ in my Android device in order to implement a native 3D game for mobile smart phones. The point is that I got an error and see no reason for that. Here is the line from the code that the debugger complains:

    mSurface = eglCreateWindowSurface(mDisplay,
                                      lConfig, mApplication->window, NULL);

And this is the error message:

    Invalid arguments ' Candidates are:
        void * eglCreateWindowSurface(void *, void *,
                                      unsigned long int, const int *) '

--x--

Here is the declaration:

    android_app* mApplication;

    EGLDisplay mDisplay;
    EGLint lFormat, lNumConfigs, lErrorResult;
    EGLConfig lConfig;
    // Defines display requirements. 16bits mode here.
    const EGLint lAttributes[] = {
        EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
        EGL_BLUE_SIZE, 5, EGL_GREEN_SIZE, 6, EGL_RED_SIZE, 5,
        EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RENDER_BUFFER, EGL_BACK_BUFFER,
        EGL_NONE
    };
    // Retrieves a display connection and initializes it.
    packt_Log_debug("Connecting to the display.");
    mDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    if (mDisplay == EGL_NO_DISPLAY) goto ERROR;
    if (!eglInitialize(mDisplay, NULL, NULL)) goto ERROR;
    // Selects the first OpenGL configuration found.
    packt_Log_debug("Selecting a display config.");
    if(!eglChooseConfig(mDisplay, lAttributes, &lConfig, 1,
        &lNumConfigs) || (lNumConfigs <= 0)) goto ERROR;
    // Reconfigures the Android window with the EGL format.
    packt_Log_debug("Configuring window format.");
    if (!eglGetConfigAttrib(mDisplay, lConfig,
        EGL_NATIVE_VISUAL_ID, &lFormat)) goto ERROR;
    ANativeWindow_setBuffersGeometry(mApplication->window, 0, 0, lFormat);
    // Creates the display surface.
    packt_Log_debug("Initializing the display.");
    mSurface = eglCreateWindowSurface(mDisplay, lConfig, mApplication->window, NULL);

--x--

Hope someone here can shed some light on it.


texts: Calculate the Intersection of Two Volumes

texts:
If you've ever played The Swapper, you'll have a good idea of what I'm asking about.

I need to check for, and isolate, areas of a rectangle that may intersect with either a circle or another rectangle. These selected areas will receive special properties, and the areas will be non-static, since the intersecting shapes themselves will also be dynamic. My first thought was to use raycasting detection, though I've only seen that in use with circles, or even ellipses.

I'm curious if there's a method of using raycasting with a more rectangular approach, or if there's a totally different method already in use to accomplish this task. I would like something more exact than checking in large chunks, and since I'm using SDL2 with a logical renderer size of 1920x1080, checking if each pixel is intersecting is out of the question, as it would slow things down past a playable speed. I already have a multi-shape collision function-template in place, and I could use that, though it only checks if sides or corners are intersecting; it does not compute the overlapping area, or even find the circle's secant line, though I can't imagine it would be overly complex to implement.

TL;DR: I need to find and isolate areas of a rectangle that may intersect with a circle or another rectangle without checking every single pixel on-screen.


texts: In Pygame, I can only display text once I stop updating and drawing, why?

texts:
At this moment, I can only display text once I stop updating and drawing sprites. In the code below (which is actually the game loop), you can see how if GAMEOVER == True (gameloop stops drawing), the text "Game Over!" is displayed. But if I try to display any text while drawing and updating, it doesn't appears until I stop drawing the sprites. In fact, the frist block to display text ("My Game!") isn't shown, as I said, until the gameloop stops drawing. I need to display some info like, name of char, instructions, etc while the game is running, so, how can I render text in every loops and frames?

The game loop:

while True:

    myfont = pygame.font.SysFont("monospace", 30)
    label = myfont.render("My Game!", 1, (255, 255, 0))
    SCREEN.blit(label, (500, 400))

    if PLAYER.healthBase <= 0:
        GAMEOVER = True #True para que se acabe la partida

    if not GAMEOVER:
        charsGroup.update(time_passed)
        npcsGroup.update(time_passed)
        mapTilesGroup.draw(SCREEN)
        charsGroup.draw(SCREEN)
        npcsGroup.draw(SCREEN)
        drawBullets()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    time_passed = freq.tick(0) /1000.

    if GAMEOVER:
        myfont = pygame.font.SysFont("monospace", 30)
        label = myfont.render("GAME OVER!", 1, (255, 255, 0))
        SCREEN.blit(label, (400, 300))

    pygame.display.flip()


texts: Does using Creative Common data in a GPL game mean the code must be CC-BY-SA?

texts:
Let's assume we have a game where the code is GPL-licensed, and all the resources (like music, textures, etc.) are licensed under the CC-BY-SA license.

Now, the first issue would be that the GPL is not compatible with the CC-BY-SA, but since it only applies when actually linking code, it's okay in this case. Am I right?

The real problem is that, arguably, the game is "built upon" (to use the same terms as the license) the music, textures, etc. So wouldn't the CC license require the code to be released under the CC-BY-SA as well?


texts:
How can I display trajectory path exactly as in this image?

I have used void OnDrawGizmos, but that only displays trajectory in the editor and without any arrows like shown below.

Trajectory with void OnDrawGizmos

Script:

public Transform someObject; //object that moves along parabola.
float objectT = 0; //timer for that object

public Transform Ta, Tb; //transforms that mark the start and end
public float h; //desired parabola height

Vector3 a, b; //Vector positions for start and end

void Update () {
    if ( Ta &&  Tb ) {
        a = Ta.position; //Get vectors from the transforms
        b = Tb.position;

        if ( someObject ) {
            //Shows how to animate something following a parabola
            objectT = Time.time % 1; //completes the parabola trip in one second
            someObject.position = SampleParabola( a, b, h, objectT );
        }
    }
}

void OnDrawGizmos () {

    //Draw the parabola by sample a few times
    Gizmos.color = Color.red;
    Gizmos.DrawLine( a, b );
    float count = 20;
    Vector3 lastP = a;
    for ( float i = 0; i < count + 1; i++ ) {
        Vector3 p = SampleParabola( a, b, h, i / count );
        Gizmos.color = i % 2 == 0 ? Color.blue : Color.green;
        Gizmos.DrawLine( lastP, p );
        lastP = p;
    }
}

#region Parabola sampling function
/// <summary>
/// Get position from a parabola defined by start and end, height, and time
/// </summary>
/// <param name='start'>
/// The start point of the parabola
/// </param>
/// <param name='end'>
/// The end point of the parabola
/// </param>
/// <param name='height'>
/// The height of the parabola at its maximum
/// </param>
/// <param name='t'>
/// Normalized time (0->1)
/// </param>S
Vector3 SampleParabola ( Vector3 start, Vector3 end, float height, float t ) {
    float parabolicT = t * 2 - 1;
    if ( Mathf.Abs( start.y - end.y ) < 0.1f ) {
        //start and end are roughly level, pretend they are - simpler solution with less steps
        Vector3 travelDirection = end - start;
        Vector3 result = start + t * travelDirection;
        result.y += ( -parabolicT * parabolicT + 1 ) * height;
        return result;
    } else {
        //start and end are not level, gets more complicated
        Vector3 travelDirection = end - start;
        Vector3 levelDirecteion = end - new Vector3( start.x, end.y, start.z );
        Vector3 right = Vector3.Cross( travelDirection, levelDirecteion );
        Vector3 up = Vector3.Cross( right, travelDirection );
        if ( end.y > start.y ) up = -up;
        Vector3 result = start + t * travelDirection;
        result += ( ( -parabolicT * parabolicT + 1 ) * height ) * up.normalized;
        return result;
    }
}


texts: Unity Build not working because resources.assets is over 10GB in size.

texts:
I made a application where a bunch of images are loaded and placed in 3d. The total amount of images in the asset folder are about 10.000 images. Only 1100 random of these images get actually used in the application. This is different eachtime on startup. The total size of the Assets folder is 3.2GB.

See the Image below for confirmation:

Now when i build the application the application wont display any of the images in 3D space... :( So i went to investigate, and i found out that my resources.assets file is over 10GB in SIZE!! And i found out that unity cant really handle a resources.assets file more then 4GB. See the proof below:

So i have no idea what happens here or what to do about it.. All suggestions are welcome!
If more explaination or details are needed let me know.

Edit:
Maybe the image import settings are useful to know.. I just used the default settings.. See image below:


texts: How to make player instantly move to the right or left when entering a box collider

texts: I have a box collider and right now when I walk into it it says "you can't go there yet" I would like it for it to also move the player like 3 steps to the right or something. How would I do thatr?


texts:
I'm trying to debug a monogame application using xamarin studio and breakpoint.
Is it possible to disable the 17 seconds timeout on the FinishedLaunching function?


texts:
Before diving too deep into my question, let it be known that I am learning as far as java script goes and figured a simple Tower Defense game would be an excellent way to learn things.

So I have found a simple background image with a path drawn on it and my question is how would I go about building a path so that I can animate my objects.
Would I have to take the image and overlay a grid system, or can I store the path in some sort of array and have my objects move across it?

Here is the background image:


texts: How to make local keyboard input move only the local player, not everyone in networked multiplayer?

texts:
I am working on Unity Networking and following this Tanks Networking tutorial:

https://www.youtube.com/watch?v=V6wEvT6G92M

Problem is that the keyboard inputs move all the tanks in the scene. It is not detecting the local tank. And when I run the game all tanks shows the same movement but it is not giving any error. I have followed all steps in the tutorial and searched all solutions on the google. This step in Tutorial is at 11:48.

Implemented Code is:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityEngine.Networking;

public class TankController : NetworkBehaviour {

// Use this for initialization

[Header("Movement Variables")]
[SerializeField] float movementSpeed = 5.0f;
[SerializeField] float turnSpeed = 45.0f;

[Header("Camera Position Variables")]
[SerializeField] float cameraDistance = 16f;
[SerializeField] float cameraHeight = 16f;

Rigidbody localRigidBody;
Transform mainCamera;
Vector3 cameraOffset;

void Start () {
    if (!isLocalPlayer)
    {
        Destroy(this);
        return;
    }
        localRigidBody = GetComponent<Rigidbody>();
        cameraOffset = new Vector3(0f, cameraHeight, -cameraDistance);
        mainCamera = Camera.main.transform;
        MoveCamera();

}

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

        float turnAmount = CrossPlatformInputManager.GetAxis("HorizontalUI");
        float moveAmount = CrossPlatformInputManager.GetAxis("VerticalUI");

        Vector3 deltaTranslation = transform.position + transform.forward * movementSpeed * moveAmount * Time.deltaTime;
        localRigidBody.MovePosition(deltaTranslation);

        Quaternion deltaRotation = Quaternion.Euler(turnSpeed * new Vector3(0, turnAmount, 0) * Time.deltaTime);
        localRigidBody.MoveRotation(localRigidBody.rotation * deltaRotation);

        MoveCamera();

}

void MoveCamera() {
        mainCamera.position = transform.position;
        mainCamera.rotation = transform.rotation;
        mainCamera.Translate(cameraOffset);
        mainCamera.LookAt(transform);

}
}

I have also checked the auto create player in the spawn info as suggested in some solutions.


texts: Using a different "max texture size" depending on the device

texts:
I am developing an Unity game for a wide range of iOS devices. I noticed that some scenes load pretty fast in the iPad mini 3, but very slow in the iPad mini 1. Of course, that's to be expected as one is much faster than the other.

The scene is composed mostly of several sprites. As an optimization attempt, one could reduce the max texture size property of the sprites, as I'd imagine this will allow them to load faster.

Is it possible to have a max size of 2048 for the iPad mini 3, but only 1024 for the iPad mini 1?

I suspect that the answer is no, as Unity "compiles" the images depending on the settings you used when building the game.


texts: Is it wrong to be creating new objects in Update()?

texts:
I'm using Unity and sometimes I'm using th new keyword in Update, like new Vector3() etc...

I wonder is this causes memory leak? I mean in every frame a new Vector3 is created. If this is the way of working that means there are thousands of Vectors created in memory. Is it true or do I think wrong?


texts: Unity Mechanim makes physics behave weirdly

texts:
I'm developing a 2D Wrestling game in Unity 5 build 5.1.2f1. It's just the beginning so the character only has a number of animation states and a rigidbody2d.
This is the state machine

and these are the Animator and Rigidbody2D components

Note that I'm using Root motion to animate "High Knee" state since I've animated the character jumping in the air(high knee) by animating character's transform.

This is the simplest form of code to move the character

void Start ()
{
    rb = GetComponent<Rigidbody2D>();
    anim = GetComponent<Animator>();
}

void Update ()
{
    print (rb.velocity);
    if(Input.GetAxis("Horizontal") > 0)
    {
        rb.AddForce(new Vector2(0,50));
        anim.SetBool("isWalking",true);
    }

    else if(Input.GetAxis("Horizontal") < 0)
    {
        rb.AddForce(new Vector2(0,-50));
        anim.SetBool("isWalking",true);
    }

    else if(Input.GetAxis("Vertical") > 0)
    {
        rb.AddForce(new Vector2(50,0));
        anim.SetBool("isWalking",true);
    }

    else if(Input.GetAxis("Vertical") < 0)
    {
        rb.AddForce(new Vector2(-50,0));
        anim.SetBool("isWalking",true);
    }

}

The Character starts moving in x direction with a constant speed as soon as i press the horizontal keys. But for the y axis, when i press up or  down key, character starts at 0 and speeds up really really fast( like 50 milisecs) and then the speed keeps increasing and increasing until i release the key. It still keeps moving but the speed doesn't increase anymore. I'm not sure but i think the former behavior is weird and latter is fine (or vice versa). When i remove all the "anim.SetBool" lines in the above code, speed becomes constant for the y axis too, that is, it starts behaving exactly like the x axis. But when i disable the Animator component, x axis movement starts behaving like y axis, that is, speed starts at 0 and quickly increases and keeps increases as long as the key is held down. When i uncheck the "Apply Root Motion" check box, character doesn't move at all. I don't know what's happening. Any help would be appreciated.


texts: Crowdfunding an indie game. What should I offer back?

texts:
I have seen many indie games making money for development using crowd funding (Kickstarter, IndieGoGo, et cetera). Some of the games will offer something back. For example, in an RPG game, you might get an NPC character based on you. Some other projects simply give you the final version for free.

Apart from actually finishing the game, which is probably the main reason why anyone would want to give you the money, what should my reward strategy be?


texts: Is it possible to have concurrent collision detection where every entity acts at exactly the same time?

texts:
There are many algorithms that can be used for collision detection. In many cases we check for an overlap in coordinates of an entity.

If we make a triangle a,b and c. We have 2 entities at a and b heading for a collision at c but each of them are moving at exactly the same time, what kind of algorithm could work?

It seems more like a chess game where you would have to predict every move that the other entity would have to make, if they swerve to the left to avoid a collision will they also run the chance to collide. Is it possible or is it too complex? Would it work for thousands and millions of entities in the same search space?


texts: Why are transform values in inspector different from animation tab?

texts: I’m trying to make animation in timeline. But transform values in animation tab and inspector are different from each other. It causes problem when ı try to rotate player. It doesn’t rotate the way I want.


texts: How to use a DualShock 4 controller in Java?

texts:
I want to use a DualShock 4 controller in a computer program I'm developing.

Do I only need to use a library? Or do I need some other things too?

I don't have any code yet, I'm just starting to look at it. I'll be using Eclipse if it has any relevance.


texts: How do I switch between the game screen and score screen without redrawing everything?

texts:
I'm working on a multiplayer game in Libgdx and  want to display the scores of say, the top 10 players on the map. The player should be able to checking the scores at any point during the game and return to the game screen (with themselves in the same location they were at earlier), much like pressing Tab during a game of Counter Strike displays the scores.

Changing the screen to the score screen is simple enough using setscreen, but how can I return to the previous view without calling a setscreen on the game screen and rendering everything all over again?


texts: Binding Nested JSON To Dictionary Not Working

texts:
I am creating nested JSON and binding it with the class. But It doesn't bind with the class.

JSON:

 {
  "PuzzleData": {
    "Category1": {
      "Cultus": {
        "Type": "Car",
        "Name": "Cultus",
        "Item1": "gate",
        "Item2": "window",
        "Item3": "tyre",
        "Item4": "tyre"
      },
      "Lion": {
        "Type": "Lion",
        "Name": "Animal",
        "Item1": "legs",
        "Item2": "hands",
        "Item3": "head",
        "Item4": "eyes"
      }
    }
  }
}

Class:

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

[System.Serializable]
public class PuzzleGameData{

    public Dictionary<string, Category1> PuzzleData;

    [System.Serializable]
    public class Category1
    {
        public string Type;
        public string Name;
        public string Item1;
        public string Item2;
        public string Item3;
        public string Item4;
    }
}

Any help would be appreciated.
Thanks.


texts: Obj Blender Export Recommendation for OpenGL C++

texts:
I have been modelling some objects inside blender, like a light bulb.
I finished the light bulb, and I got a question at the time of export it.

I want to export the light bulb in the wavefront format (.obj), but the light bulb is formed by different meshes, I mean, It's not joined in one mesh. If I export the obj that will be as different meshes inside the .obj

My final question is, for import it in the OpenGL C++ side, it's better to join all the meshes (vertexes) inside one or leave them as separated objects? There will not be any trouble on translating... resizing... etc, if they are not joined?


texts: Why is is so hard to develop a game console emulator?

texts:
I have always found emulators rather fascinating. I would seriously like to create an emulator for an older ganeration console or handheld. It would help me gain a greater appreciation of the hardware and the games which were created for that hardware. However, people are always saying how hard it is and that I should not even try. I would like to know why that is.

Also, I would like some suggestions on a good place to start and where can I find the information I need?


texts: Single or multiple inheritance for game world objects

texts:
So I am currently laying out on paper the system I want to code for a game in C++.

Now currently I am debating whether to have e.g. a class object_door that inherits from another class object_interactive, which inturn inherits from the base class object

OR

have a class object_door that inherits from both the class object and another base class interactive.

Is there any advantage to either way of doing inheritance? Or is there maybe a commonplace convention for this?


texts: Obstacle spawn constraints in Jetpack Joyride

texts:
Jetpack Joyride: https://www.youtube.com/watch?v=3KENMuzsras

tl;dr

What's the best way to add constraints to obstacle spawning (algorithms) or how to design obstacle spawning to allow constraints?

More details and my understanding

I am trying to understand how to add constraints to a spawning algorithm and I'm using Jetpack Joyride as reference (although I don't mind a general answer, especially if you're not very familiar with the game). I am particularly interested in the electrical obstacles [see image], so I will only consider them from now on.

There is probably a list of such obstacles from which one is fetched and placed on the screen. But where and when you place them is extremely important. First, you want to make sure your obstacles are between some minimum height -the floor- and some maximum height -the ceiling-. Then you may also want some minimum distance between any two consecutive obstacles. Also you don't want to spawn them too often, otherwise the game becomes repetitive. Then clearly you want to avoid sequences of obstacles that are impossible to pass. Then in some moments obstacles tend to spawn closer to the ground than usual. And so on.

I have no idea how to integrate, design-wise, all these constraints into obstacle spawning.  I could probably have a lot of if statements and flags that are checked for each new item fetched from the available obstacles pool, but if I have a great number of constraints, the code may become very messy. I don't how this is approached in general.


texts:
Being a programmer of web and DB centered applications, I have knowledge in data structures such as lists, trees, graphs, etc. I honestly use very little of these data structure algorithms in my coding, except for sorting things in plain arrays, as I worked almost entirely with client-oriented frameworks where all the core functionality was built-in. I know C, PHP, Java, HTML, PL/SQL and MySQL. I am currently learning Python.

I want start with game development. I have seen other questions regarding suggestions, tips and approaches to game development for beginners. I understand these point, and am clear with the answers. A few days after posting, I read the article Write Games, Not Engines, and realized I should implement a game before I create a game engine. Still, I have questions.

My aim is to

Improve my core level programming skills, including using data structure algorithms, mathematics and physics concepts.
Implement a good game engine, to indulge myself in core level coding.
To pave my way into the A.I. research field.

What are the specific mathematics, physics, AI and general concepts a programmer should know in order to develop a game engine?


texts: LibGDX Rectangle not Scaling to ImageButton Instance as Expected

texts:
below is the class I wrote for a GameButtoninstance:

public class GameButton {

private ImageButton button;
private TextureRegionDrawable drawableUp, drawableDown;
private Rectangle hitbox;

public GameButton(int x, int y){
    final int boxSize = 100;
    drawableUp = new TextureRegionDrawable(AssetLoader.gameButtonUp);
    drawableDown = new TextureRegionDrawable(AssetLoader.gameButtonDown);
    button = new ImageButton(drawableDown, drawableUp, drawableUp);
    button.setPosition(x,y);
    button.setSize(100,100);
    hitbox = new Rectangle(x,y,0,0);

    button.addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            if(button.isChecked()){
                hitbox.setSize(boxSize,boxSize);
                Gdx.app.log("Button", "active ("+hitbox.getWidth()+","+hitbox.getHeight()+")");
            }else{
                hitbox.setSize(0,0);
                Gdx.app.log("Button", "inactive ("+hitbox.getWidth()+","+hitbox.getHeight()+")");
                button.setChecked(false);
            }
        }
    });
}

public Rectangle getHitbox(){ return hitbox; }

public ImageButton getButton(){return button;}}

Essentially this class defines an ImageButton with a bounding Rectangle that changes size whenever I click the button. The size change works as expected, however the bounding Rectangle isn't up to scale with the ImageButton. AssetLoader.gameButtonUp is a TextureRegion with coordinates (131,142) the same dimensions as the texture image.

However, when I use ShapeRenderer to draw where the rectangle is on screen I get this,

when the desired outcome to have that big square is to be on top of the blue button in this image and for it to be the same size

(Ignore the smaller rectangle in the top left)

I'm still new to libGDX, so any help would be appreciated.
Thanks.


texts:
I'm looking for good algorithms for compressing textures offline (ie decompressing them at install or load time, I know about using DXT/3DC to save runtime video memory, but these create awful visual artifacts while often being larger in disk than a lossless format like JPEG-LS, even after using LZMA or something for entropy). Since the data will only need to be read by my program, I don't need a portable format like JPEG, which means I'm open to more experimental algorithms. To be clear, I'm concerned with reducing the download size of my game; I will be using them uncompressed on the video card.

I'm looking for formats that support different features... For example, 10 bits-per-channel color (HDR) for higher color fidelity under dynamic lighting conditions, normal map formats(16 bits in X and Y), alpha channels, etc, etc...

NOTE: My particular use case is for 2.5D backgrounds. In their uncompressed format, they are 10 bytes per pixel stored in 3 textures:

4 bytes - color  - D3DFMT_A2R10G10B10
4 bytes - normal - D3DFMT_G16R16F
2 bytes - depth  - D3DFMT_R16F

I store these in 1024x1024 tiles, and since every area has a different background, these can get really large really fast. However, I think knowing more about image codecs in general will help with finding an efficient method to compress these.


texts: Sprite Animation Software That Works With Cocos2D

texts:
So the title basically says it all. I'm looking for software that would help me to create sprite animations that I could use with cocos2d by allowing me to pose a a sprite and the software create key-frames between the sprites( basic tweening ).

Any ideas?


texts:
I am trying to make a plain white room in Unity. I used six planes for the walls, but I can't figure out how to get the lighting to not look so harsh and uneven. The top picture is my best attempt using two directional lights, and the bottom picture is the look that I am trying to replicate. It is from a demo scene in the Google VR SDK 1.50 for Unity. It uses only a single point light, but when I turn it off in the scene view, it doesn't change the appearance of the room at all. How can I make my room look more like the Google VR demo?

EDIT: I made a big improvement by changing all my walls to be static so that they receive indirect lighting, and adding a single point light above the roof.


texts: Strange warping/shimmering effect with Unity Tilemap and Cinemachine

texts:
I'm using a Cinemachine Virtual Camera in a 2D project to follow around a target. The ground / background is a Unity Tilemap GameObject.

As you can see in the gif above (or on Imgur), when following around the player (a 24x24 sprite), the background tiles seem to warp or shimmer a bit.

I've tried to script all types of solutions to adjust the Virtual Camera transform position and hopefully snap/move it "correctly" to no avail.

I don't even know for sure that the source of the issue is with the camera setup. I'm running out of solutions to something that seems like a pretty straightforward and very common scenario. I've created a sample project illustrating the issue which can be downloaded here.

Using Unity 2017.3.1f1 Personal. The background sprites are 32x32, with a PPU of 32. No compression, Point (no filter), rendered using a material with Shader: Sprites/Default, and Pixel snap.

Cinemachine Virtual Cam is set to Ortho lens size 16, Body: Framing Transposer with default settings.

Thank you so much for any suggestions or tips!!!

It feels similar to what's being described here with sub-pixel movement but I don't know for sure, and the solution in that blog post seems like it should be unnecessary (but again - maybe not).

I've created camera scripts and attached them to the virtual camera as follows:

float maxPixelHeight = 32;
CinemachineVirtualCamera vcam;

public void Awake()
    {
        float scale = Screen.height / maxPixelHeight;
        float orthographicSize = (Screen.height / scale) / 2f;
        vcam = GetComponent<CinemachineVirtualCamera>();
        vcam.m_Lens.OrthographicSize = orthographicSize;
}

    public void Update()
    {
        Vector3 tempPos = vcam.transform.position;
      Vector3 newPos = new Vector3(Mathf.RoundToInt(tempPos.x), Mathf.RoundToInt(tempPos.y), Mathf.RoundToInt(tempPos.z));
        vcam.transform.position = tempPos;
    }

I've also tried:

public void Update()
    {
        Vector3 tempPos = vcam.transform.position;
Vector3 newPos = new Vector3((float)System.Math.Round((decimal)tempPos.x, 2) , (float)System.Math.Round((decimal)tempPos.y, 2), (float)System.Math.Round((decimal)tempPos.z, 2));
        vcam.transform.position = newPos;
    }

and something like:

public void Update()
    {
        Vector3 tempPos = vcam.transform.position;
        vcam.transform.position = new Vector3(RoundToNearestPixel(tempPos.x), RoundToNearestPixel(tempPos.y), RoundToNearestPixel(tempPos.z));
    }

    public float RoundToNearestPixel(float unityUnits)
    {
        float valueInPixels = unityUnits * maxPixelHeight;
        valueInPixels = Mathf.Round(valueInPixels);
        float roundedUnityUnits = valueInPixels * (1 / maxPixelHeight);
        return roundedUnityUnits;
    }


texts:
Why are there sound effects in space shooter games like asteroid and such?

There is no medium in space for sound to travel by. Yet we get hear gun shots & explosion.

I am not talking about the background music/sound.


texts:
Any suggestions for creating ocean waves / ripples as seen in the pictures here:

http://www.pocket-lint.com/news-gallery/42042/crimson-steam-pirates-ipad-review/10#image

and video here:

http://www.youtube.com/watch?v=AtrZX3e4AL8

I was thinking of setting a background repeating tile. Then making some kind of noise tile which would mostly transparent and moving this in sections across the background tile.

Any improvements or further suggestions on this?

Cheers


texts:
In a lot of places I interviewed recently, I have been asked many a times if I have worked with shaders. Even though, I have read and understand the pipeline, the answer to that question has been no. Recently, one of the places asked me if I can send them a sample of 'something' that is "visually polished".

So, I decided to take the plunge and wrote some simple shader in GLSL(with opengl).I now have a basic setup where I can use vbos with glsl shaders.

I have a very short window left to send something to them and I was wondering if someone  with experience, could suggest an idea that is interesting enough to grab someone's attention.

Thanks


texts: I am trying to create an isometric map and I am very new to it. Please see the attached example map. While rendering it I've noticed that when my actor reaches the edges of the map the player can see the black screen after it which is not very nice. I wonder what are the best practices of dealing with it ? Do I need to show the black screen where the map ends, if not then what's the best way to avoid/hide it?


texts: Using an objects velocity to determine if it falling on a player will kill it

texts:
I've been attempting to make a falling object kill a player, but i still want to make sure the player can touch and interact with the object to move it around without dying. The code i've made so far somewhat works as it wont kill the player when they move it will kill the player when it falls and hits them, but the problem is it only works if they have not moved yet from their spawn position (could also be true for when they have stood still for a second). Here is my code

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

public class BoxyKill : MonoBehaviour
{
    public Rigidbody2D rgbd;
    public CharacterController2D character;

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            Debug.Log("Hit player");
            if (rgbd.velocity.y <= -5f) {
                character.Damage(10);
                Debug.Log("Hit player 2");
            }
        }
    }
}

Note - the 'rgbd' is the boxs and this script is attatched to the object

Thanks!

UPDATE

So as of DMGregorys suggestions i have updated the code and while it works i have encountered the same problem (however a lot more controlable this time)

Here is my current code

    public Rigidbody2D _body;
    private float minimumDamageThreshold=10;
    private float collisionDamageScale=.0001f;

    void OnCollisionEnter2D(Collision2D collision)
    {

        Vector2 normal = collision.GetContact(0).normal;
        Vector2 impulse = ComputeTotalImpulse(collision);

        Vector2 myIncidentVelocity = _body.velocity - (impulse / _body.mass);

        Vector2 otherIncidentVelocity = Vector2.zero;
        var otherBody = collision.rigidbody;
        if (otherBody != null)
        {
            otherIncidentVelocity = otherBody.velocity;
            if (!otherBody.isKinematic)
                otherIncidentVelocity += impulse / otherBody.mass;
        }

        // Compute how fast each one was moving along the collision normal,
        // Or zero if we were moving against the normal.
        float myApproach = Mathf.Max(0f, Vector3.Dot(myIncidentVelocity, normal));
        float otherApproach = Mathf.Max(0f, Vector3.Dot(otherIncidentVelocity, normal));

        float damage = otherApproach - myApproach;
        Debug.Log(damage);
        character.Damage(damage);
    }
    static Vector2 ComputeTotalImpulse(Collision2D collision)
    {
        Vector2 impulse = Vector2.zero;

        int contactCount = collision.contactCount;
        for (int i = 0; i < contactCount; i++)
        {
            var contact = collision.GetContact(0);
            impulse += contact.normal * contact.normalImpulse;
            impulse.x += contact.tangentImpulse * contact.normal.y;
            impulse.y -= contact.tangentImpulse * contact.normal.x;
        }

        return impulse;
    }
}

It now works and will kill the player, and i have it printing out the damage in the debug for the character script damage function. The only problem is, it will constantly damage the player if it touches the box at all, and the player needs to be able to move the box around so this will slowly kill it.
This could be a problem with the variable amounts that i have configured due to a lack of understanding (and a lot of mindless fideling to be honest).


texts: Changing Animation Sprites At Runtime Once

texts:
I am designing a 2d platformer with pixel 32x32 sprites, right now I’m using the method that’s utilized at 20 minutes in this video.
I’m pretty much creating a main player parent object and adding the players equipment (helmet, breastplate, leggings) sprites underneath. But obviously when the player animates and starts running the pixel equipment needs to move and shift with the player.
The solution provided by the video seems to work fine, but why can’t this just be called once at the start and be set until changed? Basically why can’t I set the sprites at the different frames of the animation when the game starts and leave it. I basically redrew all of equipment to fit the character during each frame of the run animation etc. If I equip a specific helmet, I just want to set all the sprites in the animation once, and if I replace the equipment, a new sprite sheet is used that contains the breastplate and its animations during the run animation for example.
Is there any way to not repeatedly set renderer.sprite for each sprite in an animation via the late update function? I’m just worried that the function I attached will cause animation lag or lag to the game in general.
(I do not wish to piece and part the character together, especially not a 32 pixel drawing, and boning the character and stretching the pixels is definitely not a good option either)


texts: Separating data from model and successfully visualizing it

texts:
This is a bit of a design question that I'm struggling with. I have a data model and an entity model. The data model is, of course, what is (de)serialized to represent my levels and entities within it, whereas the entity model is the run-time manifestation of the level actually being played.

In addition, I have a game editor that allows the levels to be edited and played all in the same UI. It has 2 modes, each with 2 views:

Design-time Mode:

a top-down, interactive view of the level. This is where the actual editing of the level takes place.
an in-game preview of the level that updates as changes are made in the top-down view

Run-time Mode:

a top-down view of the level that is non-interactive but live
an in-game, run-time view of the game that is interactive. ie. you can actually play the game.

The user switches between the modes by clicking play & stop buttons. Here's an example of my top-down view (this one is run-time):

Now, here is the problem: I want the design-time top-down view to mimic the run-time top-down view as much as possible, but certain information is unknown at design time, such as the texture dimensions and collision circle information. Therefore, I cannot render this information accurately.

I see these options for dealing with the situation:

don't try and mimic the run-time, top-down visualization. Instead, just render something that is as useful as I can make it given the limited information I have available.
hack my data model so that it also returns information that it really has no business knowing, such as the collision circles and texture dimensions. This would facilitate the visualization of that information, but at the cost of maintenance and code design.
since my design-time mode already has two views, one of which is a manifestation of my data model, and the other is a manifestation of my entity model, I could dynamically try to correlate that information for the purposes of my top-down visualizer. This seems like it should work, but also seems rather messy and error-prone.

This seems like it must be a fairly common problem when writing game editors, so I thought I'd try to gather some advice. Any input from the community would be much appreciated.


texts: Diamond Square Algorithm - How to fix horrible diamond shaped artefacts and spikes?

texts:
I was attempting to follow this article explaining the implementation of a wrapping version of the diamond square algorithm.

I tried running it with dimensions of 128x128 and a "feature size" of 16, like in the article, but the resultant terrain is this monstrosity:

I read through past questions on this topic and am aware that there can be some issues with somewhat noticeable diamond or square shaped artifacts when using this algorithm, but this is definitely beyond that.

Here is my code:

private float GetHeightAtPoint(int x, int z)
{
    if (x < 0) { x = width + x; }
    if (z < 0) { z = height + z; }

    return fractal[(x % (width - 1)) + (z % (height - 1)) * width];
}

private void SetHeightAtPoint(int x, int z, float value)
{
    if (x < 0) { x = width + x; }
    if (z < 0) { z = height + z; }

    fractal[(x % (width - 1)) + (z % (height - 1)) * width] = value;
}

private void SquareStep(int x, int z, int size, float value)
{
    int halfSize = size / 2;

    float a = GetHeightAtPoint(x - halfSize, z - halfSize);
    float b = GetHeightAtPoint(x + halfSize, z - halfSize);
    float c = GetHeightAtPoint(x - halfSize, z + halfSize);
    float d = GetHeightAtPoint(x + halfSize, z + halfSize);

    float meanHeight = (a + b + c + d) / 4.0f;
    float adjustedHeight = meanHeight + value;

    SetHeightAtPoint(x, z, adjustedHeight);
}

private void DiamondStep(int x, int z, int size, float value)
{
    int halfSize = size / 2;

    float a = GetHeightAtPoint(x - halfSize, z - halfSize);
    float b = GetHeightAtPoint(x + halfSize, z - halfSize);
    float c = GetHeightAtPoint(x - halfSize, z + halfSize);
    float d = GetHeightAtPoint(x + halfSize, z + halfSize);

    float meanHeight = (a + b + c + d) / 4.0f;
    float adjustedHeight = meanHeight + value;

    SetHeightAtPoint(x, z, adjustedHeight);
}

private void DiamondSquare(int stepSize, float scale)
{
    int halfStep = stepSize / 2;
    for (int z = halfStep; z < height + halfStep; z += stepSize)
    {
        for (int x = halfStep; x < width + halfStep; x += stepSize)
        {
            SquareStep(x, z, stepSize, Random.Range(-1.0f, 1.0f) * scale);
        }
    }

    for (int z = 0; z < height; z += stepSize)
    {
        for (int x = 0; x < width; x += stepSize)
        {
            DiamondStep(x + halfStep, z, stepSize, Random.Range(-1.0f, 1.0f) * scale);
            DiamondStep(x, z + halfStep, stepSize, Random.Range(-1.0f, 1.0f) * scale);
        }
    }
}

/*
 * Generate a fractal map using diamond square algorithm and store in fractal[]
 */
private void GenerateFractal(int featureSize)
{
    fractal = new float[width * height];

    for (int z = 0; z < height; z += featureSize)
    {
        for (int x = 0; x < height; x += featureSize)
        {
            SetHeightAtPoint(x, z, Random.Range(0.0f, maxHeight));
        }
    }

    int sampleSize = featureSize;
    float randomScale = 1.0f;

    while (sampleSize > 1)
    {
        DiamondSquare(sampleSize, randomScale);

        sampleSize = sampleSize / 2;
        randomScale = randomScale / 2.0f;
    }
}

Could anyone give me any guidance here? One thing that was a bit suspect was that I had to make slightly different wrapping array access functions in order to make this run as I was getting negative values. You can see that my functions have the if statements checking for negatives, whereas the original implementation does not.

Thanks in advance


texts:
I'm using a Look At function (idem as nasskov answer on this post) to orient a model:

osg::Quat result = quatLookAt(normalize(velocity));

It works but may let the model to roll. How I can avoid this ?

I'm thinking of decomposing the rotation into two quaternions (Pitch&Yaw) but not succeeded so far.

The solution:

inline osg::Vec3
VectorFront()
{
  return osg::Vec3(0, 1, 0);
}

inline osg::Vec3
VectorUp()
{
  return osg::Vec3(0, 0, 1);
}

inline osg::Quat
quatLookAt(const osg::Vec3& dir, const osg::Vec3& up)
{
  if (dir.length2() == 0.0f) {
    assert(false && "Zero length direction in quatLookAt(const osg::Vec3& "
                         "dir, const osg::Vec3& up)");
    return osg::Quat();
  }

  if (up != dir) {
    const osg::Vec3 v = dir + up * -(up * dir);
    osg::Quat       q;
    q.makeRotate(VectorFront(), v);
    osg::Quat r;
    r.makeRotate(v, dir);
    return q * r;// * q
  }

  osg::Quat q;
  q.makeRotate(VectorFront(), dir);
  return q;
}

// ...

const osg::Quat q = quatLookAt(new_forward, VectorUp());


texts: glColor is working well only in debugging mode, why?

texts:
This semester I have a class that I using OpenGL and I'm trying open a window with random colors inside rectangles.

For this, I created a class that I define RGB in constructor. If I use debugging mode and I pass step by step, OpenGL renders rectangles with the correct colors but if I run my app in Release mode, all the rectangles receive the last color set.

It is strange because I created two objects. I think that each object sould have its own properties. Am I correct?

Bellow I put two screenshots, one with the program in debugging mode and the other in Release mode.

I'm a beginner in OpenGL and have some questions in c++.

Thanks,

And bellow is my code:

Constructor of my class square GEO_Square.cpp:

GEO_Square::GEO_Square()
{
    srand(time(NULL));
    red = ((rand() % 10) / 10.0);
    green = ((rand() % 10) / 10.0);
    blue = ((rand() % 10) / 10.0);
}

//Function to draw
void GEO_Square::drawSquare()
{
    fillVectorWithPosition(width, height, posX, posY); //function to calculate positions

    glBegin(GL_QUADS);
    glColor3f(red, green, blue);
        glVertex2f(positions[0], positions[1]);
        glVertex2f(positions[2], positions[3]);
        glVertex2f(positions[4], positions[5]);
        glVertex2f(positions[6], positions[7]);
    glEnd();

    drawEdge();
    changeColor();
}

ColorGameMain.cpp:

int CALLBACK WinMain(
    __in  HINSTANCE hInstance,
    __in  HINSTANCE hPrevInstance,
    __in  LPSTR lpCmdLine,
    __in  int nCmdShow
)
{
    DrawRecs dRecs;
    GLFWwindow* window;

    if (!glfwInit()) return -1;

    window = glfwCreateWindow(WIDTH, HEIGHT, "Forms", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    gluOrtho2D(0.0, WIDTH, HEIGHT, 0.0);

    GEO_Square* quad = new GEO_Square();
    GEO_Square* quad2 = new GEO_Square();

    while (!glfwWindowShouldClose(window))
    {
        quad->setWidth(40.0);
        quad->setHeight(15.0);
        quad->setPosX(0.0);
        quad->setPosY(0.0);
        quad->drawSquare();

        quad2->setWidth(40.0);
        quad2->setHeight(15.0);
        quad2->setPosX(60.0);
        quad2->setPosY(20.0);
        quad2->drawSquare();

        quad->drawSquare(40.0, 15.0, 100.0, 40.89, 0.5, 0.5, 0.0);

        glfwSwapBuffers(window);

        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}


texts: Is this how I use activities in android studio?

texts:
I'm a student who is just stepping into android game development.

I'd like to create a text-based RPG game for android and started to learn about Android Studio (I think Android Studio is enough because I'm not using any 2D or 3D sprites).

But then I got into some confusions about the activity.

I learned that an activity has a life cycle from onCreate to onDestroy.

In some tutorials, I heard that activities are just various scenes that can be used within an app.

With that said, my question is, can an activity be used for a game scene?

For instance, I'm thinking about creating game scenes like the battle scene, exploring scene, town scene, inventory scene etc.

But opening up another scene, or activity, would destroy the previous one in which, in some cases, I would not want that to happen. (Am I correct on this?)

Do I need something else other than activity to create those scenes?


texts: Timing while calling update more than once per frame

texts:
TL;DR: Using a timestep method that calls update() multiple times per frame. After an event happens, need to add a wait time before it can happen again. What's the best way to do this so the wait times are always the same across all hardware?
Lets say that a bullet is spawned every time the player presses the mouse button. If the player holds the button down, a new bullet will spawn every frame (which is obviously WAY too many). The way I always got around this was to create a variable shotCoolDown and set it equal to some arbitrary number (usually 60). Then, in the update() function, I would subtract 1 from shotCoolDown every frame, and only allow the player to shoot if shotCoolDown was less than or equal to 0, and then after creating the bullet, set shotCoolDown back up to 60. At 60 FPS, this created a maximum of 1 bullet per second.
This worked when calling update() once per frame. However, I'm now using a new timestep method from this article, which calls update() multiple (always different) times per frame. Because I don't know how many times update() will be called, I can no longer use my original shotCoolDown method.
I've also tried comparing the current time to the time at the mouse button press, and if the difference is more than 1000 ms (1 second), spawn a bullet. However, this doesn't exactly work. Since the computer's clock continues to tick while the game is paused, the player can simply shoot, pause the game and wait for the limit to pass, then unpause the game and shoot again.
Is there a better way to add these time limits? I know I can use timers, but some of my limits will be as small as 1/10th of a second; I'd rather not use a timer for such a small period of time.


texts:
I have a turn-based game that is built with HTML 5 gaming framework and runs completely fine in Landscape mode. What I am trying to figure out is how to make the game run fine in both portrait and landscape mode such that even when the game is running and player rotates the screen to landscape the game runs perfectly or the game transition between landscape and portrait mode smoothly.

I can capture the orientation change event which is fired, my question is how should I design the game for both orientations.

Currently, I am trying to create a common file which then calls my separate orientation layouts created for the game but is this the right way?
Thanks


texts:
I would like to implement an object for my spritesheets in Javascript.

I'm very new to this language and game-developement so I dont really know how to do it.

My guess is I set spritesize to 16, use that to divide as many times as it fits on the spritesheet and store this value as "spritesheet". Then a for(i=0;i<spritesheet.length;i++) loop running saving the number of sprites.

Then tile = new Image(); and tile.src = spritesheet[i] to store the individual sprites based on their coordinates on the spritesheet.

My problem is how could I loop trough the spritesheet and make an array of that? The result should be similar to:

sprite.sprites = Array(
"0",
"1"
);

If possible this would be done with one single object that i only access once, and the tile array would be stored for later reference.

I couldn't find anything similar searching for "javascript spritesheet".

Edit 2: I've come a long bit since I first posted this question and this is what I've come up with so far:

function Sprite(){
    this.size = 16;
    this.spritesheet = new Image();
    this.spritesheet.src = 'spritesheet.png';
    this.spriteCount = this.spritesheet.height / this.spritesheet.width;
    this.spriteIndex = 0;
    var sprites = new Array();

    for(i=0;i<this.spriteCount;i++){
    sprites.push(this.spriteIndex); // Could insert pretty much whatever I want
    this.spriteIndex++;
    alert('spriteIndex # ' + sprites[i] + ' pushed');
    }
}
var sprite = new Sprite();

The alert method is only for testing, it alerts from 0 and up giving me usable X and Y values for the drawing (when multiplyed by size).
If anyone has improvements please let me know.

Edit 3: I still have some trouble with the array. How would i access the index of it?
For example the first sprite should give me sprite.sprites[0] second sprite sprite.sprites[1].


texts: Google Play Services Library not found. How can I get this?

texts:
So this question is in relation to, but not the same as my previous question (How do I successfully implement Google Mobile Ads and Google Play Services into my Unity arcade game?). That is why I am making a new one. I am almost ready to publish my app now the I have ads working but in the process of implementing Unity Ads I was forced to re-implement Google Play Services. I did so with an updated version of Google Play Services and now I am receiving this error:

Does anyone know how to fix this?


texts: Is there a standard way to store 3D meshes to easily communicate between libraries?

texts:
In a 3D game lots of different systems need to know about geometry data, however the only way they seem to be able to agree to on in representing it by an array of triangles.

Can anyone recommend a good geometry manipulation library that will allow me to easily integrate the drawing library(OpenGL), the physics engine(Bullet), Serialization(Several 3D file formats) and my own code(objective-c++).  Focus on the a representation between the drawing library and the physics engine.  Also if the library can triangulate a mesh definition that would be very helpful.  My code can work around what exists already.


texts: Lightning bolt effect with particles is not continuous

texts:
I am Drawing a lightning effect animation using this image:

Below the result:

As you can see the outcome is not a continuous purple color as I wanted it to be, but it has black spaces in between some parts.
The way i am drawing this animation is that i am drawing two LightningBolts every frame in Additive mode.
Every LightningBolt is drawn with the help of 21 random points across the width of the animation which makes 20 lines of various angles.
So I rotate the texture I have to match each angle I calculated for each of those 20 lines for the two LightningBolts I am drawing in every frame in Additive mode.

What are your suggestions to overcome this problem ?


texts: Open source level editor for HTML5 platform game?

texts:
A natty GUI editor is very helpful to create level map. I want to use some open-source choices rather than build my own from scratch. I found Tiled Map Editor but it doesn't work for what I want.

Though I'm building HTML5 game, I don't have to use a HTML5 level editor as long as it can output well-formatted map files which my javascript can read.

Edit:

Sorry for the confusion. Tiled does not work for me because to make the player perform a 'tricky' jump, sometimes I want to set the distance between two platforms to, say, 7/3 or 8/3 tiles. But in Tiled I get only 2 or 3. If Tiled can do this, please teach me.


texts: I created a blueprint called Background which is an actor. I dragged it to the main window but it isn't showing up ... I am just seeing a transparent thing. Can you help please ?


texts: Update sprite position when speed changes if frame rate is low

texts:
I have a sprite moving horizontally from left to right. For each iteration I want to start decreasing the speed.
This works ok, and the sprite will stop at some point, however depending on the frame rate it won't always stop
at the same place. What's wrong with my code?

...
Vector2 Position;
Vector2 Speed;
...
Speed.X = 50;
...

public override void Update(GameTime theGameTime)
{
    float time = (float) theGameTime.ElapsedGameTime.TotalSeconds;

    Position += Speed * time;

    Speed.X-=10; // Reduce speed for next iteration
    if ( Speed.X < 0 ) Speed.X = 0;
}

I have also tried by doing

Speed.X-=10 * time;

but that didn't work.


texts:
I am making my own collision detection in MonoGame. I have a PolyLine class That has a property to return the normal of that PolyLine instance. I have a ConvexPolySprite class that has a List LineSegments. I hav a CircleSprite class that has a Center Property and a Radius Property. I am using a static class for the collision detection method. I am testing it on a single line segment. Vector2(200,0) => Vector2(300, 200)

The problem is it detects the collision anywhere along the path of line out into space.
I cannot figure out why.
Thanks in advance;

public class PolyLine
{
    //---------------------------------------------------------------------------------------------------------------------------
    // Class Properties

    /// <summary>
    /// Property for the upper left-hand corner of the owner of this instance
    /// </summary>
    public Vector2 ParentPosition { get; set; }

    /// <summary>
    /// Relative start point of the line segment
    /// </summary>
    public Vector2 RelativeStartPoint { get; set; }

    /// <summary>
    /// Relative end point of the line segment
    /// </summary>
    public Vector2 RelativeEndPoint { get; set; }

    /// <summary>
    /// Property that gets the absolute position of the starting point of the line segment
    /// </summary>
    public Vector2 AbsoluteStartPoint
    {
        get
        {
            return ParentPosition + RelativeStartPoint;
        }

    }//end of AbsoluteStartPoint

    /// <summary>
    /// Gets the absolute position of the end point of the line segment
    /// </summary>
    public Vector2 AbsoluteEndPoint
    {
        get
        {
            return ParentPosition + RelativeEndPoint;
        }

    }//end of AbsoluteEndPoint

    public Vector2 NormalizedLeftNormal
    {
        get
        {
            Vector2 P = AbsoluteEndPoint - AbsoluteStartPoint;
            P.Normalize();
            float x = P.X;
            float y = P.Y;
            return new Vector2(-y, x);
        }

    }//end of NormalizedLeftNormal

    //---------------------------------------------------------------------------------------------------------------------------
    // Class Constructors

    /// <summary>
    /// Sole ctor
    /// </summary>
    /// <param name="parentPosition"></param>
    /// <param name="relStart"></param>
    /// <param name="relEnd"></param>
    public PolyLine(Vector2 parentPosition, Vector2 relStart, Vector2 relEnd)
    {
        ParentPosition = parentPosition;
        RelativeEndPoint = relEnd;
        RelativeStartPoint = relStart;

    }//end of ctor

}//end of PolyLine class

public static bool Collided(CircleSprite circle, ConvexPolygonSprite poly)
{
            var distance = Vector2.Dot(circle.Position -
                poly.LineSegments[0].AbsoluteEndPoint, poly.LineSegments[0].NormalizedLeftNormal) + circle.Radius;

            if (distance <= 0)
            {
                return false;
            }
            else
            {
                return true;
            }

}//end of collided


texts:
Taking for example a large (X by Y) hex map, how can I divide it into N regions of connected hexes to simulate countries?

The goal is to generate a hex map that looks like a real life map with countries with different shapes but equal sizes.


texts:
I'm trying to simulate a centipede game, and I'm doing the snake movement.
I have seen that piece of code, but can't get it, I know it gets the different between the current, previou's nodes positions, but what is the point of multiplying by the normal vector ?

for ( int i = 1 ; i < nodes.size(); i++ )
    {

    Vec2f diff =  nodes[i-1].m_Pos-nodes[i].m_Pos;

    float length = diff.length();
    Vec2f norm = diff.normalized();
    nodes[i].m_Pos+=(length - 5)*norm;

    }


texts: creating cartoon explosions like in jetpack squad

texts:
I followed this excellent tutorial for creating volumetric explosions: https://stevencraeynest.wordpress.com/2013/03/29/easy-volumetric-explosion-in-unity3d/

I get the explosions as the tutorial mentioned, however, I noticed that jetpack squad does a similar technique but has getting much nicer cloud formations.  My Question is, what kind of noise texture would I have to use to get a more cartoony explosion cloud like in jetpack squad vs the tutorial


texts:
First 2d game in Unity.
Started Character controller in C#.

Tried to get the character to move constantly right then once it hits the wall move left without needing any input from the player. Looked at a couple infinite runner character controller examples, but they seem to trick the character into thinking the player is holding down the right button in order to make the character run right infinitely "character.Move( 1, false , jump );".

Question: How to make the character start moving right automatically?


texts: Display musical symbol (unicode) in Text component not working?

texts:
I downloaded and specified to use a unicode font that supports musical symbols (Musica), but when I set the text value of the Text component to "" nothing is displayed? I tried using the unicode code point with \U as well. What is going wrong?
(I could not get TextMesh Pro working either with that symbol.)


texts: Loading a stream/asset on Android MonoGame without ContentManager

texts:
In the game I am developing, I have created a serializable class that generates a .map file for saving and loading levels. In XNA, this works great using the following code:

FileStream fileStream = new FileStream(filePath,
                FileMode.OpenOrCreate);
BinaryFormatter formatter = new BinaryFormatter();
MapInfo data = (MapInfo)formatter.Deserialize(fileStream);

Unfortunately, in android it appears that the filePath ends up at the device's root (argument being passed in as "Content/maps").
After some research, I came across this page from xamarin that explains how to properly load assets from the asset folder. However, this action takes place in a separate namespace from my main activity, and so far have not found a way to access the Assets.Open() function.

any other ways to load that asset?

UPDATE:
After playing around some more, I ended up trying to pass the Assets property of the main activity down through function calls, loading the file this way:

Stream fileStream = androidGame.Assets.Open(filePath);
BinaryFormatter formatter = new BinaryFormatter();
MapInfo data = (MapInfo)formatter.Deserialize(fileStream);

SADLY, the file still does not load. Looking at the variables in debug shows the correct address for the activity contained in the variable androidGame, but says Open is an "Unknown member"

UPDATE WITH WORKING SOLUTION:

In case anyone comes across file loading issues in Monogame Android, this is what I ended up doing:

First, make sure you copy/reference your files in the correct dir of your android build. This should appear somewhere under Assets/Content/yourfile.file or subfolder.

Then, check the properties of the file and select "AndroidAsset" for build options and "Copy if newer" for output.

Finally, open the stream using the Assets property of your main activity. This can be accessed using your Microsoft.Xna.Framework.Game class in this way:

Stream fileStream = Game.Activity.Assets.Open(path);

Turns out my issue was not the stream itself, but the deserialization which could not open a .dll in android (overlooked that one...). I ended up switching to XML serialization, since the binary serialization is build dependent