texts: Why does this code not update my object's position?

texts:
I am trying to move the object in my frame in Time.deltaTime. I have not taken care the speed yet  but the problem is, the object is almost at position (0,0) after I have multiplied the x & y axis with Time.deltaTime. I want it to appear randomly on the screen in a given range. The update function is given below:

function Update ()
{

  var x = Random.Range(-4.37,4.34) * Time.deltaTime;

  var y = Random.Range(4.45,-4.66) * Time.deltaTime;

  var velocity = Vector3(x, y, 0);

  transform.position = velocity;

}


texts: How can I Implement KeyListeners/ActionListeners into the JFrame?

texts:
I'll get to the point:  I have a player in my game that you control with the keyboard yet the key methods in the player class and ActionListener w/ KeyAdapter in the Board class don't seem to fire.

So far I've tried adding these key methods into the JFrame, doesn't seem to let me move him even though other objects that I have (enemies) can move fine.

Here's part of the JFrame class with the event listeners:

    frm.addKeyListener(KeyBoardListener);

    public void mouseClicked(MouseEvent e)
{
        nSound.play();
        StartB.setContentAreaFilled(false);
        cards.remove(StartB);
        frm.remove(TitleL);
        frm.remove(cards);
        frm.setLayout(new GridLayout(1, 1));
        frm.add(nBoard); //Add Game "Tiles" Or Content. x = 1200
        nBoard.setPreferredSize(new Dimension(1200, 420));
        cards.revalidate();
        frm.validate();
}

    public KeyListener KeyBoardListener = new KeyListener()
{
    @Override
    public void keyPressed(KeyEvent args0)
    {
    int key = args0.getKeyCode();

    if(key == KeyEvent.VK_LEFT)
    {
        nBoard.S.vx = -4;

    }
    if(key == KeyEvent.VK_RIGHT)
    {
        nBoard.S.vx = 4;
    }
    if(key == KeyEvent.VK_UP)
    {
        nBoard.S.vy = -4;
    }
    if(key == KeyEvent.VK_DOWN)
    {
        nBoard.S.vy = 4;
    }
    if(key == KeyEvent.VK_SPACE)
    {
        nBoard.S.fire();
    }

    }

    @Override
    public void keyReleased(KeyEvent args0)
    {
    int key = args0.getKeyCode();

    if(key == KeyEvent.VK_LEFT)
    {
        nBoard.S.vx = 0;
    }
    if(key == KeyEvent.VK_RIGHT)
    {
        nBoard.S.vx = 0;
    }
    if(key == KeyEvent.VK_UP)
    {
        nBoard.S.vy = 0;
    }
    if(key == KeyEvent.VK_DOWN)
    {
        nBoard.S.vy = 0;
    }
    }

    @Override
    public void keyTyped(KeyEvent args0) {
        // TODO Auto-generated method stub

    }
    };


texts: Finding which side one point is from another point

texts:
I have a simple question I think, if point a is to the right of another point I a dirx to be 1, otherwise -1. Likewise for a diry var, if it's above the other point I want it to be -1 otherwise 1. This is what I've worked out so far:

dirx = (abs(disx+1)/(disx+1))*-1;
diry = (abs(disy+1)/(disy+1))*-1;

The disx and disy are the distance from each other on x and y. I have a +1 to keep from having a division by 0 error, lastly I'm *-1 it all so that it'll match the coordinate system of the game screen where something higher has a lesser value than something lower.

My problem is that I'm still getting a division by 0 error with this code, I'm not sure why as I even added +1 to make sure it wasn't possible???


texts:
I'm new on this forum as I'm new on unity ^^
I hope I'm not writing this thread in the wrong place.

So, I'm trying to get this 3rd person multiplayer Tank with RTC controller game to work, where you are supposed to shoot at other players. For the networking I'm using Photon Network, and I already got my player prefab with model, animations and 3rd person camera going. If I start the game, everything works fine, I can shoot and stuff, but when I log in the game with a second player, the camera of the first player gets messed up...

I think I'm doing something wrong or missing something with the photonView.isMine property...
does anyone have any suggestion on how I could solve this or how could I start searching for the issue?

Thank you


texts: Rotation and translation like in GTA 1 OpenGL

texts:
Okay, so I have a figure in XZ plain. I want to move it forward/backward and rotate at it's own Y axis, then move forward again in the rotation's direction, like the character in GTA 1.

Code so far:

Init:
  spaceship_position = glm::vec3(0,0,0);
  spaceship_rotation = glm::vec3(0,0,0);
  spaceship_scale = glm::vec3(1, 1, 1);

Draw:
  glm::mat4 transform = glm::scale<float>(spaceship_scale) *
                        glm::rotate<float>(spaceship_rotation.x, 1, 0, 0) *
                        glm::rotate<float>(spaceship_rotation.y, 0, 1, 0) *
                        glm::rotate<float>(spaceship_rotation.z, 0, 0, 1) *
                        glm::translate<float>(spaceship_position);
  drawMesh(spaceship, texture, transform);
Update:
   switch (key.keysym.sym) {
   case SDLK_UP:
       spaceship_position.z += 0.1;
       break;
   case SDLK_DOWN:
       spaceship_position.z -= 0.1;
       break;
   case SDLK_LEFT:
       spaceship_rotation.y += 1;
       break;
   case SDLK_RIGHT:
       spaceship_rotation.y -= 1;
       break;
    }

So this only moves on the Z axis, but how can I move the object on both Z and X axis where the object is facing?


texts: Memory Management when changing Game States

texts:
I am just wondering what are some of the issues of loading and freeing the memory every time player changes the game state?

Or is it better to load all the resources at once?


texts: How to keep track of elements inside a std::vector?

texts:
Let's say I have a std::vector with sf::sprites and my maps are auto-generated.

Then you won't know which element is which sprite.

Example :

I want THAT tree sprite to be removed, but I have no idea which element that tree sprite is inside of my vector... :(


texts:
I have a load all chapters script which loads up all the Chapter items in an array and instantiates the buttons in the Viewport so you can select which chapter you would like to play. The problem is the chapters load up in the wrong order, they load up as Chapter 4, Chapter 0, Chapter 1, Chapter 2, Chapter 3. Below is the code I am using.

void Start()
{
    menuManager = GetComponentInParent<MainMenuManager>();
    levelManager = GetComponentInParent<LevelManager>();

    chapterArray = Resources.LoadAll<GameObject>("Chapters").OrderBy(go => go.name).ToArray();

    txtStatus.text = "";
    if (chapterArray == null)
    {
        txtStatus.text = "Could not find Chapters";
        return;
    }
    else
    {
        txtStatus.text = "Loading...";
        FillChapterList();
    }
    txtStatus.enabled = false;
}
void FillChapterList()
{
    foreach (GameObject chapter in chapterArray)
    {
        GameObject listChapter = Instantiate(chapterListItemPrefab);
        listChapter.transform.SetParent(chapterListParent, false);

        ChapterListItem _chapterListItem = chapterListItemPrefab.GetComponent<ChapterListItem>();
        chapDetails = chapter.GetComponentInChildren<ChapterDetails>();

        _chapterListItem.Setup(chapDetails.chapterNumber,chapDetails.chapterName);
    }
}

This is not only happening with the Chapter Select, it has been happening with all the arrays I load up in this fashion. Below is the visual side of the problem where you can see it loads the last object First.

I have been struggling with this for a while and I think its stopping me from progressing forward. Thank you for reading this and taking the time out of your day to help.


texts: I have a simple game scene where i have put a number of images. I combined these images into layers (SortinLayer, to be specific). So now I have 3 layers. I have read a few tutorials, but in them was described how to make parallax effect for the certain bitmap, not for a group of images that were grouped under one layer.  But I need to make a parallax effect for the whole layer. Is it possible to do this in Unity2D?


texts:
I am trying to replicate the game Asteroids as a class project. I am having trouble measuring the time elapsed while the "W" key is pressed.

This code is supposed to increase the force applied to the spaceship to increase the movement speed incrementally. This is supposed to let the space ship rotate while moving along a 'line' and then force while be slowly applied to the new direction the ship is angled.

I have tried to research this over many hours and I still don't understand the concept. It seems there are a few ways to go about this but neither attempts have been successful.This is for school submission for the first project of the first year, so obviously my code is very basic and not making use optimal use of classes/structs however I would still like to achieve this movement I have been seeking so that I can understand the concept for use in future projects.

I have tried the use of current/previous variables for speed but haven't been able to come up with an equation to accomodate that. I have also attempted the use of a timestep but have been told that is not the correct approach. Any help would be appreciated. You can view the bulk of my program at https://gist.github.com/Rifuli/4762704


texts: DirectSound only allows to capture and output from/to primary devices

texts:
I wanted to allow my users to choose the devices that they want to capture from and output to.
For this, I used DirectSound device and capture device enumeration functions, obtained GUIDs of all available devices, and arrived at the following lists (DirectSound's grammar preserved):
Primary Sound Driver
Speakers (Realtek High Definition Audio)

Primary Sound Capture Driver
Mic in at front panel (black) (

However when I proceed to create sound capture and output devices, they only work if I supply the GUID of the primary drivers. If I supply Speakers or Mic, the result is always
No sound driver is available for use, or the given GUID is not a valid DirectSound device ID.

My thinking was that since the list of devices is returned to me by DirectSound system, then each GUID should be valid for capture or output, respectively. What am I missing?


texts: How to move gameobject with touch on Android

texts:
I'm trying to make a game where you control a character via touch on Android devices.

The player will have two degrees of movement.

When you touch the touch screen and move your finger, the game object should move to your finger's location and follow your finger as you move it.

Here is an example of what I'm trying to do: http://www.youtube.com/watch?v=OoqRC8QptzM#t=01m01s (@ 1:02).

I already know I need to use Input.touches.

I've tried using Transform.translate and Vector3.Lerp, neither gave me the results I wanted.

Here is some of the code I've tried using:

#pragma strict

var speed : float = 1;

function Start () {

}

function Update () {
    if (Input.touchCount > 0 &&
        Input.GetTouch(0).phase == TouchPhase.Moved) {

        // Get movement of the finger since last frame
        var touchDeltaPosition:Vector2 = Input.GetTouch(0).deltaPosition;

        var touchPosition:Vector3;

        touchPosition.Set(touchDeltaPosition.x,
                           transform.position.y,
                           touchDeltaPosition.y);

        // Move object across XY plane
        transform.position = Vector3.Lerp(transform.position,
                                                touchPosition,
                                                Time.deltaTime*speed);
    }

}


texts: changing depth stencil state in DirectX11

texts:
An example from Frank D Luna's 3d Game Programming with Dx11 shows the following effect technique:

technique11 DrawTech
{
pass P0
{
    SetVertexShader(   CompileShader( vs_5_0, DrawVS() ) );
    SetGeometryShader( CompileShader( gs_5_0, DrawGS() ) );
    SetPixelShader(    CompileShader( ps_5_0, DrawPS() ) );

    SetBlendState(AdditiveBlending, float4(0.0f, 0.0f, 0.0f, 0.0f), 0xffffffff);
    SetDepthStencilState( NoDepthWrites, 0 );
}
}

Setting depth stencil state, blend states etc (and restoring them to previous state) when the Effects library isn't available is my goal.

I've had a hard time finding examples on this though.  Luna sidesteps the issue by using the effects framework in his book.

To complicate the issue, I'm using DXUT11 (for loading in meshes).

Can anyone help with an example or an svn repository that includes an example?


texts: How do I structure code with multiple VBOs?

texts:
As per my previous question, it seems it would be desirable to use more than a single VBO in my OpenGL program. But I've hit a wall when trying to do this. Currently my main function looks something like this in pseudocode

setup "main" VBO and VAO
load shaders
setup shader attributes

while true
  update geometry into "main" VBO
  glBufferData(... "main" VBO)
  glClear(GL_COLOR_BUFFER_BIT)
  glDrawArrays(...)

Now what I thought I could do is effectively move the setup "main" VBO inside the game loop itself

setup VAO
load shaders
setup shader attributes

while true
  setup "main" VBO
  update geometry into "main" VBO
  glBufferData(... "main" VBO)
  glClear(GL_COLOR_BUFFER_BIT)
  glDrawArrays(...)

which would then allow me to split the loop into multiple chunks, each creating its own VBO and drawing. But this doens't seem to work, and I get a blank white screen. I can only guess this is because the shaders are not only bound to the VAO, but also to the currently active VBO? I've tried glUseProgram() after the "main" VBO setup, but it doesn't seem to help.

I've found it quite difficult to find information regarding which phase exactly depends on which, and in what order things need to be executed.


texts: Unity - Permanent force when a rigibody without gravity hit a collider

texts:
I'm actually working on a 2D game, and stumbled upon something rather strange in Unity. The issue occurs pretty specifically, so the description will be long:

In the scene, I have a flying object, controlled by the player. It has a rigidbody set as follows: Mass=1, Drag=0, Angular Drag=0.05, Gravity=false, Kinematic=false. So far, so good, the script worked flawlessly, and collide as expected in other physical objects.

Our client asked us to create platforms upon which the enemies could walk, but the player would fly through. A simple collider with IgnorePhysics(GameObject with Player tag) did the trick. The script still worked, no issue until then.

I added a cube on the platform, to test if it would fall through or not. The cube effectively collide with the platform, just as usual, and rest upon it.

But now, as soon as the player hit the cube, it get pushed back in the opposite direction until it hit another surface. It happens like when a non-gravity object is pushed by something: a force is applied and continue forever without friction. (But it does not bounce the same way on other objects. I can only suppose it comes from the force inputed to the objects during the collision, but I can't know for sure)

Example: if I hit the underside of the cube, my avatar will drift towards the ground until I hit it, no matter its speed in other direction. If I hit the upperside, it'll just fly out of the screen, towards the y-infinite.

The script is a classic gameobject.transform.position = Vector3.MoveTowards, so it input no forces whatsoever. Thus, I can't counter the inverse force.

The thing bothering me is that the avatar never had this kind of drift before, even though it collided other objects.

My question is: How can I negate the new force input from the collision for the avatar? (optionnaly: why does it occurs only in this case? I'm puzzled by this case)


texts: How to keep instantiating enemies up to a set max?

texts:
I am creating a castle defense game where the enemy regulary spawns (upto limit of 24 ). After the enemy reaches 24, I want to stop creating clones. So far, I have been successful but I want to make sure that if the enemy reaches 23, it starts instantiating upto 24. How?

    public GameObject[] spawnPosition;
    public GameObject enemy;
    [SerializeField]
    private float startTime;
    private float timeForSpawn;
    public float speed;
    public float enemyLimit;
    public List<GameObject> enemyList;
    public bool stopInstantiating;
    void Start () {
        stopInstantiating = false;
        enemyList = new List<GameObject> ();
        enemyLimit = 24f;
        timeForSpawn = startTime;
    }

    void Update () {

        Spawn ();
    }

    void Spawn () {

        timeForSpawn -= Time.deltaTime;
        if (timeForSpawn <= 0 && stopInstantiating == false) {
            timeForSpawn = startTime;
                for (int i = 0; i <= 2; i++) {
                Instantiate (enemy, spawnPosition [i].transform.position, Quaternion.identity);
                if (enemy != null&& stopInstantiating == false) {
                    enemyList.Add (enemy);
                    if (enemyList.Count >= enemyLimit) {
                        stopInstantiating = true;
                }
                }
            }
        }
}

}

I see that the list doesn't update itself as I delete the gameObjects in game. How to make sure that list updates and work on that.


texts: Stencil inside Stencil? (Multiple masks on same object)

texts:
So please take a look at what I want to achieve

The Red and Blue part is the object I want to mask. The thing is that it will be masked by the green area, and only after that it will be masked by the cyan area, which shall act like a scrollview. Currently I use stencil shader and the first mask works, but I don't know how to apply the second mask. Also, I don't want to use the built-in UI mask system for this. All the objects in the scene are sprites.

The thing is that I would like to achieve a hierarchy masking system, where the kids are masked by a parent.

Could you please give me a tip about what I should do in this case?


texts: How do I export an XNA crossplateform project to Nintendo 3ds or Nintendo Switch?

texts:
I would like to document my self a bit about 3ds and switch game creation. I know that modern game engine have builtin tools to export games to these platforms, but I could not find - in google research - an article or a website talking about this. Any time I searched "Xna Export to nintendo 3ds" I ended up with "getting 3ds max files into an XNA game" stuff.
I'll be highly grateful to anyone that could help me find a way to export my games to these,


texts:
I am trying to apply a force to a bunch of b2_dynamicBodys, but it seems to only work for a random number of items and then stops with an error.

     //create some items to move
     bodyDef.type = b2Body.b2_dynamicBody;
     for(var i = 0; i < 5; ++i) {
        fixDef.shape = new b2PolygonShape;
        fixDef.shape.SetAsBox(1,1);
        fixDef.friction = 1;
        fixDef.restitution = .1;
        bodyDef.position.x = Math.random() * 10;
        bodyDef.position.y = Math.random() * 10;
        bodyDef.linearDamping=1;
        bodyDef.angularDamping=.8;
        itemsArray.push(world.CreateBody(bodyDef).CreateFixture(fixDef));  // store for later
     }

then i try to apply a force later with:

angle = 20;
for (var xIdx=0; xIdx<itemArray.length; xIdx++) {
    itemsArray[xIdx].GetBody().ApplyImpulse(new b2Vec2(50*Math.cos(angle*Math.PI/180),50*Math.sin(angle*Math.PI/180)););
}

the error I receive is

TypeError: 'undefined' is not an object (evaluating 'c.x')

Is there something wrong with saving the items for later use when I am creating them?  Does anyone know what is causing this.


texts: Why does Unity use HLSL instead of GLSL?

texts:
I am beginner in shader programming. I got my introduction (few minutes ago) to shader programming via Unity.

I didn't know what HLSL was. So, I Googled and found this post:  Difference b/w HLSL & GLSL

I can't understand one thing. Unity was initially developed for OSX & introduced at WWDC. Also DirectX is windows only API & HLSL is the shader programming language for DirectX. However, Unity3D for OSX is written in OpenGL. OpenGL uses a standard shader programming language called "GLSL".

So, I'm confused how Unity3D uses HLSL on OSX & why Unity didn't pick GLSL instead of HLSL.

  NOTE: I might be wrong somewhere. So please correct if something is wrong as I told I'm a beginner


texts:
I'm reading riemers tutorial on how to make a water effect and trying to translate it from xna 3 to xna 4. So far I figured out I have to create a shader in order to clip the planes for my refraction map. I'm new to hlsl and how to implement custom shaders into my program, so I am wondering what I am doing wrong here.

  float4x4 World;
  float4x4 View;
  float4x4 Projection;

  float4 ClipPlane0;

  void vs(inout float4 position : POSITION0, out float4 clipDistances : TEXCOORD0)
  {

clipDistances.y = 0;
clipDistances.z = 0;
clipDistances.w = 0;

position = mul(mul(mul(position, World), View), Projection);

    clipDistances.x = dot(position, ClipPlane0);
  }

  float4 ps(float4 clipDistances : TEXCOORD0) : COLOR0
  {
clip(clipDistances);

return float4(0, 0, 0, 0); // TODO: whatever other shading logic you want
  }

  technique
 {
pass
{
    VertexShader = compile vs_2_0 vs();
    PixelShader = compile ps_2_0 ps();
}
  }

This is the fx file that I found on an xna forum just for reference.

Major edit:

I was able to get the program running successfully but when I viewed the saved screenshot of the refraction map, nothing was clipped.

    public void DrawRefractionMap(Effect clipEffect, Camera camera, GraphicsDevice device)
    {
        Plane refractionPlane = CreatePlane(waterHeight + 1.5f, new Vector3(0, -1, 0), camera, false);
        clipEffect.Parameters["ClipPlane0"].SetValue(new Vector4(refractionPlane.Normal, refractionPlane.D));

        device.SetRenderTarget(refractionRenderTarget);

        device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1, 0);

        foreach (EffectPass pass in clipEffect.CurrentTechnique.Passes)
        {
            pass.Apply();

            DrawTerrain(clipEffect, camera, device);
        }

        device.SetRenderTarget(null);
        refractionTexture = (Texture2D)refractionRenderTarget;

        FileStream stream = File.OpenWrite("Screenshot33.png");

        refractionTexture.SaveAsJpeg(stream, refractionTexture.Width, refractionTexture.Height);
    }


texts: Any good book on lighting in video games?

texts: Lighting plays a fundamental role into videogames. A videogame without a good ilumination is flat and without life. I'm looking for a book that explains how must be iluminated a scene and what factors are involved in the creation of convincing worlds.


texts:
I am making a puzzle game. The puzzle in question needs to be solved in advance, with the final solution being given as a series of commands which will instruct an object to navigate a maze.

This means I need to be able to provide all the clues necessary in advance, as pure trial-and-error will be tedious for the player.

When it comes to rotation and distance, this is no problem. Rotation is visually obvious, and I can use regularly sized and evenly spaced blocks/objects for the player to count to work out distance.

However - my problem is finding a similar visual representation for time. At one point, the player will ride a lift/platform to 'a place', where the destination will be X seconds away. The player needs to wait this X seconds before continuing forward.

How can I communicate that time delay in an interesting/thought provoking way? I don't want signs next to each lift that simply state the time it will take.


texts: How to effectively check for object visibility prior to object creation?

texts:
I'm using pseudo-random noise to create a cube world a la Minecraft. So I've got my noise generators up and running, working great. Right now I'm just directly scaling the noise output to a height and assuming everything below that is solid, I intend to go back later and add some caves, pits, etc. My problem right now is taking these three dimensional integer arrays, and turning them into blocks. I'm hitting a big wall there.

After the numerical list, it's taking almost 30 seconds for a chunk(16x128x16) to generate. That's not counting rendering, that's fast enough iff I don't draw every block in the chunk at one time.

My first approach wast to draw all 20,000+ blocks every frame. I figured out that was bad really fast because I was getting maybe 2 fps.

Then I decided it was better to check if the block was exposed before rendering it. That is when I started to get a huge slowdown. If my list indicated a block existed, then I would check the value of the array in all six directions surrounding the cube with my integer list to see if they also held a cube. This works great, but as I said, my generation time for just one chunk is ~30 sec.

My Exposure check code:

        public bool determineExposed(int x, int y, int z)
    {
        try
        {
            if (_list[x + 1, y, z] == 1 && _list[x - 1, y, z] == 1 && _list[x, y + 1, z] == 1 && _list[x, y - 1, z] == 1 &&
                _list[x, y, z + 1] == 1 && _list[x, y, z - 1] == 1) return false;
            else return true;
        }
        catch
        {
            return false;
        }
    }

How Can I speed this up?


texts: Finer collision detection with multi-path Polygon2DCollider from Tiled2Unity

texts:
I'm in the process of incorporating Tiled2Unity prefabs into my code. Their exporter creates a collision object (shown below) that amalgamates the collider of each tile into a single Polygon Collider 2D made up of multiple "subcollider" paths, shown below as green polygons.

What I'm trying to do is to adapt my old corner detection code to work with the new collider, but when OnTriggerStay2D(Collider2D other) is triggered, I'm not provided with the specific path I've collided with. In the picture, each green polygon is a path, and together they make up the Collider2D (other) provided in the argument.

Is there any way to find out which path I've collided with, without looping through each of the 1000ish points every time I want to detect a nearby corner? So far I am only able to discover via events that I've collided somewhere in the ENTIRE collection of green polygonal paths.

Thanks!


texts:
How can I make levels in iOS shortcuts?
i'm making a game which will be about changing some settings to finish levels (logic game) i had idea to make autosave because levels will require that. my idea was about using rarely used system app named 'reminders' where i can save progress in a part of one reminder named 'notes' but shortuts app doesn't recognize 'otherwise' feature for if loop and when i tap shortcut it adds only one more reminder and doesn't show upcoming first level ios version is 14.4.1 (beta i think) and tablet is after JB (but i've never modified shortcuts app) .
xml source from shortcut (github) : https://github.com/hacknorris-notyetbanned/hacknorris.github.io/blob/77a47bff65bc13f21642dbebdf4023aa957ebb0a/Test.xml
where is bug in reminders?
Edit: now i wont mess up on shortcuts - im gonna update this : https://github.com/hacknorris-notyetbanned/glitched.git and leave project. I have 0 ideas and logged out of icloud...  :/


texts: Which is the better way to distribute server workload for MMO server?

texts:
I'm making a server for MMO in Unity, which implies that I'll have a big world, split into maps which will be on different servers (to distribute the workload), managed by one master server.

Now I can't decide weather I should use one executable per map and have few executables run on each server or have few maps on one executable, which will have it's own server.
Second solution also would allow me to redistribute the workload by moving maps from one server to other (which shouldn't take long to do since servers don't need to load models).

Btw servers need to be made in Unity for the physics simulation and collisions...

The networking part can easily be multithreaded simply by using many threads to process the requests and generate response.
But since Unity is single threaded adding more maps would slow down the physics engine (plus the same thread has to apply all actions of the players to the game), so the first solution helps here by using multiple executables.
(Edit: Note: physics engine will take considerable amount of CPU time, even while the scene is empty)

Which solution should I chose?

EDIT:
On the end I decided to use both: few executables on each server, with each executable being able to run multiple maps and being able to dynamically create dungeons when needed.


texts:
I can't seem to find any documentation using the Social APIs with OSX. I can successfully use the iOS Social Libraries, but when I translate it over to OSX, it doesn't do anything. Also please refrain from suggesting Prime31, as I know that option exists, but the functionality for OSX leaderboards/game center is natively built into Social API in Unity 4.1+ yet there is no documentation to be found!?

I want to know how to use Social.ReportScore, and the ShowLeaderboard UI Methods for OSX games. I would also like to know how to report achievement progress.

I've tried using the EXACT methods from the Unity.Social Library that works for my other iOS/iPhone/iPad games.  I've attempted the code in both C# and UnityScript (JScript) to no avail.

Please help.


texts: What is your Unity 3D physics engine budget for iOS games?

texts:
I'm testing Unity for a game that I'm building, and I've touched its limit.

My test scenario: a wanna-be house with 200 elements (cubes rescaled) no textures, box colliders and rigid bodies for each "cube" and fixed joints to hold them together (400+ fixed joints). The house is on a plane, and above it I put 2 sphere at different altitudes, spheres which will crash in the poor house.

This moves very slow on an iPod Touch 3rd generation. Therefore I'm looking for some documentation to create a reasonable budget for the number of polygons, physics collisions and so on. What is your recommendation?


texts:
I have a game where there is a set of tiles rotated 45° away from the camera. I want to work out what tile is being hovered over by the mouse, and for that I need to translate the mouse pos on the screen into the position on the plane rotated 45° away. How can I do this? Is there an easy way of doing this without using (expensive) 3D transformation?

Thanks in advance.


texts: Tile Based Engine: Storing Tiles and Levels

texts:
I've worked with tile-based engines before (a few years ago when I was pretty green).  Now that I know a bit more, I want to revisit tile-based engines but I want to approach it correctly.  I want to know two things: what is the best way to store the tiles, and what is the best way to store the levels?

For the first question: The tiles should be stored in sets, like a 10x10 grid of 40x40 tiles stored in a 400x400 image.  Right?  So when it's displayed, do you just place the entire image on the screen and only show the part of the image you want?  And in that case, wouldn't it create a significant amount of overhead for a bunch of unused image?  Or do multiple copies of the same image use the same cache?

For the second question: Should the levels be stored as two dimensional arrays?  Serialized in a database?  Or what?


texts:
I am currently developing a breakout clone and I have hit a roadblock in getting collision detection between a ball (circle) and a brick (convex polygon) working correctly. I am using a Circle-Line collision detection test where each line represents and edge on the convex polygon brick.

For the majority of the time the Circle-Line test works properly and the points of collision are resolved correctly.

Collision detection working correctly.

However, occasionally my collision detection code returns false due to a negative discriminant when the ball is actually intersecting the brick.

Collision detection failing.

I am aware of the inefficiency with this method and I am using axis aligned bounding
boxes to cut down on the number of bricks tested. My main concern is if there are any
mathematical bugs in my code below.

/*
 * from and to are points at the start and end of the convex polygons edge.
 * This function is called for every edge in the convex polygon until a
 * collision is detected.
 */

bool circleLineCollision(Vec2f from, Vec2f to)
{
    Vec2f lFrom, lTo, lLine;
    Vec2f line, normal;
    Vec2f intersectPt1, intersectPt2;
    float a, b, c, disc, sqrt_disc, u, v, nn, vn;
    bool one = false, two = false;

    // set line vectors
    lFrom = from - ball.circle.centre;      // localised
    lTo = to - ball.circle.centre;          // localised
    lLine = lFrom - lTo;                    // localised
    line = from - to;

    // calculate a, b & c values
    a = lLine.dot(lLine);
    b = 2 * (lLine.dot(lFrom));
    c = (lFrom.dot(lFrom)) - (ball.circle.radius * ball.circle.radius);

    // discriminant
    disc = (b * b) - (4 * a * c);

    if (disc < 0.0f)
    {
        // no intersections
        return false;
    }
    else if (disc == 0.0f)
    {
        // one intersection
        u = -b / (2 * a);

        intersectPt1 = from + (lLine.scale(u));
        one = pointOnLine(intersectPt1, from, to);

        if (!one)
            return false;
        return true;
    }
    else
    {
        // two intersections
        sqrt_disc = sqrt(disc);
        u = (-b + sqrt_disc) / (2 * a);
        v = (-b - sqrt_disc) / (2 * a);
        intersectPt1 = from + (lLine.scale(u));
        intersectPt2 = from + (lLine.scale(v));

        one = pointOnLine(intersectPt1, from, to);
        two = pointOnLine(intersectPt2, from, to);

        if (!one && !two)
            return false;
        return true;
    }
}

bool pointOnLine(Vec2f p, Vec2f from, Vec2f to)
{
    if (p.x >= min(from.x, to.x) && p.x <= max(from.x, to.x) &&
        p.y >= min(from.y, to.y) && p.y <= max(from.y, to.y))
        return true;
    return false;
}


texts: If I make a 3d model in a .fbx format, do I owe any royalties/fees to autodesk for using fbx files in Unity?

texts:
I'm currently making a game where every format for every asset is either opensource/freeformat, or requires no license fees to use.

I've pretty much settled happily on .ogg for audio, vorbis/webm for video, .png for pictures and openoffice for documents (or .pdf files since they were free standard since 2001?)

What I'd like to know though is, if I make a 3d model in a .fbx format, do I owe any royalties/fees to autodesk for using fbx files in Unity?

If not, does this apply to every 3d model format, or only certain ones? Do software companies like Blender/Unity pay for the privilege to import fbx files so that users like me don't have to?


texts:
I would just like someone to explain in relativly clear terms how hardware tessellation works considering it is the new buzzword with DX11.

Thanks.


texts: How can I define areas filled with water?

texts:
I would like to enhance my little game engine with nice looking water simulation. To start working on that I need to find a proper way to represent water in the game. Unfortunately I don't know much different representations, so I'll ask you. There is a similar question I asked some time ago. But since I hadn't formulated the issue clearly, the answer is correct but not what I was looking for.

In some games, water is just defined by a height level. For example everything under the height of zero is underwater. I saw this representation in (mostly older) games. The problem is that I'd like caves in the outdoor world which aren't flooded and different water levels for each lake and sea.

Another, more precise, representation of the occurrence of water are particles. Every water drop is stored as a point in world space. To render them, I could use techniques like metaballs so that they build a single mesh. This representation would be great for realism since I could easily calculate dynamics among them. Sadly no machine could calculate a ocean of metaballs in real time.

Are there other ways of representing water in an engine? I would like to have dynamic lakes, so defining water area by a static geometry is no option. For example if the player modifies the terrain to widen a lake, the water should fill that bay and the overall water level of that lake should slightly decrease.


texts: how to choose the board design in a multiplayer game?

texts:
I'm making a Nine Men's Morris board game in which players can play with other online players.

But my problem is in steps before starting the game between two players.

This is what I thought about:

  1- Player B requests to play with Player A

  2- If player A accept the request, the game will start.

I need a step in between, so that they can choose a board design, but I don't know who should choose it or how.

Is there any better way in maching two players or how to select a borad map? Any ideas is much appreciated.


texts: 2.5d with box2d - approaches from the top and bottom

texts:
So, I'm using box2d for my 2.5d game (think double dragon, tmnt arcade, castle crashers) where you can move around on the z-axis (faked as y-axis movement). Basically, I have box2d only doing collision if 2 entities have the same z coordinate or a z-coordinate within the depth. All is fine, except when I approach an entity from the top or bottom.

So yeah, approaching any box2d entity from the top or bottom within the correct x will make the player bounce back once the z becomes the same as the entity - which makes sense because then it starts detecting collision, and it detects a box inside a box. How could I circumvent this? Thanks.


texts: Writing an autopilot for a 2d game with newtonian physics

texts:
The subject says it all. I am making a 2d space game with newtonian physics and I need pointers on how to write an autopilot for it. The requirements are best explained by an example.

There is a target object which has speed and position vectors and there is a spaceship that is controlled by the autopilot. This spaceship also has speed, position and maximum acceleration. The autopilot needs to control the ship so that it either collides with the target or intercepts the target with matching speed and position.

Could someone give me some pointers how to achieve this behavior or perhaps even a ready implementation? I am sure someone has written something like this before and there is no point in reinventing the wheel.


texts:
In a turn based game each player has a set of properties, e.g attack, defence, speed and these can all be used to work out who should go first and how much damage should be dealt. That all works fine, but the problem I'm having is with edge cases where a player receives a power-up for one turn that lets them move first. How should I handle this? Should I increase the speed value and then somehow remember to reduce it next turn or should I implement some sort of object which holds modifiers that is checked every turn?

I'd also need to be able to scale this to different things like temporary poison etc.

Basically I'm very confused and help would be appreciated!


texts: How can I render a model on top of another model regardless of their relative Z positions?

texts: I was wondering if there's any way to render models over other 3D models regardless of their relative positions? Kind of like how it works in 2D graphics, you set a render order and it renders them based on that instead of taking the depth and figuring out which is in front of which.


texts: Hierachy organisational methodology in Unity

texts:
I'm just getting into Unity, so I do not know if my system of organisation will have any negative consequences.

I intend to store my project files and assets under an assets directory, then into scripts and such, as is commonplace. For the hierarchy I intend to have a top level empty object titled something like "Hierarchy", under which all objects will be children.

I am also thinking that I will further subdivide into logical and physical objects, putting objects that do not have components on them but have a physical space in the game (not including transforms) under the former, and anything with a physical presence under the latter (lights, player etc).

The main reason is so that I know where to look, based on functionality. I can also use alt-click to close all objects at once. I find this helpful for navigating the hierarchy.

Is this a bad plan?


texts: Handling different renderers Y axis direction in a single engine

texts:
I have an engine that uses either three.js (3D WebGL rendering library) or pixi.js (2D rendering library) depending on the game.

The problem is that pixi.js has y-axis pointing downwards (same as in most 2D applications), while three.js has it up, like most 3D rendering systems.

I am wondering if there is a way to gracefully handle the difference in the engine, so that the user doesn't have to remember to invert everything depending on if they use 2D or 3D.

Are there any known solutions or engines doing something similar? My first guess would be trying to invert all coordinates, but this seems like an ugly hack that won't necessarily handle all situations.


texts: Should a game clean up after itself when exiting?

texts:
Should a game/engine clean up after itself(close windows, shut down renderers, close files, free memory) when its closed?

The OS should do that anyway, and usually in a faster way.

I guess most developers don't really care as they need proper cleanup for everything anyways(With dynamic asset-loading, and changing maps, etc.), but won't ensure that everything gets cleaned perfectly.

But is there any positive to cleaning up vs not cleaning up or the reverse?

I am using C++.

What about game consoles? Do they all clean up after themselves?


texts: Is it possible to run GLFW eventhough my graphic card(Nvidia) supports Direct3d API?

texts: I have Nvidia 820M GPU installed in my windows 7 machine. In nvidia control panel it is showing it supports Direct3d API version 11. Am I able to run OpenGL applications(using GLUT,GLFW) on my machine with this configuration? see the below screenshot for configuration details.


texts:
I am a student C++ developer, and while I like game development, I don't like making games. Instead, I like developing the "tech" behind the games, like game engines, tools etc. The reason for this is because it enables me to code without having to worry about creating art resources, sounds, storylines, etc.

I started working on a game engine, but I am having a hard time starting from scratch. I would much rather be given a template to work off of and modify/add as I go. What are some good open source game engine I can fork?

I would rather fork an engine, as I truly want to make it my own, but I need a base to start from.

Please let me know.

Thanks


texts: Python Opengl Procedural Terrain Rendering

texts:
I am rendering procedural terrain in Python using OpenGL. Once generated, data for each terrain tile is stored in lists. However currently I am only getting around 25fps despite rendering only around 4000 polygons (2 per terrain tile). The model x and z coordinates are stored in the position matrix contained in the terrain_quad_location list where as the heights are stored in the vertices of each terrain tile quad in the terrain_VAO list.
It seems like this low fps is due to inefficiency when render large numbers of models not polygons as when I render models with high polygon counts in addition to this my fps is minimally affected. For reference I am using VAOs, VBOs and EBOs and built upon these tutorials.
Is there a way I can make the code more efficient?
Before Runtime:
count=0
for i in range(terrain_quad_number):

    terrain_VAO[count] = glGenVertexArrays(1)
    glBindVertexArray(terrain_VAO[count])

    terrain_VBO[count] = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, terrain_VBO[count])
    glBufferData(GL_ARRAY_BUFFER, terrain_quad_vertices[count].nbytes, terrain_quad_vertices[count], GL_STATIC_DRAW)

    terrain_EBO[count] = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, terrain_EBO[count])
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, terrain_quad_vertices[count].nbytes, quad_indices, GL_STATIC_DRAW)

    glEnableVertexAttribArray(0)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, terrain_quad_vertices[count].itemsize * 5, ctypes.c_void_p(0))

    glEnableVertexAttribArray(1)
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, terrain_quad_vertices[count].itemsize * 5, ctypes.c_void_p(12))

Runtime:
moo=0
    for i in range (len(rendered_terrain_number)):
        model = terrain_quad_location[rendered_terrain_number[moo]]

        glBindVertexArray(terrain_VAO[rendered_terrain_number[moo]])
        glBindTexture(GL_TEXTURE_2D, ground_textures[int(terrain_quad_sub_biome[int(rendered_terrain_number[moo])][0][0])-1])
        glUniformMatrix4fv(model_loc, 1, GL_FALSE, model)
        glDrawElements(GL_TRIANGLES, len(quad_indices), GL_UNSIGNED_INT, None)
        moo=moo+1

I understand that I may need to lower the number of draw calls which may be done my merging terrain tile models, but how do I do this given I want each tile to have its own texture?
Apparently Minecraft does this by merging every block in a chunk into one VBO but how is this done given every block has a different texture? Instancing would not work either.
Here is a video of the program.


texts: How to implement SSAO in Shader Model 3/ DX9?

texts: Ive read a few articles about SSAO, and i would like to implement it in to 3d engine at work, which runs on top of DX9. Can you give me an tips on getting the simplest implementation possible up and running using shader model 3, and how would you upgrade this implementation over time to tackle artefacts like haloing?


texts: After detecting a collision between two convex shapes by using separating axis theorem and calculating MTV. How can I calculate the contact points?(for applying torque to the rigid body).


texts:
We have animation states for Normal, Highlighted, Pressed and Disabled. How to set animation when a button is clicked?(after button released not pressed)?

Thanks in advance


texts: Projector making the scene objects grey in Unity

texts: Everytime I enable my projector, it makes all the overlapping elements look entirely grey. The shadows also disapear. I tryed a couple of other shaders found on the internet but the issue still persists.


texts: Tools for assembling textures into DDS files

texts:
There are plenty of tools for making images. I'm not looking for one of those; I have many tools for creating an image. I've got tools for compressing images, generating mipmaps, and even for poking at their basic data format.

My issue is with texture assembly. DDS files support cubemaps, array textures, and even cubemap arrays. But I don't know of a tool that can pack a series of images into a cubemap or the like. What tools are available for doing this kind of thing?


texts: Detect minimum speed of a dynamic node in 3d space

texts:
I have a 3d dynamic node with speed & acceleration vectors. It has maximum speed (magnitude) and minimum speed such as if it exceeds maximum or goes below minimum, it stops accelerating and the speed is set to the respective maximum or minimum.

I have no problem detecting the maximum, I just have to check if the magnitude of speed vector is superior to the maximum.

But I am struggling for the minimum detection, magnitudes being in the positive field it seems to me more tricky.
For example I want a minimum speed near 0, or 0, the object is decelerating, at one point it will pass through 0 and start accelerating following acceleration vector.

For example speed magnitude could be as such through frames:
5, 4, 2, 1, 3, 6 .. etc

There is no way to know if it did pass through zero, it could have well passed over zero between 2 and 1 and accelerate after, or between any other number.

Each frame I have these data: last speed vector, actual speed vector, acceleration vector.

How can I detect that next frame I'll cross my minimum value (zero in that example) ?


texts:
I am building a simple strategy game, the goal of the game to teach programming basics to kids.

The concept of the game is simple, there will be a set of colony individuals - different type (resource gathering, fight, defend, scout ..etc).

I want to build a Campaign mode for this game, simple set of scenarios and missions as beta version.

As I said, the purpose is to teach programming basics, so player need to code there strategy to play the game, means that each colony individual's behavior will be programmed separately.

I am thinking of creating a basic syntax for code conditions, commands and actions (custom language), player will simply code individual's behavior by simply grouping these conditions, commands and actions in logical order. An example:

if FindEnemy
    if stamina > 0.6
       dobattle;
    else
       returnToNest;
    endif;
endif;

My question is that I am building the game using HTML5/CSS3/JS, and wondering I can implement it a client-side library to parse custom language and convert it to animation? or whether there is already built JS library or engine that can do similar requirement?


texts: List to hold copies of a prefab for later deletion

texts:
I'm working on a game in which obstacles are Instantiated randomly 5 to 20 units ahead of the player.

When they are instantiated, I want to add them to a list so that when there are too many obstacles loaded in the game, it will remove them from the list and then delete them from the game.

I'm having trouble adding them to the list, because using obstacleList.Add(Obstacles.name); doesn't work.

Here's my code:

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

public class Generate : MonoBehaviour{

    //player position
    public Transform Player;

    // The prefab for an obstacle
    public GameObject Obstacle;

    // Holds float distance from 0 for each obstacle that is instantiated
    private float nextObstacle = 30;

    // is supposed to hold the names of all active instances of the obstacle prefab
    List<string> obstacleList = new List<string>(10);

    void FixedUpdate()
    {
        //Checks to see if the player is colser than 30 units to the most recently spawned obstacle
        if (nextObstacle - Player.position.x < 30)
        {
            //Generates a new obstacle
            GenerateObstacle();
        }
    }

    void GenerateObstacle()
    {
        // Randomly assignes a number for horizontal and vertical Transform
        int randH = Random.Range(5, 20);
        int randV = Random.Range(1, 3);

        //Instantiates an obstacle using those random values
        Instantiate(Obstacle, new Vector3(nextObstacle + randH, randV, 0), Quaternion.identity);

        //Makes that obstacle the new distance so a new obstacle can be spawned
        nextObstacle += randH;

        // Is supposed to add the name of the obstacle that was Instantiated to a list
        obstacleList.Add(Obstacle.name);

        //checks when list has more than 10 items in it
        if (obstacleList.Count > 10)
        {
            DeleteObstacles();
            // Removes the first item from the list
            obstacleList.RemoveAt(0);
        }
    }
    void DeleteObstacles()
    {
        // Supposed to destroy the copied prefab
        Destroy(Obstacle);
    }
}


texts:
If I created different XML files for each Nations' Stockpiles and made an XMLmanager to do updates such as resource consumption and trade, wouldn't that be too much resource intensive? I mean, if I had to access each Nations' stockpiles every tick and update them (Quantity, Price, Quality).

Is there any other faster way to manage all those updates?

From the back and forth in the comments, I've came up with this approach.

public class Nation
{
    public string NationName;
    public int Population;

    public void NationCreator(string name, int pop)
    {
        NationName = name;
        Population = pop;
    }

    public class Stockpile
    {
        public int food;
        public int water;
        public int wood;

        //Then methods to work with that stockpile
    }
}

However, after some thinking and reading, my next approach to this problem will be Arrays but I only know how to make an array of one particular type like:

double[] balance = { 2340.0, 4523.69, 3421.0};

How could I do an array like this (Lua style array) in C# language?:

raw_material = {
    cotton = {
        Value = 17.50
    }
}


texts: cost of Adding Social Feature to your game such Creating guilds/guild chat

texts:
I'm making a f2p game in unity C#. The game currently has no social features.

I would like to have players to have their own accounts and also a guild tab. This tab is where they can create a guild and invite other players to the roster and being able to chat with each other.

Also would like to add leader boards for individual and guild rankings.

Was just wondering if any programmers can give me a estimate on labor to be able to make that feature in a game and how long roughly it would take.

I'm think I will need a mySql and php. I'm not really familiar with how it works.

Thanks,

Phil


texts: How to rotate two textures at once in Libgdx, while keeping their relative positions the same?

texts:
I am trying to develop a game with cards, where the user can swipe left or right to tilt the cards like this. The red & white cross should stay in the same position on the yellow card as they tilt together, but you can see in the images below that their positions shift relative to one another:

I started this game with the yellow card with purple edges, and I tried to rotate it once the user swipe left or right using this code:

void renderCard(SpriteBatch sb , TextureRegion cardShape)
{
    sb.draw(cardShape, x, y, originX, originY, cardWidth, cardHeight, 1, 1, rotationAngle);
}

Once the user swipes, I modify the rotation angle in the method above.

Now, I want to add another texture region over this one, and I want to rotate it too once the user swipes.

Here is the code for that:

void renderCross(SpriteBatch sb,TextureRegion crossShape)
{
    sb.draw(crossShape, x+130.0f, y+130.0f, originX+130.0f, originY+130.0f, 200, 200, 1, 1, rotationAngle);
}

When there was no swipe performed, anything was okay, all the above are drawn. perfectly drawn.

But when I swipe left or right, there are some offsets added, as you can see in the images above.

So the question is, how do I keep the the same relative positions between these two textures, like the game started?


texts: How to make a prefab of a blood effect using provided shader/materials in 2D?

texts:
I want to create a blood splat effect as shown in this link: https://gfycat.com/CharmingThickFlies

The developer was nice enough to leave the source explain how to apply this. But I cant seem to follow the provided instructions. Instructions and code are here: https://www.reddit.com/r/Unity3D/comments/4108d1/new_splatter_shader_effect_im_working_on_perfect/cyyj988/

I want to get this effect to a prefab level which I can then instantiate in my code.

I have followed link on youtube and read up on how to use shaders but I can't seem to apply this in unity and get a prefab. I have tried applying this to a particle level system but that also did not help.

Some guidance would be appreciated. Thanks


texts: Is there an HLSL equivalent to GLSL's "map" function?

texts:
Google has not helped me in this area.

Here is the GLSL shader:

vec3 globalIllumination(vec3 p, vec3 n) {
vec3 g = vec3(0.0);
float dist;
for (float i = 1.0; i <= samples; i++) {
    dist = stepDistance * i;
float d =  vec3(dist - map(p + n * dist, returnColor));
    g += returnColor*d/ i;
}
return g;
}

I know how to convert this to HLSL, except for that map function. I could use some help.


texts:
I have a problem. I want a Grayscale effect to be applied ONLY to the chair on the stage. The chair has a layer CurrentItem. And I have two cameras:

Camera_All renders everything except layer CurrentItem (I set this exception in CullingMask)
Camera_CurrentItem

Finally:

I need to apply not just one effect, but a few.


texts:
I am trying to add force to the player's rigidbody, when the screen is held. I've written the following code:

float PlayerForce=50.0f;

void FixedUpdate()
{
   bool PlayerActive = Input.GetButton ("Fire1");

   if (PlayerActive) {
       PlayerRigidBody.AddForce (new Vector2 (0, PlayerForce));
   }
}

This does not add a smooth jump effect. I've searched for smooth force effect, but I didn't find anything useful. How do I add a smooth force my player's rigid body, to make them jump?


texts: Don't block Camera with Blocking Volume in Unreal Engine

texts:
I use Blocking Volumes to prevent players from falling off platforms in a third-person perspective game in UE4.

These Blocking Volumes however block the camera, as if they were a physical wall.

How can I easily add block the player, without blocking the camera?

Ideally without coding/blueprints. If that's impossible, a simple blueprint would be best.

  Camera at normal distance from player, when it's not being restricted by a blocking volume

  Camera being restricted by a blocking volume


texts:
I'm struggling with coming up with an elegant solution to generating random events in the game that I'm working on.

Say there are 4 classes of events that can happen, with varying events in those classes that may occur.

So something along the lines of

main_events = {"common event", "not so common event", "somewhat rare event", "rare event"}
sub_events[0] = {"common event 1", "common event 2",..}
...

I have a somewhat kludgey solution in place that first just has a random number generated between 0 and 100, and if the number falls within a given range then a main event will be triggered.  Then I'll do another random roll to see which sub event occurs.

Is there a better solution than something along these lines?  Like I mention, it doesn't feel very elegant, and I'd like to make it easily expandable for the addition of future events.


texts: recommended shader pipeline infrastructure in core opengl 3.3

texts:
I am writing a game project in Go and I am using an OpenGl 3.3 core context to do my rendering stuff. At the moment I have different types of renderers. Each renderer has it's own pair of vertex- and fragment-shader, a struct of uniform- and attribute locations. A struct with glBuffers, vertex-array-object, and numverts (int) which contains all data required to render one object (mesh). Last but not least a constructor to create and initialize the attribute/uniform locations a method to load a mesh into mesh data and the render method itself.

I am absolutely not happy with this design. Every time I want to create a new simple shader, I have to write all this code, and I haven't found a way to make the overhead of a new shader smaller. All I was able to make with the help of go reflections is to automatically get the attribute/uniform location based on the variable name in attribute/uniform location struct and to automatically set the attribute pointers based on the layout of the vertex struct.

another thing that I don't like, is that when I want to implement for example the functionality of the function glClipPlane of the fixed function pipeline, I need to add the uniform to each shader separately and I need to set this uniform in each shader and I need to implement the discard of fragments in each fragment shader

Are there some common practices that significantly reduce the code overhead of a new shader? Are there good shader pipelines that you can recommend me to take a look at?
Are there some good practices to add functionality to several shaders at once?


texts: Triangle area selection using BVH raycasting

texts:
Let's assume I'm already storing a BVH acceleration structure per mesh on my engine and I'd like start
making area selection like on many DCC tools out there, for instance, blender.
With blender you can do {rectangular, circle, lasso} selection to select faces and I'd like to understand the maths behind these algorithms. If I was using color picking techniques these sort of algorithms would be obvious but when using BVH+raycasting I'm still failing to understand the algo/maths behind it.
So, could you please explain the logic behind those? For instance, I assume rectangular selection should be easier to implement than circle/lasso, so how would you gather all screen projected triangles living inside the rectangular selection created by the mouse?


texts: Fading previous frame doesn't fade all the way to black?

texts:
I'm working on a 2D OpenGL program. It'll be a fairly simple fireworks visual.

So far what I have is that I draw a circle with a gradient "glow" to it and move it around on the screen. I want it to have a tail behind it as it moves so instead of calling glClear between each frame, I'm drawing a black quad over the whole screen with transparency in hopes of darkening the previous frame before drawing the next frame. I've got a decent tail on it but I've noticed the tail doesn't completely blend to black.

Currently the red glow moves up the screen and when it goes off the top it instantly moves back down to the bottom to make another pass. You can see that there's a "shadow" of where the ball has been before and it never gets darker.

I have a feeling it has something to do with the blend function. Here's what I currently have:

gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)

I'm using go-gl but it is equivalent to

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

Here's the shader that draws the circle and the quad:

#version 430 core

layout(location = 0) out vec4 color;
uniform float radius;
uniform vec2 center;
uniform float windowHeight;
uniform vec4 in_color;
uniform int gradient;

void main()
{
  if (gradient == 1) {
    vec2 correctedCenter = vec2(center.x, windowHeight - center.y);
    vec2 p = (gl_FragCoord.xy - correctedCenter) / radius;
    float r = sqrt(dot(p, p));

    if (r < 1.0) {
      color = mix(in_color, vec4(0, 0, 0, 0), r);
    } else {
      color = vec4(0, 0, 0, 0);
    }
  } else {
    color = in_color;
  }
}

For the circle I use gradient = 1 but for the quad I use 0.


texts: Qt 5 - QOpenGLWidget not updating the screen

texts:
I'm creating a level editor for my game using Qt for gui and i'm in really early stages. Right now i'm trying to dynamically add objects ( entities ) on screen when i click a button. So far the objects are pushed into a stack but i can't see them on screen.

When my widget inherits QGLWidget the screen is updated immediately and i can see the objects being drawn but since QGLWidget is deprecated i use QOpenGLWidget.

Strangely this class does not auto update the screen. I have also connected update() to a timer and set the interval to 0 to update the screen in real time.

connect(&timer, SIGNAL(timeout()), this, SLOT(update()));
timer.setInterval(0);
timer.start();

Am i missing something ?


texts: I am having this error in unity and i don't know what's causing it

texts:
I don't know how it happen this is an endless runner game
The road is 15 on x and 100 on z.
This is happening in android road is a cube with png image as texture it is distorted and turn blue every 2 sec.


texts: Using a vector to measure an angle relative to the screen / camera

texts:
My game is supposed to have an object that changes it sprite depending on which way the mouse faces. programming this has become a challenge, because I want to calculate the angle relative to the center of the screen using the X axis.

To explain what I mean, pretend that under a sprite in the center of a screen is a protractor.

I want to measure the angle that's formed between the cursor and the center. If I use the X axis as a base, I should get an angle between 180° and -180°.

How would I achieve this? I've tried vector.angle(reference-vector), but that doesn't seem to give the desired result.


texts:
I know that Chrome stopped supporting UWP a long time ago, but I recently tried to play a Unity game and I just couldn't. I tried all the browsers, even IE which UWP itself suggests, however I couldn't run it on any platform?

Can anyone play Unity games anymore, or are they all useless now?

Thanks,


texts: Skybox from file at runtime in Unity: Error assigning 2D texture to CUBE texture property '_Tex': Dimensions must match

texts:
I'm downloading skyboxes at runtime, and then I'd like to set them as the current scene's Skybox.
After I successfully downloaded the desired cubemap into the ApplicationData folder, I'm trying to set them as skybox as following:
private void LoadSkybox(string path)
{
    var skyboxMaterial = new Material(Shader.Find("Skybox/Cubemap"));

    var skyboxData = File.ReadAllBytes(path);
    var skyboxTexture = new Texture2D(2, 2);
    skyboxTexture.LoadImage(skyboxData); //..this will auto-resize the texture dimensions, if I understood it correctly

    skyboxMaterial.SetTexture("_Tex", skyboxTexture);

    RenderSettings.skybox = skyboxMaterial;
    DynamicGI.UpdateEnvironment();
}

The problem is that it fails to do so, because:

Error assigning 2D texture to CUBE texture property '_Tex': Dimensions must match
UnityEngine.Material:SetTexture (string,UnityEngine.Texture)

The loaded texture's dimensions are 700x525, and the file isn't corrupted or anything.
If I

manually import it,

set the type to cubemap,

create a Skybox/Cubemap material based on it

set this new material as the scene's skybox...

It works just fine.
Why doesn't this work?
What other solutions are there?


texts: How do I get an object from a .osg file in OpenSceneGraph?

texts:
I decided instead of using a really heavyweight engine like unreal that I am going to use SDL and Openscenegraph.

I would expect it to be something like:

osgObject* box = file->GetObject("Box");


texts:
I want to make a plane controller using SDL2. I want to use one joystick for pitch/roll. Y-axis sets the pitch-flaps, and X-axis sets the roll-flaps.
But there is one problem: Say I want to fully pitch and roll at the same time: I will hold the joystick at a 45 degree angle. But in SDL2, the joyAxis then get reported as 0.707... which is roughly half of the square root of 2. I understand why this happens: the physical joystick is restricted within a circle, so to move it up, you need to sacrifice a little bit of left/right. So the magnitude of the input vector is at most 1, instead of sqrt(2). How do I correct for this in code? I can't think of a good mapping.
I would like something like this:
float rawInput[2] = {0.707, 0.707};
float actualInput[2] = squaredCircle(rawInput); // {1,1}

rawInput = {1, 0};
actualInput = squaredCircle(rawInput); // {1,0}

What is a good squaredCircle function?


texts:
I first tried with a simple axis aligned bounding box to test my algorithm (later shape will be different but always convex 6 faces), but even this case did not work, it always tells me that the point is not inside:

                BoundingBox bb = new BoundingBox(-new Vector3(.5f), new Vector3(.5f));

                var corners = bb.GetCorners();

                bool liesInside = true;
                for (int cornerIndex = 0; cornerIndex < 6; cornerIndex++)
                {
                    Plane plane = new Plane(corners[cornerIndex], corners[cornerIndex + 1], corners[cornerIndex + 2]);
                    if (plane.DotCoordinate(rayPos) > 0)
                    {
                        liesInside = false;
                        break;
                    }
                }


texts:
I have a menu that you can navigate with the keyboard, but I also want it so you can navigate it with the controller thumb sticks. But my problem is that if you push down or up on the thumb sticks it will just fly through the menu. To fix problem if it was a keyboard you would just do: prevKeyState.IsKeyUp(Keys.Down).
So I was wondering if there anything like this for the controller thumb sticks?

I'm not sure if I'm doing something wrong but it still flies through the menu.

 private enum GamePadStates
    {
        None,
        GoingDown,
        GoingUp
    }

    GamePadStates CurrentGamePad, PreviousGamePad = GamePadStates.None;
     public void Update(GameTime gameTime)
    {
        keyState = Keyboard.GetState();
        gamePadState = GamePad.GetState(PlayerIndex.One);
        PreviousGamePad = CurrentGamePad;

        if (gamePadState.ThumbSticks.Left.Y > 0.1)
            CurrentGamePad = GamePadStates.GoingUp;
        else if (gamePadState.ThumbSticks.Left.Y < -0.1)
            CurrentGamePad = GamePadStates.GoingDown;
        else
            CurrentGamePad = GamePadStates.None;

        if (keyState.IsKeyDown(Keys.Down) && prevKeyState.IsKeyUp(Keys.Down) ||
             CurrentGamePad == GamePadStates.GoingDown && PreviousGamePad != GamePadStates.GoingUp)
        {
            if (selected < (buttonList.Count - 1))
            {
                selected++;
            }
        }

        if (keyState.IsKeyDown(Keys.Up) && prevKeyState.IsKeyUp(Keys.Up) ||
            CurrentGamePad == GamePadStates.GoingUp && PreviousGamePad != GamePadStates.GoingDown)
        {
            if (selected > 0)
            {
                selected--;
            }
        }


texts: Pressing the jump button also makes my character fire their weapon

texts:
In my game I want my player jump without firing their weapon, but when I press the button it jumps and also fires too in same moment.

In this Update method, I used Input.GetButton so my player will fire continuously while holding the button.

void Start () {
    isJumped = true;
}

// Update is called once per frame
void Update(){
    if (!transform.GetChild (0).gameObject.GetComponent<PlayerHealth> ().hasDied) {

        if (Input.GetButton ("Fire1") && Time.time > firespeed && isJumped == true) {
                nextFire = myTime + firespeed;
                newProjectile = Instantiate (projectile, transform.position, transform.rotation) as GameObject;
                nextFire = nextFire - myTime;
                myTime = 0.0F;
                //  EnergyCharging ();
            }
        }
    }

void JumpButton(){
if(!transform.GetChild(0).gameObject.GetComponent<PlayerHealth>().hasDied){
        if (grounded) {
            grounded = true;
            myRigidBody.AddForce (new Vector2 (0, jumpPower), ForceMode2D.Impulse);
            if(myRigidBody.velocity.y > jumpPower){
                myRigidBody.velocity = new Vector2 (0, jumpPower);
            }
            animator.SetBool ("isGrounded", grounded);
        }
    }
}


texts: How do you use these kind of rpg ground tileset ?

texts:
Searching about some tilesets for a little RPG game, I've often found these kind of tileset :

Their structure are special, there is two upper tile and 4 others for the same material. I understand that, like that, you have all what you need to create more various shapes than simple rectangles of different sizes. But I don't get how they are used in practice. I'm talking about the two little upper tiles that are used to make some corners. for me the 4 corners are stored inside only one tile ?  (hard to explain with my bad english but I'm sure you understand what I mean)

Also, do you know if that tilemapping technic has a name ? And do you kown if it is possible to use them directly in Tiled ?


texts: How could I implement fixed time step with Akihabara framework? I would like my avatar to move by fixed distances of one block as in Supaplex.


texts: How do you design a replay system for a frequently patched game

texts:
Possible Duplicate:
  How do you design a record/replay system for a frequently changing game?

I understand that in order for a game to have a replay system it must:

Have a deterministic engine
Record initial state
Record player inputs

The problem is, what if the game is being patched every few weeks, and these patches change significant parts of the game that can not really be abstracted into an attribute/state? Like, what if something (minor) is completely redesigned? Then you can no longer just play back older player inputs which took place when there were different mechanics on the current engine because it will lead to entirely different results.

Example: Let's say there is a bug in StarCraft that makes marines not take any damage if the damage they receive is greater than their maximum health. Later this is patched, but any replay from the time of the bug would be junk on the patched system. People would be trying to move marines that are dead in the eyes of the game, etc.

Is this reasonably solvable, given there will always be frequency patches that will make structural gameplay changes/fixes?


texts: Terminology for the way Transformation Matrix Data is treated

texts:
I recently asked a question at math stack exchange and realize a similar questions is more suited for this forum, but the original is here:

https://math.stackexchange.com/questions/1526601/terminology-for-transformation-matrices-update-or-rigid-body-transform

I'm attempting to describe transformation matrix operations within Sketchup's Ruby scripts, and I need some terminology.

Sketchup allows the selection of a group of "loose" drawing objects (i.e. edges and faces), and provides options to create a grouped object from them. The drawing elements inside the group have position data relative to the group's local coordinate system. The grouped objects respond to a getter "transformation" method that returns a transformation object that contains data representing the orientation, scale, and position of the group.

Sketchup's "world space" supports multiple grouped objects, and typically there are numerous grouped entities in the outer level entities, as well as loose drawing objects. Each grouped object has a separate transformation that determines their position, orientation, and scaling in world space.

The transformation can be altered or replaced with methods that include:

a) The "transform" method: Applies a transformation (i.e. like a rotation) to rotate the group; and

b) The "transformation=" setter method: Replaces the existing transformation with the supplied argument.

Lets say I have a grouped object called "entity1" and rotation transformation object called "rotation". To provide the same rotation effect I could perform either of the following in Sketchup's Ruby programming:

entity1.transform!( rotation )
    OR
entity1.transformation= rotation * entity1.transformation

Only groups and components support the "transformation=" setter method, while fundamental Point3d & Vector3d object provide "transform!" kind of methods. It is obvious, at least from within Sketchup (which uses OpenGL internally), that transformation matrix internal data can be treated as either:

Relative: A transformation performs an incremental operation
(Example "entity1.transform! identity" does not have an affect on the grouped model); or

Absolute: The data inside a transformation is treated as absolute position, orientation, and scaling of the grouped object.
(Example "entity1.transformation= IDENTITY" sets the model to Sketchup's origin position, the model is de-rotated to the orientation it was when first grouped, and it is descaled)

Questions:

1) What is the terminology for the type of transformation that is supplied to the "transform!" method?
I was calling it an "affine", now want to call it an "update transformation".

2) What is the terminology for the type of transformation that is the argument to the setter "transformation="?
I have been calling it a "rigid body transformation", and sometimes "absolute transform". It appears that OpenGL is calling this the "model matrix".

3) If I call it "model matrix", is more than one model matrix transform allowed in world space?

A previous english stack exchange article for a word to mean "position and orientation" is at:
https://english.stackexchange.com/questions/119883/word-for-position-and-orientation
The article responses recommend to use "pose matrix".


texts:
I need to render roads and some direction marks on top of them. I render roads as triangled geometry, same goes for marks (see picture - road is purple, mark is red, ignore z-fighting).

Problem goes for edge of road. Is too much "jagged" and not straight. Is it result of perspective projection (thats what I believe). And how can it be improved? There is no texture, colors are filled directly in fragment shader.

EDIT:

I have tried solution from duplicite answer, but jagged edges are still there. Even if multisampled EGLConfig is selected.


texts: Are there tools for testing multiplayer code?

texts: Are there reliable tools that can simulate real life-like network conditions e.g. networks with different bandwidth, different latencies, packet loss etc...?


texts: How can I serialize lists to JSON on mobile?

texts:
I'm having difficulties serializing lists with the built in JsonUtility. I eventually figured out this just isn't possible with its limited capabilities.
As much as I'd like to use Newtonsoft, I cannot use that either because this is a mobile game, and from what I understand it doesn't work on Android or iOS.
Does anyone have any suggestions for how I can serialize my lists on mobile? I don't want to have to use hacky solutions to get these lists in and out of JSON.


texts: How to create a perspective field of view matrix?

texts:
Hey, hello. I am learning a little of WebGL (OpenGL ES 2.0) through the http://learningwebgl.com tutorials, but it uses a third party library to create the View, Projection and transformation matrices (glutils.js). Well, I don't really like the idea of depending on a non standard library, so I am trying to learn how to create these matrices by myself.

I've already managed to understand most of it, and although I can't really tell why these matrices work if someone asks me, at least I know how to build them when I need to. Now I have my own lib to work with 4x4 matrices. I can create translation, scale, rotation and the lookAt matrix, but, I am having a hard time finding out how to create the perspective matrix. Anyone could help me out?

Here is my lib: http://pastebin.com/csMi9GuC


texts:
I have been following the "SFML Game Development By Example" and on chapter 2, the book was showing the example game design of a Snake game. However he didn't write the code of some header classes and didn't mention whether they should exist. I tried writing some of them but encountered an error:

sf::RenderWindow* Window::GetRenderWindow(return &m_window;)

Error: declaration is incompatible with sf::RenderWindow *Window::GetRenderWindow()

In my Window class:

class Window{

public:
    ...
    sf::RenderWindow* GetRenderWindow();
    ...
private:
    ...
    sf::RenderWindow m_window;
    ...
}

I think it is probably because of the function declaration.


texts: How can I move an object in an "infinity" or "figure 8" trajectory?

texts:
When I want to move object around point I do:

    point.x *= cosf(timer.timeElapsed);
    point.y *= sinf(timer.timeElapsed);

How to make point move on eight or infinity sign trajectory?


texts: Button reacts to the screen event in Unity

texts:
I use Unity 2019.4. I made a script so that if a make a long press on the screen of my mobile phone, my Personnal Character stops. I created a button to shoot gun too. The problem is when I make long press on that button too (shoot button), my personal character also stops. How to avoid this and use "Shoot button" only for shooting.
        if (MobileInput.Instance.LongPress)
        {
            {
                speed = Mathf.Lerp(speed, 0, 1f);
                if (speed <= 0)
                {
                    speed = 0;
                    isIdle = true;
                    isRunning = false;
                }
            }
        }


texts:
Does it make sense to carry out all audio (music, sound effects, etc.) in a separate thread?

In your experience, how large would you expect the performance impact of playing some MP3 music and 10-30 sound effects to be?

Could performance be an issue with starting to play many different sound effects (e.g. in the same frame)?


texts: I am writing a game in java which has a bike riding down a road. I intend to add some obstacles on the road which are structures having a slope, which the biker must negotiate. In other words, the bike must climb and run along the slope whenever it encounters one so obviously it must be aligned accurately with the slopy path. Im currently doing this using trig functions to find the angle of rotation, x y coordinates for the bike when it is climbing, descending etc. Can someone suggest a better algorithm to achieve this please ?


texts:
Building open this tutorial - https://code.google.com/p/libgdx/wiki/ProjectionViewportCamera
I have constructed a class for generating polygon meshes. But i cannot figure out how to render semi transparency, even though the mesh in the tutorial takes a color object with an alpha channel.

I am rendering with squareMesh.render(GL10.GL_TRIANGLE_STRIP, 0, 4);
This is the code used for initializing the mesh

if (squareMesh == null) {
    squareMesh = new Mesh(true, 4, 4,
                 new VertexAttribute(Usage.Position,    3, "a_position"),
                 new VertexAttribute(Usage.ColorPacked, 4, "a_color"));

    squareMesh.setVertices(new float[] {
        -0.5f, -0.5f, 0, Color.toFloatBits(128, 0, 0, 255),
         0.5f, -0.5f, 0, Color.toFloatBits(192, 0, 0, 255),
        -0.5f,  0.5f, 0, Color.toFloatBits(192, 0, 0, 255),
         0.5f,  0.5f, 0, Color.toFloatBits(255, 0, 0, 255) });
    squareMesh.setIndices(new short[] { 0, 1, 2, 3});
}


texts: Slope scaled depth bias with normal maps

texts:
I'm using a slope scaled depth bias to reduce shadow acne with shadow maps. However, it's causing artifacts when used with normal mapped surfaces because the bias varies over the surface, where it should really take the normal of the underlying geometry as a bias for all texels instead.

The bias is calculated like this:

float bias = 0.005 * tan(acos(dot(normal,-lightDirection)));

How can I get around this problem, when I don't have geometry information available while applying the shadow map (e.g. during lighting pass of deferred shader)?


texts: Unity game layout problem for high-aspect Android screens

texts:
I'm trying to port over a card game I wrote some years ago into Unity (2D, Orthographic). The game objects are placed correctly when I build and run in Windows, Linux, and Mac, for all the different resolutions I've tested. It also looks fine on my S7 phone (16:9 ratio). However, on my newer Android phone (18:9), the elements collide vertically. I've tried changing a bunch of parameters in Unity's canvas settings, such as Match Width/Height, UI Scale Mode, etc., and I've tried different values in the Build | Android Player settings: Aspect Ratio, start in Fullscreen, etc. but nothing is changing.

Can anyone help? I'm fine with black bars on the side to keep it at 16:9, if I can't force it to lay out the objects with vertical priority somehow.

Thanks.


texts: How is shot synchronization implemented in multiplayer FPS?

texts:
I'm building a 2D multiplayer shooter game. I have singleplayer working and started working on multiplayer part (server code,...) and there is one thing I just can't get my head around.

When player shoots someone, who is moving, and he has high latency (>200ms or something like that) how to synchronize it with the other client? I thought that the shot vector could be sent relatively to targeted player (so when he would recieve the info about the shot, he could animate the shot hitting him).

Problem is, shots can destroy enviroment or hit other players. So when I shoot a target and there aren't any obstacles, he gets hit and the packet about shot hitting him gets sent. 200ms (+ other player latency) later, other player recieves the packet, but in that time, he moved behind an obstacle.

Problem rises:

a) If the obstacle is destroyable by the shot, clients will have different map (shooting player will have map with obstacle, while the other player will have the obstacle destroyed)

b) If the obstacle can't be destroyed, other player will either complain, because he got shot through impenetrable obstacle or the shot will be shot, so shooter will think that target got hit and target won't see any hit.

I just can't find a better way to solve this. Any ideas or examples how other games did it?


texts: Comparing the scale and rotation of (otherwise) identical meshes from vertex data

texts: I am designing a tool that can read an obj file with duplicate meshes in, and export the transformation, scaling and rotation of each duplicate relative to the original model. I can establish the transform from the average of all the vertexes, and I think I can get scale by comparing the maximum and minimum x,y and z values, but I'm completely stumped on rotation. Does anyone have any advice re this?


texts: Animation Starts Before KeyDown Event Even Happens?

texts:
Recently when I started working on my first animation transition, it has a bug were the transition will occur as soon as the game begins, even though I haven't pressed the key to activate the transition. I would really appreciate any help I can get on this so I can continue creating more animations. I will include my C# code and an image of the transition below.
Thanks, Nova

using UnityEngine;
using System.Collections;

public class PlayerAC : MonoBehaviour
{
    private Animator anim;

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

    void Update () {

        if (Input.GetButton ("Fire1"))
        {
            anim.SetBool ("RunStright", true);
        }
        else
        {
            anim.SetBool ("RunStright", false);
        }
    }
}


texts:
So I'm trying to create a simple physics engine for the game I'm creating. I'm trying to add jumping to the game. To do this I used (where jumpPower is 30000):

impulses.emplace_back(0.0f, mass * World::getGravityForce() + jumpPower, 0.0f);

This creates a nice jump effect when using vsync, but when I turn vsync off the jump is low. This is caused by the fact that in lower fps rates, the velocity is less affected by gravity. In the code below, how could I fix this issue? (In a generalized way, so not just using the velocity vector instead)

A possibility could be updating physics at a fixed rate, but I don't know if that is the best solution.

At the moment forces is filled with a downward gravity, applied each frame
and impules is filled with a jump force as soon as the player presses Space. No other forces are used and only this code affects force/velocity/acceleration.

for (vec3f& f : forces)
    force += f;

for (vec3f& f : impulses)
    force += f;

impulses.clear();

//Add movement forces
velocity += movementVec/mass * delta;

vec3f new_acceleration = force / mass;
velocity += delta * (acceleration + new_acceleration) * 0.5;
acceleration = new_acceleration;


texts: Have an object rotate on its Y axis towards mouse position

texts:
I've been looking at some other answers to similar cases but not every one used different methods, and a lot of them were not what i needed, so here's my question :

What's the best/standard way to get the X and Z positions of the mouse onto a plane, so that object can rotate to look at that position?

I'm trying to get it in a similar setting to, for example "Angry Bots" where the Player is always facing mouse position.

Also, would that be camera independent? i mean, if my camera changes its angle, it would still work because it usually is a projection of the "screen" plane onto the "player" plane, right?

I'm sorry, i'm a bit overwhelmed with the many options Camera.main. has, and i'm not really sure which one should i use.


texts: How does faction work in a Multiplayer game?

texts:
I'm trying to work out how Factions would work in any Standard MMO
If the player is hostile with a faction, then the NPC's of that faction would attack on sight.
If the player is neutral> with a faction, then the NPC's of that faction wouldn't attack on sight.
The "Reputation Value" would be an integer.
Hostile = 0
Unfriendly = 2000
Neutral = 4000
Friendly = 6000
Honored = 8000
Revered = 10000
Exalted = 12000

Example:
When the player Logs in. The Bandit faction must find out the Player's Reputation Value towards them.
if Player.Bandit.UNFRIENDLY or Player.Bandit.HOSTILE:
    the NPC would be able to attack the player on-sight.
if Player.Bandit.NEUTRAL or FRIENDLY or HONORED or REVERED or EXALTED:
    the NPC won't be able to attack the player on-sight.

or
ReputationValue = Player.Bandit.Reputation

if ReputationValue > 4000
   the NPC won't be able to attack the player on-sight.
else
   the NPC will be able to attack the player on-sight.

This is more complicated than it initially appears.
Every player has a FactionList, and the FactionList ReputationValue can change potentially, multiple times per second.
For the player, it is relatively simple, they have a FactionList which contains the FactionName and FactionReputation for each Faction. Clientside, they can attack anything as long as it's 5999 or below.
But for the Enemy, Serverside. they need to check the players FactionList and not only for a single player, but for potentially hundreds of players.
For ANY entity to KNOW if they can or can't attack, they first NEED to know the SPECIFIC player's FactionList ReputationValue for their Faction.
the FactionList ReputationValue is a constantly changing value which must be obtained potentially every few seconds from Each Player.
How does this check work?
When is it performed?
How often is it performed?
I'm assuming Each Faction performs this check whenever a player logs in. Adding this players value to a list.
Performing this check as part of an Aggro-radius would be insanely inefficient.


texts: Unity: objects behaving different when NetworkTransform is used to sync movement

texts:
I am experimenting with some simple multiplayer/networking in unity. Currently I have a plane object as the ground, and a cube prefab as the player object. I have a network manager with round-robin spawn and the built-in HUD. The cube has simple movement control (up/down is forward/backward, left/right turns the cube).

I can successfully start a game, build it, and add a client from the built app. However, when movement gets sent over the wire, the non-local player cubes in the game appear to "tilt forward," seemingly from the drag that the cube creates against the plane while moving. Strangely, when moving the local cube, no such tilt is experienced.

Here is a gif which illustrates:

In the above gif, the cube being moved is in the foreground window. Notice how the cube is only tilting in the other window.

Here is Update function of the Cube controller script:

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

        // Change translation
        float moveAmount = CrossPlatformInputManager.GetAxis("Vertical");
        Vector3 deltaTranslation = transform.position + transform.forward * movementSpeed * moveAmount * Time.deltaTime;
        localRigidBody.MovePosition (deltaTranslation);

        // Change rotation
        float turnAmount = CrossPlatformInputManager.GetAxis("Horizontal");
        Quaternion deltaRotation = Quaternion.Euler (turnSpeed * new Vector3 (0, turnAmount, 0) * Time.deltaTime);
        localRigidBody.MoveRotation (deltaRotation * localRigidBody.rotation);

        MoveCamera();

    }

The ground is a plane with a rigid body and doesn't have a network identity or transform.

How do I stop the dragging from occurring and have the behavior be consistent across both instances of the game?

The full code to this project as it is right now is here: https://github.com/andyperlitch/blocks-multiplayer

Thanks!


texts: Engine Start and Stop Show Abnormal Behaviour

texts: In my game, when I pause the game using mEngine.stop() it works perfectly but when I press resume button that has code mEngine.start() it provide some movement to the physics body. So the created body does not stand at its desire position after the resuming the game. That fault I have found in other game developed by other developer also. So please provide some guidance for it. I also tried with mScene.onUpdate(0) and mScene.onUpdate(1) but I does not able to found anything new from it.


texts:
I'm coding a mechanic which allows a user to move around the surface of a sphere. The position on the sphere is currently stored as theta and phi, where theta is the angle between the z-axis and the xz projection of the current position (i.e. rotation about the y axis), and phi is the angle from the y-axis to the position. I explained that poorly, but it is essentially theta = yaw, phi = pitch

Vector3 position = new Vector3(0,0,1);
position.X = (float)Math.Sin(phi) * (float)Math.Sin(theta);
position.Y = (float)Math.Sin(phi) * (float)Math.Cos(theta);
position.Z = (float)Math.Cos(phi);
position *= r;

I believe this is accurate, however I could be wrong.
I need to be able to move in an arbitrary pseudo two dimensional direction around the surface of a sphere at the origin of world space with radius r. For example, holding W should move around the sphere in an upwards direction relative to the orientation of the player.

I believe I should be using a Quaternion to represent the position/orientation on the sphere, but I can't think of the correct way of doing it. Spherical geometry is not my strong suit.

Essentially, I need to fill the following block:

public void Move(Direction dir)
{
    switch (dir)
    {
        case Direction.Left:
            // update quaternion to rotate left
            break;
        case Direction.Right:
            // update quaternion to rotate right
            break;
        case Direction.Up:
            // update quaternion to rotate upward
            break;
        case Direction.Down:
            // update quaternion to rotate downward
            break;
    }
}


texts: How to resolve collision of two or more linearly moving non-rotating axis-aligned 2d boxes?

texts:
Sorry for my bad english.

In my game, to resolve collision of a moving-box (e.g. the player) and fixed-boxes (e.g. tiles) :-

I check in advance whether a moving-box is going to collide with a fixed-box. If yes, then start moving the moving-box in 1 unit displacement in the direction of original displacement but only after checking in advance whether the next movement will result in a horizontal or vertical collision with any fixed-box. If in the next move it is going to collide with a fixed-box horizontally, then the x side of the moving-box is resolved and no more displacement in horizontal direction. Same for the y side.

But my problem is - how to resolve the collision of two (or more) moving axis-aligned non-rotating boxes?

What other people do is update position (resolving collision in the process) of the moving-boxes individually (one box at a time). That is wrong because in a certain time all of the moving-boxes are supposed to move simultaneously. So, this would result in wrong collision resolution. People won't notice it but collision would be resolved in wrong direction.

Other people separate the boxes using a minimum translation vector which they calculate using Separating Axis Theorem. This would also result in wrong resolution since the axis might not be the  one that the boxes were supposed to be in contact with before intersecting with each other.

How can I resolve collision of two moving axis-aligned non-rotating 2d boxes correctly ?


texts: Saving Unity Custom Inspector state to a text / save file?

texts:
For the basic values I know how to do it like:

Item name (Simple string value)
Amount (Simple int value)
isNormalDrop (Simple bool value)

The problem is saving the Reflection variable (The script part near the bottom) which is of type 'UnityEngine.Object' and the GameObject variable how would I do this?


texts: How do I dynamically reload content files?

texts:
Is there a relatively simple way to dynamically reload content files, such as effect files?

I know I can do the following:

Detect change of file
Run content pipeline to rebuild that specific file
Unload ALL content that was loaded
Load all content

And use double references to reference content files.

The problem is with step 3 (and step 2 isn't that nice either). I need to unload everything because if I have model Hero.x which references Model.fx effect, and I change the Model.fx file, I need to reload the Hero.x file which will then call LoadExternalReference on Model.fx.

Has someone managed to make this work without rewriting the whole ContentManager (and every ContentReader) and tracking calls to LoadExternalReference?


texts:
I would like to know the math concepts behind shape based games like http://www.miniclip.com/games/fat-slice/en/

To be specific, I would like to know on

how to model shapes programmatically
finding areas of shapes
intersection of areas
curvy shapes instead of polygons

I searched for tutorials / guides to the best of my knowledge, but couldn't find anything appropriate.

Edit: I am looking at C++ libraries, that would support iOS / Android.