texts:
This morning I've seen the following animation on Twitter. It is a kind of Möbius strip effect.

It's cool! Isn't it? So I've decided to build something similar using Unity, just for fun. I want to build the effect using just the cameras, as this way we can use it for any rotating scene. The first step has been to create a circle scene and make it rotate:

Note that the camera uses an ortographic projection so perspective does not deform it. This is important so we can merge different views later.

Then I've replaced the main camera by two different ones, located in opposite positions (horizontal and vertical) and rendering to textures. A simple Canvas with two panels (divided vertically) shows the partial result (one camera texture per panel):

I know this is cool, but not perfect yet, as the center of the rendered output shows clearly where a panel finishes and the other one starts. Look at the center of the rendered output above.

The original inspiration video shows no perspective in the center, and I think that is the trick, but I cannot achieve that with an orthographic camera (or I don't know how).

Do you know any approach to distort the camera or something similar, so the cameras are perpendicular in the middle of the scene (and only in the middle)? Are you able to think a solution to dissimulate the joint of both camera views?

As a first approach (dismissed for the moment) I've tried to add another camera, perpendicular to the scene so there is no perspective in that point. Then I render its output in the UI in another panel on top of the previous ones. And it is not too bad, but again the joint is too obvious and now I have two joints instead of one:


texts:
When creating things like physics in games you need an integrator. I've seen Verlet integration mentioned several places as a great alternative to Euler integration. For instance in the famous document by Thomas Jakobsen. However in this article Glenn Fiedler writes:

  Rather than introduce you to the vast array of different integrators that exist, I’m going to cut to the chase and go straight to the best. This integrator is called the Runge Kutta order 4 integrator aka RK4.

So apparently there's no silver bullet. What is the pros and cons of different integrators? Regarding simplicity, speed, accuracy, stability, etc. Which integrators is most suitable for which types of games? When would you use Verlet, RK4 or others? Should you ever use Euler?


texts: Some meshes are visible in game view while others are not

texts:
I have a FPS character in unity. The FPS character is divided into a few different pieces (upper arm, lower arm, hand, fingers, etc). I exported it from blender, so I'm using the camera that got converted from the blender camera.
For some reason, the mesh is not showing up in the game view/camera vision.
I did a little bit of testing and found out that:

If I move the camera away, the mesh shows up, so the mesh isn't invisible or anything
I put a version of the character that I imported from blender earlier as a test(different rest pose and less animations attached to it) in the same location as the FPS character, and attached the same animator to it. When I did that, you can see the earlier version but not the newest one
The same thing happens even if I change the camera

The camera has a field of view of about 67, and a focal length of 18. Near is set to the lowest value possible. Both characters are visible in scene view, just not in game view.


texts: What does a perspective projection matrix look like in OpenGL?

texts:
I've been trying to construct a perspective projection matrix
myself and finding it extremely difficult.

I realize that a perspective projection matrix is by default a frustum in OpenGL 3.3+ that is transformed into a unit cube
and I need to divide x , y and z by -z too project x y z into -z
then I need to divide by w after I've done some equations on I believe
these values top , bottom , left , right , zFar and ZNear however
I don't exactly know what those equations are and I'm not exactly savy
in all the maths required to do this persay also I've read that this is not the full perspective projection matrix and I need some kind of clipping planes?

GLfloat x = 1.0-z;
GLfloat y = 1.0-z;
GLfloat z = 1.0-z;

GLfloat projm[16] = {0};

//crazy equations that I don't know with values
//that I don't know where to place exactly:
//top , bottom , left , right , zFar and ZNear

x / w;
y / w;
z / w;

projm[] ={x, 0.0 , 0.0, 1.0,
          0.0, y , 0.0, 1.0,
          0.0, 0.0, z,  1.0};

I'm very aware of GLM , I'd prefer too do it myself for learning , curosity and potential benefits please be gentle.


texts: When should I use GL_TRUE or GL_FALSE values?

texts:
When using GLboolean, should I just use true and false or should I use GL_TRUE and GL_FALSE? When should I prefer using GL_TRUE and GL_FALSE? or maybe I shouldn't care at all (Because both works)?

Here It is said that both are actually a different type.

But in some tutorial websites I've read, they use GL_TRUE or GL_FALSE on functions that requires GLboolean. Example:

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*) 0);

Well, it works too if we substitute GL_FALSE with false in the code above.


texts: GameObject.Find can't find the object after i changed its name

texts:
I created this script to create a group of plane meshes with offset between them in my game scene, then change their names and give an ID to every one of them:

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

public class creatingobjectslist : MonoBehaviour {

    public GameObject TargetPrefab;

    void Start () {
        for (int i = 0; i < 5; i++){
            Instantiate(TargetPrefab, new Vector3(i * 1.5f, 0f, 0f), Quaternion.identity);
            TargetPrefab.name = "Ben" +i;
        }
    }
}

Then I created this script and attached it to another object to move my object to one of the objects that was created with the creatingobjectslist script

using UnityEngine;
using System.Collections;
public class MoveCubeTogrid : MonoBehaviour {
    UnityEngine.AI.NavMeshAgent agent;

    void Start () {
        agent = GetComponent< UnityEngine.AI.NavMeshAgent >();
    }

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

            if (Physics.Raycast(ray, out hit, Mathf.Infinity)) {
                    //agent.destination = hit.point;
                    agent.destination = GameObject.Find("Ben0").transform.position;
            }
        }
    }
}

and after running that I get this error

NullReferenceException: Object reference not set to an instance of an object


texts: How do I do 2D z-index parallax in Unity3d?

texts:
I am new to unity3d and want to develop a simple game like crazy cabie. I have to implement a z-index parallax for moving sprites towards the player and generating new sprite at the farthest z-index.

How can I do this?


texts: Where does event-based audio fit in a component-based entity system?

texts:
Assuming the underlying low level audio logic is encapsulated in some outside class... what is the best way to add audio effects to a component-based entity framework?

I am taking the approach that entities are just IDs and a type of database is used to associate components with entity IDs.  The I can create masks for the systems to query particular types from the database.

So for example for components I might have:

PositionComponent.
PhysicsComponent.
VisualComponent.

And the corresponding systems:

VisualSystem, which processes visual components, hands off to outside renderer.
PhysicsSystem, which processes physics, updates position vectors.

So the question is, how best to add audio to this system... or should I even bother?  The problem I am having is mapping sounds to actions and when to play sounds.

Here are some approaches I've thought of::

Force PhysicsComponents to have a some collision sound field and when a collision occurs, play the sound within the physics system.
Same as 1 but instead when a collision is detected add a SoundComponent(sound) to the entity and lets the SoundSystem see that and consume it (so the sound plays once for example).  This still means PhysicsComponent would have a sound field.  So really this just shifts the playing of audio into a system.

I don't like either of those approaches.  They are not very suitable to expanding the game either.  Now I would need a field for every possible sound a unit could generate.

Really I think individual entities should dictate which sound to play based on some component attached to them I would assume.  The question then becomes how to know when to play that sound.

Sorry if this is all very vague.  Any tips appreciated.


texts: Is using multiple canvas objects a good practice?

texts:
We're developing a jump and run game with HTML5 and JavaScript and have to build an own game framework for this. Here we have some difficulties and would like to ask you for some advice:

We have a "Stage" object, which represents the root of our game and is a global div-wrapper.
The stage can contain multiple "Scenes", which are also div-elements. We would implement a Scene for the playing task, for pause, etc. and switch between them.
Each scene can therefore contain multiple "Layers", representing a canvas. These Layer contain "ObjectEntities", which represent images or other shapes like rectangles, etc. Each Objectentity has its own temporaryCanvas, to be able to draw images for one entity, whereas another contains a rectangle.

We set an activeScene in our Stage, so when the game is played, just the active scene is drawn.
Calling activeScene.draw(), calls all sublayers to draw, which draw their entities (calling drawImage(entity.canvas)).
But is this some kind of good practice? Having multiple canvas to draw? Each game loop every layer-context is cleared and drawn again. E.g. we just have a still Background-Layer, … wouldn't it be more useful to draw this once and not to clear it every time and redraw it?
Or should we use a global canvas for example in the Stage and just use this canvas to draw? But we thought this would be to expensive...


texts:
So recently i've been changing my XML files that i'm using in-game, to add in a bit more data to the files but i've also changed the way in which i load & save files, by now using the XDocument API.
*Previous Thread/Topic:
Xna, writing XML </Asset> end element

So now that i'm all done, i've come to trying out the new files in my new project and i have a strange error:
There was an error while deserializing intermediate XML. Input string was not in a correct format.

Oddly though, this at line 13:
http://pastebin.com/jMtNwV8N

In all honesty i don't know what to say. And to what exactly the problem is, i'm having a slight hunch that it could be something to-do with the way the files are saved:
http://pastebin.com/Q2pJye5B

Problem is that my initial thinking right now is that it might have to be something to-do with the '\t' or '\n' literals, but then there's these literals in the actual data lines i.e lines 11 & 12 so it wouldn't all of a sudden chuck me an error at line 13

Guess i'm just a bit mystified by this and to what the problem might be?

Any help greatly appreciated :)!

Edit:
Well just to test it out then, i removed all the '\t' & '\n' from the saving code. And re-tried it then, unfortunately i'm still getting the same error :/
Same place, with the error occurring at the ending element of Rect.


texts: Weird member of float4 structure in the HLSL

texts:
I have encountered a weird x.wwww component of the float4 x vector in a HLSL code. I haven't seen such a member or member function of float4 structures in HLSL, so please tell me what is the meaning of that. It is in the code of this pixel shader:

float4 PSConstantColor( PS_PARTICLE_INPUT input ) : SV_TARGET
{
   // Sample particle texture
   float4 vColor = g_baseTexture.Sample( g_samLinear, input.Tex ).wwww;

   // Clip fully transparent pixels
   clip( vColor.a - 1.0/255.0 );

   // Return color
   return vColor;
}

At first I thought it should be the w component replicated to all the members of the float4 vColor vector, but it does not make sense for the color value, does it?


texts: How do I create a closed beta on the App Store?

texts:
After months of hard work, much to my surprise I'm about to unlock the "feature complete" and "production ready" achievements with the game I'm working on, so it's time to ask my colleagues and Facebook acquaintances if they'd like to help me by playtesting the game.

This is going to be my first game, and I'm wondering if I can somehow upload it as a "closed beta" to the App Store and generate a couple of keys/tokens, so I could hand these to my playtesters? This way they wouldn't have to install unsigned developer versions, so they'd also be testing the real installation process, and of course paying customers wouldn't even be seeing the product until I make it public.

Is this how a closed-beta testing goes at all?


texts: Loading Collada Files Quickly (three.js, OpenGL, Javascript)

texts:
Okay, so I've created these sleek-looking spaceship models for an OpenGL game that I'm going to make. To make them look sleek and smooth, I used a Subdivision Surface modifier in Blender. Hmm... 100000+ triangles.

I've managed to get the files down to the 30 to 40 thousands range (EDIT: under ten thousand, but with loss of quality) in terms of triangles though. So the file size is usually around a few megabytes.

Soon I found out that this wasn't really a problem when rendering the spaceships. However, I did quickly notice that it takes forever for Firefox to load one spaceship. And I want to load three of them, possibly more.

Chances are if I create a game that starts up with a "Please wait five years whilst everything loads" loading bar, it's going to turn away a lot of users. And I still haven't even considered loading planets, images, and a bunch of other stuff.

So now, for my questions:

Has anybody else run into this before? Is there a generally accepted solution for this type of problem?
Speaking of libraries, is there one that could apply the subdivision surface modifier on the models at run time? Then I could just export the model frames, which are only somewhere around 1000 triangles.

Also, any other input would be very much appreciated.

Thanks! :)

EDIT: What I've tried so far:

So far, compression looks like a no-go but I'm not sure.

method 1: zip folders: zipping the files drastically reduces filesize, but it requires a gigantic zip.js library to actually use the zip folders. So far I've been unable to get it to work, I guess the zip.js API is just way over my head.
method 2: custom compression: I've managed to make my own sort of compression system, but it's not nearly as effective and only cuts away half of the file size. Oh and it also looks like it is broken ATM xD

EDIT: just realized that the bottleneck might not be my internet speed, but rather the Collada file loading script that I'm using. (ColladaLoader.js, it's from three.js) in this case compression is definitely out of the picture.


texts: Importing an object from Blender into a scene, rotation on X axis?

texts:
This is my situation:

I save the scene with blender no export with any processing steps.

Blender has x right y up -z into the scene for the view coordinates (OpenGL)
I have x right y up -z into the scene for the view coordinates (OpenGl)
Bleneder has x/y plane and z up as world coordinates
I have x/y plane and z up as world coordinates

I load the mesh with assimp directly from the blend file with absolutely no post processing.
The object is rotated abount π/2 on the x-axis. Why?


texts: I’m having a problem with my terrain, it’s not rendering from underneath, iv’e also noticed this with any other plane I add into unity or model in blender, is this normal or is there a technical fix for this?


texts: How can I change my script execution order programmatically?

texts:
I have a script that I want to run before any other script.  I want to change its execution order settings.  I could do that using the Script Execution Order Settings option from within Unity, but I want to do this programmatically.

The reason I want to do this programmatically is because the script has an abstract class, and I want to avoid requiring the user to change the execution order every time they extend the class.  Changing the execution order of an abstract class is not an option in the Script Execution Order Settings.  My abstract class has reference to every class that extends it.

How can I change the execution order of a MonoBehaviour?  An example of what I am looking for would be along the lines of:

MonoBehaviour myBehaviour = GetMyMonoBehaviour();
myBehaviour.ExecutionOrder = -100;


texts: Grouping entities of the same component set into linear memory

texts:
We start from the basic systems-components-entities approach.

Let's create assemblages (term derived from this article) merely out of  information about types of components. It is done dynamically at runtime, just like we would add/remove components to an entity one by one, but let's just name it more precisely since it is only about type information.

Then we construct entities specifying assemblage for every of them. Once we create the entity, its assemblage is immutable which means we cannot directly modify it in place, but still we can obtain existing entity's signature to a local copy (along with contents), make proper changes to it, and create a new entity out of it.

Now for the key concept: whenever an entity is created, it is assigned to an object called assemblage bucket, which means that all entities of the same signature will be in the same container (e.g. in std::vector).

Now the systems just iterate through every bucket of their interest and do their job.

This approach has some advantages:

components are stored in a few (precisely: number of buckets) contiguous memory chunks - this improves memory friendliness and it is easier to dump whole game state
systems process components in a linear manner, which means improved cache coherency - bye bye dictionaries and random memory jumps
creating a new entity is as easy as mapping an assemblage to bucket and pushing back needed components to its vector
deleting an entity is as easy as one call to std::move to swap the last element with the deleted one, because order doesn't matter at this moment

If we have a lot of entities with completely different signatures, benefits of cache coherency kind of diminish, but I don't think it would happen in most applications.

There is also a problem with pointer invalidation once vectors are reallocated - this could be solved by introducing a structure like:

struct assemblage_bucket {
    struct entity_watcher {
        assemblage_bucket* owner;
        entity_id real_index_in_vector;
    };

    std::unordered_map<entity_id, std::vector<entity_watcher*>> subscribers;

    //...
};

So whenever for some reason in our game logic we want to keep track of a newly created entity, inside the bucket we register an entity_watcher, and once the entity has to be std::move'd during removal, we lookup its watchers and update their real_index_in_vector to new values. Most of the time this imposes just a single dictionary lookup for every entity deletion.

Are there any more disadvantages to this approach?

Why is the solution nowhere mentioned, despite being pretty obvious?

EDIT: I'm editing the question to "answer the answers", since comments are insufficient.

  you lose the dynamic nature of pluggable components, which was created
  specifically to get away from static class construction.

I don't. Maybe I did not explain it clearly enough:

auto signature = world.get_signature(entity_id); // this would just return entity_id.bucket_owner->bucket_signature or so
signature.add(foo_component);
signature.remove(bar_component);
world.delete_entity(entity_id); // entity_id would hold information about its bucket owner
world.create_entity(signature); // automatically assigns new entity to an existing or a new bucket

It's as simple as just taking existing entity's signature, modifying it and uploading again as a new entity. Pluggable, dynamic nature? Of course.
Here I'd like to emphasize that there is only one "assemblage" and one "bucket" class. Buckets are data-driven and created at runtime in an optimal quantity.

  you'd need to go through all buckets that might contain a valid
  target. Without an external data structure, collision detection could
  be equally as difficult.

Well, this is why we have the aforementioned external data structures.
The workaround is as simple as introducing an iterator in System class that detects when to jump to next bucket. The jumping would be purely transparent to the logic.


texts: Populate triangles array when you already have sorted vertices array

texts:
Input is a Vector3[] of verticies. Length is unknown, it could be anything above 2 - so these vertices form all kinds of multifaceted shapes with 3 being a triangle and 6 hexagon-ish.

Poor example to visualize:

vertices = [Vector3(..), Vector3(..), Vector3(..), Vector3(..), Vector3(..)];

Coordinates in that array are ordered counterclockwise. I also have the coordinates of center point that these verticies form (look at illustration below) - it doesn't have to be used but if it helps..

Few examples of which shapes can occur and which cannot:

Now I need to build meshes out of them. For each shape I need:

Vertices array (which I already have, nicely ordered)
Triangles array - 3 indices (from vertices array) per triangle until all vertices are covered

How to populate triangles array with these relatively easy shapes where each vertex has "direct line of sight" to every other vertices? Number of vertices is unknown of course.


texts: Not able to change the background of the scene in cocos2dx android

texts:
I have started Game Development using Cocos2d-x. And started with HelloWorld sample game. I am able to run this sample game. But when I try to change the Background Color, I am getting error in

 HelloWorldScene.h
    The type 'HelloWorld' must implement the inherited pure virtual method 'cocos2d::CCRGBAProtocol::setOpacity'

Changes:
class HelloWorld : public cocos2d::CCLayerColor

and also in

 **HelloWorldScene.cpp**

    Invalid arguments '
    Candidates are:
    bool initWithColor(const cocos2d::_ccColor4B &, ?, ?)
    bool initWithColor(const cocos2d::_ccColor4B &)
    '
   **Changes:**
   CC_BREAK_IF(!CCLayerColor::initWithColor(ccc4(255,255,255,255)));

I am new for Cocos2d-x and also for C++. Is there any thing left to include or what?


texts: C# JSONs not formatting array of objects stored inside another object.

texts:
I know the title is a bit confusing because I don't really know how to phrase this. This is what I have:

[System.Serializable]
public class Sector
{
    public string name;
    public Vector3 sectorPosition;
    public float sectorRadius;

    public buildingComponent[] components;

}
[System.Serializable]
public class buildingComponent : ScriptableObject
{
    public string componentType;
    public Vector3 componentPosition;
    public Vector3 compenentRotation;

}

When I try converting this into a json string like this:

        Sector ssector = new Sector();
        ssector.name = "sTom";
        ssector.sectorPosition = Vector3.up;
        ssector.sectorRadius = 2;
        ssector.components = new buildingComponent[3];
        print("component length " + ssector.components.Length);
        ssector.components[1] = new buildingComponent();

        ssector.components[1].componentPosition = new Vector3 (1, 2, 3);

        string sdata = JsonUtility.ToJson(ssector);

I end up with the following:

{"name":"sTom","sectorPosition":{"x":0.0,"y":1.0,"z":0.0},"sectorRadius":2.0,"components":[{"instanceID":0},{"instanceID":-341752},{"instanceID":0}]}`

The components array is not actually being formatted, it's only saved with an instanceId or whatever this does. Is there any solution to this or will I have to go with an alternative formatting. I just want to save this data on a server but I only get one string to do so, so I have to format everything into one string. Thanks in advance!


texts: Error in destroying object in Box2D/LibGDX

texts:
I'm trying to delete an object when a collision happens. I have put the following code in the render method of the object so it would be outside of the physics calculations.

public void render(SpriteBatch spriteBatch) {
    // some other code...
    body.setActive(false);
    body.getWorld().destroyBody(body);

But I'm getting an run-time error which crashes the JVM and shows,

  AL lib: alc_cleanup: 1 device not closed

  Assertion failed!

  Program: C:\Program Files\Java\jre6\bin\javaw.exe
  File: /var/lib/hudson/jobs/libgdx-git/workspace/gdx/jni/Box2D/Dynamics/b2World.cpp, Line 133

  Expression: m_bodyCount > 0

Can anyone help me here?


texts: How can I make smoother upwards/downwards controls in pygame?

texts:
This is a loop I use to interpret key events in a python game.

# Event Loop
for event in pygame.event.get():
    if event.type == QUIT:
        pygame.quit()
        sys.exit()
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_a:
            my_speed = -10;
        if event.key == pygame.K_d:
            my_speed = 10;
    if event.type == pygame.KEYUP:
        if event.key == pygame.K_a:
            my_speed = 0;
        if event.key == pygame.K_d:
            my_speed = 0;

The 'A' key represents up, while the 'D' key represents down. I use this loop within a larger drawing loop, that moves the sprite using this:

Paddle1.rect.y += my_speed;

I'm just making a simple pong game (as my first real code/non-gamemaker game) but there's a problem between moving upwards <=> downwards. Essentially, if I hold a button upwards (or downwards), and then press downwards (or upwards), now holding both buttons, the direction will change, which is a good thing. But if I then release the upward button, then the sprite will stop. It won't continue in the direction of my second input.

This kind of key pressing is actually common with WASD users, when changing directions quickly. Few people remember to let go of the first button before pressing the second. But my program doesn't accommodate the habit.

I think I understand the reason, which is that when I let go of my first key, the KEYUP event still triggers, setting the speed to 0. I need to make sure that if a key is released, it only sets the speed to 0 if another key isn't being pressed. But the interpreter will only go through one event at a time, I think, so I can't check if a key has been pressed if it's only interpreting the commands for a released key.

This is my dilemma. I want set the key controls so that a player doesn't have to press one button at a time to move upwards <=> downwards, making it smoother. How can I do that?


texts: Playstation 4 OpenGL ES support (or Xbox)

texts:
I know that the Playstation 3 supported at least OpenGL ES 1.0, and the Vita OpenGL ES 2.0. But what about the Playstation 4 (and/or the new PS4 Pro)? Does anyone know for certain if it has native support for OpenGL ES (that is, without using a compatibility/translation layer like ANGLE)?

Because it isn't backwards compatible with regular OpenGL, it'd be helpful to know if this platform supports any version of the OpenGL ES API.

I'm also curious about the Xbox One/Scorpio, although I'd be surprised if they had nativesupport for OpenGL at all.


texts: DirecX 11 R8G8B8 24bit format without alpha channel?

texts:
This is maybe a stupid question but I can't seem to find texture format for simple 24bit R8G8B8? There is only 32bit R8G8B8A8, but some of my textures don't have alpha channel.

Is there any way to do this, or I'll just have to create alpha channel on every texture?


texts:
I made a content pipeline extension (using this tutorial) in XNA 4.0 game.

I altered some aspects, so it serves my need better, but the basic idea still applies. Now I want to go a step further and enable my game to be changed during run time. The file I am loading trough my content pipeline extension is very simple, it only contains decimal numbers, so I want to enable the user to change that file at will and reload it while the game is running (without recompiling as I had to do so far). This file is a very simplified version of level editor, meaning that it contains rows like:
1 1,5 1,78 -3,6

Here, the first number determines the object that will be drawn to the scene, and the other 3 numbers are coordinates where that object will be placed.

So, how can I change the file that contains these numbers so that the game loads it and redraws the scene accordingly?

Thanks


texts: Lens Distortion not working with Unity 5.3.5

texts:
I have downloded the latest sdk from this link

https://github.com/googlevr/gvr-unity-sdk

I imported the package into my project.From the prefab added GvrMain to my scene and set the Distortion Correction to none as mentioned in the video below and edited the "GvrDistortion.cginc" shader .

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

But the lens distortion is not working for me. I have a dout that whether to edit the same folder or should create a new shader and include the existing shader file

I am using unity 5.3.5 and GoogleVRForUnity package


texts:
I found debugging games especially hard for some obvious reasons. It's hard to monitor some internal values in dynamic, conditional breakpoints helps somehow, but only to detect some specific conditions. You don't get information that lead you there. Sometimes you just want to monitor some value, sometimes value are hard to interpret in their internal form (say a current path calculated by AI).

So I'm thinking about implementing kind of debug layer which will draw this information above gameplay in real time. The question is how to do it in most convenient and reusable way.

I'm currently thinking to make interface say IDebugInfo, implement it in all entities which I want to monitor, and add then to debug layer (it's a DrawableGameComponent) via GameServices. The debug layer will draw them. It can be turned on or off in realtime by removing/adding debug layer.

Does this sound good? I'm almost sure this was done many times already, is there some proved patterns?

Update. So, I implemented it this way:

// iface
public interface IDebugDrawable
{
    void DrawDebug(GameTime gameTime, SpriteBatch spriteBatch);
}

// service
public class StateManager
{
    public StateManager()
    {
        this.DebugDrawables = new List<IDebugDrawable>();
    }

    public List<IDebugDrawable> DebugDrawables { get; private set; }
}

// debug screen draw
public override void Draw(GameTime gameTime)
{
    SpriteBatch sb = this.ScreenManager.SharedSpriteBatch;
    StateManager sm = this.ScreenManager.Game.GetService<StateManager>();

    sb.Begin();

    foreach (IDebugDrawable debugDrawable in sm.DebugDrawables)
    {
        debugDrawable.DrawDebug(gameTime, sb);
    }

    sb.End();
}

// implementation in game entity
public void DrawDebug(GameTime gameTime, SpriteBatch spriteBatch)
{
    spriteBatch.DrawString(
        DebugScreen.DebugFont,
        this.Cell.ToString(),
        this.Position,
        Color.White);
}

this looks like:


texts:
I got a sphere that moves with an angular velocity of -2000 in the X axis, I need that sphere moves on 130 platforms, all those platforms have -0.0182175 in the Y axis.

The problem is that when I play, the sphere starts normally but as it advances starts make some jumps, first shorts but then more large, and it is as if the platforms did not have the same value in the Y axis.

Can someone help me, please?

I've put some images.

Very thanks

Hey people!!
I've uploaded a video to show you clearly the problem.

Here's the link: Platforms, sphere and sphere script

Sorry for my english by the way.


texts: When and where should I calculate collision response with multiplayer physics?

texts:
I've troubles wrapping my head around multiplayer physics and collisions on the client side, so far I interpolate the state of my network entities ( position and velocity ) of the other clients based on the snapshot data I receive, but how should I handle collisions on the client side?

If I bump into another player, should I calculate the new position of the other player immediately after I interpolated the state or should I just predict the collision response of my local player and don't set a new position / velocity of the network entity on my client?


texts:
I have a TArray of type FColor (I got it from the viewport) and I want to change that to a Texture2D object I can't find anything in the API's and I'm new to Unreal.

Thanks


texts:
In my engine I have 2 types of 2D renderables: sprites and groups (and maybe primitives later). Sprites are just textured quads and groups are multiple renderables grouped in a single object. I have this drawcall system now:

struct Renderable
{
    virtual void Render(Renderer& renderer) = 0;
};

struct Sprite : public Renderable
{
    Texture& texture;
    // other sprite specific stuff
    void Render(Renderer& renderer) override { renderer.RenderSprite(...); }
};

struct Group : public Renderable
{
    vector<Renderable*> elements;
    // Other group related stuff like a transformation matrix
    void Render(Renderer& renderer) override
    {
        for (Renderable* r : elements)
            r->Render(renderer);
    }
};

Instead of sendig them straight to the renderer, I need an indirection. This makes rendering many (like 20K) sprites super slow. Is there a better design to avoid indirection (or even abstraction)?


texts: What is it called when you combine textures for an object

texts: I am trying to gain a better understanding for modeling and texturing for Unreal 4 and Blender. Now my question is: What is the process/result called when packing textures into one image as shown below?


texts:
I have two objects, both of them with polygon colliders. When I click on one of the objects, I want the player to drag it on top of the other object (without collision). If there is overlap when he drops the object, it snaps to the same position as the other object. Otherwise, it resets its position.

How do I:
1) make the colliders not prevent movement
2) make it so that it detects if they're overlapping when I let go
3) Make it snap to a very specific place depending on if they're overlapping or not


texts:
I am creating a tiled game (2D top down) and I created explosions working this way:

The blue lines are walls, the white grid is accessable space.
The red dot is the origin of the explosion with the green explosion radius.
The orange  lines are how I am doing raycasting (I am using Box2d) at the moment to ensure that only accessable things are hit (nothing behind the blue walls should be hit).

I cant just draw a circular sprite over the whole area as I dont want to let the explosion look like it is going over walls and stuff.
My solution: I will draw an explosion tile over each tile that is in the radius.

This is how I want the explosion to look like:

Everything in the yellow "polygon" should be drawn as an explosion.

There are some issues seen here in the purple circles:

In "real life" the explosion will go around corners.

My question simply is:
Do you have any idea on how to find all tiles that should be drawn as an explosion? Or maybe you do have a better approach!

The effect I want reminds me of minecraft water physics but in 2d.

Thank you!


texts:
I made the mistake of making my game Android only (via libGDX). A lot of people are asking me for an iPhone/iPad version. Sigh. (Next time, I'll use Unity or Corona SDK.)

I've searched high and low, and cannot find much (relevant or recent -- beyond 2010) about market share of these two phones, globally.

Where can I find the relative market shares of these phones, globally, to some degree of accuracy? It doesn't have to be 100% accurate, as long as it remains recent (i.e. updated every few months). Ideally, this is something like Android's Platform Versions, albeit it tells me about different OSes.

I really want to know, because when I choose a development platform, it might matter (if I make the mistake of not using a cross-platform development tool).


texts: Is it legal to add a cameo appearance of a known video game character in my game?

texts:
If I am not going to name the character and I use my own original art that very closely resembles a well-known video game character that appears in my game for a very brief moment, is it legal to add a cameo appearance of the character in my game? In an indie game and meant as a tribute to the original game, but I doubt that makes any difference.

Example 1: A scrolling 2D platformer with Super Mario in one level performing a single action and dissapearing afterwards. Not naming the character at all.

Example 2: A video game poster inside the game with Sonic The Hedgehog with or without naming the character, with or without Sega logo.

Fair use doesn't apply here, as I won't be using the art verbatim.
The game might make some money
I don't need to use names, since it is not really necessary, but there is no problem attributing the character trademark holder
I am not going to hold anyone responsible for their answers, you don't need to say "I am not a lawyer" I know a lawyer will probably give me the best answer, but so will probably do indie game developers who used something similar in their game. This is what I am looking for.
The examples given are not real. Just analogy.


texts: How does one write a wrapper for a game server?

texts:
From what I gathered, wrappers mimic the game server in question, receiving packets from client and sending them to the server (and vice versa). It acts like a bridge between the client and server, allowing data to flow and modifying/reading it as it travels through it.

Am I right in how wrappers work? What is the general gist of them? How would one go about writing one?

I plan to write one for Starbound in Java, using https://github.com/StarryPy/StarryPy as a reference to the packets.


texts:
I'm developing an android app and want to make move the background to the right.
The problem that I have is if it moves it does not repeat the background.
I appreciate every suggestion. Thanks.

The code:

public class Background
{
    private Bitmap bmp = null;
    private int newWidth = 0;
    private int newHeight = 0;
    private Bitmap bmpScaled = null;
    private int move = 0;
    private float scale = 0;
    private GameView gameView = null;

    public Background(GameView gameView, Bitmap bmp, int x, int y)
    {
        this.gameView = gameView;
        this.bmp = bmp;
        scale = (float) bmp.getHeight() / (float) gameView.getHeight();
        newWidth = Math.round(bmp.getWidth() / scale);
        newHeight = Math.round(bmp.getHeight() / scale);
        bmpScaled = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true);
    }

    private void start()
    {
        move++;
    }

    private void update()
    {
        start();
    }

    public void onDraw(Canvas canvas)
    {
        update();
        canvas.drawBitmap(bmpScaled, move, 0, null);
    }
}


texts:
I have to rotate an object, using iTween, or any other animation software. I am creating a betting game, in Unity 5, which I have to manage at run time. I have been using iTween path, but the object only follows the path, and does not rotate along the path or follow the direction of the circular path.

I tried rotating the object using its transform, but when I changed the velocity of the object, the rotation angle would also change. I had to skip it and use iTween, but this object does not follow the path, as I also used orienttopath in iTween script. It's not working properly.

How do I make an object run along with the the rectangular circle shaped path using iTween?


texts: How to make script awake again after sleep?

texts:
I disabled gamecontroller for 15.9 seconds and controller not awake again.It's for cutscene cam before the race start.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// Move and rotation camera controller
/// </summary>

public class CameraController :Singleton<CameraController>
{

    [SerializeField] List<CameraPreset> CamerasPreset = new List<CameraPreset>();   //Camera presets
    [SerializeField] CarController OverrideCar;
    private GameObject cam;
    int ActivePresetIndex = -1;
    public CameraPreset ActivePreset { get; private set; }

    CarController TargetCar { get { return OverrideCar?? GameController.PlayerCar; } }
    GameController GameController { get { return GameController.Instance; } }

    float SqrMinDistance;
    int CurrentFrame = 0;

    //The target point is calculated from velocity of car.
    Vector3 m_TargetPoint;
    Vector3 TargetPoint
    {
        get
        {
            if (CurrentFrame != Time.frameCount)
            {
                if (!OverrideCar && GameController == null || TargetCar == null)
                {
                    return transform.position;
                }
                m_TargetPoint = TargetCar.RB.velocity * ActivePreset.VelocityMultiplier;
                m_TargetPoint += TargetCar.transform.position;

                CurrentFrame = Time.frameCount;
            }
            return m_TargetPoint;
        }
    }

    protected override void AwakeSingleton ()
    {
        CamerasPreset.ForEach (c => c.CameraHolder.SetActive (false));

        ActivePresetIndex = GameOptions.ActiveCameraIndex;
        UpdateActiveCamera ();
    }

    private IEnumerator Start ()
    {
        cam = GameObject.FindGameObjectWithTag("cam");
        ActivePreset.EnableRotation = false;
        GameController.SetActive(false);
        yield return new WaitForSeconds (15.9f);
        GameController.SetActive(true);
        cam.SetActive(false);
        transform.position = TargetPoint;
        ActivePreset.CameraHolder.rotation = TargetCar.transform.rotation;
        ActivePreset.EnableRotation = true;

    }


texts:
Working on a 2D game with SDL2, for now on Window, but I'd like to dream and imagine that if I finish it, I could run it on other platforms that SDL2 games can target. A core part of which is GGPO based lockstep netplay. So, I want to fix my framerate (to 60fps).
On Windows, should I use VSync, but then somehow override/ignore it if the refresh rate of the monitor is not 60Hz? Or not use Vsync at all, and handle the fixed frame rate manually in all cases?
It seems in this case, various platform specific hoops need to be jumped through, as SDL_Delay (= Windows Sleep()) is nowhere near accurate enough. Seems I would need to dive out of platform independnce a bit to handle this?


texts: How do I scale room transition surfaces to fit mobile display?

texts:
I followed a tutorial on how to add a left swipe room transition, which works very well. My problem is that it won't scale to my Android display. I know that it's being drawn to the GUI layer and I've tried resizing the GUI to the display width and height but I didn't see any changes. It's a really nice effect that I want to get working for my game.

Create Event:

currentframe = 0
maxframes = 45

persistent = true; // when changing room keep this object alive

// copy the old room so we can display it on the second room
sur_oldroom = surface_create(room_width,room_height);
surface_copy(sur_oldroom,0,0,application_surface);

// We have recorded what the old room looks like so we can instantly go to the next room.
room_goto(rm_game);

Destroy Event:

surface_free(sur_newroom)
surface_free(sur_oldroom)

Step Event:

currentframe++

if (currentframe > maxframes) {
    instance_destroy() // The transition has finished so destroy it
}

// We are now on the second room so record that room.
if (currentframe == 2) {
    sur_newroom = surface_create(room_width,room_height);
    surface_copy(sur_newroom,0,0,application_surface);
}

Draw GUI Event:

if (currentframe > 1) {

    // convert the number of frames that have passed into a number between 0 and the room width
    var slideamount = EaseOutQuad(currentframe,0,room_width,maxframes)

    if (surface_exists(sur_oldroom)) {
        draw_surface(sur_oldroom,-slideamount,0)
    }

    if (surface_exists(sur_newroom)) {
        draw_surface(sur_newroom,room_width-slideamount,0)
    }
}

/// I do this to hide the flicker where the next room pops up for 1 frame
if (currentframe == 1) {
    if (surface_exists(sur_oldroom)) {
        draw_surface(sur_oldroom,0,0)
    }
}

I'm using Game Maker Studio 1.4.


texts: bullet raycast vehicle - understanding coordinate system

texts:
Bullet world space coordinate system is the same as opengl world coordinate system. I have noticed that raycast vehicle has the following function:

virtual void btRaycastVehicle::setCoordinateSystem(int rightIndex,
                                                   int upIndex,
                                                   int forwardIndex)

How does that function work ?

By default raycast vehicle has the following parametets:

forward vector: [0, 1, 0]
forward axis: 1
right axis: 0
up axis: 2

Does it mean that y axis is swapped with z axis ?

After calling:

raycastVehicle.setCoordinateSystem(0,1,2);

I get the following parameters:

forward vector: [0, 0, 1]
forward axis: 2
right axis: 0
up axis: 1

which makes more sense to me but I'm still confused why a default setup is other (not compatible with world coordinate system) and how to interpret it.


texts: Devices or Smartphones That Can Run and Displayed Images Properly While Power of 2 Code is Disabled

texts: Before making game apps, I want to have any certain smartphone device brands that runs on OpenGL. I have to make a code for images that doesn't need to required power of 2 images so that I can resize the images independently from the start. However, some images appeared in white instead of the appearance that I expected like the old model phone T-Mobile on Android 1.6 for example after I disabled the power of 2 code. The only device I've known that worked and displayed image sprites properly is the Google Nexus 7. Can you tell me either other phone models that can display images without the need of power of 2 and will not display white images instead? Please give me an example at least. Thank you.


texts: Unity:How to realize a modal message box?

texts:
I'm developing a simple "modal" MessageBox.

This is the code inside Message Box panel:

public void Show(string _title , string _message, bool _showYesButton, bool _showNoButton, bool _showCancelButton) {
    this.gameObject.SetActive (true);
    Title.text = _title;
    Message.text = _message;
    btnYes.SetActive (_showYesButton);
    btnNo.SetActive (_showNoButton);
    btnCancel.SetActive (_showCancelButton);

}

And here how I call it outside:

MyMessageBoxScript _script = MyMsgBoxGameObject.GetComponent<MyMessageBoxScript >();
_script.Show("Hey..","Are you sure you want to overwrite this save ?",true,true,false);

Ok.. the problem is that I can't do a "modal" window, like in .NET version, returning what user pressed.

Something like:

buttonPressed = _script.Show("Hey.:", "Are you sure...");

So, searching with Google someone use this Way :

_script.Show(CallBackFunction; "Hey..","Are you sure you want to overwrite this save ?",true,true,false);

and

void CallBackFunction () {
...
}

But I can't understand how it works: How to pass CallBackFunction as parameter and how to execute (after clicking: yes,no or cancel) ?

Thanks


texts:
Newbie question, and sorry for my English. Suppose that we create a lot of GL_ARRAY_BUFFER buffers, fill them with some data. But only few of them we link with shader variables. During glDraw..., what happens with other non-linked buffers? Do they go to the pipeline as well as linked buffers?

I hear but can misunderstood, that all buffers linked to the current VAO will go to the pipeline
in any case, if they are involved in the shader or not. I hope this is wrong.


texts: What do I need to do to my slope collision detection to prevent the player from passing through my collision?

texts:
I've recently implemented slope collision detection for my project. The issue I'm having is that the character occasionally passes through the line.

This usually occurs when the characters MoveAcceleration is increased from 5000 to 8000 via a game mechanic. I was wondering if there is a way to make the line collision more reliable without reducing the MoveAcceleration variable ?

This is how the characters position is calculated

velocity.X += movement * MoveAcceleration * elapsed;
Position += velocity * elapsed;

This is how the slopeCollision is handled

private void HandleSlopeCollisions(GameTime gameTime)
        {
            isOnSlope = false;

            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

            if (velocity.Y >= 0)
            {
                if (attachedPath != null)
                {
                    isOnSlope = true;

                    position.Y = attachedPath.InterpolateY(position.X);
                    velocity.Y = 0;

                    if (position.X < attachedPath.MinimumX || position.X > attachedPath.MaximumX)
                    {
                        attachedPath = null;
                    }
                }
                else
                {
                    Vector2 footPosition = position;
                    Vector2 expectedFootPosition = footPosition + velocity * elapsed;

                    CollisionPath landablePath = null;
                    float landablePosition = float.MaxValue;

                    foreach (CollisionPath path in collisionPaths)
                    {
                        if (expectedFootPosition.X >= path.MinimumX && expectedFootPosition.X <= path.MaximumX)
                        {
                            float pathOldY = path.InterpolateY(footPosition.X);
                            float pathNewY = path.InterpolateY(expectedFootPosition.X);

                            if (footPosition.Y <= pathOldY && expectedFootPosition.Y >= pathNewY && pathNewY < landablePosition)
                            {
                                isOnSlope = true;
                                landablePath = path;
                                landablePosition = pathNewY;
                            }
                        }
                    }

                    if (landablePath != null)
                    {
                        isOnSlope = true;

                        velocity.Y = 0;
                        footPosition.Y = landablePosition;
                        attachedPath = landablePath;

                        position.Y = footPosition.Y;
                    }
                }
            }
            else
            {
                attachedPath = null;
            }
        }


texts: Creating a 3d level from real world room

texts:
I'm doing a project simulating autonomous drone flights inside buildings and I was asked to provide a level which is modeled after one of the floors in our faculty building.
I was given a pdf which contains 2d plans made with autocad 2014 and has layers.
Unfortunately I don't have any knowledge on how to use those plans or read them.
Is there some sort of way to model a real let's say corridor into unreal engine?
preferably using photos or something like that but every method is fine as long as it works.

Thanks


texts:
I'm looking for matchmaking algorithm for a 1 vs 1 online game. Players must not be matched by their skill level, but instead by some specific filters set by the players.

Each player sends a request that specifies some set of parameters (generally, 2-4 parameters). If some parameter is specified, the player can be matched only with those who had sent this parameter with exactly the same value or those who haven't specified the parameter at all.

I need this algorithm to be thread-safe and preferably fast. It would be great if it worked with 3-4 or even more parameters, but even one is alright (in my case, it's a game bet). Also, I'd appreciate ideas on how to implement or improve this algorithm on my server platform - ASP.NET.

One more problem I'm facing is that match finding can't be executed right after the user sends request, because if another user sends a request before a previous matching is finished, they won't be matched even if they possibly could. So it seems that match finding should be started on schedule. I need help on how to optimize it and how to choose time interval for starting new match finding.

P.S. I've also posted this question on stackoverflow


texts:
I'm working on porting a game from PC to Xbox 360.

When I want to create a level I read a .txt file that I store in my content
I read the whole file as a string using this method

File.ReadAllText(fi.FullName);

Where I'm passing in the full path to that file.

Later on in my code I parse that string to create whatever level I need.

When I try to deploy my game onto the Xbox I usually get an error stating

'System.IO.File' does not contain a definition for 'ReadAllText'

I was wondering if there was a simple way to read the text in a .txt file when I deploy onto the Xbox 360


texts: GPU particle system using vertex texture fetch in Direct3D9

texts:
I've been reading up on particle systems amongst other stuff and one interesting approach uses rendertargets to store a particle's position, velocity, lifetime, etc. A pretty neat summary is given here, for example.

However, I'm wondering how to effectively use such a system? How would you create new particles, upload them to the GPU and how'd you determine what particles to draw? I mean, if you've got a 512x512 rendertarget storing particles, would you really just send a vertexbuffer with 262144 quads to the GPU and let the shader figure out which particles to draw and which to ignore?

Right now this sounds like a good idea for those bigger, continuous particle effects like weather or something... particle systems, which don't change often, can run for a while or where particle generation. I don't really see how they'd be performant enough to power dynamic one-off effects like explosions or something, because uploading new particles would basically require locking the rendertarget(s) and manipulating its (their) pixels, right?


texts: moving box2d bodies in an arc or curved path

texts: How can I make a b2Body move in a arc-like or curved path? I have heard about cocos2d Bezier curve function (ccBezier) but this is for moving cocos2d sprites. Or can it be modified to move box2d bodies? Any help is appreciated. Thank you.


texts: Getting input from just one Axis at a time

texts: I'm trying to make a CharacterController2D Script for a simple 2D TopDown game, but i was wondering, what would be the best way to disable 2-axis movement? just allowing one direction at a time (Maybe similar to the old Pokemon games)


texts:
I'm new to game dev and using SFML. I need to use lots of sprites at the same time, so I will probably need sprite batching.

I know that sprite batching is used to draw multiple sprites with a single drawcall, but I have no idea on how it works or how to do it.

How does sprite batching work? (An SFML example would be appreciated.)


texts: Moving a Polygon based on Camera position

texts:
I am in the process of implementing TMX Maps (made in Tiled) for my game. In Tiled, I can create polygons, which leaves a  tag, containing the points.

Loading in these points to a Polygon (java.awt.Polygon) isn't a problem. When all points are loaded into a Polygon (which also had an x and y position, which is the origin of the Polygon), and I draw it, it looks perfect.

However, when I was to move it the troubles started. Every tick, I want to set the position of this Polygon according to the x, y position (the origin), and the Camera position, so that when I draw it, it will draw on position.x - Camera.x and position.y - Camera.y. So every tick, I want to set the (x, y) position of the Polygon equal to position - Camera.position.

I thought that this would be as simple as calling the translate(position.x - Camera.x, position.y - Camera.y) function in the polygon every tick, but the problem here is that this function adds a delta, instead of setting the position. Because of this, the Polygon won't stay still when the Camera is still, because it adds this delta, so the Polygon just moves off the screen.

So, the question is really how to set the position of a polygon every tick, instead of adding a delta to it every tick?


texts: Why do I get this crash when dealing with SDL_Events?

texts:
I do not know if this is the best way to handle these SDL_Events, but I am attempting to create a very abstract and generic code that will update my game object. I have a Scene which in my case is just a map from a string to a game object that has special functions to Add(string key, gameobject value), Remove(string key), Render(), and Update(SDL_Event& event). I think this last method is the problem.
Scene.cpp
void Scene::Update(SDL_Event& ev)
{
    for (std::map<std::string, GameObject&>::iterator it = x_ObjectDictionary.begin(); it != x_ObjectDictionary.end(); ++it)
    {
        it->second.Update(ev); //where the game crashes
    }
}

void Scene::Render()
{
    for (std::map<std::string, GameObject&>::iterator it = x_ObjectDictionary.begin(); it != x_ObjectDictionary.end(); ++it)
    {
        it->second.Render();
    }
}

void Scene::Add(const std::string& key, GameObject& value)
{
    x_ObjectDictionary.insert(std::pair<std::string, GameObject&>(key, value));
}

GameObject& Scene::Get(const std::string& key)
{
    std::map<std::string, GameObject&>::const_iterator iterator = x_ObjectDictionary.find(key);
    if (iterator == x_ObjectDictionary.end()) return GameObject();
    return iterator->second;
}

GameObject& Scene::Remove(const std::string& key)
{
    GameObject removed;
    std::map<std::string, GameObject&>::const_iterator iterator = x_ObjectDictionary.find(key);
    if (iterator == x_ObjectDictionary.end()) return GameObject();
    removed = iterator->second;
    x_ObjectDictionary.erase(iterator);
    return removed;
}

This iterates my map and updates all of the GameObjects. My game object update method is defined like this in the header file:
GameObject.h
class GameObject
{
public:
    GameObject() {}
    virtual ~GameObject() {}

    virtual void Update(SDL_Event& ev){}

    virtual void Render(){}

    virtual void Destroy(){}

};

Now, I created a scene. This Scene is called Splash and extends Scene properly. I created it like so
void Splash::CreateScene()
{
    Add("something", GameObject());
}

Every time I execute/debug my project now, my program "breaks" on the it->second.Update(ev); line and inside the console after I stop "debugging" the message says something along the lines of Exception thrown at 0x00007FF7CB457024 in XXXXXX.exe: 0xC0000005: Access violation reading location 0x00001CFA67BC13F9.
Am I going about this completely incorrectly? Or did I just make a stupid mistake?


texts:
How to open URL in new tab for WebGL?

Tried Application.OpenURL("url"). But it's opens a tab in same window

Thanks


texts: How can I minimise memory thrashing when doing vector math in C# or C++?

texts:
I'm doing a lot of 3D math in my game engine loop using typical classes like Vector3D, Matrix4x4, Plane3D, etc. Currently every operation causes a new object to be created for the result value. The number of new objects created causes a stutter whenever the GC kicks in.

In this simple vector operation, 2 new Vector3D objects are created, one at the divide and one at the multiply operator.

// C#
result = (v / len1) * len2; // where len* is a `double`

I happen to know some C++, so an optimized version would create a disposable object on the stack and pass that to the individual ops, thereby automatically disposing off the temporary objects at the end of the function (also avoiding the GC altogether), something like this:

// C++
Vector3D result;
v.divideBy(len1, &result);
result.multiplyBy(len2, &result);

But as you can see its cumbersome and unreadable. So what are commonly used memory optimization strategies used by pro C++ gamedevs to optimize vector math? I'm looking for general platform agnostic solutions that can be implemented in C# and other high-level languages, although C++ memory tricks are also appreciated.


texts: Why does my sprite animation sometimes runs faster?

texts:
I don't know why each time I call the Update_Animation function, my sprite animation runs faster. Is it caused by gameTime? How to fix it?

Here's the relevant code:

class Character
{
    // <SNIP>

    public void Update_Animation(Point sheetSize, TimeSpan frameInterval, GameTime gameTime)
    {
        if (nextFrame >= frameInterval)
        {
            currentFrame.X++;

            if (currentFrame.X >= sheetSize.X)
            {
                currentFrame.X = 0;
                currentFrame.Y++;
            }

            if (currentFrame.Y >= sheetSize.Y)
                currentFrame.Y = 0;

            nextFrame = TimeSpan.Zero;
        }
        else
        {
            nextFrame += gameTime.ElapsedGameTime;
        }
    }

    // <SNIP>

    private void UpdateMovement(KeyboardState aCurrentKeyboardState, GameTime gameTime)
    {
        if (mCurrentState == State.Walking)
        {
            action = "stand";
            Update_Animation(sheetSize_Stand, frameInterval_Stand, gameTime);

            mSpeed = Vector2.Zero;
            mDirection = Vector2.Zero;

            if (aCurrentKeyboardState.IsKeyDown(Keys.Left) && !aCurrentKeyboardState.IsKeyDown(Keys.Right))
            {
                action = "run";
                effect = SpriteEffects.None;

                mSpeed.X = CHARACTER_SPEED;
                mDirection.X = MOVE_LEFT;

                Update_Animation(sheetSize_Run, frameInterval_Run, gameTime);
            }
            else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) && !aCurrentKeyboardState.IsKeyDown(Keys.Left))
            {
                action = "run";
                effect = SpriteEffects.FlipHorizontally;

                mSpeed.X = CHARACTER_SPEED;
                mDirection.X = MOVE_RIGHT;

                Update_Animation(sheetSize_Run, frameInterval_Run, gameTime);
            }

            if (aCurrentKeyboardState.IsKeyDown(Keys.Z) && mPreviousKeyboardState.IsKeyUp(Keys.Z))
            {
                mCurrentState = State.Hitting;
            }
        }

        if (mCurrentState == State.Hitting)
        {
            action = "hit";

            Update_Animation(sheetSize_Hit, frameInterval_Hit, gameTime);
            mCurrentState = State.Walking;
        }
    }

    // <SNIP>
}


texts: How to store generic data in game database?

texts:
To clarify things a bit:
I want to create a kind of database for my game, that simply is a class that stores all game-state information like object positions, player scores, etc.

The main problem I am facing, that the whole game is to be scripted, to the level of the (lua)script controlling what members should the database have.

The reason for this is that I want to create a game that gives modders complete access to the game via lua scripting.(its one of the core features)
For this to be viable I need to be able to add custom elements to the
database.

I want to avoid using a 'real' database and roll my own solution.

For example I want to be able to do the following in the script file:

-- In function init...
Engine:AddStateEntry( "Score", TYPE_INT )

-- In function update...
Engine:SetStateEntry( "Score", 12 )

My engine would then synchronize data between players and render things accordingly.

How could I:

Efficiently store arbitrary types of data?(including arrays)
Set up custom interpolation functions

Efficiency and ease of use are my main priorities.(I dont care if the implementation is complex)

TL;DR: How to efficiently store arbitrary data that is defined by lua scripts and stored on the c++ side?


texts: How can obtain the relative orientation between two quaternions?

texts: How do I obtain the relative orientation given two orientations (represented by quaternions q0 and q1)?


texts: Instantiate a prefab on button press and keep it dragged

texts:
So far the gameObject is created, but I need to click on the object a second time, in order to start the Drag event. Here's the script where I use the button to spawn a prefab

public void SpawnPrefab(Transform prefab)
{
    clicked = false;
    Vector3 mousePosition, targetPosition;
    mousePosition = Input.mousePosition;
    targetPosition=Camera.main.ScreenToWorldPoint(new Vector3(mousePosition.x,mousePosition.y,distance));
    prefab.position=targetPosition;
    if(isAlreadyClicked == false)
    {
        Instantiate(prefab, prefab.transform.position, prefab.transform.rotation);
        isAlreadyClicked = true;
        Debug.Log(clicked);
    }
}

I call this Drag event from another script inside the spawned gameObject though

void OnMouseDrag()
{
    cursor.setGrab();
    if(this.transform.parent == null || this.transform.parent != null)
    {
        //drag the component
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
        transform.position = curPosition;
        if(this.gameObject.CompareTag("Component"))
        {
            mainCanvas.transform.GetChild(1).gameObject.transform.GetChild(0).gameObject.transform.GetChild(4).gameObject.SetActive(false);
        }
        if(this.gameObject.CompareTag("NewComponent"))
        {
            mainCanvas.transform.GetChild(1).gameObject.transform.GetChild(0).gameObject.transform.GetChild(4).gameObject.SetActive(true);
        }
    }
}

Hope it's clear enough. Any ideas?
Thanks in advance!

EDIT:
So I found out that the SpawnPrefab() only works when mouse button is released. Is there any way I can make the buttons work on mouse pressed?


texts: Java: See if Mouse is hovering/clicking Sprite

texts:
The game I am developing is in which you defend the Cell from the Viruses, and I need the sprites to have a MouseListener for when the mouse clicks on that sprite, it will get destroyed, and I cannot figure out how to get the location of the mouse and apply it to the sprite.

Basically, I need to grab the location of the mouse and the sprite, and when the user clicks it will reset the sprite.

I have tried to do debugging with this, so like if the mouse hovers the location of the sprite it will print a message "Hovering" but it just doesn't work.

For my update method, I added:

if(MouseInfo.getPointerInfo().getLocation() == this.getLocation()) System.out.println("SAME LOCATION");

I even got it to print out the location of the sprite and the mouse, and I aligned them both to 0,0 and it still didn't work.

CONCLUSION:
How do I check if the location of the mouse is the same as a sprite, and then print out a message to the console?


texts:
I have problem in very simple console app, code looks like this.

int x - player moving and changing axis "x" and I want make full history of moving via array. See code(only example) below...

Thank you for your help and answer

  int round = 0;

  while(infinity){

  int[] PosXSave = new int[round + 1]; //theoretically infinity size of arrray.

  PosXSave[round] = x; //every round i want save current value of x, but
                       //only last save have propertly value and rest are
                       //zero or other number

  round++

  }


texts: Unwanted roll when rotating camera with pitch and yaw

texts:
I have a quaternion class implementation, and when I apply this class to my objects all gone right (rotations), but I have a lot of troubles with the camera. I've been searching a lot trying to solved my problem but nothing works.

When I do a yaw and then a pitch rotation (or vice versa) a roll rotation is introduced. If I do the Y rotation around local axis the undesired roll disappears, but looking up and down will not work properly after a roll rotation (so I need to apply the Y rotation around the global axis).

Like I said, applying the quaternion to the object works fine, so maybe the problem is when passing the rotation data to opengl. I do this like that:

 mainCamera.getAnglesAxis(angle, vAngle);
 glRotatef(-angle, vAngle.getX(), vAngle.getY(), vAngle.getZ());
 glTranslatef(-mainCamera.getX(), -mainCamera.getY(), -mainCamera.getZ());

 glTranslatef(obj.getX(),obj.getY(),obj.getZ());
 cube.getAnglesAxis(angle, vAngle);
 glRotatef(angle, vAngle.getX(), vAngle.getY(), vAngle.getZ());

 drawCube();

I'm doing it right?


texts:
I have a game in top-down view, with little ants who can walk up/down, left/right and diagonal (and all direction with Joystick).

My little player can move, but I can't rotate it properly...
See what i mean in the youtube video of 7 seconds i made:
https://www.youtube.com/watch?v=1mGMPhJ-u4s&feature=youtu.be

See the code:

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

public class Move : MonoBehaviour
{
public float lookSpeed = 10;
private Vector3 curLoc;
private Vector3 prevLoc;

void Update()
{
    InputListen();
    transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(transform.position - prevLoc), Time.fixedDeltaTime * lookSpeed);
}

private void InputListen()
{
    prevLoc = curLoc;
    curLoc = transform.position;

    if (Input.GetKey(KeyCode.S))
        curLoc.y -= 1 * Time.fixedDeltaTime;
    if (Input.GetKey(KeyCode.Z))
        curLoc.y += 1 * Time.fixedDeltaTime;
    if (Input.GetKey(KeyCode.D))
        curLoc.x += 1 * Time.fixedDeltaTime;
    if (Input.GetKey(KeyCode.Q))
        curLoc.x -= 1 * Time.fixedDeltaTime;

    transform.position = curLoc;

}

}

I have tried a LOT of ways, but nothing worked...
I have also an animator with a stylesheet (ants walking):

thanks !

EDIT: i try another aproch for moving:

transform.Translate(Input.GetAxis("Horizontal") * speed * Time.deltaTime, Input.GetAxis("Vertical") * speed * Time.deltaTime, 0);

and for rotating:

transform.up = gameObject.GetComponent<Rigidbody>().velocity;

It move well.. but it doen't rotate when i move... BUT when i collide with another object, my player get some velocity, and then rotate correctly without touching any input, see in the video:
https://www.youtube.com/watch?v=AS3agqJbVtI&feature=youtu.be


texts: Does Debug.LogAssert gets deleted in Unity once I build the game?

texts:
Does Debug.LogAssert(expression) gets deleted in Unity once I build the game?

I was not able to find it here. I feel like it should get deleted, but still I can not assure myself in it (no reliable source was found by me).

So, I would be grateful for the source provided which would assure me in it or point me out, that it is not the case.


texts: I haven't posted here before but I came across a problem, when I save a map in Hammer as .bsp it ends up being over 10x bigger than all of the source files put together. I found the source for one map rp_downtown_v2.bsp, which the map is 2mb but when I used the source and compiled it in hammer its 40MB? Why would this be? Any further help will aid thanks!


texts: How can I achieve a 3D-like effect with spritebatch's rotation and scale parameters

texts:
I'm working on a 2d game with a top-down perspective similar to Secret of Mana and the 2D Final Fantasy games, with one big difference being that it's an action rpg using a 3-dimensional physics engine.

I'm trying to draw an aimer graphic (basically an arrow) at my characters' feet when they're aiming a ranged weapon.  At first I just converted the character's aim vector to radians and passed that into spritebatch, but there was a problem.  The position of every object in my world is scaled for perspective when it's drawn to the screen.  So if the physics engine coordinates are (1, 0, 1), the screen coords are actually (1, .707) -- the Y and Z axis are scaled by a perspective factor of .707 and then added together to get the screen coordinates.

This meant that the direction the aimer graphic pointed (thanks to its rotation value passed into spritebatch) didn't match up with the direction the projectile actually traveled over time.  Things looked fine when the characters fired left, right, up, or down, but if you fired on a diagonal the perspective of the physics engine didn't match with the simplistic way I was converting the character's aim direction to a screen rotation.

Ok, fast forward to now:  I've got the aimer's rotation matched up with the path the projectile will actually take, which I'm doing by decomposing a transform matrix which I build from two rotation matrices (one to represent the aimer's rotation, and one to represent the camera's 45 degree rotation on the x axis).  My question is, is there a way to get not just rotation from a series of matrix transformations, but to also get a Vector2 scale which would give the aimer the appearance of being a 3d object, being warped by perspective?  Orthographic perspective is what I'm going for, I think.  So, the aimer arrow would get longer when facing sideways, and shorter when facing north and south because of the perspective.  At the same time, it would get wider when facing north and south, and less wide when facing right or left.

I'd like to avoid actually drawing the aimer texture in 3d because I'm still using spritebatch's layerdepth parameter at this point in my project, and I don't want to have to figure out how to draw a 3d object within the depth sorting system I already have.

I can provide code and more details if this is too vague as a question...  This is my first post on stack exchange.  Thanks a lot for reading!

Note: (I think) I realize it can't be a technically correct 3D perspective, because the spritebatch's vector2 scaling argument doesn't allow for an object to be skewed the way it actually should be.  What I'm really interested in is, is there a good way to fake the effect,
or should I just drop it and not scale at all?

Edit to clarify without the help of a picture (apparently I can't post them yet):

I want the aimer arrow to look like it has been painted on the ground at the character's feet, so it should appear to be drawn on the ground plane (in my case the XZ plane) which should be tilted at a 45 degree angle (around the X axis) from the viewing perspective.

Alex


texts:
Recently I'm trying to implement a render queue sorting system, i.e., ordering my renderable objects in an array in such a way that the overhead of OpenGL state changes are minumum. After some googling, the most ideal one (to me) is to generate an integer key value for each renderable object, and the sorting is based on that value. Once done sorting, objects that have similar rendering states (same shader, texture, distance, etc.) will be close to each other, so we can just loop through the object array and submit the draw calls for rendering.

Here's a detailed explanation: Order your graphics draw calls around!

My problem is, how do I loop through the renderable object's array to submit their draw calls for actual rendering? Do I need to keep track of the current OpenGL states manually?

What have come to my mind is:

(for each renderable object)
{
    if(objects[i].getShader() != m_currentShader)
    {
        m_currentShader = objects[i].getShader();
        m_currentShader.bind();
    }

    if(objects[i].getTexture() != m_currentTexture)
    {
        m_currentTexture = objects[i].getTexture();
        m_currentTexture.bind();
    }

    // ... and so on

    object[i].getMesh().draw();
}

Seems not so performance-friendly to me, but I can't find any further explanation on how to submit the actual draw calls form the object's array either on the article I've provided or other sites I can find. Perhaps there's something I have missed?


texts: 3D terrain generation: geological slices and noise function

texts:
Everyone knows how to use Perlin noise to generate the surface of a 3D world. You may use one or several octaves to generate more detail.

It is also known how to use 3D Perlin noise to generate, to put it simply, a 3D world (including what's below the surface) with "holes" in it.

The advantage of Perlin noise is that you don't need to know the entire world to compute one specific point in the world. Since it's a function (or a sum of them), all you need to know is the input seed and the function, and it gives you the output wherever you want. Each point does not depend on its neighbour.

Now I'm wondering how to generate a world which terrain is a mix of different types of materials. You may call them geological layers, even though there's not necessarily slices.

I'm having a hard time picturing how Perlin noise (or any function suitable for this) would apply to this specific goal.

Generators commonly generate the world first and then add individual items (caves, deposits of precious rocks, etc.), but that's not what I want because it would lose the benefit of the function thing. Applying post-processing to the terrain makes it impossible to compute one specific point or range, with a pseudo-infinite level of detail, like a function does.

what's your take on this? (Stick to the mathematical idea, no need for implementation)


texts:
It has been mentioned in the "Application Framework" section of the LibGDX online wiki that accessing the 6 modules (application, audio, files, graphics, input & net) in a static way is not the best practice.

The exact wording written int the wiki is below:

  The modules described earlier can be accessed via static fields of the
  Gdx class. This is essentially a set of global variables that allows
  easy access to any module of libgdx. While generally viewed as very
  bad coding practice, we decided on using this mechanism to ease the
  pain usually associated with passing around references to things that
  are used often in all kinds of places within the code base.

But almost all LibGDX applications that I have seen, modules information is fetched in a static way.
If static way is not the right way then how to access these modules?


texts:
I'm having trouble with the logic for this problem. I've got a grid of modules. Each module may take 1 or more cells on the grid, and each cell of a module may have 1 or more connectors. The connectors are represented by an enum (or int). Adjacent modules may only be placed if they have matching connectors.

So, for example:

-Module A in position (0, 1) has a down (3) connector.
-Module B in position (0, 2) has an up (1) connector.

This is a valid configuration.

-Module A in position (0, 1) has a down (3) connector.
-Module B in position (0, 2) has an right (2) connector.

This configuration is invalid.

I've attached an image below for clarity:


texts: Storing rigid body collision shapes in local or world coordinates

texts:
I'm writing the beginnings of a lightweight 2d rigid body engine (in javascript, as a hobby project), and i'm debating whether to store collision shapes in local or in (updated as needed) world coordinates.

Most physics engines out there (e.g. box2d, bullet, dyn4j, chipmunk, PhysicsJS) and indeed most treatments of the subject store the collision shape(s) of a rigid body in local coordinates. Since the body is rigid, these local coordinates never have to be updated.

However, when performing collision detection, the shapes have to be transformed into world coordinates (or into the local coordinates of another body) - and even if most collisions can be discarded with some kind of broadphase culling, shapes that have moved still have to be transformed when updating bounding boxes/volumes (unless one uses some orientable or rotation invariant bounding box/volume).

In the worst case, in some of the above implementations, the shapes seem to be transformed multiple times each time-step (computing AABBs + multiple collision tests).

Would there not be a possible performance benefit in storing the shapes in world coordinates (and updating them when needed) instead, and why is it that no one seems to use this approach? There is at least a benefit for static bodies.


texts: SDL_Mixer functions Mix_Quit versus Mix_CloseAudio

texts:
Could someone please explain me the differences between the SDL_Mixer functions Mix_Quit and Mix_CloseAudio? I've read the documentation but couldn't really understand it clearly. When to use them and in which row (first Mix_Quit or Mix_CloseAudio?)?

Also, is it ok to use Mix_Quit after using Mix_CloseAudio? The documentation states that you should not call any SDL_Mixer function after Mix_CloseAudio, but it worked when I tested it.


texts: Can SFML load anything other than RGBA8888? (RGBA4444, RGB565, etc.)

texts:
I can't see this mentioned in the documentation. Am I missing something obvious? Or does SFML really give you no option, forcing everything to be loaded as RGBA8888?

Searches on Google and the SFML forums have been unproductive.


texts: Verlet collision with impulse preservation

texts:
I came across this article, recently, that presented a technique for impulse preservation with position-based verlet integration. What was interesting was that the integration steps are seemingly done differently from typical position-based verlet schemes, as well as the ordering of the integration step and collision resolutions.

Specifically, the typical verlet position integrator is:

newPosition = 2 * position - oldPosition + acceleration * timeStepSquared
oldPosition = position
position = newPosition
DoConstraints()

Where the article has:

position += acceleration * timeStepSquared
DoConstraints()
newPosition = position * 2 - oldPosition
oldPosition = position
position = newPosition

Which ignoring constraints for a moment works out to be:

newPosition = 2*position - oldPosition + 2*acceleration*timeStepSquared
oldPosition = position + acceleration*timeStepSquared
position = newPosition

Which is different in a term of acceleration * timeStepSquared.  I haven't quite convinced myself that those terms cancel out through the iteration, as the prior acceleration * timeStepSquared term may not be the same as the current one.

Could someone explain the reasoning for this, and if indeed it makes sense?


texts:
I have a dynamic surface in WebGL, that is animated in vertex shader. I want other objects to interact with this surface (for example, an object riding on dynamic terrain). What's the best way to do this? Should all these calculations be done on CPU? Is there a way to calculate this stuff on GPU?

Basically, what I want is vertex shader with access to other (already transformed) vertices -- that would be perfect.


texts: How to project a vector onto a plane, but not along plane normal?

texts: In 3d space, is there any way to project a vector onto a plane,  but alongside the UP vector (0,1,0) instead of the plane normal? If so, then how do I do that and what is it called?


texts: How do I ensure that perspective and orthographic projection matricies show objects at the same size on the screen?

texts:
I am working on a 3d scene editor and would like to show the scene in orthographic projection. My current problem is that I am not sure how to calculate the orthographic projection matrix such that the objects do not appear at a completely different size on the screen.

I currently have the following 2 functions for calculating the camera projection matrix.

Matrix4.createPerspective = function(fov, aspect, near, far, result) {
    if (typeof result === 'undefined') {
        result = new Matrix4();
    }

    var ymax = near * Math.tan(fov * Math.PI / 360);
    var ymin = - ymax;
    var xmin = ymin * aspect;
    var xmax = ymax * aspect;

    Matrix4.createFrustum(xmin, xmax, ymin, ymax, near, far, /*out*/ result);

    return result;
};

Matrix4.createOrthographic = function(left, right, top, bottom, near, far, result) {
    if (typeof result === 'undefined') {
        result = new Matrix4();
    }

    var re = result.elements;
    var w = right - left;
    var h = top - bottom;
    var p = far - near;

    var x = ( right + left ) / w;
    var y = ( top + bottom ) / h;
    var z = ( far + near ) / p;

    re[0] =2/w;  re[4] = 0;   re[8]  = 0;   re[12] =-x;
    re[1] = 0;   re[5] =2/h;  re[9]  = 0;   re[13] =-y;
    re[2] = 0;   re[6] = 0;   re[10] =-2/p; re[14] =-z;
    re[3] = 0;   re[7] = 0;   re[11] = 0;   re[15] = 1;

    return result;
};

And this is how they are being used:

    updateProjectionMatrix: function(entity) {
        var camera = entity.getComponent('Camera');
        if (camera.isDirty()) {
            camera.aspect = camera.width / camera.height;
            if (camera.isOrthographic()){
                Matrix4.createOrthographic(
                    0,
                    camera.width,
                    0,
                    camera.height,
                    camera.near,
                    camera.far,
            /*out*/ camera._projectionMatrix);
            } else {
                Matrix4.createPerspective(
                    camera.fov,
                    camera.aspect,
                    camera.near,
                    camera.far,
            /*out*/ camera._projectionMatrix);
            }
        }
    },

Here is an example of what I am trying to accomplish inside Blender (F5 toggles between Ortho and Perspective). Note that both cubes appear to be about the same size on the viewports:


texts: Add Rigidbody and MeshCollider at runtime : is it a bad practice?

texts:
Good day.

To simulate an explosion of a vheicle, I decided to do this:

When I need to explode veichle , at runtime, i add rigidibody for every single part of veichle (5-10 part: door, wheel, hood etc), and collider (mesh).
I detach them from parent
I apply an AddExplosionForce to every single part

This cause a big lag in my game, so I'm supposing this is not the efficent way.

The other way could be to add Rigidbody and Collider in my prefab, with Rigidbody.gravity = false, and isKinematic=true, then enabling after explosion, but also this is not good for performance.

Do you have some suggestions to achive my scope, considering that I could have a lot (5-10) enemy veichles at time on my scene ?

Thanks


texts: Drawing an arrow cursor on user dragging in XNA/MonoGame

texts:
I am writing a touch enabled game in MonoGame (XNA-like API) and would like to display a an arrow 'cursor' as user is making a drag gesture from point A to point B.
I am not sure on how to correctly approach this problem. It seems that its best to just draw a sprite from A to B and scale it as required. This would however mean it gets stretched as user continues dragging gesture in one direction.
Or maybe its better to dynamically render the arrow so it looks better?


texts: How to know when all 2d rigid bodies have stopped in unity3d?

texts: Is there anyway to know if all 2d rigid bodies in untiy 3d phisics world have stopped?


texts: How to convert strict limit in position into gradual slow down?

texts:
The player moves a spell object, the spell must stay withing a certain range of the player.  The spell is moved using a physics system and it has mass and velocity.  Currently when the spell goes out of range of the player it's being moved back into range, this has the effect stopping the spell abruptly at the edge.  I want to smooth out this abrupt stop so that it gradually slows down.  I tried to apply an easing function but because the time and distance change every frame I couldn't figure out the formula.

Is there some sort of physics or easing formula I can use to gradually slow down the spell before it gets to the edge of its range, while at the same time guaranteeing that it never leaves the range?

Additional Info:

The spells range is a circle.  I only care about the center of the spell object.  Movement forces are continually being applied to the spell.


texts: If I call glDeleteTextures, will it release memory immediately? And what is the performance? I know that glGenTexture is quite cheap, because it only alocated id, but I have nor found anything about deleting.


texts: How do I make a game object appear on the other side when it leaves the screen?

texts:
I'm doing an assignment for a course and what's required is to include a moving asteroid in the game that starts moving in a random direction and when the asteroid leaves the bottom of the game window it should re-appear at the top of the game window
,so I wrote the script for warping and I applied it to the asteroid and a ship in my game ,then built it to WebGl game. the warping worked fine in the editor for both the ship and the asteroid, while it only worked for the ship in the built game, and I can't figure out what's wrong

this is the script

(ScreenUtils gives the borders of the screen)

float Radius;

void Start () {
    Radius = GetComponent<CircleCollider2D>().radius;
}
void OnBecameInvisible()
{
    // Make the ship wrap
    Vector3 position = transform.position;
    if (position.x - Radius >= ScreenUtils.ScreenRight || position.x + Radius <= ScreenUtils.ScreenLeft)
    {
        position.x *= -1;

    }
    if (position.y -Radius >= ScreenUtils.ScreenTop || position.y + Radius <= ScreenUtils.ScreenBottom)
    {
        position.y *= -1;
    }
    transform.position = position;
}


texts:
Sorry if this question has already an answer somewhere, but I've just started to play with Unity and now I'm stuck. :(

I've tried a few things ( from here , here and here and others ) but none of them work, I'm sure that I do something wrong but I don't know what.

I have this code:

public class SceneManager : MonoBehaviour {

    public Image myButtonImage;
    private Button switchBtn;

    // Use this for initialization
    void Start () {

        switchBtn = GameObject.Find("switchBtn").GetComponent<Button>();
        myButtonImage = Resources.Load<Image>("switchCameraImg");

        switchBtn.image = myButtonImage;
    }
}

and this are my objects:

where cameraSwitchObj is a GameObject and switchBtn is the button itself.

SceneManager is the script attached to MainCamera

I receive this error :

NullReferenceException: Object reference not set to an instance of an object SceneManager.Start ()

for this line : switchBtn.image = myButtonImage; but according to what i read from different posts this is all i must do. What I am missing?


texts: How to start external AS file playing on frame 2 (instead of frame 1)

texts:
I am using actionscript 3 and I have used an external actionscript file (.as) for my game.

I would like the external actionscript file to be played at frame 2 (instead of frame 1, as it is an introductory page of the game) on the timeline.

How do I do that? I have been trying and looking for answers for hours, appreciate if you can help on this. Many thanks in advance!


texts: Collision Detection algorithm using Line Detection

texts: For a 2D physics sandbox I am working on, I need a way of detecting detecting a collision using lines. This sandbox uses a class called Particle, which has a x and a y (stored as a struct called vector2) and a velocity, which also has a x and y. Previously, to find a collision, I tried to detect if the coordinates + the velocity was where another particle's coordinates + velocity was, and then I divided the velocities by the highest velocity, then checked all the velocities incrementally, to prevent tunneling. However, I could not get this to work, and I had suspicions it would be slow when velocities were very large. I now want an algorithm that detects whether two lines (one point is the coordinates, the other is coordinates + velocity) intersect, then put the particles one space before the collision. Since this algorithm is for a physics sandbox, it has to detect any collision, including, for example, if the two lines will collide but are parallel. For simplicity's sake, I won't post the Particle class code, so feel free to create the function using whatever variables you wish (as long as they're self-explanatory)


texts: Find a path centered on the edge between traversable tiles

texts:
I'm trying to implement a pathfinding system in a simple tower defense game I'm working on. I've a 15x8 tilemap where each cell is of size 64x64.
image 1

 A is the start point, B is the end point, the green blob is the bad guy, the brown tiles are the route and the green tiles are the "walls".

So basically I want to auto find a grid-based path from point A to point B for the enemy, similar to this:
image 2

Down below are the scripts I've implemented in the game, should be a bit messy...

Main script

func _astar_search(graph, source, target):
    var q = Heap.new()
    var nodes = {}
    nodes[source] = Vertex.new(source, null, 0)
    q.insert(source, 0)

    while not q.empty():
        var current = q.extract_min()

        if current == target:
            break

        for next in graph.neighbors(nodes[current]):
            if nodes.has(next) == false:
                nodes[next] = Vertex.new(next)

            var new_cost = nodes[current].get_cost() + graph.weight(nodes[current], nodes[next])
            if new_cost < nodes[next].get_cost():
                nodes[next].set_cost(new_cost)
                nodes[next].set_parent(current)

                if q.contains(next) == false:
                    q.insert(next, nodes[next].get_cost() * _heuristic(target, next))

    return nodes

func _find_path(nodes, source, target):
    var path = []
    var current = target

    while current != source:
        path.append(nodes[current])
        current = nodes[current].get_parent()

    path.append(nodes[source])
    path.invert()
    #_dir.invert()
    return path

func _heuristic(a, b):
    return abs(a.x - b.x) + abs(a.y - b.y)

Graph class

func neighbors(vertex):
    var cell = vertex.get_cell()
    var result = PoolVector2Array([
        cell + Vector2.UP,
        cell + Vector2.LEFT,
        cell + Vector2.DOWN,
        cell + Vector2.RIGHT,
    ])

    #if fmod(cell.x + cell.y, 2) == 0:
    #   result.invert()

    result = _filter("_in_bounds", result)
    result = _filter("_walkable", result)
    return result

func _in_bounds(cell):
    return cell.x >= 0 and cell.x < size.x and cell.y >= 0 and cell.y < size.y

func _walkable(cell):
    return obstacles.has(cell) == false

It's not working properly. I need the path to be centralized in between the two "roads" just like the image 2, but what I've now is:

image 3

The blue line is the path generated by the algorithm and the red dots are the same path but centered at tile's position

Do you have any suggestions on how could I center the path?


texts:
I'm working on a particle field system, where the particles can go from a point of the map, to another point of the map, using an angle (with sin and cos).

By now, I can calculate the vector by defining an angle using the cos and sin

float X = sin(DEGREES_TO_RADIANS(45));
float Y = cos(DEGREES_TO_RADIANS(45));

That forms a trajectory, like in this image: (Trajectory in red)

I need the particle to follow that trajectory, to move over that trajectory and arrive to the the vector (X,Y).

How can I translate the object ONLY over the red trajectory?


texts:
I have set my game up so that I can run one instance as host and one instance as client and I see two people in the room. How do I get from that setup to another computer (as client) connecting to mine (as host) without matchmaking.

I understand I will need a static IP, and have set my router up for port forwarding (I tested it with an FTP server application I made). I am specifically asking for what options you select in the Unity NetworkManager to do this.

Here is my current NetworkManager (I erased the last number in my IP so I dont get DDos):


texts: How do I visualize parallax layers in a level editor?

texts:
I'm making a 2D game in Unity, but this would apply to any 2D game engine.

If I implement multiplane parallax with orthographic cameras, it is difficult to lay out the background layer's sprites and know where they will line up with sprites in other layers.

My first instinct was to use multiple cameras, one for each layer, and scale down the movement speed of cameras for background layers. This avoids having to move all background sprites every frame.  The problem is that a layer that moves at half speed will take up half the space of the main layer when viewed in the editor. So it is difficult to know where to place sprites as you're laying out the game. The problem gets exponentially worse as you increase the number of layers.

How do I get around this? I've tried inversely scaling the layers by their intended movement speeds while working with them in the editor. That puts all background sprites in the correct locations relative to the main layer, but they're horribly distorted.

Do I need to just suck it up and constantly switch between the editor and the running game to test the parallax backgrounds?


texts:
I am trying to save player's objects but my loaded result is corrupt and placed in weird shapes like 3D arrows.
Weirdly enough when terrain is saved, the terrain is fine but objects added later cause the problem.
I am using OpenTK for OpenGL.
What I expect:
What I get:

The file seems to contain some repeated parts? Here is a part of the (large) file I end up with:
(0; 0; 0),(0; 0; 0),(0; 0; 1),(0; 1; 0),(1; 0; 0),(0; 0; 2),(0; 2; 0),(2; 0; 0),(0; 0; 0)

Here is my loading code:
void MapLoad(string filelocation)
{
    string[] map_;
    string line = File.ReadAllText(filelocation);//
    map_ = line.Split(new char[] { ',', ';', '(', ')' }, StringSplitOptions.RemoveEmptyEntries);

for (int xj = 0; xj < line.Split(',').Length; xj += 3)
        {
            // Here xj is an index of a X coordinate, xj + 1 is an index of a Y coordinate, xj + 2 is an index of a Z coordinate
//copied pasted for suring answer will work
         block_file.Add(new Vector3(Int32.Parse(map_[xj]), Int32.Parse(map_[xj + 1]), Int32.Parse(map_[xj + 2])));
        }

}

The Vector3 is from OpenTK.
Here is my writing code:
if(key.KeyCode == Keys.F7)
{
    File.WriteAllText("usermap.txt", String.Join(",",block_file));//new char[] { ',', ';', '(', ')'
}