texts: Can you help me resolve a bug in mesh collision code?

texts:
I have entities which walk along a 3D mesh. I move the units along their x,z axis, and every frame I update their y-position according to the quad or triangle they are standing on, using Barycentric coordinates. They do walk along the mesh, however every time they enter a new quad or triangle, they "bob" up and down on the y-axis.
Height testing is done by finding the "bottom-left" vertex of a "sqaure" of four vertices made by converting the unit's x,z position into a 1d index into an array of vertices.
They move smoothly until they enter a new part of the mesh, where it looks like their y-coordinate shifts once very noticeably and then keep moving smoothly. It happens both when testing against the square made by the four vertices around the unit, and with testing against triangles of mesh.
Here is the code to find y-coordinate on a square:
float px = batchTranslation[ i ].Value.x;
float pz = batchTranslation[ i ].Value.z;

int index = ( int ) ( ( math.floor( pz / MAP_SCALE ) ) * MAP_SIZE + ( math.floor( px / MAP_SCALE ) ) );

int bL = index;
int bR = index + 1;
int tL = index + MAP_SIZE;

float3 p1 = vertices[ bL ];
float3 p2 = vertices[ bR ];
float3 p3 = vertices[ tL ];

float3 normal = math.cross( ( p2 - p1 ) , ( p3 - p1 ) );

float py = ( normal.x * ( p1.x - px ) + normal.z * ( p1.z - pz ) + normal.y * p1.y ) / normal.y + HALF_HEIGHT;

batchTranslation[ i ] = new Translation { Value = new float3( px , py , pz ) };

Here is the code for finding the y-coordinate on the triangles of the mesh:
float px = batchTranslation[ i ].Value.x;
float pz = batchTranslation[ i ].Value.z;

int index = ( int ) ( ( math.floor( pz / MAP_SCALE ) ) * MAP_SIZE + ( math.floor( px / MAP_SCALE ) ) );

int bL = index;
int bR = index + 1;
int tL = index + MAP_SIZE;
int tR = index + MAP_SIZE + 1;

float3 V1 = vertices[ bL ];
float3 V2 = vertices[ bR ];
float3 V3 = vertices[ tL ];
float3 V4 = vertices[ tR ];

float py = batchTranslation[ i ].Value.y;

if ( IsInside( V1.x , V1.z , V2.x , V2.z , V3.x , V3.z , px , pz ) )
    py = CalcY( V1 , V2 , V3 , px , pz );
else if ( IsInside( V1.x , V1.z , V2.x , V2.z , V4.x , V4.z , px , pz ) )
    py = CalcY( V1 , V2 , V4 , px , pz );

batchTranslation[ i ] = new Translation { Value = new float3( px , py , pz ) };

private float Area( float x1 , float z1 , float x2 , float z2 , float x3 , float z3 )
{
    return math.abs( ( x1 * ( z2 - z3 ) + x2 * ( z3 - z1 ) + x3 * ( z1 - z2 ) ) / 2.0f );
}

private bool IsInside( float x1 , float y1 , float x2 , float y2 , float x3 , float y3 , float x , float y )
{
    float A = Area( x1 , y1 , x2 , y2 , x3 , y3 ); // Calculate area of triangle ABC
    float A1 = Area( x , y , x2 , y2 , x3 , y3 ); // Calculate area of triangle PBC
    float A2 = Area( x1 , y1 , x , y , x3 , y3 ); // Calculate area of triangle PAC
    float A3 = Area( x1 , y1 , x2 , y2 , x , y ); // Calculate area of triangle PAB
    return ( A == A1 + A2 + A3 ); // Check if sum of A1, A2 and A3 is same as A
}

// Returns y coordinate of point on triangle given point x and z coordinates
private float CalcY( float3 p1 , float3 p2 , float3 p3 , float x , float z )
{
    // determinant
    float det = ( p2.z - p3.z ) * ( p1.x - p3.x ) + ( p3.x - p2.x ) * ( p1.z - p3.z );

    float l1 = ( ( p2.z - p3.z ) * ( x - p3.x ) + ( p3.x - p2.x ) * ( z - p3.z ) ) / det;
    float l2 = ( ( p3.z - p1.z ) * ( x - p3.x ) + ( p1.x - p3.x ) * ( z - p3.z ) ) / det;
    float l3 = 1.0f - l1 - l2;

    return l1 * p1.y + l2 * p2.y + l3 * p3.y;
}
```


texts: Setting up a Visual Studio project for OpenGL and OpenGL ES

texts:
I want to make a small game with OpenGL and glew for desktop, android and web.

So far I know how to set up a project for opengl and a project for opengl es but I would like to have the game source code just once. For the web version I want to use emscripten.

Now my question is how do I set up the project for this? I thought about making three projects in one solution: One for OpenGL, one for OpenGL ES and one for the game itself. But should I include the OpenGL projects into the game project (and choose the correct one when initalizing/drawing)? Or should I include the game project into the OpenGL projects and have a single game object which returns all the objects to draw?

Or is this a bad approach and can be done better?


texts:
I'm coding (or at least trying to code) a single player game in pure JS. I was wondering how I was gonna be able to write data without having the user setting up a server or a database, only way I found is local storage.

I'm aware that this kind of data is attached to the browser but I don't think someone would swap between browser, IMHO people start with one and stick to it. What I'm more concerned about is what else in the local system can modify this storage?

For instance, can cleaning up applications remove the JSON I put in there?


texts: Deciding when to switch focus between UI elements

texts:
I've been coding a simple logic game recently and there is a UI decision that has been bothering me.

Since certain blocks of logic are going to be used across many levels (e.g. logic to reverse the input queue) I decided to add a template feature, allowing the user to name and save blocks of logic.

As it stands, I simply have a text field in which to enter the template name. While the game is primarily played with the mouse, some keys are used as controls (w, a, s, d, space, delete). This creates the requirement of deciding when to take focus away from the text field. Some decisions are obvious (e.g. when the user presses the New Template button and the template is created) but others, not so much. For example, the user clicks the text field, then decides not to create a template.

While one option is to simply pop up a dialog and remove the text field from the main UI altogether, I was trying to avoid this. Does anyone have any thoughts on what would be a good trigger for taking focus away from the text field? Or do you think I should just drop the field and go with the dialog?


texts: Automatic Disconnecting of Players and The game is kinda Lag in PUN 2

texts:
I am creating a 3d game application in unity with the use of PUN2. When I start the game, all players automatically disconnected and the animation of players is kinda lag or not synchronizing towards all players. I was wondering if it is because of the RPC's that i called.
I know this is kinda stupid but i have 200+ methods marked as PunRPC.
My Question is: does using or calling an RPC in PUN causes a lag and automatic disconnecting of player/s? or is it because i calls a lot of data/objects  all over the network?
I do have this error occurs when a player/s disconnected automatically:
Error 1:

PhotonView ID duplicate found: 999. New: View 999 on RoomManager (scene) old: View 999 on RoomManager (scene). Maybe one wasn't destroyed on scene load?! Check for 'DontDestroyOnLoad'. Destroying old entry, adding new. UnityEngine.Debug:LogError(Object) Photon.Pun.PhotonNetwork:RegisterPhotonView(PhotonView) (at Assets/Photon/PhotonUnityNetworking/Code/PhotonNetworkPart.cs:1003) Photon.Pun.PhotonView:Awake() (at Assets/Photon/PhotonUnityNetworking/Code/PhotonView.cs:590)

Error 2:

InvalidOperationException: Duplicate key 999 ExitGames.Client.Photon.NonAllocDictionary`2[K,V].Add (K key, V val) (at D:/Dev/Work/photon-dotnet-sdk/PhotonDotNet/DataTypes.cs:309) Photon.Pun.PhotonNetwork.RegisterPhotonView (Photon.Pun.PhotonView netView) (at Assets/Photon/PhotonUnityNetworking/Code/PhotonNetworkPart.cs:1014) Photon.Pun.PhotonView.Awake () (at Assets/Photon/PhotonUnityNetworking/Code/PhotonView.cs:590)

and I know this errors will occur only if I did not disconnected properly from the previous game on which my room manager still exist and did not destroy from the previous one...


texts: unbelievable strange problem in unity android build - texture and frame

texts:
Suddenly the texture quality of Unity Android Build and the frame of the game was greatly degraded.

See the picture A and B. In image A the center lines on the road are sharper, but B is blurred. I want my game to look like A, not B.

What is surprising is that you can roll back the project to the point where it worked and then run the apk build again.

In the above picture, A is a screenshot of a normal time. I have installed apk backed up at that point.

B is a screenshot of when I built A after I rolled back the Unity project at the build time.

Both are the same project, but the build output is different. (Of course not good ...)

Of course I did not touch Unity, Java, Android SDK etc at the same time.

Of course, there is no configuration change on the testing phone as well.

It's just like this all of a sudden.

I even reinstalled the PC this morning.

I still have this problem.

Even if you build on a separate PC, you're having the same problem.

I build a project at another pc, mac book pro, but problem is still there.

Of cause, I factory-reset my test phone, but problem still there.

Test phone is Samsung Galaxy S4.

build environment is Windows 10, Unity 2017.


texts:
I am in the process of recording dialogue via FaceCapX and an animation recorder script that checks for changes between frames and if there is one it saves the value of 52 blend shapes, as well as head transform rotation and position.
To my limited understanding, the file should be containing something like (int) frame + (double) blend shape value per frame.? Which would lead to something like:
in byte:
4 + (8 * 52 blend shapes) * 60 frames per second * 60 seconds = 1,497 MB per minute.
Anyway, I end up with 18 MB for roughly 15 seconds of recording.
What is missing in my calculation?
Is there a bug in unity .anims?


texts:
I'm trying to implement unity rewarded ads. They work fine in the editor. However when I run it on my phone, the ads don't show up. Nothing happens when I click on the show ads button. I have a very simple project. There is a button that has the ShowRewardedVideo() function assigned and an admanager script. Not sure what's going wrong. Can someone please help?
Here is the admanager script:
 string gameId = "123456";
 bool testM = true;
 string reward = "rewardedVideo";

 void Start()
  {
    Advertisement.AddListener(this);
    Advertisement.Initialize(gameId, testM);
  }

 public void ShowRewardedVideo()
  {
    if (Advertisement.IsReady(reward))
    {
        Advertisement.Show(reward);
    }
  }

 public void OnUnityAdsDidFinish(string placementId, ShowResult showResult)
  {
    if (showResult == ShowResult.Finished)
    {
        Debug.Log("got reward");
    }
    else if (showResult == ShowResult.Skipped)
    {
        // Do not reward the user for skipping the ad.
    }
    else if (showResult == ShowResult.Failed)
    {
        Debug.LogWarning("The ad did not finish due to an error.");
    }
  }

 public void OnUnityAdsReady(string placementId)
  {
    if (placementId == reward)
    {

    }
  }

 public void OnUnityAdsDidError(string message)
  {
    // Log the error.
  }

 public void OnUnityAdsDidStart(string placementId)
  {
    // Optional actions to take when the end-users triggers an ad.
  }

// When the object that subscribes to ad events is destroyed, remove the listener:
 public void OnDestroy()
  {
    Advertisement.RemoveListener(this);
  }
}


texts: How can I convert my list of vertices and indices to a list of triangles?

texts:
I have a full 3D collision mesh that is represented by a list of vertices and another list of indices. I need to convert the list of vertices and the list of indices into a set of triangles.

First I tried to group every three vertices from the vertex list into a triangle, so vertices 0-2 were triangle 0, vertices 3-5 were triangle 1, etc. But that method did not produce the same triangles I see on the original mesh.

Then I remembered the indices list, but I didn't know how to use them. So I came here to ask: how can I use the indices list to make my list of triangles?


texts:
If I understand correctly, there are two major kinds of artists involved in game development - 2D and 3D.

I think I somewhat understand, that if I want to go 3D, I should learn some 3D modeling package really well and that would be it. Please correct me if I am wrong.

With 2D I am completely lost. There are a lot of tutorials on the web describing so many different topics like general drawing, vector graphics, raster graphics, pixel art and a whole lot of other things.

So what tools and techniques are most commonly used by professional 2D artists and if I wanted to become one, exactly were should I start(like tomorrow) and what should my goals be?


texts:
I'm wondering if it's possible to make a light source only affect one object? I know that it's possible to use layers and culling mask, but then I would need one layer for every single object which is not possible.

Is there a way for example that I could make only children or siblings be affected by a light source? Or other solution?

Have a nice day!

Update #1:


texts:
I want to create a countdown timer in a Unity game I am creating. Up until now my game was running for a specific time but I was using InvokeRepeating to end the game after the set time.

But now I want to display the time left in a GUI text. One approach could be to use InvokeRepeating again but this time call it every second to decrement the timer. With this approach though it would mean do extra calculations for when a minute passes in order to display time appropriately and not just display the whole time in seconds.

Is there a different approach? Does Unity have any timers built in?
Also which is the more efficient method?


texts: Do I have to keep all my UI elements within the safe area defined by the iPhone X?

texts:
Suppose this is my game's screen for the iPhone 8:

I have 7 blue buttons, and one blue bar at the bottom which is used to display commentary text.

I understand that the iPhone X has a safe area. In this case, there would be a bottom inset because of the home indicator and the swiping gestures.

The swiping and the home indicator pose no issue to my players. The game does not use any sort of gestures, and the center button is large enough that the home indicator doesn't really affect its aesthetics.

Given that, do I still have to avoid the bottom inset? Am I supposed to keep all my buttons within the safe area defined by the iPhone X even when it doesn't affect my user experience?

If I were to stay within the safe area, then I would have to push the bar and the buttons upwards by several pixels, then the leftmost buttons have to be pushed to the right, and the rightmost buttons to the left. That wouldn't look really great with my game art.

Would my game be rejected if I don't keep my elements inside the safe area?

It seems like I must indeed keep all my UI elements within that area, based on this image from the keynote:


texts: Going from a solo game project to a team project, how should I organize the new team and potential revenues?

texts:
I have been working on a game partial time for 2 years now, I've done the code and assets myself, but eventually I understood that I would not be able to have nice looking assets without spending a lot of time into it. And that greeting a new team member with graphic designer skills on this project would be a good idea.

My project is purely casual ATM. While I would love to earn a bit of money from it, my main goal is to have something fun to play with my friends (it's a couch console game) and I'm not sure what I want for the release of the game.

Now that I'm about to greet a graphic designer in the game project I'm excited but I want to do things right.

What should I define prior welcoming a second member in the team to make things work regarding the organization of the new team and the potential earnings?

What if things goes wrong and we split, when I have worked 900h on the game and him 20?

Any other tips from your experience regarding this aspect of welcoming a new teammate?


texts: What exactly does SDL_RenderSetClipRect do?

texts: I assumed that this function would move the area which is clipped out of conceptual space and copied onto the renderer (and subsequently drawn to the window) - i.e. change the origin of rendering - but it doesn't seem to do this. Anybody know how it works?


texts:
Using the following setting for the OpenGL particle effect:

SRC: GL_SRC_ALPHA
DST: GL_ONE

Creates an additive blend, which looks spectacular on a black background but terrible on brighter colours, as it begines to fade to white.

I then used alpha blending:

SRC: GL_SRC_ALPHA
DST: GL_ONE_MINUS_SRC_ALPHA

This allows other backgrounds to be used without affecting the color of the particles, but the particles themselves look dull compared to the additive blend.
How can I achieve a good fire effect with alpha blending and particles?

Additive:

Alpha:

UPDATE:

Following David's advice below, I created a separate texture and then used additive blend on the particle effect before drawing onto the texture. The problem with that is that drawing on an alpha=0 texture resulted in just the coloured parts of the particle appearing in front of my world map, since normally you have a black background instead. The trick was to use two textures. I created a black texture and then drew the particles on it. Then I removed the alpha layer of the particles from this texture, effectively removing all the surrounding solid black and fading out the partially visible particles, while leaving the underlying black as you'd expect when making additive blend particles on a black background. In short, a gruelling process, but I got there eventually:

Here's the thread where I posted my process: http://www.cocos2d-iphone.org/forum/topic/28707?replies=8#post-141528

Video: http://www.youtube.com/watch?v=JptGbEO3b5E


texts: Making a Collision Detection for ImageViews

texts: I'm trying to make a collision detection system for two ImageViews, but I can't seem to figure it out. I've tried doing several things from StackOverflow and other places, but they don't work. One ImageView stays still and the other moves toward it (it's animated, not a sprite). They don't do anything when the collide, though. Do I need to make them sprites or drawables on a canvas or something?


texts:
I have two arrays A and B. I want to do color mapping of their difference A - B. So far, I am doing this:

1) calculate d = A - B
2) find min / max in d
3) linear mapping of d from (min, max) to (0, 1)
4) convert (0, 1) to color

The problem is, that sometimes, there are noise values in my data. For example, several values in B are too large (like 100 times bigger than the rest) and it leads to enormous difference and increased min or max. After mapping to (0, 1) all other values are "wiped". How can I solve this?


texts: Unable to create a blueprint containing multiple actors

texts:
I'm having some trouble in Unreal 4.23. According to the documentation, if I select a bunch of Actors and hit the Blueprints button in the toolbar, I should get an option to "Convert Selection To Blueprint Class," which then gives me a choice of three options of what to do with the different objects before creating the blueprint. Instead, I get "Convert Selected Components To Blueprint Class," the dialog asking me what to do with the objects does not show up -- it goes straight to the one asking where to save the blueprint -- and the blueprint it generates is a mess: textures get changed, the names of the actors are lost, and all of the objects are "dropped on the ground" rather than being positioned where they had been relative to each other!
The objects in question are a character (Skeletal Mesh) and several sub-objects representing the character's clothing (also skeletal meshes, attached to the character as sub-objects in the World Outliner hierarchy.) I basically want to do the same thing you can do in Unity: take this character and save it as a prefab so I can make copies of it easily in different maps. From researching the documentation and various forum posts, it seems like making them into a Blueprint using the Harvest Components option is the best way to do that, but that option is never showing up! This problem persists even after closing and restarting Unreal.
Anyone have any idea why the editor is not behaving as documented, and what I can do about it?
(And yes, I know about Prefabricator.  This is supposed to be for Marketplace content, though, where third-party dependencies are discouraged.)


texts: Is Entity Component System (ECS) considered a part of OOP or is it a completely different concept?


texts: Do all normalized quaternions represent valid rotations?

texts: Basically, I'm getting a bug where the rotations in the animations seem to be skewing the model even though I'm normalizing them. I suspect that the rotations are showing the error, but not causing it, if that makes sense.  But that's based on the idea that a normalized quaternion can't skew a model.


texts:
I am creating a 2D car racing game. (Yes, a Hill Climb Racing clone)

What I am doing right now is load 10% of the map every time the user gets to 7%. For example:

Imagine the map has 10km. (10000m)

When the game starts, the game loads the road from -100m to 1000m.

When the user gets to the 700m (7%) mark, the game deletes 0-500m and loads 1000m to 2000m (10%) (Having loaded from 500m to 2000m).

This will happen every 1000m from now on (1700m, 2700m, 3700m).

I used to create the whole world, and with this new method, I increased my mobile phone fps from 32-34 to stable 60 fps.
BUT, every time the user is in the 700m mark, the game freezes for 0.55-0.60 seconds. (When I load/delete the new road).

Is there a better way (In terms of FPS (Performance)) to load the world?


texts: Unity - Loading Assets / Resources during run-time for a highly customizable game

texts:
I haven't had to think too much about this problem too much until now.

I am in the middle of creating a character customization system for my game.

There are 60+ characters in the game, I have created them using an internal character customizer, using multiple assets/meshes - bodies, eyes, clothes, hair, etc. - combining them into create a single mesh which can be controlled by a rig.

Currently I have all the body parts and clothing in one folder, labelled in such a way that with a bit of simple logic, they can be assigned to certain parts of a character's body.

In another folder, I have all the Character prefabs - GameObjects with a special Character component, which allow me to configure each character using the editor's inspector. So instead of interacting with the hierarchy directly, I use dropdowns in the inspector to choose what the character wears and other aspects of their appearance)

With this system I can drag and drop characters into a scene, hit play and they'll work as intended.

But what if I considered all character's appearances as dynamic (suppose they wear different clothing depending on time of day, different accessories, etc.), then it becomes too variable to consider pre-compiling each character.

Or to really accentuate the problem - what if I consider an in-game character customizer? Or even in-game scene editor? Where objects like chairs, tables and walls have to be loaded individually during run-time.

Currently, I rely on AssetDatabase (LoadAssetAtPath(), FindAssets(), etc.) to generate a character within the editor, obviously this won't work in-game.

I am very confused by Unity's whole asset-bundle/resource pipeline.
Should I put all of the body-parts, hairstyles and clothing into a Resources folder and replace 'AssetDatabase' references with 'Resources'?
From looking online, I get the impression this is bad practice. Why?

Do I put every single one of these assets into a single AssetBundle? Is there any difference between a Resources folder an AssetBundle containing the same objects?

I understand this will create an overhead whenever a character needs to be created and initialized, but I don't see any other way.

I'm sure my understanding of AssetBundles and Resources is muddled at best.
Possibly at the most basic level - I don't understand why I can't just say 'Unity, load this asset now' as I do with the AssetDatabase class in an editor script. I know the compiled asset doesn't resemble the same file-mapping as my project folder, but surely it can still be got at.

Any suggestions on the matter would be really appreciated.

I hope the confusion I've expressed fully illustrates the depth of my ignorance.
While I've been using Unity for over a year now, I've had so much trouble getting familiar with it, yet I'm usually very adaptive to new software, APIs or coding practices.
There's just something about Unity that causes so many misunderstandings and misapprehensions.
We don't see eye to eye on anything it seems.


texts: Why Unity3d takes so long time to "rebuild" when I change build platform?

texts:
I would like to know what happens "behind the scenes" when I change my unity game target platform .

If I switch from Android to iOS or Pc or etc, Unity rebuild something and takes a lot of hours to complete.

What is the reason ?

Thanks


texts: Unity - Proper use of threads with procedural generation

texts:
I have been working on a simple chunk based terrain generation system, with voxel octrees. The overall method works pretty well, but testing this system with large amounts of chunks completely freezes the game/main thread until the generation process is finished. Looking for a solution, I read about threads and coroutines and I implemented a simple thread class (based on this template) to call the "generate" function from it. The only advantage I had was a faster generation, with full CPU usage, but the game still freezes until the chunks are completely loaded. Am I doing something wrong? Here some parts of the code:

public class ChunkThread : ThreadedJob {
  public Chunk chunk;
  protected override void ThreadFunction(){
    chunk.root = chunk.root.BuildOctree (chunk.pos, Chunk.size, -1);
  }
  protected override void OnFinished(){
    chunk.RenderChunk ();
  }
}

This is the simple Thread class I use to call the Build function, and the Render function when finished. This piece of code below is the start\update method for every Chunk gameObject (I kept only the relevant part), that simply creates the Thread instance and calls Start() pressing the mouse button.

void Start () {
  t = new ChunkThread ();
  t.chunk = this;
}
void Update () {
  if (Input.GetButtonDown ("Fire1")) {
  t.Start ();
}

Now, coming to the questions, what should I do to generate the terrain while still being able to play? Is there something wrong in my thread? Should I use a thread pool, if so how?


texts: Unreal installation and storage space requirement

texts:
I am a new user of Unreal. I installed the program on Windows 7, and after using it for awhile I noticed that the C:/ partition was filling up very fast as I worked on my projects. I store my projects on a storage device different than the one with Windows- does Unreal nevertheless write files related to a project to C:/ and if it does, can such a setting be changed?

I am upgrading to Windows 10. Is there any difference in the behavior explained above between the two Windows versions? Is there any rule of thumb about how much there should be free space on the C:/ partition for Unreal to work with, regardless of where projects are stored?


texts: Voronoi / Delaunay Graph - Triangle Circumcenter error

texts:
I have written a Delaunay Graph script that given a set of points (voronoi cell/region) will generate the Delaunay triangles with their edges. Considering that the Voronoi diagram is complimentary to the Delaunay graph, I can infer the Voronoi regions, edges and corners once the Delaunay graph is complete.

I had previously implemented this in 2D without any troubles and the results were flawless in all of the diagrams I generated. However, I have since tried to implement this in 3D and have now encountered issues.

My implementation of this appears to work fine in 99.9% of cases which leads me to believe that perhaps floating point/rounding errors may be the problem or (more likely) my understanding of the code used to determine the circumcenter is incorrect.

I have based the following implementation on this answer from How do I find the circumcenter of a triangle in 3D?

public static Vector3 Circumcenter(Vector3 a, Vector3 b, Vector3 c)
{
    Vector3 ab = (b - a);
    Vector3 ac = (c - a);

    Vector3 abXac = Vector3.Cross(ab, ac);

    Vector3 i = (ab.sqrMagnitude * ac);
    Vector3 j = (ac.sqrMagnitude * ab);
    Vector3 k = Vector3.Cross((i - j), abXac);

    return (a + (k * (0.5f / abXac.sqrMagnitude)));
}

The screenshots below are of two separate graphs both generated by creating the Voronoi cells/regions in nested for-loop's before attempting to solve the graph. I have tried creating the points randomly, hard coding them, setting different values along the Y-axis or having them all set to a specific constant on the Y-axis, all of which exhibit the same behaviour.

These examples do not use Lloyd relaxation but for the sake of completion, running the solver over several iterations also produces incorrect results.

I have been trying to debug this for weeks now and cannot for the life of me understand why this does not work. My understanding of the math is fairly solid but I really can't begin to narrow this down to resolve the issue.

It would appear that when solving the graph, the circumcenter for three of the nodes is sometimes incorrect (or so i'm lead to believe from the visual output). However, the Delaunay representation appears to be correct which leads to even more confusion on my part.

In the above images, the lines and points represent:

Red point: Voronio cell/region.
Black Line: Delaunay Edge.
Blue point: Voronoi Corner.
White Line: Voronoi Edge.

The Voronoi graph is determined by creating a Delaunay edge between two nodes and first setting the start point of a Voronoi edge. Once the graph finds another Delaunay triangle along this exact same edge between two nodes, the end point of the Voronoi edge is then set completing this edge entirely.

As you can see in the both images, the Delaunay representation of the graph is correct. However, again in both images, the Voronoi representation has incorrect corners which then leads to incorrect edges.

If anyone can shed any light on this, or point me in the right direction, that would be greatly appreciated.


texts: Correct way to compute separation velocity from impact velocity, normal, friction and resitution?

texts:
I am creating a simulation of rigid bodies in 2D space.
My collision detection returns:

normal - The normal vector of the collision (e.g. (0.0f, -1.0f) would be the normal for a collision with the ground)
impactVelocity - The velocity of the object the instance before it collides with the wall

From these, I need to compute the separation velocity of the object after the collision.
I already have two working strategies for computing the separation velocity:
// Reflect
// This is a perfect bounce away from the collision
let reflect impactVelocity normal =
  impactVelocity - 2.0f * normal * (Vector2.dot normal impactVelocity)

// Slide
// When an object hits a wall it slides along it, maintaining contact
let slide impactVelocity normal =
  impactVelocity - (Vector2.dot impactVelocity normal) * normal

These both work well, but I would like to simulate something more sophisticated, using friction and restitution for the colliding object.

friction - How much an object should be slowed as it slides along a wall (0.0f <= x <= 1.0f)
restitution - How much an object should be bounce away from a wall (0.0f <= x <= 1.0f)

let separationVelocity impactVelocity normal friction restitution =
  // ?

I suppose that slide acts like friction = 0.0f and restitution = 0.0f, whereas reflect acts like friction = 1.0f and restitution = 1.0f.
How should I implement separationVelocity?


texts: Changing the size of shuriken particle effects to simulate a torch flame Unity3D

texts: Basically I'm trying to use the "Flame" particle effect to simulate the flame on a torch. My problem is the flame is far too big. I've been trying too figure out how to resize the flame to fit the torch, but nothing seems to work. I've adjusted all the properties, and the scale itself. But no matter what it's too big. Anybody know how I could accomplish this?


texts: Should we go for our Vector2Int/Vector3Int implementation or just use built-in float based vectors?

texts:
So in one of our projects we're using Vector2/Vector3's a lot but we do only use integer/byte values mostly. So up to the point we've implemented our Vector2Int, Vector3Int, Vector2Byte and so structures;

public struct Vector2Int
    {
        public int X;
        public int Z;

        public Vector2Int(int x, int z)
        {
            this.X = x;
            this.Z = z;
        }

        public override bool Equals(object obj)
        {
            if (obj is Vector2Int) return this.Equals((Vector2Int)obj);
            else return false;
        }

        public bool Equals(Vector2Int other)
        {
            return ((this.X == other.X) && (this.Z == other.Z));
        }

        public static bool operator ==(Vector2Int value1, Vector2Int value2)
        {
            return ((value1.X == value2.X) && (value1.Z == value2.Z));
        }

        public static bool operator !=(Vector2Int value1, Vector2Int value2)
        {
            if (value1.X == value2.X) return value1.Z != value2.Z;
            return true;
        }

        public override int GetHashCode()
        {
            return (this.X.GetHashCode() + this.Z.GetHashCode());
        }

        public override string ToString()
        {
            return string.Format("{{X:{0} Z:{1}}}", this.X, this.Z);
        }
    }

But i don't know if we're on right track? Should we just better use XNA's float based vectors because of performance-wise concerns?

On the other hand a Vector2Byte or Vector3Bytes consumes less space which is also quite important when you use so much vectors.

I've searched for tests / information on XNA's built-in vector performance but couldn't find a bit even on it.

I'm happy to hear your experiences.


texts:
I'm trying to make a simple game, when the ball falls into certain block, you win.

Mechanics: The ball falls through several obstacles, in the end there are two blocks, if the ball touches the left block you win, the next level will contain more blocks and less space between them.

Test the movie (click on the screen to drop the ball):
http://gabrielmeono.com/downloads/Lucky_Hit_Alpha.swf

These are the main variables:

    var winBox:QuickObject;//You win
    var looseBox:QuickObject;//You loose
    var gameBall:QuickObject;//Ball dropped

Question:

How do I trigger a collision function if the ball hits the winBox? (Win message/Next level)

Thanks, here is the full code:

    package  {

    import flash.display.MovieClip;
    import com.actionsnippet.qbox.*;
    import flash.events.MouseEvent;

    [SWF(width = 600, height = 600, frameRate = 60)]

    public class LuckyHit extends MovieClip {

        public var sim:QuickBox2D;
        var winBox:QuickObject;
        var looseBox:QuickObject;
        var gameBall:QuickObject;

        /**
         * Constructor
         */
        public function LuckyHit()
        {
            sim = new QuickBox2D(this);
            //sim.createStageWalls();
            winBox = sim.addBox({x:5,y:600/30, width:300/30, height:10/30, density:0});
            looseBox = sim.addBox({x:15,y:600/30, width:300/30, height:10/30, density:0});

            // make obstacles
            for (var i:int = 0; i<(stage.stageWidth/50); i++){
            //End
                 sim.addCircle({x:1 + i * 1.5, y:16, radius:0.1, density:0});
                 sim.addCircle({x:2 + i * 1.5, y:15, radius:0.1, density:0});

            //Mid End

                  sim.addCircle({x:0 + i * 2, y:14, radius:0.1, density:0});
                  sim.addCircle({x:0 + i * 2, y:13, radius:0.1, density:0});
                  sim.addCircle({x:0 + i * 2, y:12, radius:0.1, density:0});
                  sim.addCircle({x:0 + i * 2, y:11, radius:0.1, density:0});
                  sim.addCircle({x:0 + i * 2, y:10, radius:0.1, density:0});

            //Middle Start
                 sim.addCircle({x:0 + i * 1.5, y:09, radius:0.1, density:0});
                 sim.addCircle({x:1 + i * 1.5, y:08, radius:0.1, density:0});
                 sim.addCircle({x:0 + i * 1.5, y:07, radius:0.1, density:0});
                 sim.addCircle({x:1 + i * 1.5, y:06, radius:0.1, density:0});

            }

            sim.start();

            stage.addEventListener(MouseEvent.CLICK, _clicked);
        }

        /**
         * ..
         * @param e MouseEvent.CLICK
         */

        private function _clicked(e:MouseEvent)
        {
            gameBall = sim.addCircle({x:(mouseX/30), y:(1), radius:0.25, density:5});

        }
    }

}


texts:
I want to create a simple java networking game and search a networking engine that eases use of sockets etc. I have already read some questions on here and the internet about java networking for games, but many of them were over 10 years old or not really answered.

I have no idea whatsoever about what exactly I need to send in terms of messages, but I figured simple strings or integers will be enough for my purposes.

It's basically a peer to peer game, so I don't need a centralized server structure. Messaging doesn't have to have an extremely low ping, yet of course all players need to have a synchronized view.

What are the possibilities I have here?


texts: Do I always need to call SaveAssets & Refresh after calling AssetDatabase.CreateAsset?

texts:
I'm working with AssetDatabase.CreateAsset and all over the internet (not so much in the official documentation) I see

AssetDatabase.CreateAsset(blah, blahPath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();

Why?

SaveAssets says it Writes all unsaved asset changes to disk so I assume that there's a situation in which you can have changes to your assets in memory, but not on disk. Is this the case when you create an asset with CreateAsset? I tried ending the Unity process right after creating a file but it looks like it writes to disk immediately, but I've only tried in-editor on Windows. Maybe it behaves differently in runtime or on different platforms.

Refresh says it will import any assets that have changed their content modification data or have been added-removed to the project folder. The editor UI gets updated when I call CreateAsset even if I don't Refresh, so is this for updates from other sources, or what?

I'm trying to understand the process and not do things just because everyone does it like that.


texts: Box2D and OrthographicCamera working incorrectly

texts:
I'm trying to build a simple game where TileMapRenderer renders a labyrinth, a ball moves in it and camera follows it. I'm currently having the following bug:

For some reason, the game renders the world incorrectly. The gamescreen is cleared with the following method:

private void clearScreen() {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}

Which is basically red, and the camera seems to show it incorrectly while moving.

Camera movement method:

public void moveCamera() {
    GameInfo.camera.position.set(player.body.getPosition().x,
            player.body.getPosition().y, 0);

    // LEFT
    if(GameInfo.camera.position.x < GameInfo.WINDOW_WIDTH / 2){
        GameInfo.camera.position.x = GameInfo.WINDOW_WIDTH / 2;
    }

    // UP
    if(GameInfo.camera.position.y > GameInfo.WORLD_HEIGHT_PIXELS / 100.0f - GameInfo.WINDOW_HEIGHT / 2) {
        GameInfo.camera.position.y = GameInfo.WORLD_HEIGHT_PIXELS / 100.0f - GameInfo.WINDOW_HEIGHT / 2;
    }

    // DOWN
    if(GameInfo.camera.position.y < GameInfo.WINDOW_HEIGHT / 2) {
        GameInfo.camera.position.y = GameInfo.WINDOW_HEIGHT / 2;
    }

    // RIGHT
    if(GameInfo.camera.position.x > GameInfo.WORLD_WIDTH_PIXELS / 100.0f - GameInfo.WINDOW_WIDTH / 2f) {
        GameInfo.camera.position.x = GameInfo.WORLD_WIDTH_PIXELS / 100.0f - GameInfo.WINDOW_WIDTH / 2f;
    }
}

As you can see, I'm using Box2D physics for the ball.

Setting up the camera:

public static OrthographicCamera camera = new OrthographicCamera();

public static void setCamera() {
    camera.setToOrtho(false, 8.0f, 4.5f);
}

Rendering method:

public void render () {
    batch.setProjectionMatrix(GameInfo.camera.combined);
    clearScreen();
    moveCamera();
    GameInfo.camera.update();
    Game.tiledMapRenderer.setView(GameInfo.camera);
    Game.tiledMapRenderer.render();
    batch.begin();
    batch.draw(player.texture,
            player.body.getPosition().x - player.radius,
            player.body.getPosition().y - player.radius,
            player.radius,                   // originX
            player.radius,                   // originY
            player.radius * 2,               // width
            player.radius * 2,               // height
            1.0f,                          // scaleX
            1.0f,                          // scaleY
            player.body.getTransform().getRotation() * MathUtils.radiansToDegrees,
            0,                             // Start drawing from x = 0
            0,                             // Start drawing from y = 0
            player.texture.getWidth(),       // End drawing x
            player.texture.getHeight(),      // End drawing y
            false,                         // flipX
            false);                        // flipY
    player.updatePlayer();
    Game.checkStateOfGame(player);
    batch.end();
    //GameInfo.doPhysicsStep(Gdx.graphics.getDeltaTime());
    Game.world.step(1/60f, 8, 3);
}

It's not only while moving either. As soon as the game starts, the red block is visible like seen in the first picture.

Also the red blocks seem to always be coming from left and down, never from up or right...

What could be wrong in here?


texts: How can I rotate my character so that he is facing the mouse?

texts:
I just want to preface this by saying I am very new to pygame.

At the moment I have calculated the angle that I need to apply to my character so he can rotate but I am unsure how to actually make him rotate (I understand the principle of it but not how to code it). I have tried to watch videos and look at other questions on here but I have only seen lots of different solutions that I can't implement into my own code.

I want to make it so that my character faces wherever my mouse is moving.

import pygame
import math
from random import randint

pygame.init()

screen = pygame.display.set_mode((600, 600))
screen_width = 600
screen_height = 600
pygame.display.set_caption("Mousey")
char = pygame.image.load('76011.png')
background = pygame.image.load('pygameback.png')
clock = pygame.time.Clock()

class Player:
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.velocity = 12.5
        self.original = pygame.image.load('76011.png')
        self.rotated = self.original
        self.rect = self.rotated.get_rect()
        self.angle = 0

    def draw(self, win):
        screen.blit(char, (self.x, self.y))

class Enemy(Player):
    def __init__(self, x, y, width, height):
        Player.__init__(self, x, y, width, height)

    def draw(self, win):
        pygame.draw.rect(win, (0, 255, 0), (jeff.x, jeff.y, jeff.width, jeff.height))

def drawWindow():
    screen.blit(background, (0, 0))
    mag.draw(screen)
    jeff.draw(screen)
    pygame.display.update()

def XOR(a, b):
    if bool(a) != bool(b):
        return True
    return False

mag = Player(300, 300, 60, 60)
jeff = Enemy(180, 180, 60, 60)
run = True
while run:
    clock.tick(40)

    keys = pygame.key.get_pressed()

    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            run = False
        if e.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pygame.mouse.get_pos()

        if e.type == pygame.MOUSEMOTION:
            mouse_x, mouse_y = pygame.mouse.get_pos()
            rel_x, rel_y = mouse_x - mag.x, mouse_y - mag.y
            angle = math.atan2(rel_y, rel_x)

    if XOR(keys[pygame.K_a], keys[pygame.K_LEFT]) and mag.x > mag.velocity:
        mag.x -= mag.velocity
        right = False
        left = True
    elif XOR(keys[pygame.K_d], keys[pygame.K_RIGHT]) and mag.x < screen_height - mag.width - mag.velocity:
        mag.x += mag.velocity
        right = True
        left = False
    elif XOR(keys[pygame.K_w], keys[pygame.K_UP]) and mag.y > mag.velocity:
        mag.y -= mag.velocity
        right = False
        left = False
    elif XOR(keys[pygame.K_s], keys[pygame.K_DOWN]) and mag.y < screen_height - mag.height - mag.velocity:
        mag.y += mag.velocity
        right = False
        left = False

    drawWindow()

I was also confused about where I need to make the character rotate. By this I mean, do I make a method inside the class that calculates the angle and makes the character rotate OR do I do all the calculations down where they are now?


texts: Behavior Trees :: Actions That Take Longer Than One Tick

texts:
From what I understand on Behavior Trees, each Behavior should be a short goal oriented Action that could be done in a few iterations.

So for example, below is an image of a Behavior Tree:

Now let us assume that the Drive To Enemy behavior takes more than a few iterations in the tree.  So on each pass Drive To Enemy is called because it is now in the running state.

The problem is I want to call Evade Enemy if an Enemy is nearby.  And considering that Drive To Enemy is always called I never get a chance to call Evade Enemy (Should probably be called Avoid Enemy).

Should I traverse the Tree EACH pass no matter what Action is currently running?
Am I going about this the right way?
What is the proper way of handling such a behavior?

Originally asked on Stackoverflow. Thought here would be a more appropriate place to ask this question.


texts: Automatic audio segmentation and find the most energetic segments

texts:
What algorithm can be used for audio segmentation? I want to divide song to segments and find the most energetic segments (begin and end in seconds). It is needed for the rhythm-game.

Examples:

https://soundcloud.com/dieantwoord-yolandi/die-antwoord-cookie-thumper
(most energetic segments: first 3:09-3:38; second 5:02-5:27)

https://www.youtube.com/watch?v=StZcUAPRRac (rammstein - sonne)
(most energetic segments: first 0:55-1:20; second 1:52-2:44)


texts: I'm trying to figure out how script gravity reversal on collision with an object. How can I reverse gravity?


texts: I've got a ray defined by P1 and P2, and then a target P3, and I want to find P4. How do I go about this? I've come to understand that I should use vector projection, but I can't get it to work. Any help? I'm using C# and XNA.


texts: LibGdx: Texturing cube results in jagged transparent edges

texts:
currently I'm in the works of programming a game - surprise xD
I'm using LibGdx for this manner but I've encountered a very unknown bug I guess.
I wasn't able to get any further by searching the internet.

If you're interested in the entire source code - it's on Github

here is the code of the Block class

package richbar.com.github.treasurepyramid.block;

public abstract class Block implements EventSubscriber, Loadable {

    public abstract String getId();

    Vector3 pos;
    String name;
    Model model;
    BoundingBox bounds;
    Texture texture;
    Material attributes;

    private boolean loadedData;
    public boolean isLoaded(){return loadedData;}

    public Block(){
        Main.getInstance().addAssetListener(this, "blocks/"+getId()+".json",    Text.class);
    }

    public Block(Block block){
        Main.getInstance().addAssetListener(this, "blocks/"+block.getId()+".json", Text.class);
        pos = block.pos;
        attributes = block.attributes;
        bounds = block.bounds;
    }

    public Model getModel(){
        if(model != null) return model;
        texture.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat);
        Material material = new Material(TextureAttribute.createDiffuse(texture));
        ModelBuilder modelBuilder = new ModelBuilder();
        modelBuilder.begin();
        modelBuilder.node();
        MeshPartBuilder mesh_part_builder = modelBuilder.part("box", GL20.GL_TRIANGLES, VertexAttributes.Usage.Position
            | VertexAttributes.Usage.Normal | VertexAttributes.Usage.TextureCoordinates, material);
        BoxShapeBuilder.build(mesh_part_builder, 5, 5, 5);
        return modelBuilder.end();
    }

    boolean stayUpdated = true;
    @Override
    public void eventUpdate(Event e, Object args) {
        AssetManager manager = Main.getInstance().getAssetManager();
        if(e == Event.ASSET_LOADED && manager.isLoaded("blocks/"+getId()+".json")){
            Main.logger.log("loaded blocks/"+getId()+".json");
            stayUpdated = false;
            JsonValue json = new JsonReader().parse((manager.get("blocks/"+getId()+".json")).toString());

            name = json.getString("name");
            texture = new Texture(Gdx.files.internal(json.getString("texture")));
            loadedData = true;
        }
        //generate Cube Model if Absent
        model = getModel();
    }

    @Override
    public boolean stayUpdated() {
        return stayUpdated;
    }
}

Pic of this weird behavior     ||   Changing angles only changes the jaggedness

I'd really appreciate if anyone could help me fix this issue : )

Have a nice evening,

Marco


texts: I have made games with box2dflash, but how much ever i have wanted to try out the test bed, the resources on the net don't help me. I have a folder called Testbed and various Test???.as files inside it. It would be a great help if somebody could just jot down how the testing of a box2dflash game is done. Thank you


texts: XNA 4.0: Trouble Aligning an Animating Sprite (Texture Origin)

texts:
I'll try to explain this as best as I can.

I'm trying to build a game where there exists a "Surfer" who is surfing down a rail.
I have a sprite sheet for the surfer however I have been running into animating the surfer for the following reasons:

The source rectangles for each animation are sometimes different
The feet of the surfer are at different locations within each texture animation.

What do I mean by #2?
For instance, I have an animation for the surfer to jump rails.
My spritesheet is built so that my surfer's feet might be positioned on the left side of the texture at the start of the animation and after the jump (iterating through the textures) his feet are now at the right hand side of the texture.

This is causing me problems because in order to align the feet to the rail for each animation I tried to offset the origin of the texture so that it points at his feet.

(The origin is given in the SpriteBatch.Draw call)

However this isn't working :(

Any recommendations on how to properly set this up?

PS: I Hope I explained it well, if not I can edit it and retry.


texts: Analog sticks, deadzones, diagonals, etc

texts:
I'm messing about with a knockoff PS3 controller and SDL2 on windows, and noticed that despite the circular restriction, when I position the stick as close as I can to an extreme diagonal, I am reading a max value for displacement on the X and Y axis. Now as a newbie, I would not expect this as obviously in this position the stick is some way from being as far displaced in either axis as it could be. So it seems that the region for min and max readings is a square whose limits are well within the full circular range of movement of the stick, and anything outside this region is deadspace.
I guess different controllers might have different exact sizes for deadzones, but in general, is it the case that all analog controllers are going to exhibit this general behaviour?


texts: moving object on game background after scaling it based on screen size

texts:
I am creating a game using Corona SDK, I have a map with a ball and another other object that moves on the map.

I use the the ultimate config.lua file for scaling background based on device screen resolution.

My problem is that I want to arrange some objects on this map.  I have created specific assets for a specific device resolution, but on devices with aspect ratio lower than 1.72 the map is stretched horizontally so that appears wider than other assets.

Also when I want to arrange an object to a specific location on top of the map the result is that things don't line up right because of the scaling issue.  For example, when i set myobject.y=100 on a device with aspect ration more than 1.72 it set on the right place but when I do the same thing on device with aspect ratio less than 1.72 my object is off the map.

I tried to convert my pixels to inches using device DPI but it's still the same.


texts: Why am I getting an access violation when assigning to a 2D array member?

texts:
c++ Beginner here, coming from Java background, and I'm getting the feeling this is a c++ specific error I'm running into. I am trying to procedurally generate a 2D map, which is of type Tile[y][x]. As seen in code below I loop through all the indeces in the 2D array and I generate a colorvalue, which lets it decide what color the tile is, and a position, which defines the position the tile should be drawn to. However, I get a read access violation when I try to add Tiles to the 2D array. What am I doing wrong here?

Also whenever I have an array that is a bit bigger than this one, I get a stack overflow error. Now I read that arrays are kept in stack memory, and the stack is only very small, so what would be a solution to this? Thanks in advance

Map.cpp:

    #include "Map.h"
    #include <memory>

    Map::Map(int size)
    {
        this->size = 10;
        noiseGenerator.SetNoiseType(FastNoise::NoiseType::Perlin);
        std::cout << "Setting noise" << std::endl;
        for (int x = 0; x < size; x++) {
            for (int y = 0; y < size; y++) {
                tileMap[x][y] = Tile{ sf::Vector2f{x * 8.0f, y * 8.0f }, noiseGenerator.GetValue(x, y) //This is where the read access violation happens
            };
            }
        }
    }
void Map::draw(sf::RenderWindow *window)
{
    for (int x = 0; x < size; x++) {
        for (int y = 0; y < size; y++) {
            window->draw(tileMap[x][y]);
        }
    }
}

Map.h: Tile is inheriting from base class sf::RectangleShape

#pragma once
#include <iostream>
#include <string>
#include "FastNoise.h"
#include <SFML\Graphics.hpp>
#include "Drawable.h"
#include <memory>
#include "Tile.h"

class Map : public Drawable
{
public:
    Map();
    Map(int size);
    ~Map();
    void draw(sf::RenderWindow *window);

public:
    int size;
    sf::RectangleShape tileMap[5][5];
    FastNoise noiseGenerator;
};

Game.cpp with the main function:

std::list<Drawable*> drawableList;
    int main()
    {

        sf::RenderWindow window(sf::VideoMode(800, 800), "Zieke game");

        Map map{100};
        drawableList.push_front(&map);

        sf::Clock clock;

        while (window.isOpen())
        {
            deltaTime = clock.restart().asSeconds();
            sf::Event event;
            while (window.pollEvent(event))
            {
                if (event.type == sf::Event::Closed)
                    window.close();
            }

            for (auto x : updateableList) {
                x->update(deltaTime);
            }

            window.clear();

            for (auto x : drawableList) {
                x->draw(&window);
            }
            window.display();
        }

        return 0;
    }


texts: Why should I not use glTools/glut when developing complete applications?

texts:
I've started learning how to use OpenGL a while back, using the OpenGL SuperBible, Fifth Edition, and I've had people arguing about the fact that the book doesn't really teach how to use OpenGL but instead it teaches how to use two of the wrapper libraries related to it, glut and glTools.

I've also been told that glut should never be used for full-blown projects, but there was no valid reason supplied with the argument.

My question is why, and when should I not use the glTools/glut libraries, and what should I use instead?


texts: How to handle keyboard controls in Arkanoid game

texts:
I'm making simple Arkanoid clone in Unity with both keyboard and mouse controls available. When I gave it to my colleagues to test one complain was that keyboard controls are not precise enough,. The problem is that I don't really know how to find a balance between two factors:

If I make paddle speed too high then it lacks precision to position it just right to make ball go to the last few blocks.
If I make paddle speed too slow then it's going to be difficult to reach ball in time.

I thought about it and I don't recall any version of arkanoid that solved that problem. Currently I have 3 ideas:

Make two (or more) keys to go in each direction. One will go faster and another slower.
Instead of making multiple buttons lets allow player to change speed of paddle during the game. Probably by entering number from 0-9 on keyboard.
Just leave it like it is now. Other control schemes are not intuitive enough.

Does anyone have any experience with this? Which approach is the most reasonable?

Edit:
Code I'm using:

    Vector3 pz = transform.position;
    pz.y = y;
    pz.z = 0;
    if (Input.GetKey(KeyCode.LeftArrow)) {
        pz.x -= Time.deltaTime * KEYBOARD_SPEED_MULTIP;
    }
    if (Input.GetKey(KeyCode.RightArrow)) {
        pz.x += Time.deltaTime * KEYBOARD_SPEED_MULTIP;
    }
    pz.x = Mathf.Clamp(pz.x, -60, 60);
    rb.MovePosition(pz);

I simply move paddle by constant speed which includes timedelta. And then I clamp position to screen.


texts:
I know that questions like this have been asked many times, but I have not found one exactly like this yes. I have implemented a top-down grid based world in Monogame, and am starting on the lighting system soon. How I want to do lighting is to have a grid that is 4 times wider and higher, basically splitting each world tile into a 4x4 system of "subtiles". I would like to use a flow like system to spread light across the tiles by reducing the light by a small amount each time. This is kind of the effect I was going for:

http://i.imgur.com/rv8LCxZ.png

The black grid lines are the light grid, and the red lines are the actual tile grid, and the light drop-off is very exaggerated. I plan to render the world by drawing the unlit grid to a separate RenderTarget2D, then rendering the lighting grid to a separate target and overlaying the two.

Basically, my questions are:

What would be the algorithm for a flow style lighting system like this?
Would there be a more efficient way of rendering this?
How would I handle the darkening of the light with colors, reducing the RGB values in each grid, or reducing the alpha in each grid, assuming that I render the light map over the grid using blending?
Even assuming the former are possible, what BlendState would I use for that?


texts: Something other than Vertex Welding with Texture Atlas?

texts:
What options (in C# with XNA) would there be for texture usage in a procedural generated 3D world made of cubes to increase performance? Yes, it's like Minecraft.
I've been doing a texture atlas and rendering faces individually (4 vertices per face), but I've also read in a couple places about using texture wrapping with two 1D atlases to merge adjacent faces with the same texture.
If two or more adjacent faces share the same image, it'd be quite easy to wrap in this way reducing vertices by a large amount. My problem with this is having too many textures, swapping too often, and many image related things like non-power of 2 images.
Is there a middle ground option between the 1D texture atlas trick and rendering 4 vertices per cube face?
This is a picture of what I have currently (in wireframe). 4 vertices per face seems extremely inefficient to me.


texts: Is it a bad idea to store all textures in linear color-space?

texts:
I am wondering about the performance behind color-space conversions for textures during reading.
If a project decides to go with a linear workflow, as in, when doing any sort of color manipulation, like lighting, they operate on within the linear color-space, is there any good reason to not store all texture assets in the linear color-space?
My understanding is that when loading textures which are stored in sRGB, the GPU can do the conversion to linear for you very quickly. Is that cost completely negligible? Why not just store all the textures in that form?
The only reason I can think against this is that you may want to store the textures in a color-space that looks like the one you intend to display to (if you're going to display to sRGB then you should store the textures in sRGB). In that case, why not master the texture as sRGB but then store them on disk already converted to linear colorspace?


texts: Passing heightmap data to btHeightfieldTerrainShape constructor

texts:
I was searching for a couple of hours, but I didn't find final solution, after trying many ways.

I'm trying to get heightmap heights data, and pass it to btHeightfieldTerrainShape.

Let's say my heightmap has 1024x1024 resolution.
I've stored each pixel color of my heightmap inside dynamic array as a final vertex height.

I use them to create and render terrain's model and it works fine.

But my question is: how to correctly convert those heights for bullet?
I've tried like this:

std::vector<float> dataVector;

for (size_t i = 0; i < terrainWidth; ++i)
    for (size_t j = 0; j < terrainHeight; j++)
        dataVector.push_back(getHeight(i, j));

Then pass it to the constructor: new btHeightfieldTerrainShape(terrainWidth, terrainHeight, &dataVector[0], ...);

...but I expected that it won't be working.


texts: Slick2d Particles loading xml returning null

texts:
I've made a particle class that creates a particle of Slick2d library, but the XML file doesn't want to load , it keeps giving me null error. I gave it the path as I do for everything but it refuses to work and its been like this for days I just cant get it to open that XML file. If anyone can help me it would be much appreciated.

try {
        particleImage = new Image("res/particles/particle.png", false);
        system = new ParticleSystem(particleImage,1500);

        //load the xml file and add the emitter to the system
        File xmlFile = new File("res/particles/bloodDown.xml");
        ConfigurableEmitter emitter = ParticleIO.loadEmitter(xmlFile);
        emitter.setPosition(315, 358);
        system.addEmitter(emitter);
    } catch (Exception e) {
        System.out.println("Exception: " +e.getMessage());
        e.printStackTrace();
        System.exit(0);
    }

Entire particle class : http://pastebin.com/rBR0xpE7

Particle manager class : http://pastebin.com/N8gNFk6W

Slick 2d documentation : http://www.slick2d.org/javadoc/

My structure of workspace:


texts: Octree implementation for fustrum culling

texts:
I'm learning modern (>=3.1) OpenGL by coding a 3D turn based strategy game, using C++.

The maps are composed of 100x90 3D hexagon tiles that range from 50 to 600 tris (20 different types) + any player units on those tiles. My current rendering technique involves sorting meshes by shaders they use (minimizing state changes) and then calling glDrawElementsInstanced() for drawing. Still get solid 16.6 ms/frame on my GTX 560Ti machine but the game struggles (45.45 ms/frame) on an old 8600GT card. I'm certain that using an octree and fustrum culling will help me here, but I have a few questions before I start implementing it:

Is it OK for an octree node to have multiple meshes in it (e.g. can a soldier and the hex tile he's standing on end up in the same octree node)?
How is one supposed to treat changes in object postion (e.g. several units are moving 3 hexes down)? I can't seem to find good a explanation on how to do it.
As I've noticed, soting meshes by shaders is a really good way to save GPU. If I put node contents into, let's say, std::list and sort it before rendering, do you think I would gain any performance, or would it just create overhead on CPU's end? I know that this sounds like early optimization and implementing + testing would be the best way to find out, but perhaps someone knows from experience?


texts: Using Event Driven Programming in games, when is it beneficial?

texts:
I am doing a refresher on ActionScript 3.

Other than using rudimentary tools like, Event.ENTER_FRAME and using events to receive input from the user's mouse and keyboard, I find that I rarely use events and prefer to use public functions.

I am starting to reconsider this approach. From what I have learned thus far, the event system works this way:

Each dispatcher can listen to itself during the target phase. Each display object on the stage, can listen to it's children before the target phase, during Capture or after the target phase, during bubbling.

I would like to see an example of good use of the Event class for
game programming. Have you used Event driven programming in a game
and have a good example you could share?
A lot of times I want to pass a message to a 'sibling' so I could
have their methods listen to the stage or the parent object. Is that
the best way to communicate between objects that are not parents of
the dispatcher they want to listen to?
I would like to know if events are better performance wise than public functions.
Are there cases where using events can result in superior performance than avoiding events and sticking to function calls?


texts:
I'm using unity and trying to get my bullet to shoot at a target. I am clicking the mouse and I'm wanting to fire my bullet in that direction.

I have gotten the coordinates of the mouse click and tried to compute the vector. Then I've tried instantiate the bullet prefab (which has rigidbody component and is in front of the scene) at my position and then fire it in the direction of the mouse.

I can see that my objects being instantiated in my Hierarchy Pane but can't see anything on the screen!

Not sure if I'm doing the vector thing right (newb here), but if I click on Yoshi's head, I'm getting (-2.0, -0.4). Does this sound right?

Code:

void fireBullet(float mousePositionX, float mousePositionY)
    {

        Vector2 position = new Vector2(mousePositionX, mousePositionY);
        position = Camera.main.ScreenToWorldPoint(position);
        GameObject bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity) as GameObject;
        bullet.transform.LookAt(position);
        Debug.Log(position);
        bullet.rigidbody2D.AddForce(bullet.transform.forward * 1000);
    }


texts: SpriteKit Obj-C – How to add a force on a node a certain distance according to screen size

texts:
I have an SKSpriteNode that I'm trying to throw up to a certain point on the screen. I've tried applying an impulse and/or force according to the screen size, but that has strange results. I've also tried changing the sprite's velocity according to the screen size. Here's some code I tried.

- (void)createFlyingButton
{
    NSLog(@"Flying button created!");

    // Create the button.
    SKSpriteNode *button = [SKSpriteNode spriteNodeWithImageNamed:@"BlueButton"];
    button.name = @"BlueButton";
    button.size = _buttonSize;
    button.position = CGPointMake(randomInRange(self.size.width * 0.25, self.size.width * 0.75),
                                  -(_buttonSize.height * 3.0));
    button.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:_buttonSize.width * 0.5];
    button.physicsBody.collisionBitMask = 0.0;
    [self addChild:button];

    // Send it flying.
//    button.physicsBody.velocity = CGVectorMake(randomInRange(-self.size.width * 0.4, self.size.width * 0.4),
//                                               randomInRange((self.size.height * 1.6), self.size.height * 1.8));
//    [button runAction:[SKAction applyImpulse:CGVectorMake(randomInRange(-self.size.width * 0.1, self.size.width * 0.1),
//                                                          randomInRange((self.size.height * 0.8), self.size.height * 0.8))
//                                    duration:1.0]];

}

Any other suggestions?


texts: How can I get pre-release reviews of my mobile game?

texts: My iOS and Android game is at its last stage of development. Is there a way for me to get pre-release reviews from people? Or maybe from the press? How should I proceed?


texts:
Just a question regarding the storage of 2D map data. There are several topics discussed within gamedev, i.e. Array Storage: How to store 2D tile-map, custom map formats: A way to store potentially infinite 2D map data? etc

Considering that I intend to pre-generate my entire map at the start of the game (Much like Terraria does) and store that and then load 'chunks' of the data into an array or custom format as the player moves through it and interacts with the environment.

Been a total noob my question my be a little naive, but is there something wrong with pre-generating the map data (tile based, side view with each tile type represented as a discreet integer) as a PNG (No alpha) and saving that. Then read in the section of the PNG for the chunk to be loaded and converting the specific pixels to their integer value to determine what tile it represents ?

I could possibly even have one PNG for the terrain, one to represent containers and loot, which would be read separately and overlaid, then one for structures etc.

Then also obviously update the PNGs as terrain is created/destroyed by the player.

I can only assume this is not discussed anywhere as its probably slow versus maybe just reading/writing from/to a binary data format/array?

Regards
John


texts: Smoothly resize minimap camera rect width and height

texts:
I have an orthographic camera that is working as a mini-map. Now I want to make it resizeable using mouse drag. I have applied some UI beside my minimap camera rect and those UI resizing perfectly with this code. But I have no clue that how to resize my camera rect with mouse drag:
 void Awake()
    {
        rectTransform = transform.GetComponent<RectTransform>();
    }

    public void OnPointerDown(PointerEventData data)
    {
        if (!resizePanelFeatureActive) return;
        rectTransform.SetAsLastSibling();
        RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, data.position, data.pressEventCamera, out previousPointerPosition);
    }

    public void OnDrag(PointerEventData data)
    {
        if (!resizePanelFeatureActive) return;

        if (rectTransform == null)
            return;

        Vector2 sizeDelta = rectTransform.sizeDelta;

        RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, data.position, data.pressEventCamera, out currentPointerPosition);
        Vector2 resizeValue = currentPointerPosition - previousPointerPosition;

        sizeDelta += new Vector2(resizeValue.x, resizeValue.y);
        sizeDelta = new Vector2(
               Mathf.Clamp(sizeDelta.x, minSize.x, maxSize.x),
               Mathf.Clamp(sizeDelta.y, minSize.y, maxSize.y)
               );

        rectTransform.sizeDelta = sizeDelta;

        previousPointerPosition = currentPointerPosition;
    }


texts: How to update model transform of components when using physics?

texts:
I implemented a high level components system for my renderer and am curious about the right way to update the transforms components of models that have a physics rigidbody attached. I am using bulletsharp. To clarify. Transformcomponents holds the model matrix that is used for rendering. Rigidbody holds the worldmatrix that is getting modified by step simulation of bulletsharp. I want my rigidbody and transformcomponents matrices to stay synced.

My idea is to do it like this per render loop:

Always use transformcomponent for rendering
Execute physics step simulation
Update all transformcomponents with new matrices from  rigidbody
Whenever transformcomponent gets a matrix update from user input and not physics... Update the matrices recursive for the attached rigidbody and all children
Render with matrices of transformcomponents

Is there a better way to implement rigidbody physics in a components system for rendering? I use the physics mainly for raycast picking and OBB collision detection.

And when I use the term "better", I mean more efficient in terms of least updates on scene components. Syncing two components matrices seems tedious and I want to know if there is a solution without syncing.


texts:
While attempting to constrain camera scrolling to within the TiledMap I discovered that it seems the renderer for the map is not drawing the entire map. The map is 1600x960px so one would assume the setting the camera position to 1600, 960, 0 would result in the top right corner of the map to be centered, however to actually center the map (I had to do some trial and error for this) the coordinates are closer to 1175, 740, 0.

The map is made of 25x15 tiles and each tile is 64x64px. I initialize the map and renderer like this:

    tileMap = new TmxMapLoader().load("maps/" + file);
    renderer = new OrthogonalTiledMapRenderer(tileMap, stage.getBatch());
    renderer.setView((OrthographicCamera) stage.getCamera());

Then to render I just call renderer.render().

Any idea why this could be happening and how to fix it?


texts: How to use MaterialPropertyBlocks to randomly change the color of multiple materials on an object?

texts:
I have a character prefab for a civilian with 5 materials. Each one should be a random color but I don't want a new material for every civilian in the game. I asked a question earlier and had a good answer. However I was pointed towards this question with MaterialPropertyBlocks. This is the code I currently have:

void Start () {
    Color newShirtColor = shirtColor[Random.Range(0, shirtColor.Length)];

    MaterialPropertyBlock props = new MaterialPropertyBlock();
    props.AddColor("_Color", newShirtColor);
    GetComponent<SkinnedMeshRenderer>().SetPropertyBlock(props);
}

It works really well but the color is assigned to the whole mesh. How can I do this for each of the 5 materials on the object so that it only changed the color for the assigned parts of the mesh, with only one material for each section?


texts: Choose Atom as my script editor for Unity3D, problem with autocomplete

texts:
I am trying to configure Atom, so that when I edit my C# scripts from my project, I am aided by the Unity autocomplete. So far, I am able to open the project and every time I type an error in Atom, Unity shows it in its logs. But you get my point, for example, when I am using Visual Studio, I have had this autocomplete functionality from the beginning without having me to do anything in particular.

I went to External Tools and choose the atom.exe from the following the AppData folder path. I am required some External Script Editor Args and I am not sure what to type there. After doing all of this, I pressed Open C# Project from the Assets drop-down menu as I have read that this syncs the project. Atom opened, I had the project in the tree-view and when I start editing, I did not get the autocomplete functionality.

Does anyone else use Atom or at least Sublime as text editor? Did you stumble over this issue too?


texts: How to draw a circle with WebGL using GL_POINTS

texts: I'm trying to draw a circle using simple vertices points and a big gl_PointSize value. I found this example and try to reproduce it on WebGL with no success.


texts: Am I allowed to release an app I developed with Xcode on windows?

texts: I want to develop an app for the iOS app store, but don't want to invest in a mac since they start very expensive. So I considered running Xcode via VMware using OSX Lion on my windows 7 computer. Would it be legal for me to create and sell an app if it was created on windows? Is Apple fine with it? Selling it on Cydia or other jailbreak stores are not an option.


texts: Why do my game objects jitter when moving the camera?

texts:
I'm moving from Qt Widgets' QGraphicsScene to Qt Quick's QQuickItem for rendering my game objects. One of the things this involves is setting up a scene and the view onto that scene, as this was previously managed by QGraphicsScene and QGraphicsView.

My naive attempt was to do the following:

void SceneView::centerOn(const QPointF &pos)
{
    if (mScene) {
        mScene->setX(-(pos.x() - width() / 2));
        mScene->setY(-(pos.y() - height() / 2));
    }
}

This works, but it produces this odd effect where some game objects "jump around" between neighbouring pixels while the camera comes to a halt while following the player:

The player's movement is fine. The crate also does not seem to exhibit this problem (though its Box2D debug drawing marker does).

This is what it looks like when the player moves without the camera following it:

This is what I'd expect from the other game objects when the camera is moving; no movement whatsoever relative to the scene.

The old, correct movement looked like this:

The old code:

void MapView::centerOverFollowedItem()
{
    QRectF geometry(mFollowing->pos(), mFollowing->boundingRect().size());
    centerOn(geometry.center());
}

(QGraphicsView::centerOn implementation)

What could be causing this?


texts: According to Collision Change Rotation of Car

texts:
Basically I want to give rotation to player car as per collision occur with wall. Following image gives you over all idea.

I have following code that giving me correct collision reflection but its in position form not for rotation.

void OnCollisionEnter2D (Collision2D other)
{
    ContactPoint2D contact = other.contacts [0];
//      Vector3 reflectedVelocity = Vector3.Reflect (direction, contact.normal);
//      direction = reflectedVelocity;

    Quaternion reflectedRot = Quaternion.FromToRotation (transform.up, contact.normal);
    transform.rotation *= reflectedRot;
}

What I have to do for getting correct collision rotation for car? As well smooth turn for car on same rotation so car start moving on that way.

Please give me some help for this.


texts:
Trying to implement a movement through a curve - I'm trying to find a type of curve/spline that interpolates constantly. What I mean: when I interpolate from t=0 to t=0.1, I want it be the same distance as when interpolating from t=0.1 to t=0.2. And I want it to happen for every delta t on the spline.

I dont' want to make lookup tables that map the interpolated values to distances in order to save the memory. Does anybod knows are there any kind of such mathematical constructs?

I could do a in depth research, but as far as I can, I dont wan go to deep into details. It would be great having some simple formula.


texts: Is there a way to prevent users from adjusting their gamma correction to 'cheat' their way out of a 'dark' area?

texts:
In almost every game I've come across that includes a dark situation designed to change the way a user interacts with the environment, there are always some players who turn up their monitor's gamma correction in order to negate the desired effect.

Is there a way to prevent users from adjusting their gamma correction to 'cheat' their way out of a challenge? (the darkness)

I'd imagine if you could reliably retrieve the current gamma correction of the user's monitor, you could use that to more or less prevent the advantage it would otherwise grant without causing the normal users any inconvenience.


texts: How do you set the movement speed of a sprite?

texts:
I'm using Slick 2D/Java to play around with graphics. Getting an image to move is easy:

Input input = gc.getInput();

        if(input.isKeyDown(sprite.up)){
            sprite.y--;
        }else if (input.isKeyDown(sprite.down)){
            sprite.y++;
        }else if (input.isKeyDown(sprite.left)){
            sprite.x--;
        }else if (input.isKeyDown(sprite.right)){
            sprite.x++;
        }

However, this is called on every update, so if you hold up, the sprite moves to the edge of the screen in a few hundred milliseconds. Since coordinates are integers, I can't add less than 1 to slow the sprite down. I'm assuming I must have to implement a timer of some sort or something. Any advice?


texts:
I know that what both glEdgeFlagv and glEdgeFlag do is toggle boundary edge status, but my question is why does the v version exist when the documentation specifies that the only difference is that glEdgeFlagv takes (quoting from documentation):

  a pointer to an array that contains a single Boolean element, which
  replaces the current edge flag value.

What's the point of having a special version that takes a pointer to an array of length one? I can't imagine its to let you toggle the pointed-to bool to change the value later because the documentation would have to mention that to avoid inadvertent frees. I don't know of any platform where a pointer is smaller than a bool. When would one use glEdgeFlagv instead of glEdgeFlag?


texts: Implementing a more reliable upwards slash?

texts:
I am working on a 2D action platformer and I am currently implementing an upwards slash.

For a normal horizontal slash, the player must press the attack button. For an upwards slash, the player must hold up and press the attack button.

I notice that when trying to do an upwards slash, players often press the attack button a few milliseconds before the up  button, causing the player to do a normal slash rather than the intended upwards slash. It feels bad.

I am wondering what are some techniques I could use to get a more reliable-feeling upwards slash?

I considered waiting for some interval (for example, 20 milliseconds) after attack is pressed to see if up is pressed. If it is pressed in that interval, do upwards slash, otherwise do regular slash at the end of the interval. But this made the game feel unresponsive.

For a similar reason, I want the attacks to happen on button press rather than button release.


texts: How to activate an object only when it's within the camera view

texts:
I want to toggle an object's active state using the camera view:

when the object leaves the view it deactivates
when the object enters the camera's view it activates

I'm using this to control the activity of objects in a carousel like this

I did this with a coroutine, but in my project the fps is falling a lot
because of the coroutine.

I've already used OnBecameVisible and isVisible but that's not it since they only work with a renderer.

    public void next() {
        StartCoroutine(On(waitnext));
    }

    IEnumerator On(float waitnext) {
        yield return new WaitForSeconds(waitnext);
        myArray[Selecao].SetActive(false);
        Selecao++;
        if(Selecao > myArray.Length - 1) {
            Selecao = 0;
        }
        yield return new WaitForSeconds(waitnext);
        myArray[Selecao].SetActive(true);
    }

    public void previous() {
        StartCoroutine(On2(waitprevious));
    }

    IEnumerator On2(float waitprevious) {
        yield return new WaitForSeconds(waitprevious);
        myArray[Selecao].SetActive(false);
        Selecao--;
        if(Selecao < 0) {
            Selecao = myArray.Length - 1;
        }
        yield return new WaitForSeconds(waitprevious);
        myArray[Selecao].SetActive(true);
    }


texts: Unity 2d: Not Destroying enemies - impact on memory

texts:
I know pretty much zero about game performance in Unity. I am trying to figure out if I can afford to put this feature in my game:
I would like to have the enemies killed to pile up in a sort of heap, so I was thinking about not using the same old destroying routine after they die.

The game itself is really simple, it's 2D and for mobile. It has a fixed background and there's not much moving around aside from the player, the enemies and few npcs (which would get destroyed when offscreen), we're talking around ten 32X32 sprites onscreen at a time. Once dead the enemies would not be removed but they wouldn't need to be raycasting, colliding, ecc.. Just only be there for visual sake.

So the question is: would a mobile device easily handle not removed enemies in the order of a hundred or so (I could destroy those at the bottom of the heap) and not slow down or crash the game?
Are there some example of this kind of feature (other games that don't destroy dead enemies)? Or is there a good practice too keep enemies in game without impacting memory resources?

Thanks for the attention.


texts: Which image format is more memory-efficient: PNG, JPEG, or GIF?

texts: Which image format is more efficient to save memory? PNG, JPEG, or GIF?


texts: sound stops after scene reloads in unity3d

texts:
I'm recently facing problem regarding the inclusion of sounds in my game. Although i have used the technique of DontDestroyOnLoad() for background sounds and that work perfectly fine. But for the casual sound, it is creating problem that it stops during scene reloads. I have my script below that contains AudioClips and AudioSources and that script is attached to an empty game object, and calling that script in different scripts for the playback of the sounds.

AudioScript.cs

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

public class AudioScript : MonoBehaviour {

    public AudioClip pinshit;

    public AudioClip rowlingball;

    public AudioSource rowling;

    public AudioSource hit;

    public AudioClip cheer;

    public AudioClip strike;

    public Text counttext;

    public AudioClip spare;

    public AudioClip sorrow;

    public AudioClip winaudio;

    GameObject[] music;

    // Use this for initialization
    void Start () {

        rowling = GetComponent<AudioSource>();

        music = GameObject.FindGameObjectsWithTag("class");

        if (music.Length == 1)
        {

        }
        else
        {
            for (int i = 1; i < music.Length; i++)
            {
                Destroy(music[i]);
            }
        }

    }

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

    }

    private void Awake()
    {
        DontDestroyOnLoad(this.gameObject);
    }
}

To play sound on different actions routines

sorrow.clip = GameObject.FindWithTag("class").GetComponent<AudioScript>().sorrow;

                sorrow.Play();

                sorrow.volume = 1;


texts: Layout problem when implementing chat UI in Unity

texts:
I want to implement UI layout in Unity:

And here's what I've already done in Unity using an scroll view and putting a Vertical Layout Group and a Content Size Fitter on its content

Now the problem is because I'm using Vertical Layout Group on scroll view's content I'm unable to assign the x value of these chat bubbles because I have to align the other user's chat bubbles to the left and align the self chat bubbles to the right just like the first image. Any ideas on that?


texts:
I am using GLFW to manage OpenGL context and as such, delegate this task to a GLFW window. For managing the pointer to a window instance, I am thinking a class like this:

class window_t {
public:
    using win_handle = GLFWwindow*;

    window_t(size_t width, size_t height, const std::string &title)
    {
        // Initialize GLFW
        if (!glfwInit())
            std::exit(EXIT_FAILURE);

        // Set up OpenGl core profile
        ...

       // Open the window
       w = glfwCreateWindow(width, height, title.c_str(), NULL, NULL);

       if (!w) {
            glfwTerminate();
            std::exit(EXIT_FAILURE);
       }

        glfwMakeContextCurrent(w);
    }

    void swap_buffers()
    {
        glfwSwapBuffers(w);
    }

    void poll_events()
    {
        glfwPollEvents();
    }

    void terminate()
    {
        glfwTerminate();
    }
    bool about_to_close()
    {
        return glfwWindowShouldClose(w);
    }

private:
    win_handle w;
};

Think something similar. In my display_t class, I have an instance of window_t and an instance of scene_graph. Functions on my scene graph are like render(window_t), handle_input(window_t) etc. What would my strategy should be in passing around these window instances? These are actually a handle to GLFW window and OpenGL context. It is not desirable to copy them because some parts of these context variables are living in VRAM and relates to GPU state. So if I want to change the context variables on say handle_input(window_t), copying the window would defy the purpose. On the other hand, I don't want to pass raw pointers around. I can do a singleton maybe, considering I probably won't have multiple windows and OpenGL contexes. I am not really sure about this one though. And they say, singleton is as good as a global variable.

Maybe I should make window_t moveable but not copyable, making it hold a unique_ptr or something like that. I want to use value semantics as much as I can.

I really don't know the correct abstraction here. What would you suggest? Should I get rid of passing a handle to window to each object in scene graph? I am actually looking for a way to do this but all render calls, input handling etc. modifies the context variables. Want to hear your suggestions on this.


texts: Rendering tiles at a larger size for a detailed look

texts:
I'm trying to make my 32-bit tiled map become more "zoomed" in. However, I experience an error that I can't resolve. Firstly, I followed this post on how to render the tiles larger.
This is my code (close to identical to the code in the other post):
class TiledMap:
    def __init__(self, filename):
        tm = pytmx.load_pygame(filename, pixelalpha=True)
        self.width = tm.width * tm.tilewidth
        self.height = tm.height * tm.tileheight

        self.tmxdata = tm

    def render(self,surface):
        ti = self.tmxdata.get_tile_image_by_gid
        for layer in self.tmxdata.visible_layers:
            if isinstance(layer,pytmx.TiledTileLayer):
                for x,y,gid in layer:
                    tile = ti(gid)
                    tile = pg.transform.scale(tile,(64,64))       <---------- Line that gives Error
                    if tile:
                        surface.blit(tile,(x * 64, y * 64))

    def make_map(self):
        temp_surface = pg.Surface((self.width, self.height))
        self.render(temp_surface)
        return temp_surface

The error that is produced is:
tile = pg.transform.scale(tile,(64,64))
TypeError: argument 1 must be pygame.Surface, not None

I'm suspecting that some tile that its trying to render simply is empty. I've tried a separate smaller map but the issue persists. Is it the tileset? They've all been processed through the program Tiled where they were initially part of one png.
If anyone knows a possible solutions I'll gladly try one. Or any other methods that could make it more zoomed in...


texts:
I'm trying to find a half float for the purposes of doing math in a fragment shader, not trying to have a half float texture.

Is there an equivalent of the half float data type in WebGL?
I know you can create a lowp float, but is that the same, or not necessarily?


texts: Creating installer for WinForms XNA with compiled content

texts:
I have a Windows Forms application that uses a custom Graphics Device control based on Microsoft's "WinForms Series 1: Graphics Device" sample. The application makes use of a single model (the spaceship model included with the second sample) and its associated texture.

My main project includes a reference to an XNA Game Library project, which contains a Content reference to my Content project.  When I build and run the project in either Debug or Release configuration, my model and texture are compiled into XNB format and loaded into the application as expected.

However, when I create an installer (either Windows Installer or ClickOnce) and run it, the content files are not present in any form in the installed location, so obviously I get a runtime exception. I've toggled every option I can find that looks relevant. Am I missing something?


texts: How can I apply a mesh collider in Unity to an entire imported model rather than a single piece?

texts:
I have a series of models from Blender I'm importing to Unity as .blend files and I need mesh colliders applied to each one.

What I'm finding is that with any model that is constructed of multiple primitives, applying the mesh collider to the object is unsuccessful.  The mesh collider can't find the mesh.  Unity seems to treat each shape inside the model as a separate object.  I've even noticed that the Unity editor will allow me to select a single piece of a model and drag it away if I'm not careful.  This is unexpected behavior and somewhat alarming.

I've discovered that if I apply a separate mesh collider to each individual piece inside the model, the colliders will find the sub-meshes and the collision detection will work.  My primary concern at the moment is that this is monotonous.  For example, if I have the following model of a road intersection, then I'll need to individually select each of the seven pieces and create a mesh collider for each one.

How can I apply a mesh collider to the entire model in one move?

UPDATE:

Based on some feedback and some thoughts on my own, I'm redesigning the road pieces to simply be solid road on the bottom with the sidewalks on top.  This way, I'll only need one collider for the bottom, for now (if I don't care about testing collisions with the sidewalk edges yet).

I'm hesitant to merge the meshes into a single mesh at this time, though, since I'm potentially not done modelling street pieces yet.  This also doesn't address the long-term question of what to do in the final version of the game.

Unity primitives have automatic collision detection, but simulating hills this way and still having the pieces meet seamlessly is difficult.  They also won't do curved surfaces as far as I know.

I'd rather not use box colliders, since that will involve a lot of painstaking zooming in and tweaking of tiny values to get them perfect.  It also seems that box colliders will only rotate with a model and not to a model that's already sloped.

What I'm trying to avoid is spending almost as much time messing around with the colliders as I did modelling these bits in the first place.

Sticking with the mesh colliders is looking like the best option for now, since most of these shapes are simple, 6-sided objects and it's only a couple of clicks to add a mesh collider to each shape.  It sounds like if I do it this way, it might be smarter to keep the meshes un-merged, since I would then be using a mesh collider on a concave object.


texts: How can I convert .X files from text to binary form?

texts:
Is there a tool for Linux (preferably a command-line tool) that can convert from the .x text format to the binary format? I wish to use this format with Irrlicht but the text format is loading very slowly (taking around 8 seconds to load one model), so I'm wondering if the binary format will be faster.

I have seen this question, but that seems to be asking more for pointers on learning the .x format, whereas I am specifically looking for a Linux tool.


texts: I made match-3 game and now i trying to add level generator. Now I generate level by filling random cells with random blocks, but I want to create generator which for given number of moves and number of block kinds generate level. What algorithms I can use if they exists?


texts:
I am starting to develop my fist bigger game in HTML5 and struggling a bit with sprites. I can cut out single items, but I need to repeat them as well. For example, I have a battle ground that consists of grass, dirt path, building and a pond. I have all these in one sprite. But what I really need is to cut out the grass and repeat is as background on whole canvas.

I cannot believe that this wouldn't be possible, using sprites would loose almost completely point there... (apart from single static items of course).

I would appreciate if someone would have solution to this.


texts:
I'm working on a little game for learning purposes so please don't recommend me to use any library like libgdx or slickutils.

I have just one simple question. Does rendering bigger images with Graphits.drawImage(); slow the Process down?

I'm currently drawing about 200 little Objects (PNG, 64x64 resized to 48x48), but they don't seem to be an issue (i know resizing them each frame is not very performant).

The game slows down as soon as I draw the background with a parallax effect (several layers and at least 3 seamless fitting objects per layer).

They Art drawn in their original size 900x900 Pixel. But they keep slowing the game down. It's only the graphisch.drawImage(); Part. The Rest of the calculation doesn't seem to affect the game at all.

I store all Images I need once when starting the game in a class called Resources in BufferedImages.

I hope someone can explain this to me.


texts: Unity Mesh and Collider not aligned on rotation

texts: I have a GameObject with a mesh and a collider. When I rotate the object the mesh and the colider do not act the same way and when the GameObject is rotate 65 degrees on the z axis the mesh and the colider are no longer aligned. This must affect game play. I don't understand why this happens and how it is supposed to be fixed.


texts: Effect of graphics card on game programming

texts: I know the question can be pretty funny to some, but I have been thinking, does a gaming  graphics card like agtx and a professional graphics card like quaddro have any effect on game development during texture rendering, materials, importing assets, shader compilation, etc..