texts:
I'm trying to figure out a good way to implement dialogs (that is, talks, not UI's). My thoughts so far:

I see a dialog as a tree of sentences (or better, a forest), so I think that XML is a good choice.
There would be a XML file for each NPC. And more files for generic NPC's. Example: Peter.xml, Linda.xml, Citizen.xml, Soldier.xml, etc.
These files would look like this:

<?xml version="1.0" encoding="UTF-8"?>
<dialog npcName="skeleton">
<ops>
 <q>Hi, how are you?</q>
 Oh, thank you! It's been so long since I was last asked about that...
 Well, so and so. And you?
 <ops>
  <q>Oh, I'm fine. But you look starving. I'll fetch some food for you.</q>
  Don't worry. In fact, I have no stomach,
        so the groceries would fall to the ground if I tried to eat. For example:
        if I ate an egg, it would break for sure.
  <q>I was wandering how a skeleton can talk. And how can be 'so and so'.</q>
  What? Haven't you ever heard about undead?
  <q objectCondition="egg, inInventory" objectAction="egg, destroy"
           questComplete="eggToSkeleton">I have an egg just here. Let's try to
          see what happens.</q>
  *The skeleton eats... well, it puts the egg into its mouth. When its
          bony fingers release the egg, it begins to roll down and finally
          crashes to the ground, leaving an orange splash among the green
          blades of grass.*
  Just as I told you. But... thanks.
  <farewell mode="polite"/>
 <ops>
 <q>Begone, monster! You are an unnatural being!</q>
 Yes, I know. But it is not my fault, and I can do nothing about that. I
      can't even commit suicide!
 <farewell mode="rude"/>
</ops>
</dialog>

I have no experience with XML and I haven't found sample codes for this purpose. Am I on the right path?


texts: How to convert isometric screen space coordinates to top-down world coordinates in Unity?

texts:
I have 2d grid in a 3d world facing the world up. My camera is setup so it shows an isometric view of the grid.

I want to get the player's input in screen space (cyan) and find the same point on the grid (purple) ignoring the z position which will ultimately select the nearest tile (red square) from the input. I want to do this without using colliders as there could be hundreds of tiles in the same scene.

I want to know how I can project the screen space point into the 2d grid in a 3d world.
The image below summarizes what I want to achieve.


texts:
For intentional reasons, certain units in the game I'm currently programming don't have any collision detection and response among each other.

This enables them to clutter right on top of each other. This is a wanted behavior, since there will be situations in the game when the player does want them to stack like that.

However, I want to make the process of uncluttering them easy for the player, so that they just have to press a hotkey or click some button on the screen and have the units disperse just enough so it's easy to select a group of them with the mouse (if they stand on top of each other one mouseclick selects all units).

How could I do this without running a brute force N^2 nearest neighbor search on all units?


texts: Unity3d select empty gameobjects in scene

texts:
I have a pathing system that I am creating in Unity. When you add nodes to denote the path, I create a empty GameObject and render it in OnGUI as a square. The problem that I have is clicking on the object in the scene view. I am trying to figure out what would be the best way to click the Node, so that I can move and rotate the Node.

I had some ideas, like:

Creating a Cube or some other GameObject with a mesh, and change the layer to Node. Then make the camera cull out the Node layer.
Only in editor mode, create a temp asset and delete it before runtime.
Do a raycast and see what objects are near the click, then pick the closest one.

I have a feeling that I am putting to much thought into it, and suggestions would be greatly appreciated!!


texts: Different kinds of collision detection in Android

texts: Are there any other ways to detect collision between two objects besides the bounding rectangle method and downloading another class to put into Android?


texts: Zelda LttP (Super Nintendo) room changes?

texts:
I'm trying to make a tile-world adventure game on iOS similar to Zelda Link to the Past on SNES, and one issue I've run into is having my camera move beyond walls revealing the rooms on the other side.
I like the way Zelda handled room changes where once you went through a door the screen would slide over to show the new room, but I can't figure out how they did it.
I'm using Obj-C on my own tile-world engine, so I'm more interested in logic than code, but anything would help.

I'd also be interested to hear any alternative suggestions for limiting the movement of the camera.
(Presently I have the position of the camera restricted to the bounds of the level being drawn, but in order to reduce loading I've decided to increase the size of levels to put multiple rooms/floors on the same map.)

Edit
One of the key things that the transition I am asking about offers is the ability for the player to leave the center of the screen. I think that you lose a sense of motion or progress when the player is always dead center in the screen. My camera is designed to stop moving at the world bounds, but I'm having trouble figuring out how to define 'room bounds' within a world for the camera to stay within until triggered to move.

I also recognize how transitions break up gameplay, but when you're dealing with a top-down 2D adventure game, if you want to conceal the contents of the next room over and also allow for some range of motion free of the camera, I'm not sure what better way there is.


texts:
I am developing an isometric game like Anno 1602.
I have an isometric tilemap. The default tilesize is 64x31.
My goal is to show the area a building has influence to. For that I want to show a circle in isometric style around that building. Look at the picture below:

I need to find an algorithm which turns information about a building (width, height, radius in tiles) into a polygon containing screen coordinates of the outer parts of the dark area (see picture, I want the red points). For example, the data for the picture above would be:
w = 2;
h = 2;
r = 3
I tried creating circles with midpoint algorithm for each tile of the building. Merging all points together and running concave hull algorithm to get the outer most points. But this did not yield nice results.
What could be an approach to get points to create a polygon which resembles an isometric area around an object.


texts:
I am developing an application that has to take STL files from users. However, some modeling programs seem to invert some of the surface normals. Basically some surface normals will be facing inward rather than outward.

I have to make a component that will correct the surface normals, and write these corrections to file.

Otherwise, later steps with the model will fail.

I have heard that the surface normals can be calculated from the winding information.

What is the best way to go about correcting these surface normals?

I am using OpenGL with QT for Window management.


texts: How to solve photon lobby error in unity?

texts:
I need urgent help i am trying to build a online multiplayer game in unity but i am unable to solve error my console is showing no error but when i put my script in use it works fine in editor but not running after build means build crash every time.
Please help someone urgently.


texts: How much freedom should my players have regarding naming characters?

texts:
I'm currently developing a text based adventure game (original, eh?). I'm not sure how much freedom they should have in character naming.

I've thought of three options:

Option 1:
Predetermined names for all characters. The player is told of people's names.

Option 2:
Predetermined names for most characters. They are introduced in certain situations. The player picks their own name, and their best friend's name, etc.

Option 3:
The player picks everyone's name that they meet. If the person is killed before they are introduced (e.g. if someone is held at gunpoint and you pull the trigger), then their name is not needed to be known.

If you have any better ideas, say them. The easiest would be the first, but the second will make the player feel more involved but I think the third is too much and would become tedious.


texts: How to make obstacles spawn randomly but still leave a way for player to pass?

texts:
I'm trying to make a game like Crossy Road:

In this game, you control the character(the frog in this case) to go across the streets, and you have to prevent your character from being hit by a car.

There are also  "footpaths". On the footpaths there are trees act as stationary obstacles and you can't go through them.

I tried to make a similar game but I have a problem:

The obstacles prevent the player from getting further. What can I do to make sure that the player always has at least one way to pass through?


texts: I'm looking for suggestions on easy or simple art styles that can be created by anyone. It would be for a 2D game, but pixel art isn't really my thing. An example from a game would help. Thank you very  much.


texts:
If I'm going to draw cubes effectively, I need to get rid of the numerous amounts of draw calls I have and what has been suggested is that I create a "mesh" of my cubes. I already have them being stored in a single vertex buffer, but the issue lies in my draw method where I am still looping through every cube in order to draw them. I thought this was necessary as each cube will have a set position, but it lowers the frame rate incredibly.
 What's the easiest way to go about this? I have a class CubeChunk that inherits Microsoft.Stuff.DrawableGameComponent, but I don't know what comes next. I suppose I could just use the chunk of cubes created in my cube class, but that would just keep me going in circles and drawing each cube individually.

The goal here is to create a draw method that draws my chunk as a whole, and to not draw individual cubes as I've been doing.


texts: Is running cron jobs every minute a good practice for browser-based games?

texts:
I'm trying to create a browser-based game (made in PHP, MySQL, Js, HTML, and CSS) that is heavily dependent on user's actions being carried out after a certain amount of time passed whether online or offline. Will running cron jobs every second/minute a good practice or a solution to my problem?

Please check out this question first before answering, I ask this new question to focus more on the pros and cons of using cron jobs. To be more specific, here's a list of the things that I want to know:

Scalability? Up to what extent?
Performance? How fast? How slow?
Server Overhead? Will a normal server be able to accommodate the load?

Assuming the game will be an MMO.

I appreciate all the help people! Thanks in advance!


texts: Should there be a specific link between the characters height as well as the tile size for the tile maps? That is if a tile is 32x32 does that mean that a character sprite has to be the same size? Also does the size of tiles I use have any great impact on the game itself?


texts: Game Programming Gems series still of value?

texts:
Former Nintendo dev Mark DeLoura wrote a series of books called "Game Programming Gems".

(http://www.satori.org/game-programming-gems/)

Do these books still contain valuable concepts, considering where games are today, the engines that are available, etc?


texts: I am developing clone of Bomberman game and I am experimenting with different types of AI. First I used searching through state space with A* and now i want to try different approach with Minimax algorithm. My problem is that every minimax article i found assumed players alternates. But in Bomberman, every player make some action at the same time. I think i could generate all possible states for one game tick, but with four players and 5 basic actions (4 moves and bomb place) it gives 5^4 states at first level of the game tree. That value will raise exponentially with every next level. Am I missing something? Are there any ways to implement it or should i use totally different algorithm? Thanks for any suggestions


texts: Suggestions to start a cross-platform project

texts:
I have a big project in my head, it should be cross-platform (Win, Max and Linux), online (Client - Server) and with 3D graphics. I would like some suggestions to start with the right things.

Currently I'm a PHP/MySQL coder, I used to code in C and Pascal on DOS ages (Borland Times ;)), my C knowlegde need a refresh but it's ok.

I guess C++ it's the right language. What platform and what i should use to code? I can choose from all three platforms. My idea was to use Visual Studio 2010 C++, but i'm not sure if it support Native code.

What kind of libraries should i use? I guessed OpenSSL for the login, OpenGL for graphics part. For the Audio or the GUI?  Any other suggestions are well accepted.

I know it's a "BIG DEAL" but I have no rush and it'll be a free-time project, only for my pleasure.

Thank you in advance.


texts: How can I keep a GUI on-screen without moving/resizing it according to camera motion?

texts:
I'm trying to make a GUI library with SFML, and everything's done except for one problem: making the interface stay still even when the camera moves or zooms in and out.

This would be easy to fix if zooming wasn't possible, but zooming out means having to scale the contents of the interface up so it doesn't shrink, which causes it's text/images to become blurry.

Does anyone have a way to get around this issue (preferably only using SFML as I don't want to make my library OpenGL-dependent)?


texts: I'm pretty interested in game development and I've tried a couple of platforms and languages. Including libgdx and game maker studio, all without any real success. I'm currently using unity and it's the farthest I have ever gotten, but it just doesn't feel right. I follow tutorials and learn how to do certain things, but it just feels like I'm a parrot learning a new word I don't really understand what I'm doing just kind of memorizing stuff. I'm trying to become a good game developer, but I just don't know how to practice c# in a way where I will gain actual understanding and not just memorize a bunch of syntax. Thanks in advance I really need help.


texts:
From Wikipedia the (image) conversion degrees / radians shows the quadrants so that the increase of radians causes a counter-clockwise rotation but when using the following code the sprite is rotated clockwise:

rotation = (rotation + 0.5f) % MathHelper.ToRadians(360);
...
spriteBatch.Draw(sprite, sprite_center_other_sprite, new Rectangle(0, 0, 50, 50), Color.White, rotation, new Vector2(width/2, height/2),1.0f, SpriteEffects.None, 0.0f);

Why? The direction is a convention or XNA is different?


texts: Best way to implement Finite State Machine for player character in Unity?

texts:
I'd like to implement the player in my game as an FSM as described in this guide to programming patterns in games.

What is the best way to accomplish this? Should I implement each state as a monobehaviour with a state interface that can be enabled/disabled when the state transitions? Or would it better to the states as plain classes (with their own Update method) where the main player monobehaviour calls StateName.Update() from its own Update method (.e.g. void Update() { currentState.Update() })


texts: Getting "Non-invocable member 'items.item' cannot be used like a method." when invoking a class

texts:
I have my item class (items.cs) not attached to any gameObjects, I want to use items for all items in my game so I can use arrays as inventories.

I have Stone.cs which is attached to a gameObject. On the line inv = items.item(100f, "Stone", "Rock used for building"); I get a compiler error Non-invocable member 'items.item' cannot be used like a method. I am confused by this as I copied it from the Unity class tutorial, just splitting creating the item to another script.

items.cs

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

public class items : MonoBehaviour{
    public class item{
        public float iQuan;
        public string iName;
        public string iDesc;

        public item(float iQ, string iN, string iD){
                iQuan = iQ;
                iName = iN;
                iDesc = iD;
        }

    }
}

Stone.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Stone : MonoBehaviour {
    // Use this for initialization
    public items.item inv;
    public float iMax;
    public float iCur;
    void Start () {
        inv = items.item(100f, "Stone", "Rock used for building");
    }

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

    }
}


texts: Change opacity for texture or sprites in XNA

texts: Is there a way to change the opacity or transparency for a texture or sprite?


texts: How to make the snake bodyParts follow same places and directions as the player on a curved surface?

texts:
I try to make a game like the classic snake game but on a round ground (Earth). On a plane, the script works well, but when i moved it on a sphere, the bodyparts (prefabs), are not working good as you can see in the picture ( they are going right/left, but they do not sit on the spehre and i tried already to use sphere collider, box collider, rigidbody) and i dont know really how to make it so that they will follow 100% correctly the player. Thanks for help! :/ . Here i put the script for the Player and bodyparts:
using System.Collections;

using System.Collections.Generic;

using UnityEngine; using UnityEngine.UI;

public class PlayerMovementScript : MonoBehaviour {

protected Joystick joystick;
public float speed;
[SerializeField] private float turnFactor;
[SerializeField] private Transform planet;
public List<Transform> bodyParts = new List<Transform>();
public float minDistance = 0.25f;
public int beginSize;
public float rotationSpeed = 50;
public float timeFromLastRetry;
public GameObject bodyprefabs;
public Text currentScore;
public Text scoreText;
public GameObject deadScreen;
private float dis;
private Transform curBodyPart;
private Transform PrevBodyPart;

public bool isAlive;
 void Start()
{
 joystick = FindObjectOfType<Joystick>();
 speed = 3f;
 StartLevel();
}
public void StartLevel()
{
 timeFromLastRetry = Time.deltaTime;
 //deadScreen.SetActive(false);
 for (int i = bodyParts.Count -1; i > beginSize; i++)
 {
     Destroy(bodyParts[i].gameObject);
     bodyParts.Remove(bodyParts[i]);
 }
 bodyParts[0].position = new Vector3(0, 0.5f, 0);
 for (int i = 0; i < beginSize - 1; i++)
 {
     AddBodyPart();
 }
 bodyParts[0].position = new Vector3(0, 0.5f, 0);
 bodyParts[0].rotation = Quaternion.identity;
 currentScore.gameObject.SetActive(true);
 currentScore.text = "Score: 0";
 isAlive = true;
}
void Update()
{
 if (isAlive)
       Move();
 if (Input.GetKey(KeyCode.Q))
     AddBodyPart();
 //RotateAroundPlanet();
 var rb = GetComponent<Rigidbody>();
 //rb.velocity = new Vector3(joystick.Horizontal * 100f, rb.velocity.y, joystick.Vertical * 100f);
}
public void Move()
{
 float curspeed = speed;
 //if (Input.GetKey(KeyCode.W))
 //    curspeed *= 2;
 bodyParts[0].Translate(bodyParts[0].forward * curspeed * Time.smoothDeltaTime, Space.World);
 if (Input.GetAxis("Horizontal") != 0)
     bodyParts[0].Rotate(Vector3.up * rotationSpeed * Time.deltaTime * Input.GetAxis("Horizontal"));
 for (int i = 1; i < bodyParts.Count; i++)
 {
     curBodyPart = bodyParts[i];
     PrevBodyPart = bodyParts[i - 1];
     dis = Vector3.Distance(PrevBodyPart.position, curBodyPart.position);
     Vector3 newpos = PrevBodyPart.position;
     newpos.y = bodyParts[0].position.y;
     float T = Time.deltaTime * dis / minDistance * curspeed;
     if (T > 0.5f)
         T = 0.5f;
     curBodyPart.position = Vector3.Slerp(curBodyPart.position, newpos, T);
     curBodyPart.rotation = Quaternion.Slerp(curBodyPart.rotation, PrevBodyPart.rotation, T);
 }
}
public void AddBodyPart()
{
 Transform newpart = (Instantiate(bodyprefabs, bodyParts[bodyParts.Count - 1].position,
 bodyParts[bodyParts.Count - 1].rotation) as GameObject).transform;
 newpart.SetParent(transform);
 bodyParts.Add(newpart);
 currentScore.text = "Score: " + (bodyParts.Count - beginSize).ToString();
}
public void Die()
{
 isAlive = false;
 scoreText.text = "Your score was: " + (bodyParts.Count - beginSize).ToString();
 currentScore.gameObject.SetActive(false);
 deadScreen.SetActive(true);
}


texts: How do I make one of my objects break into random pieces? I've tried Add-Ons, Blender, and a few other things that I can't remember of the top of my head.


texts: How to design player attribute updates in persistent game worlds?

texts:
Take a game with a persistent state that can continue even when players are not online. E.g. your player enters into a fight and loses some health points which are replenished 1 point every five minutes. There are a number of ways to implement this "update stuff even when the player isn't logged in" scenario. E.g. run a server-side background worker that performs scheduled updates (e.g. +1 to health) once a second.

Or, forgo the background worker and store the next-update-time for an attribute (e.g. health) in your Player model. Then, anywhere you fetch/get a Player, perform any attribute updates lazily. That is, if the next-update-time is earlier than the fetch/get time (e.g. "now"), update the attribute and then return the updated Player.

My goal is to make this system as simple as possible.

What are your thoughts? How would you do this?


texts:
I'm developing a real time, tile-based RTS. This is an example map:

This map consists of 4 regions with 256 tiles each. Blue tiles represent obstacles. Units can move in the standard eight directions. Units are bound to tiles; one tile can hold one unit.

These are some examples of the ideal paths I'm looking for. Typical A* stuff:

My question is: Is a navigation mesh applicable to a tile-based RTS? I've only seen navigation maps used in games where units are free-moving and not bound to a grid of tiles. What would the navigation mesh look like on this particular map? An example image would be excellent.


texts:
I implemented the IPointerClickHandler in a script that runs on multiple GameObjects in my scene. I'm definitely missing something since the implementation is not being called at all. The objects are not UI elements. Here is the implementation of the interface :

 public void OnPointerClick(PointerEventData eventData)
 {
      Debug.Log("clicked on " + eventData.selectedObject.name);
 }

Can I even use the EventSystem with normal GameObjects? If I can how do I do it.

What i tried: Adding a BoxCollider2D to the object, using the event trigger component on the object calling a public method.

Edit: I was missing a raycaster on the main camera.


texts: Object coming from far away effect in 2D

texts:
I have a path made using segments of sine wave interpolation put together that is drawn flat on the screen. And I would like to give the path the effect of coming towards the player. I tried to draw what I want to do, left is what I have now and right is the desired effect:

so the "farther" away the end of the segment is the smaller it's scale is and the segments are closer together. I think this would give the effect I'm looking for but I'm not sure how to do it.

This is the code I use to create a segment. It keeps track of the last point of the segment so the next segment can start from there.

private void createSegment() {
    int g = r.Next(i, i + 240);
    for (float j = 0; j < 1f; j += 0.01f) {
        Points.Add(new Vector2(CosineInterpolate(lastX, g, j), startY));
        startY--;
    }
    lastX = g;
}


texts: Why the canvas position is affected by screen resolution in Unity?

texts: I meet an issue that if I use 1024x768 resolution to run my game, the position(not local position) of the canvas is -1 in z axis. On the other hand, with resolution of 1136x640, the position is -5 in z axis(I never use code or anything to change its position). Is there any reason to cause this issue?


texts: How to apply Buoyant force to a Box2d body?

texts:
I have been following a formula to calculate the buoyant force needed to apply to a dynamic body to be able to simulate water.

  Fb = ρgV

Fb - is the buoyant force
ρ - density of the liquid
g - gravity
V - volume of the object

My box2d body will always be submerged to the sensor so I don't have to detect what portion of the body is in the water, basically the entire body is always in the water and I will always apply the force to the center of the body.

body.applyForceTocenter(0, Fb, true);

If I apply the force on upon collision to the censor then it will just fall cause there is not enough force, and if I type this to the render method then the body will fly cause there is too much force. So how do I implement the force? and how to compute for the drag? so that it won't bounce.


texts:
I'm trying to make a clean and advanced Material class for the rendering of my game, here is my architecture:

class Material
{
    void sendToShader()
    {
        program->sendUniform( nameInShader, valueInMaterialOrOther );
    }

private:

    Blend       blendmode;      ///< Alpha, Add, Multiply, …
    Color       ambient;
    Color       diffuse;
    Color       specular;
    DrawingMode drawingMode;    // Line Triangles, …
    Program*    program;
    std::map<string, TexturePacket> textures;   // List of textures with TexturePacket = { Texture*, vec2 offset, vec2 scale}
};

How can I handle the link between the Shader and the Material? (sendToShader method)
If the user want to send additionals informations to the shader (like time elapsed), how can I allow that? (User can't edit Material class)

Thanks!


texts: How to connect a GUI button to function?

texts:
I am developing a new Roblox game where you can setup and control you're own virtual machine using SurfaceGUIs on a modeled screen. I am trying to make a confirmation GUI
where if you click YES, then it starts the VM, and if you click NO, then it closes the GUI and doesn't start a VM. But when I click on NO, nothing happens! Here is my code:
local gui = script.Parent.Parent
local button = script.Parent

local function cancel()
    gui.Visible = false
end

button.Activated:Connect(cancel())

Please help!
P.S: The confirmation frame is in the ScreenGUI, the button is in the frame, and the LocalScript is in the button.


texts: 2D Matrix Transformation (with a Player and Ground)

texts:
I have a simple game that I'm trying to do for learning purposes, but Matrices are a bit hard, especially in DirectX.

I currently have a tilesystem that renders tiles at the screen and a character position at the center (on startup)

When the player move to the left, the ground should move to the right so he's always at the center of the screen. I use a Sprite to transform the Tiles and the player, but having trouble because the ground is moving and the player stands still on the ground still positioned at the center.

This is a topdown 2D game so I only need to transform Position (and perhaps rotation)

My Camera class has this method:

D3DXMatrixTransformation2D(&View, NULL, 0, &Scale, &Center, D3DXToRadian(Rotation), &Position);

I've also tried (for the Camera):

D3DXMatrixTranslation(&View, Position.x, Position.y, 0);

then when I render the ground sprite I set it to transform to the camera, but the Player has it's own Matrix that I use when he's moving.

Exactly like the one above but with his position, rotation and such...

What am I missing and what do I need?

I only have a tilesystem that fits the width/height of the screen so I should see when he's moving but he's standing still at the center and the ground and the player is moving.

Do I need to invert the matrix so that the ground moves in the opposite direction?


texts:
Read some threads, basically with following command:
TexturePacker filename.pvr.ccz --sheet filename.png --data dummy.plist --algorithm Basic --allow-free-size --no-trim

you can convert ONE pvr.ccz to ONE png. But how do I do this with multiple pvr.ccz files? and without changing its filename?


texts:
I'm trying to export a (.max) file to openCOLLADA (.dae). Whenever I do this, 3dsmax crashes and produces this error:

  An error has occurred and the application will now close.
      No scene changes have occurred since your last save.

3dsmax then crashes but the COLLADA file is still produced. Whenever I try opening this COLLADA file in other software though, it comes up with a bad mesh data error. This is leading me to think that it wasn't exported correctly out of 3dsmax. Any advice?


texts: Checking if bullet collides with enemy when I know the start X & Y, the angle, the speed and dist traveled of the bullets

texts:
This is the bullet I create when a player clicks to attack

var angInRadians = Math.atan2(data.y - playerArr[i].y, data.x - playerArr[i].x);//data.y & data.x is mouseY and mouseX
var temp = angInRadians * (180/Math.PI);
        function newBullet() {
          this.attack = temp;
          this.playerX = playerArr[i].x;
          this.playerY = playerArr[i].y;
          this.speed = 10;
          this.traveled = 0;
        }

Then in my game loop I do this

for(var j = 0;j<playerArr[i].bullets.length;j++)
    {
      playerArr[i].bullets[j].traveled += playerArr[i].bullets[j].speed;
    }

Then to draw the bullet I am doing this

ctx.translate(playerArr[i].bullets[j].playerX, playerArr[i].bullets[j].playerY);
        ctx.rotate(playerArr[i].bullets[j].attack * (Math.PI/180));
        ctx.fillStyle = 'black';
        ctx.fillRect(playerArr[i].bullets[j].traveled, 0, 4, 1);

Then for the players I just have a usual player X and Y and I can't figure out how to check if the bullet is within the area of the player, if you need any more code just ask/If you want to see how the game is working here.


texts: Unity3d: calling a web service in unity editor works, but not in standalone. Why?

texts:
I have this line of code:

   SDE3D _webService = new SDE3D();
   int result = _webService.UserLogin(txtLoginUsername.text, hashString);

My UserLogin function looks like this:

[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.something.com/UserLogin", RequestNamespace="http://www.something.com/", ResponseNamespace="http://www.something.com/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public int UserLogin(string username, string password) {
    object[] results = this.Invoke("UserLogin", new object[] {
                username,
                password});
    return ((int)(results[0]));
}

In the Unity Editor it works well.

At runtime, in my Unity game build, it doesn't work and doesn't return any error message!

What is the issue?

Thanks


texts:
I just made my first game, a clone of Pong, using OpenGL and C++. But its using ~50% of the CPU, which I guess is very high for a game like this. How can I improve that? Can you please look up my code and tell me what all things I am doing wrong? Any feedback is welcome.

http://pastebin.com/L5zE3axh

http://pastebin.com/rMJ6PG9k

Also it would be extremely helpful if you give some general points on how to develop games in OpenGL efficiently..

Thanks in advance!

EDIT 1:

I forced VSync on from CCC, and now the game just shows ~5% CPU usage, except when my own wait() method is called (my fault). I can solve that...but now another problem has come, the game feels very choppy and its not smooth after forcing on VSync.
Maybe tearing because of single buffering?

Any ideas?

EDIT 2:

Was calling the display callback twice from my idle function, using display() and glutPostRedisplay()! Also, changed the mode to GLUT_DOUBLE, now Fraps works on it..

One more thing! This game is working fine with VSync on (or forced) at 60fps.. but when I turn off VSync, it goes too fast. Do I have an option to turn on VSync? Or is any any other way?


texts:
i need to import model from two separate files.

I have

dog.mesh
pet.material

dog.mesh contains vertices (converted to GeometryContent) and string "pet.material" (reference to .material file)

My MeshImporter that handles .mesh files returns NodeContent (one of children should be MaterialEffectContent)

Problem is, that in ContentImporter there is nothing to handle loading of additional assets.

Should pet.material be build by content pipeline in some way? To EffectMaterialContent for example. (Now i build it into MaterialDescription by MaterialImporter - contains string reference to .fx file)

The question is, can you even do things like this in xna? Split something that xna expects to be in one file (MeshContent) into two?


texts:
I use sampler2DShadow when accessing a single shadow map. I create PCF in this way:

result += textureProjOffset(ShadowSampler, ShadowCoord, ivec2(-1,-1));
result += textureProjOffset(ShadowSampler, ShadowCoord, ivec2(-1,1));
result += textureProjOffset(ShadowSampler, ShadowCoord, ivec2(1,1));
result += textureProjOffset(ShadowSampler, ShadowCoord, ivec2(1,-1));
result = result * 0.25;

For a cube map I use samplerCubeShadow:

result = texture(ShadowCubeSampler, vec4(normalize(position), depth));

How to adopt above PCF when accessing  a cube map ?


texts: Cocos2d rotating sprite while moving with CCBezierBy

texts:
I've done my moving actions which consists of sequences of CCBezierBy. However I would like the sprite to rotate by following the direction of the movement (like an airplane). How sould I do this with cocos2d?

I've done the following to test this out.

    CCSprite *green = [CCSprite spriteWithFile:@"enemy_green.png"];
    [green setPosition:ccp(50, 160)];
    [self addChild:green];

    ccBezierConfig bezier;
    bezier.controlPoint_1 = ccp(100, 200);
    bezier.controlPoint_2 = ccp(400, 200);
    bezier.endPosition = ccp(300,160);

    [green runAction:[CCAutoBezier actionWithDuration:4.0 bezier:bezier]];

In my subclass:

@interface CCAutoBezier : CCBezierBy

@end

@implementation CCAutoBezier

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }

    return self;
}

-(void) update:(ccTime) t
{
    CGPoint oldpos=[self.target position];
    [super update:t];
    CGPoint newpos=[self.target position];

    float angle = atan2(newpos.y - oldpos.y, newpos.x - oldpos.x);
    [self.target setRotation: angle];
}

@end

However it rotating, but not following the path...


texts: Would seam carving/liquid rescale make changing aspect ratios easier?

texts:
Seam carving is an algorithm which allows for resizing images without major distortions. I think it might help to make games which would adapt to different aspect ratios/resolutions much easier. But am I right?

You can watch this presentation to see how seam carving works for videos.


texts: What are the basic equations in 2D physics collisions?

texts:
I'm making a 2D fighter, and I have gotten a basic engine, but right now I need to add the collisions, but I'm sure a basic AABB check will not be enough.

I'm sure it needs some basic 2D physics equations, but every resource I see on the web is extremelly complex or try to teach you everything you need to know to make a 2D physics engine.

So far, I'm sure it's related to momentum and forces, but don't know if those are enough for a 2D collision in a fighting game and what are the simplest ways to implement them.


texts: How should matrix-based Parallax Scrolling work?

texts:
The question is at the end, as it requires a bit of context.

I'm not sure if my understanding, my code, or LibGDX's ParallaxCamera is wrong.

LibGDX's ParallaxCamera uses Matrix4s to achieve a parallax effect by transforming the vertices used in a SpriteBatch#draw call.

Depth is modelled as a float between 1 and 0. 1 means move directly proportionally to the camera; 0 means never move; 0.5 would move half as fast as the foreground.

Suppose I have a screen of 320x240. My camera is pointing at 160,120. What should be the screen coords for the following things?

World Coords    Depth    Screen Coords?
0,0             0,0      0,0

160,0           0.5,0    160,0
320,0           0.5,0    240,0

160,0           0.75,0   160,0
320,0           0.75,0   ???,0

160,0           1,0      160,0

I was expecting that if the camera is at X:160, then all things with world coords with X:160 should be drawn at screen coords with X:160. My thinking is that effectively that means everything should be 'lined up', and that moving the camera should give the impression of them all moving away from that point at different rates.

As it stands, my code is drawing something with X:160 and xDepth:0.5 at screenX:240. I don't think that's right, but I don't know if I'm misunderstanding what should happen, my code is wrong, or if the camera is wrong :(


texts: Sparse Voxel Octrees which parts on GPU or CPU?

texts:
I'm currently doing research into building my own voxel engine and found a lot of articles mentioning SVOs as the best mechanism. I just wanted to know that I understood the algorithm correctly, before I implement it.

I read my data into an octree on the CPU, maintained through standard node->children constructs. With that I can do collision detection, frustum culling, etc.

For rendering the octree is then written to a texture and processed by vertex and pixel shader to display the actual voxel directly on the GPU. Although I guess I could walk the octree on the CPU, and instead of building the texture, draw the individual voxels through instancing although probably a bit slower.

Is that correct or did I misunderstand?


texts: LibGDX: Best Texture Sizes to use for highest resolution?

texts:
I have two texture atlases: 1 is 1024x1024 (mostly used for GUI elements), the other is 2048x2048 (for game objects like characters).

I used Texture filter mip map linear on them. But when the textures (GUI textures) show up on my phone, they are blurry and vaseline-ish. The bigger textures (found on the 2048x2048) show up much more pristine and sharp.

How do I get the GUI ones to show up sharp? Do I simply have to make the textures large? If I do, wouldn't having two different 2048x2048 textures cause performance issues on an average phone?


texts: Create an atlas texture in photoshop to use in unity

texts:
To create a button in NGUI looks like we need to create something called Atlas that is a material that contains a lot of little images called Sprites.

I created a set of 40 sprites (for 20 buttons needed in game, normal state and clicked state) in photoshop in a 2048x2048 image file. When i tried to use NGUI atlas maker i realized that atlas maker requires each sprite in a separate file and wants to merge them in the atlas itself!

Well, i already have them in one file, should i slice all these buttons and save them in 40 other  separate files and let the atlas maker merge them again for me? (Sounds very stupid!)

Isn't there any way to give the merged 2048x2048 file to atlas maker (or any other equivalent plugin/software) and then tell the software "Hey! I have 40 sprites in this image, let me tell you where they are! The first one is in (3,3) with size of (150px, 150px), The second one is..."?

UPDATE: I found a part of solution, unity could identify my 40 sprites in texture using sprite editor tool, but NGUI cannot still find them.

I created a material using "Unlit/Transparent Colored" shader and referencing the atlas to it, then i created a new empty game object, added UI Atlas component to it and referenced the material in it, but it says there are no sprites. If i make a prefab out of this game object then NGUI can use it as an atlas and my problem will be solved


texts: OpenGL - drawElements 2D imposible z-sorting (textured)

texts:
I am creating a 2D program in OpenGL 3.2 Now to render what I do is have a VBO for each texture and add the elements of the objects that use that texture to this vbo. Now as you know the order you render objects will be the (fliped) order you see them on the screen.

Here is the problem, as you know its possible to sort objects by their Z value in the same VBO (by inserting them to the vbo according to their Z value). But when you want to sort them between VBOs thats impossible because they have to be in the correct VBO to have the correct texture, Meaning the VBOs that are drawn last will have positive Z value priority over VBOs that are drawn first.

This causes the Z value to transfer from the actual objects, to their textures and makes the Z value be grouped for all objects that use the same texture.

That was kinda confusing so to recap, because of the way VBOs work this is what is going to happen:

Turtule texture id 1

Box texture id 2

(Each textures has its own VBO)

There is one turtle and one box, the turtle (z = -1) is behind the box (z = 0) . if I render the box VBO then the Turtle VBO
What will happen is we will see the turtle over the box even though it has a z value that is less then the box.

Here is some art I drew to help you visualize the problem:

^^^ That makes the Z value of the actual turtle meaning less compared to the " Z " value of the VBO. This can be worked around by having a Z value for each VBO but that limits the program because if the Z of the boxes is bigger than turtles no matter what every turtles is gonna be hidden behind every box. And its a stupid way of doing it.

So finally to the question:

  What can I do to fix this, to have a meaning full Z value to each
  OBJECT.

Notes:

I cannot draw the object individually because I use drawElements and
because I add them to texture coresponding VBOs to reduce the VBO
count and texture binding count.

Stuff I have tried* : I have tried using the actual opengl Z-buffer, but I cannot blend layers because of that so its not a solution.


texts:
Basically I am working on side scrolling 2d game. For that I want to check whether player is collided with wall. I have written some code for it but can't able to decide where I have done stupid mistake. So please guide me in this. If you need any more details then I am always available.

Code for detecting wall :

 RaycastHit2D hit = Physics2D.Raycast (wallCheck.position, Vector2.right, wallCheckDistance);

     if (Physics2D.Raycast (wallCheck.position, Vector2.right, wallCheckDistance)) {
         Debug.Log ("collider name : " + hit.collider.name);
         isDead = true;
     }

     Debug.DrawRay (wallCheck.position, Vector3.right * wallCheckDistance, Color.red);

Following image gives you all idea about situation. In that I have allocated player with groundCheck and wallCheck flag. At present in wallCheck section, I am detecting ground as collider response after execution of above code. Above code I have placed in Update method for continuous checking.

For this game, I want to do game over if wallCheck object detect any object in collision.

Why wallCheck object detecting collision of ground object (stage1a)? That is big question of mine.


texts: How do you create fnt (angelcode format) files from existing bitmaps?

texts:
I often gets the same problem: Someones creates a nice bitmap font for me in form of a sheet nicely formated into a png, like this:

...and i need to create the angelcode .fnt atlas for using it (into Unity, libGDX, or countless other engines).

Yet, every time I google it, I stumble upon dozen of tools that create .fnt files from rasterized TTF fonts. (BMFont, Fontbuilder, etc.) Correct me if i'm wrong but they don't support exsting images, they always start by generating one from a vector font.

I end up semi-manually creating the file with an ugly script (the format is quite simple), but it's incredibly tedious. Surely there is a much better way to do that? Especially for monospaced fonts which are very easy to partition...

edit: I've made a small javascript tool to solve that. if by any chance you're interested, it's here : http://fontcutter.fbksoft.com/


texts: Position Unity UGUI ScrollRect Content Position from Script

texts:
I have a map in my game the user can interact with. I am using Unity UGUI ScrollRect to let the user move the map on the screen. Only one area of the map is visible at a time and you can scroll it to get to the desired level (just like in King games). The content of this map system is an Image and level buttons which are all children of the map image.

I want my ScrollRect to point to the current active level when the map loads. For example, if I am on level 30 then on loading the map level the content of the ScrollRect should be on the portion of the map where level 30 is.

I can't find anything regarding managing ScrollRect's content position


texts: How to make multiple types of game objects destructible

texts:
Problem
I have a set of various objects on my map that I would like to make destructible. Basically, they are split into 3 parent objects - plants, buildings and moving objects. Each parent contains 100+ children. So, if I shoot an object or objects, it/they should suffer certain amount of damage, and if the damage is critical then get destroyed.
So, I have created a single script called Damageable and added it to every child described in the previous paragraph as below:
Damageable.cs
public class Damageable : MonoBehaviour
{
    private float m_CurrentHealth;
    private bool m_Destroyed;
    ...

    public void TakeDamage(float amount)
    {
        m_CurrentHealth -= amount;

        if (!m_Destroyed && m_CurrentHealth <= 0f)
        {
           HandleDeath();
        }
    }

    ...

}

Then, in my ShellHit script, I retrieve a list of affected Damageable objects and cause them damage via TakeDamage method.
ShellHit.cs
public class ShellHit : MonoBehaviour
{
    ...
    private void OnTriggerEnter(Collider other)
    {
        Collider[] colliders = Physics.OverlapSphere(transform.position, m_ExplosionRadius, m_DamageableMask);

        foreach (Collider collider in colliders)
        {
            Rigidbody targetRigidBody = collider.GetComponent<Rigidbody>();

            targetRigidBody = collider.GetComponent<Rigidbody>();
            if (!targetRigidBody)
            {
                continue;
            }

            targetRigidBody.AddExplosionForce(m_ExplosionForce, transform.position, m_ExplosionRadius);

            Damageable damageable = targetRigidBody.GetComponent<Damageable>();

            if (!damageable)
            {
                continue;
            }

            float damage = CalculateDamage(targetRigidBody.position);

            damageable.TakeDamage(damage);

            ...
        }
    }
    ...
}

Question
Is it a common practice in Unity what I'm doing by adding the same script to every game object or is there a more common/efficient way of doing the same? For instance, by adding the script to a parent object and make it handle the damage for its children.


texts:
One of our testers on Linux reported long load times. In looking through the player log, I noticed that there are several errors about BC7 textures:
WARNING: RGBA Compressed BC7 UNorm format is not supported, decompressing texture

Is there an easy way to search a Unity project to find textures that are compressed in a particular format? I tried making a build and searching the Editor log afterward, but the build log doesn't reference the specific texture formats.


texts: How do I make planet move slower the further away they are?

texts:
I got this code from somewhere else, I want to implement Kepler's third law to make the simulation look more realistic, the simulation is a 2D satellite orbiting around a planet, the satellite(Planet) script here is :

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

public class Planet : MonoBehaviour {
private float alpha; //will use for cos & sin (as angle)
private float distance;//distance from center
private float Rotation;//rotation angle
private float currentTime;//Time start when Instantiated
//input values
public float speed;
public Vector2 RotationValues;
public Vector2 distanceValues;
public Vector2 sizeValues;

void Start () {
    //Initialize with Random rotation & distance & size

    //Random Rotation between -2 & 2
    Rotation = Random.Range(RotationValues.x, RotationValues.y);
    //Random distance  between -1 & 2
    distance = Random.Range(distanceValues.x, distanceValues.y);
    //Random Size between 0.2f & 0.7f
    var Size = Random.Range(sizeValues.x, sizeValues.y);
    //Set localScale with random size
    transform.localScale = new Vector3(Size, Size, Size);

    //calculating current time by subtraction Time.time and lastTime
    currentTime = Time.time - Generator.lastTime;

    //GetComponent<MeshRenderer>().material.color = new Color(Random.value, Random.value, Random.value); //Random Color
}

void Update () {
    //Timer
    currentTime += Time.deltaTime;

    var X =  (distance * Mathf.Cos(currentTime)); //X
    var Y =  (distance * Mathf.Sin(currentTime)); //Y
    var R = (Rotation * Mathf.Cos(currentTime)); //Rotation
    //give earth from generator class
    var Earth = Generator.Earth;
    transform.position = Earth.transform.position + (new Vector3(X, R, Y));// RotateAround Earth

}
}

also I have this other script which generates the planets:

using UnityEngine;
using System.Collections;

public class Generator : MonoBehaviour {
public GameObject prefab;
public static GameObject Earth;
public static float lastTime;
public int numerOfSatellites;

void Start() {
    Earth = GameObject.FindGameObjectWithTag("MainPlanet");//Find Earth
    for (int i = 1; i <= numerOfSatellites; i++) {
        lastTime = Time.time;
        GameObject sat = Instantiate(prefab, Earth.transform.position, Quaternion.identity);
        Physics2D.IgnoreCollision(sat.GetComponent<CircleCollider2D>(), Earth.GetComponent<CircleCollider2D>());
    } }
}

I know that the main part here is

void Update () {

    //Timer
    currentTime += Time.deltaTime;

    var X =  (distance * Mathf.Cos(currentTime)); //X
    var Y =  (distance * Mathf.Sin(currentTime)); //Y
    var R = (Rotation * Mathf.Cos(currentTime)); //Rotation

    //give earth from generator class
    var Earth = Generator.Earth;
    transform.position = Earth.transform.position + (new Vector3(X, R, Y));// RotateAround Earth

}

The main problem is that whatever distance the planets have from the mainPlanet (called earth) they move at the same angular velocity, how would I change this?

Those are the basic 4 steps of every orbit, the problem here is that they all align in the center, which shouldn't be possible because of the random distances they have


texts: Why does multiplying texture coordinates scale the texture?

texts:
I'm having trouble visualizing this geometrically - why is it that multiplying the U,V coordinates of a texture coordinate has the effect of scaling that texture by that factor?

eg if you scaled the texture coordinates by a factor of 3 ..then doesn't this mean that if you had texture coordinates 0,1 and 0,2 ...you'd be sampling 0,3 and 0,6 in the U,V texture space of 0..1? How does that make it bigger

eg HLSL:
tex2D(textureSampler, TexCoords*3)

Integers make it smaller, decimals make it bigger

I mean I understand intuitively if you added to the U,V coordinates, as that is simply an offset into the sampling range, but what's the case with multiplication?

I have a feeling when someone explains this to me I'm going to be feeling mighty stupid


texts: How can I get GetMouseButtonDown two positions on two clicks?

texts:
private void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                Vector3 pos1 = Input.mousePosition;
            }
        }

Like two points. I click once and the click one on another position so I will have two positions and now I will be able to draw a line between them. I want to get and store two positions.


texts:
How would I use my right mouse button to turn a player character in unity, while only turning in the direction and speed of the drag?

Not sure if I'm meant to post this here or stackoverflow.

EDIT: game is 3D

EDIT2: Hold right click and drag to turn the camera

Edit3: Got this code

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

public class Control : MonoBehaviour {

public int speed;
public Transform tf;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if (Input.GetMouseButton(1))
    {
        tf.eulerAngles = new Vector3 (0, Input.GetAxis("Mouse X") * speed, 0);
    }
}
}

^ Code works, but after moving the mouse in the specified direction the character jumps back to its original position and kinda does this glitchy turn while moving the mouse (keeps jumping back to original position)

^ nevermind, I think that I figured it out


texts:
What is the difference between #define NAME VALUE and const int NAME = VALUE in GLSL 410 core?

As far as I can see, they both create a constant integer.


texts:
I have been trying to use OpenGL for two days now. First on Mac, then on Windows. The problem with Mac is that it doesn't support the newer versions of OpenGL. I ran a tutorial that actually did get some things working, but it only works in XCode (i.e., I can't create a new file, paste in the same code, and get it to work). Because of these issues, I moved to Windows. My Windows 7 has OpenGL 4.3, which is the same that is used in alot of other tutorials. However, not one of these tutorials gives any instruction on how to set it up for the first time. I have come across some vague posts saying that some libraries need to be linked. But WHAT libraries, and HOW do I link them?

Please help. I am pretty desperate to set this up as this project is due for work soon. I have actually used OpenGL before at my university, but the computers already had everything set up. The project itself is very easy, but setting up OpenGL is not something I know how to do.

Edit: Using C++.


texts: Learning GLSL: What's a good intermediate project to work on?

texts:
I know the basics of OpenGL and I'm starting to love computer graphics more and more. I have a computer science background and have been programming for 5 years. I've been reading the orange book and kind of want to figure out a project that can push me to the next level. I don't want it to be over overwhelmingly hard, I just want a project that can help me progress.

As, of right now I've played around with basic programs in the book. Changing parameters seeing how data moves from one shader to the next.

Any Ideas of what might be a good intermediate project to tackle?


texts: Running Unreal Build Tool with CreateProcess vs command line

texts:
I'm working on a tool that generates some files for Unreal Projects. The only thing is if I try to get it to compile the project through CreateProcess the command doesn't run the same as the command line. I just get an error message from UBT about rule files not existing.

Command being run from CreateProcess:

STARTUPINFO si;
PROCESS_INFORMATION pi;

ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));

CreateProcess("C:/path/to/UnrealBuildTool.exe",
       "ProjectEditor Win64 Development C:/path/to/project.uproject -waitmutex -Deploy",
            NULL,
            NULL,
            FALSE,
            0,
            NULL,
            NULL,
            &si,
            &pi
        );
WaitForSingleObject(pi.hProcess, INFINITE);

CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);

In the command line C:\path\to\UnrealBuildTool.exe ProjectEditor Win64 Development C:\path\to\project.uproject -waitmutext -Deploy successfully compiles the project from any directory. Is there any other variables I need to pass into CreateProcess to get this command to run?

EDIT: Adding space to the start of the argument string fixed the issue. Is there any reason why Windows would need that space?


texts: How can I make a progress bar for EXP in JavaScript?

texts:
So I am making an incremental game with JavaScript, HTML5, and CSS, I need to have this bar that is essentially a div with a p element in it "fill up" as the player earns more points through sacrifice. All the ways I saw to do this on Google required other CSS code that messed up the spacing and such of my whole page.

Here is a non-functioning idea of how it should look. I basically need the Div to fill with any color behind the p element:

function expCalc(){
 var expC = exp;
 var expN = expC + clickCount + modif;
  exp = exp + expN;
 getElementById("exp").innerHTML = exp;
}
div#ovvw-c{
float: center;
border: 3px solid green;
width: 3.3%;
height: 50%;
text-align: center;
margin-top:1%;
margin-left:49.25%;
margin-bottom: 1%;
background-color: rgba(255, 255, 255, .5);
}
.pbar{
 transform: rotate(270deg);
 margin-right:4px;
 margin-top:250px;
 text-align:center;
 font-size:20px;
 font-weight:900;
}

Hatchling:0/100

I understand that my coding is probably sub-par so any constructive criticisms would be appreciated but my main question is how to turn the div into a progress bar with minimal changes to size/spacing/CSS in general. Thanks!


texts: Existing Chat-Text Systems with Autocomplete?

texts:
We're building a multiplayer (dyads) puzzle game where players need to collaborate to be successful. We'd like to use a text chat system that has two must have features: a) autocompletes a player's statements/questions and b) allows only a limited number of predefined messages to be sent.

Any advice on where to go looking for existing text/chat systems with at least the autocomplete feature?


texts: Player acceleration formula and using it with authoritative server

texts:
I know the theory behind authoritative client-server architecture, it works very well for character movement in a tile-based world: you send messages like "I moved one square to the right", the server double checks that and sends the correction. But what if I need acceleration-based system like for a race car game? You start slowly and gradualy increase your speed over time and when you release throtle, you loose speed depending on how fast you are moving right now.

When we tried implementing this system with our naive acceleration formula we ran into a problem: pawns move differently on server and client. That does NOT mean the sever's pawn (obviously) lags, that means after any movement action they end up in different places in the world. We only pass messages with the actions for the movement: that is if the player pressed "forward" we send "forwardON" and raise that flag on the server, similarly when the "forward" action key is released we send the appropriate message. I believe that is the way to do it for the acceleration system, right? You cannot send velocity as you will need to send 60 packets per second and you might still have trouble syncing everything.

So my question is: what sort of movement formula do you need to use for such scenarios and how do you send messages to make sure client and server are syncronized?

UPDATE: we already use smoothing, that is wenever the server and client is not far appart, we smooth the client's position to prevent client "jumping" from place to place. But the client's movement are often VERY different from the server's and that depends on how big lag is, that is why we need to improve our system.


texts: Passing an SDL KeyboardState(Uint8*) to Lua

texts:
I'm working on my first big project and I've decided to integrate Lua with my C++ framework. Everything's worked out so far, but the only way I've managed to pass the SDL_GetKeyboardState(NULL) array to Lua is by building a Lua table manually.

void passKeyboard(const Uint8* keyboard){
    std::map<std::string,std::string> kmap;
    kmap.clear();
    kmap["UP"]=toString(keyboard[SDL_GetScancodeFromKey(SDLK_UP)]);
    kmap["DOWN"]=toString(keyboard[SDL_GetScancodeFromKey(SDLK_DOWN)]);
    kmap["LEFT"]=toString(keyboard[SDL_GetScancodeFromKey(SDLK_LEFT)]);
    kmap["RIGHT"]=toString(keyboard[SDL_GetScancodeFromKey(SDLK_RIGHT)]);
    ...
    vbind_SetTable("keyboard",kmap);
}

Now, the code works and is reasonably fast for my purposes, but it's undeniably ugly. I even feel dirty looking at it. Is there any way I could to this more elegantly?

For reference, vbind.h:

void vbind_SetTable(const std::string &name,std::map<std::string,std::string> &t){
    lua_newtable(L);
    for(std::map<std::string,std::string>::iterator it=t.begin();it!=t.end();it++){
        lua_pushstring(L,it->first.c_str());
        std::string value=it->second;
        const char* p=value.c_str();
        char* end;
        long t=strtol(value.c_str(),&end,10);
        if(p!=end&&errno!=ERANGE){
            lua_pushnumber(L,t);
        }
        else{
            lua_pushstring(L,value.c_str());
        }
        lua_settable(L,-3);
    }
    lua_setglobal(L,name.c_str());
}


texts: ARCore: Differentiate between two planes detected in adjacent vertical walls in the room

texts:
I'm working on Vertical plane detection.
When I'm pointing at wall 1 of my room, plane1 here is the vertical plane detected in wall 1...
I'm recording the quaternion via this formula
 val quat =  Quaternion(plane1.centerPose.qx(), plane1.centerPose.qy(), plane1.centerPose.qz(), plane1.centerPose.qw())

Now, when I point my phone to the other wall (adjacent) of my room and check its rotation, I get the same values, I assumed this is the world rotation. Let me know if I'm wrong.
Is there any other way where I could differentiate between vertical planes detected in adjacent walls
I'm using this to loop through the detected planes
 for (plane1 in frame.getUpdatedTrackables(Plane::class.java)) {
                if (plane1.trackingState === TrackingState.TRACKING) {
                    val type: Plane.Type = plane1.type
                    if (type == Plane.Type.VERTICAL) {


texts:
I am using Daz Gen 8 characters and clothes in my project.
After I read this I decided to use a fork of UE4 which uses Dual Quaternion Skinning.
Basically if you use Daz characters under UE4, they going to distort better if you use DQS, which UE4 doesn't support by default.
You can get the DQS modded engine from here.
I compiled it and I managed to get all my stuff from my original project to a DQS one.
No problem.
But I also need a soft body and a clothing solution in the project.
4.25 has a clothing solution and it does work fine, but there is no soft body, that I know about...
So there are a few options:

Vico Dynamics from the Marketplace
using a Flex branch of UE4
if you know any more please please let me know

Tested Vico, and it works fine for simple meshes, up to 20k poligons. Over that the editor becomes unresponsive... But this works with my modded DQS engine.
The latest version of an UE4 branch with Flex is 4.22. I could get this compiled and running.
I would like to know if I can merge the 2 repositiories (4.22 DQS and Flex) into one, and source build it...
What software or workflow do you recommend to do merge these big branches of UE4?
I guess there will be quite a few conflicts, because Flex distorts the mesh in it's own way, so does the DQS version of Unreal...


texts: EXTREMELY Confused Over "Constant Game Speed Maximum FPS" Game Loop

texts:
I recently read this article on Game Loops: http://www.koonsolo.com/news/dewitters-gameloop/

And the recommended last implementation is confusing me deeply. I don't understand how it works, and it looks like a complete mess.

I understand the principle: Update the game at a constant speed, with whatever is left render the game as many times as possible.

I take it you cannot use a:

Get input for 25 ticks
Render game for 975 ticks

Approach since you would be getting input for the first portion of the second and this would feel weird? Or is that what is going on in the article?

Essentially:

while( GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP)

How is that even valid?

Let's assume his values.

MAX_FRAMESKIP = 5

Let's assume next_game_tick, which was assigned moments after initialization, before the main game loop is say... 500.

Finally, as I am using SDL and OpenGL for my game, with OpenGL being used for rendering only, let's assume that GetTickCount() returns the time since SDL_Init was called, which it does.

SDL_GetTicks -- Get the number of milliseconds since the SDL library initialization.

Source: http://www.libsdl.org/docs/html/sdlgetticks.html

The author also assumes this:

DWORD next_game_tick = GetTickCount();
// GetTickCount() returns the current number of milliseconds
// that have elapsed since the system was started

If we expand the while statement we get:

while( ( 750 > 500 ) && ( 0 < 5 ) )

750 because time has passed since next_game_tick was assigned. loops is zero as you can see in the article.

So we have entered the while loop, let's do some logic and accept some input.

Yadayadayada.

At the end of the while loop, which I remind you is inside our main game loop is:

next_game_tick += SKIP_TICKS;
loops++;

Let's update what the next iteration of the while code looks like

while( ( 1000 > 540 ) && ( 1 < 5 ) )

1000 because time has elapsed getting input and doing stuff before we reached the next ineteration of the loop, where GetTickCount() is recalled.

540 because, in the code 1000 / 25 = 40, therefore, 500 + 40 = 540

1 because our loop has iterated once

5, you know why.

So, since this While loop is CLEARLY depedent on MAX_FRAMESKIP and not the intended TICKS_PER_SECOND = 25; how is the game supposed to even run correctly?

It was no surprise to me that when I implemented this into my code, correctly I might add as I simply renamed my functions to handle user input and draw the game to what the author of the article has in his example code, the game did nothing.

I placed an fprintf( stderr, "Test\n" ); inside the while loop which doesn't get printed until the game ends.

How is this game loop running 25 times a second, guaranteed, while rendering as fast as it can?

To me, unless I am missing something HUGE, it looks like... nothing.

And isn't this structure, of this while loop, supposedly running 25 times a second and then updating the game exactly what I mentioned beforehand at the start of the article?

If that is the case why couldn't we do something simple like:

while( loops < 25 )
{
    getInput();
    performLogic();

    loops++;
}

drawGame();

And count for interpolation some other way.

Forgive my extremely long question, but this article has done more harm than good to me. I am severely confused now - and have no idea how to implement a proper game loop because of all these arisen questions.


texts:
I'm currently researching how to model/simulate radar for my naval simulation.
Since the emphasis is on modelling ASW or submarines in general, I need only a basic radar model - at least for the beginning.

So, does anybody know a resource for such a simple model?

The model should take signal strength of the sensor, the size of the target and the terrain (height/ground clutter) into account.

Edit: This question is not about displaying a radar screen but to simulate the underlying physics of radar. The model would need to work for ships/aircraft/missiles.

Thanks.


texts: Clever way to do the Sonic 2 Bonus Stage effect saving memory

texts:
What would be a good way to save memory to achieve an effect like this one?
http://www.youtube.com/watch?v=K89LkvL9JZ0

We're using pre-rendered 3D.

I'm asking this because this naive approach of just rendering all frames and putting them into a single file (sprite sheet) is producing a gigantic file, would we have to manage this loading creating multiple files?

If it helps, we are using Flex SDK.


texts:
I am teaching game development, and would like my students to upload their homework assignments to a place in which I and the other students can easily see them, so that I can comment on them along the way. Itch.io seems like a good option, since it allows anyone to upload games and make them immediately playable in the browser. However, there are several potential problems:

The homework assignments are not games yet - they are only solutions to specific programming exercises, that some day may become games. Here is an example from my own account. Is it allowed to upload such material to itch.io? I read their terms of service and did not find any clause against it, but I am not sure.
Even if it is allowed, I am not sure it is good for the students' reputation to upload such half-made games. Ideally, it should be possible to create, for each game, a URL that is not published in the itch.io website, but can be opened by anyone that has the URL. Youtube.com has such an option. But I did not find this option in itch.io. I found only three options: Draft - which is available only to the owner, Restricted - which allows only download (not play in browser), and Public - which is available to all but can also be found in searches in itch.io.

So my question is: is there a way to use itch.io (or another similar service) for uploading rough drafts of games, such that the drafts will be available to the teacher and to other students in the course, but will not be published to the entire world?


texts: Issues with the camera following the spline

texts:
I am trying to make a roller coaster and currently I have created a spline class which loads a spline from a text file .
So I have all the points and I have a Catmull-Rom Spline function but I have trouble figuring how a proper track can be created from those points.

Anyone done anything similar?

edit:
Ok i think i will make it more clear now. I was working on it yesterday that's why i didn't reply sooner.

First problem is that my camera is going off tracks.
This is the path generated: http://prntscr.com/ci9sud drawing it as GL_LINE_STRIP.

I have a cameraUpdate function:

float t = (float)TrackPointIndex / (float)1000; ++TrackPointIndex;
point viewPoint = tr->over->getInterpolatedSplinePoint(t);

t = (float)TrackPointIndex / (float)1000; ++TrackPointIndex;
point nextPoint = tr->over->getInterpolatedSplinePoint(t);

std::cout << "viewPoint " << glm::to_string(viewPoint) << std::endl;
std::cout << "nextPoint " <<glm::to_string(nextPoint) << std::endl;

if (TrackPointIndex == 1000)
    TrackPointIndex = 0;

control->bodyTranslation = viewPoint;
control->bodyRotation = nextPoint;

which with the use of getInterpolatedSplinePoint(t) returns the viewPoint and the nextPoint which are points on the spline.  Printing them proves they are indeed on the line. But since i am using GLM i update my camera with the glm::lookAt function . So i thought that the first argument which is the camera position should be the viewPoint and the second one which is where the camera should be pointing at should be nextPoint . But that just doesn't work .
cameraUpdate is called every 250ms or so but it is off tracks . Do i have to do any extra calculations to define where the camera should be / or be looking at?

That's my first problem.

The second one is not really a problem because i have not started working on it yet. I want to know how can somebody generate from the path a fairly good looking rail track.

Thanks.

Edit2: I put a sphere to travel through the tracks and it seems to be working fine . Still if i try moving the camera along the path it does not .

Anyone knows any way around this?


texts: A little bit confused on how to set normals in this case

texts:
I'm learning how to use VBOs and I'm following up on the tutorial at the bottom of this page.
So I went ahead and created a structure Vertex to hold vertex data.(coordinates and normals).
struct Vertex  {
  GLfloat  x,  y,  z;
  GLfloat nx, ny, nz;
  GLfloat   r, g,  b;
  GLfloat padding[7];
};

For the moment I'm trying to draw a cube.So I created an array with 8 vertices.
My question is how do I set the normals?
When I used immediate rendering, I would just do a glNormal3f and proceeded to draw the vertices for that face.
Now that the normals are defined on a per-vertex basis, and a vertex practically belongs to 3 faces, I'm somewhat confused as what I should do here.
Have I taken a wrong approach on making that structure, or I am missing something else.
I would also like to note that I want to make something more generic, so I don't want it to be limited to just drawing cubes.
Thanks.


texts: Which leg does the each animation start with? ( Unity - Blend Tree - Locomotion System )

texts:
I am creating an animation pack for creating a movement system. I'm afraid I will make the animations wrong, as I think it is important that each animation starts from a specific leg, i.e. the legs that will be in front of the character at the beginning of the clip.
Can you tell me - Which leg does the each animation start with?


texts:
Have a question on keyboard inputs. Currently I am using this method to read my input, Gdx.input.isKeyPressed(Input.Keys.A), it is working fine. But I do realized at times there are multiple instances of A being pressed when I only press once. And I understand that the method had to be placed in the render() method for it to work. Is the problem due to the refreshing?

My question is, how can I only detect 1 instance of "A", when A is pressed for once.


texts: Zelda-style top-down RPG. How to store tile and collision data?

texts:
I'm looking to build a Zelda: LTTP style top-down RPG. I've read a lot on the subject and am currently going back and forth on a few solutions. I'm using C#, MonoGame, and Tiled.

For my tile maps, these are the choices I can see in front of me:

Store each tile as its own array. Each one having 3-4 layers, texture/animation, depth, flags,  and maybe collision(depending on how I do it). I've read warning about memory issues going this route, and my biggest map will probably be 160x120 tiles. My average map however will be about 40x30. The number of tiles might cut in half if I decide to double my tile size, which is currently 16x16. This is the most appealing approach for me, as I feel like I would know how to save maps, make changes, and separate it into chunks for collision checks.
Store the static parts of my tile map in multiple arrays acting as the different layers. Then I would just use entities for anything that wasn't static. All of the other tile data such as collisions, depth, etc., would be stored in their own layers as well I guess? This way just seems messy to me though.

Regardless of which one I choose, I'm also unsure how to plan all of that other tile data. I could write a bunch of code that would know which integer represents what tile and it's data, but if I changed a tileset in Tiled and exported it again, all of those integers could potentially change and I'd have to adjust a whole bunch of code.

My other issue is about how I could do collision. I want to at least support angled collision that slides you around the corners of objects like LTTP does, if not more oddball shapes as well. So do I:

Store collision as a flag for binary collision. Could I get this to support angles?
Would it be fine to store collision as an integer and have each number represent a certain angle of collision?
Store a list of rectangles or other shapes and do collision that way?

Sorry for the large two-part(three-part?) question. I felt like these needed to be asked together as I believe each choice influences the other.


texts: Why it's not removing the right doors from the list?

texts:
GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag(c_doorLeft);
        GameObject[] doorsRight = GameObject.FindGameObjectsWithTag(c_doorRight);

        List<GameObject> allDoors = doorsLeft.Union(doorsRight).ToList();

        for(int i = 0; i < allDoors.Count; i++)
        {
            if(allDoors[i].transform.parent.name != "Wall_Door_Long_01" && allDoors[i].transform.parent.name != "Wall_Door_Long_02")
            {
                allDoors.RemoveAt(i);
            }
        }

        foreach(GameObject door in allDoors)
        {
            Debug.Log("Door Parent : " + door.transform.parent);
        }

If it's not "Wall_Door_Long_01" and not "Wall_Door_Long_01" then remove the item from the list.

After that when I'm doing a loop on the allDoors again and debug log the parents I see that some of the parents are not "Wall_Door_Long_01" and not "Wall_Door_Long_02" but after removing they all should be only "Wall_Door_Long_01" or "Wall_Door_Long_02"

Maybe the comparison is wrong ?


texts: Browser-Based Game Design: Keeping track of NPC stats (Attack, Defense, Health, etc)

texts:
Hope this is a proper question to ask here. If not, I'd appreciate somebody pointing me to other game developer communities.
Since I am creating my game by myself it'd be nice to communicate with other developers.

Is it best to keep NPC stats in the database, or calculate them using code?
I store the NPC's level in my database table. So from there I could use code to calculate it's Attack & Defense, and any secondary stats.

I can't think of any "Cons" to using just code.
But a "Pro" would be that I can easily adjust the NPC's stats using different algorithms.


texts: How to manage grid-based inventory with items larger than 1x1 cell?

texts:
Me and my team have been trying to implement some sort of inventory system. We've set our eyes on an inventory system where some items may take up more than one box on the grid system, sort of like the one used in SOTS the pit, like this:

(source: webguyunlimited.com)

Notice how some items, such as the gun, take up more than one slot. How can we implement this? This includes checking to make sure that a slot we would like to insert an item in hasn't already been taken up (we may have irregular shaped items too).


texts: Is it possible to load asset bundle dependencies manually in Unity 5.0?

texts: Is it possible to tell Unity to not load asset bundle dependencies automatically so they can be loaded manually. If so, how can this be done?


texts: What should I expect from volunteer playtesting?

texts:
I have recently been invited to do some volunteer playtesting for a pretty well known developer. They made it very clear that it was on a volunteer basis only. It's not a job and I won't be getting paid. What should I expect? What kind of input are they going to be looking for from me? What tips do you have for doing the playtesting well? What should I do to ensure I'll be invited back? Have you or anyone you know done something similar to this before?

Also, although this is unlikely (at best) to turn into a job, what tips do you have for possibly getting my foot in the door at the company? I am happy to just be able to participate, but I would love to be able to make some good connections since I plan on building a career in the game industry. Thanks in advance.

Update:
I've been invited back to be part of a regular test group for the same game. We went over some UI designs and filled out a survey on what we thought of them and how well we understood them. Then we had a video taped Q&A session with the QA supervisor and some of the developers. We discussed the designs we critiqued in the survey and elaborated more on what we thought of them. Finally, before leaving, we played a few rounds of one of the test builds of the game, just for fun. It was a great experience and from what I observed about the offices and the general work atmosphere, I'm even more sure I've made the right career choice for myself, personally.
I've accepted an answer to this question, but I'm still open to hearing about experiences from other people who have been involved in volunteer playtesting!


texts: Javascript board game: looking for optimization

texts:
I posted this question on stackoverflow before but received no answers so I decided to post it here and see if someone could suggest me something.
I'm working on a html/javascript game for android. It's a board game which does the following.
It has tiles of different colors and user can place one tile (chosen programatically) on the board. If we get 4 or more tiles of the same color/shape we score some points and these tiles will disappear. The tiles above the removed tiles will replace them and new tiles will be added to the empty places. The image below shows how it works (this is just an example, the real board can have different dimensions):

The Tiles are <img> elements with their ids stored in an array which I use to check for matches and replacement.
It all works pretty well but once the new tiles are added to board I need to examine the whole board to check if new matches are avalable. And I want some advice here, because examining the whole board can be really slow. Is there a way I can do this efficiently?
Here's what I thought about doing:

Given the previous example, I thought about examining only the elements in the red area, i.e. only the elements that have been moved or added. It can be effective if the tiles move vertically, as I'll only have to check the moved/added tiles and it'll give me the new matches. But in case where I remove tiles horizontally it can be problematic, because if these tiles are at the bottom i'll have to examine the whole board and i confront the same problem.
Any advice or suggestion will be appreciated.
Note: I didn't add any code because it simply consists of checking the lines and columns for a given tile and look for matches. But if needed I can provide it.
EDIT: Adding horizontalMatchCheck function that for a given index checks for matches horizontally. It's the same thing for vertical check.
function horizontalMatchCheck(itemId) {
    hArray = new Array();
    if (rightMatch(itemId)) {
        var index = itemId + 1;
        hArray.push(itemId + 1);
        while (rightMatch(index)) {
            hArray.push(index + 1);
            index++;
        }
    }
    if (leftMatch(itemId)) {
        var index = itemId - 1;
        hArray.push(itemId - 1);
        while (leftMatch(index)) {
            hArray.push(index - 1);
            index--;
        }
    }
    //if >=4 matches found I replace the indexes with 5 (because no other tile can have this id) which'll then be removed and shifted.
    if (hArray.length >= 3) {
        hArray.push(itemId);
        for (var i = 0; i < hArray.length; i++) {
            board[hArray[i]] = items.length;
        }
    }
    else
        hArray = new Array();
}

function rightMatch(pos)
      return (!isRight(pos) && board[(pos+1)] == current) ? 1 : 0 ;
function leftMatch(pos)
      return (!isLeft(pos) && board[(pos-1)] == current) ? 1 : 0 ;


texts: Is the Key Bindings delay unavoidable in Java when pressing different directional keys quickly?

texts: I've read just about every tutorial I can on why to use Key Bindings instead of implementing the KeyListener interface, including all the examples that show using a field to track the key event because of the repeating delay when holding down the same key. No matter what I do though I simply can't get past a keyboard delay when alternating quickly between directions (i.e. - 'W','D','S','A'). I've read some comments that state this is very dependent on your keyboard OS settings, and in some cases is just unavoidable. Some of the registry editing suggestions for keyboard speed seem to indicate there is some truth in that. Is there a posted solution somewhere that guarantees a "hardware independent" Java solution for handling quick key presses without delay?


texts: Wrong behavior when trying to move on air

texts:
I´m using Andengine and jBox2D to implement a Mario-like platform videogame. Jumping and moving works fine. The problem comes in a very specific case:

I keep the "Move left" button pressed all the time
Player is on air and when moving left, it hits a wall and it stops moving left (while it keeps falling) This is correct.
When the player passes the wall, if the "Move left" button is pressed, it should start moving left while falling but it doesn't. If I lift my finger and press "Move left" again, it works.

The code to move left/right is:

_playerBody.setLinearVelocity(-mLinearVelocityX, _playerBody.getLinearVelocity().y);

The jump code is:

_playerBody.applyLinearImpulse(0, -mImpulseY, _playerBody.getPosition().x, // /////JUMP
            _playerBody.getPosition().y);

This is the code for the hud:

Sprite left = new Sprite(-10, CAMERA_HEIGHT - 150, mLeftTextureRegion) {
    @Override
        public boolean onAreaTouched(TouchEvent pEvent, float pX, float pY) {

            if (!pEvent.isActionOutside() && !isDead && !isPaused) {
                movePlayerLeft(player_self_sprite, player_self_body);
            }

            if (pEvent.isActionUp())  {
                if (isPlayerMoving) {
                    stopPlayer(player_self_sprite, player_self_body);
                    isPlayerMoving = false;
                }
            }
            return true;
        }
    };


texts:
Ok, so yesterday I understood that "rigging (bone and joints)" are things that are use inside a 3D animation software like maya. By that I mean that those bones and joints are not inside the .obj file but only inside the software to help you animate the model.

My plan was to create my own voxel model using my own editor, then load it up into maya to animate it and then put it inside Unity to use the animation but from what I understand, its impossible to put multiple frame inside a file to use the pre-made animation inside a software like Unity.

Does that mean that I will have to load my voxel model inside unity and animate it using the Unity Animation Engine ?


texts: Applying an outline effect to primitives

texts:
I am trying to draw an outline on a collection of quads in Direct3D. I have three intersecting quads on the same plane in the following configuration:

(The different colors here are just to visually break out the quads). Using two pixel shaders, one for the longer segments and another for their intersection (the purple quad), I am rendering this as a single color:

I would like to outline this shape, something like the following (please excuse my Paint skills):

My first approach was to write a pixel shader that would calculate the distance along the y-axis (before the transform) from the center of the quad and colorize based on that. However, when I render this, there is a problem where the quads overlap:

What is the best way to achieve my desired result? Is this possible with a texture and a clever use of blending, perhaps? What about somehow stenciling the non-outline areas?

I should mention that my outlines need to be thicker than one pixel, and that I'm working in DirectX 9 with shader model 4 level 9.1, and C++.


texts: Is an ECS viable in garbage collected languages?

texts:
I've done some research on Entity Component System architectures. Right now I have a convoluted OOP implementation which I'm planning on rewriting, so I was considering switching to a different architecture. Since everything was already composed using components, the switch from OOP to ECS shouldn't be too difficult. However, I'm doing my project in a language with managed memory and GC, and  a lot of the benefits of ECS are to do with memory management, processor cache, etc. so I was wondering whether there is any real performance advantage of ECS over OOP in a garbage collected language?
Also, I'm not too familiar with manual memory management and I haven't really used C/C++ for anything big.


texts: Verlet chain with two fixed points is not converging properly

texts:
I am trying to create a simple chain between two fixed endpoints. The problem is that I can't seem to get the chain to reach a stable state. Further, the chain is always biased toward one of the endpoints.

Here are my constants and variables:

const NUMBER_OF_LINKS = 100
const CHAIN_LENGTH = 400
const DIST_BETWEEN_LINKS = CHAIN_LENGTH / NUMBER_OF_LINKS
const ITERATIONS = 20 # number of times we iterate through constraints each frame
const GRAVITY = Vector2(0, 300)

var anchor1
var anchor2

var prev_link_positions = []
var links = []

Here's what I do on initialization:

create_links(NUMBER_OF_LINKS)

var first_link = links[0]
var last_link = links[NUMBER_OF_LINKS - 1]

first_link.global_position = anchor1.global_position
last_link.global_position = anchor2.global_position

And here are the adjustments I do each frame:

links[0].global_position = anchor1.global_position
links[NUMBER_OF_LINKS - 1].global_position = anchor2.global_position

for i in range(NUMBER_OF_LINKS):
    var acceleration = GRAVITY
    acceleration *= delta * delta
    var prev_position = links[i].global_position
    if not i in [0, NUMBER_OF_LINKS - 1]:
        links[i].global_position = 2*links[i].global_position - prev_link_positions[i] + acceleration
    prev_link_positions[i] = prev_position

for iteration in range (ITERATIONS):
    for i in range(NUMBER_OF_LINKS):
        var link = links[i]

        var prev_link_position
        if i == 0 or i == NUMBER_OF_LINKS - 1:
            prev_link_position = links[i].global_position
        else:
            prev_link_position = links[i-1].global_position

        var next_link_position
        if i == 0 or i == NUMBER_OF_LINKS - 1:
            next_link_position = links[i].global_position
        else:
            next_link_position = links[i+1].global_position

        # get vector to previous link and adjust position
        var vec_to_prev_link = prev_link_position - link.global_position
        link.global_position += vec_to_prev_link.normalized() * max(vec_to_prev_link.length() - DIST_BETWEEN_LINKS, 0) / 2.0

        # get vector to next link and adjust position
        var vec_to_next_link = next_link_position - link.global_position
        link.global_position += vec_to_next_link.normalized() * max(vec_to_next_link.length() - DIST_BETWEEN_LINKS, 0) / 2.0

When I run this, I almost get what I want, except the chain contorts and never reaches a stable state. Also, it is biased in the first direction I look at when solving the constraints.

It looks something like this:

What am I doing wrong? How can I get a chain that stabilizes with links more uniformly distributed?


texts: AI-possessed Pawn flies off at incredibly high speed immediately after hitting play (UE4)

texts:
I have a very simple pawn with a Sphere Collision and a child Static Mesh. This pawn is set to be possessed by an AI Controller on spawn and the AI Controller basically sets up the blackboard and runs the behaviour tree. The behaviour tree is set to do nothing. As soon as I hit play in the editor, the pawn falls to the floor and bounces off at speeds almost too fast to see and quickly flies out of the edges of the worldmap and gets deleted.

alt text

In the picture above, the blurred blue thing is the object thats rocketing away.

I've been stuck on this for a very long time, any help is appreciated.


texts: Is there a 2d physics engine that can model fluids and gases?

texts: At this point the platform and programming language don't matter I would just like to know if something out there exists for this.  Any help is appreciated.


texts: Impact of increasing physics simulation rate

texts:
I am working one Mini Golf game development using Scenekit (iOS). To fix one of the problem with Scenekit, I have to increase the physics simulation rate by 4 times.

Questions:

What is the impact on the CPU requirements?
What are the common advantages and disadvantages of changing the physics simulation rate?
What are the expected problems/issues with such increase in the physics simulation rate?

I would appreciate any suggestion on this topic. Thank you.


texts:
After compiling a shader with glCompileShader, I can call glGetShaderiv with GL_COMPILE_STATUS to check if the shader compiled successfully. I can also call glGetShaderInfoLog to get information about possible errors, warnings or other info. The information log returned by this function is unspecified.

In a tool where users can write their own shaders, I would like to print all errors and warnings from the compilation, but nothing if no warnings or errors were found. The problem is that the GL_COMPILE_STATUS returns only false if the compilation failed and true otherwise. If no problems were found, some drivers return empty info log from glGetShaderInfoLog, but some drivers can return something else such as "No errors.", which I do not want to print to the user. How is this problem generally solved?


texts: OBJ file, face materials and drawing them with OpenGL

texts:
I'm implementing a model class which loads OBJ and MTL files, and ran into an issue or question with face materials.

Consider the following example: It's a cube with 5 sides Gray and 1 side Green.

mtllib Materials.mtl

o Cube
v -1.000000 -1.000000 1.000000
v -1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 -1.000000
v 1.000000 -1.000000 1.000000
v -1.000000 1.000000 1.000000
v -1.000000 1.000000 -1.000000
v 1.000000 1.000000 -1.000000
v 1.000000 1.000000 1.000000

usemtl Green
f 7 8 4 3

usemtl Gray
f 5 8 2 1
f 6 7 3 2
f 8 5 1 4
f 1 2 3 4
f 8 7 6 5

The OBJ file obviously shares same vertices for adjacent faces even if the faces get different materials.

When drawing such a cube with OpenGL however, I would need to duplicate the vertices of the adjacent faces with different materials, since every vertex specifies the color it has - and I have two different colors for the same vertices here, depending on the face and the different material it has.
If I wouldn't do that, the adjacent faces would smooth over to the different materials.

First: Did I get this correctly or am I missing an OpenGL "feature" here which lets me "specify" the color of a whole triangle / face rather than a single vertex?

Second: If not, is there an easier way to keep track of the faces materials and duplicating the adjacent vertices if they get different materials? What would be the easiest way to implement different materials on one object?


texts: Minkowski Portal Refinement collision detection algorithm

texts:
Preface: While I was learning the basics of collision detection, I read in various  places that the SAT and GJK algorithms don't natively return contact points. So I decided to research the MPR algorithm. I've found very little information about it online.

My questions are the following:

What are the steps it takes?
Does MPR detect collisions continuously? If not, is it feasible to upgrade it?
Does it return contact points, or a simple true/false on collision? How does it calculate them?

(I'm targeting 2D, but it would be nice to know the differences in 3D.)


texts:
I'm learning OpenGL and now after I made everything I needed, I started with 3D, my first problem is that my mesh doesn't draw like I intended...

Here's my rectangle (uses GL_TRIANGLES):

std::vector<GLfloat> Vpos =
{
    0.5, 0.5, //0.0,
    0.5, -0.5, //0.0,
    -0.5, -0.5, //0.0
    - 0.5, -0.5, //0.0
    - 0.5, 0.5, //0.0,
    0.5, 0.5, //0.0
};//comms are the 3d version

And here I draw my array:

glDrawArrays(GL_TRIANGLES, 0, verNum / 2); //it is binded with vertex array, I use shaders

And my fragment shader is:

#version 330

in vec2 passTextureCoords;

out vec4 outColor;

uniform sampler2D ourTexture;

void main()
{
    outColor = vec4(0.0, 1.0, 0.5, 1.0);// texture(ourTexture, passTextureCoords); I don't have a texture so I use a lightgreen for debug proposes
}

Also my vertex shader:

#version 330

layout (location=0) in vec3 inVertPos;
layout (location=1) in vec2 inTexCoords;

out vec2 passTextureCoords;

void main()
{
    gl_Position = vec4(inVertPos.x, inVertPos.y, inVertPos.z, 1.0);
    passTextureCoords = inTexCoords;
}

Thanks for help by now, I pretty sure that I missed something small but important.


texts: How do I export my Blender model to OGRE XML format for jMonkeyEngine 3?

texts:
I'm an amateur software engineer with several simple 2D-game projects under my belt. I'v recently turned my attention towards creating a basic 3D game, nothing too fancy, just to get a grip on things.

I used jMonkeyEngine 3 (RC 2) because I'm interested in Java, and open-sourced games. Unfortunately, being an independent project, jME3 is not as complete as other Game Engines, and its community is not as large.

I've followed most of their basic how-to tutorials to get me started on jME3, but one area always escapes me; the use of models in a game. jME3 recommends Blender, and also recommends exporting the models as OGRE XML files.

In my experience, jME3 can import .blend files directly, but at the loss of anything other than the very basic model itself. No bones, no animation, and so far, my attempts at giving it a solid color failed as well.

I'm only interested in using and seeing my model in game, with bones, if at all possible. Animations an come later. I've followed their tutorials on how to import models here:

http://jmonkeyengine.org/wiki/doku.php/jme3:beginner:hello_asset

But I get stuck on "Open the menu File > Export > OgreXML Exporter to open the exporter dialog."

For one, there IS no Export to OgreXML (in Blender). I've fiddled around in the preferences and still found nothing. I've installed the required 'stuff' by going through jME3 and clicking 'install OGRE plug-ins.'

I've also tried to download a converter from Ogre itself, but all I get are some command line parameters that open CMD and close it way too fast for me to do anything.

Am I missing something?

My experience with Blender and modelling is even more limited than my experience in programming, so I don't really understand scripts, and python and whatever it is I found on the net in my research.

I used:

Blender 2.65
JMonkeyEngine 3.0 RC 2
Windows 8 (ick)


texts: How can I test if a point is behind a polygon in 2D?

texts:
In order to improve the performance of my visibility graph generator I am trying to figure out the following.

Given the image below; is there a way to find out if a point is 'behind' the polygon? For example, from the blue points perspective green and pink would be behind the polygon so there is no need to do expensive visibility checks. Is there an easy way to figure this out?

Basically, what I need to know is, when drawing a line from Blue to Green, does it start in or outside the polygon? There must be some simple math for this.

So green and pink are 'behind' and purple and red are in front.