# Question
Title: Java: Exported JAR file doesn't load images
I am using Netbeans to create my game. The images do seem to load when I run it in Netbeans. However, the built jar file only leaves me with a blank screen.

This is how I call the images in my game.

```
public Image playerSprite = playerSprite = Toolkit.getDefaultToolkit().getImage("sprites\\spritesL.png");

```

I put all image resources in a folder called *sprites*, and I declared it as a Source in the Project Properties. In addition, the image files does appear in the root directory of the JAR file, but cannot seem to access it.

# Answer
Java can be quite a pain when trying to load files that are inside the .jar. So first, try to put your *sprites* folder **outside** of your jar, on the same level. See if that works.

To load files that are inside the jar, you must use this following piece of code to retreive it's URL:

```
getClass().getResource("myimage.png")

```

So your line of code would be :

```
public Image playerSprite = playerSprite =
   Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("sprites\\spritesL.png"));

```

NOTE: You might need to call .toString() on the return value of .getResource() since it returns a URL object and .getImage() takes a String as parameter.

See if that works too. If there's any problems, feel free to ask.
> 0 votes

---
Tags: java, sprites, image
---


title: Collision problem JBox2D

text:
# Question
Title: Collision problem JBox2D
I work with Processing and the JBox2D library and wanna code a new Ping Pong game. But if I move the player to the top border (or lower border), he collide on a wrong position.

The picture shows player 1 colliding with the top border.

If I move the player again upwards then he moves through the border.

**My Player Class:**

```
class Player {
  Body body;
  float pWidth;
  float pHeight;
  Vec2 pos;
  float speed;

  Player(float x, float y, float w, float h) {
    pWidth = w;
    pHeight = h;
    speed = 5;
    pos = new Vec2(0, 0);

    // Add the player to the box2d world
    makeBody(new Vec2(x, y), w, h);
  }

  void playerStep(){
  pos = box2d.getBodyPixelCoord(body);
  }

  void moveUp() {
    body.setTransform(box2d.coordPixelsToWorld(pos.x, pos.y-speed),0);
  }

  void moveDown() {
    body.setTransform(box2d.coordPixelsToWorld(pos.x, pos.y+speed),0);
  }

  void makeBody(Vec2 center, float w_, float h_) {

    // Define the body and make it from the shape.
    BodyDef bd = new BodyDef();
    bd.type = BodyType.DYNAMIC;
    bd.position.set(box2d.coordPixelsToWorld(center));

    PolygonShape sd = new PolygonShape();
    sd.setAsBox(box2d.scalarPixelsToWorld(w_), box2d.scalarPixelsToWorld(h_));

    // Define a fixture.
    FixtureDef fd = new FixtureDef();
    fd.shape = sd;

    // Parameters that affect physics.
    fd.density = 5;
    fd.friction = 2;
    fd.restitution = 1;

    body = box2d.createBody(bd);
    body.createFixture(fd);
  }
}

```

**Boundary Class:**

```
class Boundary {

  // A boundary is a simple rectangle with x,y,width,and height.
  float x;
  float y;
  float w;
  float h;

  // But we also have to make a body for box2d to know about it.
  Body b;

  Boundary(float x_, float y_, float w_, float h_) {
    x = x_;
    y = y_;
    w = w_;
    h = h_;

    // Define the polygon.
    PolygonShape sd = new PolygonShape();

    // Figure out the box2d coordinates.
    float box2dW = box2d.scalarPixelsToWorld(w/2);
    float box2dH = box2d.scalarPixelsToWorld(h/2);

    // We're just a box.
    sd.setAsBox(box2dW, box2dH);

    // Create the body.
    BodyDef bd = new BodyDef();
    bd.type = BodyType.STATIC;
    bd.position.set(box2d.coordPixelsToWorld(x, y));
    b = box2d.createBody(bd);
    b.createFixture(sd, 1);
  }

  void display() {
    fill(255);
    rectMode(CENTER);
    rect(x, y, w, h);
  }
}

```

# Answer
You are setting the position which doesn't allow box2D to act on the bodies the way you are intending. Set the velocity instead.
> 0 votes

---
Tags: collision-detection, jbox2d, processing
---


title: Roguelike 2D Collision Detection

text:
# Question
Title: Roguelike 2D Collision Detection
I'm just a normal guy trying to do some basic collision detection but I suck at it. I either get stuck in a wall or I go in reverse in the wrong direction trying to update the player position to a non collision part. So here is how I check for collision and this function will return true or false. True if collision and false if not.

```
roguelike.player.collision = function() {
  var player = roguelike.player;
  for(var i = 0; i < roguelike.map.rooms.length; i++) {
    var room = roguelike.map.rooms[i];
    if(player.x > room.x && player.x < room.x + room.width && player.y > room.y && player.y < room.y + room.height){
      return false;
    }
  }
  return true;
};

```

This function works just fine just like expected. But it's when I try to stop the player when he hits a wall is where I get bugs. When the player goes down and hits a wall he gets stuck there. Here is the function that updates the player position.

```
roguelike.update = function() {
  var player = roguelike.player;

  //Left
  if(player.moving.left && !player.collision()) {
    player.x -= roguelike.game.speedPerSecond(player.speed);
  } else if(player.collision()){
    player.resetPosition();
  }
  //Up
  if(player.moving.up && !player.collision()) {
    player.y -= roguelike.game.speedPerSecond(player.speed);
  } else if(player.collision()){
    player.resetPosition();
  }
  //Right
  if(player.moving.right && !player.collision()) {
    player.x += roguelike.game.speedPerSecond(player.speed);
  } else if(player.collision()){
    player.resetPosition();
  }
  //down
  if(player.moving.down && !player.collision()) {

    player.y += roguelike.game.speedPerSecond(player.speed);
  } else if(player.collision()){
    player.resetPosition();
  }
  player.savePosition();

};

```

So what I do is check what direction the player is moving and if there is no collision detected then the player is free to move. Otherwise if there is a collision I put the player position as the last position he was when there was no collision so he will be free to move. This works going left, up, and right, but not going down. Going down the player gets stuck in the collision and the resetPosition function doesn't put the player back in the safe zone.

So I know there must be a better way. And I would appreciate your advice on what you think that way should be.

# Answer
> 6 votes
Instead of testing the collisions ON the player, you should testing them AHEAD, to check whether there's a wall where the player WILL be walking. To do that, you'll only need to change 2 things:

1- Your player.collision function should accept two arguments: an x and y offset. You should add them to your collision checking algoythm too.

2- When calling player.collision, you should pass the offset equal to the movement the player would make.

In your code, this resumes as this:

```
roguelike.player.collision = function(x, y) { // The function now accepts 2 arguments
    var player = roguelike.player;
    for(var i = 0; i < roguelike.map.rooms.length; i++) {
        var room = roguelike.map.rooms[i];
        if(player.x + x > room.x && player.x + x < room.x + room.width
                && player.y + y > room.y && player.y + y < room.y + room.height)
        { // The offset is added to the player position when testing
            return false;
        }
    }
    return true;
};

```

And calling a movement would look like this:

```
if(player.moving.left
        && !player.collision(-roguelike.game.speedPerSecond(player.speed), 0) {
    player.x -= roguelike.game.speedPerSecond(player.speed);
} else if(player.collision()){
    player.resetPosition();
}

```

---
Tags: collision-detection, javascript, html5, html-canvas
---


title: Unable to achieve two finger panning

text:
# Question
Title: Unable to achieve two finger panning
I'm looking to achieve a two finger smooth pan system in my project. However, the code below does not work, any interaction with the screen doesn't change to position of the camera.

I am unsure where did I go wrong as I'm quite new to Unity.

Any help will be greatly appreciated.

```
void Update () {

    //Detect If there are a) two fingers, b) touching the screen.

    if (Input.touchCount == 2 && Input.GetTouch(0).phase == TouchPhase.Began)
    {
        if (Input.GetTouch(0).phase == TouchPhase.Began && Input.GetTouch(1).phase == TouchPhase.Began)
        {
            if (Input.GetTouch(0).phase == TouchPhase.Stationary && Input.GetTouch(1).phase == TouchPhase.Began)
            {
                if (Input.GetTouch(0).phase == TouchPhase.Moved && Input.GetTouch(1).phase == TouchPhase.Began)
                {

                    Vector2 defaultCamera = transform.position;

                    Touch touchZero = Input.GetTouch(0); //Get locality of first touch.
                    Touch touchOne = Input.GetTouch(1); // Get locality of second touch.

                    Vector2 originalMid = Vector2.Lerp(touchZero.position, touchOne.position, 0.5f);

                    // Find the position in the previous frame of each touch.
                    Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
                    Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;

                    Vector2 touchMid = Vector2.Lerp(touchZeroPrevPos, touchOnePrevPos, 0.5f); //Get locality of midpoint between touches.

                    // Find the magnitude of the vector (the distance) between the touches in each frame.
                    Vector2 finalTouch = touchMid - originalMid;

                    transform.position = defaultCamera + finalTouch * Time.deltaTime; //transform camera using the new vector.

                }
            }
        }
    }

```

# Answer
> 1 votes
From the Unity documentation:

```
Moved   A finger moved on the screen.
Stationary  A finger is touching the screen but hasn't moved.

```

You are checking to see that the fingers are both station and have moved. It is either one of the other. Your code inside the if statements will never run.

I see what you are trying to do, but it does not wait after one if statement for the next to be true. After your 2nd/3rd if statement is false, it exits all of the if statements. When it comes back around, it will start at the first if statement. It will not pick up where you left off.

You need to do something along these lines:

```
if (Input.touchCount == 2 && Input.GetTouch(0).phase == TouchPhase.Moved) {
    //do stuff
}

```

---
Tags: c#, unity, vector, scripting, touch
---


# Question
Title: How do I manually make a .pack file like TexturePacker (without using TexturePacker)?
I am using libGDX and apparently the only way I see for creating a UI is with texture packs.

I would say that since a texture pack is nothing more than JSON or XML file and a large png I could manually code a texture pack. How?

# Answer
> 2 votes
I wouldn't recommend you creating texture atlas manually. With only two textures it looks like this:

```
atlas.png
size: 1024,256
format: RGBA8888
filter: Linear,Linear
repeat: none
player
  rotate: false
  xy: 404, 4
  size: 400, 174
  orig: 400, 174
  offset: 0, 0
  index: -1
tank
  rotate: false
  xy: 2, 2
  size: 400, 176
  orig: 400, 176
  offset: 0, 0
  index: -1

```

What is your problem with automatic atlas creating? You can either use TexturePacker GUI or run TexturePacker from code which is cool because you don't need manually edit anything after adding new texture.

---
Tags: libgdx, textures, texture-atlas
---


# Question
Title: how to make a sprite jump or fly and fall slowly
I'm a beginner in java and im suffering to make a 2d game.
I already wrote a simple code that makes the character or the sprite jump by increment his Yposition when key is pressed and do the reverse when released ,but it doesn't satisfy me because i don't want the sprite to fall the same speed he fly with it, i want to make fall slowly ,i mean speed (Y increment) of fllying is separated from the falling one.

this may explain what im saying :
1-fllying https://jsfiddle.net/54xfevoc/embedded/result/
2- falling https://jsfiddle.net/poL9cowz/embedded/result/

thank you.

# Answer
> 0 votes
Well, the fix I would suggest would be adding this to your update method:

```
if (velocityY <= 0)
{
    gravity = 0.3;
}
else
{
    gravity = 0.1;
}

```

Pretty straight-forward in my opinion. I looked at your falling program and it seemed to lack acceleration. Was that on purpose? If you really want to do that, you can change your update method to:

```
function Update()
{
    if(gravity == 0.0)
    {
        positionY += 0.3
    }
    else
    {
        velocityY += gravity;
        positionY += velocityY;
    }
    if(positionY > 175.0)
    {
        positionY = 175.0;
        velocityY= 0.0;
        onGround = true;
    }
    if (velocityY <= 0)
    {
        gravity = 0.3;
    }
    else
    {
        gravity = 0.0;
    }

    if(positionX < 10 || positionX > 190)
        velocityX *= -1;
}

```

but in my opinion that's not very realistic at all, and it's really easy to get stuck in the clouds (way too far above the screen) in my opinion.

I suggest you take a look at some physics documentation for acceleration, it should help you understand more of the velocity-type problems you're having in the future.

Hope this helps!

# Answer
> 1 votes
When I make a physics part of a game, Personally I don't like to fix or modify basic physics constants. ex) gravity.

So, I suggest you to add delta time concept in your physics.
When the object jumps up, time is passing fast. When the object goes down, the time become slow.

I modified your js fiddle sample source. this is not exactly what I want to say. but it could be a example.

Run Sample
JS Source

---
Tags: movement
---


# Question
Title: Unity How do you rotate an object with a rigidbody so it's facing the it is traveling
I would like to know how i can rotate an object with an rigidbody so it's facing the way it's traveling.

# Answer
> 1 votes
First you need to get the direction you are traveling in:

```
Vector2 direction = rigidBody2D.velocity.normalize();

```

Then you want to get the angle of this direction:

```
float ang = Vector2.Angle(rigidBody2D.transform.position, direction);
Vector3 cross = Vector3.Cross(rigidBody2D.transform.position, direction);

if (cross.z > 0)
    ang = 360 - ang;

```

Then you can use MoveRotation to adjust your rigidBody's new direction:

```
Quaternion q = Quaternion.Euler(ang);
rigidBody2D.MoveRotation(q);

```

I didn't test any of this.

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


# Question
Title: Single Switch Script vs Multiple Scripts
Would it be better to have one script that switches or have multiple scripts with each with their own function?

In example, Lets say I am making a powerup script.

Option 1: Create a single powerup script that switches the effects

```
switch (/*Enum of effects*/)
{
    case Effect.IncreaseHealth:
        health += amount;
}

```

Option 2: Create multiple scripts that each does its individual function

```
Class IncreaseHealthPowerup
{
    protected void Start()
    {
        health += amount
    }
}

```

This is different from the question of Multiple Script versus Single Script as it is already in component form. The question is whether to further segregate down to the types of component.

I would also like to ask the Pros and Cons of each option with regards to potential development issues, or lack of, as well as the overhead caused in either cases.

# Answer
> 2 votes
The Unity3D tutorials actually have a chapter about this:

https://unity3d.com/learn/tutorials/modules/intermediate/scripting/coding-practices

The author would argue that your switch already gives you a structure to modularize from. You have different effects like *Increase Health*, *Take Damage* or *Give Item*. Those can be astracted in interfaces like

* `IDamageable` – Interface for classes which can accept damage
* `IInventory` – Interface for classes which can store and retrieve items

You then compose your game objects of different implementations of those interfaces like a wizard has a different implementation of `IDamageable` than a dog.

# Answer
> 1 votes
**Single switch script**

* Everything is in one place, better readability.
* It will be a lot easier to add cases (powerups) when needed.
* Centralized ressources = good.

**Multiple scripts**

* Can help when the cases have too much lines.
* Object-oriented, can be easier to call cases.

Looking at your example, the best way to go would be to have one script with a switch case. The example case you gave is simple and I don't really see the need to put it in another file. This would only cause the code to be difficult to maintain, mainly because each case would be in it's own file of 7 lines. For simple cases, keep them in a switch case.

You can, however, put some of your cases in seperate files if they take too much space and harm readability. The switch case would then call the said script.

Keep this in mind: concise code is ofter better, especially when programming video games. Yes, there are good things about OOP but making a class for one line of code is just absurd. KISS (Keep it stupid simple).

# Answer
> 0 votes
I use multiple scripts.

A power-up is a prefab which is then composed of multiple components which will then apply the changes separately:

* Resize Changes
* Speed Changes (can have configurable values)
* Health Changes (can have configurable values)
* Visual Effects (reacts to the start and end of the other scripts)

This way each script can be configured to apply its effect for a longer or shorter period of time.

Each script then emits Messages when its effects starts or when it reaches the end of its effect.

This way I can add visual effects which will trigger at the end of some of the effects.

---
Tags: c#, unity, component-based, scripting
---


# Question
Title: 3D zooming technique to maintain the relative position of an object on screen
Is it possible to zoom to a certain point on screen by modifying the field of view and rotating the view of the camera as to keep that point/object in the same place on screen while zooming ? Changing the camera position is not allowed.

I projected the 3D pos of the object on screen and remembered it.

Then on each frame I calculate the direction to it in camera space and then I construct a rotation matrix to align this direction to Z axis (in cam space).

After this, I calculate the direction from the camera to the object in world space and transform this vector with the matrix I obtained earlier and then use this final vector as the camera's new direction.

And it's actually "kinda working", the problem is that it is more/less off than the camera's rotation before starting to zoom depending on the area you are trying to zoom in (larger error on edges/corners).

It looks acceptable, but I'm not settling for only this. Any suggestions/resources for doing this technique perfectly? If some of you want to explain the math in detail, be my guest, I can understand these things well.

# Answer
> 5 votes
Expanding on my comment, the basic approach for a single zoom-step would be:

1. Project object on screen and remember coordinates
2. Reduce fov
3. Unproject remembered screen coords (raycast into view space)
4. Rotate camera to align ray with the camera-to-object vector (in view space)

## Step 4

When unprojecting the point using the inverse projection matrix, the ray will already be in view space (camera space) by default. To get the camera-to-object vector (let's call it `toObj`) in view space, it's easiest to transform the object position using the `VIEW * MODEL` transform. The camera is at `[0, 0, 0]` in view space, so that transformed vector is `toObj`.

*The following assumes the Y-axis is up/down in view space. This may or may not be the case in your engine; verify this.*

Get rotation that aligns ray with `toObj`:

```
ray = normalize(ray)
toObj = normalize(toObj)

angle = acos(dotProduct(ray, toObj)) // NOTE: may need to negate this
if (angle < THRESHOLD) exit // THRESHOLD is a small value, like 0.001
axis = normalize(crossProduct(ray, toObj))
rotationRay = { angle, axis }

```

This would be the rotation to rotate the camera with, but in many cases, we'd get a funky orientation because the camera will be rolling as well (rotating up vector around forward axis).

To fix this, we first determine the rotated up-vector to get the right-vector when considering `toObj` as the forward vector. Then we determine the desired right-vector and rotate around the `toObj` axis to align them (Using the right-vectors is just to save an extra calculation that would occur to get the desired up-vector):

```
upRotated = rotate(UP_VECTOR, rotationRay) // UP_VECTOR is (0, 1, 0)
right = normalize(crossProduct(upRotated, toObj))
rightDesired = crossProduct(UP_VECTOR, toObj)

angle = acos(dotProduct(right, rightDesired)) // NOTE: may need to negate this
rotationRoll = { angle, ray }

```

The last statement rotates around the `ray` axis, because we will do this transform after rotating the camera with `rotationRay`, so from the camera's point-of-view, `ray` will remain unchanged.

Now we have to combine these rotations and transform the combined rotation back to world space (since your camera transform is probably defined in world space).

```
// combine rotations with quaternion product
q = quaternion(rotationRoll) * quaternion(rotationRay)
rotationView = q.toAngleAxis()

// transform rotation to world space
axis = inverse(VIEW).transformNormal(rotationView.axis)
rotationWorld = { rotationView.angle, axis }

```

I've used a fictional `transformNormal` method to emphasize that the transform disregards translation and should strictly also be done with the transpose of the inverse of the matrix in case of scaling, but that probably doesn't occur.

Now you have the camera's rotation to perform in world space. If the camera already has an orientation, you can combine both rotations using the quaternion product like demonstrated earlier.

Keep in mind this was all written without testing or sketching anything, so maybe I messed something up along the way. Regardless, I hope it points you in the right direction. Good luck :)

# Answer
> 0 votes
In AS3, the correct and quick solution would be to alter the ***projection matrix***. Beware, culling will stop working correctly and should be ***disabled***. `rx,ry` is zoom-rectangle's center, `rw,rh` width and height.

```
    const viewPort:Rectangle = (this.scene).viewPort;
    const viewWidth:Number = viewPort.width;
    const viewHeight:Number = viewPort.height;
    const rh:Number = rw * (viewHeight/viewWidth); // if we don't use the same aspect ratio, the image will be stretched
    const rx:Number = viewPort.x + viewWidth * 0.5 - stageX;
    const ry:Number = viewPort.y + viewHeight * 0.5 - stageY;
    const scale:Number = viewWidth / rw;

    const alterProjectionRaw:Vector.<Number> = origProjection.rawData;
    alterProjectionRaw[0] *= scale;
    alterProjectionRaw[5] *= scale; // NOTE : if same aspect ratio, viewWidth/rw === viewHeight/rh
    alterProjectionRaw[8] = 2*rx/rw;
    alterProjectionRaw[9] = -2*ry/rh;

```

---
Tags: 3d, camera
---


# Question
Title: Cocos2d-x project every time must compile the project plus other libraries
I'm using `cocos2d-x v3.6` for win32 desktop and `Visual Studio 2013` with c++.

When I change the code and then compile the project again, I must re-compile my project AND other libraries *every time* (e.g. libraries: `libbox2d` and `libcocos2d`), and this phase takes a *long* time.

I don't know why I get this bad behavior of having to re-compile the dependency libraries every time with the project.

**Is there is any way to change this bad behavior, to compile the project only without dependency libraries every time?**

# Answer
The fastest code to compile is the code that has not been written. If you don't intend to modify the libraries (which is the typical way to use 3rd party open source libraries), you should not include them in your solution.

You should compile them in a separate solution and make them available for your main project, whether they'll be statically linked or dynamically linked.

Another thing you could check, even if it's stating the obvious: when compiling, don't use "Rebuild Solution"; use "Build project".
> 1 votes

---
Tags: c++, cocos2d-x, visual-studio
---


# Question
Title: Making a 2D sprite move in a curved jump in Unity
Given a 2D Sprite (I'm using NGUI if it matters), what is the simplest way to move it to another position using a curve that resembles a jump?

When I used `cocos2d`, there was an action called `JumpTo` which basically tweened the sprite to a particular position. It had parameters for curve height and speed and such.

How can I achieve this in Unity? I have the `DOTween` plugin if it helps (although I don't think it does this).

I don't have a predefined path for the sprite to follow either. I only want it to behave like `cocos2d`.

# Answer
> 7 votes
1. Go to the DOTween documentation
2. Scroll down to the Move section.
3. Click on DOJump to expand that explanation.

Is that what you're looking for?

---
Tags: unity, tweening, ngui
---


title: Spawn scene object not found for 1

text:
# Question
Title: Spawn scene object not found for 1
I'm getting this error with the new Unity Networking (5.1):

```
Spawn scene object not found for 1
UnityEngine.Networking.NetworkIdentity:UNetStaticUpdate()

```

This happens in the client, when it connects to the server: the server is file, while the client fails to load the scene. I *guess* this error means "I failed to load the (online) scene" (which in fact it is the scene number 1), but I've no clue why it does fail.

The server has a custom player spawning function:

```
public class NetworkDirector : NetworkManager
{
    public override void OnServerConnect (NetworkConnection conn)
    {
        base.OnServerConnect(conn);

        Transform spawnPoint = FindObjectOfType<SpawnPoints>().getNextSpawnLocation();
        GameObject spawned = FindObjectOfType<InstancedElements>().SpawnObjectFree(playerPrefab,spawnPoint);

        FindObjectOfType<CameraFollow>().SetTarget(spawned);
        NetworkServer.AddPlayerForConnection(conn,spawned,0);
    }
}

```

# Answer
> 0 votes
`OnServerConnect` gets called **as soon as** the client connects, before he has been able to do pretty much anything else, including loading the online scene.

Player spawning should be done in the `OnServerReady` function, instead.

```
public override void OnServerReady (NetworkConnection conn)
{
    base.OnServerReady(conn);
    [...]

```

---
Tags: unity, networking, unity-networking
---


# Question
Title: Unity gravity not effecting everyone like it should
so My problem is a bit weird. I have a model that will not fall at the correct speed. She falls incredibly slowly. This is the only script attached to her, and I did the "Scale to large" test by placing a box next to her and letting them drop at the same time. The box fell instantly to the ground and she just kind floats taking her time.

Gravity is on kinematic is off, I'm out of ideas and could use some help. :D!

Thank you.

This is unity in c#.

```
using UnityEngine;

```

using System.Collections;

public class PlayerController : MonoBehaviour {

```
// public variables
public float speed = 1.5f;
public float JumpH = 1.5f;
public float RotateSpeed = 30f;

//pivate component checks
private Animator animr;
private Rigidbody LillyRB;

//private generic bits.
private bool checker;
private float movever;
private float movehor;
private float turn;

void Start (){
    LillyRB = GetComponent<Rigidbody> ();
    animr = GetComponent<Animator> ();

}

void FixedUpdate () {

    // movevertical and move horizontal check for player input wasd
    // jump checks for jump/spacebar.

    movever = Input.GetAxisRaw ("Vertical");
    movehor = Input.GetAxisRaw ("Horizontal");
    turn = Input.GetAxisRaw ("mouse x");
    Quaternion rot = LillyRB.rotation;

    Quaternion Exturn = Quaternion.Euler (0.0f, RotateSpeed * Time.deltaTime *  turn + rot.eulerAngles.y, 0.0f);

    if (movehor != 0 || movever != 0) {
        checker = true;
    }
    else {
        checker = false;
    }

    animr.SetBool ("IsMoving", checker);
    LillyRB.MoveRotation (Exturn);
    LillyRB.MovePosition (LillyRB.position + (transform.forward * movever));
    LillyRB.MovePosition (LillyRB.position + (transform.right * movehor));

}

```

}

# Answer
> 2 votes
It looks like these two lines are overriding the velocity-based movement from the RigidBody:

```
LillyRB.MovePosition (LillyRB.position + (transform.forward * movever));
LillyRB.MovePosition (LillyRB.position + (transform.right * movehor));

```

Generally when combining player/AI control with Rigidbody physics, you'll want to use forces & accelerations to move your character, rather than wrenching position & velocity control away from the physics system - otherwise you take away its ability to handle things like gravity and collisions consistently.

---
Tags: c#, unity, scripting, rigid-body-dynamics
---


# Question
Title: Damping in Unity Shuriken Particle System
Is there no damping functionality in Unity Shuriken Particle?
"Velocity Over Lifetime" is different from damping.

I try to find it on particle system, but can't.
Or is there any other way to apply particle damping?

I want to control each particle's velocity decrement?

**Update:** Add a poor art work :)

# Answer
> 0 votes
Limit Velocity Over Lifetime-\>Dampen in the Editor.

From Unity Docs: "(0-1) value that controls how much the exceeding velocity should be dampened. For example, a value of 0.5 will dampen exceeding velocity by 50%."

For best results set Speed under Limit Velocity Over Lifetime to a Curve that shows how you want the particles velocity to react over its lifetime then use Dampen to fine tune it to your liking.

---
Tags: unity, particles
---


title: SpriteKit Game State Management

text:
# Question
Title: SpriteKit Game State Management
I've created a SpriteKit Mac OS X app and I am using a simple finite state machine to manage the game states. I've seen some solutions, especially for C++ games, where a GameState class and a GameStateManager class are used to regulate states of the game through the use of a stack of GameState objects. What I don't understand is what these GameStates objects would be in SpriteKit. Would they be separate SKScene nodes? How would I implement this into a SpriteKit game?

# Answer
iOS 9 actually introduces a GameplayKit framework that includes State objects. This link shows you the implementation of their GKState class. It inherits from NSObject, but not from any SpriteKit node class, or any SpriteKit class at all.

The thing to remember is that SpriteKit is all about drawing and physics simulation. SpriteKit tends to confuse the logic and rendering of objects, but nothing outside of physics or rendering is inherent to the framework. Nodes are great for anything in a scene that needs a position, or a physics body, or somehow organizes rendered or physics objects. States, however, are purely logical, do not need positions or velocities or physics, and can therefore be purely separate from SpriteKit, SKNodes, and SKScenes.
> 4 votes

---
Tags: spritekit, game-state
---


# Question
Title: Getting one-point-collision object to conform to uneven terrain while keeping constant distance covered
This is probably best described by image:

I have a character. For floor collision, it uses a single point (the red X). When the character moves, it conforms to the terrain; note how the blue line (its movment per frame) is the same length regardless of the slope.

I have the top three situations working fine. The issue is the bottom one, where the character is crossing over a change in slope. I handle the single-slope case just by rotating the impending movement vector, but obviously that won't work here.

My first instinct was to do something like this:

1. Measure length to next vertex along first slope.
2. Subtract length from impending movement vector.
3. Position impending movement vector at vertex; rotate to match second slope and get resulting position.
4. Put character at result position.

The problem is that it doesn't seem like this will chain very well if the character has to cross over three or more segments at once (maybe it's moving very fast over round-like terrain).

So basically at this point I'm looking to see if there's an easier solution I'm missing.

# Answer
> 4 votes
So what you want is like this?

As Stephan says, you have the right idea, just repeat it until you're all out of movement.

```
 1. Measure length to next vertex along first slope.
while( impending movement vector > length to next vertex )
{
 2. Subtract length from impending movement vector.
 3. Position impending movement vector at vertex...
 1. Measure length to next vertex along first slope.
}
 3.1 ...rotate to match second slope and get resulting position.
 4. Put character at result position.

```

# Answer
> 1 votes
You are describing the proper algorithm. If you loop while you have remaining movement left, it wont matter how many segments you have to cross over. All of the calculations you describe are O(1) calculations so performance isn't an issue.

Keep in mind that all terrain is triangles under the hood, so Trig and/or Dot Products may possibly offer some calculation advantages, but still within O(1) domain.

# Answer
> 0 votes
I guess terrain is 2d from the picture. If it is terrain the {x} axis distance between every vert should be constant. I also condider both players are grounded.

Now lets have such varriables: Player 1 : `p1`where we have `p1.x and p2.x`

Player 2 : `p2` same as player 1 Let's also say player p1 is before p2 in other words he is behind him vert array: `V` with lenght `n`

and {x} spacing between every vertex : s

now what we need to find is a float variable we call: distance

i also consider the terrain start point is at `x=0` Algorithm:

First of all we need to determinate the start and end vertex index `v_start` `v_end`

Dividing p1,p2 with `spacing` we can find on which segment does the players stand. as the player 1 is behind player 2 we find that we need to take the front vert from the segment from player 1 and the back vert from player 2. So as finding this we can start calculating the distance.

Notice now we have `v_start` `v_end`

Let's say we have function `dist` whcih finds distance in 2d space

fist of all you must calculate distance between the player 1 and v\_start and player 2 and `v_end`

and then we need to find distance between all segments inbetween verts v\_start and v\_end

we have:

```
distance = 0
for(int v = v_start; p<v_end;p++)distance+=dist(verts[v],verts[v+1]);
distance += dist(p1,verts[v_start]);
distance += dist(p2,verts[v_end]);

```

---
Tags: collision-detection, algorithm, terrain
---


# Question
Title: Texturing in OpenGL, Should texture coordinates be assigned to vertices in the shader?
I attempting to texture 3D models (a cube for example) using ibo’s, with OpenGL in Java. Currently, my textures are distorted. I believe this is because only a single texture coordinate is being assigned to each vertex, as the meshes are loaded from wave front (.obj) files.

As each vertex should correspond to multiple texture coordinates, should I be assigning texture coordinates to vertices as the data is loaded from file or would it be better to assign texture coordinates to vertices in the shader?

I would appreciate example code.

# Answer
Your picture is of a cube, so I assume that's what you're talking about.

You can only share vertices between *continuous* surfaces. That is, on a sphere, you share all/most of the vertices. On a cube, you *must* you separate vertices for each face.

Aside from texturing, think of the normals you need for lighting. The normal for each side of a cube should point directly out of it. That means that the vertices' that form that side must all have normals pointing in the same direction. That's a problem for the vertices in the corners, as those vertices must have normals that somehow point in three different directions; clearly impossible. The solution is to just make separate vertices for the corners.

On a sphere you can share the normals/vertices because you *want* the normal to smoothly interpolate along the surface in order to get a rounded look.

For more complex models, whether or not you can share vertices between two surfaces comes down to whether the "edge" between them is something you distinctly want (it's a hard, pointy edge) or whether the edge is just a necessity of polygonal rendering (it's an edge that's simulating a smooth, rolling surface).

Short version: a cube needs a minimum of 24 vertices, 4 for each face. More if you tessellate.
> 1 votes

---
Tags: opengl, textures, obj
---


# Question
Title: An archery's arrow should be a node or particle?
I am using Sprite Kit to do game development. I would like like to design an archery with arrow. Should I use the arrow as one of the node? If so, it is a concern to have too many arrow on the screen, so that the performance will be slower? What do you think?

# Answer
> 2 votes
Particles in SpriteKit are meant for visual effect. They cannot be given physics bodies in the default SK implementation. This would make them very inappropriate for a logical object in your game. Definitely use nodes.

Don't worry about performance at this point. It's unlikely to matter, and if it does, you can research ways to improve performance through SpriteKit and other iOS APIs. (Or ask a performance improving question on gamedev.SE with the specifics of your code/implementation)

If you really want to ensure some performance benefit from the start, use circles as the physics body type for your arrows (a small circle at the tip, for example). Reuse SKActions when you can, and definitely reuse textures for the arrows. However, I would reiterate that it's unlikely you'll really have problems, and should deal with performance when it becomes a problem.

---
Tags: spritekit
---


# Question
Title: Getting stuck going left with tile based collision detection
Thanks to Alexandre Desbiens I have awesome collision detection. I can just slide right along walls. However if I try to go left into a wall I get stuck. But the good news is I can just back out and everything is okay. But it would be nice to have a consistent behavior when running into walls. Here is what my tryMove function looks like.

```
tryMove: function() {
      var game = roguelike.game;
      var speed = game.library.speedPerSecond(this.speed);
      //Left
      if(this.moving.left
        && !this.collision(speed, 0)
        && !this.collision(speed, 1)) {
        this.x -= speed;
      }
      //Up
      if(this.moving.up
        && !this.collision(0, -speed)
        && !this.collision(1, -speed)) {
        this.y -= speed;
      }
      //Right
      if(this.moving.right
        && !this.collision(speed + 1, 0)
        && !this.collision(speed + 1, 1)) {
        this.x += speed;
      }
      //down
      if(this.moving.down
        && !this.collision(0, speed + 1)
        && !this.collision(1, speed + 1)) {
        this.y += speed;
      }
    }

```

I added the second collision test to check two different points of the player one on both corners of the players moving direction. I really appreciate it. Thanks.

# Answer
Try putting *-speed* when doing a left or up movement and *speed* when doing a down or right movement:

```
tryMove: function() {
    var game = roguelike.game;
    var speed = game.library.speedPerSecond(this.speed);
    //Left
    if(this.moving.left
        && !this.collision(-speed, 0)) {
        this.x -= speed;
    }
    //Up
    if(this.moving.up
        && !this.collision(0, -speed)) {
        this.y -= speed;
    }
    //Right
    if(this.moving.right
        && !this.collision(speed, 0)) {
        this.x += speed;
    }
    //down
    if(this.moving.down
        && !this.collision(0, speed)) {
        this.y += speed;
    }
}

```

When doing a collision check on the X asis, going left will move your character of *-speed* pixels. You must then check the collision at the position *-speed* in order to catch any present wall.

I also have fixed the down and right collisions, you didn't need to put +1 to *speed*.
> 1 votes

---
Tags: collision-detection, tilemap, roguelikes, tiles
---


# Question
Title: Discoordinated Chromatic Aberration Effect
The game Teleglitch heavily utilizes the CA effect with screen distortion.

I am trying to achieve this effect.

**Issue 1. How to not apply the effect onto the floor? (solved)**

They render the screen then apply the CA effect. However, the floor is not rendered with the post processing effect.

**Issue 2. How to have discoordinated position for each rendered CA effect?**

Currently I have three offsets for each channel: red, green, and blue. However, I cannot assign different offsets for the channels for certain areas only. What would be a way to have discoordinated positions?

# Answer
Welcome to the tutorial to discooridnated chromatic effect. The above is an example of screen distortion. It is necessary to understand the first type of screen distortion in order to understand the final effect listed second.

It is achieved by having screen coordinate texture then applying the altered screen coordinate when rendering the final scene.

Better to see what's happening then read description. Let's take a look at the debug screen.

I use this green texture of color .5 .5 0 as my new coordinate texture. Why .5 .5 0? Because red value is used for x coordinate and green value is used for y coordinate. And because default value for coordinate change of the screen should be 0, 0. And .5 .5 0 gives you coordinate change value of 0, 0.

The equation for translating the color pixels to coordinate is following.

final\_coordinate = original\_coordinate + (colorPixel - (.5 , .5) ) / .5;

This effect only takes three lines of code. That's right. Three lines then you are good to go.

```
fixed4 GetColor(sampler2D main, sampler2D src, float2 uv){
            //main is the main screen texture. src is the green texture, uv is the original screen coordinate for the pixel
            float4 color = tex2D(src,float2(uv.x,1-uv.y));
            float2 coordinate = (color.rg - float2(.5,.5) ) /.5;
            return tex2D(main,uv + float2(coordinate.x,coordinate.y) );
        }

fixed4 frag(vertex  i) : COLOR  {
            return  GetColor (_MainTex,_DistortionCoordinateTextue, i.uv );
        }

```

However the effect we want to achieve is not a simple screen distortion but color channel based screen distortion.

All we need to do is repeat the step above three times for each color of the pixel; red, green, and blue.

In order to distort three times, we are going to need three distortion fields.

```
fixed4 frag(vertex  i) : COLOR  {
            float4 originalColor = tex2D(_MainTex,i.uv);
            float4 r = GetColor (_MainTex,_distortionRed, i.uv );
            float4 g = GetColor (_MainTex,_distortionGreen, i.uv );
            float4 b = GetColor (_MainTex,_distortionBlue, i.uv );

            return float4(r.r,g.g,b.b,originalColor.a);
        }

```
> 5 votes

# Answer
I'm not sure if this method is completely possible with unity/shaders, but I think this is a method that could work.

For each colour channel; define what I would call a "warp field". A "warp field" in this case would be a 2 dimensional array of Vector2s, with each element corresponding to a pixel on screen. (you could have this representation at a lower resolution, and upscale/interpolate to reduce performance impact.

The elements in this array represent a distortion for that colour channel, effectively stretching/warping parts of the image. For example:

Interpolation would be used to fill in the areas where the pixels have been stretched apart or pushed together.

(This next section is off the top of my head, and may not work/ be as easy to implement)

The next problem is generating warp information for a good looking distortion effect. This could be achieved by simulating a 2d grid of spring-connected points and populating the warp field with the vector from a nodes rest position to its current position.

This grid of points can then have forces applied to it to give the distortion wobbly kind of effect (you would use different magnitudes of force/altered directions for the different colour channels).

A 3d version of the spring-grid simulation I am imagining: https://www.youtube.com/watch?v=ib1vmRDs8Vw
> 0 votes

---
Tags: unity, shaders, rendering, gpu, post-processing
---


# Question
Title: Assigning IDs to entities and obects for use in scripts and by other objects
I'm currently planning a small, simple scripting system for my game engine that will allow me to easily define scenes (similar to the "cutscenes" found in 2D RPGs). It consists mainly of simple commands such as "Change scene", "Move to" and so on.

Some of these scripting commands require operands. For example, the "Move to" command should expect an entity ID and a target node ID (where the node is just another placeable object). The aim is that whenever you create an entity, map or other object in the editor, it is assigned an ID that other objects and scripts can use to refer to it easily. These IDs will be stored when the game loads its data and used during runtime to make sure I'm targeting the correct object when an interaction occurs.

The problem I'm having is in how best to assign IDs to these objects of interest. I thought about just automatically assigning an incremented integer ID to new objects, but was unsure of how I should deal with the possibility of stale references. As I work in the editor, I may add and then later remove an item that was assigned an ID when it was created. If I delete an item that previously had an ID, should that ID be released for use by something new, or should I just leave a gap? Also, how should I keep track of assigned IDs between uses of the editor so that I can easily avoid collisions and also check easily for stale references?

For example, if I was to (either accidentally or intentionally) delete door A that is linked to door B, what would be the simplest way to check for any stale references, so that door B can be known to refer to something that no longer exists? Is it literally just a case of iterating through every object and seeing if any IDs it refers to are there or not?

I have the same problem when trying to decide how best to refer to the game's central list of items, spells, etc. These are the things that can be considered a core part of the game, but may be modified or removed over time. How can the game deal with a situation like the deleting of an item that has already been put in numerous places (i.e containers) in the game world?

Thanks in advance for any enlightenment you can offer with the above.

# Answer
What you are looking for is really similar to a type of smart pointer, called a weak pointer. A weak pointer lets you have a pointer to something, but if that something goes away, that pointer will then point at null automatically.

I mention that because you can search the net for different smart pointer implementations to find more info and techniques if you want them.

Your instincts are good about the method you are trying to use to solve your problem, I've seen the same sort of solution used in multiple AAA game engines!

A nice simple solution to this is something I've seen in object pools, and I think will also apply here.

Basically, an object pool is an array of objects (can be anything), where each object has a bool to specify whether or not it's in use. When someone wants a new object, it finds an unused object, marks it as used, and returns that to the caller. When someone frees an object, it marks that object as unused and is thus returned to the pool. Object pools are great for avoiding dynamic memory allocations. That isn't what you are trying to solve but I wanted to mention that in case it helps you in the future.

Anyhow, you can upgrade the idea of an object pool to solve your situation by adding a "use count" to each object.

Whenever an object is freed, you increment it's use count.

How this helps you is that when you allocate an object, you can identify that object uniquely by it's index in the object pool array, but you also have it's use count.

These two values together make up a "weak pointer", so you could have some struct with these two values in them and treat that as your object reference.

When you want to get the object itself, you pass the index and use count of the object count you want to the object pool, and it does the following logic:

1) If the index specified is unused (or out of bounds), return null 2) If the index specified is in use, but it has a different use count than was asked for, that means the person asking for an object is asking for a STALE REFERENCE, so return null 3) Else, return a pointer to the object

There are other ways to implement weak pointers that may or may not be better for your needs, but I think this is one of the ones that is most appropriate to your usage case.

The only thing you have to watch out for here is that you need to make sure that these object pools are the same on all machines involved.

Essentially, you have to make it so objects are only created or destroyed in a deterministic, synchronized way between clients.

Another option could be to have the server be the only one who can create or destroy objects.

Yet another option though could be to reserve "object id ranges" for individual clients. like player 1 is in charge of object id's 0 to 99, player 2 is in charge of object id's 100 to 199 etc.

There are cheating concerns here to watch out for, but I think this is starting to stray outside of the realm of your question so will leave it at this.

Hopefully you get what I mean, I think this ought to be real useful in your situation!
> 3 votes

# Answer
The approach I prefer treats handles as simple unique integers.

In order to access the data via a handle you must pass the handle to its appropriate manager. For instance, if you have an `ObjectId`, and you want to get the position of the object with that id, you call a function akin to `GetPositionOf(ObjectId id) -> Vector3f`.

Because you are always passing the handles to accessor functions for interesting work the staleness of the ID can be checked at each call site. Likewise, a helper function like `IsValid(ObjectId id) -> bool` can be used if you need to check explicitly.

For more complex uses, you can either return a struct directly (which is far cheaper than most people think) or you can return a pointer to an internal structure. The rule in the latter case is that you aren't allowed to hold on to the pointer for longer than a single frame, since the pointer might become invalidated at the end of the frame (because you only actually delete/deallocate game objects at the end of a frame).

Unlike a `weak_ptr` model, such a handle system has several advantages. One of them is that you can freely copy the handles around using `memcpy`, which is a huge advantage for hihgly-efficient threading, graphics, physics, etc. A second advantage is that you can more easily reuse the handle in different systems allowing you to use the same index into otherwise completely independent chunks of code.

An implementation of this approach is covered in this BitSquid article on their "packed\_array" (which I've always seen called a "slot map" before the BitSquid article).
> 5 votes

---
Tags: c++, entities
---


# Question
Title: Tile map creation, problem with position of tiles
I am trying to create a basic tile map script to learn Unity and I am unable to understand why my tiles are spaced far apart and I can't seem to control their spacing.

Moreover, there seems to be a difference between tile map size and Unity sizes, how do I convert tile map size to Unity size?

My understanding of tile maps are limited but here is what I want to do. I want to be able to set tile size, amount of tiles displayed and the spacing between each tiles.

Image: http://puu.sh/in6XW/416f8971bc.png

```
 public static int TILE_WIDTH = 32;
 public static int TILE_HEIGHT = 32;

 public float tileSize = 0.1f;
 private Transform[,] tiles;

 void Start () {
     var w = 18; // width
     var h = 15;  // height
     tilePrefab.gameObject.GetComponent<SpriteRenderer>();
     tiles = new Transform[w,h];

     for (int y = 0; y < h; y++)
     {
         for (int x = 0; x < w; x++)
         {
             Transform tile = Instantiate(tilePrefab, new Vector3(x* tileSize,y * tileSize,0),Quaternion.identity)as Transform;
             tile.parent = transform;
             tiles[x,y] = tile;
         }
     }

```

# Answer
Make sure whatever tile prefab you are using is scaled correctly. I recommend using an object which is exactly one unity unit wide
> 0 votes

# Answer
I am not sure but it looks like your "pixel to units" value is different, try setting it to your tile size, its very easy to handle it that way and if you do so, set the TILE\_WIDTH and TILE\_HEIGHT to 1
> 0 votes

---
Tags: unity, tilemap
---


title: Optimizing Texture Text Rendering?

text:
# Question
Title: Optimizing Texture Text Rendering?
I have an implementation currently that stores each letter as it's own separate texture, usually only a couple pixels in width and height. So this has some problems as i am unable to do a batch render, i can only batch render the same characters. I am stuck with this format, all i can do is try and process it into something better at runtime. I was thinking of creating a single larger texture from all the little ones instead.

What algorithm can i use to sort the small images into a larger one?

How big can this texture get without losing pixel precision with single floating point precision UV mapping (texture width/height normalization into percent 0.0 to 1.0)?

# Answer
For more efficient storage of font texture data, if you want to go beyond putting it all in one texture you should check out distance field textures.

A popular distance field texture technique was invented at valve which stores the distance from each pixel to the shape (character in your case). This is great for monochromatic images, such as fonts and decals and gives you the ability to zoom in pretty darn far. Its almost a vector graphics technique but its still just sampling textures.

Its even so simple to implement you can do it with an alpha test in fixed function pipelines!

Check this out for more info: http://blog.demofox.org/2014/06/30/distance-field-textures/
> 2 votes

# Answer
I created this app to build texture atlases for fonts quite a while back https://fontconvert.codeplex.com/

texture size vs pixel preciscion has a lot of answers depending on if you are attempting pixel perfect rendering on a display of known resolution, or if you are going to be using a single font atlas with scaling to get different font sizes.

For pixel perfect rendering you want your texture needs to be sized to fit all the characters needed from the font at the exact correct resolution

For scaled rendering, you normally want to create the font atlas at the largest scale you plan to use the font at to prevent artifacts at full size.

For both these cases the app will help you decide how large a texture you need.

In either case with modern hardware, having large textures isn't all that much of a problem, however, the app is designed to split the font into multiple textures if needed, though you will need to create a shader that takes a set of UV coords for each texture and and blends the resulting pixel from each texture

typically one UV coord will point to a character on its corresponding texture, and all the others will point at a blank area, or one UV coord can be used if you pass some additional info in the vertex data for each character quad specifying which texture to use
> 0 votes

# Answer
there 2 way to do it

1. use bitmap font, as Ascendion say, each character represented as a GL\_QUAD. you can just use 1 texture to render many paragraph, with hundred of GL\_QUAD.
2. you can dynamically generate a texture which has text on it. then use this text texture to render. you just need a single GL\_QUAD to render a paragraph, but be careful, as the text grow, memory needed to store text texture grow too.

in fact, we use both way to render texts, 1st method, for those text that change frequently(item description, chat log, ...). 2nd method, for those text that fixed during game running(game name, player name, ...).
> 0 votes

# Answer
For my font renderer I store all characters in a texture\_array, which eliminates the need for atlas mapping and worrying about uv float precision.

For drawing use pointsprites and give each vert only a single attrib for character id, while the vertex shader tracks the spacing and scaling, you could easily adapt it to render multiple lines. Afaik this is the best way to maximally take advantage of gpu for rendering text.

```
uniform vec2 corner;//ndc
uniform vec2 scale;//ndc
uniform int px;

layout(location=0) in int chin;

flat out int character;
void main(){
    gl_PointSize= px;
    gl_Position= vec4(gl_VertexID, 0., 0., 1.);
    gl_Position.xy*= scale;
    gl_Position.xy+= corner;
    character= chin;
}

uniform sampler2DArray tex;
uniform vec4 coloration;

flat in int character;

out vec4 color;
void main(){
    color= texture(tex, vec3(gl_PointCoord, character))*coloration;
}

```
> 0 votes

---
Tags: textures, text
---


title: UDK - Commercial Use Age Limit

text:
# Question
Title: UDK - Commercial Use Age Limit
So I'm 15 and I was wondering if there is an age limit to be able to publish a commercial-game. I know that I have to pay $99 to buy a commercial license

# Answer
You must at Age of consent so you could get a license personally, quote:

> A note to developers under the age of consent (minors): Please have your parent or guardian contact us for a UDK Commercial Use License, as we cannot enter into a license agreement with a minor.
> 1 votes

---
Tags: udk, commercial
---


# Question
Title: How can I consistently identify location on a mesh from a raycast hit?
I am using RaycastHit.triangleIndex to identify a location on a mesh (very low poly). However, I have discovered that a given triangle on the mesh does not have the same triangleIndex value from one execution of the game to the next (index "1" maps to location "A" on the first run, but location "B" on the second run). It is consistent within a given game, but for my mapping to work I need it to be consistent across games.

Given that I am using Raycast, how can I consistently identify the same logical location on the model?

Notes:

* The game object must be instantiated from a prefab (there are a variable number of them), so it could be that this is why the vertex order changes? Is there a way to instantiate with consistent vertex order?
* If I need to ask the artist to recreate the asset with submeshes for each location, will I be able to consistently identify those?

# Answer
> 1 votes
My suggestion is make empty gameObjects on the certain points, add (sphere) colliders(isTrigger=true), and use hit.point to accomplish that same purpose.

This is less troublesome than having your artist to recreate sub-meshes.

I haven't use the trianglIndex before but according to the API: triangleIndex is accurate but it may be difficult to collect the indexes, and a set of arrays MUST be made to declare certain points on the mesh.

# Answer
> 0 votes
You might check to see if the triangles in each index variant are still listed in the same order (for instance, sometimes it's A0 B1 C2 D3, sometimes it's B0 C1 D2 A3, but always the same triangles come before and after each other in the index). If that's the case, you might be able to calibrate when you instantiate your gameobject by shooting a raycast at the triangle you want to treat as index 0 and noting the difference between 0 and its actual index. You could infer the index of other triangles from there.

---
Tags: unity, raycasting
---


# Question
Title: Gamemaker - Change the fired bullets' direction using objects as guide
So I am trying to create a shooting-ship-puzzle game at sea on gamemaker. There is a playership that must shoot the enemy ships using only the available "whirlpools". There are many whirlpools in the sea, but there is only one path consisting of whirlpools that will lead the bullets to the enemy ships and destroy them. There are different types of whirlpools, one that can direct the bullets using 90 degrees angle, U-turn whirlpool, etc. But my problem is how to change the direction of the fired bullets using those whirlpools. So can you guys maybe help me out with this problem...?

Thanks,

# Answer
Add a static variable stored in each whirlpool that declares the angle to turn:

```
public static float turningAngle = 90.0f;

```

\*Commonly, positive values for turning right, negative values for turning left.

When the bullet enters the trigger bound with the whirlpool, the bullet takes the turningAngle's value and rotates itself by that angle.

```
// Rotate(x, y, z, w) <-- A Quaternion's rotate function
this.Rotate(0, turningAngle, 0, 0);

```

Make sure the bullet is travelling at the positive direction of x-axis or z-axis, or else you may have to modify the axis and angle.
> 1 votes

---
Tags: game-maker, puzzle, shooter
---


# Question
Title: Half top-down view collision and mechanics
I'd like to create a game with a half top-down (2d RPG) view (I don't know the exact name of it). It would be 2d, but I'd like to add 3d-like collisions. For example:

If the grenade lands on the roof, it would roll down and fall. Or if it hits a wall, it would bounce back.

I've never worked with this view, that's why I'm asking for advices for how to do proper collisions and physics. I don't want to use any external libraries.

Thanks in advance!

# Answer
The simplest answer will be: Use 3D Colliders

It's possible to freeze one of the axes (z-axis) when the grenade is bouncing back from a 3D Collider, hence it will only moves in x-axis and y-axis.

Apply a sphere collider and rigidbody(with z-axis frozen) on the grenade, a cube collider with thin z-scale on the roof, when the grenade is thrown to the roof, collisions occur and the grenade will be bounced back.
> 1 votes

---
Tags: collision-detection, physics
---


title: Making a zoom out/in space map in Unity

text:
# Question
Title: Making a zoom out/in space map in Unity
I'm new to unity, I was wondering how would one go into implementing a dynamic 2d space map. Let me give you an example what i mean. You see our solar system on the map, if you zoom out at a treshold value this solar system would just be represented by a name and our sun and around it you see adjacent solar systems. How would I do this in unity?

# Answer
Zooming by setting the Z-Position.

Obtain the Z-Position value by using `transform.position.z`, and then make a if-condition to declare when the different modes you would like to show.

```
private float maxZoomIn = 5.0f;
void Update()
{
    zoom();
    checkZoomState();
}

void zoom()
{
    //Simple zooming mechanics
    if(transform.position.z >= maxZoomIn)
        transform.position.z += Input.GetAxis("Mouse ScrollWheel");
    else
        transform.position.z = maxZoomIn;
}

void checkZoomState()
{
    //Assuming the space map plane is at z = 0
    if(transform.position.z <= maxZoomIn)
        Debug.Log("The camera touches the plane.");
    else if(transform.position.z > maxZoomIn && z <= 50)
        Debug.Log("Zoomed inside the solar system.");
    else if(transform.position.z > 50 && z <= 100)
        Debug.Log("Zoomed outside the solar system, seeing adjacent solar systems");
    //Add more as you like
}

```
> 0 votes

---
Tags: unity, 2d, maps
---


title: Isn't OnGUI and Event cyclical?

text:
# Question
Title: Isn't OnGUI and Event cyclical?
Here's what I don't understand about Events:

the documentation says that `Events correspond to user input (key presses, mouse actions), or are UnityGUI layout or rendering events. For each event OnGUI is called in the scripts; so OnGUI is potentially called multiple times per frame. Event.current corresponds to "current" event inside OnGUI call.`

the documentation pertaining to onGUI states that it has`one call per event`

That doesn't make sense to me, because I know I can call Events within OnGUI.

I have an OnGUI function that draws a grid using x and y nested for loops, then checks using `Event.current.mousePosition` if your mouse is hovering over a grid block. What I don't get is how OnGUI is ever called, if OnGUI is only called when an event occurs, but I have the event inside OnGUI so how can you ever check if the event is being called inside a script that is only called after the event is called?

I know that probably sounds confusing -- I'm just puzzled by the seemingly cyclical nature of ongui.

# Answer
> because I know I can call Events within OnGUI.

Accessing data from the current event i.e. `Event.current.mousePosition` is not "calling an event", at least not in the sense that you're activating the event so triggers an `OnGUI` call. As the documentation says, that you posted in your question:

> `Event.current` corresponds to "current" event inside OnGUI call.

That means using `Event.current.mousePosition` is just accessing the event that triggered the `OnGUI` call, not triggering a new event.

Events are triggered outside of `OnGUI` via user interaction with the UI.

There is one event type that happens every frame, no matter the user input, `Repaint`. `Repaint` is sent every frame when the GUI is redrawn. This is the last event processed. This is where your grid is drawn every frame, because this event happens every frame.
> 3 votes

---
Tags: unity
---


# Question
Title: Objects spawned on clients only appear locally
I'm trying out the new Unity 5.1 networking for a Bomberman style game and i can't seem to get the bombs to instantiate on both the client and all those connected, what am i missing?

The code below instantiates a prefab at the players current position, that prefab has a Network Identity and a Network Transform same as the players, i thought if the object is spawned using "NetworkServer.Spawned(Object)" then that would be instantiated on both clients?

```
    // Update is called once per frame
void Update()
{
    if (isLocalPlayer)
    {
        this.transform.Translate(new Vector3(Input.GetAxis("Horizontal") * speed * Time.deltaTime, Input.GetAxis("Vertical") * speed * Time.deltaTime, 0.0f));

        if (Input.GetKeyDown(KeyCode.Space))
        {
            GameObject item = Instantiate(prefab, this.transform.position, Quaternion.identity) as GameObject;
            NetworkServer.Spawn(item);
        }
    }
}

```

# Answer
It seems i misread the docs for \[Command\], the objects are now instantiated on both clients

```
// Update is called once per frame
void Update()
{
    if (isLocalPlayer)
    {
        this.transform.Translate(new Vector3(Input.GetAxis("Horizontal") * speed * Time.deltaTime, Input.GetAxis("Vertical") * speed * Time.deltaTime, 0.0f));

        if (Input.GetKeyDown(KeyCode.Space))
        {
            CmdSpawnBomb(this.transform.position);
        }
    }
}

[Command]
void CmdSpawnBomb(Vector3 pos)
{
    GameObject item = Instantiate(prefab, pos, Quaternion.identity) as GameObject;
    NetworkServer.Spawn(item);
}

```
> 2 votes

---
Tags: unity, unity-networking
---


# Question
Title: What is the difference between Djikstra and flow fields?
I understand flow field pathfinding (as illustrated in recent Gas Powered Games titles) consists of 1) computing a vector field covering the map for a given destination, 2) deriving unit directions from their position on that field, and 3) recomputing it at each frame to take dynamic obstacles into account.

I was wondering if the very same steps could be used, but by computing the vector field simply with Dijkstra. After all, if you apply Dijkstra in reverse (from the destination), and continue until you've covered the whole map, you end up with a vector field giving the best direction for each unit trying to get to that destination. If you recompute it each frame, don't you end up with the same behavior and efficiency as flow field, only without the math I don't understand?

# Answer
> 6 votes
The *Fast Marching* method for solving the \*Eikonal Equation is in fact based on Dijkstra's algorithm. It has O(N log(N)) performance, which is fine for small grids but can be improved on for larger grids by employing either the *Fast Iterative* or *Fast Sweeping* methods.

As noted in your link:

> More importantly, the *Fast Marching Method* uses a binary heap, which means it's not straightforward to parallelize, and has poor cache coherency. The *Fast Sweeping Method* has the potential to perform better, yet is slowed down by any direction changes that could happen, say, in the case of a winding maze. The *Fast Iterative Method* is a pretty good compromise between these two, working pretty well in winding mazes, being somewhat amenable to parallelization, and having good cache coherency.

This link contains additional references on use of Dijkstra in solving the *Eikonal Equation*.

The particular technique most applicable to any particular situation is a meta-decision that the program designer must make, or direct the application itself to make.

In my Hex-Grid game engine I use two separate path-finding algorithms: one for short distances that does not utilize road movement, and employs a tie-breaker heuristic for improved visual aesthetics, but is prohibitively slow for long distances; and a second that uses a much more efficient heuristic and does employ road movement, but is visually unaesthetic. The game engine chooses between the two based on the *as-the-crow-flies* distance from origin to target.

---
Tags: path-finding, rts
---


title: Separate rotation transform from parent

text:
# Question
Title: Separate rotation transform from parent
I have a hierarchy like this

```
Body
  - Head
  - Arms

```

Currently this works fine in that the `Body's` transformation is reacting as it should. Being children, the Head and Arms match the Body's transform. Is it possible however to separate just the rotation transform? I would like the head to translate with the body but not necessarily rotate the same way.

I tried using Transform.DetachChildren but that removes the translate transform which is a bit of an issue as I move the object using physics so there's a chance the head and arms would react differently and physically separate from the body.

Thanks

# Answer
This is a script that keeps the rotation of the head to the rotation you set in the script, however it is very simple and may need adjustment to your purpose.(I have included sliders for easy editing). I hope this answers your question.

```
using UnityEngine;
using System.Collections;

[ExecuteInEditMode] // This allows it to run during editmode(Makes it easier to work with)
public class KeepHeadRotation : MonoBehaviour
{
Quaternion rotation;
Quaternion newRotation;

[Range(-90,90)]
public float X = 0, Y = 0, Z = 0, W = 0;

void Start()
{
    rotation = transform.rotation;
}

void Update()
{
    newRotation = new Quaternion(rotation.x - X, rotation.y - Y, rotation.z - Z, rotation.w - W);
    transform.rotation = newRotation;
}
}

```

It works by storing the rotation of the object at the beginning and fixing it to that rotation and the sliders affect the rotation by either adding or subtracting from it allowing you to change it via the script.

Here is the link to the Quaternion page on the Unity API: http://docs.unity3d.com/ScriptReference/Quaternion.html
> 2 votes

---
Tags: c#, unity, rotation, transformation, heirarchy
---


title: Lighting changes when loading scene

text:
# Question
Title: Lighting changes when loading scene
I have a script that changes the levels using

```
Application.LoadLevel (sceneNameToChangeTo);

```

Once a level is loaded using that code when testing with the editor, the lighting changes dramatically. I've checked if something changes in the light or lighting settings, but it doesn't.

This is a screen of how the scene looks when I simply press RUN in the scene in the editor:

Notice the blue tints from the sky etc. This is clearly PBS lighting.

Now after I use my code to change the scene to another one and then back to this one, the scene looks like this:

What am I doing wrong? I am using Unity 5.0.1. This effect does not happen on mobile devices.

# Answer
> 1 votes
I encountered this problem as well. I believe it is due to using the editor that unity doesn't load it as quickly and as a result not all the shaders are implemented or not all the lighting that is baked is configured.

All I can suggest is wait for a fix. In the meantime it does not actually affect the project when you build it, and when testing you should build it often to check how it works as it should.(just grin and bear it until unity make a fix)

---
Tags: unity, lighting
---


title: Platformer Collision in JavaScript

text:
# Question
Title: Platformer Collision in JavaScript
I'm making a platformer in JavaScript and this is the collision detection function that I have

```
if(obj2.y > obj1.y + obj1.height ||
   obj2.y + obj2.height < obj1.y||
   obj2.x > obj1.x + obj1.width ||
   obj2.x + obj2.width < obj1.x){
    return false;
} else {
    return true;
}

```

So my question is, how do I tell which side `obj1` is colliding with `obj2`?

# Answer
In your collision function, instead of returning a boolean, return a string so that you can detect each face:

```
function colCheck(args) {
    if(obj2.y > obj1.y + obj1.height) {
        return "u"
    }
    if(obj2.y + obj2.height < obj1.y) {
        return "d"
    }
    if(obj2.x > obj1.x + obj1.width) {
        return "r"
    }
    if(obj2.x + obj2.width < obj1.x) {
        return "l"
    } else {
        return false;
    }
}

```

Depending on the collision, the function will return `u`,`d`,`l`, or `r`, which you can use however you like
> 1 votes

---
Tags: 2d, collision-detection, javascript
---


# Question
Title: Keyboard input vs character movement encapsulation
In our game created with c++ and sdl we are having difficulty delegating how the main character should be controlled. We have a keyboard class and a sprite class for the main character, but are unsure if the main character should have an instance of the keyboard class or if keyboard input should be done through the game loop. If you need anymore information I would be happy to provide it, thanks in advance for any help.

# Answer
Your main character class should not have a reference to the keyboard or any input-related class. Input should be handled in the game loop, or preferably a dedicated input class, decoupled from other entities so they'll only need to respond to abstract actions, not raw input.

Not all input is related to your characters and and not all types of input devices are the same, so your best bet is to separate the input handling into several stages so you can handle it contextually e.g.

1. Gather input data
2. Examine current game state or context (MainMenu, InGame, InGameMenu, GameOver etc.)
3. Mapping raw input to actions ... etc.

This will make it easier for you to implement new actions, control schemes, input devices or multiplayer controls.
> 1 votes

---
Tags: c++, movement, sdl, keyboard
---


title: How to create gui image with script

text:
# Question
Title: How to create gui image with script
So I've been fiddling around with the new UI system recently -- and one problem I have is adding images of my sprites to the ui.

I know I can create a prefab of an image gameobject with the sprite I want, but I have hundreds of the sprites I want to add to the ui (They're different characters) so I don't want to create hundreds of prefabs. Instead, what I want to do is in a script, create an image gameobject, set its sprite, and child it to a parent panel in my canvas. Is this possible?

# Answer
> 14 votes
Its entirely possible. Here's a simple script showing how.

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

public class PopulateSprites : MonoBehaviour {

public List<Sprite> Sprites = new List<Sprite>(); //List of Sprites added from the Editor to be created as GameObjects at runtime
public GameObject ParentPanel; //Parent Panel you want the new Images to be children of

// Use this for initialization
void Start () {
    foreach (Sprite currentSprite in Sprites)
    {
        GameObject NewObj = new GameObject(); //Create the GameObject
        Image NewImage = NewObj.AddComponent<Image>(); //Add the Image Component script
        NewImage.sprite = currentSprite; //Set the Sprite of the Image Component on the new GameObject
        NewObj.GetComponent<RectTransform>().SetParent(ParentPanel.transform); //Assign the newly created Image GameObject as a Child of the Parent Panel.
        NewObj.SetActive(true); //Activate the GameObject
    }
}

```

}

Unity Reference for AddComponent: AddComponent

---
Tags: unity, gui
---


# Question
Title: Cannot Get The Texture Showed Up Correctly glDrawElements
I still have this problem almost 1 month. Tried to search on Google but did not find any solution to this. I have loaded all the data correctly but don't know why the texture came up like this.

Here is my loader:

Header

```
struct SVertex
{
public:
    float X, Y, Z;
};

struct STexture
{
public:
    float U, V;
};

struct SFace
{
public:
    int X, Y, Z;
};

class CBMap
{
public:
    struct SMesh
    {
        SVertex *Vertex;
        SVertex *Normal;
        STexture *TexCoord;
        SFace *Face;
        SFace *FaceNormal;

        char Texture[32];
        int TextureID;
        int TotalVertice;
        int TotalNormal;
        int TotalFace;
    };

    SMesh* Mesh;

    CBMap();
    ~CBMap();

    int TotalMesh;

    int Load(char* szFile);
    int Get_FileHeader(FILE* pFile);
    int Get_TotalMesh(FILE* pFile);
    int GetData(FILE* pFile);
};

```

CPP

```
int CBMap::Load(char* szFile)
{
    FILE* pFile = fopen(szFile, "r");

    if (!pFile) return 0;

    int iBMap = Get_FileHeader(pFile);

    if (!iBMap)
    {
        printf("BMAP file is not valid\n");
        return 0;
    }

    TotalMesh   = Get_TotalMesh(pFile);
    Mesh        = new SMesh[TotalMesh];
    GetData(pFile);

    int iMesh = 0;

    char* pJunk;
    char szHeader[32];

    while (!feof(pFile))
    {
        fscanf(pFile, "%s", &szHeader);

        if (!strncmp(szHeader, "BMAP", 4)) continue;
        if (!strncmp(szHeader, "mesh", 4)) continue;
        if (!strncmp(szHeader, "mtl", 3))
        {
            fscanf(pFile, "%s", Mesh[iMesh].Texture);
            Mesh[iMesh].TextureID = LoadTexture(Mesh[iMesh].Texture);
        }

        if (!strncmp(szHeader, "ve", 2))
        {
            fscanf(pFile, "%d", &pJunk);
            Mesh[iMesh].Vertex = (SVertex*)malloc(sizeof (SVertex) * Mesh[iMesh].TotalVertice);

            for (int i = 0; i < Mesh[iMesh].TotalVertice; ++i)
            {
                fscanf(pFile, "%f %f %f", &Mesh[iMesh].Vertex[i].X, &Mesh[iMesh].Vertex[i].Y, &Mesh[iMesh].Vertex[i].Z);
            }
        }

        if (!strncmp(szHeader, "uv", 2))
        {
            fscanf(pFile, "%d", &pJunk);
            Mesh[iMesh].TexCoord = (STexture*)malloc(sizeof (STexture) * Mesh[iMesh].TotalVertice);

            for (int i = 0; i < Mesh[iMesh].TotalVertice; ++i)
            {
                fscanf(pFile, "%f %f", &Mesh[iMesh].TexCoord[i].U, &Mesh[iMesh].TexCoord[i].V);
            }
        }

        if (!strncmp(szHeader, "vn", 2))
        {
            fscanf(pFile, "%d", &pJunk);
            Mesh[iMesh].Normal = (SVertex*)malloc(sizeof (SVertex) * Mesh[iMesh].TotalNormal);

            for (int i = 0; i < Mesh[iMesh].TotalNormal; ++i)
            {
                fscanf(pFile, "%f %f %f", &Mesh[iMesh].Normal[i].X, &Mesh[iMesh].Normal[i].Y, &Mesh[iMesh].Normal[i].Z);
            }
        }

        if (!strncmp(szHeader, "f", 1))
        {
            fscanf(pFile, "%d", &pJunk);
            Mesh[iMesh].Face = (SFace*)malloc(sizeof (SFace) * Mesh[iMesh].TotalFace * 3);
            Mesh[iMesh].FaceNormal = (SFace*)malloc(sizeof (SFace) * Mesh[iMesh].TotalFace * 3);

            for (int i = 0; i < Mesh[iMesh].TotalFace; ++i)
            {
                fscanf(pFile, "%d %d %d %d %d %d",  &Mesh[iMesh].Face[i].X, &Mesh[iMesh].Face[i].Y, &Mesh[iMesh].Face[i].Z,
                                                    &Mesh[iMesh].FaceNormal[i].X, &Mesh[iMesh].FaceNormal[i].Y, &Mesh[iMesh].FaceNormal[i].Z);
            }
        }

        if (!strncmp(szHeader, "end", 3))
        {
            if (iMesh < TotalMesh) iMesh ++;
        }
    }

    printf("CBMap::Model Loaded\n");

    fclose(pFile);
    return 1;
}

```

First picture is reality and second picture expectation

# Answer
DirectX and OpenGl have different coordinate systems for their texture coordinates. OpenGl uses a origin in the lower left but your model assumes that the origin is in the upper left. Because of that you need to mirror the UV coordinates or your images along the y axis. You can do so by setting the v component to 1 - loadedV.
> 0 votes

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


# Question
Title: 2D C# Collecting Item For Acceleration Unity
I have an issue regarding acceleration for Unity in C#, I'm trying to have my player collect an item and gain speed from it. Now, I have this working, but I need it to be a gradual acceleration, I don't want my player to just instantly jump to the maximum speed like he is now.

Here is how far I've got, I'm not sure if I'm on the right track or not. Any help?

```
void OnTriggerEnter2D(Collider2D other) {

            if (other.tag == "speedBoost") {

            transform.position += Vector3.right * acceleration * Time.deltaTime;

            if (acceleration < horizontalSpeed) {
            acceleration += 1;
        }
                    //transform.position += Vector3.right * horizontalSpeed * Time.deltaTime;
                    Destroy (other.gameObject);
            }
    }

```

I appreciate any help you can give, thanks!

# Answer
You can use Mathf.Lerp. Mathf.Lerp takes in 'From', 'To' and 'T' parameters. It interpolates your value From to To over T. The T parameter should be a value between 0 and 1. 0 is equal to your From value and 1 is equal to your To value.

For example:

**From** = 1

**To** = 2

**Difference** = **To** \- **From** = 1

So if T were equal to 0.5, the returned value would be 1.5

I'm not entirely sure what your exact plans for this idea are or how it will tie into your game, but I have constructed a basic script for you to read over and understand what is happening.

```
using UnityEngine;
using System.Collections;

public class PowerUpTest : MonoBehaviour
{
    public float minSpeed = 1.0f;   //Minimum powerup speed 'From'
    public float maxSpeed = 10.0f;  //Maximum powerup speed 'To'
    public float incrementRate = 0.1f;  //The rate you want the speed to change
    public string powerUpName = "SpeedBoost";   //The tag of the powerup gameobject

    private bool executePowerUp = false;  //Checks whether to execute the powerup
    private float currentSpeed; //The current speed of your powerup boost value
    private float lerpTime;  //The lerp time 'T'

    void Start ()
    {
        currentSpeed = minSpeed; //Set current speed to equal the minimum speed
    }

    void Update ()
    {
        if (executePowerUp) //If the executePowerUp bool is true
        {
            if (lerpTime <= 1) //If the lerp time has not reached the maximum value ('To')
            {
                lerpTime += Time.deltaTime * incrementRate; //Increase the lerp time by deltaTime multiplied by the rate
                currentSpeed = Mathf.Lerp (minSpeed, maxSpeed, lerpTime); //Set the current speed to the current lerped value
                print (currentSpeed); //print the current speed for you to see the change in the value
            }
            else //If the lerp time has exceeded the 'To' value
            {
                executePowerUp = false; //Turn execute powerup to false
                lerpTime = 0; //Reset the lerp time
            }
        }
    }

    void OnTriggerEnter2D (Collider2D other)
    {
        if (other.CompareTag (powerUpName)) //If the trigger object tag is equal to the powerup tag
        {
            executePowerUp = true; //Set execute power to true to initiate the lerp code
            Destroy (other.gameObject); //Remove the collided object
        }
    }
}

```

The code is fully commented. If you don't understand something, post a comment.
> 1 votes

# Answer
The first clear issue is this line:

```
transform.position += Vector3.right * acceleration * Time.deltaTime;

```

`transform.position` is in length units (it's value represents distances along the 3 world axes from the origin).

In this line of code you are adding a value with velocity units to a variable with length units. `acceleration` is length/time^2, `Time. deltaTime` is time, and `Vector3.right` is unitless (it's a direction). Multiplied together we get length/time which is velocity.

Perhaps the name of the `acceleration` variable is misleading and it's actually velocity. By any case, you have to make sure your units check out first. Then, to get the effect you want what you want to do is instead of adding values to the position of the object, add values to it's maximum speed (store this variable somewhere in a component).
> 0 votes

---
Tags: c#, 2d, transformation
---


# Question
Title: GetButtonDown for Unity keyboard UI navigation?
By default, Unity's keyboard navigation for buttons seems to check for GetButton rather than GetButtonDown--if a menu has 5 items and I hold the down arrow, it'll scroll very quickly to the bottom.

This feels awkward; it would make more sense to check for GetButtonDown and only move 1 space per input. However, I can't find any option to let me change that. Any ideas or workarounds?

# Answer
> 1 votes
Sadly there's currently no way to make Unity's keyboard navigation to use `GetButtonDown` instead of `GetButton`.

However, **EventSystem** -\> **Standalone Input Module** exposes an **Input Actions per Second** variable.

The default value is *10 seconds*.
If you change it to a lower value, like *3*, you will slow down considerably the scroll to bottom speed.

Because picking a low value for this setting will limit your in-game input, you might want to set different values in your menu and game scenes via code. http://docs.unity3d.com/ScriptReference/EventSystems.StandaloneInputModule.html

---
Tags: unity, input, gui
---


# Question
Title: Looking for specific "textured quad" openGL tutorial in c++
I'm new to openGL and I've been googling around for the old and simple textured quad tutorial in openGL but I haven't been able to find one that suits my needs.

* OpenGL3.X compatible
* OpenGL|ES 2.0 compatible AND
* Only uses core openGL library (no GLUT, GLEW...)

I'm creating the window and the openGL context with SDL2.

I only need the most basic stuff to draw quads. I'm not interested in any of the new OpenGL features, just in compatibility and cross platformness (Windows, OSX, Linux, Android and iOS).

# Answer
*Seeing as though you said you need to support OSX I'm going to presume you request a 3.3 core context or better.*

You said you don't want to pull in any extra dependencies and to keep it cross platform, so I will try to adhere to this as much as possible.

I am using `stb_image.h` from the Nothing itself nothings.

---

I'm going to define a basic class for a texture:

```
#include "stb_image.h"

class texture{
    public:
        texture(const char *filepath)
            : image(stbi_load(filepath, &width, &height, &components, STBI_rgba)){
            // check image != nullptr

            glGenTextures(1, &handle);

            GLint curr_tex; // for saving original state
            glGetIntegerv(GL_ACTIVE_TEXTURE, &curr_tex);

            // I think this is good practice incase somebody else uses your code

            glActiveTexture(GL_TEXTURE3); // or some other texture unit
            // I use 3 because reasons

            glBindTexture(GL_TEXTURE_2D, handle);

            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

            GLint gl_internal_format = ((components == 3) ? GL_RGB8 : GL_RGBA8);
            GLenum gl_format = ((components == 3) ? GL_RGB : GL_RGBA);

            glTexImage2D(
                GL_TEXTURE_2D, 0,
                gl_internal_format,
                width, height, 0,
                gl_format,
                GL_UNSIGNED_BYTE, image
            );

            glActiveTexture(curr_tex); // restore original state
        }

        ~texture(){
            stbi_image_free(image);
            glDeleteTextures(1, &handle);
        }

        int width, height, components;
        unsigned char *image;
        GLuint handle;
};

```

You could expand on this class, adding conversions and such.

---

Next I'm going to add a basic quad class:

```
class quad{
    public:
        quad(){
            GLfloat vertices[] = { // format = x, y, z, u, v
                -1.0f, -1.0f, 0.0f,  0.0f, 0.0f,     1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
                 1.0f,  1.0f, 0.0f,  1.0f, 1.0f,    -1.0f,  1.0f, 0.0f, 0.0f, 1.0f
            };

            glGenVertexArrays(1, &vao); // vao saves state of array buffer, element array, etc
            glGenBuffers(1, &vbo); // vbo stores vertex data

            GLint curr_vao; // original state
            glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &curr_vao);

            glBindVertexArray(vao);
            glBindBuffer(GL_ARRAY_BUFFER, vbo);

            glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

            glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float)*5, nullptr);
            glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float)*5, (void*)(sizeof(float) * 3));

            glEnableVertexAttribArray(0);
            glEnableVertexAttribArray(1);

            glBindVertexArray(curr_vao);
        }

        ~quad(){
            glDeleteVertexArrays(1, &vao);
            glDeleteBuffers(1, &vbo);
        }

        GLuint vao, vbo;
};

```

---

Now the most important part: the shaders.

**vertex.glsl**

```
#version 330 core

layout(location = 0) in vec3 vertex;
layout(location = 0) in vec2 uv;

// will be used in fragment shader
out vec2 uv_frag;

void main(){
    uv_frag = uv;
    gl_Position = vec4(vertex, 1.0);
}

```

**fragment.glsl**

```
#version 330 core

// has to have same name as vertex shader
in vec2 uv_frag;

// our texture
uniform sampler2D tex;

// actual output
// gl_FragColor is deprecated
out vec4 frag_color;

void main(){
    frag_color = texture(tex, uv_frag);
}

```

Lets make a class for loading these in

```
class shader_program{
    public:
        shader_program(const char *vert_path, const char *frag_path)
            : program(glCreateProgram()), vert(glCreateShader(GL_VERTEX_SHADER)), frag(glCreateShader(GL_FRAGMENT_SHADER)){

            std::ifstream vert_file(vert_path), frag_file(frag_path);
            // check both opened fine

            auto lvalue = [](auto &&arg) -> decltype(arg)& {return arg;}

            std::string temp, vert_source, frag_source;
            while(getline(vert_file, temp)) vert_source += temp + '\n';
            while(getline(frag_file, temp)) frag_source += temp + '\n';

            glShaderSource(vert, 1, &lvalue(vert_source.c_str()), nullptr);
            glShaderSource(frag, 1, &lvalue(frag.source.c_str()), nullptr);

            glCompileShader(vert);
            glCompileShader(frag);
            // check shaders compiled. google glGetShaderInfoLog

            glAttachShader(program, vert);
            glAttachShader(program, frag);
            glLinkProgram(program);
            // check program linked correctly. google glGetProgramInfoLog
        }

        ~shader_program(){
            glDeleteProgram(program);
            glDeleteShader(vert);
            glDeleteShader(frag);
        }

        GLuint program, vert, frag;
};

```

---

Then we throw it all together:

```
// set function pointers to no-op functions
// always initialize global function pointers
void(*glGenVertexArrays)(GLsizei n, GLuint *arrays) = [](){};
void(*glGenBuffers)(GLsizei n, GLuint *buffers) = [](){};
void(*glDeleteVertexArrays)(GLsizei n, GLuint *arrays) = [](){};
void(*glDeleteBuffers)(GLsizei n, GLuint *buffers) = [](){};
// more than probably a few more pointers

int main(int argc, char *argv[]){
    // create window and context

    glGenVertexArrays = reinterpret_cast<decltype(glGenVertexArrays)>(SDL_GL_GetProcAddress("glGenVertexArrays"));
    // do this for every function pointer

    texture t("mytexture.png");
    quad q;

    shader_program program("vertex.glsl", "fragment.glsl");

    glBindVertexArray(q.vao);
    glActiveTexture(GL_TEXTURE3);
    glBindTexture(GL_TEXTURE_2D, t.handle);
    glUseProgram(program.program);

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    bool running = true;
    while(running){
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
        // we laid our quad out in a fan

        SDL_GL_SwapBuffers();
    }

    glUseProgram(0);
    glBindVertexArray(0);
    glBindTexture(GL_TEXTURE_2D, 0);
    glActiveTexture(GL_TEXTURE0);

    // destroy window and context
    // make sure they are destroyed after the texture, quad and shaders
}

```

I really recommend you don't go through getting all those function pointers yourself though. I can't recommend glLoadGen enough; or something similar (glew).

---

I Gotta warn you now, I haven't tested this code because I'm not at home, but I've written code similar to that before and it's worked great. If any issues arise just leave a comment and I'll fix anything.
> 0 votes

---
Tags: opengl, opengl-es2
---


# Question
Title: How to iterate a sprite group correctly in Pygame avoiding "maximum recursion depth exceeded"?
I'm making a game and I have almost finished it, but I'm usually finding the error `RuntimeError: maximum recursion depth exceeded` when I iterate a sprite group.

This is an example and the group is `self.nextStageCollision()`:

```
def nextStageCollision(self):
    for tile in self.nextStageCollision():
        if tile.rect.colliderect(self.rect):
            self.rect.x = 18*20
            self.rect.y = 20*20
            return True

    return False

```

The group `self.nextStageCollision()` has 4 sprites (tiles) and I'm checking collision between my player and those 4 tiles to go to the next stage but I have to be doing something wrong iterating the sprite group because (I don't know why) it becomes recursive and raises the maximum recursion depth runtime error. I've debugged it and when it reaches the `for each` line, it loops a lot of times there (althought there are only 4 sprites in that group).

I know I can increase the recursion depth, but probably it's better to not play with that and try to improve the code. So, what am I doing wrong? Is there another better way to interate a sprite group to check collisions?

# Answer
> 1 votes
You've made an infinite loop:

```
def nextStageCollision(self):
    for tile in self.nextStageCollision():

```

You probably meant something like:

```
def nextStageCollision(self):
    for tile in self.tileList:

```

Note what you are iterating over. You are calling the `nextStageCollision` to find what to iterate over, which calls `nextStageCollision` to find what to iterate over, which calls `nextStageCollision` and so on until you've hit the "maximum recursion depth".

You shouldn't change the maximum recursion depth, it's in a good position and it wouldn't matter, it would just take longer for your code to crash.

---
Tags: collision-detection, sprites, python, pygame, recursion
---


# Question
Title: Adjust bitmaps according to screen ratios on android
I always thought that pixels were square... it turns out i'm wrong, and I am quite worried by this.
This means that if I draw a circle, it will be round on my screen but it could be an ellipse on someone else's.

My first question is: How common is that? Should I bother to take this in consideration when I draw my graphics/ scale my bitmaps? Or are such weird pixel shapes only used in not-intended-for-gaming screens like hi-tech washing machines?

And my second question is: How can i programmatically get the exact screen size in millimeters (both width and height) of my custom SurfaceView?

# Answer
> 1 votes
No. Pixels *are* squared. At least from an API point of view, you can safely assume that your pixels are square, and that if you draw a circle, you will get a circle.

What you're most likely experiencing is a problem where your target canvas size is not the same as the screen resolution, so pixels will seem stretched. What you need to do is figure out the resolution of the device, and then act accordingly. However...

Making a game that works on any aspect ratio is difficult. Generally, you have two choices: you either modify the game so it works on the target resolution (involves using coordinates and sizes relative to the screen corners, not absolute coordinates), or force the game to use whatever resolution (or aspect ratio) you wish, and then add black bars to compensate for the extra space.

I rarely see a game that does work on any aspect ratio, and black bars are much more common than I would like, but that's life.

# Answer
> 0 votes
First question: You need to have multiple images to suit the user's screen size.

Second question: To get the user's screen size you would need to call the onSizeChanged() method which automatically captures the values of the screen, which you can then use to scale your images to fit the screen.

---
Tags: java, android, aspect-ratio, scale
---