texts: Show Camera field of view in minimap but without y axis rotation

texts:
Here is the function to draw a triangle that represents the camera field of view in a minimap. The problem with this code snippet is that when I rotate up and down (Change the pitch of camera) the viewport triangle also rotates up/down.
void makeViewPortCube()
{
    if (player.GetComponent<Camera>() == null)
    {
        // Debug.LogError("Please assing a Main Camera to Follow");
        return;
    }

    if (viewPortMesh == null)
    {
        viewPortGameobject = new GameObject();
        viewPortGameobject.AddComponent<MeshFilter>().mesh = makeStartingMeshForViewPort(2.0f, 2.0f);
        viewPortGameobject.AddComponent<MeshRenderer>().material = materiaForViewPortGameobject();
        viewPortGameobject.name = "View Port Object";
        viewPortMesh = viewPortGameobject.GetComponent<MeshFilter>().mesh;
        viewPortGameobject.layer = LayerMask.NameToLayer("MiniMap");
        viewPortGameobject.transform.position = new Vector3(viewPortGameobject.transform.position.x, /*transform.position.y-*/100, viewPortGameobject.transform.position.z);
    }

    // change vertices of the viewport
    Vector3[] aVertexList = viewPortMesh.vertices;

    if (stopRotation == false)
    {
        //Orignial
        aVertexList[1] = player.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(Screen.width, 0, 10f));
        aVertexList[2] = player.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(Screen.width, 0, player.GetComponent<Camera>().nearClipPlane));
        aVertexList[3] = player.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(0, Screen.height / 4, player.GetComponent<Camera>().nearClipPlane));

        aVertexList[0] = player.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(0, Screen.height / 4, 10f));

        for (int i = 0; i < 4; i++)
        {
            aVertexList[i].y = 3;
        }
    }

    viewPortMesh.vertices = aVertexList;
    viewPortMesh.RecalculateBounds();
}


texts: How to extract data from a resource compiler script in c#

texts:
I need to know how to extract all data from a resource compiler script to a folder or the desktop.

the .res files are compiled and added to an exe file.

.res is the file extension.

and if that is possible I need to know how to re-pack the data after it's been changed.

The shorter answer I need to extract the data from a resource compiler script aka ".res" and then after data changed re-pack the data back into the ".res" file.


texts: Dividing properties between RigidBody and Collider

texts:
I am currently making a physics engine in Rust.

The 2 main data structures concerning collision detection are:

RigidBody: Physics-related aspects of the body. Contains a reference to a Collider structure.
Collider: Shape and structural-related aspects

However, I am unsure as to which data structure should store the instance fields:

mass (or inverse mass)
inertia (or inverse inertia)
angle of orientation
restitution

The reason for this absolute segregation is that during collision detection, only references to the concerning Colliders will be passed.

Could someone please advise me on the matter?


texts: Are the prefabs stored in RAM or in the Hard disk? (Unity3D)

texts:
I have many prefabs objects (65 MB) in an Unity3D project.

My game use 100 different levels with combinations of the prefab objects.

What is better create 100 scenes or create only one scene where the prefab objects are placed with data from a XML?.

Each Scene load your own prefab objects?

Are the prefab objects loaded in the RAM when the scene is loaded or are stored in the hard disk and then loaded in the RAM when come in the scene?


texts: How do I set a single pixel of an image in Slick2D?

texts:
I would like to set an individual pixel in Slick (i.e Image.setPixel(x, y, r, b, g)) but I can't figure out how.

There is an Image.setPixel function but it doesn't take x and y coordinates. Any ideas?


texts: I know that gameplay mechanics programmers, either directly working with source or with scripting are needed, however there are so many shaders written already that I would imagine you could find anything to meet the visual effects you are looking for, is this a fair assumption?


texts: Mathematics: matrix-to-quaternion conversion in left-hand coordinate system

texts:
I am implementing a typical skeletal animation system, and it requires the usage of quaternion to interpolate rotations between each poses. The asset I import only has a transform matrix for each joint, so I need code to convert a rotation matrix to a quaternion. However, my game is in left-hand system, and most code snippet online out there are for right-hand system only. I tried the code for such conversion in a right-hand system from this gamasutra post. The animation interpolates correctly in some cases, but most of the time it's not working correctly, and here's the symptom:

Say I am animating a guy, in the first key frame he is in bind pose, and in the second key frame he's supposed to raise his right arm by 30 degrees. If my system interpolates the rotation correctly, his arm would slowly raise up to 30 degrees in the interval, maybe first frame it's 10 degrees, then its 15 degrees, and eventually 30 degrees. However, with the code I have, the guy's arm is rotating the longest path. First frame, the guy's arm rotates -30 degrees, then -60 degrees, and comes to the same place to where 30 degree is. Can anyone give me the code snippet that's equivalent to the gamasutra one, but for left-hand coordinate system? Thanks!


texts: Tweaking incentives for lottery with a twist

texts:
I have been developing a game which is a lottery where your chance of winning is proportional to the square of your bet.

To prevent people from overbetting the pot (optimal strategy shouldn't just be to bet as much as possible, I think), and to make subsequent jackpots appealing, I've made it so the winner gets (current round bets + past round leftovers) / 2.  48% of the jackpot goes forward, and 2% of the jackpot goes to the house.

This is generally working, but when there are not many people on the site, one person will sit there and drain the pot every round with the minimum bet.

Though I think the concept is pretty cool, I have the feeling that some small tweaks could make a big difference.

Any ideas how to get the pot to grow as big as possible?

Apologies if this is not the right place to post.


texts: How to always land a square box in 90 degree

texts:
How can i Always Land a box in 90 degree

Here What i want

Here what i don't want

{
public Rigidbody2D boxRb;
public float jumpSpeed;
 public Vector3 rotation;
public float rotationSpeed;
public bool rotationEnabled;
public float gravityMultiplier;
void FixedUpdate()
{
    if (Input.GetMouseButtonDown(0))
    {
        boxRb.velocity = jumpSpeed * Vector2.up;
    }
    if (rotationEnabled = true)
    {
        transform.Rotate(rotation * rotationSpeed * Time.deltaTime);
    }
    if (Input.GetMouseButtonDown(1))
    {
        boxRb.velocity += Vector2.up * Physics2D.gravity.y * (gravityMultiplier - 1) * Time.deltaTime;
    }

}
void OnCollisionEnter2D(Collision2D collision)
{
    rotationEnabled = false;
    Debug.Log("Collided");
    rotationSpeed = 0f;
    boxRb.constraints = RigidbodyConstraints2D.FreezePositionX;
    transform.Rotate(0, 0, 90f);

}
void OnCollisionStay2D(Collision2D collision)
{
    rotationEnabled = false;
    Debug.Log("In collison");
    rotationSpeed = 0f;
    boxRb.constraints = RigidbodyConstraints2D.FreezePositionX;
}
void OnCollisionExit2D(Collision2D collision)
{
    rotationEnabled = true;
    Debug.Log("Free");
    rotationSpeed = 10f;
}

}


texts: How can I clamp the transform to a range?

texts:
I am trying to create a level editor in Unity.  When the position of an object is changed, I want that object to have its X and Y positions clamped between 1 and 10.  So if the position is changed to 15, it will snap back to 10; and if the position is changed to -5, it will snap back to 1.

I have tried using the OnValidate() method, but without success.  It snaps everything correctly when I reload the script (make a change to the script and reopen Unity), but it will not snap it on the fly.

void OnValidate(){
    float newX = Mathf.Clamp(child.position.x, 1, 10);
    float newY = Mathf.Clamp(child.position.y, 1, 10);
    transform.localPosition = new Vector2(newX, newY);
}

Any suggestions on how I can accomplish this?


texts:
I've recently solved the single selection problem but now I want to do multiple selections. I know I need to find two points with the mouse position to draw a box but it just won't work for me.

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            bool dragging = true;
            Debug.Log("Multiselect active");
            MultiSelect(dragging);
        }
    }
    private void MultiSelect(bool dragging)
    {

        mouseDownPoint = Input.mousePosition;
        if (Input.GetMouseButtonUp(0) && dragging)
        {
            mouseUpPoint = Input.mousePosition;
        }
        Debug.Log("First pos: " + mouseDownPoint + " Second pos: " + mouseUpPoint);
        dragging = false;

    }

What is a better way to achieve what I'm trying?
If someone can tell me a way that can also detect any units inside the area that'd be nice too.


texts: Mesh filter component is removed from prefab [Unity]

texts:
I am trying to procedurally generate a city with cubes. I generate the cubes' location, size and textures randomly with an external program and I save to a txt. I created a script in C# that loads that txt file and by instancing a "cube" (made of 6 quads) I generate the buildings. It is important to use these cubes since I can control what textures to use on each side. So far so good, the script runs at runtime (I know it is not the best thing to do) and saves these buildings as prefabs that I can see in the editor.
The problem comes when I want to control the tiling of the textures, since these are buildings, the amount of windows is proportional to the height of the building. I don't want to set the x-y scales of the textures because this creates a considerable amount of materials and affects the batching and performance in general.
What I thought was to instead of changing the material, it would be more efficient to change the mesh uv coordinates of each quad. But as soon as I barely access this component, the mesh filter component of the prefabs disappear.
This code below creates a "voxel" --cube formed by 6 quads--
cube = Instantiate(voxel);
cube.transform.parent = building.transform;
cube.transform.localPosition = something;
cube.transform.localScale    = something;
cube.transform.localEulerAngles = something;

and this below is what breaks the prefabs, note that I don't do anything yet with the mesh, just accessing it messes everything up.
If I comment the line with the mesh, everything is okay. But if I run it like this, in the game the cubes are visible, but when coming back to the editor, the quads in the saved prefabs lack of the mesh filter component and hence they are invisible.
for(int i = 0; i < 6; i++){
    child = cube.transform.GetChild(i).gameObject;  // this is the i-th quad
    Mesh mesh = child.GetComponent<MeshFilter>().mesh; // PROBLEMATIC LINE

    material = set_material(mat_name2[i]);
    child.GetComponent<Renderer>().sharedMaterial = material;
}
localPath = "Assets/Buildings/" + building.name + ".prefab";
PrefabUtility.SaveAsPrefabAssetAndConnect(building, localPath, InteractionMode.AutomatedAction);

As I explained, I need to modify the values of this mesh in order to efficiently control the tiling, this seems to be an impossible task. Since I don't even modify the values of this component, I feel like this is a very annoying bug, I don't see what is wrong with the code.
I have lost several hours trying to understand what is going on. Any help is appreciated!


texts:
I am about to upgrade to the last version of Cocos2d and would like to uninstall my current Cocos2d templates before installing the new one but cannot find the templates to delete.

I have looked at a number of web comments on this such as Uninstall Cocos2D ans another uninstall example but to no avail. However, I still see Cocos2d in my Xcode (4.5) framework. I have been searching my directories but cannot find it.

Is there anyone out there who can give me a hint where to find it so i can delete in?


texts:
For the GitHub Game Off Jam, I plan to create a small game with a boomerang. But I don't know how to build the equation that will update the boomerang position.

I try to build a direction vector and rotate it a little to each update. But it generate each time a circle.

Is a bezier curve a good alternative? Or is it too complex?


texts: How do you deal with loot in an RPG where all mosters drop their full inventory?

texts:
I currently have a system where both players and monsters in an RPG use equipment. This means that when an enemy is killed, I can technically drop everything they have. These are armor and weapons that players may choose to equip. This is fun for the first 5 times this happens(when the player is missing some equipment), then the inventory gets crowded with junk, and it's hard to figure out what's valuable and what's not. Most of the NPCs will lag behind player in terms of gear with the exception of bosses, who will have very good gear.

I've seen suggestions of using a "junk bag", where looted white/ gray equipment goes. Junk bag can be sold with one click.

I can think of two old school MMORPGs that had near full loot: Shadowbane and ultima Online. Both of these used disposable equipment that was easy to craft or "farm" from NPCs.

Recently the age of decadence, a PC RPG had a good full looting system where equipment could be broken down to get iron ingots and such and used in crafting. However, that game only has less than 100 enemies to kill and loot during the entire game, and had weight limit.

In my game there would be hundreds of enemies to kill in rapid succession, maybe 2-3 kills per minute. Another option is to abandon the full looting idea and only "drop greens, blue and purple items if the enemy had them.

In other words, how do you use or get rid of unwanted items when there is a lot of junk loot?


texts: Make a callback to android methods from libgdx

texts: How can I make a callback from libgdx to an Android method? I want to use the method to overwrite a file in the internal memory.


texts: How to draw a rotated pixel perfect line by hand?

texts:
If you have a pixel perfect line like 1:16 pixels, and you want to draw that same line rotated by a degree, for example 45°, what would be the correct way to do that by hand?

I know it should have something like n:n pixels, but 16:16 pixels just looks like it is to long to be the same line.

So what would the correct size would be for that pixel? And is there some kind of formula to calculate it with any degree?


texts:
I've got this NPC walking around and I'm trying to create a cone to represent their line of sight, including how it would be blocked by buildings, similar to how Nicky Case has implemented it as described here: https://ncase.me/sight-and-light/

My main problem with this, right now, is that it seems like I'm not detecting collisions between my 2D box colliders and Physics2D.Raycast when I would expect to much of the time. The green rays in the image below are NOT colliding (this is fine on the corners, I don't really care, but when the rays are going straight through walls, that's a big problem for me). Red rays are colliding.

Why aren't the Physics2D.Raycasts reliably colliding with the 2D Box Collider walls?

I believe everything is in the same z-plane and has the correct collision matrix in place.

![
]image of my NPC and raycasts from them at various points along their path

    List<UnityEngine.Vector2> endPoints = new List<UnityEngine.Vector2>();
    GameObject[] corners = GameObject.FindGameObjectsWithTag("verticies");
    //corners MUST BE WORLD-ORIENTED!

    for(int i = 0; i < corners.Length; i++) {
        UnityEngine.Vector2 corner = new UnityEngine.Vector2(corners[i].transform.position.x, corners[i].transform.position.y);
        RaycastHit2D endPoint = Physics2D.Raycast(this.transform.position, corner);
        if(endPoint.collider != null) {
            endPoints.Add(endPoint.point);
            Debug.DrawLine (this.transform.position, endPoint.point, Color.red);
        } else {
            Debug.DrawLine (this.transform.position, corner, Color.green);
        }
    }


texts:
Is there an algorithm to make ships take semi-circular patterns? I need something like the below image:

Big Blue- Command Ship
Small blues - fighters
Red lines - path of movement

I want the fighters to zip around the command ship while avoiding obsticles such as space debris and eachother. I need at most a dozen fighters zipping around each ship and there would be up to a dozen command ships zipping around at a slower pace. All the fighters should return to the ship every once in a while for repair and rearming.

I chiefly need the circular path and I need to keep the path centered constantly on the command ship despite any movements. Are there any circular path finding algorithms? (and a better question; is there an official term for this kind of algorithm/path?)? Also note that I am developing this as an RTS for mobile, so the least expensive the operation the better.


texts: Physical attributes as a function of age

texts:
My workerclass has physical attributes such as physical_fitness and sexual_fitness which are intended to be functions of their age (the attribute is, unsurprisingly, called age). When the class is initialized, the initial values of XYZ_fitness are computed by a randomized normal distribution.

In each game tick, worker's grow a year older. I want to appreciate/depreciate the values of their physical attributes such that, for example, they increase until they are at their maximum value around age 35, and decline with age after that. What is an efficient way of defining this function?

Would this involve something like running their age through a quadratic function with its maxima at the age value 35? I'm sure there's some elegant math/statistics here that's escaping me.


texts: Is there a way to setup an Android game project with a large assets during development to allow for fast testing/iteration?

texts:
I'm working on an Android port of an iOS game at the moment. I am using the Android NDK only (android_native_app_glue) in Eclipse (CDT + ADT). I am using the Android emulator, API 15 (but we are targeting API9+) as we do not yet have an Android device. The game has about 200-300mb of assets and I'm unsure of how to include them properly or how to get into a fast testing/debugging cycle with assets attached.

As it stands I am linking the assets folder in my Android project to the resources folder that contains the game assets. This works but the problem lies in the fact that when I build it takes about 9-10 minutes for the 200mb .apk file to be installed onto the emulator. This is simply unacceptable when things need to be tested quickly.

If I strip the assets out of the project, it installs very quickly. Because of this I am stripping out the bulk of the assets at the moment to do my testing but when it comes to the long run I need a better solution.

My question, is there a way to setup an Android game project with a large asset collection during development to allow for fast testing/iteration? E,g. fast deployment or updating of .apk to allow for quick testing.


texts: Can I release any sort of app or game on the PlayStation Store?

texts:
I'd like to develop a game, and try it out mainly on the Playstation 4.

Can I build any game, or app, and release it on the Playstation Store? Or does Sony only allow what it wants in the store, much like Apple and the AppStore? Note that I'm not asking how to build a game, but whether or not there are restrictions that would prevent me from releasing certain kinds of games or applications to the Store.


texts: Hide an image once all enemies in a zone are defeated

texts:
In my game there are several buildings that a main character has to free from enemies. I put a kind of a logo above all those have-to-be-released buildings, indicating that a certain building is not free and it has to be released.

What I want to achieve is that when I kill all of the enemies near a certain building, the logo above that building has to disappear, indicating means that the building was released.

I don't know how to detect this condition of "all nearby enemies defeated" in my script — how can I do that, and hide the image when the condition is met?


texts:
Here's the problem: I'm writing an Arkanoid-like game in Unity 5.3. I'm using 3D physics and simply ignoring z-axis in computations. No gravity, 0 drag and velocity reset every bounce by script. My ball has sphere collider and rigidbody with continuous dynamic collision detection on it, and bricks have box colliders with continuous detection. They are set like tiles, one by one, without gaps.

The problem occurs when a ball collides with two bricks at once, which causes a wrong bounce angle. Smaller sphere colliders makes this situation occur less often, but causes the ball to ignore collisions sometimes and phase through a single brick.

I know the probable reason for this bug, I think a collision with two objects affects ball physics twice. The question is: how to avoid it?


texts: What is a direction vector and why should it be normalized?

texts:
I've been trying to get the hang of vectors and I read Wolfire's blog about linear algebra and I seem to understand most stuff except when it comes to storing a direction as a vector and using it by multiplying the velocity by it. I know it has to be normalized (have a length of 1), but why does it have to be 1 specifically and how would I use it?

Also how would I represent it in 2D [x,y] coordinates. For example if I wanted a direction such as North-East?


texts:
I am creating an asset, in Unity, and I need to use System.Drawing. I have been trying to figure out how to add the DLL in a way that works, but I have had zero luck. I have tried adding the DLL to the assets folder, but it just shows up in Visual Studio as if it couldn't be found. I have also followed the instructions of a similar question, on the Unity Answers page, without any luck.

How do I use System.Drawing in Unity?


texts: How can I simulate shadows for a 2D top-down game?

texts:
I'm trying to simulate shadows for a 2D top-down RPG (in Python), but I can't think of the best way to do this

So far I've tried making copies of the original game entities and turning all opaque pixels black (which is a bit slow), then rotating them around the bottom of the original image... but i couldn't quite get that approach to work.

So how can I simulate this effect?


texts: My Directional light lights the floor of my cave but not the ceiling (concave mesh)

texts:
I am developing a small demo with Meshes created from a vertex map.

When i put a hole in the mesh (making it concave) the physics work fine but the directional lightning only lights one part of the concave park.

All of my mesh can receive and and cast shadow (so i should have self-shadowing) but it does not seem to work.

my directional light creation:

            var dirLight = new THREE.DirectionalLight( 0xffffff, 1 );
            dirLight.position.set( -50, 50, 1 );
            dirLight.position.multiplyScalar( 50);
            dirLight.name = "dirlight";
   dirLight.castShadow = true;
            dirLight.shadowCameraVisible = true;
   dirLight.shadowDarkness = 1.0;

my shadow settings:

   renderer.setSize( window.innerWidth/1, window.innerHeight/1 );
   renderer.shadowMapEnabled = true;
   renderer.shadowMapSoft = true;

   renderer.shadowCameraNear = 3;
   renderer.shadowCameraFar = camera.far;
   renderer.shadowCameraFov = 50;

   renderer.shadowMapBias = 0.0039;
   renderer.shadowMapDarkness = 0.5;
   renderer.shadowMapWidth = 1024;
   renderer.shadowMapHeight = 1024;

Finally my mesh creation code:

var newGeometry = new THREE.Geometry();
for (var i = 0; i < rawGeometry.vertices.length; i++) {
  newGeometry.vertices.push(new THREE.Vector3(rawGeometry.vertices[i][0], rawGeometry.vertices[i][1], rawGeometry.vertices[i][2]))
}
for (var i = 0; i < rawGeometry.faces.length; i++) {
  newGeometry.faces.push(new THREE.Face3(rawGeometry.faces[i][0], rawGeometry.faces[i][1], rawGeometry.faces[i][2]))
}

newGeometry.computeFaceNormals();
;

var color = rawGeometry.color;
var newMesh = new Physijs.ConcaveMesh(newGeometry, new THREE.MeshLambertMaterial({
  color: color
}), 0, 50, 50);
newMesh.position.x = location[0];
newMesh.position.y = location[1];
newMesh.position.z = location[2];

newMesh.castShadow = true;
newMesh.receiveShadow = true;

this.Chunks[chunkIndex[0]][chunkIndex[1]][chunkIndex[2]][typeIndex] = newMesh;

scene.add(newMesh);


texts:
I am trying to create a bounding box for my sprite using box2d, but the box is being created at the wrong spot. I followed a tutorial on the wiki using this code

    BodyDef bodyDef1 = new BodyDef();
    bodyDef1.type = BodyDef.BodyType.DynamicBody;
    bodyDef1.position.set(player.getX(), player.getY());
    playerBody = world.createBody(bodyDef1);
    PolygonShape square = new PolygonShape();
    square.setAsBox(player.getWidth() / 2, player.getHeight() / 2);
    FixtureDef fixtureDef1 = new FixtureDef();
    fixtureDef1.shape = square;
    fixtureDef1.density = 0.1f;

Player is a just the sprite that I am trying to create the box around.


texts:
I have a inventory and I need to add a hotbar to access certain items.

What this hotbar needs to do is when in the inventory "Menu" you add items to it and when you close the menu the hotbar moves to the bottom of the screen and you select and item, weapon, food ect, and can use it (like in Minecraft).

My problem is I don't know whether I should:

Keep track of which items are in hotbar "spaces" of the inventory and use them accordingly, or
Make a separate list for hotbar items and move them between the inventory and hotbar lists when needed

or a third way I did not even think of.

My inventory works by having items in a list. The item class has values such as dmg, uses, name, etc. I have an item data class I put on GameObjects that has a public item variable. I have an inventory UI class that takes the inventory list and displays them.


texts:
Very simple question. With C++/Direct9, I'm creating a texture as RenderTarget with a full screen quad, creating a scene, setting a HLSL pixel shader, copying the image and then call Present.

1) How does the shader's input texture get defined? Does it get configured automatically, and if so how? Let's take this very basic sample shader.

sampler2D TexSampler : register(S0);

float4 main(float2 uv : TEXCOORD) : COLOR
{
    float4 color = tex2D(TexSampler, uv);
    return float4(1 - color.rgb, color.a);
}

2) Where in the chain does the shader's magic get applied? Somehow it's not being applied and I don't know where to look.

3) What about shaders that take 2 textures as input, how do I configure the input?

sampler s0 : register(s0);
sampler s1 : register(s1);
float4 p0 :  register(c0);
float2 p1 :  register(c1);

#define width  (p0[0])
#define height (p0[1])
#define px (p1[0])
#define py (p1[1])

When creating the pixel shader, I get a PixelConstantTable that allows me to define C0 and C1, and how do I feed in all the other information?

I'm trying to make the question as basic as possible to get a quality answer. I found PSSetShaderResources in DX11 which seems to be getting close but what's the equivalent in DX9?

Thanks!

Edit: Is it possible that DirectX9 doesn't support passing multiple textures in such a way, and that DirectX11 would be required?


texts: How do you handle loss aversion in probability-based games?

texts:
The psychological phenomenon of loss aversion refers to how players feel losses twice as powerfully as victories.

For example, Bite Fight's PvP is a simulation based on probabilities related on character skills, and players voice this feeling many times per week in the community forums.

If you don't want to create a pay-to-win game, but you do want to let the worst players win often enough to feel good about it, how can you do that?

The question has two parts:

How do you handle it technically? Do you use some kind of math techniques or a memory based simulation to avoid many loses in the row for a certain player?
How do you handle it from the community point of view? What do you do about complaints like this on public forums?


texts: What's the best way of transforming a 2D vector into the closest 8-way compass direction?

texts:
If you have a 2D vector expressed as x and y, what's a good way of transforming that into the closest compass direction?

e.g.

x:+1,  y:+1 => NE
x:0,   y:+3 => N
x:+10, y:-2 => E   // closest compass direction


texts: Tagging "regions" in rot.js map generator

texts:
I'm working on a small roguelike and I'd like to be able to tag the various "regions" generated via the Map generators so that I can use it as a lookup to environment descriptions.  I see that there are "Rooms" that are generated in the dungeon generator algorithms, however I didn't really see anything similar in say, the cellular automata generator.  Is there a way to leverage the generator in rot.js, or am I stuck with manually determining if I'm in a particular open area (and breaking encapsulation of internal, private variables along the way)?
Basically, I'd like to be able to link up my player's location to the text you see at the bottom of , but can't seem to figure out how to do it generically.  I'm fairly certain I could use the 'Rooms' object in the first 2 screenshots, and everything else is a hallway, but I'm not clear on how I could get a particular 'region' in a cellular automata generator (or one of the maze generators, for instance).


texts: How to rotate a local position offset based on a direction vector?

texts:
I'm trying to fire three raycasts in the direction of movement, from offset starting points. I'm having trouble calculating the start positions of the rays based on the direction.

As you can see in the animation, the three parallel lines in the middle overlap when moving upwards using the code below, but I want them to remain evenly spaced.

I cannot use transform.right (up/etc) etc because the transform is always facing the same direction by design. Instead I am using the currentDirection which is the normalized last movement velocity.

I want the lines to always be evenly spaced based on the direction the object is moving without rotating the actual transform - the problem is I don't know the math behind it and have spent last several hours trying to figure it out.

Current code:

Debug.DrawRay(this.transform.position, currentDirection * (avoidObjectsScanDistance + 0.05f), Color.blue, 0.09f);
Debug.DrawRay(this.transform.position + new Vector3(0, 0.1f, 0), currentDirection * (avoidObjectsScanDistance + 0.05f), Color.magenta, 0.09f);
Debug.DrawRay(this.transform.position + new Vector3(0, -0.1f, 0), currentDirection * (avoidObjectsScanDistance + 0.05f), Color.blue, 0.09f);

I've tried to get the position based on direction by using

var drawRayTopPos = currentDirection * localpos + position;


texts:
I am using Nifty in JME SDK to make different screens. I stuck in this problem that nifty doesn't refresh its design preview to reflect any changes in xml.

But this works:
If I close .xml and reopen it changes are refreshed.

Its impractical and annoying to close/open xml each time to view changes in design. So if anybody know any patches or method to reflect changes in design as soon as we make changes in xml, it would be great.


texts:
I would like to listen for an event that some asset (prefab, precisely) has been modified. To my surprise, there's no such event in AssetModificationProcessor.

Is there any way to do this in Unity?


texts: How to make a Sprite using CoreGraphics iOS - Cocos2d-iPhone

texts:
I'm trying to make a sprite that uses the graphics that are made with core graphics.   I cant seem to find anything to explain how to make shapes using core graphics to create a sprite to use in cocos2d-iPhone.

Thanks for any insights and help!


texts: How to select an image on the J2ME Canvas

texts:
I am working on J2ME. I have got a canvas, with a layout of a Checkers board. At the position of pieces, I have placed images. The point at which I got stuck is, how to select/highlite a piece's image for a move. I can't figure out the appropriate commandListener and how to handle this keyPressedEvent.
I understood the logic of this game from:
Draughts AI

Any suggestions?


texts: FlxSprite ignore camera follow in flixel

texts: I am using flixel v2.5 and am using FlxG.camera.follow to get the camera to follow the player. I have a background FlxSprite that I don't want to move with the camera. Is there a way I can set this FlxSprite to stay in the same place on the screen? I would also like to have a GUI HUD that stays fixed to the screen, and was thinking I could do this the same way.


texts: Vertices displaced when smoothing in Maya

texts:
The issue below appears when smoothing in maya. I would prefer to solve the problem normally as opposed to import/export obj.

Below the image is a .ma file you can download yourself.

File: https://www.dropbox.com/s/nhtc1uj2lvakjwf/reload.ma?dl=0

Steps Taken To Isolate Problem

-Issue does not occur when doing a smooth mesh preview with the EXCEPTION of 1 face

-Deleted face. Error moves up another face.

-Continued to delete the face ring one face at a time and noticed the error moves up.

-Selected face ring, delete and rebridged. Fixed.

-Infered that the root cause of the problem has something to do with the way I created face ring or edge ring.

-The issue only occurs in this one mesh object.

-Deleted all items in the scene except the problem mesh and saved an isolated file.

-Deleted UVs.

-Deleted history.

-Optimized scene.

-Cleaned mesh with the following settings.

-Select matching polygons.

-Apply to selected objects, Keep Construction History.

-Lamina faces.

-Nonmanifold geometry, Normal and geometry.

-Merged all vertices with a tolerance of 0.01.

-Unlocked normals.

-Ensured normal directions were correct.

-Ensured there were no faces inside of edges.

-Issue ONLY occurs with 1 subdivision.

-Hardened all the edges.

-Exported and reimported OBJ. Again, I do not want the lazy solution, I want the correct one. I did this so I can infer that the root cause is not mesh-related.

-Combined with cube

-Deleted history (again)

-Optimized scene (again)

-Cleaned mesh (again)

Specs

Maya Version: Maya 2016.5 Ext 2 (64bit)

OS: Windows 10 Pro (Build: Latest)

Video Card: Nvidia GeForce 980 X (Driver: Latest)

CPU: Intel Core i7 3930K

Mirror Threads

http://polycount.com/discussion/198641/maya-2-vertices-displaced-when-smoothing/p1?new=1


texts: How can I find and get all enabled cameras and switch between them?

texts:
I have 5 cameras in the scene.
In the Inspector I added to the cameras array 3 cameras.
In the script I store this cameras using storedCameras array.
In cameras array there are 5 cameras.

I added a flag allCameras to change between the stored cameras mode and all cameras mode.

And I'm using the G key to switch between the cameras either the stored or the all cameras.

But when I press on G I see in the Inspector that each press on G remove one camera from the array cameras in the end I left with one camera.
And the idea is to press G and switch between the cameras either if it's on stored cameras mode or all cameras mode depending on the flag.

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

public class SwitchCameras : MonoBehaviour
{
    [Header("Cameras Init")]
    public Camera[] cameras;
    public Vector3[] originalPosition;
    [HideInInspector]
    public Vector3 currentCameraOriginalPosition, currentCameraPosition;
    public bool allCameras = false;
    private Camera[] storedCameras;

    [Space(5)]

    [Header("Cameras Switch")]
    public string currentCameraName;
    public Vector3[] lastCameraPosition;

    private int currentCamera = 0;

    void Start()
    {
        storedCameras = cameras;

        if (allCameras == true)
        {
            cameras = new Camera[Camera.allCameras.Length];
            cameras = Camera.allCameras;
        }

        lastCameraPosition = new Vector3[cameras.Length];

        if (cameras.Length >= 1)
        {
            originalPosition = new Vector3[cameras.Length];
            for (int i = 0; i < cameras.Length; i++)
            {
                originalPosition[i] = cameras[i].transform.position;
            }
        }

        if (cameras.Length == 1)
        {
            Debug.LogError("Need more then 1 camera for switching..");
        }
        else
        {
            Debug.Log("Found " + cameras.Length + " cameras");
        }

        for (int i = 0; i < cameras.Length; i++)
        {
            cameras[i].enabled = false;
        }
        cameras[0].enabled = true;
        currentCameraName = cameras[0].name;
        currentCameraOriginalPosition = originalPosition[0];
    }

    void LateUpdate()
    {
        if (allCameras == true)
        {
            cameras = new Camera[Camera.allCameras.Length];
            cameras = Camera.allCameras;
        }
        else
        {
            cameras = new Camera[storedCameras.Length];
            cameras = storedCameras;
        }

        if (Input.GetKeyDown(KeyCode.G))
        {
            cameras[currentCamera].enabled = false;

            if (++currentCamera == cameras.Length)
                currentCamera = 0;

            cameras[currentCamera].enabled = true;
            currentCameraName = cameras[currentCamera].name;
            currentCameraOriginalPosition = originalPosition[currentCamera];
        }

        lastCameraPosition[currentCamera] = cameras[currentCamera].transform.position;
        currentCameraPosition = lastCameraPosition[currentCamera];
    }
}


texts: Clones size is bigger than the original?

texts:
I'm trying to clone items inside array. But the clones i'm getting is bigger than the original one!! Also, after couple of second the script is missing/removing some clones !!
Update 1:
I'm working on puzzle game such as "Candy Crush". Now I have my items to fill inside sorts"dots". What script should do, Clone my items and insert them on sort place. What happen is I get the size bigger than the original one. and after seconds script is missing/removing some clones from "Clone_Ghost" !!
public GameObject[] Items; // 4 elements
public GameObject[] dots; // where to place my clones
public GameObject ClonePlace; // hold inside canvas
public GameObject[] Clone_Ghost; //

void Start()
{

    Clone_Ghost = new GameObject[dots.Length];

    for (int i = 0; i < dots.Length; i++)
    {
        Clone_Ghost[i] = Instantiate(Items[Random.Range(0,3)], dots[i].transform.position, dots[i].transform.rotation);
        Clone_Ghost[i].transform.parent = ClonePlace.transform;
    }

}

Update:
Add this line at end to solve the scale problem.
    Clone_Ghost[i].transform.localScale = new Vector3(1, 1, 1);

and about the "missing/removing" is because another script that work to destroy matches items.


texts:
Recently  I'm  working on a PAC-MAN clone.

I created  3 classes:

StartingClass which extends Jframe and uses  KeyListener
Board which  extends Jpanel
Sparx which is responsible for changing the player's  sprite  coordinates.

The result is a frame with an unmoving image.

I changed  the  code  in various  ways  but  the  result  was  always  the  same (well sometimes even worse).

On zetcode.com,  kilobolt.com  and a  few  other  webpages I found some  source  code which works on some  other  concepts, but  still  I don't know how to fix my code.  I'm  sure  that  I'm missing something  obvious. Could you tell  me  what  is  wrong with my repaint  method?

Here's  my  sourcecode

StartingClass

public  class  StartingClass extends  JFrame  implements  KeyListener, Runnable{
public  StartingClass(){
       board=new  Board();

       add(board);

       sparx=new  Sparx();
}

public  static  void  main(String[]  args) {

       new  StartingClass();

}

@Override public  void keyPressed(KeyEvent  arg0) {

       switch(arg0.getKeyCode()){

       case  KeyEvent.VK_UP:

       sparx.moveUp(); break;

       case  KeyEvent.VK_DOWN:

       sparx.moveDown(); break;

       case  KeyEvent.VK_LEFT:

       sparx.moveLeft(); break;

       case  KeyEvent.VK_RIGHT:

       sparx.moveRight(); break; }

}
@Override public  void  run()

{ while(true){

       sparx.update();

       board.repaint();

       try  { thread . sleep (17) ;

        }  catch  (InterruptedException  e)

       { //  TODO  Auto-generated catch block e.printStackTrace();

}

}

}

}

Board

public  class  Board extends  JPanel{

       Sparx sparx;

       public  Board(){

              sparx=new  Sparx();

}

@Override public void paintComponent(Graphics g) {

       g.drawImage(sparx.getSparx(),  sparx.getSparxX(),  sparx.getSparxY(), null);

 }

}


texts: When a quest is completed in my game, money gets re-set rather than added

texts:
I have two quests in the game I am trying to create and each of the quests gives 50 coins if the quest is completed successfully and when I finish the first quest, I am given 50 coins and all is cool!

There's a problem when I complete the second quest: it has to give me additional 50 and overall I have to have 100 coins. However when I complete the second quest, it, kind of, regives me 50 coins and overall I have 50 coins but it has to be 100.

Here is the code I am using:

The fragment of quest 2 and 1 script since they are identical
------------------------------

 void OnTriggerStay(Collider col)
    {

        if (col.tag == "Player" & Input.GetKeyDown(KeyCode.E))
        {
            Money.MoneyAmount = +50;//here I am trying to reference Money class
            exclamation.SetActive(false);

            if (TextBoxOnCheck == 0)
            {
                BaseQuest.QuestNumber = 0;
                TextBoxOnCheck = 1; //Sets the variable to turn the box off
                MessageBox.SetActive(true); //Re-enables the box

                TextBox.GetComponent<Text>().text = "Local rezident: Thank you a lot"; //changes the message
                QuestText.SetActive(false); // input the quest name

The money class handles adding coins to UI text
-----------------------------------------------

public class Money : MonoBehaviour {

    public static int MoneyAmount;
    public int InternalMoney;
    public GameObject MoneyDisplay;
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        InternalMoney = MoneyAmount;
        MoneyDisplay.GetComponent<Text>().text = "" + InternalMoney;
    }
}


texts: How do I pack my game LWJGL game into a single executable JAR with Maven?

texts:
I am trying to use Maven to manage building my LWJGL projects. The entire project needs to be packed into a single executable jar, dependencies, natives and resources included, so that can be easily distributed. I have been using JarSplice to do this until now.

Is it possible to do the same with Maven?

My attempts thus far have failed: either the main class/natives could not be located or OpenAL would crash when I tried to execute the jar file.

My current pom.xml is below:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<groupId>Sidian</groupId>
<artifactId>LWJake2</artifactId>
<version>0.1</version>
<packaging>jar</packaging>
<name>LWJake2</name>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <mainClass>Main</mainClass>

    <lwjgl.version>2.9.3</lwjgl.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.lwjgl.lwjgl</groupId>
        <artifactId>lwjgl</artifactId>
        <version>${lwjgl.version}</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <showDeprecation>true</showDeprecation>
            </configuration>
        </plugin>
    </plugins>
</build>


texts: Unity - how to put a target under a character's feet that follows ground model contours?

texts:
In my current projects, one of the power-ups needs to place a target marker centered on the position of the player triggering it - the actual design for this is TBC, but will be a circle with a radius of 10 units.

The ground for the playing arena is a model, and not flat. Assuming that I use a texture to show this target area, how can I have this texture render following the contours of the ground?

Alternatively, any other approach to solving this would be appreciated.

Thank!


texts: client - server position syncronization in flash

texts:
I trying implement client - server position syncronization. Every 20 game ticks i sending to flash client correction of player position... and it always wrong on client, flash always cant predict player position. I think it due to different frame rate or different time on server and client (server is running on 30 fps when client on 60 fps).

Take a look here. How can I implement so precise player movements like they did? Any suggestions?


texts: When I want to use texture atlasing, should I try to place all of my sprites into one single texture atlas?  Or are there times when I should have multiple smaller texture atlases?


texts: Hide movieclip parts that are out of bounds

texts: I'm making a game where one takes a picture of their face to use on a character.  I have them zoom in on the picture, but the bitmapdata extends out of its movieclip.  How do I assign bounds to my bitmapdata?


texts:
I want to play 360 video in skybox. Is there any direct way avaiable to do this task. One long, boring, inefficient  procedure which seems that

Convert 360 to frames
Convert frames into cubmap
Use that cubeMap in skybox and Programatically change it's textures(Frame) quickly so that video effects shown

This is the long task which seems to me possible but is there any other way available?


texts:
In my Libgdx project i need to handle several types of inputs.

In particular these input events are needed in order to interact with the Actors that the user puts in the Stage.

The possible interactions are:

1) Drag And Drop with DragAndDrop class.

2) Rotate the Actor (90 degrees clockwise each time)

3) Remove the Actor

I thought that i could rotate the Actor with a simple click (touchDown), and remove the Actor with double tap, but this strategy gives rise to some issues.

1) When the user does double tap on the Actor, before the Actors gets removed it rotates 2 times.

2) If the user wants to drag and drop the Actor, when he clicks on the Actor it rotates.

Then, i thought that i could rotate the Actor in the touchUp method, only if the current position of the Actor is the same as before in order to avoid to rotate the Actor when the user just want to move it.

This gives rise to another problem. In order to detect the double tap, i need to implement GestureListener interface that does not have the touchUp method!

I could remove the actor when the user does long press on it, but this will be a game that will require fast interaction.

So.. i need your help, any kind of help, thank you very much!


texts:
For the past 8 years, I've been working on a Pokémon fan-game. It's been awesome, well-received by players, and I'm very proud of the community we've built. But, as with all things "fan-game", there's always that looming grey cloud of "will a C&D arrive tomorrow?"

Now, I've taken some steps to ensure we're as respectful as possible towards Nintendo's property:

We stay as true as possible to the source material. While we have added our own variants and original characters ("Fakemon"), we've made great efforts to keep them consistent.
We make it clear that we are a fan-game, not affiliated with Nintendo, and that it is entirely unofficial. I also include a link to a shareholder Q&A (Q14) where Satoru Iwata confirmed that they are not interested in treating people like myself as criminals.
Our game concept is original. It's not a clone of any existing game, and I like to think it fills a nice little hole for fans of the series.
I (briefly) met C-level people from Game Freak and Nintendo, including Junichi Masuda and Tsunekazu Ishihara, and given them "business cards" for our game. However, it wasn't a formal meeting, rather they were signing autographs at the Pokémon World Championships, so for all I know I was probably just some fan and they didn't pay much attention to the card (they've got enough to do already, right?)

But, all that being said, we're still unofficial, using intellectual property that doesn't belong to us.

My friend and I quit our jobs to work on this game full-time. If we do get shut down, we're going to have to seriously struggle to put our lives back together. So for now, the game has mostly been kept "under the radar", with basically zero marketing and only word-of-mouth of players to keep it populated.

The biggest thing here is that I want to give back to Nintendo. Thanks to them, and to my project, I've made incredible progress as a developer, designer and just as a person in general.

As mentioned earlier, my biggest fear is that one day they'll shut us down. And we'd have no choice but to do so. But it's been 8 years now...

So I'm trying to figure out what options I have, if any. I think what I want to do is to reach out and ask about some kind of licensing, but I don't want to draw too much attention. I don't want to lift my head over the parapet only to have it blasted off, you know? I'm not looking for Pokémon GO levels of attention, or even Magikarp Jump. (Our single server would melt either way - I'm working on it!) Just some way of having actual "permission" to do what I'm doing.

I expect the answer will probably be along the lines of "IANAL, get one", but what kind of lawyer would be best? And any insights or advice besides that would be helpful too.


texts: From simple physics with a ball, to a more complicated shape

texts:
Hello fellow game devs and stack overflowers...

I recently made a transition from OpenGL ES 1.1 to 2.0 (on Android via NDK) and things are going well so far. I'm working on doing a dice rolling application (gaming dice up to 20 sided, not just regular 6 sided die) as a way to learn more about how physics is implemented in a gaming environment.

I've explored implementing existing engine options (such as Bullet) and I don't think I need to implement something quite so sophisticated. I've found several tutorials that handle a lot of the general physics involved with initial trajectory, velocity, angle of contact and reflection angle, etc. I'm confident that I'd be able to implement ball-like behavior without much trouble.

My question lies in when I attempt to make the interaction of the die shape with another surface more "realistic," for example... the die strikes the floor surface at such an angle where only one corner makes contact with the floor. In my mind, the center of gravity of the object would play a part in determining how the die bounces away, possibly even spinning it it faster, etc... but I am not sure what the actual math involved is.

Are there any recommended resources for getting into this level of detail? Initial searches haven't turned up much...

Thanks to everyone in the community,
-Jeremiah


texts: Unity won't compile project successfully

texts:
I am trying to build the project into a Web GL, but it throws 3 errors when it reaches the "Building additional assets" stage.

Error 1
Building - Failed to write file: resources.assets
UnityEditor.HostView:OnGUI()
Error 2
An asset is marked with HideFlags.DontSave but is included in the
build: Asset: 'Library/unity editor resources' (You are probably
referencing internal Unity data in your build.)
UnityEditor.HostView:OnGUI()
Error 3
Error building Player: Couldn't build player because of unsupported
data on target platform.

Things to note:

I do not use NGUI or any other third-party GUI solution, but Unity's
new UI system
I have tried versions 5.2.3 and higher and it still has returned me
errors
I have one DLL LitJson that is used to parse JSON files
Project includes StreamingAssets and Resources folders
Error occurs even if I try building on other platforms such as
Windows. Same errors are returned
I am using a custom font downloaded online
Blacksmith's Character "Challenger" is also included
I thought the project folder has been corrupt so I decided to migrate
all assets to a clean project. No changes

Any idea how do I fix these?
Thanks in advance!


texts:
I can't figure out how they are used, how to actually use them, or what they are meant for. I would have thought I could assign blocks or colour palettes to a layer...turn it off and temporarily hide/delete it while I work with specific sections etc. I'm clicking around and highlighting and trying to get it to work but all I can do is assign the entire box of voxels to 1 layer and turn that on/off.

I've been unable to find any documentation explaining how to use the layers.


texts: Physics in carrom like game using cocos2d + Box2D

texts:
I am working on carrom like game using cocos2d + Box2D. I set world gravity(0,0), want gravity in z-axis. I set following values for coin and striker body:

Coin body (circle with radius - 15/PTM_RATIO):

density = 20.0f;
friction = 0.4f;
restitution = 0.6f;

Striker body (circle with radius - 15/PTM_RATIO):

density = 25.0f;
friction = 0.6f;
restitution = 0.3f;

Output is not smooth. When I apply ApplyLinearImpulse(force,position) the coin movement looks like floating in the air - takes too much time to stop.

What values for coin and striker make it look like real carrom?


texts:
I am trying to find angle between vectors a and b. But the cosine for some reason is not within +/- 1, that means that it is not possible to find an angle between a car and a pedestrian...

Any help appreciated

EDIT I have rewritten my function in accordance with the answer below (I had to do some changes due to writing in Python, for example pedestrian.body.position is equivalent to body.GetPosition()

I also tried to normalize both vectors, but the cosine is still not within +/- 1
And the car can move in both direction, so I do not know how to get its other component...

    def detect_pedestrian(car,pedestrian):
        #Find a vector which connects pedestrian with a car
        pedestrian_position = pedestrian.body.position
        car_position = car.body.position

        #Find vectors a and b
        car_vector = Box2D.b2Body.__GetTransform(car.body).R.GetYAxis()
        pedestrian_vector = pedestrian_position - car_position

        #Calculate magnitudes of both vector
        pedestrian_vector_magnitude = np.linalg.norm(pedestrian_vector)
        car_vector_magnitude = np.linalg.norm(car_vector)

        #Normalize both vectors
        pedestrian_vector_normalized = pedestrian_vector/pedestrian_vector_magnitude
        car_vector_normalized = car_vector/car_vector_magnitude

        #Calculate angle
        magnitudes = pedestrian_vector_magnitude * car_vector_magnitude
        dot_product = b2Dot(pedestrian_vector_normalized, car_vector_normalized)
        cosine = magnitudes/dot_product
        arccos = np.arccos(cosine)

        print(cosine)

```


texts: Using XNA's XML content pipeline to read arrays of objects with different subtypes

texts:
Using XNA's XML content importer, is it possible to read in an array of objects with different subtypes?

For instance, assume these are my class definitions:

public abstract class MyBaseClass
{
    public string MyBaseData;
}

public class MySubClass0 : MyBaseClass
{
    public int MySubData0;
}

public class MySubClass1 : MyBaseClass
{
    public bool MySubData1;
}

And this is my XML file:

<XnaContent>
    <Asset Type="MyBaseClass[]">
        <Item> <!-- I want this to be an instance of MySubClass0 -->
            <MyBaseData>alpha</MyBaseData>
            <MySubData0>314</MySubData0>
        </Item>
        <Item>  <!-- I want this to be an instance of MySubClass1 -->
            <MyBaseData>bravo</MyBaseData>
            <MySubData1>true</MySubData1>
        </Item>
    </Asset>
</XnaContent>

How do I specify that I want the first Item to be an instance of MySubclass0 and the second Item to be an instance of MySubclass1?


texts:
I have currently have a path that wraps around a Sphere from one side to another - this is basically a 3D highway in the sky type object that is a textured road.  I have an Aircraft model that I can get to follow this path, however I'm having trouble getting it to rotate correctly so that it is parallel to the surface of the globe

Using the following code:

this.transform.forward = Vector3.RotateTowards(this.transform.forward, this.transform.position - TargetWaypointPos, Airspeed * Time.deltaTime, 0.0f);

this.transform.position = Vector3.MoveTowards(this.transform.position, TargetWaypointPos, Airspeed * Time.deltaTime);

This gets the plane to correctly face the next waypoint and follow the path, however I cannot get it to rotate correctly in the Z-space to be parallel to the path/globe.  I can compute the correct angle by:

Vector3 yAxis = this.transform.position;
yAxis.Normalize();
Vector3 zAxis = nextPoint - this.transform.position;
zAxis.Normalize();
xAxis = Vector3.Cross(yAxis, zAxis);
xAxis.Normalize();
float angleZ = Vector3.Angle(Vector3.right, xAxis);

However attempting to apply this to my model in any way appears to ruin the Vector3.RotateTowards logic.  I must be missing something simple to combine these two.

Any ideas?  I'm new to Unity, still figuring out all the available options.


texts: I have a basic prototype working with health, resources and units. The problem is: How do I select multiple units? I have an idea of making an rectangle which dynamically extends with the mouse position. I think I need to convert this rectangle to transparent rectangle.


texts:
I am making a 2d platformer where the player can press a button, and restart the level, only their previous character will also run the level at the same time, like they are traveling back in time.

I know other games have done this before, and the way I have thought of doing it is to make the game character have a set of actions (Idle, Jumping, Walking Left etc.) and then detect changes in those actions and log them into a list along with the game time. So then when I need the character to run the level again on its own, I can just go through the list changing its actions at the right time.

Is this the best way to do it? Does anyone have any experience in this?

Thanks.


texts:
I intended to use jbox2d for my project. But as I went deeper into it's manual I'd found out that it supports dynamic objects between 0.1 and 10 meters (if use scaling and assume that 0.1 is smallest unit we would have 100 units). I want to create pretty complex and big shapes about 1000 units width.

So will box2d will handle it?
Or I should simplify them more to achieve 100 units width max?
Or my calculations about 100 units width max are wrong? ( But if 0.1 meter is box2d minimum I don't think than I can get smaller unit as measure.)

I had also read about kollider2d, but can't find any info about stress testing it.

As in comment below:

I understand that it doesn't matter if 32 pixels of my system represents 0.1 meter of box2d system nor if it is 50 pixels. With good scale I can manage any value as minimum. I wan't to create objects 1000 times larger than smallest one. And I don't know if box2d will crash or try to handle it but will be very slow or inaccurate.


texts: Trouble creating a "Game Log" for a text-based RPG

texts:
I've made significant progress porting my game from print-output to Pygame over the last few days, and I think I'm almost there!

Unfortunately, I'm beginning to suspect one of the methods I'm using to display my output is deeply flawed when it comes to what I eventually want it to do.

My goal is to create a "Game log" that displays the output from the most recent actions the player has taken.

For example, if the player entered a cabin, searched the cabin, then picked up the key they found there, I would like the gamelog to display

You enter the cabin

You find a Rusty Key

You take the Rusty Key

Currently, any time the gamelog updates, it replaces the previous output. This poses several issues:

1.) In a game of this style, a player can easily forget what the last few things they've done are. Not being able to see recent actions can be tedious and annoying to the player.

2.) The method I use to allow players to check their inventory works through a for-loop. With the way the gamelog works right now, only the most recently picked up item will display.

3.) In some situations, the info I need to display in this output is contained in a set. This system for displaying output can not take sets as an argument.

The code below is what I'm using to generate the output. This comes from this set of functions called "Pygame_Functions"

https://github.com/StevePaget/Pygame_Functions

which has been quite helpful.

I'm beginning to think that this may not be the best way to achieve what I'm trying to do. It seems like this is only really effective for rendering a singular message.

class newLabel(pygame.sprite.Sprite):
    def __init__(self, text, fontSize, font, fontColour, xpos, ypos, background):
        pygame.sprite.Sprite.__init__(self)
        self.text = text
        self.fontColour = parseColour(fontColour)
        self.fontFace = pygame.font.match_font(font)
        self.fontSize = fontSize
        self.background = background
        self.font = pygame.font.Font(self.fontFace, self.fontSize)
        self.renderText()
        self.rect.topleft = [xpos, ypos]

    def update(self, newText, fontColour, background):
        self.text = newText
        if fontColour:
            self.fontColour = parseColour(fontColour)
        if background:
            self.background = parseColour(background)

        oldTopLeft = self.rect.topleft
        self.renderText()
        self.rect.topleft = oldTopLeft
        updateDisplay()

    def renderText(self):
        lineSurfaces = []
        textLines = self.text.split("<br>")
        maxWidth = 0
        maxHeight = 0
        for line in textLines:
            lineSurfaces.append(self.font.render(line, True, self.fontColour))
            thisRect = lineSurfaces[-1].get_rect()
            if thisRect.width > maxWidth:
                maxWidth = thisRect.width
            if thisRect.height > maxHeight:
                maxHeight = thisRect.height
        self.image = pygame.Surface((maxWidth, (self.fontSize+1)*len(textLines)+5), pygame.SRCALPHA, 32)
        self.image.convert_alpha()
        if self.background != "clear":
            self.image.fill(parseColour(self.background))
        linePos = 0
        for lineSurface in lineSurfaces:
            self.image.blit(lineSurface,[0,linePos])
            linePos+=self.fontSize+1
        self.rect = self.image.get_rect()

And this bit here is the function I'm using to update the output after each player action.

def changeLabel(textObject, newText, fontColour=None, background=None):
    textObject.update(newText, fontColour, background)

My general concept for how to get my gamelog made is that each of these output statements needs to be inserted into the first spot of a list.

Then, display the whole list, and pop off items from the list once they reach a set limit.

If anything on this needs to be clarified, or if other parts of my code are required to understand what my issue is, I'll update this post with whatever is requested.


texts:
Well I have a simple 2D game where all positions are defined by and X and Y coordinate.

There are objects moving at a constant velocity. And a turret fires a bullet at the X and Y coordinates of the object. By the time the bullet goes to the desired area, the object has already moved.

So i need to adjust the X and Y target positions for the turret to shoot at taking into account the bullet speed and object speed.

Here's an image showing the problem.


texts: How do you calculate the rotational velocity of a flying object?

texts:
When a arrow shaped object is fired it slowly adjusts it's rotation to match the direction it is moving. But what is the actual physics behind it?

The question is: How many degrees does the ship turn in a second?

I usually approximate the effect by simply setting the rotation to the angle of the velocity, however this is not possible this time since the player is able to influence the rotation of the ship by steering.


texts: I have been searching everywhere for master volume for sound and music in LibGDX but to no avail. Can anyone tell me if it is implemented somewhere or do i need to implement such functionality myself? Thanks in advance.


texts:
Introduction:

The main idea is to "classify population as they age". Let me further explain it with an example:

Example:

There are 50k population (we are not going to care about if male or female for now). Inside these number there are kids [0 - 16], fertile[16 - 40], non-fertile [40 - 100].

Question

Which would be a nice implementation to represent an evolving population data that is better or at least not too resource intensive as my example below?

My Idea

(Pseudo code)

Population[] // Array
   Age [0 -> 5] //Array
       a pop obj that stores data
   Age [5 -> 10]
       pop obj
   .
   .
   .
   Age[95 - 100]
      pop obj

This would be the structure and each tick happens this calculation:

FertilePop.count * fertility rate * (some other stuff) = numberOfBirths

where numberOfBirths are added to the Age[0-5].obj.count

and the rest of Age[rang] are subtracted a number and added onto the next Age[rang] until Age[95 - 100] where they "die of old age".

Notes:

This is purely background data and i am asking for a better solution/implementation that could be less complex, more dynamic and learn from it.

I expect to be able to do a graph plot so the user sees the pop evolution.

I took my interest in the matter from this link here to a population simulator.

https://niko.roorda.nu/computer-programs/popsim-population-simulation/

Thanks for your interest in this question.


texts: Resize the Texture Region (parallax background) to fit my screen size in libgdx

texts:
I am using libgdx to make a running game. I am using vertical parallax background. I have successfully implemented parallax background many times. But for this game, I want my Texture region to fit my screen size. I tried several things but the texture region is streched badly.Here is a screenshot.

I used this code:

texture_bg  = loadTexture("data/road1.png");
bg  = new TextureRegion(texture_bg, 0,0, 600, 600);

that is obvious. Now ..what should I do... so that while making it as a parallax background... it would fit my screen... I am worried only about the width.... as if the width will fit the screen width... it will look like a running road... no matter how long the height is.

I found some solution here
https://stackoverflow.com/questions/7551669/libgdx-spritebatch-render-to-texture

but not able to understand.. it seems somewhat complex.
Please make it clear if it is the solution or suggest on other possibilties.


texts: Lots of bouncing balls sink into each other

texts:
I'm trying to model a system that simulates an arbitrary number of bouncing balls with some gravity. So far I've come up with a solution that can be seen here: https://github.com/ahahalol/BouncingBalls

It works fine if the number of balls is small (a few dozens) or if I do not set any gravity. But once I turn gravity on and set the number of balls to a few hundreds, the balls "on the bottom" start sinking into each other over time as new balls fall on them "from the top".

Here's a picture that shows lots of sinking balls when I have gravity and hundreds of balls:

I want a system that perfectly simulates rigid balls physics: no matter how many objects "on top" push the ones "on bottom", nothing should ever sink. How can I achieve this?


texts:
as the title says, I have a problem using glGetUniformLocation call that returns, for the following code, the value 23724032. I'm writing a little engine and the draw function of my models is:

void Model::draw()
{
    // enable the shader program
    m_material->enable();
    // set the current value of the ModelViewProjection matrix
    m_material->getShaderProgram()->uniform("u_mvp", getPose());
    // draw the mesh using VAO
    m_mesh->draw();
    // disable the shader program
    m_material->disable();
}

where

void ShaderProgram::uniform(std::string i_varName, glm::mat4& i_value)
{
    // get the location of the uniform variable in the shader program
    GLint loc = glGetUniformLocation(m_programId, i_varName.c_str());
    if(loc != -1)
        glUniformMatrix4fv(loc, 1, GL_FALSE, glm::value_ptr(i_value));
}

My shaders are very simple:

// vertex shader
#version 330

uniform mat4 u_mvp;

attribute vec4 i_position;
//attribute vec4 i_normal;
//attribute vec2 i_texcoords;

void main(void)
{
    gl_Position = u_mvp * i_position;
}

and

// fragment shader
#version 330

precision highp float;

void main(void)
{
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}

So, I have a question: why I get this weird value from the glGetUniformLocation call?
I found this topic (link) from the OpenGL discussion board, but I still don't understand why my code doesn't draw anything. If the Intel integrated video card uses its own ids for attributes and uniforms, why is this a problem? What I have to do to fix it?

Note that if I run my application on high performance (with the dedicated video card), the function returns 0 as expected.

My notebook is a HP Pavilion dv7 6c90el with a ATI Radeon HD 7690M XT and a Intel 3000.

Thanks.


texts: I am using the unity NetworkDiscovery component, and I am wondering how I can auto-start broadcasting when the server starts, instead of the client having to click on the gui: Initialize Broadcast => Start Broadcasting. I would like to be able to put some C# in my start host function so that the user does not have to do anything.


texts: Steady zoom on center in LWJGL (Modelview)

texts:
I am having a problem in LWJGL with zooming in and out. I am using glScaled(zoom, zoom, 1) before glTranslated. There are 2 problems:
1. The rate of zoom speeds up a lot when zooming out (lower zoom value).
2. It zooms in on the bottom left corner of the screen rather than the center. Eventually, I would like to have the zoom focused on the mouse position.

I have tried to fix these problems by make it glScaled(zoom^12, zoom^12, 1) so that the greater the zoom value, the faster it will zoom in order to balance out the faster zoom at lower zoom values. To compensate for the zoom focused on the bottom left, I have tried to subtract (zoom+1)^10 + 2^10 from the X and Y of each sprite. This results in a curved zoom path, first to the left and then to the right. It is a 2D game.


texts: Implementing a hook (Like pudge in Dota)

texts:
I'm coding a new game, which involves hooking.

Ive been testing a couple of ideas now and im quite stuck.

The player can throw a "hook" which fires away in the aimed direction, until it hits something, it will bounce on some obstacles and will return to the player if hitting other obstacles. While the hook is in the air, the player can move as he/she wishes, and hook will after a certain time be pulled back to the player.

I don't know if you guys have played pudge wars, but that is the kinda hook I'm after.

What do you think is the best approach in simulating this?

Should i save points a long the way?

Edit: Yes the bounce thing is a from pudge wars.
And yes the length, not time, that is true!


texts: Turning On/Off Vsync no longer working when rendering to an offscreen buffer

texts:
I have this reaallly strange issue that as soon as I render to an offscreen framebuffer I am no longer able to toggle VSync while my application is running. I am using OpenTK as the opengl wrapper, but I have a strong feeling it's not related at all to OpenTK.

The odd thing is I can still turn VSync on/off during startup of the application, but not anymore while the game is running. If I temporarily redirect rendering to the default framebuffer i can also again toggle Vsync.

I can use an ugly hack to just redirect rendering to the default framebuffer, a frame later set toggle vsync mode, then redirect rendering to the offscreen framebuffer again, however I would much prefer a proper fix.

Here's some pesudo code what my code does:

Initialize 2 Framebuffers. Bind first offscreen framebuffer.
while(!exit) {
    Render opaque stuff
    Switch to second framebuffer for transparent objects
    Render transparent stuff
    Switch to first buffer
    Render transparent texture to primary buffer
    Switch to default framebuffer (default FB in write mode, first FB in readmode)
    Blit from first to default framebuffer
    Bind first offscreen FB
}

I had to use offscreen frame buffers in order to re-use the depth buffer in the transparent render pass for implementing WOIT (Weighted Blended Order Independent Transparency)


texts: Help for choosing a cost effective game server for Flash client

texts:
I am developing a flash-based game primarily for desktops, to be hosted on facebook platform (like cityville, sims social etc). The gameplay doesn't involve real-time communication between players unlike an mmorpg. Here each player plays in his own world without any knowledge of other online players. I've written almost 95% of the game logic in actionscript on the client side.
I used Smartfox Server pro on the server side (mostly used for getting data from the DB) and the entire server code is an extension written in java. I'm using json as the protocol for communication.
Although I love smartfox server, as an indie, its tough for me to afford the unlimited users license. Morever its limited just to one machine. So I'm looking for an alternative to smartfox server now.

The reason for choosing smartfox server earlier was to use the server properties supported by it.

Server properties on smartfox server take advantage of the socket connection and are essentially server side objects in java which store some data for the player which he can change frequently during the game. And when he logs out of the game, the extension can write out the final state in the DB (I'm using MySQL). This significantly reduces the number of DB UPDATE/INSERT calls made during the game.

I love the way this works since the data is secure as its on the server side and smartfox server is known to be scalable. (although I'm not sure whether this approach is used widely by gaming industry or not, since this is not an mmorpg, I'm putting all player in the lobby).
So my question is whether any of the free and community supported servers like reddwarf, firebase, BlazeDS etc can provide a similar architecture so that I can use server properties without many code changes?

EDIT : I am not insisting on the exact same feature (thats asking too much!), but atleast a viable messaging system on the server so that I can send actionscript objects from the client using json/binary so that its fast. OR maybe some completely different way to implement what I need here. Thanks in advance.


texts: Separate renderng thread in Android (OpenGL ES 2.0)

texts:
I'm used to mainly working with the Canvas SurfaceView API on Android and have recently been learning openGL ES 2.0

With canvas I know that surfaceView gives you the ability to start a new thread to render on, but it doesn't specifically do this for you, so I was creating a new thread and managing that thread when the app was ended / paused etc....

However, from what I've read with glSurfaceView it seems that this is actually done for you automatically? Does this mean I don't actually need to manually create / start and manage my own rendering thread? (I'm talking specifically about a rendering thread (which could also be used for logic updates) which is separate the main UI thread.

Clarification on this matter would be greatly appreciated.


texts:
I can move within my 2d array. But I'm not sure if my right or left and up and down is messed up, or what but for some reason the movements don't correspond to anything I'm familiar with on the map(like if I move into a wall, and type the opposite direction, there is a wall on both sides of me, you may have to just try this little game out yourself and see).Also sometimes, when it should output that you are on an empty tile, or something, it just goes straight to my if else instead of saying one of my if statements(Which I'm sure is my blunder). Is it just my directions within the 2D array that are messed up or something more? Thank you again for your time I am just self learning java and having a great time.
TLDR: I just want my movements (up, down,left,and right) to correspond to my 2d array map.

    package login;

import java.util.Scanner;

public class Form {
static String dir = "";
static int player;
static int chest;
static int monster;
static int key;
static int tile;
static int wall;
static Scanner scan = new Scanner(System.in);

static int[][] map = new int[][]{
    {1,1,1,1,1,1,1,1,1,1},
    {1,2,2,2,3,4,2,2,4,1},
    {1,3,2,2,2,2,2,2,2,1},
    {1,2,5,4,2,2,2,5,2,1},
    {1,2,3,3,0,5,5,3,2,1},
    {1,2,2,2,2,2,2,2,2,1},
    {1,3,3,5,2,2,3,2,2,1},
    {1,4,4,2,2,2,2,2,2,1},
    {1,3,5,2,2,2,3,4,5,1},
    {1,1,1,1,1,1,1,1,1,1}};

    static int x= map[5][0];
    static int y = map[0][5];
    static int playerPos = map[x][y];
    static int life = 3;

static boolean isInGame;

public static void main(String[] args){
int isPlaying;
    System.out.println("Press 1 to play..anything else to exit!");
    isPlaying = scan.nextInt();
    if(isPlaying == 1){
    isInGame = true;
    enterGame();

    }
    else{
        System.out.println("You missed out on a good game...");
        System.exit(1);
    }
}

public static void enterGame(){
    System.out.println("Type, up, down, left, or right, to move.");
    while(isInGame == true){
        move();

    }

}

public static void move(){
    dir = scan.nextLine();
    switch (dir){
    case "up":
        x = x+1;
        playerPos = map[x][y];
        map();
        break;
    case "down":
        x = x-1;

        playerPos = map[x][y];
        map();
        break;
    case "left":
        y = y-1;

        playerPos = map[x][y];
        map();
        break;
    case "right":
        y = y+1;

        map();
        break;

    }
}

public static void map(){
    wall = 1;
    tile = 2;
    monster = 3;
    chest = 4;
    key = 5;
    player = 0;

    if(playerPos == wall){
        System.out.println("Thats a wall. Can't move there.");
    }
    if(playerPos == tile){
        System.out.println("You move to a free tile");
    }
    if(playerPos == monster){
        monsterEncounter();
    }
    if(playerPos == chest){
        System.out.println("Woah a chest!");
    }
    if(playerPos == key){
        System.out.println("Woah a key!");
    }
    else if(playerPos != wall){
        System.out.println("Keep going.");
    }
}
public static void monsterEncounter(){
    if(life > 0){
    if( x == 3 || y == 3){
        System.out.println("WOAH! A MONSTER! HE BEATS YOUR ASS.. -1 LIFES");
        life =- 1;
        System.out.println("You have: "+ life +" life left! Don't die..");
    }}else{
        System.out.println("You have: "+ life +"You encountered too many monsters. GAME OVER.");
        System.exit(1);
    }

}
}


texts: Recreating A Puzzle Effect Using Stencils

texts:
I'm trying to recreate something I saw on reddit a while back. I tried rendering camera output onto planes, but am not getting the results that I want -- this is basically what I'm trying to recreate:

I found this project on GitHub, which is similar, but definitely different as it's rendering stationary objects depending on the view (is that what I want to be doing?).

Here is what I have so far:

A cube with inward-facing planes, which has a sphere inside it:

An orthographic camera facing each inner wall:

A cube with outward-facing planes:

Each cube face has a material on it:

With a texture on it that reflects one of the camera's viewports:

I'm sure I need to do some kind of shader stencil work - and I don't have too much experience. Any help is greatly appreciated!


texts: Blurring part of the screen - optimisation

texts:
I develop 3d menu and sometimes I need to blur only part of the screen. I use a forward rendering. I create a frame buffer object with 3 color attachments. Rendering looks like this:

bind fbo
render objects which  are blurred to the first texture
bind the first texture
perform vertical blur and save a result in the second texture
bind the second texture
perform horizontal blur and save a result in the third texture
unbind fbo (render to the default fbo)
bind the thrid texture
render the third texture
render objects which are not blurred

I can use subroutines to reduce overhead during switching shaders. I also found the following article . Do you have any other ideas how to optimize above rendering ?


texts: What is the AlphaToCoverage blend state useful for?

texts:
Alright, just finished most of my early UI stuff and I wanted the windows to have some transparency. So I expanded my application to initialize and bind blend states so that my UI shader could implement alpha blending. I was initially having no luck but I got the blend state configured to achieve my purpose, however the way it is configured doesn't make sense to me so I must be missing something.

Here is how I initialize my blend state.

bool BlendState::StartUp() {
    D11DeviceManager* _pDeviceManager = D11DeviceManager::GetSingleton();

    D3D11_BLEND_DESC _desc;
    _desc.AlphaToCoverageEnable = false;
    _desc.IndependentBlendEnable = false;

    _desc.RenderTarget[0].BlendEnable            = true;
    _desc.RenderTarget[0].SrcBlend               = D3D11_BLEND_SRC_COLOR;
    _desc.RenderTarget[0].DestBlend              = D3D11_BLEND_DEST_COLOR;
    _desc.RenderTarget[0].BlendOp                = D3D11_BLEND_OP_ADD;
    _desc.RenderTarget[0].SrcBlendAlpha          = D3D11_BLEND_SRC_ALPHA;
    _desc.RenderTarget[0].DestBlendAlpha         = D3D11_BLEND_DEST_ALPHA;
    _desc.RenderTarget[0].BlendOpAlpha           = D3D11_BLEND_OP_ADD;
    _desc.RenderTarget[0].RenderTargetWriteMask  = 7;

    return !FAILED(_pDeviceManager->GetDevice()->CreateBlendState(&_desc, &pBlendState));
}

Right now my alpha blending only works when the AlphaToCoverage bool is set to false... I thought this was just a bool enabling the pixel fragment blending (which upon retrospection would be redundant considering the BlendEnable flags...) but looking at the MSDN documentation is appears to do this...

  You can use the AlphaToCoverageEnable member of D3D11_BLEND_DESC1 or D3D11_BLEND_DESC to toggle whether the runtime converts the .a component (alpha) of output register SV_Target0 from the pixel shader to an n-step coverage mask (given an n-sample RenderTarget). The runtime performs an AND operation of this mask with the typical sample coverage for the pixel in the primitive (in addition to the sample mask) to determine which samples to update in all the active RenderTargets.

Could someone explain this to me and how it differs from when the AlphaToCoverageEnable bool is false? I see that it adds a new mask to the fragment but I don't quite follow what the mask exactly is.


texts: How can I reduce draw calls when using glBufferSubData and DYNAMIC_DRAW?

texts:
At first I had the problem where I had about 150 rectangles rendered every tick. I only used STATIC_DRAW and glBufferData. I added support for DYNAMIC_DRAW and glBufferSubData and now I have a very good result... but the number of draw calls (glDrawArrays) is the same. Best practices from Mozilla Dev website said it should be reduced, but how?

Every rectangle has a method render() in which I do following (shortend):

_gl.bindBuffer(WebGL.ARRAY_BUFFER, vertexBuffer);
_gl.enableVertexAttribArray(a_position);
_gl.vertexAttribPointer(a_position, 2, WebGL.FLOAT, false, 0, 0);
_gl.bufferSubData(WebGL.ARRAY_BUFFER, 0, vertices);

_gl.bindBuffer(WebGL.ARRAY_BUFFER, texCoordBuffer);
_gl.enableVertexAttribArray(a_texCoordLocation);
_gl.vertexAttribPointer(a_texCoordLocation, 2, WebGL.FLOAT, false, 0, 0);
_gl.bufferSubData(WebGL.ARRAY_BUFFER, 0, texVertices);

_gl.uniform2fv(_utranslation, _translation);
_gl.uniform2fv(_urotation, _rotation);
_gl.uniform2f(_location, Dart2D.WIDTH, Dart2D.HEIGHT);

_gl.drawArrays(WebGL.TRIANGLES, 0, 6);

So every rectangle calls drawArrays in every frame...


texts: What is the relationship between glVertexAttribPointer index and GLSL location?

texts:
I've been getting some strange results when trying to implement a normals buffer for the purpose of rendering lighting.  It seems to be related to the indexes for glEnableVertexAttribArray, glVertexAttribPointer and the location value in the vertex shader.
Take a look at the following code for example:

  gl.glEnableVertexAttribArray(1);
  gl.glEnableVertexAttribArray(0);

  //bind vertex data - why does the index have to be 1?
  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[VERTICES_IDX]); //the vertex data
  gl.glVertexAttribPointer(1,3,GL4.GL_FLOAT, false,  0,0);

  // Select the VBO, GPU memory data, to use for colors
  // - why doe the index have to be 0??
  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[COLOR_IDX]);
  gl.glVertexAttribPointer(0, 3, GL4.GL_FLOAT, false, 0, 0);

  //bind IBO
  gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, vboHandles[2]);

Where do the values for the indexes used in the above functions come from?  If I were to switch them and make the color buffer 1 and the vertex buffer 0, nothing renders.  It seems logical to me that the vertices should be applied first and then the colors?  My confusion is compounded when I try to pass the data to a shader.  I thought the location value in the shader program referred to the index in glVertexAttribPointer but that doesn't seem to be the case.  In fact it looks like location is being completely ignored (targeting GLSL 430).
Have a look at this:

From the shader:

layout (location=0) in vec3 vertexPosition;
layout (location=1) in vec3 vertexNormal;

The Java code:

//with glEnableVertexAttribArray 0 and 1 enabled all of the cubes render but they
//are individually lighted - ie the shading doesn't propagate over the whole scene,
//only over each cube.
//if i rem 1, the scene looks lighted properly.  So only 1 vertex array enabled
//and it still works?
  gl.glEnableVertexAttribArray(0);
  gl.glEnableVertexAttribArray(1);
  //gl.glEnableVertexAttribArray(2);

  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[VERTICES_IDX]);
  //with the index set to 5 (doesn't relate to any other index) the scene still
  //renders...
  gl.glVertexAttribPointer(5,3,GL4.GL_FLOAT, false,  0,0);

  //normals
  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[3]);
  gl.glVertexAttribPointer(1, 3, GL4.GL_FLOAT, false, 0, 0);

      // Select the VBO, GPU memory data, to use for colors
  //almost strangest of all.  If I remove colors the program crashes.  I don't
  //even use this buffer..
  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[COLOR_IDX]);
  gl.glVertexAttribPointer(0, 3, GL4.GL_FLOAT, false, 0, 0);

  //bind IBO
  gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, vboHandles[2]);

There is obviously something fundamental here that I am not understanding.  I would think that by setting the glVertexAttribPointer index for the vertices to 5 it would
unlink from the shader in variable as its location is 0.  I need to know what is going on here especially now that I am implementing lighting.
So, what is the relationship between the glVertexAttribPointer index and the shader location value?  Also, why does the index have to be certain value (eg 0 for color, 1 for vertex)?


texts: Does animation have internal "update"-cycle where I can make calculations between steps?

texts:
I am new to Unity and not game developer at all, so sorry if this question might be stupid. I have an animation in my project. Is there some points where Unity calculates/recalculates the next position of animated character? Is there some function like for example "OnAnimationSample()"? I want to make calculations between theese points. I didn't found anything in the documentation and hope that someone more experienced than me know some way to tackle, although the task is quite peculiar.
I am programming a simulation environment for robots. There is a need to take screenshots at certain events happening by means of raycasting (gathering img data for CNN). The robot has various physical specification like for example speed. I don't want the environment depends on speed of the robot, so I am planning to make calculations and screenshots constatly for example in between two animation "milestones". That will slow fps and overall game down, but I don't mind since I need only right data at right step. For example suppose there are exist such points in the Unity, when before taking any movement the Unity calculates the next state of the object being animated. I want to stuff my calculation and such, that next animation step won't start until all is done.
I hope that explained not so tricky. Say if the explanation is obscure I will try my best again.


texts: What image format supports transparency in Android?

texts:
I want to show an apple on screen but the image has a white background and it doesn't blend with the background of a tree.

Is there any image format in which only the red apple is displayed?


texts: How to randomize Motion/animation without create a state for each animation?

texts:
I'm using Animator and state for animating my charachter.

So, i've (example) an Idle state, associated to an Idle motion animation , and a Death State, associated to a Death animation.

But I've 5 possible animation for death so i would like to randomize death animation without create a state for each animation.

My State "Death" has a "Motion" variable. I would like to change at runtime this  "motion" variable. Is it possible ?

Thanks


texts: (Hitbox) OnTriggerEnter2D only work if enemy is moving

texts:
(UPTADE) I am developing a 2D Topdown Rpg Game. I have a problem with trigger colliders. I have button which make active an object and ı use it like Hitbox when i press button ı destroy enemy if it is touching hitbox but there is a problem about something. When i press button enemy is destroyed if only enemy is moving when it stop i cant destroy it
How can I fix this?
This is my hitbox's destroy script
 private void OnTriggerEnter2D(Collider2D other)
    {

        if (other.tag == "Enemy")
        {
            Destroy(other.gameObject);
        }
    }
```


texts: Gaussian blur spritesheet/texture atlas without clipping edges

texts:
I'm trying to apply a Gaussian blur to a shadow to soften them a bit. I can apply the blur fine, but the problem is that I end up with this:

Instead of this:

Which isn't great. The image is part of a spritesheet with a single pixel gutter around each frame.

I don't want to have to go back and add gutters big enough to accommodate the blur to every single frame of every spritesheet. Additionally because of the way the sprites have to be sorted I can't render all the shadows to a render target and then blur the entire target. I can achieve the effect I want with a sprite as a single image instead of as a spritesheet. I do that by creating the triangles 20% bigger than they need to be and then sampling the texture outside the bounds when the UV addressing is set to clamp. That doesn't work with a spritesheet though because then it just starts sampling the frames on either side of the current frame.

Is there a way to achieve what I want with a shader or other trickery? I really don't want to have to alter every spritesheet.


texts: 3D rotation and movement of ball on a 2D plane

texts:
Here is a video of Amiga arcade pool game:
https://www.youtube.com/watch?v=zTQIPFBUFIg
I am making a similar game with C and Gtk+3.0 but I don't know how to show balls 3D movement on 2D plane!
I guess there is some tricks with changing image of the ball but I don't know exactly what to do.
I can move the balls on 2D plane but I can't show their rotation!
how did they show 3D movement of ball in Amiga's pool game?


texts: Lifting vehicles (and spawners) using InterActors, strange collisions causing flying vehicles

texts:
Making a VCTF map with the Unreal Tournament 3 Editor, and thus have vehicles in it. Currently I have 2 walkways next to each other (Big enough for a vehicle). One of them (A InterActor) drops down, and a grate covers the hole until the vehicle respawns. Once its respawned the InterActor Walkway lifts the vehicle up (and the grate pulls back). However what I'm finding is that the vehicle seems to collide with something when it gets near the top.

(Looks something like this: ----_ where _ is the moving InterActor and - is a walkway)

I created a new map to test this, and found it seems the front of the scorpion collides with the walkway in front of it, however I don't know why, it physically (in terms of how it looks in game) does not touch the walkway in front of it, but its actions look like it has.

Im using InterActors, and a vehicle spawner, looking like so

How do I stop this from happening? Right now everything is perfect, except the vehicle keeps flying away every time its lifted up, likes it been forced in between the "lift" and another object!


texts: Is collision detection with static environment necessary for npcs

texts:
I can't find any information on this topic. I'm wondering about the differences between the collision detection approach for player as opposed to npcs.
Basically NPCs will move strictly along the navigation mesh (constructed for static environment) with a pathfinding algorithm. And should in theory not collide with any static obstacles. In that case do we really need to check for collision against the static environment?
As opposed to NPCs, players are not bounded by navigation mesh. So we would definitely have to handle collision with static environment.
I'm wondering what the general consensus is around this in game development?


texts: How to make player move into next level in pygame

texts:
When my player reaches at the end of the map, I want it to enter to the next level. I've created the first level and it all works fine. All I want to do is that when player finishes 1st level I want to load another map on which it can move forward. But I'm not able to understand how to do it.
Here is piece of my code:
def runGame(theGame):

    theGame.clock.tick(FPS)

    # This function consists code for Events
    theGame.events()
    # This function consists code from enemy hit events
    theGame.hit_or_not()
    # This function consists code for player movements
    theGame.movements()
    # This function consists code for drawing the sprites over the screen
    theGame.redrawGameWindow()

def readyGame(run, gameOver):
    game = Game()

    while run:
        runGame(game)

        keys = pygame.key.get_pressed()

        if keys[pygame.K_x]:
            game = Game()
        elif keys[pygame.K_ESCAPE]:
            run = False
        pygame.event.pump()

        if gameOver:
            runGame(game)

readyGame(True, False)

Here is my whole code which is responsible for my 1st level please kindly check it - https://pastebin.com/zMFetAd6 (Game Class)
Do I have to create another class for 2nd level like I did for the 1st level?
Can anyone please help me out in this issue? Thanks in advance!


texts: I'm currently looking into adding sound to my game. I have seen OpenAL and SDL, but I would like to know what else is out there. Can you recommend any good cross-platform Audio APIs for  game development?


texts: Null instance on manager class extending from singleton class

texts:
I have four classes:

class A, which is abstract and partial extending from singleton class C.
class A1, which is partial and extending from class A .
class B,  extending from class A.
class C, a singleton which has code to throw an exception if the instance is null, and otherwise uses DoNotDestroyOnLoad().

In scene view, I add class B to the scene. It works, but throws a null instance exception for class A, as it's instance is not present in scene. I think this is because class A extends from a singleton class, and it has ability to throw exceptions when the instance is null. I can not add the class A to the scene because it is abstract.

What can I do to in order to add the class A component to the scene, or otherwise not to get this error?


texts:
In OpenGL, is there a format for a texture in glTexImage2D that prevents blending, or do you have to disable it using glDisable(GL_BLEND).

Reason for use is that I would like to store additional data in the alpha channel of a texture, but it blends with whatever's behind it.


texts:
I'm not sure whether this place is the correct for asking this. If it's the wrong place I'm sorry, please tell me if so!

I'm making a small game for fun which would uses an own engine with OpenGL and Vulkan as underlying renderer implementation. The engine itself is targeted for Mono/.Net.

Currently I'm not yet there but I'll come to the point where I'm pushed to implement some kind of GUI (I'm thinking ahead because of good design).
I already searched the Internet for render independent GUI systems but I wasn't lucky yet. As result I thought about how I could implement the GUI on my own and came to the conclusion:

a independent implementation is needed which takes care only for layout, positioning of GUI objects with responding to inputs.
another implementation is needed which only takes the results of calculations for rendering (the renderer)

Before I start inventing the whole wheel new I simply want to know:

Is it a correct approach to doing it this way? Is there a different common approach doing what I described?


texts:
I am looking to get into game development, after a lot of searching I have decided to try with html5 and, while I can see the advantages of frameworks, I would like to learn the basics without a "crutch".

Is it realistic to even try and start learning game development without using a framework? Also, if I decide to use one, what should I consider when deciding on one?