texts: How do I calculate normals correctly for dynamic terrain (DX11, C++)?

texts:
I am currently looking for some guidance on how to correctly calculate my normals on the CPU for my terrain as the results I'm getting seem to be incorrect. Eventually I will attempting to calculate them on the GPU as I'm aiming for terrain deformation in real-time.

These are the results

The different colours on the image represent different normal values.

Here is the code I'm using to generate them.

for (int i = 0; i < width; i++) {

    for (int j = 0; j < height; j++) {
        int index1 = (j * width) + i;
        int index2 = (j * width) + (i + 1);
        int index3 = ((j + 1) * width) + i;

        int index4 = ((j + 1) * width + i);
        int index5 = ((j * width + (i + 1)));
        int index6 = ((j + 1) * width + (i + 1));

        //vertices of triangle
        Vertex vertex1 = vertices->at(index1);
        Vertex vertex2 = vertices->at(index2);
        Vertex vertex3 = vertices->at(index3);

        Vertex vertex4 = vertices->at(index4);
        Vertex vertex5 = vertices->at(index5);
        Vertex vertex6 = vertices->at(index6);

        //each vertex as XMVECTOR
        XMVECTOR point1 = XMVectorSet(vertex1.Pos.x, vertex1.Pos.y, vertex1.Pos.z, 0.0f);
        XMVECTOR point2 = XMVectorSet(vertex2.Pos.x, vertex2.Pos.y, vertex2.Pos.z, 0.0f);
        XMVECTOR point3 = XMVectorSet(vertex3.Pos.x, vertex3.Pos.y, vertex3.Pos.z, 0.0f);

        XMVECTOR point4 = XMVectorSet(vertex4.Pos.x, vertex4.Pos.y, vertex4.Pos.z, 0.0f);
        XMVECTOR point5 = XMVectorSet(vertex5.Pos.x, vertex5.Pos.y, vertex5.Pos.z, 0.0f);
        XMVECTOR point6 = XMVectorSet(vertex6.Pos.x, vertex6.Pos.y, vertex6.Pos.z, 0.0f);

        //lines to compute the cross product
        XMVECTOR line1 = XMVectorSubtract(point2, point1);
        XMVECTOR line2 = XMVectorSubtract(point3, point1);

        XMVECTOR line3 = XMVectorSubtract(point5, point4);
        XMVECTOR line4 = XMVectorSubtract(point6, point4);

        //cross product to get our unnormalized normal
        XMVECTOR cross = XMVector3Cross(line1, line2);

        XMVECTOR cross2 = XMVector3Cross(line3, line4);

        //normalize to get our normal value
        cross = XMVector3Normalize(cross);
        cross2 = XMVector3Normalize(cross2);

        vertices->at(index1).Normal = Operations::vectorToXMFLOAT3(cross);
        vertices->at(index2).Normal = Operations::vectorToXMFLOAT3(cross);
        vertices->at(index3).Normal = Operations::vectorToXMFLOAT3(cross);

        vertices->at(index4).Normal = Operations::vectorToXMFLOAT3(cross2);
        vertices->at(index5).Normal = Operations::vectorToXMFLOAT3(cross2);
        vertices->at(index6).Normal = Operations::vectorToXMFLOAT3(cross2);
    }

}

Edit: I have made some changes to the code to account for the second triangle in the triangle pair but still produces similar results.
The green (grass) represents a normal value of 0. The pink represents a normal value of 1. The red represents a normal value of -1

Why is the majority of the mesh 0, and where the normals are calculated, they are incorrect?

Edit 2

I have removed the use of the indices array in this loop and now the whole plane is processed, but results are still incorrect.

Edit 3

I did not realise I was referencing the indices array in more than one place. When I corrected this, I am now seeing better results. Although there is a slight problem of the normal that is being calculated is -1 instead of the expected +1

Edit 4:

Normals are calculated per vertex and don't take other touching faces into account, that is the next step. I'm guessing some parts of the texturing/terrain look a little weird due to this.

At the moment my terrain is just a flat plane, so all of the normals should be the same, right? However the values seem to be different when rendering/printing out.

There are some values that are 0, some are -1 and the rest are +1. Does anyone know where I'm going wrong?


texts: How to draw the path with a thicker stroke?

texts:
I have a game where objects follow a path that resembles a circuit (f1, nascar, stock car).

Using the draw_path function, I can draw the circuit on the game screen:

It turns out that dash got too thin.

To thicken the drawing line and actually look like a circuit (so I don't have to sprite and put in the background) I tried the following (Draw Event):

draw_path(circuito_ovo,500,50,false);
draw_path(circuito_ovo,501,51,false);
draw_path(circuito_ovo,502,52,false);
draw_path(circuito_ovo,503,53,false);
draw_path(circuito_ovo,504,54,false);
draw_path(circuito_ovo,505,55,false);
draw_path(circuito_ovo,506,56,false);

The result was not as expected (detail I added a unit in two dimensions, I thought the secret would be this):


texts: Why doesn't Unity's OnCollisionEnter give me surface normals, and what's the most reliable way to get them?

texts:
Unity's on collision event gives you a Collision object that gives you some information about the collision that happened (including a list of ContactPoints with hit normals).

But what you don't get is surface normals for the collider that you hit. Here's a screenshot to illustrate. The red line is from ContactPoint.normal and the blue line is from RaycastHit.normal.

Is this an instance of Unity hiding information to provide a simplified API? Or do standard 3D realtime collision detection techniques just not collect this information?

And for the second part of the question, what's a surefire and relatively efficient way to get a surface normal for a collision?

I know that raycasting gives you surface normals, but it seems I need to do several raycasts to accomplish this for all scenarios (maybe a contact point/normal combination misses the collider on the first cast, or maybe you need to do some average of all the contact points' normals to get the best result).

My current method:

Back up the Collision.contacts[0].point along its hit normal
Raycast down the negated hit normal for float.MaxValue, on Collision.collider
If that fails, repeat steps 1 and 2 with the non-negated normal
If that fails, try steps 1 to 3 with Collision.contacts[1]
Repeat 4 until successful or until all contact points exhausted.
Give up, return Vector3.zero.

This seems to catch everything, but all those raycasts make me queasy, and I'm not sure how to test that this works for enough cases. Is there a better way?

EDIT
If this really is just the way things are with 3D collision, an overview of why in the general case would be just as welcome as something specific to Unity.


texts:
I am rendering a textured model using the XNA BasicEffect.  When I enable fog, the model outline is still visible as many small black dots when it should be "in the fog".  Why is this happening?

Here is a minimal example showing my problem: (the ship model that this example uses is from the chase camera sample on this site — in case anyone wants to try it out ;))

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    Model model;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        // TODO: use this.Content to load your game content here
        model = Content.Load<Model>("ship");
        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (BasicEffect be in mesh.Effects)
            {
                be.EnableDefaultLighting();
                be.FogEnabled = true;
                be.FogColor = Color.CornflowerBlue.ToVector3();
                be.FogStart = 10;
                be.FogEnd = 30;
            }
        }
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        // TODO: Add your drawing code here
        model.Draw(Matrix.Identity * Matrix.CreateScale(0.01f) * Matrix.CreateRotationY(3 * MathHelper.PiOver4),
            Matrix.CreateLookAt(new Vector3(0, 0, 30), Vector3.Zero, Vector3.Up),
            Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 16f/9f, 1, 100));

        base.Draw(gameTime);
    }
}


texts:
Are there any algorithms out there for non deterministic dice rolls?

For example, I'd like to make a small mini-game: Liars dice. But the biggest issue here is dice rolling. When the cups are turned the result of the dice should be determined by the game rather than physics (if I were using unity for example). How can I ensure that the model behind it provides random results acute to an actual dice role?


texts: Combining Many Small Colliders into Larger Ones

texts:
I am creating a game using a tile-map made of many thousands of grid squares. At the moment, each square has a square collider on it for checking collisions.

However, with many thousands of tiny blocks, checking them all for collisions is inefficient. If I had known the tilemap was going to look like this in advance, I could have just used 3 or 4 big colliders rather than thousands of tiny ones:

Is there some sort of standard algorithm for combining many small adjacent tiles into maximally large ones? If so, could someone describe it here, or point to literature on such algorithms?

Alternatively, maybe pre-processing the tile colliders in this way is completely the wrong approach. If so, what is the correct one to deal with the efficiency of an extremely large number of colliders?


texts: Why don't top selling mobile games have localization?

texts: For example: Plants vs Zombies 2, Angry Birds, Bad Piggies, Candy Crush Saga, Temple Run 2 and so on. These games are available in English only. These companies have huge resources; why don't they localize their games?


texts: Phaser 3 - How to trigger an event every 1 second?

texts:
I have just started learning Phaser 3 and making a simple idle game, where you would gain x resources per second. What is the best/recommended way to do something like this?

The two main ways I have found so far are:

delayedCall - this.time.delayedCall(1000, onEvent, null, this);

addEvent - this.time.addEvent({ delay: 1000, callback: onEvent, callbackScope: this });

But I read that Phaser update/rendering is in lockstep and runs at 60fps. So if the game were to drop in FPS, then other things like movement, physics etc. would slow down, but would the timers still fire every second? ie you could end up gaining more resources then you should have as the game is running.

Would it not be better to do a modulus 60 frame count, and invoke any per second logic in that manner?


texts: How does one first draft a linear visual novel plot?

texts: I’m making a linear visual novel with partial interactivity that allows the player to influence small portions of the story, but I just want to know how one goes about drafting something like that. The interactivity feature allows you to build a relationship with some characters, this is what can change different parts of the story. Thing is that I have several other characters whose growth I would like to cover, but don’t know how.


texts: Moving an object around the the circle to the specific location in circumference

texts:
Well I have run out of ideas how to approach this particular problem.See the picture below:

So the idea is that the object (dot in black) has to get to a point mark X (red X mark).However the limitation is that it has to get there without crossing the circle (i.e going in the straight line the the X mark).I was reading on some steering algorithsm but seems rather too complicated for this problem.Also I should mention that the object has the speed and velocity and position attributes which controls how its moving.

Now I was reading some ideas on how to move an object around a circumference here:

Here

However this doesn't entirely answer my question.The thing is I first need to get to the circle in order to be able to move around it.What I was thinking,was to allow the object to move towards  the position in a straight line until it hits the circle and then start moving along the circumference of the circle.Also the "X" mark can be anywhere on the circle even right in-front of it (not behind on the other side of the as in this example shown in the image)

I am not a game developer and thus never came across issues like so.The idea is that there will be more than one black object trying to get to their own "X" mark on the circle from random positions.(They idea is that they will be surrounding some objects in the middle). Here is an image to show what I mean,where each black object has an X position that they need to attend to without directly going through the circle.(Sorry for my bad drawings,was using laptop track-pad to do these images)

Anyway I am kinda lost with this and would to see different on tackling this particular problem.


texts: How to reset scene (stage1) when selecting it from Level stagemain menu

texts:
Good day I have a problem when the player finish stage 1 the screen look like this

Then going back to selecting level

When I try to play the stage 1 again. I want to reset the stage 1 so i can play it again.
I only use
Scene.LoadScene("stage1") in main menu to go to stage1 and
Scene.LoadScene("mainmenu") to back to main menu


texts: How to get Google Play to suggest my app?

texts:
I uploaded a game to Play and obviously it isn't the very first suggestion on the list. I uploaded it 3 days ago.

As somehow new games do get played, I assume people start to know about them.

I would like to ask that how does Play start suggesting an app? Is it by download count/download frequency? Or does it show new apps by itself?


texts: Canvas UI elements out of place in Unity3d

texts:
I placed all elements in the places I want to show in the Game mode,
nevertheless, when I go to Game Mode they are shown in the wrong place as it was shown in the pictures (they go to the center). I tried different modes of render mode but no one seems to work in this case. I want the elements to be fixed in the window no matter monitor size.


texts: How to decide the budget as independent game developer?

texts:
I'm currently try to make a business plan and was just wondering, how you guys decide the budget for outsourcing tasks. Is there a kind of a reference point? Or does the client decide this mostly by himself, what he want for his work?
I speaking specially about tasks like:

translation (en->xxx)
character artwork
tiles/background artwork
sprites
music (BGM/SE)
voice synchronization

Naturally it depends really a lot about content size and requirements - but have any here a generally idea about the neccessary budget for tasks like this?
Any link or ressource to this topic would be highly appreciated.
Thank you guys,

Edit: Already thank you, for the great answers!
Specially I mean also things like: How do you compromise with graphics artists and what kind of "contract" do you use. In which frame I can imagine the payment for i.e. a drawn character artwork or a standard sprite sheet with a few animations? Any experiences? I haven't really an idea, what to offer an artist for such tasks...


texts:
I'm new to game development and am curious to know if you can add your own cg effects? Like if I wanted to add fog to my game and UDK didn't support that, is that possible?

What kind of coding does one do, in a engine like UDK?


texts: Player moving up, is he jumping or climbing?

texts:
In a 2D physics-based platformer game that has ladders in it, how do you determine whether the player moving up is caused by a jump or him climbing a ladder, such that you know what animation to play?

And in general, obviously the direction vector is not enought to determine the animation to play: how do you also determine the cause of the movement (so you know the correct sprite to use)?


texts:
I'm using a simplex noise system to generate height maps for an "infinite" 2d world map. It works perfectly - I can define which tile belongs at which height value, etc.

However, I'm trying to add in biomes - I want different areas of the map to use tiles exclusive to that "biome".

I've tried generating a second noise value divided by a larger number so that I can generate very large areas. That noise value determines the biome, and the noise value for tiles determines the tile inside that biome. This works ok - but when the same noise value means different tiles in each biome, then you wind up with very ugly cut-off lines between biomes.

I tried adding the biome noise and tile noise together and only selecting the tile based on those. The edges were smoother, but there really was no actual use of the biome code - just tiles locked to unique noise values, never overriding each other.

What's a better way to do this, so that biome boundaries follow "features" of the terrain? I want them to be fairly large, but not cut through a "mountain" - the boundary should follow the natural curvature of the height map values.


texts: Is there a standardized way for creating a 2D ball physics movement method?

texts: Is there a standardized method for creating a 2D ball physics movement like you can see on gif below?


texts: Way to Reset Varible After Collision Resolution

texts:
I have some code that, if a player is in contact with the wall, prevents the player from moving.

Is there any way with this code to reset the collide variable, and if not, what would be the simplest alternative.I have tried resting it at the start of the step but that did not work.


texts: How to make rhythm game long notes in Unity?

texts:
I'm making a rhythm game for a university course and I can't figure out a way to make the long/sustained notes. For reference, this is what I mean taken from Guitar Hero:

I already have a system working for regular notes. The way I do it is that the notes are stored in an external file as numbers which represent the absence or presence of a note as well as what type of note it is, separated into musical bars:
000
010
020
001

There are three lanes for the notes to be, and this means that in this particular bar there are notes wherever it's not 0 (with the numbers being different types of notes).
I had thought of using this system to create long/sustained note start and end markers (say 3 and 4) and that create another game object which would be the line between the start and end markers. But the way my note generator works is that the notes are not all generated at once because that'd be pretty heavy.
Instead, the notes are generated at a certain time taking into account its speed so that it's instantiated and will reach the player's activator when it's supposed to. The following is a part of my note generator code, put in the Update method:

// if current song time - time offset is greater than
// time taken for all executed bars so far
// spawn the next bar's notes
if (songTimer - _timeOffset >= (barExecutedTime - barTime))
{
   StartCoroutine(PlaceBar(noteData.bars[barCount++]));

   barExecutedTime += barTime;
}

And here is the PlaceBar coroutine:

// go through all notes in a bar
// creates an instance of note prefab
// depending on which note is meant to be spawned
private IEnumerator PlaceBar(List<SongParser.Notes> bar)
{
   for (int i = 0; i < bar.Count; i++)
   {
       if (IsThereNote(bar[i].bottom))
       {
          GameObject _obj = (GameObject) Instantiate(GetNotePrefab(bar[i].bottom, true), new Vector3(bottomLane.transform.position.x + distance, bottomLane.transform.position.y, bottomLane.transform.position.z - 0.3f), Quaternion.identity);
       }
       if (bar[i].middle != 0)
       {
          GameObject _obj = (GameObject) Instantiate(GetNotePrefab(bar[i].middle, false), new Vector3(middleLane.transform.position.x + distance, middleLane.transform.position.y, middleLane.transform.position.z - 0.3f), Quaternion.identity);
       }
       if (bar[i].top != 0)
       {
          GameObject _obj = (GameObject) Instantiate(GetNotePrefab(bar[i].top, true), new Vector3(topLane.transform.position.x + distance, topLane.transform.position.y, topLane.transform.position.z - 0.3f), Quaternion.identity);
       }

       yield return new WaitForSeconds((barTime / bar.Count) - Time.deltaTime);
   }
}

So if I were to make start and end markers, the start marker would not know where the end marker is because it doesn't exist. Could anyone help please?


texts:
Say we have the following simple mesh data:

// additional data
// Vector3(x, y, z) - +x left, +y up, +z forward
// triangle indices are in clocwise order

// list of vertices that form a place
List<Vector3> vertices = new List<Vector3>() {
  new Vector3(2f, 0f, 2f),
  new Vector3(-2f, 0f, 2f),
  new Vector3(2f, 0f, -2f),
  new Vector3(-2f, 0f, -2f),
};

List<int> indices = new List<int>() {
  0, 3, 2, 3, 0, 1
};

How to extrude given plane in a certain direction? E.g 2f in y axis, it should form a bottomless cube.

I'm interested in how it works in general, not only this specific example.


texts: How to separate colliding objects without creating more collisions

texts:
Suppose I use a simple discrete collision detection system where I move all objects then check for collisions. I want any colliding objects to be separated (of course) and assigned appropriate response velocities (bounce, slide, stop, etc.).

When I have a pair of colliding objects, how do I separate them without ending up with one or both of them colliding with other objects?


texts: How to Subscribe to Events from Unity's VRInput Script

texts:
I am new to Unity and trying to modify the Unity tutorial Interactive 360 Sample. I want to be able to call a function when a user swipes using an Oculus Go Controller. I noticed that the VRInput script is included in the project, which seems to be able to detect swipe gestures.  But where do I attach that script, and how do I subscribe to the OnSwipe event.

I am currently trying by making an empty game object, and attaching the InputVR script as well as my own script called "GestureHandler" (I'm not sure whether InputVR is already attached to something else in the sample project, or whether I need to attach it at all). In my GestureHandler script I currently have the following:

using System.Collections;
using System.Collections.Generic;
using Interactive360.Utils;
using UnityEngine;

public class GestureHandler : MonoBehaviour {

    void onEnable(){
        VRInput.OnSwipe += HandleSwipe;
    }

    void onDisable(){
        VRInput.OnSwipe -= HandleSwipe;
    }

    void HandleSwipe(){
        Debug.Log("swipe");
    }
}

and currently have the following errors:

An object reference is required for the non-static field, method, or property 'VRInput.OnSwipe' [Assembly-CSharp]

No overload for 'HandleSwipe' matches delegate 'Action<VRInput.SwipeDirection>' [Assembly-CSharp]

An object reference is required for the non-static field, method, or property 'VRInput.OnSwipe' [Assembly-CSharp]

No overload for 'HandleSwipe' matches delegate 'Action<VRInput.SwipeDirection>' [Assembly-CSharp]


texts: Why are people developing and publishing games online without charging money?

texts: What's the incentive of sharing games one designs themselves for free online such as itch.io? I see people doing this and I don't understand.


texts: PreferredBackBufferWidth/Height from GraphicsDeviceManager not working?

texts:
It works fine in other "projects" so it has something to do with project.
The project im talking about here has tons of classes but nothing with graphicsdevicemanager other than game1.cs
game1.cs starts with

    GraphicsDeviceManager graphics;

then in public game1()

        graphics = new GraphicsDeviceManager(this);
        graphics.PreferredBackBufferWidth = 1024;

nope, the game is still 800x600.
I have also tried adding graphics.ApplyChanges(); while I dont need it in game1 and would be calling twice, still didnt work.

HOWEVER, if I add

        graphics.PreferredBackBufferWidth = 1024;
        graphics.ApplyChanges();

to "Initialize" (graphics' init is still from game1) it works

as you can see, I can fix it by going to Initialize and wasting some resource but I wonder why this is happening ? Im sure someone else in my code doesnt interfere.(I have no idea if something like this exist in properties etc. tho)


texts:
i have an cylinder with self-rotating script,

using UnityEngine;
using System.Collections;

public class rotate : MonoBehaviour {

    // Update is called once per frame
    void Update () {
        transform.Rotate (new Vector3 (0, 0, 30) * (float)5);
    }
}

i placed a cube  (not at center) with rigidbody on the cylinder, but it is not moving, anyone know how to make it moves according to the cylinder except using make parent?


texts: Setup script variables before attaching to an object

texts: I need to attach a script at runtime, but that script requires some public members to be set in order to be helpful. Is there a way for me to setup the public members of the script before attaching it to a GameObject at runtime?


texts: UE4 - custom template can only start with blueprints

texts:
I tried making a custom template for UE4 to help save some time during gamejams.
I follow this tutorial:
https://docs.unrealengine.com/en-US/Engine/Basics/Projects/CreatingTemplates/index.html
It works alright, even though some minor things don't work, like saving custom folder colors. But what really bothers me is this:

Normally, the options are Blueprint and CPP. I tried making a new template with a different config file, but nothing changes. Is there a way to fix it?


texts:
Im trying to randomly generate a map of rooms connected by doors, and I've succeeded in generating one using this code:

public void generate(GameContainer gc) {
        rooms = new ArrayList<Room>();
        startingRoom = new Room(0);
        startingRoom.setPosition(viewport.getCenterX(), viewport.getCenterY());
        lastRoom = startingRoom;
        rooms.add(startingRoom);
        int roomsize = 25;

        for (int i = 0; i <= (1000 + Math.random() * 4000); i++) {
            Room room = new Room(i + 1);
            int direction = (int) (Math.random() * (4));

            switch (direction) {
                case 0:
                    room.setPosition(lastRoom.x, lastRoom.y - roomsize);
                    break;
                case 1:
                    room.setPosition(lastRoom.x, lastRoom.y + roomsize);
                    break;
                case 2:
                    room.setPosition(lastRoom.x + roomsize, lastRoom.y);
                    break;
                case 3:
                    room.setPosition(lastRoom.x - roomsize, lastRoom.y);
                    break;
                default:
                    room.setPosition(lastRoom.x, lastRoom.y - roomsize);
                    break;
            }
            rooms.add(room);
            lastRoom = room;
        }
    }

However, this doesnt allow me to find out which doors the given room has. I need to be able to figure that out so that I can place the doors in the correct places so that they can be used to adjoin rooms. Is this sort of "smart map" possible with my current algorithm, or should I start over? What steps can I take to get this working?

I'm using Slick2d and Java for this

Thanks.


texts: Single object decreasing frame rate from 60 to 5

texts:
I'm new to game development and I'm not sure what I've done wrong. My game runs at about 60 frames per second until I add one instance of a model I made in Blender. As soon as I add it the frame rate drops between 5-6fps and even the Unity UI seems sluggish.

I created the model using Blender v2.77a and it has 25,925 vertices, 22,919 faces and 49,224 triangles in 3 objects plus an armature, camera and hemi light source (6 objects total). Two of the objects contain very little. They were made just for me to attach a line renderer in Unity. The third object contains the entire model so there is only 1 UV map. I created about 5 materials, Baked them to an image (using the Blender Game engine), then deleted the materials and made a single material to apply the image. Then I exported an fbx file (mainly so I could adjust the axis to match unity) and imported that along with the texture image in to Unity.

For some reason two volumes in my model also render in Unity with the faces facing the camera invisible. If I move the camera those faces become visible and the others become invisible.

My PC is a few years old now so it's not the fastest. But I didn't expect it to struggle with one object. I'm running an Intel Core2 Quad Q9400 (2.67GHz), 8GB RAM and a single Radeon HD5770. The hard drive is a standard SATA 2 with 7.2k spindle and I'm using Win 10 x64.

If you need any more info, please let me know.

Edit: Here's a screenshot of the Profiler.


texts: SteamVR locks position of dynamically created cameras

texts:
I'm having trouble tracking down a problem with SteamVR. Here is a quick way to set up an MWE:

Create a new Unity project.
Import the SteamVR package from the Asset Store.
Create the following script:

using UnityEngine;

public class CameraCreator : MonoBehaviour {
    private GameObject cameraObject;

    private void Start ()
    {
        cameraObject = new GameObject("CameraObject");
        cameraObject.AddComponent<Camera>();
        cameraObject.transform.position = Vector3.one;
    }
}

Create an empty game object and add this script to it.

SteamVR seems to lock this object's position (and that of any other game object with a dynamically created camera component) to the origin. No matter what I try to do to change it (inspector; set it inside update; set it in a coroutine), it always ends up back at the origin at some point during the frame (I believe somewhere between LateUpdate and OnRenderObject, but I'm not entirely sure). Without data breakpoints I find this really hard to track down.

This behaviour isn't really a problem for my actual project, but I need to be able to create cameras and modify their positions in my unit tests, where I'm having the same issue.

Does anyone know what's causing this, or have any advice on how to track down the cause?


texts:
sorry for the unhelpful title. I'm trying to understand how to convert information to bytes so that I can save it using Google's Saved Games feature that comes with Play Services, as explained here.

https://codelabs.developers.google.com/codelabs/playservices_unity/index.html?index=..%2F..%2Findex#9

I've mostly copy-pasted the code but it's not really working out for me.

However, my initial question is about bytes. So it looks like Google stores game information in bytes[] . The example only shows a single int being converted to byte and then being saved. What if I wanted to save multiple integers in Google's Saved Game services? I'm not exactly sure what this byte array is in the first place and how everything can be converted to bytes. If anybody has any good resources or examples, it would be much appreciated! Thank you


texts: Unity: Have raycast penetrate through other colliders/triggers

texts:
I have a setup where an enemy prefab has a trigger box that is in front of it:

Box and enemy itself is in the Enemy Layer.
Now I want to project a raycast to the Player, which is in Player layer.
[![enter image description here][2]][2]
But the raycast only hits the box(another layer) and does not hit the player at all.
If I invert the layermask it logs the box as the hit.
How can I make the raycast penetrate through the other object, I think setting up a layer mask was supposed to do it, but it doesn't work as I expected.
Also the box is a trigger:

Is it normal that the raycast be to stuck to other layers when cast via layermask?
Added the ignore trigger as a parameter but it didn't help.
This still happens when I change the layer of the box.
All the debug rays project correctly and I double checked the layering of objects.


texts: Figuring out which direction my object is facing on a 2D plane?

texts:
My friend and I were messing around in XNA 4.0 making a 2D racing game. Kind of like this one: Ivan “Ironman” Stewart’s Super Off Road. The problem we are having is knowing which direction the car is facing to move it appropriately. We could track the direction by a enum value North, South, East, West but we don't want to do that for a number of reasons.

We were wondering if there was a way to accomplish this via math. Maybe by having an anchor point designated at the hood of the car and having the car always move towards that spot and then move that anchor point. We aren't sure. Or maybe there is a way using a 2D Vector.

I figured since we hit a hard spot, we should ask the coding community for help!

Just to be clear. I'm not looking for code; I just want to discuss some concepts of 2D movement in all directions without having to track a direction enum. I know that can't be the only way to do it.


texts: How to calculate the outcome of a battle?

texts:
My game's war system is pretty straightforward, so I will give you a brief overview. You assign soldiers to commanders, and you also assign equipment. Equipment being weapons (e..g: rifles, pistols, etc ...) and vehicles (e.g.: tanks).

If a commander has 10,000 weapons in their inventory, and they only have 5,000 soldiers, then there will be 5,000 unused weapons in the commanders inventory. These unused weapons will not have any affect on the battle, but are still at risk to be lost during the fight (so it would actually be rather unwise for the player to assign that many weapons).

If a commander has 1,000 tanks - tanks require 3 soldiers - in their inventory, then the commander will need at least 3,000 soldiers to be able to use every single tank in battle.

If there are more soldiers than there are weapons and vehicles, then there will be some soldiers who are not assigned a vehicle or weapon, and so they will fight with their base/default stats.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Now for the actual mechanic that I seem to be struggling with:

Every soldier, weapon, and tank only has two variables that are used or considered in battle: attack & power.

Say a tank has 70 attack and 100 defense, and a rifle has 15 attack and 0 defense. These stats will be ADDED to the soldier's base stats.

Assuming that there is only the attacker's commander vs. the defender's commander of a city, no external forces or variables, I could simply calculate one commander's total combined attack & power, and if it's greater than the other commander, then I should declare him the winner.

Whether this is the best method for this I'm not sure yet.

But my current question is, how do I determine losses? How do I determine how many soldiers, weapons, and tanks either commander has lost during the fight?


texts:
I am making a 2D action-adventure platformer video game using the C++ computer programming language and the Simple DirectMedia Layer 2.0 (SDL 2.0.5) development library.

So far I have created over 50 levels, added enemies (with A.I.), assigned controls, animations, and of course, added the player.

As you know one of the most important features of a video game is the game save feature, in which the game software actually stores the data in the computer memory.

Is there any way to add this feature to my game using SDL 2? If so, please answer in detail with the nessecary code.

Thank you. You have been the most helpful.

Here are the items I'm using:

Microsoft Windows 10 (O.S.)
Microsoft Visual Studio Community 2017       (I.D.E.)

VSX 17 C/C++ Compiler (Compiler)
C++ (Programming Language)
Simple DirectMedia Layer 2 (Version 2.0.5) (Development Library)

Thanks again.


texts: I'm using Glut with OpenGL for drawing. Glut is very simple and straightforward but I have to give up Glut and move on toward SDL2. I'm reading SDL for Game Development, good book. I need to speed up a bit, so I'm looking for a list of comparisons between Glut and SDL2. At least with common similarities between the two. For example, in Glut we need for drawing Display() to be passed to glutDisplayFunc(). My understanding so far for SDL2 is that SDL_Renderer is like Display() in Glut. Is this correct? Also, what do exactly SDL_Surface and SDL_RenderPresent mean?


texts: Preventing XNA from anti-aliasing textures?

texts: It appears that if a image is undersized for covering the model it's set to cover, it anti-aliases instead of stretches. How can I control this behavior?


texts: Variable sized cube texture stretching problem

texts:
I have a 1x1x1 cube made in Blender with a simple UVW mapping. It represents a 3D platform of variable size.

The thing is that this cube gets resized a lot, and I want to draw a "border" of a fixed-length on each cube.

Another problem is that I am using Static Geometry, so I have to use a shader (I am using openGL, so I have to use GLSL).

So far I made this (note that the second platform is big, so it has larger borders):

What would you recommend to achieve this effect?


texts: Replacing keycode by UI Buttons doesn't work

texts:
I have tried everything but it still doesn't work. I am not talking about implementing functions wich has stuff inside when you click the UI Button. I want literally replace this Input.GetKeyDown(KeyCode.E). That is inside an if statement and replace with the UI Button object. How can i do this? I have tried with GetButton, GetButtonDown, trying to give a name and with Input.touchCount>0

I am developing a game like Resident Evil old style and when you enter a triggerStay and push the button, a text is showing up.

The Script

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

public class readingNote : MonoBehaviour {

    public AudioSource audio;
    public AudioClip collectSound;
    public  bool playerNextToKey = false;
    bool hasCollided = false;
    public GameObject pic;
    public GameObject text;
    public GameObject notePad;

    public Button yourButton;

    void Start()
    {
        pic.SetActive(false);
        text.SetActive (false);
        Button btn = yourButton.GetComponent<Button>();
        btn.onClick.AddListener(TaskOnClick);
    }

    void TaskOnClick()
    {
/*THIS IS SHOWING ALL TEXT IN THE SCENE AND NOT ONE BY ONE WHEN PRESSING*/
//      text.SetActive (true);
//      pic.SetActive(true);
    }

    void OnTriggerStay ( Collider other) {

        if(other.gameObject.tag == "Player") {
            if(Input.GetKeyDown(KeyCode.E)) {
            //if(Input.touchCount>0) {
                text.SetActive (true);
                pic.SetActive(true);

                AudioSource.PlayClipAtPoint(collectSound, transform.position);

            }

        }
    }

    void  OnTriggerExit ( Collider other  )
    {
        if (other.gameObject.tag == "Player")
        {
            //enter = false;
            //print("close");

            playerNextToKey = false;
            hasCollided = false;
            pic.SetActive(false);
            text.SetActive (false);

        }
    }

}


texts: How to make user move in virtual reality with Google Cardboard and Unity?

texts:
I am working on a virtual walkthrough using Google Cardboard in Unity 5.3.5.

I have a building, and I need to move around inside the room using google cardboard. How can I do that? Is it possible to move around when we walk holding the Google Cardboard? I have done movement using arrow key. I am able to turn around the building with Google Cardboard.


texts: I'm moving in the direction metaverse developing. A few years back I wandered around in Second Life and found it entertaining for a New York minute. Now, I'm set to plunge into the Virtual World/MMO enviroment. ReactionGrid's Jibe seems to be wonderfully paired with Unity3d. I've been a Unity developer for 5-6 years now. Is there a open source Virtual World Platform that integrates with Unity like Jibe? I've read an article on platforms like OGRE, Open Colbalt, OpenSimulator, Project Wonderland and Sirikata but none seem to mention working with Unity3d.


texts: How can I make an object move in four directions relative to its rotation?

texts:
I want to make a game object move in directions relative to the direction it is facing.
That is, if the user presses the "W" key the object goes "forward"; if they press "D" the object goes to its left. etc

So far I am having trouble, because I can't make it move in the correct direction when its rotated.
I just want some pseudo code to point me in the right direction, thank you.


texts: How to handle collision detection & response in voxel engine with slopes?

texts:
Voxels are fairly small
An object can span an area of 8x8x8 or more
Vertices of Voxel Type are always snapped to the grid:

Voxel types are convex (except the second type - which can be thought of as an OR between two rotated voxels of third type)
Including all the configurations of the above, there are 77 distinct voxel types.

Seems like there could be a fairly simple algorithm for doing collision detection and response between AABB / Bounding-Box / sphere and a single Voxel - considering the simple and rigid geometry restrictions in place, but I can't come up with one at the moment.


texts: In a scrolling 2D game, should the objects move or should the camera move?

texts:
I'm new to game design and don't really know how things are done. I'm thinking of building an iOS game where a ship has to fly as high up as possible (at variable speeds), collecting power ups, et cetera, on the way.

What is the way to go here? Should the background and items scroll down from the top or should the ship really fly up moving the view with it?


texts: How to place 10 static meshes in circular pattern so they are equaly aligned from the center ?


texts: How to manage "jump" in my 2d platform game?

texts:
I'm developing a simple 2d platform game with Unity 2d.
I have a problem managining my "Jump" action for the player.

I would like the player to Jump only when he has his feet on a "surface": terrain, platform, crate etc.
I'm considering using colliders: when my player collides with a surface, set my bool canJump = true.
When he jumps, I set canJump = false (he is midair).

My terrain has a Rigidbody2d is Kinematic and a Box Collider 2d.
My Player has a Rigidbody2d is Dynamic and a Capsule Collider 2d (or a Polygon Collider.. )

The events OnCollisionEnter2d() and OnTriggerEnter2d() are never raised when Player collides with terrain.

Does anyone know what's wrong?

Thanks

EDIT: Now i'm using this to check if "something" is under my feet:

RaycastHit2D hit = Physics2D.Raycast(rb.transform.position, -Vector2.up, 0.1f);
        if (hit)
            canJump = true;

It doesn't works!
hit is always true!
I'm getting mad!


texts:
I'm drawing lines using GL.lines but they disregard the zbuffer and always appear over my model.

I found this thread: http://answers.unity3d.com/questions/434827/gllines-over-game-objects.html

and decided to give the answers a try, but it didn't seem to fix things. For now I'm using the shader found in that thread, here is the rest of the code:

void OnPostRender() {
GL.PushMatrix();
testMaterial.SetPass(0);
GL.Begin(GL.LINES);
   for (int i = 0; i < basicMesh.linePoints.Length; i++)
   {
     GL.Color(new Color(1,1,1,1));
     GL.Vertex(basicMesh.linePoints[i].point1);
     GL.Vertex(basicMesh.linePoints[i].point2);
   }
GL.End();
GL.PopMatrix();
 }

Any advise on how to make the lines not go over my 3D models?


texts: Should I use a graphics engine or do the low level graphics myself?

texts:
Programming is more of a hobby for me right now as I'm still in highschool. When I get to college I plan to make it less of a hobby and more of a profession. But for now what would you guys suggest for making a 3D game in c++ (not c++11)? Should I learn and do the low level graphics myself or just use a graphics engine like Ogre while I learn the other aspects of making a game, or just use a full game engine?

My goal would be to learn. I want to learn how to do the lower level stuff such as graphics, physics, AI, ect. but I'm not sure if I should jump right into graphics or do the other stuff first.

I am currently taking the highest level math I can at my school (calculous) and might end up taking a c++ class at my local community college for a semester this year if that makes a difference.


texts: Updating the position of a prefab in Unity for A* pathfinding

texts: I am trying to use Aron Granberg A* pathfinding project in my game. I am very new to Unity, so I am having some trouble figuring out how to instantiate multiple enemies from a prefab that will seek out my player. I am unable to set the player object from the scene as the target, since prefabs cannot take in scene objects. However, if I use the player prefab as the target, the enemies will only go toward the starting position of the player. Is there any way to update the prefab position as the player instance moves? Or is there a better way of doing this? I want this to be a top-down shooter style game (2D) with constant enemy spawning, so it doesn't make sense to set the target for each individual enemy instance. Any help would be greatly appreciated. Thank you!


texts:
Given the sprites X and Y values, and the mouses X and Y values, how can I make the sprite face the mouse cursor?

I tried doing this in my move method which I found in another SO question:

    private function move(mousePosX:Number, mousePosY:Number) {
        if(key.isDown(Keyboard.A))
            this.vx -= this.speed;
        else
            this.vx *= this.friction;
        if(key.isDown(Keyboard.D))
            this.vx += this.speed;
        else
            this.vx *= this.friction;
        if(key.isDown(Keyboard.W))
            this.vy -= this.speed;
        else
            this.vy *= this.friction;
        if(key.isDown(Keyboard.S))
            this.vy += this.speed;
        else
            this.vy *= this.friction;

        this.x += vx;
        this.y += vy;

        // Make the player face the cursor
        this.rotation = Math.atan2(this.x - mousePosX, this.y - mousePosY);
    }

And rotation does happen, but it's of one or two pixels. this.x and this.y are the sprite X and Y values.

Cheers!

EDIT: Got it. here's the final calculation:

this.rotation = -(Math.atan2(this.x - mousePosX, this.y - mousePosY) * 180 / Math.PI);


texts: Instancing pixel shader parameters -- pass instance data through vertex shader?

texts:
I'm working on a deferred shader, and I want to use instancing to draw point lights.

From what I understand, I can send the instance data through the vertex shader and pass it through unchanged to the pixel shader. Is this the correct way to do it, or can I send the instance data straight to the pixel shader somehow?


texts: How do RPG games like Titan Quest, Diablo, WoW or similiar ones handle XP distribution?

texts:
For my own game I'd like to know if any of you have an idea about how some popular RPG games handle XP distribution? What I'd be particularly interested in is how the amount of XP a certain enemy gives the player after it's defeat is determined.

For my game I'm struggling to find a proper algorithm/formular to determine that specific amount, since it's a rather small game with not that many enemies types it might be okay to set a value for each enemy type by hand. At first I was experimenting with a formular which takes certain stats of an enemy and then calculates the amount of XP the enemy is 'worth' but as I already said I could not achieve a satisfying result by this.

Nonetheless it would be interesting to know how large games handle this determination. I'd assume that it's not done by hand because you have too many different enemies but I also might be wrong. If anyone could give me any insights or good reads on this I'd be very thankful.

Another thing I'd be interested in is how the XP gaining for the player with a level difference is handled. For instance: If the player is 10 levels ahead of an enemy he should gain 100% less XP from that enemy. If he is 5 levels ahead he only should get 50%. Of course that's a bit depended on my game and the entire design but would that be a common approach to deal with farming low level enemies and still gaining full XP from that? Or are there other approaches such games usually use?

Thanks for any hints, comments and opinions!


texts:
I am trying to figure out the best way to create a procedurally generated terrain at runtime in Unreal Engine 4. For the moment, my idea is to generate a heightmap and apply it to a plane as a displacement map, since it sounds a lot simpler than trying to procedurally generate a mesh.

Is it how it is generally done? And if not, will I run into issues by doing it this way?


texts: Can I optimize my voxel meshing regardless of different textured blocks?

texts:
At the moment, I mesh every voxel in my terrain data to a block with 4 vertices for each face. This makes assigning texture coordinates of my texture atlas very easy, since I can just pick the desired part for each face independently.

Unfortunately, rendering a bigger amount of such terrain chunks becomes very slow because of the unoptimized meshes. Therefore I want to redue the number of faces and vertices produced by the meshing algorithm. This is an image I found on the web showing what an optimized mesh could look like.

Grouping faces of different voxels make me think of how to still handle distinctive textures for each block. Is my worry right and how can this be handled?


texts: Loop through a loaded .x file's vertices

texts:
I need to compute the "gravity center" of a mesh, some kind of barycenter, and then find the farest vertices to compute a bounding sphere.

Here is what I have for the moment:

D3DXVECTOR3 result(0,0,0);
int num = mesh -> GetNumVertices();
LPDIRECT3DVERTEXBUFFER9 vertexBuffer;
mesh -> GetVertexBuffer((*vertexBuffer));
void* rawData;
vertexBuffer -> Lock(0, mesh->GetNumBytesPerVertex() * mesh->GetNumVertices(), &rawData, D3DLOCK_READONLY);
D3DVERTEXELEMENT9 decl;//[MAXD3DDECLLENGTH];
UINT numElements;
mesh -> GetDeclaration();
mesh -> GetFVF();

Apparently I need to cast the rawdata pointer, but I don't know what to do next...


texts:
I am using Ogre3D as my rendering API, and OgreBullet as my physics engine.

I have an test entity that when the y part of the velocity is 0 and spacebar is pressed, the velocity changes to, lets say: (10, 10, 0) that is a forward jump.

The thing is that when it arrives to the ground, instead of staying still (like any normal human jump) it bounces like a box and changes orientation.

What would be the correct way of implementing a human-like jump in 3D? I fixed it using a if() in the update loop that sets the y-velocity to 0 if it touches the ground, but this doesn't seem the correct way of doing it.


texts:
I'm trying to detect when a Group actor (my "slot") on my stage is clicked by add an InputerListener to the group. I've added the stage to my InputMultiplexer, but when I click on the actor, nothing happens.

Relevant code from the main Screen:

InputMultiplexer inputMultiplexer = new InputMultiplexer();
Stage stage = new Stage();
inputMultiplexer.addProcessor(stage);
Gdx.input.setInputProcessor(inputMultiplexer);

From the Group class:

Label amountLabel = new Label("", GameScreen.labelStyle);
Image itemImage = new Image();
Image slotImage = new Image(new TextureRegionDrawable(new TextureRegion(new Texture("Slot.png"))));
public SlotGroup() {
    this.addActor(amountLabel);
    this.addActor(itemImage);
    this.addActor(slotImage);

    this.addListener(new InputListener() {
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            System.out.println("Hello world");
            return true;
        }
    });
    this.setStage(Screen.stage);
}


texts:
Before I used GLU.gluUnproject to calculate my picking ray in my OpenGL game. Recently I switched to my own calculated matrices, and now I can forget the gluUnproject.

How can I calculate the picking ray with my own matrices?

My picking ray code (for the fixed pipeline):

public Ray getPickingRay() {
    FloatBuffer modelBuffer = BufferUtils.createFloatBuffer(16);
    FloatBuffer projBuffer = BufferUtils.createFloatBuffer(16);

    glGetFloat(GL_MODELVIEW_MATRIX, modelBuffer);
    glGetFloat(GL_PROJECTION_MATRIX, projBuffer);

    IntBuffer viewPort = BufferUtils.createIntBuffer(16);
    glGetInteger(GL_VIEWPORT, viewPort);

    FloatBuffer obj_pos = BufferUtils.createFloatBuffer(3);
    float middleX = (Display.getWidth() / 2)-0.01f;
    float middleY = (Display.getHeight() / 2)-0.01f;
    GLU.gluUnProject(middleX, middleY, 1.0f, modelBuffer, projBuffer, viewPort, obj_pos);

    Vector3f objPos = new Vector3f(obj_pos.get(0), obj_pos.get(1), obj_pos.get(2));

    Vector3f.sub(objPos, game.player.position, objPos);

    return new Ray(game.player.position, objPos);
}

At first I thought I just could use my own model- and projection matrix, but I have not found a way to manually calculate the GL_VIEWPORT intBuffer.

Thanks folks.


texts: Using a DirectX Vertex Shader to Modify the Vertex Data in VRAM?

texts:
I'm working on a GPU-side particle system in DirectX 11 where the vertex shader  uses a vector field encoded into the color channels of a texture to modify the positions of the vertices before drawing them to the screen.

I'm trying to keep the computations on the GPU rather than calculating the updated particle positions on the CPU and send the new vertex data to the GPU every frame, so I've been investigating the possibility of having the vertex shader overwrite the vertex buffer in VRAM with the updated vertex positions each frame. So far, I haven't managed to find anything on the topic.

Would this be possible, and if so, how would I accomplish it?


texts:
I'm trying to set a Occlusion culling on my topdown 2D game. I have made a sprite object with a Occlusion Area on it.Once I try to bake it, it gives me the following error:

No Renderers that are marked static were found in the scene. Please mark all renderers that will never move as static in the inspector.
UnityEditor.DockArea:OnGUI()

What exactly does this mean?

I'm using V5.3.2


texts: How can I render a simple lattice in LibGDX?

texts:
I have searched all over, but I can't find what I think will be a simple answer. I am using Opengl ES 2.0, and LibGDX. I simply want to use GL_LINES primitives to create a lattice structure.

I have used shapeRenderer with the following code:
in create():

shapeRenderer = new ShapeRenderer();
shapeRenderer.setProjectionMatrix(cam.combined);

in render():

shapeRenderer.setProjectionMatrix(cam.combined);
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(0, 1, 0, 1);
for (float i = -10; i <=10; i++) {
    for (float j = -10; j <= 10; j++){
        shapeRenderer.line(i, j, -10, i, j, 10);
        shapeRenderer.line(-10, i, j, 10, i, j);
        shapeRenderer.line(j, -10, i, j, 10, i);
    }
}
shapeRenderer.end();

The problem is, this is not a model instance, thus doesn't seem to use the RendererContext (GL_DEPTH_TEST, etc.). When I render the lattice this way, it either shows up entirely behind my models, or entirely in front of them (depending on the order I render them in the render method).

Is there a way to build a model which is simply a set of lines to be rendered with Opengl primitive GL_LINES? Any pointers would be greatly appreciated.


texts: What legal matters do I need to consider when releasing an MMO?

texts:
Let's say I've finished programming an indie MMO game similiar to Tibia. I've got:

a stable server application ready to launch;
a tested, bug-free, working client application ready to play;
the game's official website (ready to host), with a payment system and freely downloadable game client.

No matter how impossible it sounds, let's also assume none of these break copyright laws.

My game divides accounts into free and premium groups. Premium accounts can access all game features, requiring server authorisation to work properly. Let's say that the "premium account" can be bought on the website for a fixed monthly rate. Free accounts can play for free, but with limited access. This is what the mentioned payment system will be for. If I've correctly understood, this is the freemium model.

I'm completely novice to business entity issues, so
in short: what steps, in legal terms, do I have to take from here so my game can legally earn me money? For example, is there something like verification that the game gives the user what it actually offers when paying on its website?

If relevant, I live in Europe.


texts:
I'm trying to achieve a mirror effect where a second camera renders to a render texture, which is then passed into a shader using SetGlobalTexture.

Everything works fine outside of VR, but in Steam VR it seems like the render texture only stores the texture for one eye (left), even with single-pass stereo enabled in player settings.

How can I access the texture for the second eye? Or rather, how can I access the texture where both eyes have been drawn, one on each half of the screen?

What I'm doing at the moment:

void Awake()
{
    mirrorCameraRenderTexture = new RenderTexture(vrCam.pixelWidth, vrCam.pixelHeight, 24);
    mirrorCamera.targetTexture = mirrorCameraRenderTexture;

    Shader.SetGlobalTexture("_MirrorCameraRenderTexture", mirrorCameraRenderTexture);
}


texts:
How does Google match two players looking for a random game? For our app it is better to match people from the same location. Is Google already preferring people living closer together when matching them?

If not: Is there a better approach to match players than seperating the world by longitudes and latitudes, generating a unique id per square and use setVariant(id)?


texts: How to access `GameObject` to which `MonoBehaviour` is added from C# `Attribute`

texts:
Unity's RequireComponent inherits from System.Attribute. Somehow they made it that whenever component is added it has a reference to GameObject its being added to. So they can callAddComponent` to it.

I am trying to replicate that behaviour.

My theory is that because UnityEngine.RequireComponent has types stored inside class - they do it by reflection later. In method AddComponent<T> they get T class attributes from type and then try to cast them, get information from them, and apply to GameObject. If that is the case, then I doubt I will be able to do something with it, unless I have access to change AddComponent<T> somehow.

Is there another way around it?(that is no problem to do in code (just extension), but what about how it will work in inspector) Maybe apply different method to Unity`s default component addition.

EDIT

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class RequireComponentAttribute : Attribute
{
    public RequireComponentAttribute(Type type, int quantity)
    {
        if (quantity < 0)
            throw new ArgumentOutOfRangeException("Required components quantity cannot be negative");
    }

#if UNITY_EDITOR
#endif
}


texts: Do resolution settings have any impact or give any advantage in online FPS games?

texts:
There is this crazy theory that has always bothered me. I am not after a technically but more theoretically (although technical knowledge is required to) answer;

Two friends are playing the same video game over the internet (say ... CS:GO). The only difference is that Bob is playing on a 640x480 but Mike on 1900x1600.

Does the different resolution give any of them any advantage?


texts: Which part of MVC should be responsible for selecting a unit

texts:
Imagine a turn-based tile game, that generally looks like Heroes' combat view. Except for the fact a player can choose any of his units to command.

Our team is implementing the game according to MVC paradigm.

Some logic needs to be defined in order to allow selecting only allied units, for instance. And the selected one should be highlighted by the View.

For now we have made a Controller responsible for this. But to me it feels strange when the View is rendering data that comes from the Controller itself instead of the Model.

Is there any common practice to put such logic in Model or Controller?


texts: Is it legal to develop a game using D&D rules?

texts:
For a while now I've been thinking about trying my hand at creating a game similar in spirit and execution to Baldur's Gate, Icewind Dale and offshoots. I'd rather not face the full bulk of work in implementing my own RPG system - I'd like to use D&D rules.

Now, reading about the subject it seems there is something called "The License" which allows a company to brand a game as D&D. This license seems to be exclusive, and let's just say I don't have the money to buy it :p.

Is it still legal for me to implement and release such a game? Commercially or open-source? I'm not sure exactly which edition would fit the best, but since Baldur's Gate is based of 2nd edition, could I go ahead an implement that?

in short: what are the issues concerning licensing and publishing when it comes to D&D?

Also: Didn't see any similar question...


texts: Particle system: BlendMode of particle's draw call

texts:
I noticed by reading some tutorial around the web, that when dealing with particle systems, you can both use these approces:

Black background on the single particle and additive mode as blending mode for drawing
Transparent background on the single particle and alpha blend mode for drawing.

What are the differences between the two approces?


texts: What are the semantics of these quaternion functions in XNA/Monogame?

texts:
I am having trouble understanding the semantics of some members of the XNA/Monogame Quaternion class. The docs are not helpful, and tutorials trying to explain quaternions are using heavy math, which isn't helpful for me either, since I simply do not have proper background for that.

My main questions currently are:

Is there any difference between Multiply and Concatenate?
What is the exact difference between Inverse and Negate?


texts: Moving a 2D object along circular arc between two points

texts:
I have a sprite which I need to move along a curve between two points in 2D space. Speed must be consistent all the way. No physics involved. How can I achieve this?

The object is sun sprite.


texts: Moving an Object along a Curve while Rotating it

texts:
I woud like to move an object along a curve. At particular points on the curve, I wish the object to change speed and rotate itself along its axis.

Imagine an airplane flying to a destination. It has its path it must follow, plus, it adjusts its speed and orientation all the way (heading, pith, bank).

Could I kindly ask for a startup information on the following:

What kind of curves to use to smoothly interpolate an object
What formulas to use for reliable interpolation, where I could control the speed of moving oject, and the transition between curve knots would be seamless
What information should be exported from a 3D authoring application
Should I use quaternions slerp() for this?

If you know about a book that covers this topic efficiently, that would hlep the most. Thank you.


texts: Trying to use yield to wait for a few seconds to avoid the sounds from Interfering with each other

texts:
Ok so when my player hits a wall (Enemy tag). My player is destroyed after a certain amount of time. During this time, I disabled the mesh renderer on impact so it "appears" as if the player is destroyed.

I have some sounds I want to play upon impact. One is 'game over" sound and one is an "explosion sound".

right now, when they play at the same time, they interfere with each other, causing the game over not to be heard correctly.

I wanted to delay the output of "game over" by 3 seconds. So the explosion is over. Play the 'Game over sound' and then destroy the player.

This is my code so far, but the compiler tells me that now OnTriggerEnter cannot be an iterator block now that I have a yield function. Is there any way to just delay the output of the game over sound without creating a whole new function for the game over sound and using Play Delayed?

and if I do have to use Play delayed, how do I set the volume of the sound? as right now I am using PlayOneShot

     // function to detect whether collision is with a pick-up cube or an emeny wall.
void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("PickUp"))
    {
        // if pick-up object. Pick it up!
        float vol = Random.Range(volLowRange, volHighRange);
        playerSource.PlayOneShot(coinSound, vol);
        other.gameObject.SetActive(false);// other.gameObject should destroy here by the way.
        getCount = GameObject.FindGameObjectsWithTag("PickUp");
        count = getCount.Length;
        countCollected = countCollected + 1;
        SetCountText();
        if (count < 10)
        {
            // spawns new pick-up objects
            Invoke("SpawnObject", 2.0f);
        }
    }
    if (other.gameObject.tag == "Enemy")
    {
        // if enemy wall... kill the player it is game over
        rend.enabled = false;
        float vol = Random.Range(volLowRange, volHighRange);
        playerSource.PlayOneShot(deathSound, voldeath);
        playerSource.PlayOneShot(explosion, volex);
        yield return new WaitForSeconds (3);
        playerSource.PlayOneShot(gameOver, volgo);
        deathText.text = "GAME OVER!";
        Destroy(Player.gameObject, deathTime);
    }
}

Note: before the addition of yield the code runs perfectly and does everything I want it to.

Thanks for any help you can provide


texts: JNI multidimensional array as return value

texts:
I have some C++ code that I wrote to generate voxel terrain and would like to access it in JAVA. you pass it three integers; the seed and the coordinates of the chunk that it is generating (represented as int x and int y). It returns to you a 3D array of integers representing the value of each block in that chunk. In java I have:

private native static int [ ][ ][ ] genTerrain ( int seed , int x , int y );

And in the generated header I have:

#ifndef _Included_co_lambdas_koc_server_Terrain
#define _Included_co_lambdas_koc_server_Terrain
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     co_lambdas_koc_server_Terrain
 * Method:    genTerrain
 * Signature: (III)[[[I
 */
JNIEXPORT jobjectArray JNICALL Java_co_lambdas_koc_server_Terrain_genTerrain
  (JNIEnv *, jclass, jint, jint, jint);

#ifdef __cplusplus
}
#endif
#endif

And for the Class file I have tried:

JNIEXPORT jobjectArray JNICALL
Java_co_lambdas_koc_server_Terrain_genTerrain ( JNIEnv * env , jclass , jint seed , jint xCord , jint yCord )
{
    jclass intClass = env->FindClass("[I");

    jintArray x = env->NewIntArray ( 32 ) ;
    jintArray y = env->NewIntArray ( 32 ) ;
    jintArray z = env->NewIntArray ( 512 ) ;

    jobjectArray terrain = env->NewObjectArray(3, intClass, NULL);
    env->SetObjectArrayElement(terrain, 0, x);
    env->SetObjectArrayElement(terrain, 1, y);
    env->SetObjectArrayElement(terrain, 2, z);

    return ( terrain ) ;
}

Of-course this may be completely invalid as I have found little JNI documentation and haven't been able to understand much of what I have read. Could anyone show me how to generate a 3D JAVA int array (jint[][][]) in C++ through JNI?


texts: Rendering characters, with cut off limbs (Blender models in Java/OpenGL)

texts:
What aspects should I take into consideration for creating character animation and rendering classes if I want to be able to have detachable limbs? I've developed a detailed body system that can have everything down to the nervous system defined. I'm aiming for something similar to the level of damage detail found in Dwarf Fortress. For example, when a character takes damage to their upper arm, there is a chance of nerve damage that can disable the entire arm. Or they could lose the arm entirely.

I have a system written up for handling the data part of this. Each character has a trunk, which has appendages and internal parts. Each appendage can also have child appendages and internal parts. Child appendages are disabled/removed if a parent appendage is disabled/removed. If any of the disabled/removed appendages or internal parts are required for life, the character will soon die.

What I'm working on now is the drawing/animation portion of this. How do I define animations to know which ones are allowed given the current state of the body (missing arms/legs and so on)? How do I set up the drawing system to not draw missing limbs? Does each limb/appendage have to be its own model (I'd like to draw cut off appendages on the ground)?

The simple system I'm transitioning from (I just wrote it for testing) imports all the key frames of an animation as full models into a VBO (along with vertex counts for where key frames start/stop). It doesn't import or utilize the bones defined in Blender, and it doesn't interpolate between frames.

This is likely a pretty big question, so I'm also looking for resources that can get me where I need to go.

EDIT

I ask about the animation knowing which limbs it's animating because I would like to have it set up to perform an alternate animation if a required limb is missing. After thinking about that, I imagine I would perform that check before activating an animation, and activate the appropriate animation at that time.


texts: What is the best way to remove a list reference after the object has been deleted at edit time?

texts:
Inside a MonoBehaviour MyComponentA I have a list of MyComponentB (also a MonoBehaviour) like so:

List<MyComponentB> myList;

This list gets populated mostly through editor scripts at edit time.
Now say that someone who is editing the scene comes along and deletes a game object that has MyComponentB attached, and also happens to be referenced by the list above.

How can MyComponentA fix the list to remove null references after such a deletion? I basically want to make this automatic so that when designers delete these objects, they dont have to go hunt down which MyComponentA referenced them and fix the list.

My naive approach was to have a circular reference from MyComponentB to MyComponentA (so that it knows which list it belongs in), and then unregister it properly when OnDestroy gets called. This however doesn't work at edit time unfortunately since OnDestroy is not called.

Thanks for your help!


texts: Is finding graph minors without single node pinch points possible?

texts:
Is it possible to robustly find all the graph minors within an arbitrary node graph where the pinch points are generally not single nodes? I have read some other posts on here about how to break up your graph into a Hamiltonian cycle and then from that find the graph minors but it seems to be such an algorithm would require that each "room" had "doorways" consisting of single nodes.

To explain a bit more a visual aid is necessary. Lets say the nodes below are an example of the typical node graph. What I am looking for is a way to automatically find the different colored regions of the graph (or graph minors)


texts: Room generation with external walls and doors

texts:
I am looking to implement a means to generate rooms with outer walls with windows and doors from prefab game objects in Unity.

The idea is that a group of tiles is defined as a room which I then iterate through to find the outer tiles and then use their external edges to generate the walls of the entire room. Gathering the outer tiles is easy enough and working out the external edges is already implemented.

What I need to understand is the best approach for using prefab game objects as the set pieces for walls and floors.

Currently for a single wall piece, I have created a quad and made that into a prefab which I then clone, position and rotate into place along the outer edges. The below screenshot shows a room with walls made using the prefab wall GameObject. In this screenshot, the room consists of 12 wall GameObjects. I want to avoid having lots of GameObjects for single wall segments and instead perhaps merge them all into a single mesh on a single GameObject.

What I would like to achieve is to be able to create a consistent set of pieces for each outer wall, with windows and doors (most likely cloned from other prefabs) to build a realistic looking room. For example, any single length of a wall would be made up from

Wall -> Wall -> Window -> Wall -> Wall

Perhaps there is a much easier way to achieve this that I have overlooked but searching for room generation always leads back to examples for dungeon crawlers and roguelikes. I am not creating a dungeon crawler, nor am I generating the environment proceedurally, instead the player will be able to create rooms in a similar fashion to Evil Genius and The Sims.

In the current approach, creating a room which is 5x5 would mean that there are a total of 20 wall GameObjects and 25 floor GameObjects. I am not keen on having this many objects in the scene for a single room. I would prefer to be able to create a mesh for the entire room, adding in the vertices and triangles from the prefab mesh to cut down on the number of GameObjects in the scene.

Does anyone have any experience with building rooms in this fashion, or are there any clear examples of how to achieve this? I am not sure how to translate and rotate a prefab and then merge the translated meshes into a single mesh. Perhaps I am barking up the wrong tree and there is a better approach but for now, this is the only way I can see which is possible to achieve what I want.


texts:
libGDX using Stage and Actor produces different camera angles on desktop and Android Phone.

Here are pictures demonstrating the problem: http://brandonyuh.minus.com/mFpdTSgN17VUq

On the desktop version, the image takes up most all the screen. On the Android phone it only takes up a bit of the screen.

Here's the code (not my actual project but I isolated the problem):

package com.me.mygdxgame2;
import com.badlogic.gdx.*;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.scenes.scene2d.*;
public class MyGdxGame2 implements ApplicationListener {
    private Stage stage;
    public void create() {
        stage = new Stage();
        stage.addActor(new ActorHi());
    }
    public void render() {
        Gdx.gl.glClearColor(0, 1, 0, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        stage.draw();
    }
    public void dispose() {}
    public void resize(int width, int height) {}
    public void pause() {}
    public void resume() {}
    public class ActorHi extends Actor {
        private Sprite sprite;
        public ActorHi() {
            Texture texture = new Texture(Gdx.files.internal("data/hi.png"));
            texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
            sprite = new Sprite(new TextureRegion(texture, 0, 0, 128, 128));
            sprite.setBounds(0, 0, 300.0f, 300.0f);
        }
        public void draw(SpriteBatch batch, float parentAlpha) {
            sprite.draw(batch);
        }
    }
}

Why does this happen?


texts:
I'm implementing a Bomberman-esque game in which players try to eliminate each other on a square tile-based arena. I'm currently implementing powerups that give the player who collected them a bonus (such as a larger inventory or faster movement speed).

How should the game system place these powerups such that, provided players collect powers closest to them, the game remains fairly balanced?

My first approach was to spawn a powerup on a random empty tile every few seconds. The problem with this purely random approach is that a player can have a massive advantage early in the game just by the luck of having many powerups spawn near them.

Ideally, I'd like powerups appear equally often near each player, but occasionally spawn near the map's center to encourage competition. To be clear, I do want some element of randomness -- specifying exactly which powerups spawn when and where would make the game predictable and dull.

What alternatives exist?


texts: How can I reduce a frustum to the subset that passes through a portal AABB?

texts:
I'm trying to implement portal based occlusion culling:

There are sectors and portals.

When a portal is visible, the sector it is connected to is rendered.

The sector is made of polygons and portals.

The sector is sealed by a portal to the next sector.

The portal has an axis aligned bounding box.

The view frustum has an array of mathematical planes in it. There is top, bottom, left, right, near and far.

The view frustum planes change shape when in contact with a wall.

When the view frustum planes are in contact with the portal's AABB, the sector get rendered.
Then an array of mathematical planes are added behind the portal to create a reduced view frustum.

Reduced frustums are made from other portals in contact with the view frustum until there are no more portals in view.

How can I perform the bolded step, where I find a new collection of frustum planes representing the portion of the original frustum that continues through the portal's AABB?


texts: In my tile-based game, GameObjects are stored in a std::map, but I want the GameObjects to be in control of their position!

texts:
GameObjects are stored in a Tilemap class, within a std::map<Vec2Int, GameObject> container. The Vec2Int struct describes the object's x and y coordinates. Each GameObject also contains a Vec2Int describing the same thing.

There are two things I would like to do (unless there is an entirely different/better way):

The Tilemap should be able to traverse all GameObjects so that they may be drawn to the screen. The Tilemap uses a Camera class so that it can figure out which tiles/objects can be seen in the current camera view.
However, GameObjects should be in control of their own position, not the Tilemap! The GameObject should be able to reposition itself by simply changing its x or y coordinates

For reference (I've only included the relevant stuff):

struct Vec2int {
    int x, y;
};

class Tilemap {
    public:
        Tilemap(const int &w, const int &h);
        void LoadLevel();
    private:
        //A 2D array of Tile pointers
        std::vector<std::vector<Tile*>> _tileMap;
        std::map<Vec2int, GameObject*> _objects;
};

class GameObject : public Tile {
    public:
        GameObject(const int &tileID, const Vec2int &position);
        //virtual void Update() = 0;
    private:
        Vec2int _position;
};


texts: Designing Character Movement Need Advice

texts:
(This game is written in C++ with GDI+ It's a simple side-scroller.)

I am having a problem deciding on how I should handle player movement. Currently it runs at 20 frames per second (I just chose that number, it could no doubt run at higher fps.)

Now I have one function that moves the character 1 pixel. It checks collisions with anything around.

There is two ways I can do this (because moving 20px/ second is too slow.)

I can use a for loop and then I can move any amount of space per frame. One minor problem is that the player will be moving several pixels between screen updates, so the player moves 5px (or any amount) increments every second.
I can turn up the fps, and then, consistently move the character 1px per frame, and it would be smooth movement.

I am having trouble deciding which way of doing this is better and need a bit of input, ideas, advice, etc...

Thanks.


texts: Procedural generation of evenly distributed random points (2d)

texts:
I am coming here because I've have a performance problem with my current implementation of an algorithm. I am the idea of Voronoi diagrams to distribute patches on an infinte 2d layer.

For a Voronoi pattern you need to have a set of points which is in my case procedural generated to allow an infinite generation of the Voronoi pattern.

And there is the problem. I have an algorithm which requires uses a grid of interval for the distance between each point on the grid. But I don't want a perfect square pattern so I add a randomization to each point on the grid with amplitude as possible randomization on X and Y axis.

Here you can see how the points are shifted by adding the randomiation. (The randomization depends on the coordinates of the point on the grid to allow procedural generation. They are generatied by a noise map, but let's assume they are just a seed for a RNG)

And now we come to the performance problem. I have a point (x,y) which I need to find the nearest point. So what I do is I take all points within the maximum randomization amplitude and apply the randomization to get the points in my layer.

Now I take the random point with the shortest distance to my point (x,y) and return it.

The performance of the code is exploding very quickly though.

n = amplitude / interval
runtime = (2n + 1)^2

A basic shape of the code is here, in the actual code I already use caching to avoid costly randomization of one point multiple times.

Vector2d currentlyBest = null;
double bestDistance = Double.POSITIVE_INFINITY;

double gridX = round(x / interval) * interval;
double gridY = round(y / interval) * interval;
for (double ix = 0; ix <= interval + amplitude; ix += interval) {
    for (int loopX = -1; loopX < 2; loopX += 2) {
        double dx = gridX + ix * loopX;
        for (double iy = 0; iy <= interval + amplitude; iy += interval) {
            for (int loopY = -1; loopY < 2; loopY += 2) {
                double dy = gridY + iy * loopY;
                Vector2d point = new Vector2d(dx, dy);
                randomizePoint(point);

                double px = point.x - x;
                double py = point.y - y;
                double disSq = px * px + py * py;
                // save point if disSq is smaller than before
            }
        }
    }
}

Thanks for reading so far! My question now is, if anyone knows a way to improve that or if you know a better way to produce evenly distributed randomized points on a 2d layer.

Thank you very much!

PS: I am not allowed to post more images so I can't give you more images, sadly :(


texts:
I'm trying to create a stamina script, where you can only use rb.AddForce (movement) if you have stamina, else you shouldn't be able to move.

Here is my code so far (with help from here):

using UnityEngine;
using System.Collections;

public class PhysicsBall : MonoBehaviour {

    public float speed;

    private Rigidbody rb;

    public float maxStamina; // from the editor
    public float staminaReconveryRate; // from the editor
    public float staminaDrainRate; // from the editor
    public float joystickDeadband; // from the editor
    private float currentStamina;
    public float nothing;

    void Start ()
    {
        rb = GetComponent<Rigidbody> ();
        currentStamina = maxStamina;
    }

    // Update is called once per frame
    void FixedUpdate () {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        // Make sure the player actually ask to move; this is done to avoid spending stamina when
        // not expecting it
        bool hasHorizontal = false;
        bool hasVertical = false;
        if ( moveHorizontal > joystickDeadband )
            hasHorizontal = true;
        else
            moveHorizontal = 0.0f;

        if ( moveVertical > joystickDeadband )
            hasVertical = true;
        else
            moveVertical = 0.0f;

        // player requests to move
        if ( hasHorizontal || hasVertical )
        {
            // and has stamina
            if (maxStamina > 0.0)
            {
                // lets move him and consume stamina
                Vector3 movement = new Vector3 (moveHorizontal, 0, moveVertical);

                rb.AddForce (movement * speed);

                currentStamina -= Time.deltaTime * 70;
            }
        }
        else
        {
            // the player does not request to move, so we restore the stamina.
            moveHorizontal = 0.0f;
            moveVertical = 0.0f;
        }

    }

    void Update () {
        Debug.Log (currentStamina);
    }

}

Some of the code may be irrelevant as I'm building it off another answer I got but I can't seem to fix some of the bugs:

I can see the stamina decreasing to negative figures, which is good,
but even after it becomes negative the character is still able to
move normally.
The character can only move UP and to the RIGHT, not BACK and to the LEFT??


texts: How can I transform a group of objects in libGDX?

texts:
I'm new in LibGDX.
I created group with actors in show method and add listener (where i calculate rotation matrix) and want to rotate all actors from group with batch.setTransformMatrix(matrixResult); but nothing happens. How can I force to rotate all actors of group?

 @Override
   public void show() {
      camera = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
      camera.position.set(0f, 0f, - 120);
      camera.lookAt(0,0,0);
      camera.near = 0.1f;
      camera.far = 300f;

      camera.update();
      stage = new Stage();
      shader = new ShaderProgram(vertexShader, fragmentShader);
      myBatch = new SpriteBatch();
      shapeRenderer = new ShapeRenderer();
      sphere = BuildSphere(5, 100);
      group = new Group(){
         @Override
         public void draw(Batch batch, float parentAlpha) {
            batch.setTransformMatrix(matrixResult);
            super.draw(batch, parentAlpha);

         }
      };

      group.setTouchable(Touchable.enabled);
      group.addListener(new InputListener(){

         @Override
         public boolean touchDown(InputEvent event, float x, float y,
               int pointer, int button) {
            Gdx.app.log("MOUSE_X_BEG", Float.toString(x));
            Gdx.app.log("MOUSE_Y_BEG", Float.toString(y));
            begX = x;
            begY = y;
            return true;
         }
         @Override
         public void touchDragged(InputEvent event, float x, float y,
               int pointer) {
            endX = x;
            endY = y;
            //isRotate = true;
            float translationX = endX-begX;
            float translationY = begY-endY;
            float length = (float)Math.sqrt(Math.pow(translationX,2) + Math.pow(translationY,2));
            Vector3 axis = new Vector3(0, 0, 0);
            if(length>0){
               if(begX-endX == 0){
                  axis.x = 1;
               }else{
                  float angle = (float) (Math.atan(translationY/translationX) + Math.PI/2.0*(translationX <0 ? -1 : 1));
                  axis.z = 1;
                  axis.x = (float) Math.cos(angle);
                  axis.y = (float) Math.sin(angle);
               }
            }
            quaternion = new Quaternion(axis, 0.02f*length);
            Matrix4 rotation = new Matrix4(quaternion);
            matrixResult = rotation.mul(matrixRotationOld);
            matrixRotationOld = matrixResult;

         }

      });
      //group.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
      for (CenterCoordinate cenCoordinate : sphere.getPolygonCenterCoordinates()) {
         Vector3 vector = cenCoordinate.getCartesianCenter();
         Polygon polygon = new Polygon(1, cenCoordinate.getType().getCode(), cenCoordinate.getRadius(), cenCoordinate.getPsi(),
               cenCoordinate.getKsi(), vector, cenCoordinate.getRotation());

         group.addActor(polygon);
      }

      stage.addActor(group);
      Gdx.input.setInputProcessor(stage);

   }

Polygon extends Actor draw method :

         @Override
  public void draw(Batch batch, float parentAlpha) {
     translation.setToTranslation(vertex.x, vertex.y, vertex.z);
     matrix.mul(translation);
     shader.begin();
     shader.setUniformMatrix("u_worldView", matrix);
     mesh.render(shader, GL20.GL_LINE_LOOP, 1, mesh.getNumVertices()-1);
     shader.end();
     matrix.idt();

  }


texts: how are the vertex properties of meshpart decided based on model format in xna

texts:
Exactly how the question says , how does the vertex properties like vertex stride and the data stored in the mesh part decided based on the format of a model and how would i determine that and then decide which vertexdeclaration to be used properly

For ex - a .obj model might or might not have vt data , vn data based on which it may have a different data in the meshpart .
How would i go about deciding which vertex declaration to use to properly decode the data in that mesh's vertex buffer


texts: Graphic render speed in libgdx using many sprite sheets

texts:
I am currently working on a customizable Player-character for my top down view 2D pixel game. I am using libgdx and aiming for android devices as well as desktop applications.

I am wondering about an efficient, but yet simple concept. So far my character is build up from different parts ( Feet, Body, Shoulder L, Shoulder R, Hand L, Hand R, Head, Haircut). Every part has its on layer, thus they are 8 layers already. My animations (for example walk cycle) has 8 frames. My character fits on a 24 x 48 px image, thus the naked walking character sprite sheet, with all body parts having their own image and keyframe ends up in having 8 layers x 8 images (24x48 px) = 64 frames.

This fills up 40% of a 512 x 512 sprite sheet. This is only for the walking down animation, weapons would be rendered from a separate sprite sheet, underneath the hands. So for the other 3 directions ( okay maybe they fit here), but certainly for other states (dying, hitting, casting spells) I would need separate character sheets.

Now my questions:

Since my character is customizable, it could end up that every layer has to be taken from a different sprite sheet ( naked head, metal armor, poor gloves, icy shoes etc) thus I would need to switch my textures a lot since they can't possibly fit on one sheet. Sometimes I have to use a sheet again later like: render body and so on naked, bind sword sheet, render weapon, use body parts sheet again and render hands on top.

Questions:

1.
In an old book by Mario Zechner I read that sprite sheets with a size of 512 x 512 px are good to go for, since older devices still support this size. Is this still up to date or can I go for bigger Textures (which I then split in TextureRegion Arrays to use for the Animations).

2.
Currently I tested using one sprite sheet (the one above) and took 7 TextureRegion Arrays to store the images of all body parts, then I created 7 Animations, which I render all on top of each other in the corresponding order.

Is it good to do so? Should I rather combine all the textures in a pre rendered TextureRegion (or so) and use this in ONE animation instance?

What are the expensive calls? Are they hidden in the use of the many animation instances? Is it the use of many TextureRegion instances?

As far as I can see I only use the texture ( sprite sheet ) in the beginning anyways to then split it up in my TextureRegion Arrays, which are then used in the render method. So does it even make any difference if I would be using different textures which I'd split up at the beginning? Would this splitting-up and preparing take much time if done during the gameplay? Currently I set it up in the create method. How much / many TextureRegions can be stored in memory simultaniously (since if all sprite sheets fit into memory I could preload them like this during the splash screen). Do I even need to worry about this with my low Pixel Resolution Assets?
How to get a feeling for this?


texts:
I've been trying some different approaches for collision detection and now I want to try to implement simple Mesh-Mesh collision detection for triangular meshes. I'm wondering if I'm on the right track, or if I'm missing something critical.

My general idea for collision detection involves a moving object with no rotation, against stationary objects. I also want the moving objects to slide across the surface/ edge of stationary objects in which they collide. The algorithm is:

  Make a list of all the stationary objects which are in range of the moving object origin.
  Add to the list of all the stationary objects which are in range of the displaced moving object
  Sort the list by shortest distance to the moving object origin.
  Iterate through the list and detect collisions between the displaced moving object and stationary object

  find the shortest distance in which a vertex of the moving object passes through a triangle of the stationary object (or vice versa).
  find the shortest distance in which an edge of the moving object passes through an edge of the stationary object.
  If shortest distance was vertex

  Project the displacement across the broken triangle plane and locate the end point.
  Recalculate the displacement using this end point and the origin
  Restart iterations

  If shortest distance was vertex

  Project the displacement across the plane created by these two edges at the point of contact. Find the end point of this projection
  Recalculate the displacement using this end point and the origin
  Restart iterations

  If no collisions found then continue iterating

  Apply final displacement to position of the moving object

The reason the iteration is repeated after a collision is found is to avoid the case where the resolution causes a new collision in previously checked objects.

To get the vertex and edge intersections I have made two equations, both of which have M as the displacement I wish to apply to the moving object.

All capital variables are Vec3's, Two capitals next to eachother are deltas AB == B - A. lowercase variables are scalars. Mat3's take Vec3's as columns

This is my equation for testing a moving vertex against a stationary triangle:

//Ray:
P = M*t + Q
//Trianlge:
P = A + AB*u + AC*v
//Ray-Triangle Intersect:
M*t + Q = P = A + AB*u + AC*v
AQ = -M*t + AB*u + AC*v
AQ = Mat3(-M, AB, AC*v) * Vec3(t, u, v)

Vec3(t, u, v) = Mat3(-M, AB, AC*v)^-1 * AQ

t, u, v must all be [0,1], and u + v <= 1 for a collision to occur

This is my equation for testing a moving edge against a stationary edge:

//Moving Ray:
P = AB*u + M*t + A
//Stationary Ray
P = CD*v + C
//Moving Ray - Ray Intersect
AB*u + M*t + A = CD*v + C
AC = M*t + AB*u - CD*v
AC = Mat3(M, AB, -CD) * Vec3(t, u, v)

Vec3(t, u, v) = Mat3(M, AB, DC)^-1 * AC

t, u, v must all be [0,1] for a collision to occur

So how does this look?


texts:
I have skinned and rigged a human character with IK / FK and helper objects to control the position of the IK goals and the rotation of the bones. For example, the characters' left arm IK goal is parented to a point helper, to make it easier to select and move around and the arm IK solves accordingly.

I have the skeleton (without the helpers) set up as an avatar in Unity and I want to use this rig to create and export animations to work with the avatar.

I create animations by moving the helpers in Auto Key mode in 3DS Max, so that when the helpers move, their new transform details (pos, rot, scale) are recorded in key frames.

My questions is this: using Auto Key only records the transform of the helpers I'm moving, it does not record the bone transforms, even though they have been changed by moving the linked helpers. Is there any way to record bone positions using Auto Key with this rigging method, or do I have to select the affected bones every time a movement is made and use Set Key?


texts: What is the difference between a game director and game producer?

texts:
I was browsing through the list of games Hironobu Sakaguchi has worked on and noticed that he is credited differently from game to game. Just to cite a few games from that list, he is credited as:

Director in Final Fantasy 1 to 5, The Last Story
Producer in Final Fantasy 6, 7, 9 and Tactics, Lost Odyssey
Executive Producer in Xenogears, Vagrant Story, Final Fantasy 8

This made me realize that I do not know the difference between these positions and in what ways do they contribute to the game development process.


texts: How do I prevent falling tiles from bouncing on each other in my match 3 game?

texts:
I am working on a match 3 game in Unity. The tiles have a RigidBody2D in dynamic mode and a BoxCollider2D. When a match occurs and the tiles are removed, the tiles above (including spawned replacement tiles) fall until they land on another tile or the tile catcher at the bottom of the board. There is a routine which checks when everything is settled (all tile rigidbodies are asleep) and then processes any new matches. However, the tiles push each other down on impact, causing a rebound and a very slow process of "settling" to their final position. The physics material for the tiles has no bounciness, so I believe this is being caused by the cumulative force of the tiles landing on each other in the physics simulation.

What I'm hoping to do is have the tiles drop the way they do (the gravity simulation is just right!) but essentially stop when they collide with another tile (i.e. not transfer any force at the point of collision). This way, they shouldn't rebound visually and also should sleep more rapidly, so matches from falling can process more immediately.

So far, the suggestions I've seen are:

Set the velocity to 0. This doesn't work, and I assume it's because there is still being force applied.
Detect the tile collision and set the tile to kinematic, then set it back to dynamic. I haven't been able to get this to work, as they won't turn back to dynamic. I even tried to disable the colliders until they turn back in case the collision detection keeps happening and is just overwriting it too rapidly. At any rate, this feels like a dead end.
Scrap the rigidbodies and essentially write my own, scripted gravity simulation. I'm simply hoping to avoid this because the rest of the simulation is working great.
Create a kinematic rigidbody on a child object, set the dynamic parent and kinematic child to ignore collisions with each other, make the kinematic collider slightly (0.1) larger so it collides first. I gather the idea here is to have the physics simulation pull down the dynamic body, while the kinematic child will stop on collision. At any rate, this also did not work, and also sounds like a bad idea.

I've considered trying to calculate the impact force and apply an equal opposing force, but I haven't figured that out yet, and I imagine at that point I should just write my own gravity simulation, per above.

I've recorded a video for visual reference on the "bounciness": https://youtu.be/aSCEJX4nzoI


texts: Is it better to create a scene in blender or in unity?

texts: First of all, I am really new to all of this. This is my first time so its really confusing me if it's better to create a scene and then import it into Unity or is it better to just create objects like chracters, chairs in blender and scenes in Unity? I just want to recreate a scene of my school and include it in my final project as a Unity game where it will have no function other than walking around and some jumping and fighting? Because my project is not based on the game, it will just help it.