title: Fix buttons on screen

text:
# Question
Title: Fix buttons on screen
I've added buttons and SKCameraNode for my player. I got problem. When player moving left/right/jump all buttons dont follow for him.

**UPDATE**

class GameScene: SKScene, SKPhysicsContactDelegate {

```
var player: SKSpriteNode?

let buttonDirUp = SKSpriteNode (imageNamed: "button_dir_up")
let buttonDirLeft = SKSpriteNode (imageNamed: "button_dir_left")
let buttonDirDown = SKSpriteNode (imageNamed: "button_dir_down")
let buttonDirRight = SKSpriteNode (imageNamed: "button_dir_right")

var pressedButtons = [SKSpriteNode]()

override func didMoveToView(view: SKView) {

    physicsWorld.contactDelegate = self

    self.physicsWorld.gravity = CGVectorMake(0, -5)

    userInteractionEnabled = true

    player = self.childNodeWithName("player") as? SKSpriteNode

    buttonDirUp.position = CGPoint(x: 100, y: 150)
    buttonDirUp.zPosition = 2
    buttonDirUp.setScale(2.0)
    buttonDirUp.alpha = 0.2
    self.addChild(buttonDirUp)

    buttonDirLeft.position = CGPoint(x: 50, y: 100)
    buttonDirLeft.zPosition = 2
    buttonDirLeft.setScale(2.0)
    buttonDirLeft.alpha = 0.2
    self.addChild(buttonDirLeft)

    buttonDirDown.position = CGPoint(x: 100, y: 50)
    buttonDirDown.zPosition = 2
    buttonDirDown.setScale(2.0)
    buttonDirDown.alpha = 0.2
    self.addChild(buttonDirDown)

    buttonDirRight.position = CGPoint(x: 150, y: 100)
    buttonDirRight.zPosition = 2
    buttonDirRight.setScale(2.0)
    buttonDirRight.alpha = 0.2
    self.addChild(buttonDirRight)
}

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        for touch: AnyObject in touches {
            let location = touch.locationInNode(self)

            for button in [buttonDirUp, buttonDirLeft, buttonDirDown, buttonDirRight] {

                if button.containsPoint(location) && pressedButtons.indexOf(button) == nil {
                    pressedButtons.append(button)
                }
            }
        }

        for button in [buttonDirUp, buttonDirLeft, buttonDirDown, buttonDirRight] {
            if pressedButtons.indexOf(button) == nil {
                button.alpha = 0.2
            }
            else {
                button.alpha = 0.8
            }
        }
    }
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

        for touch: AnyObject in touches {
            let location = touch.locationInNode(self)
            let previousLocation = touch.previousLocationInNode(self)

            for button in [buttonDirUp, buttonDirLeft, buttonDirDown, buttonDirRight] {

                if button.containsPoint(previousLocation)
                    && !button.containsPoint(location) {

                        let index = pressedButtons.indexOf(button)
                        if index != nil {
                            pressedButtons.removeAtIndex(index!)
                        }
                }

                else if !button.containsPoint(previousLocation)
                    && button.containsPoint(location)
                    && pressedButtons.indexOf(button) == nil {
                        pressedButtons.append(button)
                }
            }
        }

        for button in [buttonDirUp, buttonDirLeft, buttonDirDown, buttonDirRight] {
            if pressedButtons.indexOf(button) == nil {
                button.alpha = 0.2
            }
            else {
                button.alpha = 0.8
            }
        }
    }

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for touch: AnyObject in touches {
            let location = touch.locationInNode(self)
            let previousLocation = touch.previousLocationInNode(self)

            for button in [buttonDirUp, buttonDirLeft, buttonDirDown, buttonDirRight] {
                if button.containsPoint(location) {
                    let index = pressedButtons.indexOf(button)
                    if index != nil {
                        pressedButtons.removeAtIndex(index!)
                    }
                }
                else if (button.containsPoint(previousLocation)) {
                    let index = pressedButtons.indexOf(button)
                    if index != nil {
                        pressedButtons.removeAtIndex(index!)
                    }
                }
            }
        }
        for button in [buttonDirUp, buttonDirLeft, buttonDirDown, buttonDirRight] {
            if pressedButtons.indexOf(button) == nil {
                button.alpha = 0.2
            }
            else {
                button.alpha = 0.8
            }
        }
    }

override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {

    for touch: AnyObject in touches! {
        let location = touch.locationInNode(self)
        let previousLocation = touch.previousLocationInNode(self)

        for button in [buttonDirUp, buttonDirLeft, buttonDirDown, buttonDirRight] {
            if button.containsPoint(location) {
                let index = pressedButtons.indexOf(button)
                if index != nil {
                    pressedButtons.removeAtIndex(index!)
                }
            }
            else if (button.containsPoint(previousLocation)) {
                let index = pressedButtons.indexOf(button)
                if index != nil {
                    pressedButtons.removeAtIndex(index!)
                }
            }
        }
    }
    for button in [buttonDirUp, buttonDirLeft, buttonDirDown, buttonDirRight] {
        if pressedButtons.indexOf(button) == nil {
            button.alpha = 0.2
        }
        else {
            button.alpha = 0.8
        }
    }
}

override func update(currentTime: CFTimeInterval) {
            if pressedButtons.indexOf(buttonDirUp) != nil {
        player!.position.y += 9.0
    }
    if pressedButtons.indexOf(buttonDirDown) != nil {
        player!.position.y -= 9.0
    }
    if pressedButtons.indexOf(buttonDirLeft) != nil {
        player!.position.x -= 9.0
    }
    if pressedButtons.indexOf(buttonDirRight) != nil {
        player!.position.x += 9.0
    }
}

```

}

# Answer
You could add the buttons as a child of the player. Instead of:

```
self.addChild(buttonDirUp)

```

it would be

```
player.addChild(buttonDirUp)

```
> 0 votes

---
Tags: spritekit, swift
---


# Question
Title: Does Apple allow customers to play over Bluetooth?
I'm a beginner in app development so sorry if my question is cheap :(

I wanted to start developing a card game and i was wondering if apple allows customers to play over Bluetooth or not ( on multiplayer )

I asked this question because i did not want to go all the way and realize that my game does not work over Bluetooth.

# Answer
> 1 votes
Look into the Multipeer Connectivity Framework from apple. It doesn't exclusively use bluetooth but it's meant for the type of connections you're describing. It uses Bluetooth, infrastructure wifi, and peer-to-peer wifi, depending on what's available.

https://developer.apple.com/library/ios/documentation/MultipeerConnectivity/Reference/MultipeerConnectivityFramework/

---
Tags: ios, swift
---


# Question
Title: Change material emission for a second then go back to default
I'm looking for a way to change the emission of a material for a second then get it back to where is was by default

Here's what I have for now

```
float emission_lvl = 5.0F;
float emission_lvl_start = 0.5F;

public Update(){
    mat.SetFloat("_Emission",emission_lvl);
    Invoke ("SetEmissionBack", 1.0f);
}

public void SetEmissionBack(){
    mat.SetFloat("_Emission",emission_lvl_start);
}

```

# Answer
Well, your placement is wrong. Execute same code of `Update` in `Start` or whenever you want to execute it and remove it from `Update`. Because `Update` is a loop that executes 30 - 60 (depends) per second and `mat.SetFloat("_Emission",emission_lvl);` executing per frame, that is preventing to change material's emission property.

And now I came to know that you want flicker effect. So you can use `Coroutine` for that.

```
void Start()
{
    StartCoroutine("StartEffect");
}

IEnumerator StartEffect()
{
    while(true) // Or any other condition, this will repeat until this condition is true
    {
        mat.SetFloat("_Emission",emission_lvl);
        yield return new WaitForSeconds(1.0f);
        mat.SetFloat("_Emission",emission_lvl_start);
        yield return new WaitForSeconds(1.0f);
    }
}

```
> 3 votes

---
Tags: c#, unity
---


title: Object not Augmenting on small marker

text:
# Question
Title: Object not Augmenting on small marker
I am new to **Augmented reality**. I am developing a jewellery try on app with vuforia using unty3D editor. What I want is to augment a ring on the marker. I download an image(attached bellow) and used it as my marker and it was working fine but when I resized the image in paint to fit to finger the marker stopped augmenting the object. any help.

* What should be the marker size or anything else which I am missing ? Please help me.

# Answer
> 2 votes
This guide from Vuforia gives some advice on marker design:

Image Target Guide

Specifically the section named "Designing Target Images"

However I've had success with image markers down to approx. 2x2 cm, using custom marker graphics in good conditions.

Since marker size is critical in your situation I would also look at alternative solutions, such as simple QR markers or Vuforia's framemarkers. Or if identification of the unique marker is not a requirement then I'd also look at custom solutions using OpenCV or similar.

---
Tags: unity, augmented-reality, vuforia
---


title: Aiming direction using mouse

text:
# Question
Title: Aiming direction using mouse
I'm using the following code to rotate my object using mouse, for aiming direction. The only problem with this is that it only rotates between 0 to 180 and not full 360 degrees. Can any help me locate the problem?

```
void Update()
{
  var pos = Camera.main.WorldToScreenPoint(this.gameObject.transform.position);
  var dir = (Input.mousePosition - pos).normalized;
  var angle = (Mathf.Atan2(dir.z, dir.x) * Mathf.Rad2Deg + 270) % 360;
  this.gameObject.transform.rotation = Quaternion.AngleAxis(angle, Vector3.down);

  if (Input.GetMouseButtonDown(0))
  {
    GetComponent<Rigidbody>().AddForce(dir.x * Force, 0, dir.y * Force, ForceMode.Impulse);
}

```

# Answer
> 1 votes
Well, your answer is good for your specific situation but you could use LookAtMouse script. That is very handy, beautiful and will work in all type of circumstances.

Pasting the important part of script that you can use easily.

```
public float speed = 10;

    void FixedUpdate ()
    {
        // Generate a plane that intersects the transform's position with an upwards normal.
        Plane playerPlane = new Plane (Vector3.up, transform.position);

        // Generate a ray from the cursor position
        Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);

        // Determine the point where the cursor ray intersects the plane.
        // This will be the point that the object must look towards to be looking at the mouse.
        // Raycasting to a Plane object only gives us a distance, so we'll have to take the distance,
        //   then find the point along that ray that meets that distance.  This will be the point
        //   to look at.
        float hitdist = 0.0f;
        // If the ray is parallel to the plane, Raycast will return false.
        if (playerPlane.Raycast (ray, out hitdist)) {
            // Get the point along the ray that hits the calculated distance.
            Vector3 targetPoint = ray.GetPoint (hitdist);

            // Determine the target rotation.  This is the rotation if the transform looks at the target point.
            Quaternion targetRotation = Quaternion.LookRotation (targetPoint - transform.position);

            // Smoothly rotate towards the target point.
            transform.rotation = Quaternion.Slerp (transform.rotation, targetRotation, speed * Time.deltaTime);
        }
    }

```

# Answer
> 0 votes
Got it myself. The above code should look like this:

```
var pos = Camera.main.WorldToScreenPoint(this.gameObject.transform.position);
var dir = (Input.mousePosition - pos);
var angle = (Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg) - 90;
this.gameObject.transform.rotation = Quaternion.AngleAxis(angle, Vector3.down);

```

---
Tags: unity, rotation, aiming
---


# Question
Title: OpenGL texture 2d array won't render with depth > 1
Below code uploads my texture memory that's described in the passed parameters. When '*vPixelData*' only holds 1 item/texture it is rendered properly, but once there's 2 or more nothing shows up.

glTexSubImage3D() is returning '**GL\_INVALID\_OPERATION**' when I call glGetError() after it only when vPixelData.size() is greater than 1.

```
/*virtual*/ uint32 HyOpenGL::AddTextureArray(uint32 uiNumColorChannels, uint32 uiWidth, uint32 uiHeight, vector<unsigned char *> &vPixelData)
{
    GLenum eInternalFormat = uiNumColorChannels == 4 ? GL_RGBA8 : (uiNumColorChannels == 3 ? GL_RGB8 : GL_R8);
    GLenum eFormat = uiNumColorChannels == 4 ? GL_RGBA : (uiNumColorChannels == 3 ? GL_RGB : GL_RED);

    glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, eInternalFormat, uiWidth, uiHeight, static_cast<uint32>(vPixelData.size()), 0, eFormat, GL_UNSIGNED_BYTE, NULL);

    GLuint hGLTextureArray;
    glGenTextures(1, &hGLTextureArray);
    //glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D_ARRAY, hGLTextureArray);

    // Create storage for the texture
    glTexStorage3D(GL_TEXTURE_2D_ARRAY,
                    1,                      // Number of mipmaps
                    eInternalFormat,        // Internal format
                    uiWidth, uiHeight,      // width, height
                    static_cast<uint32>(vPixelData.size()));

    for(unsigned int i = 0; i != vPixelData.size(); ++i)
    {
        // Write each texture into storage
        glTexSubImage3D(GL_TEXTURE_2D_ARRAY,
                        0,                                      // Mipmap number
                        0, 0, i,                                // xoffset, yoffset, zoffset
                        uiWidth, uiHeight, 1,                   // width, height, depth (of texture you're copying in)
                        eFormat,                                // format
                        GL_UNSIGNED_BYTE,                       // type
                        vPixelData[i]);                         // pointer to pixel data

        GLenum eError = glGetError(); // Getting 'GL_INVALID_OPERATION' when > 1 texture depth. It's 'GL_NO_ERROR' otherwise
    }

    glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    return hGLTextureArray;
}

```

(My current passed parameters are uiNumColorChannels == 4)

(uiWidth and uiHeight are both 512)

# Answer
Apparently everything works if I use:

```
glTexImage3D(GL_TEXTURE_2D_ARRAY,
             0,
             eFormat,
             uiWidth, uiHeight,
             static_cast<uint32>(vPixelData.size()),
             0,
             eFormat,
             GL_UNSIGNED_BYTE,
             NULL);

```

instead of:

```
glTexStorage3D(GL_TEXTURE_2D_ARRAY,
                    1,                      // Number of mipmaps
                    eInternalFormat,        // Internal format
                    uiWidth, uiHeight,      // width, height
                    static_cast<uint32>(vPixelData.size()));

```
> 0 votes

---
Tags: opengl, c++, textures
---


# Question
Title: When do I save the buffer data to the database?
My entire game is server side and I use `nodejs` with `mysql`.

When players connect or join a game, their player data (Items, Stash, Quests, etc) all get stored into the memory buffer.

For example, if a player joins a game and there are 40 items on the floor and he decides to pick them all up, it's easier just to add that to their Inventory object instead of using a `insert` statement each time. Then, when that user disconnects I can save all that data respectively. (Now that I think of it, that query would run 40 `insertion` rows..)

That's the problem I have though, do I save the data during the looting process **or** wait until the player disconnects and run a `db update` to save their memory buffer (**only the changed buffer**) to the database?

The Issue I have with that is, if a player picks up over 40 items in the game, that's going to be a lot of `sql insertions` when they disconnect..

Imagine them finding a ton of items from mobs and having a huge amount of new updated buffer data that needs to be stored.. (after they disconnect), that would be a dreadful update. Especially if they stored hundreds of items in their stash or whatnot. Hmmm.

# Answer
# \[1\] Database Reader / Writer Forked Process

You could use a `db update` **child process** that is called when a user leaves the game.
That would be non-blocking for your node.js socket server's main thread and the other clients wouldn't experience the lag during the db update
**------------\[EXAMPLE\]------------------**

```
// server.js
var process = require('child_process');
var fs = require('fs');
var db_rwp = process.fork('db_rwp.js');
    db_rwp.on('message', function(data) {
      switch(data.acid){
        /* INIT : ERROR  */ case 'error':
            console.log(' # database reader / writer ERROR  ');
            console.log(data.arg1);
          break;
        /* INIT :  OK!   */ case 'success':
            console.log(' # database reader / writer : 0N   ');
          break;
        }
    });

```

```
// db_rwp.js
var mysql = require('mysql');
var fs = require('fs');
//When Spawned Return Connection Status
var db = mysql.createConnection({
    host:'host', user:'user', password:'pass', database: 'database'
});
db.connect(function(err){
    if (err) { process.send({acid:'error',arg1:err}); }
    else { process.send({acid:'success'});}
});

```

Comunication example :
(maintain the socket.id of the request to return post-action results to specific client)

```
// server.js -to- db_rwp.js :
db_rwp.send({acid:'action_id', csid:socket.id});
// db_rwp.js -to- server.js :
process.send({acid:'action_id', csid:data.csid});
// server.js -to- client :
io.to(data.csid).emit('action_id_result');

```

**------------------------------------**

# \[2\] Global save from main thread

You could call a `db update` using a desired world save frequency.
Freezing all the clients to prevent dupes/etc...
While the server saves you could display a message in the clients:
'*The world is saving please wait...*'

**#1** would need a way to detect when a client is performing a log-in whilst another client is already inside that account. (Avoid loading obsolete data from db)
**#2** is useful for having a recent backup to load in case of crash, RunUO (Ultima Online Server Emulator) does this to save the world state.
> 2 votes

---
Tags: savegame
---


title: Super formula on shader

text:
# Question
Title: Super formula on shader
I'm using Shader-toy to experiment and try to learn a bit the shader science. As exercise I wan to replicate some of the wikipedia math plots. I've started with a Super Formula.

What I want to achieve is this:

(taken from this wikipedia image)

This image shows the parameter of the super formula thing:

* *a=b=1*,
* *m=3*,
* *n1=5*,
* *n2=18* and
* *n3=18*

I've looked for a similar example, simplified it and try to reproduce my curve.

In shader-toy this is my code:

```
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    // Variables to be fed into the formula
    float a = 1.0;
    float b = 1.0;
    float m = 3.;
    float n1 = 5.0;
    float n2 = 18.;
    float n3 = 18.;

    vec2 uv = fragCoord.xy / iResolution.xy;

    // translation
    vec2 sf = uv - 0.5;

    // r of the current point
    float pr = sqrt(sf.x*sf.x + sf.y*sf.y);
    // Angle (Phi) of the current point
    float f = atan(sf.y/sf.x);

    // The formula itself. Division by 10.0 added to scale the result down a bit.
    float r = pow((pow(abs(cos(f*m/4.0)/a),n2) + pow(abs(sin(f*m/4.0)/b), n3)), -(1.0/n1)) / 10.;

    // Output with coloring by relative radius
    fragColor = (pr <= r) ?
        vec4(1., 0., 0., 1.0) :
        vec4(0.1, 0.1, 0.1, 1.0);
}

```

But I'm achieving a different shape:

What am I doing wrong?

# Answer
> 4 votes
Instead of `atan(sf.y/sf.x)`, use `atan(sf.y,sf.x)`. This works because it takes the sign into consideration. Dividing the two numbers loses the sign bit data, so which quadrant you are in is unknown.

You can add `fragColor=vec4(pr,f,0.0,1.0);` to see what is going on.

Also, if you want to fix your aspect ratio (the image stretching) add `sf.y *= iResolution.y/iResolution.x;` after the declaring sf.

---
Tags: 2d, shaders, geometry, fragment-shader, trigonometry
---


# Question
Title: Determine if set of connected tiles can fit inside grid
Feel free to edit the title; I had a hard time figuring out how to explain it in a single line.

Here goes. I'm trying to generate these grids automatically, and randomly.

I have a grid of 25 tiles (indicated by #)

```
#####
#####
#####
#####

```

Let's say that I have 2 monsters I want to place in this grid, each monster occupies 3 or 4 tiles, with different patterns (these are not random, but is defined somewhere).

Monster 1 indicated by the letter A Monster 2 indicated by the letter B

An example of this:

```
#AA##
#BA##
#BBB#
#####

```

Or it could be (this is whre the randomness comes in):

```
AA###
#A###
#B###
#BBB#

```

How would I go about calculating where, for example, monster B fits in the grid after A has been placde? Monster B has a pattern of:

```
B
BBB

```

And A has a pattern of:

```
AA
 A

```

A possible pattern could also be (for a different monster than A and B):

```
C
 C
  C

```

Is this even possible to automate? Hope that makes sense, otherwise I can try drawing it instead.

Thanks

# Answer
> 0 votes
The best way to do this would be to randomly pick a tile, and just do checks for the other tiles needed to place the monster. If the monster can't fit being placed in the tile given, then loop until a spot is found where it can fit.

```
int[,] monsterA = [[1,1]
                  [0,1]]

int[,] level = [[0,0,0]
                [0,0,0]
                [0,0,0]]

point placeLocation(int[,] layout, int[,] monster)
{
    bool completed = false

    point chosenPoint

    while (completed == false}  //while a good spot hasn't been found
    {
        //method which picks a random point from the array
        chosenPoint = getRandomPoint(layout)

        bool fail = false
        for (int i = 0;i<monster.width;i++)
        {
            for (int j=0; j<monster.height;j++)
            {
                if (monsterA[i,j] == 1 && level[chosenPoint.X + i,chosenPoint.Y + j] != 0
                {

                   //if any point of the monster is blocked, fail is set to true
                   fail = true;
                }
            }
        }
        if (fail == false){
           //monster can fit here
           completed = true
        }
    }
    return chosenPoint
}

```

If you want to prevent the loop from running forever, you could put a limited number of tries on it or keep track of chosen points until all of them have been exhausted.

---
Tags: mathematics, grid, tiles
---


title: Libgdx Megaman Engine

text:
# Question
Title: Libgdx Megaman Engine
This is my first time posting here. Through the tutorials and videos I can find regarding developing games using libgdx. I thought I would start with something that was relatively simplistic, a Megaman game. I have a rudimentary engine up and running, but I have been having some difficulty accurately representing the physics of Megaman.

I found this thread that lists out the physics of the original:

http://sprites-inc.co.uk/showthread.php?tid=388

One other issue I have had is that, in testing, I found that after jumping, if you continually hit the jump button('S'), you can slow your fall. I have been unable to find a way of stopping that.

Any assistance or information would be greatly appreciated.

Megaman class:

```
package com.mygdx.game;

import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Input.Keys;

public class Megaman extends Sprite implements InputProcessor
{
/**the movement velocity*/
private Vector2 velocity = new Vector2();

private float speed = 60 * 1.375f;

private float gravity = 60 * .25f;
private boolean canJump;

private TiledMapTileLayer collisionLayer;

public Megaman(Sprite sprite, TiledMapTileLayer collisionLayer)
{
    super(sprite);
    this.collisionLayer = collisionLayer;

}

@Override
public void draw(Batch spriteBatch)
{
    update(Gdx.graphics.getDeltaTime());
    super.draw(spriteBatch);
}

public void update(float delta)
{
    // apply gravity
            velocity.y -= gravity * delta;

            // clamp velocity
            if(velocity.y > speed)
                velocity.y = speed;
            else if(velocity.y < -7.0f)
                velocity.y = -7.0f;

            // save old position
            float oldX = getX(), oldY = getY();
            boolean collisionX = false, collisionY = false;

            // move on x
            setX(getX() + velocity.x * delta);

            if(velocity.x < 0) // going left
                collisionX = collidesLeft();
            else if(velocity.x > 0) // going right
                collisionX = collidesRight();

            // react to x collision
            if(collisionX) {
                setX(oldX);
                velocity.x = 0;
            }

            // move on y
            setY(getY() + velocity.y * delta * 5f);

            if(velocity.y < 0) // going down
                canJump = collisionY = collidesBottom();
            else if(velocity.y > 0) // going up
                collisionY = collidesTop();

            // react to y collision
            if(collisionY) {
                setY(oldY);
                velocity.y = 0;
            }
}

public Vector2 getVelocity() {
    return velocity;
}

public void setVelocity(Vector2 velocity) {
    this.velocity = velocity;
}

public float getSpeed() {
    return speed;
}

public void setSpeed(float speed) {
    this.speed = speed;
}

public float getGravity() {
    return gravity;
}

public void setGravity(float gravity) {
    this.gravity = gravity;
}

public TiledMapTileLayer getCollisionLayer() {
    return collisionLayer;
}

public void setCollisionLayer(TiledMapTileLayer collisionLayer) {
    this.collisionLayer = collisionLayer;
}

@Override
public boolean keyDown(int keycode) {
    switch (keycode)
    {
    case Keys.W:
        if(canJump) {
            velocity.y = 60 * 4.75f;
            canJump = false;
        }
        break;
    case Keys.A:
        velocity.x = -speed;
        break;
    case Keys.D:
        velocity.x = speed;
        break;
    }
    return true;
}

@Override
public boolean keyUp(int keycode) {
    switch (keycode)
    {
    case Keys.W:
        velocity.y = 0;
        break;
    case Keys.A:
    case Keys.D:
        velocity.x = 0;
        break;
    }
    return true;
}

@Override
public boolean keyTyped(char character) {
    return false;
}

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {

    return false;
}

@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
    return false;
}

@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
    return false;
}

@Override
public boolean mouseMoved(int screenX, int screenY) {
    return false;
}

@Override
public boolean scrolled(int amount) {
    return false;
}

private boolean isCellBlocked(float x, float y) {
    Cell cell = collisionLayer.getCell((int) (x / collisionLayer.getTileWidth()), (int) (y / collisionLayer.getTileHeight()));
    return cell != null && cell.getTile() != null && cell.getTile().getProperties().containsKey("blocked");
}

public boolean collidesRight() {
    for(float step = 0; step < getHeight(); step += collisionLayer.getTileHeight() / 2)
        if(isCellBlocked(getX() + getWidth(), getY() + step))
            return true;
    return false;
}

public boolean collidesLeft() {
    for(float step = 0; step < getHeight(); step += collisionLayer.getTileHeight() / 2)
        if(isCellBlocked(getX(), getY() + step))
            return true;
    return false;
}

public boolean collidesTop() {
    for(float step = 0; step < getWidth(); step += collisionLayer.getTileWidth() / 2)
        if(isCellBlocked(getX() + step, getY() + getHeight()))
            return true;
    return false;

}

public boolean collidesBottom() {
    for(float step = 0; step < getWidth(); step += collisionLayer.getTileWidth() / 2)
        if(isCellBlocked(getX() + step, getY()))
            return true;
    return false;
}

}

```

TestMap class:

```
package com.mygdx.game;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;

public class TestMap implements Screen
{
private TiledMap map;
private OrthogonalTiledMapRenderer renderer;
private OrthographicCamera camera;

private Megaman megaman;

@Override
public void render(float delta)
{
    float dt = Math.min(Gdx.graphics.getDeltaTime(), 1 / 60f);
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    renderer.setView(camera);
    renderer.render();
    renderer.getBatch().begin();
    megaman.update(dt);
    megaman.draw(renderer.getBatch());
    renderer.getBatch().end();
}

@Override
public void resize(int width, int height)
{
    camera.viewportWidth = width;
    camera.viewportHeight = height;
    camera.setToOrtho(false, width, height);
    camera.update();
}

@Override
public void show()
{
    map = new TmxMapLoader().load("maps/test2.tmx");

    renderer = new OrthogonalTiledMapRenderer(map);

    camera = new OrthographicCamera();
    megaman = new Megaman(new Sprite(new Texture("img/Megaman/megaman_idle.png")), (TiledMapTileLayer) map.getLayers().get(0));
    megaman.setPosition(14 * megaman.getCollisionLayer().getTileWidth() , (megaman.getCollisionLayer().getHeight() -  22) * megaman.getCollisionLayer().getTileHeight());

    Gdx.input.setInputProcessor(megaman);

}

@Override
public void hide()
{
    dispose();
}

@Override
public void pause()
{

}
@Override
public void resume()
{

}

@Override
public void dispose()
{
    map.dispose();
    renderer.dispose();
    megaman.getTexture().dispose();
}
}

```

# Answer
> 0 votes
The problem with your code is here:

```
@Override
public boolean keyUp(int keycode) {
switch (keycode)
{
case Keys.W:
    //when W is released, set Y velocity to 0
    velocity.y = 0;
    break;
case Keys.A:
case Keys.D:
    velocity.x = 0;
    break;
}
return true;
}

```

While `canJump` is a boolean that checks if the character has jumped, I assume you want the megaman style of jumping, so that as soon as you let go of the button, you start falling, but we need to track if the user has let go of the button this jump, like this:

```
@Override
public boolean keyUp(int keycode) {
switch (keycode)
{
case Keys.W:
    if (released == true)
    {
        //when W is released, set Y velocity to 0
        velocity.y = 0;
        released = false;
        break;
    }
case Keys.A:
case Keys.D:
    velocity.x = 0;
    break;
}
return true;
}

```

```
if(velocity.y < 0){ // going down
    canJump = collisionY = collidesBottom();
    released = collidesBottom();
}

```

---
Tags: java, libgdx, platformer
---


# Question
Title: OpenGL - Quad is being separated like a two triangles after blending
I wanted to add transparency for my UI elements, so I enabled blending by adding:

```
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

```

before renderer and

```
glDisable(GL_BLEND);

```

after renderer.

So I tried to render simple rectangle (with `glDrawArrays()` because I'm using GLSL shaders).

Before I enabled blending my rectangle (1 quad) looked like this:

And now, after blending it looks like this (Like a two triangles):

Do I need some extra settings for my blending or what?

Edit:

I noticed that if I remove anti-aliasing code:

```
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

glEnable(GL_LINE_SMOOTH);
glEnable(GL_POINT_SMOOTH);
glEnable(GL_POLYGON_SMOOTH);

```

Problem will disappear, but I want to keep anti-aliasing in my game. Any ideas?

# Answer
> 1 votes
Modern hardware often lacks the ability to actually draw quads. If you're using a legacy API like OpenGL, the drivers will generally just emulate quad support by asking the hardware to draw two triangles.

With general edge smoothing, you'd get pretty much exactly what you're seeing. Of course, polygon smoothing itself is a legacy artifact of OpenGL's history and not a feature you should actually be using in modern code.

If you want anti-aliasing, use MSAA or a post processing filter to smooth your scene. Do not use the OpenGL smoothing controls. They're effectively dead legacy cruft in the GL API. I'm surprised they work at all still, honestly.

Notes on how polygon smoothing produces the effects you're seeing.

Apple apparently removed support for polygon smoothing entirely almost a decade ago.

---
Tags: opengl, blending
---


# Question
Title: how to check mouse is not over any object in unity
Im working on a way to check mouse is not over any object on scene to put my object in there. i know i can use **OnMouseOver** function but i have to add it on all objects script. Is there any other way to check my mouse position is not on any object collider? Its a 2d project. thank you for helping

# Answer
> 2 votes
An easy way to handle input over a range of gameobject, is to raycast and handle the input yourself.

Consider doing something like this in the Update loop.

```
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        Vector2 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        RaycastHit2D[] hits = Physics2D.RaycastAll(pos, new Vector2(0, 0), 0.01f);

        for (int i = 0; i < hits.Length; i++)
        {
            if (hits[i].collider.tag == "Button")
            {
                 Button button = hits[i].collider.GetComponent<Button>();
                 button.Submit();
            }
        }
    }
}

```

# Answer
> 2 votes
You can use 2D RayCast to get the desired effect. In the following example I only have it checking when the user clicks, but I'm sure you can work it out from there.

The trick to checking a single point in 2D is to not give the raycast direction as shown below with vector2.zero

```
using UnityEngine;
using System.Collections;

public class RayCastPoint : MonoBehaviour
{
    public Camera MainCamera;

    // Use this for initialization
    void Start ()
    {
        if(MainCamera == null)
            Debug.LogError("No MainCamera");
    }

    // Update is called once per frame
    void FixedUpdate ()
    {
        if(Input.GetMouseButtonDown(0))
        {
            var mouseSelection = CheckForObjectUnderMouse();
            if(mouseSelection == null)
            {
                Debug.Log("nothing selected by mouse");
            }
            else
            {
                Debug.Log(mouseSelection.gameObject);
            }
        }
    }

    private GameObject CheckForObjectUnderMouse()
    {
        Vector2 touchPostion = MainCamera.ScreenToWorldPoint(Input.mousePosition);

        RaycastHit2D hit2D = Physics2D.Raycast(touchPostion, Vector2.zero);

        return hit2D.collider != null ? hit2D.collider.gameObject : null;
    }

}

```

---
Tags: unity
---


# Question
Title: How to make a 2D Soft-body physics engine?
The definition of **rigid body** in Box2d is

> A chunk of matter that is so strong that the distance between any two bits of matter on the chunk is completely constant.

And this is exactly what i don't want as i would like to make ***2D*** (maybe 3D eventually), elastic, deformable, breakable, and even sticky bodies.

What I'm hoping to get out of this community are resources that teach me the math behind how objects bend, break and interact. I don't care about the molecular or chemical properties of these objects, and often this is all I find when I try to search for **how to calculate what a piece of wood, metal, rubber, goo, liquid, organic material, etc. might look like after a force is applied to it.**

Also, I'm a very visual person, so diagrams and such are EXTREMELY HELPFUL for me.

# Answer
Blob Physics is likely what you're looking for.
> 3 votes

# Answer
It sounds like you are trying to implement a mass spring system for deformable bodies.

Your bodies springs must have a "breaking" value that will separate them into individual bodies if the force applied exceeds this value. That will handle the smashing effect. for deformation, the mass spring system will work, but I should point out that it's processor intensive, so a GPGPU solution will be desirable.

Fracture mechanics are very complex, and a field of study in and of itself. Many games just fudge it, as "close enough" effects are often enough to fool the user.

For example, take a stick. If an impact halfway has enough force to cause it to break, just create two more sticks with half the length, and noone will be the wiser. 90% of games tech is smoke and mirrors, and creating convincing fake physics. Only the trained eye will notiice the difference.
> 0 votes

---
Tags: mathematics, physics, physics-engine
---


# Question
Title: How do engines avoid "Phase Lock" (multiple objects in same location) in a Physics Engine?
Let me explain Phase Lock first: When two objects of non zero mass occupy the same space but have zero energy (no velocity).

Do they bump forever with zero velocity resolution vectors or do they just stay locked together until an outside force interacts?

In my home brewed engine, I realized that if I loaded a character into a tree and moved them, they would signal a collision and hop back to their original spot. I suppose I could fix this by implementing impulses in the event of a collision instead of just jumping back to the last spot I was in (my implementation kind of sucks).

But while I make my engine more robust, I'm just curious on how most other physics engines handle this case. Do objects that start in the same spot with no movement speed just shoot out from each other in a random direction? Or do they sit there until something happens? Which option is generally the best approach?

# Answer
> 4 votes
I guess this kind of ends up being a non-answer...

I think sometimes it depends on the implementation and the basic approach used for collision detection and resolution (which is like 80% of a rigid body physics engine, I guess). It's funny because I just hit this problem the other day in my own home-grown physics engine and threw an object into NaN space.

I had an object spawn in exactly the same spot as another object and both were the same shape. In this particular case the contact generator made very bad values. I fixed it by picking arbitrary values for the contact (push smaller/lighter object straight up, basically). This was a pretty cut and dry, case, though.

If a chair were to spawn inside of a table then it would be dependent on what contacts were generated whether they flew apart or got stuck. In my case, I'm not using a constraints based system (at least not yet) so the object is just as likely to blow apart as to oscillate and fall asleep. In a penetration+impulse system like the one I use it's pretty easy to see all of the ugly and how it will result. I have no idea how a constraints based system solves this problem or if it even detects it... the constraint seems unreachable to me without some intervention and I have no idea if there is a standard way for those types of engines.

Others will surely have smarter things to say but this was too long for a comment.

# Answer
> 0 votes
This is handled in two ways:

1. Correct the overlap between collidable objects
2. generate a "normal" force which will push objects apart, should they collide.

This only works, however, if you are differentiating velocity/time. It won't work in a tile based game, and will result in visible artefacts, such as one object either tunneling through an object, or being visibly pushed out of the other object.

In the case of tile based games, you can take a predictive approach, by checking where the object will be *if* it moves. If the movement would cause phase lock, then disallow the movement.

---
Tags: physics, physics-engine
---


# Question
Title: What different ways are there to model restitution in a physics engine?
In my physics engine I give a body a value for restitution between 0 and 1. When two bodies collide there seems to be different views on how the restitution of the collision should be calculated. To me the most intuitive seems to be to take the average of the two but some seem to take only the largest one.

Are there other ways to do it? Also, could the closing velocity or some other parameter come into effect?

# Answer
> 1 votes
> Also, could the closing velocity or some other parameter come into effect?

According to Wikipedia,

> in a series of experiments performed at Florida State University in 1955, it was shown that the COR varies as the collision speed approaches zero, first rising significantly as the speed drops, then dropping significantly as the speed drops to about 1 cm/s and again as the collision speed approaches zero.

Sadly the link to the paper on this is dead.

---

To answer the main question, Cholesky's suggestion of a table is a good one, but if you want to reduce the number of cases you have to select values for then one approach would be to store for each material a base restitution and a weight with which to take a weighted average. What restitution is really about is how much of the energy of the collision is converted into forms other than the post-collision kinetic energy of the bodies. Sound can be neglected: what you're interested in is deformation. So give easily deformed materials such as soft sand a high weight and a low restitution and you have a model which should be good enough.

After all, games only have to feel right to the player: they don't have to be accurate simulations of the real world.

# Answer
> 2 votes
I personally think that taking the largest one make the most sense: (throwing a bouncy ball at a brick bounces even though a brick has no restitution to speak of), but if you have a game where you need to model complex bouncy interactions you could store a "material" per body and build up a materialA vs. materialB lookup table.

# Answer
> 1 votes
BulletPhysics seems to just multiply the restitution factors. This might not be a universal solution, but it satisfies the "everything just works" approach when adding new materials.

# Answer
> 0 votes
From a physics standpoint, the minimum restitution between two bodies should be used.

Think of gel hitting a rubber ball. The rubber ball has high restitution, but the gel has low. The rubber ball will not bounce off the gel. In the case of bounciness, lowest wins.

However, gel has low density, which allows the ball to penetrate it and hit something with higher restitution, such as the ground.

The gel will absorb some of the kinetic energy of the ball, how far the ball bounces, often considerably. But that's a bit off topic.

Restitution is a representation of loss of kinetic energy through collisions, so the lowest value is the most accurate. Throw a golf ball at a block of soft clay and you will see what I mean.

---
Tags: physics, physics-engine
---


# Question
Title: How to deal with pushing objects out of collision in a physics engine
I'm developing a 3D physics engine (I know, I should use one of the many good existing physics libraries, however my collision detection is optimised for objects with highly ordered highly complex substructure which seems to be unusual and slow in the engines I've tried).

Collision detection is working really nicely, as are bouncing type behaviours but contact behaviours are not behaving nicely at all. Initially I had the problem that an object would spin up out of control if it had prolonged contact with a surface; I found that the reason for this was that an object was falling under gravity into collision, then getting a "free ride" upwards while it was pushed out of collision; giving the object free energy. If a significant portion of this energy made it into rotational degrees of freedom then considerable energy could be imparted before eventually the object was flung outwards. My solution to this was to impart an energy penalty when pushing out of collision equal to:

```
 EnergyPenalty=mass * gravity dotted with the push-out-of-collision vector (i.e the E=m*g*h it has gained for free)

```

This improved matters considerably, but now objects "get stuck" on their corners just before the shape relaxes into its resting position; presumably because too much energy seems to be being taken away.

A loop round the engine works as following

-Collisions detected
-Pushed out of collision (energy penalty if pushed up against gravity)
-Collisional forces applied if object are still approaching (may not be the case if push energy penalty slowed to 0)
-Gravity applied
-Contact forces applied if object are still approaching (as collision but with elasticity = 0)
-Move and rotate objects

I've taken friction out of the equation for the time being

I’ve found that while in contact with the surface the contact forces correctly bring the two objects at their collision points to zero relative velocity (taking into account both translation and rotation) but that that balance of translational movement balancing rotation is instantaneous. I.e. over a complete physics step the rotational component changes to be no longer in perfect balance with the translational. So a very small push-out-of-collision is required even when in ‘contact mode’ with a very small energy penalty to boot. However this energy penalty seems too large; freezing the object in position.

Which brings me to my question; what is the correct way to deal with the “free energy” imparted by a push-out-of-collision in a collision resolution step? (Even if the answer is; what you're doing is the correct way to deal with it i'll know this is a debugging issue not an algorithmic issue)

# Answer
If I understand, you currently apply a collision impulse--an instant change to linear and angular velocity--with the goal of bringing the relative velocity of the contact point to zero.

However, the point may still be penetrating, so you try to "push out" of collision using either force (over time) or another impulse. A problem with this approach is that, once the contact point is free of penetration after the next frame or so, it continues moving away (undesired for resting contact).

To resolve the penetration, instead of an impulse, you may consider applying an "offset". (I don't know the correct physics term here because I've never seen this discussed.) I just mean an instant change to linear and angular position, with the goal of bringing the penetration depth to zero. The math (how much to translate the COM? How much to rotate?) is similar to your impulse calculation (involving mass and inertia tensor).
> 3 votes

# Answer
I'm going to ignore angular effects here for simplicity.

In your contact resolution function, do the following: calculate relative velocity of the two bodies. if the relative velocity dot normal \< 0 apply no force (moving apart) else correct position, to make penetration distance == 0 calculate normal force based on relative velocity / combined inverse mass apply impulses to bodies.

Google "physics engine slop" for more info.
> 0 votes

---
Tags: collision-resolution, physics-engine
---


# Question
Title: How should browser based muiltiplayer game state be syncronized using WebSockets and a Node.js backend?
I'm in the process of learning how to create browser based html5 games. I'd like to eventually be able to achieve a game with mechanics very similar to that of the game agar.io. I've been observing coding streams and doing a fair amount of reading on the subject of network latency, jitter, and buffering but I'm still having difficulty ironing out an appropriate aproach to coding a node.js implementation to handle these things. I'm not so much as interested in having a solution provided to me as learning how more expierenced developers code tick counts, frames, etc...

Thank you all very much for your time and I very much look forward to any input your willing to provide regarding the subject. :)

# Answer
> 0 votes
Node.js & *the event loop* :
To prevent flooding the action queue by multiple users playing the same game, I would divide the MMO into game rooms or game regions / zones. Dividing the game server into independent threads that could even run on independent machines.

A `login socket server` for handling new incoming clients
with a `db reader & writer process` for db queries & updates
For each game room available a `zone socket server` (for communicating with clients that are interacting in that specific zone : action requests & action result emission)
with a corresponding forked `zone manager process`
(for validating requests & result generation)

Maybe you like some personal notes...
(maybe a chance for this model to be reviewed & evaluated by the opinions of other devs)

```
<client>        Socket.emit('login_request', {credentials})
<server>        Receive login request [send to db_rwp]
<db_rwp>        Validate login_request {credentials} :: if valid fetch client (user) data & insert entry in active_sessions db table
<server>        Evaluate user.region : prepare region for client (ipc between procs with the folowwing data) {user:'{userData}', secret:'%ha$h%', csid:'login_handshake'}
<region>        Store @ incomingClients['%ha$h%'] ) = '{userData}'
                Inform to login.server {action:'prepared', region:'region_id', csid:'login_handshake'}
<server>        Inform Database then client
<db_rwp>        UPDATE sessions WHERE socket_id = login_handshake
<server>        Now inform the client :: io.to(data.csid).emit('valid_login', user:'{userData}', region:{id:'region_id', port:'region_port', secret:'%ha$h%'})
<client>        Load region splash screen while socket disconnects from <server> and connects to <region> (server:region.port)
<region>        On client connect, return a client probe (requesting the secret hash)
<client>        Client is probed, return a Socket.emit('region_snapshot_request', '%hash%');
<region>        if incomingClients['%ha$h%'] is found valid
                    return the snapshot to the incomingClient
                    notify the incomingClient to the activeClient[]
                    activeClient['region_handshake'] = incomingClients['%ha$h%']
                    then destroy the incomingClients['%ha$h%']
                    Inform to login.server {action:'completed', region:'region_id', old_csid:'login_handshake', csid:'region_handshake'}
<server>        Inform handshake changes to Database
<db_rwp>        UPDATE sessions SET socket_id=csid WHERE socket_id=old_csid

```

Here I gave an answer that contains a client model that will only render what the server emits.
https://gamedev.stackexchange.com/a/116531/52482

---
Tags: html5, browser-based-games, node.js, websocket
---


# Question
Title: Can copying assets be legal if I'm not intending to make money?
I very recently started going through game development tutorials and I was thinking of trying to mimic a game I know as closely as possibly just to see if I can do it as a first project.

I wouldn't at all be wanting to sell this game but would I be able to show this in some kind of online portfolio so long as I mention that none of the assets are mine and give credits to the relevant companies/people?

# Answer
> 0 votes
It depends on the license under which the assets have been released. Most of the time you just put "xxx asset is being used under YYY License" and refer to the source. Typically when you download assets from an online source there will be `LICENSE.txt` attached. If there is no such file, next thing would be to contact the person who did the tutorials. If all of the above fails, considering these assets have been used in the tutorial to be followed and recreated, your approach should be fine. (**Please note that this answer is not legal advice**)

---
Tags: legal
---


# Question
Title: Spawning random objects at random positions in the 3D world
My main character can move horizontally and not vertically. It can move from x = -4 to 4 and z = -4 to 4 (a square area). I don't want objects to spawn where my character can move but every where else.
I wrote the following script. According to me it should have worked perfectly fine. But, I can't figure out why the objects are still spawning in the perimeter where the main character is present.

```
public class SpawnGameObjects : MonoBehaviour
{
    public float secondsBetweenSpawning = 0.1f;
    public float xMinRange = -25.0f;
    public float xMaxRange = 25.0f;
    public float yMinRange = -5.0f;
    public float yMaxRange = 0.0f;
    public float zMinRange = -25.0f;
    public float zMaxRange = 25.0f;
    public GameObject[] spawnObjects; // what prefabs to spawn

    private float nextSpawnTime;

    void Start ()
    {
        // determine when to spawn the next object
        nextSpawnTime = Time.time+secondsBetweenSpawning;
    }

    void Update ()
    {
        // exit if there is a game manager and the game is over
        if (GameManager.gm) {
            if (GameManager.gm.gameIsOver)
                return;
        }

        // if time to spawn a new game object
        if (Time.time  >= nextSpawnTime) {
            // Spawn the game object through function below
            MakeThingToSpawn ();

            // determine the next time to spawn the object
            nextSpawnTime = Time.time+secondsBetweenSpawning;
        }
    }

    void MakeThingToSpawn ()
    {
        Vector3 spawnPosition;

        // get a random position between the specified ranges
        spawnPosition.x = Random.Range (xMinRange, xMaxRange);
        spawnPosition.y = Random.Range (yMinRange, yMaxRange);
        spawnPosition.z = Random.Range (zMinRange, zMaxRange);
        if ((spawnPosition.z < 4 && spawnPosition.z > -4) || (spawnPosition.x < 4 && spawnPosition.x > -4))
        {
            MakeThingToSpawn ();
        }

        // determine which object to spawn
        int objectToSpawn = Random.Range (0, spawnObjects.Length);

        // actually spawn the game object
        GameObject spawnedObject = Instantiate (spawnObjects [objectToSpawn], spawnPosition, transform.rotation) as GameObject;

        // make the parent the spawner so hierarchy doesn't get super messy
        spawnedObject.transform.parent = gameObject.transform;
    }
}

```

# Answer
> 2 votes
I think you problem is caused by continuing to execute the method when invalid position is generated:

```
//is position valid?
if ((spawnPosition.z < 4 && spawnPosition.z > -4) || (spawnPosition.x < 4 && spawnPosition.x > -4))
{
    //no -> call again
    MakeThingToSpawn (); //this will likely generate object at valid position
    //...and continue to execute this function after returning from function call above
    // spawning second object originally generated, at invalid position(!)
    return; //add return to quickfix to your problem - it will stop exectuing the rest of the function
}

```

also I would improve the method a bit - as for now it could(though unlikely) cause stack overflow, crashing the game. Again the problem is `MakeThingToSpawn ();` recursion. Rather then using recursion, I would translate the result to correct range, I would replace the code above with these two lines:

```
private static readonly double safeZoneSize = 4.0; //up in definitions
//greater than zero? add the safe zone size, subtract otherwise
spawnPosition.x += spawnPosition.x > 0 ? safeZoneSize : -safeZoneSize ;
spawnPosition.z += spawnPosition.z > 0 ? safeZoneSize : -safeZoneSize ;

```

*note: you need to compensate the safe zone size in the valid range definition(!)*

---
Tags: unity, c#, monogame
---


# Question
Title: AntTweakBar doesn't register SFML mouse events
I'm trying to add GUI for easier level editing in our game engine. We're using SFML for all the basic stuff (window management, input events etc). I've chosen AntTweakBar because it is a well known library with a few examples around. I was following the tutorial at AntTweakBar's website

I was able to draw a simple bar with those example codes. However, mouse events received by SFML are not registered by AntTweakBar's `TwEventSDL()` function. Here is an example code for Input:

```
sf::Event event;
while (_pWindow->pollEvent(event))
{
    // Check if the event should be handled by AntTweakBar
    int handled = TwEventSFML(&event, 2, 3); // for SFML version 2.3
    if (!handled){
        switch (event.type)
        {
        case sf::Event::MouseButtonPressed: // To check whether SFML received mouse button events properly
            if (event.mouseButton.button == sf::Mouse::Button::Left){
                std::cout << "Left button pressed" << std::endl;
                std::cout << "x: " << event.mouseButton.x << std::endl;
                std::cout << "y: " << event.mouseButton.y << std::endl;
            }
        }
    }
    else{ //To check whether TwEventSFML received events
        std::cout << "FINALLY!" << std::endl;
    }

```

When I press buttons, I can see "FINALLY!" showing up. I can also see that my mouse clicks are received by SFML. However, when I click on an AntTweakBar element (be it a button or help section) it doesn't register it. (Also, I can't see "FINALLY!" when I use the mouse).

Any help or ideas will be appreciated.

# Answer
> 2 votes
Anttweakbar hasnt been updated in 3 years, last SFML integration was for SFML 1.6 Are you using SFML 1.6 ? if not then you have to create your own input handler for it.

---
Tags: gui, input, sfml
---


title: Start Menu Does not Work

text:
# Question
Title: Start Menu Does not Work
On starting the game, a basic startmenu should load. startScreenUI is the background image, and startUI is the buttons for "play" and "exit".

I set Time.timescale to zero in Awake() so that the time would initially be set to zero.

However, the game just plays behind the start screen as normal.

My PauseMenu scripts runs perfectly, pausing the game etc.

My MoveEnemy scripts controls the movement of a wall that moves back and forth between the scene. It moves fine, on pause it stops moving. I should add that the Wall is kinematic and used gravity.

I do not understand why the initial time.Timescale is not set to zero upon starting the game and the game runs normally behind the start screen.

My code for the StartMenu:

```
using UnityEngine;
using System.Collections;

public class StartMenu : MonoBehaviour
{

public GameObject startUI;
public GameObject startScreenUI;
public PauseMenu otherscript;

  private void Awake() {
    otherscript.enabled = false;
    startUI.SetActive(true);
    startScreenUI.SetActive(true);
    Time.timeScale = 0;
  }

  private void Start() {
    startUI.SetActive(true);
    startScreenUI.SetActive(true);
    Time.timeScale = 0;
  }

  public void Play() {
    startUI.SetActive(false);
    startScreenUI.SetActive(false);
    Time.timeScale = 1;
  }

  public void Quit() {
    Application.Quit();
  }
}

```

This is my code for the Moving of the Enemy Walls:

```
using UnityEngine;
using System.Collections;

public class MoveEnemy : MonoBehaviour {
  public Vector3 pos1 = new Vector3 (-7.6f, 1.1f, 7f);
  private Vector3 pos2 = new Vector3(7.6f, 1.1f, 7f);
  public float speed = 1.0f;

  // get StartMenu for bool of startUI

  public StartMenu otherScript;

  // get PlayerController for bool of "dead" to reset the static component manually
  // resets the position of the wall

  void Awake() {
    transform.position = pos1;
  }

  // moves object from pos1 to pos 2
  void Update () {
    transform.position = Vector3.Lerp(pos1, pos2, Mathf.PingPong(Time.time * speed, 1.0f));
  }
}

```

using the Awake() function was a troubleshooting attempt I heard worked to reset the position of the walls upon restart. But as my game does not restart properly, I do not know if this works fully yet.

and finally this is my code for the Pause Menu that actually works:

```
using UnityEngine;
using System.Collections;

public class PauseMenu : MonoBehaviour {

  public GameObject pauseUI;
  private bool paused = false;

  void Start() {
  }

  void Update() {
    if(Input.GetButtonDown("Pause")) {
      paused = !paused;
    }

    if(paused) {
      pauseUI.SetActive(true);
      Time.timeScale = 0;
    }

    if(!paused) {
      pauseUI.SetActive(false);
      Time.timeScale = 1;
    }
  }

  public void Resume() {
    paused = false;
  }

  public void Restart() {
  }

  public void MainMenu() {
    Application.LoadLevel(0);
  }

  public void Quit() {
    Application.Quit();
  }
}

```

Initially I wondered if the problem was associated with the PauseMenu's timescale function interfering with the timescale set on the startMenu, but on disabling the PauseUI completely the game still ran behind the start screen.

Can anyone think of a quick fix to this? I have been troubleshooting for a while and not really getting anywhere.

# Answer
> 1 votes
I believe what happens is that you set the Time.timescale to 0 in the start menu script but at the same time you have the pause menu script setting the Time.timescale to 1 because your variable pause is false. So what you could do is change your pause script so that it only is able to resume the game (set pause to false) if the game was previously paused.

Another option is to make another public Boolean variable (for example called "canRun") in the pause script then when ever the game starts (eg. Start button is pressed) you set canRun to true from the start menu script. In your pause script you adjust your if statement to check for canRun as well. Change this if statement:

```
 if(!paused) {
  pauseUI.SetActive(false);
  Time.timeScale = 1;
}

```

To look like this:

```
 if(!paused && canRun) {
  pauseUI.SetActive(false);
  Time.timeScale = 1;
}

```

# Answer
> 0 votes
Time.timeScale is global and is affecting all instances using time related functionality.

You are setting TimeScale to 1 every frame in your Update method since the member **paused** is false from the start in you Pause menu script. This is setting timescale to 1 as soon as the game is not paused, for example directly when the level is loaded, in the start screen.

```
if(!paused) {
  pauseUI.SetActive(false);
  Time.timeScale = 1;
}

```

I would recommend using methods for Pause and UnPause and restrict timescale to be controlled only in those methods.

Quick fix: make a reference to *PauseMenu* in *StartMenu* and deactivate it in *Awake*.

---
Tags: c#, unity
---


# Question
Title: Show procedural map without running the game?
Currently I have a script that generates prefabs by code and I'm wondering if I could show a certain "seed" of that map without actually running the game. The reason why is that I often want to tweak things, and when I run the game and alter settings for objects like lights they get reset when I stop running the game and perhaps have some kind of button where I can reset the seed and see another generation of the map.

# Answer
> 2 votes
You could write your own **CustomEditor** script for your map generation, where you show a button that will trigger the map generation with the new settings and instantiate it.

A small example:

```
using UnityEngine;
using System.Collections;

[CustomEditor(typeof(MyMapGenerator))]
public class MyMapGeneratorEditor : Editor
{
    // cache the current map preview
    Transform current;

    public override void OnInspectorGUI()
    {
        // target is a variable that is available to scripts that derive from Editor
        // and holds the Object that is being inspected
        MyMapGenerator gen = (MyMapGenerator)target;

        DrawDefaultInspector();
        if(GUILayout.Button("Generate and preview"))
        {
            // Generate() should create and return the prefab
            var prefab = gen.Generate();

            // delete the cached preview if there is one
            if(current != null)
                DestroyImmediate(current);

            // instantiate a new preview and cache it
            current = Instantiate(prefab);
        }
    }
}

```

Please note that I have not tested this script, so there may be errors.

You can find more Information on Custom Inspectors from Unity here

---
Tags: unity, procedural-generation
---


title: Unity: C# Spell System

text:
# Question
Title: Unity: C# Spell System
I couldn't find any proper tutorials in the internet how to make one so I tried it myself. I've written a base "Skill" class with methods like `Cast()`, `DealFlatDamage()`, `ShootProjectile()` and they all work so far. But I also wanted to implement trigger methods for passive spells: `OnDeath()`, `OnKilled()`, `OnProjectileHit()`.

**First Question:** Is this a wrong way to go? Because I couldn't find anything like this in the internet.

**Second Question:** The idea was to create new classes inheriting from this base class and the base class calling all the "On..."-methods of each derived class. How can I do this?

Would appreciate help!

# Answer
> 3 votes
There is no right or wrong way to do this, but here is an alternative approach.

```
interface IOnDeath
{
    void Action( /*some context here*/ );
}

class Skill
{
    public List<IOnDeath> OnDeathEffects;
}

class OnDeathNova : IOnDeath
{
    public void Action(...)
    {
        /* creates an outward facing ring of projectiles */
    }
}

...
    skill.OnDeathEffects.Add(new OnDeathNova());
...

```

This gives you a very dynamic approach, and lets you modify things at run-time. Maybe you want to make a spell deal double damage when a buff is applied. Maybe you want to have it bounce. All these things could be hardcoded into a single class, but it would get messy fast. This approach lets you give each "effect" their own separate implementation.

---
Tags: unity, c#
---


# Question
Title: Creating a Zelda-like map in pure C++ not working
I wanted to create a map like in Zelda, but it keeps showing hashtags instead of 1 on A1 and I don't know why.

```
vector <string> A0 {"#","#","#","#","#","#","#","#","#","#"};
vector <string> A1 {"1","1","1","1","1","1","1","1","1","1"};
vector <string> A2 {"#","#","#","#","#","a","#","#","#","#"};
vector <string> A3 {"#","#","#","#","#","#","#","#","#","#"};
vector <string> A4 {"#","#","#","#","#","#","#","#","#","#"};
vector <string> A5 {"#","#","#","#","#","#","#","#","#","#"};
vector <string> A6 {"#","#","#","#","#","#","#","#","#","#"};
vector <string> A7 {"#","#","#","#","#","#","#","#","#","#"};
vector <string> A8 {"#","#","#","#","#","#","#","#","#","#"};
vector <string> A9 {"#","#","#","#","#","#","#","#","#","#"};
int main()
{
    vector <vector<string>> MiniMap {A0,A1,A2,A3,A4,A5,A6,A7,A8,A9};//A0-9 rows
    for (unsigned z=0;z<MiniMap.size();z++)
    {
      cout<<z<<".";
      for (unsigned i =0;i<MiniMap[z].size();i++)
          cout<<MiniMap[0][i];
      cout<<"\n";
    }
    return 0;
}

```

The idea is that it would show the entire map, but it doesn't work for some reason, please help.

# Answer
```
cout<<MiniMap[0][i];

```

Shouldn't it be

```
cout<<MiniMap[z][i];

```

?
> 2 votes

---
Tags: c++
---


# Question
Title: My SDL Game executable cannot run outside codeblocks
After compiling and running SDL programs successfully inside CodeBlocks, when I run them outside CodeBlocks (by clicking .exe file) my program does not run. Instead, it says that libstdc++6.dll is missing from computer.

I have all the SDL dlls, but why is this error happening?

# Answer
> 7 votes
In the linker options add -static-libgcc or -static-libstdc++ ( -static-libgcc worked for me )

Alternatively add the libstdc++6.dll from the compiler bin folder to the folder where your exe resides.( Assuming we are talking about MingW/Gcc it's in mingw/bin/)

# Answer
> 3 votes
Often when you run a program inside an IDE it sets a specific 'working directory' where it looks for your DLLs. This may not be the same directory as where your executable is located.

To fix this, you usually need to do the following:

* Ensure the exe is being output in the place you want (usually under the project's output or linker settings)
* Move all DLLs to that place (do this yourself, via Explorer etc)
* Ensure the IDE runs the exe from that location (usually under the project's debug settings)

This allows it to work the same way whether run from the IDE or not.

# Answer
> -2 votes
Try compiling it on another computer, or reinstall codeblocks along with gcc. At least that's how it worked for me.

---
Tags: c++, software-engineering, sdl
---


title: MinGW Windows Cross-Compile Error

text:
# Question
Title: MinGW Windows Cross-Compile Error
While I was developing my game on Linux (I'm using an ARM system), I decided that I want to cross-compile it to Windows. Yet, I get an error while I try to link Allegro (version 4.2) to the compiler.

I have installed MinGW32 (x86\_64-w64-mingw32-c++ in the terminal) and have moved the bin / include / lib folders from the Windows Allegro version to the /usr/x86\_64-w64-mingw32-c++/ folder.

When I enter into the command line:

```
x86_64-w64-mingw32-c++ *.cpp -o W_Survival `allegro-config --libs`

```

It returned to me a linking error:

```
/usr/bin/x86_64-w64-mingw32-ld: unrecognized option '-z'
/usr/bin/x86_64-w64-mingw32-ld: use the --help option for usage  information
collect2: ld returned 1 exit status

```

The compiling is all the same as I would do it using g++. the only thing different is that I have it set to compile for windows.

Is there anything that I did wrong? All help is appreciated :)

# Answer
> 1 votes
You need to make sure you link against the correct version of your dependencies: In this case, the 64-Bit MinGW ones.

---
Tags: windows, cross-platform, linux, mingw
---


# Question
Title: Using sourceRect or cropping out a Texture 2D to draw? MonoGame/XNA
I was wondering what is the best way to draw textures (for performance). Using the sourceRectange in the spriteBatch.Draw() call and just draw the whole spriteSheet, or crop out every texture on the spritesheet and store them in there own Texture2D object? Like this :

```
    public static Texture2D Crop(Texture2D spriteSheet, Rectangle source)
    {
        Texture2D croppedTexture2d = new Texture2D(spriteSheet.GraphicsDevice, source.Width, source.Height);
        Color[] imageData = new Color[spriteSheet.Width * spriteSheet.Height];
        Color[] croppedImageData = new Color[source.Width * source.Height];

        spriteSheet.GetData<Color> (imageData);

        int index = 0;

        for (int y = source.Y; y < source.Y + source.Height; y++)
        {
            for (int x = source.X; x < source.X + source.Width; x++)
            {
                croppedImageData [index] = imageData [y * spriteSheet.Width + x];
                index++;
            }
        }

        croppedTexture2d.SetData<Color> (croppedImageData);
        return croppedTexture2d;
    }

```

And just call that method in the LoadContent() method?

# Answer
The sourceRect is much better for this.

Watch this if like a funny video explaining why:

https://www.codeandweb.com/what-is-a-sprite-sheet-performance

The more technical explanation:

I am using pseudo code - the exact number of commands required might vary - but you should see what I am talking about.

If you use isolated sprites the game engine has to perform the following actions on OpenGL (pseudo-code)

```
foreach sprite as s do
    gl->setTexture(s)
    gl->setSpriteCoordinates(s)
    gl->setDestinationCoordinates(s)
    gl->draw()
end

```

So you end up with approx. 4\*number\_of\_sprites OpenGL calls. These commands are usually asynchronous - but depending on the exact calls you are using this might even trigger a synchronization between OpenGL and your code. That means: Your code waits until the draw operation is finished. Just wasting the CPU cycles during the refresh.

Using a sprite sheet and a sprite batch changes this completely:

```
foreach sprite as s do
    sourceCoordinates[] = s->sourceCoordinates()
    destinationCoordinates[] = s->destinationCoordinates()
end
gl->setTexture()
gl->setSpriteCoordinateList(sourceCorrdinates)
gl->setDestinationCoordinateList(desintationCoordinates)
gl->draw()

```

As you see only 4 OpenGL calls are required. It's simply setting the coordinate lists which have been pre-processed.

The drawing process runs now asynchronously without interruption and the CPU is free for other tasks.

The plain drawing process might take more or less the same time - but you've reduced the overhead for the communication - and the CPU is available.
> 3 votes

# Answer
Using the sourcerect is better performance wise.

The GPU benefits from as little texture changes as possible. With a textureatlas one texture is sent to the GPU and all sprites can be batched without a texture change.

In reality sprites are actually quads with each vertex points to a coordinate in the texture based on the source rectangle. All vertices inside the same batch are then drawn as one drawcall. This is the reason sprite atlasses are used.
> 0 votes

---
Tags: xna, textures, monogame, spritesheet, texture-atlas
---


# Question
Title: How can I once run For Loop in void OnGUI?
I want once run GUI on screen same Initialization a number. I try say my think In easiest way then please payattention to this code:

```
using UnityEngine;
using System.Collections;

public class guimanager : MonoBehaviour {
    public bool Isdone;
     void OnGUI()
    {
            for (int j = 0; j <= 100; j+=20) {
            if (Isdone == true) {
                break;
            }

            GUI.Box(new Rect(j, j, Screen.width/2, Screen.height/2), "This is a test");
                print (j);
            }
        }
    }

```

I want keep my GUI.Box When end loop,So I need a boolean that when finish stop loop.

my problem Is frequent loop:

```
0,1,2,3,4,5,0,1,2,3,4,5,0,1,2,3,4,5,0,1,2,3,4,5,0,1,2,3,4,5,......

```

GUI.Box will Show

but When I want break my loop:

```
0,1,2,3,4,5

```

GUI.Box won't Show!!!!

Can I show my GUI.boxes In my loop when finished?

```
using UnityEngine;
using System.Collections;

public class guimanager : MonoBehaviour {
    public bool Isdone;
     void OnGUI()
    {
            for (int j = 0; j <= 100; j+=20) {
            if (Isdone == true) {
                break;
            }

            GUI.Box(new Rect(j, j, Screen.width/2, Screen.height/2), "This is a test");
                print (j);
            }
Isdone = true;
        }
    }

```

Why when I stop loop GUI.Box won't show!!!

# Answer
Because you are showing `GUI.Box` in your for loop after `break`. That is preventing your `GUI.Box` to draw.

What you have to do is simply draw your `GUI.Box` outside the for-loop. You can do it in a little bit better way, like,

```
using UnityEngine;
using System.Collections;

public class guimanager: MonoBehaviour
{
    public bool _isDone = false;

    void OnGUI ()
    {
        for (int j = 0; j <= 5; j++) {
            GUI.Box (new Rect (j * 20, j, Screen.width, Screen.height), "This is a test");
            if (_isDone)
                continue;
            print (j);
        }
    _isDone = true;

    }
}

```
> 1 votes

---
Tags: c#, unity, gui
---


title: Game State being skipped

text:
# Question
Title: Game State being skipped
One of my game states is being skipped (pressing space goes straight to the 'GameScreen' game state skipping the 'CharSelect' state). All help is appreciated.

```
        if (currentGameState == GameState.TitleScreen)
        {
            if (keyboard.IsKeyDown(Keys.Space))
            {
                currentGameState = GameState.CharacterSelect;
                testFontTitle = "CharSelect";
                changedstate = true;
            }

            if (keyboard.IsKeyDown(Keys.Escape))
            {
                this.Exit();
            }
        }

        else if (currentGameState == GameState.CharacterSelect)
        {
            if (keyboard.IsKeyDown(Keys.Space))
            {
                currentGameState = GameState.GameScreen;
                testFontTitle = "GameScreen";
                changedstate = true;
            }

            if (keyboard.IsKeyDown(Keys.Escape))
            {
                currentGameState = GameState.TitleScreen;
                testFontTitle = "Title";
                changedstate = true;
            }
        }

        // TODO: Add your update logic here
        base.Update(gameTime);
    }

```

# Answer
> 4 votes
It is probably due to your gameloop is faster then your pressing speed. You should stop detecting space key when you pressed it once. For checking purpose you can use a flag for now. Like,

```
bool _isKeyPressed = false;
if (currentGameState == GameState.TitleScreen && !_isKeyPressed)
    {
        if (keyboard.IsKeyDown(Keys.Space))
        {
            currentGameState = GameState.CharacterSelect;
            testFontTitle = "CharSelect";
            changedstate = true;
            _isKeyPressed = true;
        }

        if (keyboard.IsKeyDown(Keys.Escape))
        {
            this.Exit();
        }
    }

    else if (currentGameState == GameState.CharacterSelect && !_isKeyPressed)
    {
        if (keyboard.IsKeyDown(Keys.Space))
        {
            currentGameState = GameState.GameScreen;
            testFontTitle = "GameScreen";
            changedstate = true;
            _isKeyPressed = true;
        }

        if (keyboard.IsKeyDown(Keys.Escape))
        {
            currentGameState = GameState.TitleScreen;
            testFontTitle = "Title";
            changedstate = true;
        }
    }

    if (keyboard.IsKeyUp(Keys.Space))
        _isKeyPressed = false;

    // TODO: Add your update logic here
    base.Update(gameTime);
}

```

If you have to check more than just the spacebar to check, you may replace the flag with a 'old' and 'new' keyboard state mechanism like so:

```
    Keyboardstate _oldKBstate;

    protected override void Initialize()
    {
        _oldKBstate = Keyboard.GetState(); // Make sure it is initialized!

        // ...
    }

    protected override void Update(GameTime gameTime)
    {
         Keyboardstate newKBstate = Keyboard.GetState();

         // ....

         if(_oldKBstate.IsKeyDown(Keys.A) && newKBstate.IsKeyUp(Keys.A))
         {
               // On A key press.
         }

         if(_oldKBstate.IsKeyUp(Keys.A) && newKBstate.IsKeyDown(Keys.A))
         {
               // On A key release.
         }

         _oldKBstate = newKBstate; // remember the new state.
    }

```

---
Tags: c#, xna-4.0, game-state
---


# Question
Title: Floating point determinism with respect to procedural generation, clustering and GPU offloading
I've been designing a distributed procedural generation system for a while now in my spare time and one of the problem's I've been thinking about recently, with respect to the broader architecture, is that of floating point determinism inconsistency when you can't ensure that you have a homogeneous cluster of machines running a persistent world.

Part of my design requires that any given machine can regenerate procedural content as needed, allowing for unimportant but resource-hungry content to be destroyed and recreated as needed on whatever machine is available to do the work.

I have been running on the basic idea that I will use high-precision 32/64 bit integers for most things, and that generally works fine, but the standard coherent noise algorithms all use floating point values in their calculations.

* Do I need to implement custom non-floating-point versions of all those algorithms (i.e. using longs) or is there a better approach?
* Should I be using fixed-point types for this kind of thing, and if so, how does that impact my desire to have the option to offload some of the PCG work to the GPU, when possible? Also, are fixed point types fast enough for heavy use within a game engine?
* Can I ignore floating point precision issues if I can get away with a maximum level of precision? i.e. If I'm happy to use no more than, say, six decimal places of a result, does that keep me safe across different machines and architectures?

Note: my engine is purely the simulation side of things. It doesn't matter to me if there are slight rendering inconsistencies when a user is playing the game; all that matters is that the procedurally-generated source data is consistently regenerated no matter which machine in a cluster is doing the work.

# Answer
> Can I ignore floating point precision issues if I can get away with a maximum level of precision? i.e. If I'm happy to use no more than, say, six decimal places of a result, does that keep me safe across different machines and architectures?

This depends entirely on your needs. If you **must** ensure that repeat execution on different hardware with identical inputs gives identical outputs, the answer is probably no. There's enough wiggle room in floating-point arithmetic that without extensive testing, this approach amounts to guess & hope. The oft cited required reading is What Every Computer Scientist Should Know About Floating-Point Arithmetic; it's a good piece & what I often turned to back when I was doing scientific computing, but predates IEEE 754-2008 & thus may no longer give the whole story.

> Should I be using fixed-point types for this kind of thing, and if so, how does that impact my desire to have the option to offload some of the PCG work to the GPU, when possible?

Fixed point only solves the inconsistency problem if you can ensure things don't cross over into floating point either in your own code or behind your back in library calls.

> Also, are fixed point types fast enough for heavy use within a game engine?

Somewhat covered in this question & more recently in this article. The short answer is, it depends. The operations you're performing, the frequency you perform them, the hardware being used & a quantitative performance expectation are all factors in determining if it's good enough. If you must ensure output consistency, you might have no other viable option.

> Do I need to implement custom non-floating-point versions of all those algorithms (i.e. using longs) or is there a better approach?

Most languages have libraries for fixed point math. It might be worth searching for distributed scientific computing resources.

As something of an alternative, you might consider building some sort of checksum operation for the outputs that need ensured consistency. This doesn't solve the original problem, but does allow you a way to determine if the problem is manifesting itself in you system. (I.E. quickly determine mismatched outputs). It's entirely possible that it will happen so rarely that it's not worth the trouble to prevent the problem, but easier to deal with by reconciling differing results.
> 3 votes

---
Tags: procedural-generation, floating-point
---


# Question
Title: Android: Synchronizing timers across multiple devices
Im writing a turn-based multiplayer game that implements a chess timer. When the current players turn starts, all devices start timing for the current player, however, as his turn proceeds, the timers fall out of sync, and at the end of his turn(say for example he took 1 minute to make a move) his time on the other players devices are sometimes up to 10 seconds ahead or behind. I understand theoretically its impossible to time-sync devices down to the millisecond, but if i can get it atleast within a second, that will work just fine. I tried the following the try overcome this:

-Sync time across devices at the beginning and end of current players turn.

-Sync time whilst it is current players turn.

-Combination of the two.

The problem with these attempts is that they cause a lot of flickering on the clock, and, at the end of the turn, when other players see the current players time increasing by 5-10 secs, they feel cheated, and it just doesnt look good. Newbie here so be gentle with your responses :)

# Answer
First of all, consider if you want to prevent cheating. If you do, you must have a server (that is, a computer which belongs to neither player) which not only enforces the legal moves but also calculates the remaining clock time. Then it is just a matter of accurately displaying that time.

If you aren't going to use a central server, then: My first concern is that you're seeing much more clock error than you should be. Modern computers and smartphones should *not* drift 10 seconds in 60 seconds. This suggests that you are not properly implementing timekeeping.

For example, one such mistake is to do things like request of the system "call me back in 1 second" to tick the game clock and do that repeatedly. This causes trouble because the time spent executing your callback adds to the overall time; you need to measure from some reference point (either when the game starts, or the time at which you *expected* a given callback to be called).

Another thing is to make sure your time synchronization takes network latency into consideration. Doing this right is hard (see NTP for details) but you don't need *high* accuracy, just to not have a consistent large error.

---

But still, there may be some error, and you'd like the clock on screen to not obviously jump. The way to deal with this is to *not reset the local time*; instead, adjust the rate-of-flow-of-time (“seconds per second”, if you will) so that the error is eliminated gradually. If the local displayed clock is behind whatever your devices sync to, then make it run a little bit faster, and so on.
> 0 votes

---
Tags: android, turn-based, synchronization
---


# Question
Title: Cycling through colors with the same brightness
Ok. So I have a game I am working on with a bunch of colored particles. Each of them gets their own color however they are all close to a specific shade.

To explain that better I am using the HSV color space, and I have a global variable that is cycling from 0-360 (H) and each of the specific particles add or subtract a random amount from that.

I use HSV because it is the easiest way for me to cycle through colors because you can just change H.

This looks very nice and all, however the particles are supposed to be pure light that is colored. Right now all they are are circles colored with the shade, but later on I might add glow effects and other shading techniques.

The problem is that not all shades (I dont mess with H or V) are equal as far as the brightness our eyes see, and this causes problems. For example when all of them are shades of blue things look pretty dark.

Obviously in the shader I have to convert these HSV colors to RGB colors and doing some math I quickly saw what was wrong... the colors didn't have equal luminance!

As I understand it luminance is roughly `(0.2126*color.r + 0.7152*color.g + 0.0722*color.b)` which is why everything is off.

Is their a way to get it so I can still get all of the different chroma (colors on the wheels degrees) while maintaining a high luminance? Perhaps I should work with a different type of color then HSV, or perhaps their is a formula that finds a color at degree x on the color wheel with luminance of y?

Thanks much!

# Answer
> 2 votes
HCY could be better for your needs. According to Wikipedia's HSL and HSV page, the problem you're having with HSV -- that the same "V" with different hues doesn't correspond to human perception -- is similar with HSL, but HCY could suit your needs -- the "Y" in HCY is for "luma":

> Luma is roughly similar \[in lightness to the original color image\], but differs somewhat at high chroma. HSL L and HSV V, by contrast, diverge substantially from perceptual lightness.

HCY is described in the Wikipedia page as "luma/chroma/hue". This page, on the other hand, appears to use the "HCY" shorthand and shows how to convert it to and from RGB.

---
Tags: shaders, color
---


# Question
Title: Bullets Are Spawning Weirdly in my Java/LibGDX Plane Shooting Game
**What I'm trying to do**

Have bullet's spawn in the center ( or close enough, the exact number can be played with after ) of my player sprite.

**What's going wrong:**

They're spawning super weirdly. The first one always spawns at the bottom left corner. Than they spawn all over the place though not completely random. If I shoot on only the right side of the screen, bullets don't spawn on the left side.

**How I'm doing it:**

Creating a New Bullet and Managing them , Methods:

Method Placement:

Drawing (In Batch):

**Also:**

I know that I'm not using LibGDX arrays, or objects, or array of objects, or sprites for the bullets. ( I used sprites for the player ) though I was going through confusing complications and this strategy with batch drawing seems inefficient but simplified for my development ability.

I also haven't made a bullet disposal/reset system yet. I'm still working on this part first.

**Anyone know what I'm doing wrong or a solution?**

EDIT: ManageBullets is just so the bullet's go up once they spawn. ( Shooting )

# Answer
> 0 votes
Assuming that your activeBullets member is initialized with 0:

In newBullet you increment the activeBullet variable **before** adding a new bullet to the vector. So your first "initialized" bullet with x and y coordinates will be on index 1. But in manageBullets() your loop goes from 0 to activeBullets-1 ( i \< activeBullets ). That means your bullet at index 0 will never be set with player coordinates.

Thats the reason your first bullet is in bottom left corner ( 0 / 0 ).

Your code should be

```
public static void newBullet(){
   bulletX[activeBullets] = player.getX(); // first bullet = bulletX[0]
   bulletY[activeBullets] = player.getY();
   activeBullets++; // next bullet will be bullet[1]
}

```

Also note that the bullet will spawn on the left side of your player-sprite ( because the sprite has its left side at x ). So you need to add half the player-sprite width to your bullet x and subtract half bullet-sprite width

Pseudo code:

```
bulletX[activeBullets] = player.getX() + ( playerSprite.getWidth() / 2 ) - ( bulletSprite.getWidth() / 2 )

```

Hopefully last edit:

You should handle the player movement **before** adding new bullets. You spawn the bullet first and then move the player, so the bullet will spawn at the point where the player was in the last frame. Thats the reason for your strange behaviour, that the bullet spawns "randomly".

So first move, then shoot!

---
Tags: java, libgdx
---


# Question
Title: Swap between first person and eagle eye view cameras, hiding the FP controller
Not sure what has to be done to correctly swap between a generic fps controller camera, to something like an eagle eye view.

The idea is to have the player use the FPS controller, then when he get in a control seat; I want to switch to a larger view; kinda like a RTS view from the top (I call it "eagle eye", not sure about the technical name).

I did check around and from my research, I have to swap active camera parameter; but when I do so, the FPS remain active, while I would like to hide it, and also disable it completely, since the player will use the mouse at that point.

If I destroy the FPS, that works, but when the player leave the control seat, I have to re-create it, which bring a whole level of pain, to restore its state.

How do you disable temporarily a FPS, so it won't be neither visible nor it will interact with anything?

# Answer
The solution is to call in the script the enable/disable for all the elements connected to the 2 camera objects.

You can have only 1 camera and one audio listener, so to swap cameras, you need to

1) disable the FPS camera, and enable the other camera 2) disable any element tied to the FPS camera (player controller, audio listener and so on) and enable their counterpart on the other camera.

It is pretty straight forward and you won't see any flicker when swapping the cameras; just remember to write code that will always enable one camera at any time, or Unity will complain.
> 1 votes

---
Tags: unity
---


# Question
Title: Referencing multiple canvas images through script in C#
What is the best way to reference multiple Canvas Images within C# script attached to my player in Unity?

Currently I have something similar too:

```
public Image image;

//Finds the Image Object being referenced.
image = GameObject.Find ("Canvas/Image").GetComponent<Image> ();

```

# Answer
Well, as far as I understand your question, you can assign whole array on `Image` type.

```
public Image[] images;

//Finds the Image Object being referenced.
images = FindObjectOfType<Canvas> ().transform.GetComponentsInChildren<Image> ();

```
> 1 votes

---
Tags: unity, c#
---


# Question
Title: How to decide whether to use a physics engine for a platformer
I'm planning on creating a 2D platformer and doing some research to make sure that when I get started, I avoid making some poor decisions. Something I've seen come up multiple times is that I should consider writing my own physics for a 2D game instead of using the physics provided by an engine. For example, in this question, multiple answerers tell the OP to write their own character controller logic instead of using the physics built into Unity.

Why is this advice common? What benefit would I gain by writing my own physics code? And how do I decide whether writing my own physics is appropriate for my game?

# Answer
Using an off-the-shelf physics engine for unrealistic characters often leads to situations where you have to fight the system just to do things that would otherwise be simple. Here are two quick examples:

1. Your character is probably best represented as a rectangle, however, rectangles do not slide along the ground smoothly, and rectangles do not remain axis-aligned on an incline, so characters in a rigid body physics engine are frequently represented as a rectangle sitting on top of a circular wheel that acts as the "feet" of the character. The circle is less effected by friction, but it's also not prone to "catching" on edges like rectangles are, and it can maintain even contact on an incline. In ad-hoc physics, you just make the character a rectangle and forget about it, because you aren't bound by the rules of physical reality.
2. Thinking in terms of force: objects in motion tend to remain in motion. If you apply forces to set something in motion, you'll have to apply forces to curtail that motion. I.e. if you push a character forward to start them moving, you'll also have to apply a braking force to stop them. For the precision of a 2D platformer, working in terms of velocities is much more direct and flexible.

That said, most physics engines will allow you to opt-out of realistic simulation, you just lose the bulk of the purpose of the physics engine by doing that, apart from collision detection.

Ad-hoc 2D physics for a platformer is fairly basic, and is probably likely to provide a "tighter" end result. However, if any objects in your game do require realistic physical simulation, e.g. you want to throw a crate at the player and you want it to bounce and roll along the ground, I wouldn't recommend even trying to do that yourself. Just manage your player physics with your own solution, and other world objects with a "real" physics engine.
> 1 votes

# Answer
If you want to have *unrealistic* physics ( like in question you mentioned ) or you need to use relativity theory, then you should write your own physics engine, because most of public engines aim to deliver *realistic* Newtonian physics experience. And if you want to have *normal, realistic* physics, then using physics engine will be much easier than writing your own code.
> 2 votes

# Answer
You're likely going to want to write your own collision and physics for any type of 2D platformer, even if resembles real life. Otherwise you're going to need to apply phantom forces, or jack up friction in weird spots which usually ends up with hacky code.

That said, I suggest using a physics engine for any cosmetic stuff, like debris chunks in explosions, or if a table gets flipped in the background, etc.
> 0 votes

---
Tags: platformer
---


# Question
Title: Why is SCNNode.rotation property a four dimensional vector?
I don't understand why SCNNode's rotation property is a SCNVector4 instead of a SCNVector3. The documentation states that:

> The four-component rotation vector specifies the direction of the rotation axis in the first three components **and the angle of rotation (in radians) in the fourth**. The default rotation is the zero vector, specifying no rotation. Rotation is applied relative to the node’s pivot property.

What's the fourth axis? I tried adding a light (SCNLight) and if I don't specify the value of the 4th float in the vector the light has no effect (the scene is dark). Why? shouldn't a 3-dimensional vector (x,y,z) be enough?

# Answer
As the documentation specifies, the first 3 values will specify the 3d position of the axis for rotating the light, while the 4th parameter will specify the rotation around that axis.

For instance, specifying (pseudo-code) `(0, 0, 1, degToRad(45))` will have the effect of a light that will be rotated 45 degrees around the vertical axis (assuming that z is up), coming from the pivot location.

Now the fact that if you don't specify a value for the w (the 4th parameter), it does not light the scene, it might be related to the fact that your light is a directional light, or a spot, and the default 0 value lights in the opposite direction of where the scene is.
> 2 votes

---
Tags: ios, swift, scenekit
---