# Question
Title: How to make async step timing (game loop) using Box2D and C++
I'm making a game in C++ using Box2D and WebSocket++. The world needs to updated every `1/60 second`. Meanwhile the WebSocket server handles players. How I should make the interval? I know there's no `setInterval` function in C++, but I can do something like this:

• make async function - https://stackoverflow.com/questions/33234403/using-setinterval-in-c/33234557

• make async thread - https://codereview.stackexchange.com/questions/40915/simple-multithread-timer

or maybe there's a lib?

*Note: this isn't a duplicate of How should I write a main game loop? because here I need **asynchronous** game loop. In linked topic there are synchronous game loops.*

Why I won't use `while` (sync loop):

* commands after `while (loop)` are never excuted if `loop` is set to `true`.

# Answer
> 1 votes
It looks you fell into "I need this!" scheme. But all you need is just call some specific part of game loop asynchronously or non-blocking.

How to achieve this? Make sure whole loop is executed 60 times every second. In more proper words: Make sure every iteration takes less than 16.(6) ms. If it takes longer (your loop "lagged"), make two (or more) updates next frame, so the average FPS remains constant. In the loop gather user input, network data, update game state, render. With this, you can have another thread running WebSocket or a non-blocking function that checks whether anything is in network buffer to read. If not, it returns immediately.

Anything past the while loop is... not a game anymore. Make some cleanup there or anything you find appropriate. Loop might take some bool `isRunning` as condition and be handled inside.

---
Tags: c++, box2d, websocket, timing
---


title: transform.Rotate with z clamped to 0

text:
# Question
Title: transform.Rotate with z clamped to 0
I have a virtual joystick to rotate the player and this piece of code works nice and smooth for the rotation of the players view.

```
public void rotatePlayer(Vector3 newPosition){
  transform.Rotate(new Vector3(-newPosition.y,newPosition.x,0)*Time.deltaTime);
}

```

I pass a Vector3 with the position of the joystick in relation of his parrent's(the joystick border) anchor.That gives me the rotation direction.Which means that if I set the rotation of the camera direclty it will just flip to that point and not move progresively to that point.

Even though z is set to 0 in the vector3, it changes the z axis angle of the camera. How can I clamp it to 0 without using many resources?

I tried other methods but they just switch the camera's rotation directly when the joystick is touched like I already said.Flip and stop.

I guess I could just set the z axis rotation to 0 every time but that just seems like double work.

# Answer
> 1 votes
Use localEulerAngles instead

```
float rotationX = transform.localEulerAngles.x + amount to rotate x;
float rotationY = transform.localEulerAngles.y + amount to rotate y;
transform.localEulerAngles = new Vector3(rotationX, rotationY, 0);

```

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


# Question
Title: How to make characters line up in front of a kiosk at Unity?
In my project I have a queue struct which contains character models. I need to make them line up. When the first model on the line leaves it, the one behind it must take his place and all the line also should align again. Any idea for the algorithm? Thanks in advance.

# Answer
> 0 votes
One way to approach this is to make the kiosk manage its queue. To do this, your kiosk game object should have some information about the queue, at the bare minimum it will probably need a normalized vector indicting the direction of the queue away from the kiosk and a linked-list-like structure referring to the other game objects in the queue. You'll probably also want methods on the kiosk to allow other objects to enter and exit the queue.

```
class Kiosk : ... {
  Vector3 queueDirection;
  LinkedListOf<GameObject> queueMembers;

  void RequestEnterQueue(GameObject object);
  void RequestLeaveQueue(GameObject object);
}

```

To enter the queue, a game object calls `RequestEnterQueue` on the kiosk. `RequestEnterQueue` should compute the desired position for the querying game object to walk to in order for it to line up at the back of the queue. A simple way to do this is to start at the kiosk's position, and displace that position along the queue direction by the kiosk's collision radius. This gives you the idealized location of the first queue position. Continue to displace this position by the collision *diameter* of every object currently in the member list. This gives you the idealized location of of new game object's position in the queue. Displace this position by the new game object's collision radius to get the actual center point the game object should walk to. Tell the game object to walk to that position, and put the game object on the end of the queue list.

To exit the queue, a game object would call `RequestLeaveQueue`. This removes the game object from the member queue list and tells it to move somewhere else. Then, for every member object still in the queue, tell that object to move forward along the opposite of the queue direction by the collision radius of the game object that left the queue.

---

This process is simple to implement. It has the advantage of centrally coordinating the queue management, which means it's easier to do operations on the entire queue. For example, the kiosk can easily tell the first member of the queue to do something (whatever the kiosk is for, withdraw money from a bank account or add a hamburger to the game object's inventory, et cetera), can easily tell every member of the queue to play a bored fidget animation at various times, et cetera.

The disadvantage is that the game object's don't naturally know that they are in the queue unless you add some state to them to indicate that fact. This means they could easily "fight" with the kiosk (the kiosk says "line up here," but something else, maybe even another kiosk the object is trying to line up with, says "no, line up there" and the object jitters back and forth like it can't make up its mind).

Depending on the complexity of other potential interactions with those game objects in the world, this might not be an ideal approach to structuring the queue management (although the approach for actually forming the line could be translated relatively easily to any other way you want to represent the fact that an object is "in the queue").

# Answer
> 0 votes
If you're asking about how to get characters to **Physically** line up, then I would say you could try to have the kiosk keep track of position values that correspond to a queue position, then the characters could automatically travel to queue positions depending on where they are in the queue itself.

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


# Question
Title: Shared data in multithreaded pathfinding engine
Imagine a case where you have lots agents in a big world, who frequently need to calculate the shortest/best path from A to B. In this case it seems natural for me to create a pathfinding engine where each path request is performed in a separate thread. Similar to this example. Requests are stored in a queue, and when there are available threads to perform calculation the request will be taken from the queue and finally moved to a collection of calculated paths.

My problem is: *how do you store and update the data that will be shared among all the threads?* The threads needs access to some kind of map structure (could be a 2D array), and his data needs to be updated frequently. Using some kind of synchronisation mechanism would be too expensive, since we have several threads frequently reading from the data.

I have come up with two suggestions:

1. Store the map structure as an array of atomics. This seems like a simple and effective solution, however we will give ourself a limitation: we can only use data that can be stored as an atomic type - which in most cases should be OK.
2. Create two buffers containing a copy of the data, and keep a reference count for how many threads are currently using the buffer. First update buffer A, then for each new path request we let the thread read from buffer A. When there are no more threads accessing buffer B (RefCount==0) update buffer B and set it as the new active buffer. With this solution we can use any kind of data structure, but it will (depending on the calculation time) be slightly out of sync - which I believe should not be a big problem for pathfinding. If the calculations take a long time, it will be out of sync anyway.

What are your thoughts? I don't have too much experience in the field, so I'm not sure if there are any "popular" solutions to this problem.

# Edit

This is what I ended up with (after reading Kromster's answer):

1. Update the data
2. Take requests out from the queue and start a thread for each request.
3. For each frame: check if all threads have finished.
4. When all threads are done, go back to step 1.

At step 1, all worker threads are idle.

When an agent needs to get a path from A to B, it will call *requestPath(from, to)*, which will return a unique ticket. The ticket has an atomic(modified by pathfinder thread, accessed by agent) indicating whether it is valid or not. When the path has been caluclated, the ticket becomes valid and the agent can call *getPath(ticket)* to get the path.

# Answer
> 0 votes
I would expect all pathfinders working in threads while the rest of the game is busy with other things unrelated to map changing. So map structure could be locked from updates and be in read-only mode while pathfinders do their work.

Of course such system is handy when you do have several lengthy paths to build on each tick or other tasks that can be parallelized (think at least thousands of non-cache-friendly agents on a map).

---
Tags: path-finding, multithreading
---


# Question
Title: Unity3D: Rigidbody2D not colliding with BoxCollider2D
In Unity3D (Version 5.3.1f1 Personal) I have a scene with a sprite with a Rigidbody2D and some sprites with a BoxCollider2D. The BoxColliders **don't** have the `Is Trigger` enabled and the RigidBody is **not** `Kinematic`, but they are not colliding. What am I doing wrong?

# Answer
> 1 votes
Rigidbody2D is a component that gives the GameObject physics properties like gravity, mass, drag etc in a 2D environment.

BoxCollider2D is component that gives the GameObject a box shaped collision detector with certain surface properties in a 2D environment.

When you simulate physics in your game like object falling with gravitational acceleration, stop moving when in contact with another collision detector, having force applied etc you need both `BoxCollider2D` and `Rigidbody2D`.

In some case like non moving obstacles where we usually don't want physics simulation but just collision detection or trigger detection, `Rigidbody2D` can be ignored. But one of the collides must have `Rigidbody2D` in it for collision or trigger detection.

There is also layer based collision detection if you want work with layers of collision detection or ignorance.

---
Tags: unity
---


# Question
Title: How does input work when exporting to Android?
I know I must add Android sdk , but my question is this :

If I make a game that works with the mouse, for example a puzzle game, then I output my game to Android, do I have to rewrite it to work with the touch screen?

# Answer
With Unity, the mouse input will work like a touch input on android, automatically.

Alternatively, you can look at the Input.touches class to handle multiple touches.
> 5 votes

---
Tags: unity, android, input
---


# Question
Title: Vulkan Error: cmd buffer submit cant use image because of layout
I've been coding a Vulkan rendering engine for the past few weeks. My code still continues to execute and I get the desired output, but I am getting an error.

I'm fairly certain that my error is a mistake in my code somewhere. My code is 1000+ lines, so I'm not going to ask anyone to debug it. I guess my question is what typically causes the error I'm getting, and how can I fix it?

I've been pretty closely following this (if this helps anyone): https://software.intel.com/en-us/articles/api-without-secrets-introduction-to-vulkan-part-3#\_Toc445674490

My code draws the desired triangle from the tutorial, but I get an error for the first 3 frames:

```
VKDBG: ERROR: @[DS]: Cannot submit cmd buffer using image (0x6) [sub-resource: aspectMask 0x1 array layer 0, mip level 0], with layout VK_IMAGE_LAYOUT_UNDEFINED when first use is VK_IMAGE_LAYOUT_PRESENT_SRC_KHR.
VKDBG: ERROR: @[DS]: Cannot submit cmd buffer using image (0x7) [sub-resource: aspectMask 0x1 array layer 0, mip level 0], with layout VK_IMAGE_LAYOUT_UNDEFINED when first use is VK_IMAGE_LAYOUT_PRESENT_SRC_KHR.
VKDBG: ERROR: @[DS]: Cannot submit cmd buffer using image (0x8) [sub-resource: aspectMask 0x1 array layer 0, mip level 0], with layout VK_IMAGE_LAYOUT_UNDEFINED when first use is VK_IMAGE_LAYOUT_PRESENT_SRC_KHR.

```

I suppose I could just ignore this, because I get a desired output and the error doesn't seem to break anything, but I would guess that it's bad practice to leave this unfixed.

Thank you for anyone helping!

# Answer
> 2 votes
Swapchain images, when acquired from the presentation engine, are in a PRESENT\_SRC layout. Before we can use an image in a command buffer, we need to transition away from this layout, but using the UNDEFINED as an old layout during transition is also a proper behaviour. Nevertheless, it should also be a proper behaviour to transition away from the PRESENT\_SRC layout and the reported error is (probably) a bug in validation layers.

# Answer
> 3 votes
From Dustin Graves of LunarG about this exact issue:

> This message appears to be generated for a swapchain image that is not being tranitioned from `UNDEFINED` to `PRESENT_SRC_KHR`. Initializing `texture->imageLayout` as `VK_IMAGE_LAYOUT_UNDEFINED` instead of `VK_IMAGE_LAYOUT_PRESENT_SRC_KHR` in `GpuTexture_CreateFromSwapChain` should take care of it.

# Answer
> 0 votes
Right, I thought images acquired from the presentation engine are always in PRESENT\_SRC layout, not after the first time they were acquired:

"After a successful return, the image indicated by pImageIndex will still be in the VK\_IMAGE\_LAYOUT\_PRESENT\_SRC\_KHR layout if it was previously presented, or in the VK\_IMAGE\_LAYOUT\_UNDEFINED layout if this is the first time it has been acquired."

So it is safer to always transition away from the UNDEFINED layout.

---
Tags: vulkan
---


title: LibGDX: How to handle Touchpad input?

text:
# Question
Title: LibGDX: How to handle Touchpad input?
I know that you can just write a code like this in the render method:

```
 public void render(float delta) {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    myStage.act(delta);
    myStage.draw();

    if(myTouchpad.isTouched()){
         //do stuff
     }else{
         //do different stuff
     }
}

```

But I don't think it's a good way to solve this, is there a way to handle this using listeners or something like that?

# Answer
Why not just use it with a `Stage` and `Table` as intended?

```
Stage stage = new Stage();
Table table = new Table(skin); // You can skip table and add it directly to the stage as well.
Touchpad touchpad = new Touchpad(deadzoneRadius, skin);

stage.addActor(table);
table.add(touchpad);

Gdx.input.setInputProcessor(stage); // Stage will handle all input and updates for you.

```

Then you can just use the touchpad methods for whatever you need. If you need to be alerted when the touch pad is pressed you could use a listener.

```
touchpad.addListener(new ChangeListener() {
    @Override
    public void changed(ChangeEvent event, Actor actor) {
        // This is run when anything is changed on this actor.
        float deltaX = ((Touchpad) actor).getKnobPercentX();
        float deltaY = ((Touchpad) actor).getKnobPercentY();
        ...
    }
});

```

There are several listeners available (listener superclass javadoc, lists all listeners), but for a `Touchpad` a `ChangeListener` is probably best suited for the task.
> 3 votes

# Answer
You can use a `ChangeListener`:

```
touchpad.addListener(new ChangeListener() {
     @Override
     public void changed(ChangeEvent event, Actor actor) {
        //do your things
     }
  });

```

Add the listener in your `show()` or `create()` method or in the `screen`'s constructor and you're done!
> 0 votes

---
Tags: libgdx, scene2d
---


# Question
Title: How to calculate move forward direction in Libgdx with Box2d body
I'm working on a game using Libgdx, I've create my world, bodies, fixtures etc. Everything is functional everything is working perfectly but the problem is my body just can left-right-up or down and I do not want to just do this, I want my body go toward to its front side, so it will be like that; User press "D" and Body (player) rotate around and user press "W" body should go wherever its looking direction.

The picture maybe will tell you what is the problem more clearly.

I do not think to share any code blocks because I didn't write any specific code, I just wrote body properties etc. you know. But here is my update method;

```
     public void update(float dt) {
       if (Gdx.input.isKeyPressed(Input.Keys.UP)) {
            player.getBody().setLinearVelocity(0f, 0.5f);
    }
       if (Gdx.input.isKeyPressed(Input.Keys.D)) {
           player.getBody().setAngularVelocity(-0.5f);
    }

```

And if it is possible, I don't want to use body.setTransform() method for move my bodies.

# Answer
> 2 votes
Let's take your image as an example and make a triangle out of it (no hate on drawing skills haha).

By treating this problem like a triangle we can apply some trigonometry to this problem and calculate `X` and `Y` assuming we know `Velocity` and `a (angle)` (which we do!).

Calculation:

```
float velocity = ...; // Your desired velocity of the car.
float angle = body.getAngle(); // Body angle in radians.

float velX = MathUtils.cos(angle) * velocity; // X-component.
float velY = MathUtils.sin(angle) * velocity; // Y-component.

body.setLinearVelocity(velX, velY);

```

I'm not awfully good at explaining (feel free to edit my answer if you wish), so I'm going to reference you to the Wikipedia entry for Trigonometric Functions if you wish to read more on the subject.

---
Tags: libgdx, mathematics, box2d
---


title: Smooth character movement

text:
# Question
Title: Smooth character movement
I want my character to move smooth not instant stopping etc. I want it to decrease velocity slower not instant. I tried with keystates but that doesn't work for 2 keys at once. I tried using key.keysym.sym in switch to set bools: left, right, up, down if key is held but that does not work too when 2 keys are held. Now I am using this

```
void CharProp::handleEvent(SDL_Event e)
{
    if (e.type == SDL_KEYDOWN && e.key.repeat == 0)
    {
        switch (e.key.keysym.sym)
        {
        //case SDLK_w:
        case SDLK_UP:
            cVelY -= CharVel;
            break;
        //case SDLK_s:
        case SDLK_DOWN:
            cVelY += CharVel;
            break;
        //case SDLK_a:
        case SDLK_LEFT:
            cVelX -= CharVel;
            break;
        //case SDLK_d:
        case SDLK_RIGHT:
            cVelX += CharVel;
            break;
        }
    }
    else if (e.type == SDL_KEYUP && e.key.repeat == 0)
    {
        switch (e.key.keysym.sym)
        {
            //case SDLK_w:
        case SDLK_UP:

            cVelY = 0;
            break;
            //case SDLK_s:
        case SDLK_DOWN:

            cVelY = 0;
            break;
            //case SDLK_a:
        case SDLK_LEFT:

            cVelX = 0;
            break;
            //case SDLK_d:
        case SDLK_RIGHT:

            cVelX = 0;
            break;
        }
    }
}

```

This works with multiple keys but I cannot figure out how to make increasing/decreasing velocity. Do you have any tips how to make it using SDL2?

EDIT: Code for decelerating looks like this

```
if (!accelerationX)
{
    if (cVelX > 0)cVelX -= 0.5;
    if (cVelX < 0)cVelX += 0.5;
}

```

Now when character is decelerating it can move through walls because I am subtracting 0.5. I want it to decelerate slow so I don't know what to do( If I changed it to subtract 1 it would work good)Any ideas how to do it?

# Answer
> 6 votes
To create smooth movement you need 4 things:

* The position of the character
* The velocity of the character
* The acceleration of the character
* The max speed of the character

When the user presses the movement keys you need to set the acceleration of the player to the movement acceleration.

When the user releases the key you need to set the acceleration to 0.

When you update the character you need to add the acceleration to the velocity and then add the velocity to the position of the character.

Also, everytime you update you need to check if the velocity is bigger than the max speed of the character and if it is, then set it back.

# Answer
> 0 votes
```
/** I think directly changing the velocity inside the key-listener is
  * not a good idea. You can store which key is pressed inside variables.
  */
var game = {
    leftDown: false,
    rightDown: false,

    keyUpListener: function(event) {
        if(event.keyCode === leftKeyCode) {
            leftDown = false;
        }
        if(event.keyCode === rightKeyCode) {
            rightDown = false;
        }
    },

    keyDownListener: function(event) {
        if(event.keyCode === leftKeyCode) {
            leftDown = true;
        }
        if(event.keyCode === rightKeyCode) {
            rightDown = true;
        }
    },

/** you can pass which those variables inside the required objects, in this case,
  * the player. It would be much cleaner that way and you also won't have the
  * keypress delay/repeat problem which is different in different operating systems.
  */
    update: function(delta) {
        player.update(delta, leftDown, rightDown);
    }
};

/* You wan't the player to not instantly start or stop running. To do that, you
 * need one more variable other than the velocity ("dx" in this case) which is
 * the acceleration (lets call it "ax").
 */

/* Inside your player object, update the velocity and position like this :- */

var player = {
    update: function(delta, leftDown, rightDown) {
        // When left key is down, velocity will deccelerate till it reaches -max value.
        if(leftDown) {
            if(this.dx > -this.maxValue) {
                this.dx -= this.ax * delta;
                if(this.dx < -this.maxValue) {
                    this.dx = - this.maxValue;
                }
            }
        }
        // When right key is down, velocity will accelerate till it reaches max value.
        if(rightDown) {
            if(this.dx < this.maxValue) {
                this.dx += this.ax * delta;
                if(this.dx > this.maxValue) {
                    this.dx = this.maxValue;
                }
            }
        }
        // When both keys are down, or when both keys are up, bring the velocity to zero.
        if((leftDown && rightDown) || (!leftDown && !rightDown)) {
            if(this.dx < 0) {
                this.dx += this.ax * delta;
                if(this.dx > 0) {
                    this.dx = 0;
                }
            }
            else if(this.dx > 0) {
                this.dx -= this.ax * delta;
                if(this.dx < 0) {
                    this.dx = 0;
                }
            }
        }

        // update the position
        this.x += this.dx * delta;
    }
};

```

---
Tags: c++, sdl2
---


# Question
Title: Why my Edit Collider in Unity2D has no point to adjust size?
Why when I clicked to Edit Collider of Box Collider 2D component, is not showing points for me resize the collide box?

# Answer
Edit collider in the Scene view instead of trying it in Game view.

Image shows you are trying it in zoom-able game view.
> 1 votes

---
Tags: unity
---


# Question
Title: Custom Update Function -OR- Multiple TimeScales
I'm trying to create some interesting variations on timescales in my game. In essence, I'd like at least two, probably three or four separate timescales.

* *The player* \- the player timescale is likely to be the game/scene timescale always.
* *Mobs* \- mob timescales can be altered (slower primarily, but also faster possibly) depending on cast spells or other effects in the game.
* *Environment* \- like mobs, the environment may be slowed or sped up depending on some game effects that occur. This would control things like traps, torches, etc.

I'm thinking about things such as a *Slow Time* spell that might slow most mobs, but maybe not others (bool flag), something like a time elemental or something of that nature. I'd also like to possibly slow environmental time so the player may have a single-use item that would allow them to move easily navigate traps (but not have guaranteed success if they still don't see the pattern or such).

Having controller scripts that are added to all objects that listen for calls to change a multiplier on `Time.deltaTime` could be an option, but it's clunky, would have to be in all of the scripts, would have to be accounted for in many areas (movement, combat, possibly related effects), and is just not an ideal option.

Inversely, the same effect (a lich for example casting *slow* on a player) could require opposing things. If I had global settings that contained a multiplier for player/mob/object that were impacted by an effect, I could still always use a multiplier with `Time.deltaTime`, but I still think it would be clunky.

Has anyone done this? Are there any good ideas? I've searched a bit, but didn't find anything terribly useful.

I've considered custom `Update()` classes, though I'm not entirely sure how to implement them. Maybe extend the `FixedUpdate()` class that's built in to take other things into account? I know that `Time.timeScale` is inherently for the current scene, but could I make instances of `Time` that are used by different scripts `FixedUpdate()`? Am I overthinking this? I feel like this shouldn't be quite so difficult.

# Answer
I'd solve this by introducing a global `TimeManager` (probably a Singleton or a static class) whose job is to keep track of the appropriate time scale values for each subset of content, centralising your time-manipulation logic.

It would expose a method something like:

```
public float GetTimeScale(EntityType entityType)

```

…where `EntityType` is an enumeration containing all the different categories of stuff in your game which might need custom time scales.

Internally it can use an array or dictionary to map this type to a timescale coefficient. If you need something more nuanced than a table lookup (eg. time speed varies from place to place around the level, and characters wearing purple are immune on Tuesdays...) you could pass more information in and apply whatever game logic you need in this method to decide what time scale to use.

Each script whose behaviour can be affected will need to call this `GetTimeScale()` method when making any time- or physics-related updates, passing in its identifying information and using the result to scale any changes it's making.

Anything that needs to modify the time scale rules can talk directly to the `TimeScaleManager`, rather than broadcasting out to all the objects that might use the modified rule.

If you want to modify the behaviour of any built-in components like ParticleSystems or Rigidbodies, you'll need to write a little adapter script, like...

```
[RequireComponent(typeof(ParticleSystem))]
public class ParticleTimeScaler : MonoBehaviour {

    public EntityType entityType;
    ParticleSystem _system;

    void Start() {
        _system = GetComponent<ParticleSystem>();
    }

    void Update() {
        _system.playbackSpeed = TimeManager.GetTimeScale(entityType);
    }
}

```

...so you can adjust its behaviour to respect the appropriate speed for its category.
> 1 votes

# Answer
I'd have every class extending MonoBehaviour instead extend TimeBehaviour, where TimeBehaviour extends MonoBehaviour. It has a layer, such as environment, enemies, player, etc, that can be set from the inspector. It also has a map of layers to timescales. In the update method, get the timescale associated with the layer, and set it.

Now in your subclasses, just remember to call base.Update(), and you can forget about everything else. Alternatively, have TimeBehaviour be abstract, and call ScaledUpdate() from the Update method. Then in your subclasses, call ScaledUpdate instead of update.

This is an interesting question to me, and I am actually going to implement this feature for fun tomorrow. I'll let you know if anything from my suggestion changes.
> 1 votes

# Answer
My approach:

* Make a singleton class that contains 3 `Dictionary<float, float>`. One for player, mob, and environment. The two floats would represent a timeScale multiplier and the other a lifeTime value.
* On update, remove Time.deltaTime from each lifeTime values in the 3 Dictionaries. If an entry has negative time remaining then remove it from the map. Store three public floats representing the total multiplied scale values from the three maps.
* Add a method to the singleton class that can add a new value pair to one of the maps. Something like `ChangeMobTimeScale(float percent, float duration)`
* Now: in all update scripts, just multiply Time.deltaTime by the relevant singleton class combined float.

This is more complicated than a single multiplier but would allow for compound effects and would "clean" itself automatically. You will need to access Time.deltaTime frequently so adding that multiplier shouldn't change any greater structure of the gameloop.

Your other option would be a class that checks all GameObject tags and handles calling a custom update function in all objects found with that tag, passing a custom scaled deltaTime value. This method would be slower because of the overhead in constantly checking every tag in the hierarchy.
> 0 votes

---
Tags: unity, game-loop, time-travel
---


title: Unity WaitForSeconds Not Working?

text:
# Question
Title: Unity WaitForSeconds Not Working?
I'm testing out WaitForSeconds

```
using UnityEngine;
using System.Collections;

public class Wait : MonoBehaviour {
private int time = 3;

void Start() {
    StartCoroutine(Example());
}

IEnumerator Example() {
    yield return new WaitForSeconds(time);
    print(":)");
}

}

```

# Answer
**TL;DR:** In the example you give, `WaitForSeconds()` works perfectly fine. When tested, the code waits approximately 3 seconds, before providing the printed output. It is important to note that a co-routine does not deliberately repeat itself - you actually have to tell it to do so. *If repetition is your intention, scroll down to **Reiteration in Co-routines***.

## Testing the Code

I made a few changes to more accurately test your code, and found that it actually works as intended. While I made a few changes, the logic is original to your design:

```
using UnityEngine;
using System.Collections;

public class TestScript : MonoBehaviour
{
    public float time = 3;

    void Start()
    {
        StartCoroutine(CoroutineExample());
    }

    IEnumerator CoroutineExample()
    {
        Debug.Log("CoroutineExample started at " + Time.time.ToString() + "s");

        yield return new WaitForSeconds(time);

        Debug.Log("Coroutine Iteration Successful at " + Time.time.ToString() + "s");
    }
}

```

---

To address the small changes I made,

* I used `float time` instead of `int time`, but `int time` still works correctly. I used a floating point instead of an integer, because `WaitForSeconds()` is designed to take a `float`, not an `int`. In this context, it works it out pretty well, on its own. This is not always the case, and it is best practice to use the correct types whenever possible. If you really had to use an integer, you could also cast it as `(Float)time`, for example.
* I changed the `print()` function calls to `[Debug.Log()]`. Using the editor in Windows, it is easier to simply route debug script to the Debug.Log. At the end of the day, we get the same result; text-based feedback to confirm correct functionality. If you are unfamiliar with Debug.Log, you can find it's API reference here. I believe it works similar, if not identical, to `print()` but it is simply the way I was taught to perform debug output.
* I added a 'Debug.Log()' to the start of the co-routine, so we can confirm that the co-routine has initially started.
* I added `Time.time` to the format printed by `Debug.Log()`, in order to see the exact time stamps of each debug output.

---

When I run the code, this is what I get in my debug log:

As you can see, the timing is not perfect; but we start the co-routine at 0 seconds, and see the final output after *approximately* 3 seconds. After the second `Debug.Log()` command, the co-routine reaches the end of the line, and nothing else is done.

## Reiteration in Co-routines

As mentioned, the code you supply offers nothing to tell the co-routine to reiterate. It will print ":)" once, and only once. That is because co-routines are not specifically designed for repetition - they are designed to allow you to perform a set function *over time*. While you can have a co-routine that repeats itself, you need to specifically tell it to.\

---

In your example, we can use a generic `while(true)` loop to tell the co-routine to repeat through the last 2 steps. Typically you would use a more specific loop to ensure the co-routine loops when it is suppose to, but `while(true)` is fine to demonstrate simple repetition of a `Debug.Log()` or `print()` function.

```
while(true)
{
    yield return new WaitForSeconds(time);

    Debug.Log("Coroutine Iteration Successful at " + Time.time.ToString() + "s");
}

```

---

As you can see in the debug log, we now have scripted output appearing approximately every 3 seconds.

---

## The 'countdown' approach

I am going to address the proposed solution offered by *ardaozkal*, as in this particular case it would be a suitable alternative to using `WaitForSeconds()`. Consider the following code:

```
/// <summary>The time we wait between iterations of Debug.Log</summary>
public float time = 3;
/// <summary>Our current timer, counting down.</summary>
public float countdown = 3;

void Update()
{
    countdown -= Time.deltaTime;   // Reduce our countdown by the
                                   // it has been since our last update

    if(countdownTimer <= 0)        // IF our countdown timer is below
                                   // 0, we have reached 3 seconds.
    {
        countdownTimer = time;              // Reset our countdown,

        Debug.Log("Print Iteration");       // print our output
    }
}

```

In this way, we can set up a 'countdown timer' to handle the same functionality. Every update, we subtract the time since the last update from our countdown. When countdown is at or below 0, we know that the set time has passed, and that that particular update should perform the timed print function. We then reset the countdown timer, using an alternate variable we store to remember the initial time.

---

This might be more suitable if you are unfamiliar with co-routines, but it does have its draw backs. Primarily, the functionality it offers is not anywhere near as extensive as the functionality offered by a co-routine. Further more, it can unnecessarily over-complicate your code, by requiring additional timers/variables.

Then again, you have to remember that co-routines are designed to run *alongside* your other code. They are more favorable for particular events you wish to occur *over* time, not so much *after a* time. You may find that in your scenario, you do not need to use co-routines at all, and this option would be easier to implement.

---

## More on Co-routines

If you are unfamiliar with co-routines, I would suggest you invest a little bit of time looking into them. While they can be abrasive, at times, they can also save you a lot of pain and suffering. You can find the **Unity manual entry on co-routines here**, and **some intermediate scripting tutorials on using co-routines here**.
> 2 votes

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


# Question
Title: How likely will I be able to get a job in game design with a masters in computer programming?
I'm currently attending college and am almost finish with my Bachelors in Computers science.I plan on getting my masters in computer programming in hopes that it will help me get into game design. If not I at least will have a fallback plan in any other IT related field. I'm just curious as to how likely it is to happen for me.

# Answer
You should notice that game design is nothing that is necessarily related to programming. It also applies to board games, card games and every type of game, computer games being one of these. It's a different field and being a good programmer doesn't mean you're a good game designer. However being a programmer already can help you becoming a good game designer because as such you have to have knowledge about what's possible in game development.

I'm currently on the same path working towards my masters degree in media informatics and thinking about how to get into the games industry. Unless you want to be an indie you don't have to master both programming and game design.

Either way start making games with one of the popular engines out there. You will have to be the programmer and the game designer at the same time. Make a lot of games. Most of them will suck but you'll become better and better. Ragarding your question if it's going to happen it won't just happen. You'll have to make it happen and it's not going to be easy.
> 17 votes

# Answer
Let's talk about my experience. I did a diploma in game design, cool right? Then I did a year of games design at degree level, super cool. And then my dreams kinda ended there. I found getting work in the game industry extremely difficult and I had qualifications that were intended to allow easier access into the industry. I ended up with an apprenticeship in software development, a real turn around.

But I still have this spark of games design and development in me, so I took to making my own game. I made a really bad Flappy Bird clone to start with (to get used to GameMakers engine) then took to Unity and Unreal, and found what I enjoyed to work with (which was 2d games with GameMaker.)

I am now working with a company and making assets for games in GameMaker, as well as working on my own project. It will be slow, but this way you have an income, you can live comfortably but also enjoy what you love to do. Making games is fun, but you don't simply make a game, you craft it, mold it from your creativity.

When I visited Ubisoft in Newcastle, one of the designers told me "Never make a game the people want, make a game you want... people will soon realize it's what they wanted all along."

*To sum it up*

Follow your dream (if it is your dream.) But just be careful, and put your heart into a game you want, and just work on it. If you need help with anything, or a direction to go with creating your first indie game, just ask.

Hope this helps.
> 3 votes

---
Tags: game-design, software-engineering, career, jobs
---


# Question
Title: A way to make camera get distance from the player when the player gains velocity?
I'm building upon roll a ball example and I'm trying to make the camera gain distance from the player, when the player starts moving (gaining velocity). i came up with this, but it feels clunky and the camera jumps. is there a better way to achieve this?

```
public float MiddleLineForCameraAdjuster = 2.4f;
float velocityCounter, offsetCounter, normalizedVelX, normalizedVelY, normalizedVelZ;

//Camera Adjuster
private void CameraAdjuster()
{
    if (rb.velocity.x < 0) normalizedVelX = -rb.velocity.x;
    else normalizedVelX = rb.velocity.x;
    if (rb.velocity.y < 0) normalizedVelY = -rb.velocity.y;
    else normalizedVelY = rb.velocity.y;
    if (rb.velocity.z < 0) normalizedVelZ = -rb.velocity.z;
    else normalizedVelZ = rb.velocity.z;

    if (normalizedVelX + normalizedVelY + normalizedVelZ < 25)
    {
        velocityCounter = normalizedVelX + normalizedVelY + normalizedVelZ;
    }
    else if (normalizedVelX + normalizedVelY + normalizedVelZ >= 25)
    {
        velocityCounter = 25;
    }
    else velocityCounter = 0;

    if (normalizedVelX > 0 || normalizedVelY > 0 || normalizedVelZ > 0)
    {
            offsetCounter = 2.4f + (velocityCounter / 10);
            CameraController.offset.x = (CameraController.offset.x * offsetCounter) / MiddleLineForCameraAdjuster;
            CameraController.offset.z = (CameraController.offset.z * offsetCounter) / MiddleLineForCameraAdjuster;
            MiddleLineForCameraAdjuster = offsetCounter;
    }
}

offset = (transform.position - Player.transform.position);

```

# Answer
If you want the camera to simply increase the distance relative to the velocity I would do something like:

```
float cameraDistanceMultiplier = DefaultCamDistance * velocity.length;

if(cameraDistanceMultiplier < MIN_CAMERA_DISTANCE)
    cameraDistanceMultiplier = MIN_CAMERA_DISTANCE;

if(cameraDistanceMultiplier > MAX_CAMERA_DISTANCE)
    cameraDistanceMultiplier = MAX_CAMERA_DISTANCE;

newCamPos = cameraDistanceMultiplier * CameraDirection;

```

To add a rubbery feel to it you could do:

```
Camera.Position = Camera.Position + (newCamPos - Camera.Position) * 0.9f; //tune this value

```
> 2 votes

---
Tags: unity, camera
---


title: Using Steering Wheel in Unity

text:
# Question
Title: Using Steering Wheel in Unity
Is there any way to use a steering wheel in Unity? All I find online is people with the same problem. The numbering on the axis are not the same as with keyboard input. In some cases left is 1 and as you turn it more to the left it gradually goes down to 0 even though you are still turning left

# Answer
> 3 votes
As we can infer from the problem you are actually explaining, yes. You can most certainly use a steering wheel controller. The problem you face is in your *assumption* of how the axis and buttons will be handled, in the first place.

To give a better example, let's take a look at the Xbox 360 controller, courtesy of the Unity 3D Wiki:

As you can see from the diagrams, and the table of axis values provided by the Unity 3D Wiki, we simply can not assume a standard in interpreting input - across controller type ***or*** platform.

By default, nothing should *invert* the axis, either. So if the controller reports "left" as 0, and "center" as 1, you will just have to accept that this is the way the controller outputs, and cater for it on your end.

You can certainly work out the correct axis and inputs through trial and error. Without access to documentation, which is made harder by the fact that input labeling could be unique to both the manufacturer and model of the steering wheel, this might be the easiest solution. There are two ways this could work for you; the automatic approach is by far the easiest, but you may need to take a slower manual approach, if the automatic approach does not expose the complete functionality of the controller you intend to use.

*Keep in mind that this will only tell us what input axis are being used relative to your own operating system and/or drivers. As we have already seen, these values may change across configurations.*

## Automatically identifying each axis

The first option you have is to simply build your game, as is, and use the pre-startup Input Configuration Manager to identify the axis.

Build your game, and run the `.exe` you create. Before the game starts, you are shown a configuration menu. Select 'Input' to look at the input fields you have made available through the Input Manager.

Simply click on an input, under *Primary* or *Secondary*, and you will be prompted to *Press a button or key*. Make the desired input on your controller, and observe the new value it gets registered as.

Note that an axis input shows the positive (+) and negative (-) values as separate controls. This is especially useful, and it may not necessarily be safe to assume that your controller will correctly output opposite directions as the same axis. It may be safer to confirm that the opposite direction on the controller ***does*** correctly register as the opposite direction on the axis, and if not, make a mental note of it.

## Manually checking each axis

You have the option of exposing each axis through a basic script. By creating public floats to update with each available axis, you can see the input values of the many input axis, while providing the desired input with the controller. In turn, you can identify what axis change when you perform certain inputs, and what values they change to. This is quite cumbersome; Unity handles 28 separate axis! I have provided an example of such an implementation, with the presumption that we would only need to check the first 10.

---

First, we need to ensure the Input Manager is correctly set up to forward the intended axis. Ensure that you have an entry for each axis in your Input Manager, and that each one has the correct "axis" selected. For example, the X axis is labelled 'X axis', and your third axis is labelled '3rd axis'.

---

Next, create a script, and make a `public float` for each axis. Name them using the same naming conventions, and ensure that each one is passed the correct `Input.GetAxis()` in an update function.

```
public float x, y, three, four, five, six, seven, eight, nine, ten;

void Update()
{
    x = Input.GetAxis("X");
    y = Input.GetAxis("Y");
    three = Input.GetAxis("Three");
    four = Input.GetAxis("Four");
    five = Input.GetAxis("Five");
    six = Input.GetAxis("Six");
    seven = Input.GetAxis("Seven");
    eight = Input.GetAxis("Eight");
    nine = Input.GetAxis("Nine");
    ten = Input.GetAxis("Ten");
}

```

---

We now have an inspector element that gives us visual feedback of our axis input! While in play-testing, with this script active and visible on the inspector, you can now see the values being stored in your Input Manager. Through trial and error, you can manually work out which axis is represented by which functionality, and what values are passed.

---

Ultimately, there is a lot of special cases to consider, when using *any* non-default controller. At the end of the day, it might be of better consideration to simply set your game up for use with a default gaming controller, or even the keyboard and/or mouse.

The user can still set up their steering wheel during the startup configuration, and this ensures your control scheme matches their unique setup. The only down side to this is that Unity does not save custom key mappings, by default. Unless you implement a way to record customised key mappings to reuse them later, the user would have to configure their controller every time they play the game.

---
Tags: unity, gamepad
---


title: Unity WebGL not loading on chrome

text:
# Question
Title: Unity WebGL not loading on chrome
I've made a simple game but when I tried to load this on chrome its not loading.

I am building for WebGL (HTML 5). I am getting these errors when the page loads.

Unity version - 5.3.1f1 Chrome version - 47.0.2526.106 m

Its working fine on firefox .

```
XMLHttpRequest cannot load file:///C:/Users/Public/Documents/Unity%20Projects/Box%20Shooter/HTML5%20Builds/Release/HTML5%20Builds.js. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.LoadCompressedFile @ UnityLoader.js:1
UnityLoader.js:1 XMLHttpRequest cannot load file:///C:/Users/Public/Documents/Unity%20Projects/Box%20Shooter/HTML5%20Builds/Release/HTML5%20Builds.jsgz. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.DecompressAndLoadFile @ UnityLoader.js:1
UnityLoader.js:1 XMLHttpRequest cannot load file:///C:/Users/Public/Documents/Unity%20Projects/Box%20Shooter/HTML5%20Builds/Release/HTML5%20Builds.mem. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.LoadCompressedFile @ UnityLoader.js:1
UnityLoader.js:1 XMLHttpRequest cannot load file:///C:/Users/Public/Documents/Unity%20Projects/Box%20Shooter/HTML5%20Builds/Release/HTML5%20Builds.memgz. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.DecompressAndLoadFile @ UnityLoader.js:1
UnityLoader.js:1 XMLHttpRequest cannot load file:///C:/Users/Public/Documents/Unity%20Projects/Box%20Shooter/HTML5%20Builds/Release/HTML5%20Builds.data. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.LoadCompressedFile @ UnityLoader.js:1
UnityLoader.js:1 XMLHttpRequest cannot load file:///C:/Users/Public/Documents/Unity%20Projects/Box%20Shooter/HTML5%20Builds/Release/HTML5%20Builds.datagz. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

```

Why its not loading up on chrome ?

# Answer
I believe the issue is occuring because you are running it locally rather than on a webserver or an emulated webserver.

Basically: You need it to say http:// or https:// or whatever rather than file:// in the address bar

If you have a webserver, try uploading it there. If not, check out WAMP or XAMPP

I can recommend WAMP for people with little to no experience in "webserver emulation", but remember to either quit Skype or change the port which Skype uses as WAMP will use the same port which doesn't work.
> 2 votes

# Answer
try in Firefox.

Here is related info from Unity doc: "You can view your WebGL player directly in most browsers by simply opening the index.html file. For security reasons, Chrome places restrictions on scripts opened from local file: URLs, so this technique will not work. If you use Unity’s Build & Run command (menu: File \> Build & Run) then the file will be temporarily hosted in a local web server and opened from a localhost URL (this avoids the security restrictions). You can also run Chrome with the --disable-web-security command line option to enable it to load content from file: urls."

https://docs.unity3d.com/Manual/webgl-building.html
> 0 votes

---
Tags: html5, unity, webgl, chrome
---


title: Trouble With Physics Joints [Gamemaker]

text:
# Question
Title: Trouble With Physics Joints [Gamemaker]
I'm trying to create a series of physics-enabled 'ropes', with hard limits on how far they can swing left or right. They are comprised of an `oRopeRoot` kinematic physics object, which generates a certain number of `oRopeSections`, round little objects, and finally a single `oRopeEndSection`to cap it off.

These are connected by revolute joints with restricted angle of movements. Unfortunately, as you can see from this gif, they are all over the shop. I am still learning about physics joints in Gamemaker, and if anybody can look at the code below and see what might be wrong, I'd be very grateful for the learning experience.

**oRopeRoot**

Density: 0

Restitution: 0

Collision Group: -1

Linear Damping: 0.5

Angular Damping: 0.5

Friction: 1

(Kinematic)

*Create Event:*

```
depth = global.ForeignObjectsOnFaceLayer -1
OriginalX = x
OriginalY = y
image_alpha = 1
image_xscale = random_range(0.3,0.7)
image_yscale = image_xscale
GeneratedValues = true
RopeLength = irandom_range(20,30)
SectionsCreated = 0
EndCreated = false
ParentPore = noone

```

*Step Event:*

```
phy_position_x = OriginalX
phy_position_y = OriginalY - mLeftCheekFurArea.Difference

if SectionsCreated < (RopeLength - 1) {
CreateAndAttachSection()
SectionsCreated = SectionsCreated + 1
} else if SectionsCreated >= (RopeLength - 1) {
if EndCreated = false {
CreateAndAttachEndSection()
EndCreated = true
}
}

```

**CreateAndAttachSection()**

```
if SectionsCreated = 0 {

ParentSection = self.id
ChildSection = instance_create(ParentSection.x,ParentSection.y,oRopeSection)
physics_joint_revolute_create(ParentSection, ChildSection, ParentSection.x,ParentSection.y,-45,45,true,0,0,false,false)
ParentSection = ChildSection
ChildSection = noone

} else if SectionsCreated > 0 {
ChildSection = instance_create(ParentSection.x,ParentSection.y + 6,oRopeSection)
physics_joint_revolute_create(ParentSection, ChildSection, ParentSection.x, ParentSection.y + 6,-45,45,true,0,0,false, false)
ParentSection = ChildSection
ChildSection = noone
}

```

**CreateAndAttachEndSection**

```
ChildSection = instance_create(ParentSection.x,ParentSection.y + 6,oEndSection)
physics_joint_revolute_create(ParentSection, ChildSection, ParentSection.x, ParentSection.y + 6, -45, 45, true, 0, 0, false, false)
ParentSection = noone
ChildSection = noone

```

**oRopeSection**

Density: 1

Restitution: 0

Collision Group: -1

Linear Damping: 1

Angular Damping: 1

Friction: 1

**oEndSection**

Density: 1

Restitution: 0

Collision Group: -1

Linear Damping: 0.5

Angular Damping: 0.5

Friction: 1

# Answer
I think I might have solved this myself. There were several problems with my specific approach which may be useful to others:

* The *pixels-to-meters* scale in my physics world (found in the Physics tab of the Room window) was set far, far too low. The default value is there for a reason: once I started using this, everything calmed down an awful lot.
* Setting a higher density for each component in the revolute joint (\>= 1) also helped to calm the simulation down.

There is further illumination on this thread: https://www.reddit.com/r/gamemaker/comments/4vyop8/help\_using\_prismatic\_joints\_and\_textured/
> 0 votes

---
Tags: physics, game-maker, joints
---


title: Wang tiles generating

text:
# Question
Title: Wang tiles generating
I'm trying to get rid of repetition on terrain, when viewed from up high. To achieve that, I've chosen Wang tiles. One thing I'm missing, and can't really find is any kind of generator that can take a source image and generate a set of Wang tiles from it.

So is there any kind of generator that implements Wang tiles generation from source image? I've tried to read the research papers, but algorithms descriptions there are quite sketchy and vague to be actually put to code.

# Answer
> 1 votes
My understanding is that generating the Wang tile content is the most difficult part of using Wang tiles. All of the papers I've read use some manner of texture synthesis to build the tiles. It is possible to generate synthetic textures based on a source image using things like stochastic sampling, image quilting, & other techniques, but the quality of the output varies greatly depending on the combination of source image properties & the generation methodology. To the best of my knowledge, texture synthesis works best on abstract source images &/or highly repetitive source images. My academic experience with texture synthesis is that it can take a fair bit of tuning & tweaking to get desirable output.

@user1617735 mentioned the GPU Gems 2, Chapter 12, Tile-Based Texture Mapping, which in turn has this to say:

> There are several methods to construct the Wang tile set. One possibility is to draw the tiles manually; all we need to do is to ensure that the drawings are continuous across tile boundaries while producing sufficiently interesting tiling results... This manual approach works only for line art.
>
> For natural texture patterns such as those from photographs, there are algorithmic ways to build the tile set, as described in Cohen et al. 2003, Section 3.2. We have found that this approach works well for many natural texture patterns, and we provide the source code on the accompanying CD.

# Answer
> -4 votes
From what I know, no one's ever heard about Wang tiles, and those few who have are making wang tiles in photoshop. Like this. However, there is a tool from Robert Burke, it is old and not very good, but it does what you ask.

---
Tags: tiles, tilemap, procedural-generation
---


# Question
Title: I am trying to create a plugin and upload it online.But I do not want the users to be able to edit any of the content.Is that possible?
I am trying to create a plugin that can be uploaded into the unity asset store.I do not want the users to be able to edit the content.Functions should not be editable,just the variables should be editable.Is that possible? Or it would be still better if i could just hide the entire script.Any suggestions please ?The scripts are to be attached to the gameobject that will be active in the scene. Thanks

# Answer
Anything that ends up on the user's computer in some form is going to be editable by that user. It's simply a matter of how difficult it would be.

You can choose a method of packaging your content that makes it harder to trivially inspect and modify it (see this related question but you won't be able to completely protect against a dedicated user modifying this data.

Your best bet is to do something simple to protect against casual hacking (the way Unity assets are bundled and supplied to an end-user may already be sufficient for this), indicate in your license agreement for the asset that you cannot modify the core content but can only "change the variables" you've exposed, and be done with it. Anything more will quickly run you into a case of diminishing returns.
> 5 votes

---
Tags: unity
---


# Question
Title: NavMesh.CalculatePath returns invalid path Unity3D
I am trying to get coordinates for path from source to destination object using `NavMesh`. `NavMesh.CalculatePath()` is only working for one level surprisingly. For all others, it returns false. Also `NavMeshPathStatus` is invalid. This is working Level, while this is not working fine with navmesh.

**Code:**

```
private NavMeshPath path;

    void Start () {
        path = new NavMeshPath();
    }

//Following function is called on button press
public void giveHint() {

        NavMesh.CalculatePath(source.transform.position, destination.transform.position, NavMesh.AllAreas, path);

    if (path.status == NavMeshPathStatus.PathComplete)
        print ("Path complete");
    else if (path.status == NavMeshPathStatus.PathInvalid)
        print ("Path invalid");
    else if (path.status == NavMeshPathStatus.PathPartial)
        print ("Path partial");

    for (int i = 0; i < path.corners.Length-1; i++) {
            Debug.Log(path.corners[i]);
        }
   }

// Update is called once per frame
    void Update () {
    if (path.corners != null) {
            if(path.corners.Length > 0) {
                for (int i = 0; i < path.corners.Length-1; i++) {
                Debug.DrawLine (path.corners [i], path.corners [i + 1], Color.red);
                }
            }
        }

    }

```

Please tell me way to debug/solve this issue. How unity calculates path between source and destination? Can there be possibly blockage in path? If yes then how? How path is invalid? Is there any bottleneck with the usage of `CalculatePath` function? Need guide from you guys... Thanks!

# Answer
> 1 votes
Finally, I figured out where I was wrong. I have a cube gameobject as destination. I was not making it part of navmesh baking. `Navigation Static` was not marked for it. So when navmesh was baked, destination was not included as part of it, so path status was invalid.

I cleared the navmesh, made my cube `Navigation Static` and `Walkable`, baked the navmesh again. Now I am getting valid path for all my levels.

Hope it helps someone!

---
Tags: unity, path-finding, navmesh
---


# Question
Title: gameObject and col.gameObject both get destroyed
I want a square\[0\] to be destroyed by triangles(tag = 2) and circles(tag = 3) when the square comes into contact with them.

Also I want square\[0\] to destroy square(tag = 1) and not be destroyed itself.

The code bellow destroys both square\[0\] and any other object it comes in contact with.

Also if there is a more efficient way to put this please tell me. As on the actual script I am dealing with 9 tagged objects and 9 array objects.

My question is: Does my code read "If player is square and it collides with a triangle(tag = 2) or circle(tag = 3) then destroy the square\[0\] and if square\[0\] collides with square(tag = 1) then destroy square(tag = 1)"?

```
void OnCollisionEnter2D (Collision2D col)
{
  if (player[0] && (col.gameObject.tag == "2" || col.gameObject.tag == "3" ))
  {
    Destroy (gameObject);
  }
  if (player[0] && col.gameObject.tag == "1")
  {
    Destroy(col.gameObject);
  }
}

```

# Answer
All 50 lines which didn't work got cut down to about 4 lines which work. I am So Happy.

```
 void OnCollisionEnter2D (Collision2D col) {

    if (gameObject.tag == col.gameObject.tag) {
        Destroy(col.gameObject);
    }
    else { Destroy(gameObject); }
}

```

Thank you all who helped me out
> -1 votes

---
Tags: c#, gameobject
---


# Question
Title: Programmatically placing objects along Polygon Collider 2D
In my game, I have Tiled "rooms" that were imported with Tiled2Unity. All of these rooms have walls that are defined by Polygon Collider 2D objects. In the event of a cave or dungeon, I'd like to implement torches. Currently, I literally randomly place torches in each room, which is pretty good for lighting, but looks ridiculous.

After the room is added, rather than randomly place torches anywhere, I'd like to have them placed along the inside of the collider. Is there a good way to make this happen?

Edit:

One of my first attempts was to get a list of all of the points in all colliders in a given room after it's instantiation. I was starting with something like this.

```
GameObject _roomGO =
   (GameObject)Instantiate(_room.gameObject, new Vector3 (-6.5f, 6.5f, 0f), Quaternion.identity);

List<PolygonCollider2D> _polyList =
   _roomGO.GetComponentsInChildren<PolygonCollider2D>().ToList();

```

However, this only gets the points from the first collider, whereas I need the points for all colliders in the room GameObject. Additionally, I'm not sure how those points are stored in such a way that I could create a `List` or `Array` of lines, then evaluate those lines to determine which are inside the room (as opposed to along the outside, so nothing in the set \[(x,0),(x,-13),(0,y),(13,y)\].

Once I had a list of lines that weren't part of that set, I could choose a point on the line and drop in a torch.

Edit2 - images:

Edit 3:

Thank to @SP., I've used some of his code as shown here:

```
        if (_torches)
    {
        Transform _roomGOLayer = _roomGO.transform;
        int numTorch = rndObjects.Next(2,4);

        List<PolygonCollider2D> _polyList = _roomGO.GetComponentsInChildren<PolygonCollider2D>().ToList();

        foreach (PolygonCollider2D polCol in _polyList)
        {
            foreach (Vector2 point in polCol.GetPath(0))
            {
                Debug.Log(point.x +" : "+ point.y);//you will be using these values

                GameObject _to = Instantiate(_torch, new Vector2(point.x, point.y), Quaternion.identity) as GameObject;
                _to.transform.parent = _roomGOLayer;
                _to.transform.position = _to.transform.parent.transform.position + new Vector3 (point.x, point.y, 0f);
            }
        }
    }

```

The biggest problem I'm having up front is that \_polyList is only getting the first collider definition. I think if I could solve that, I'd be in good shape.

# Answer
You can get the elements of the paths. Then spawn torch there. Store them as `Vector2`. Very simple implementation below.

```
public GameObject mSphere;
PolygonCollider2D polCol;

void Start ()
{
    polCol = GetComponent<PolygonCollider2D>();

    foreach (Vector2 point in polCol.GetPath(0))//Implemented on outer path only, you will need multiple paths
    {
        Debug.Log(point.x +" : "+ point.y);//you will be using these values

        Instantiate(mSphere, new Vector2(point.x, point.y), Quaternion.identity);
    }
}

```

Result:

If you get the list of colliders, so you have the points of them as well.

Use {(x1+x2)/2, (y1+y2)/2} for determining the midpoint between (x1, y1) and (x2, y2) as well as next points.
> 3 votes

---
Tags: unity
---


title: Unity - Ambient Occlusion artefacts

text:
# Question
Title: Unity - Ambient Occlusion artefacts
When I create two cubes from Unity \> Component menu. And turn on AO the bottom cube is not shaded properly. I mean the upper cube is alright but the bottom cube does not have any shadow present. What am I doing wrong ?

Lighting setup:

Result:

# Answer
Reduce `Indirect Resolution` under Baked GI. Bake with these setup.

Modified upon your setup:

Result:

Also close the corners if possible.
> 2 votes

---
Tags: unity, shaders, global-illumination, ambient-occlusion
---


# Question
Title: clamp a 2D coordinate to fit within an ellipse
I need to clamp a 2D coordinate to fit within an ellipse.

Call of Duty: Modern Warfare 2 does something similar where capture points are translated from a 3D vector in the world to a 2D screen coordinate and then the 2D coordinates are clamped within an ellipse.

When the capture points are in view they're within the bounds of the ellipse.

When they're behind you they are clamped to be within the bounds of the ellipse.

Given a 2D coordinate that could be off screen, etc, what is the math behind clamping it within an ellipse?

# Answer
> 3 votes
Here's a general method to clamp a point \\$A\\$ to the ellipse of center \\$C\\$ and half-dimensions \\$d\\$ (i.e. the ellipse is \\$2d\_x\\$ wide and \\$2d\_y\\$ high):

* \\$B = \frac{(A - C)}{d}\\$ gives you the coordinates of \\$A\\$ in the frame in which the ellipse is the unit circle. The fraction is memberwise division (\\$ \frac{a}{b} = (\frac{a\_x}{b\_x} ; \frac{a\_y}{b\_y})\\$)
* \\$B' = \frac{B}{|B|}\\$ normalizes \\$B\\$: \\$B'\\$ is now on the unit circle.
* \\$B'' = C + B' × d\\$, where **\\$×\\$** is the memberwise product. This brings our clamped point back into the original frame : \\$B''\\$ is \\$A\\$, clamped onto the ellipse.

This method can be greatly simplified if the ellipse is centered (\\$C\\$ disappears), and/or if your frame has the same aspect ratio as your ellipse (\\$d\_x = d\_y\\$, so the scaling isn't necessary).

# Answer
> 0 votes
The equation for an ellipse centered at the origin is just:

$$\bigg( \frac{x ^ 2}{Rx ^ 2}\bigg) + \bigg(\frac{y ^ 2}{Ry ^ 2} \bigg) = 1$$

where:

* Rx is the X-dimension radius; and
* Ry is the y-dimension radius

Combining this with a transformation that maps the relevant ellipse to the origin is straightforward.

Then just replace the *=* sign with a *\<=* to get a test for (inclusive) containment in the ellipse.

---
Tags: opengl, 2d, mathematics, coordinates
---


title: Ray-tracing Moveable Objects

text:
# Question
Title: Ray-tracing Moveable Objects
I am fond of creating graphics and animations using the frameworks on the iOS platform; lately, I discovered that, in order to create better visual designs, those higher-level of frameworks do not provide enough controls to satisfy the needs of creating more advanced-level designs. Hence, I decided to invest my time in studying OpenGL ES.

Whilst doing so, I came across the ray-tracing topic; I have spent quite a bit of time studying the mathematics and topics related to it. And, I have been able to render simple stationary objects (geometrically) using this technique.

In order to learn deeper, I started to toy around with the idea of allowing these objects to have movements based upon user-interactions (I.e., when the user moves the object on the screen with her finger, the corresponding object will spin around or simply move to the respective location based upon the user's touch (on mobile device)).

According to what I have studied thus far on ray-tracing, however, this operation of allowing the objects to move based on user-interactions could be very costly in ray-tracing. To me, for example, it would mean that, if a rendered sphere were to spin around based on user's touch on the screen, I would need to ray-trace the whole sphere for every frames as the sphere spins.

Is my understanding correct here?

My question is, is it possible to perform ray-tracing on objects that are movable; if so, is there another ray-tracing technique specialized especially for this purpose, which could be less costly? Or, is ray-tracing more suitable for rendering only architectural objects, which are usually stationary?

Thank you.

# Answer
> 1 votes
Ray tracing is great for many uses and very interesting but it is a very computationally heavy process. Most of the time when you move an object you are going to have to retrace it, but this is not always the case. If you are not changing the perspective or the camera or the orientation of the object and it's not in shadow then you could keep the already traced version as a display.

Alternatively, you could have a fallback method of rendering for when you are moving the object around if this is not an extremely dynamic scene. For example if it's an adventure game then moving objects around does not usually happen that often so you could fall back onto standard rendering. Then your ray tracing could be done offline ie in a multi-frame process instead of making your whole rendering wait. Then once it's ready you could pop the finished render into the scene.

I did something similar in a project a while back to create icons for a drag and drop inventory and it worked like a charm.

---
Tags: raytracing
---


# Question
Title: Determining how much of a tile is intersected by a ray to help calculate lighting and deal with shadow issues
I'm currently using the following steps for my lighting system

* Calculate all the tiles along the perimeter based on the radius of the light
* Cast a ray from the center of the light to each perimeter tile
* The ray cast returns which cells it intersects
* Each cell is lit based on their distance from the source (light attenuation)
* If a cell is determined to be opaque then the subsequent cells are not lit (hard shadow)

The problem is that in some cases this makes the shadowing looks a bit odd and gives a Peter Pan type of effect where the shadow is not attached to the shadow caster (opaque cell).

For example:

The culprit is highlighted here:

If we take a look at the ray causing the issue we can see that it hardly intersects the cells behind the opaque object but they are still counted as being lit:

The method used for ray traversal is a typical Bresenham line drawing algorithm:

```
    while (true)
    {
        // Do not return cells outside the map bounds
        if (x0 < 0 || x0 >= width || y0 < 0 || y0 >= height)
            break;

        // Add the current cell to the list
        cells.Add(GetCell(x0, y0));

        if (MathExt.AlmostEquals(maxX, maxY, 0.01f))
        {
            // Cannot travel any further in this direction so this is the last cell
            if (x0 == x1 || y0 == y1)
                break;

            maxX += deltaX;
            maxY += deltaY;
            x0 += stepX;
            y0 += stepY;
        }
        else if (maxX < maxY)
        {
            // Cannot travel any further in this direction so this is the last cell
            if (x0 == x1)
                break;

            maxX += deltaX;
            x0 += stepX;
        }
        else
        {
            // Cannot travel any further in this direction so this is the last cell
            if (y0 == y1)
                break;

            maxY += deltaY;
            y0 += stepY;
        }
    }

```

My current line of thinking is to calculate how much of the cell is intersected by the ray and use that to influence the contribution of the lighting, alongside the attenuation.

Therefore, my question is how do I calculate how much of the cell is intersected by the ray?

Alternatively, can anyone suggest a more suitable solution for this issue?

# Answer
> 3 votes
First of all a ray isn't going to help you with this. You will need at least 2 rays.

"How much of a tile a ray intersects" is not really a meaningful question, since the ray will always split a tile it intersects into two parts and then how do you decide which part you want.

Instead you want to know how much of a tile is in between two rays, both of which extend from the sides of an obstacle. That will give you an idea of how well lit a tile should be. But if you are going to do that you might as well just do stencil shadows to begin with.

The basic answer is, you will have to build shadow geometry one way or another. Then you need to calculate how much light each tile gets. You can do it on the CPU like your proposed solution, or you can do it on the GPU which basically turns it into stencil shadows.

# Answer
> 1 votes
I disagree with @Nils Ole Timm, you can use a single ray. (While two rays is another, probably much nicer and robust, implementation.)

What you should use with a single line is to just use the length of the line inside the square.

To do that you could either calculate the exact (floating point) intersections with the square at all four edges and use that.

Or I guess you could use the variable that just counts up and resets regularily in Bresenham's algorithm. Your Bresenham doesn't really look the way I'm used to, I'm referring to D at https://en.wikipedia.org/wiki/Bresenham%27s\_line\_algorithm

# Answer
> 1 votes
I mostly agree with the solution presented by @NiklasJ in that a single ray may be sufficient, but I don't think that only using the length of the line segment in the interior is the correct metric to determine the outcome.

Consider a case where the light ray runs just inside & parallel to the edge of the rectangle. This could produce a relatively long line segment, but you might prefer to reject the intersection due to its glancing nature. If so, I suggest comparing the areas of the sections on either side of the intersecting line.

Calculating the areas isn't too complex, but it is more complex than simply checking the length of the intersection. If performance is a concern, first use @NiklasJ's solution. If the intersection is very small you can reject the hit. If the intersection is very large (say comparable to the hypotenuse), you can accept the hit. If the result is in between & you want to filter out glancing edge cases, resort to comparing the areas on either side of the bisection.

With all this being said, I'll agree with @Nils Ole Timm in that you may get a truer result via shadow geometry; I'm currently using a 3D Bresenham algorithm to determine visibility & have not yet resolved all the undesirable edge cases.

# Answer
> 0 votes
People are overcomplicating, which is easy to do in computational geometry.

All you need to find is the two points of intersection with the circle, which I am sure you can figure out on your own.

From there, calculate the area of the triangle. 1/2 base * height.

That should be a close approximation for most purposes but you can also calculate the other bit.

This remaining area is called a chord. The area formula for a chord is A = 1/2 R2 theta - L/2 (R-h).

O is the center of the circle.

So you can calculate out the exact area. Or you could approximate this by coming up with a constant to multiply by the chord length since this is a pretty small area really.

---
Tags: c#, lighting, tilemap, raycasting
---


# Question
Title: Copy velocity of one object to other object
I have a script to pick up items with a VR controller. I connect the object to the VR controller through a `FixedJoint` on a rigidbody `attachPoint`. When I drop an item through destroying the Joint however it plummets straight down to the ground, no force from the controller is transferred to the released object. Thus I can't throw the object.

I tried it using the `AddForce()` method. `attachPoint`'s velocity is the controller's as it is a child of the controller. Relevant code below.

Can someone help me with transferring the velocity of the controller at the time of release to the object just released?

Thanks!

```
public class PickupCarryRelease : MonoBehaviour {

    public Rigidbody attachPoint;

    FixedJoint joint;
    GameObject obj;
    Collider grabbedObjColl;

    void Update()
    {
        Release();
    }

    void Release()
    {
        var device = SteamVR_Controller.Input((int)trackedObj.index);
        if (canGrab && joint != null && device.GetTouch(SteamVR_Controller.ButtonMask.Trigger))
        {
            var obj = joint.gameObject;
            var rb = obj.GetComponent<Rigidbody>();

            grabbedObjColl.isTrigger = false;
            rb.detectCollisions = true;

            //Transfer velocity

            Destroy(joint);
            rb.AddForce(attachPoint.velocity, ForceMode.Impulse);
            StartCoroutine(GrabDelay());
        }

    }
}

```

# Answer
I will post this answer since this question was resolved by me in the comments above.

In order to get the velocity of the VR controller, you need to use:

```
var device = SteamVR_Controller.Input((int)trackedObj.index);
device.velocity;

```
> 2 votes

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


# Question
Title: Libgdx: move img from one point to another?
I'm trying to make an image move towards another point. I only have the current X/Y and the destination X/Y + Speed.

That's it.

```
public void Draw(SpriteBatch batch, int goalX, int goalY){
    destX = goalX - posX;
    destY = goalY - posY;

    dist = Math.sqrt(destX * destX + destY * destY);
    destX = destX / dist;
    destY = destY / dist;

    posX += destX * this.speed;
    posY += destY * this.speed;

    batch.draw(img, posX, posY);
}

```

This is my code, it kinda moves towards the object, but it moves past the object to a certain distance and then starts spazzing out for some reason.

The other point is also moving, just so you know.

Anybody can help me with this?

# Answer
You have to check if the distance travelled is greater than what remains to travel; if it is, you arrive at your destination on that frame, explicitly set the position instead of 'travelling':

```
public void Draw(SpriteBatch batch, int goalX, int goalY){
    destX = goalX - posX;
    destY = goalY - posY;

    dist = Math.sqrt(destX * destX + destY * destY);
    destX = destX / dist;
    destY = destY / dist;

    travelX = destX * this.speed;
    travelY = destY * this.speed;

    distTravel = Math.sqrt(travelX * travelX + travelY * travelY);

    if ( distTravel > dist )
    {
        posX = destX;
        posY = destY;
    }
    else
    {
        posX += travelX;
        posY += travelY;
    }

    batch.draw(img, posX, posY);
}

```
> 2 votes

# Answer
LibGDX provides actions for `Actors` which make moves like this easy.

If your image is an `Image` class, it extends `Widget` which extends `Actor` so you can easly make him move (even with tons of interpolation types!):

I'll write you an example:

```
public SomeScreen implements Screen{

    Image someImage;

    //optional
    Stage stage;

    public SomeScreen(){
        someImage = new Image(//Load the image);
        someImage.setPosition(0,0); // left down corner of the screen

        float destinationX = Gdx.graphics.getWidth() - someImage.getWidth();
        float destinationY = Gdx.graphics.getHeight() - someImage.getHeight();

        // we move the actor to the destination point in 3 seconds
        someImage.addAction(Actions.moveTo(destinationx, destinationY, 3f));

        // remember that you should add the image to the stage here:
        stage.addActor(image);
    }

    public void draw(SpriteBatch batch, int goalX, int goalY){

        // if you don't have a stage, you should call:
        image.act(Gdx.graphics.getDeltaTime());
        batch.draw(image, image.getX(), image.getY(), image.getWidth(), image.getHeight());

        // if you have a stage (recommended)
        stage.act(delta);
        stage.draw();
    }
}

```
> 1 votes

---
Tags: libgdx, movement
---


# Question
Title: Circular trajectory for sprite in LibGdx
I want four sprites to orbit a single origin point. But if I use like this

```
    sprite_p1_avatar = new Sprite(dummyText);
    sprite_p1_avatar.setPosition(200, 200);
    sprite_p1_avatar.setOrigin(100, 100);

    sprite_p2_avatar = new Sprite(dummyText);
    sprite_p2_avatar.setPosition(300, 300);
    sprite_p2_avatar.setOrigin(100, 100);

    sprite_p3_avatar = new Sprite(dummyText);
    sprite_p3_avatar.setPosition(400, 400);
    sprite_p3_avatar.setOrigin(100, 100);

    sprite_p4_avatar = new Sprite(dummyText);
    sprite_p4_avatar.setPosition(500, 500);
    sprite_p4_avatar.setOrigin(100, 100);

    sprite_p1_avatar.rotate(40 * delta);

    sprite_p1_avatar.draw(batch);

    sprite_p2_avatar.rotate(40 * delta);
    sprite_p2_avatar.draw(batch);

    sprite_p3_avatar.rotate(40 * delta);
    sprite_p3_avatar.draw(batch);

    sprite_p4_avatar.rotate(40 * delta);
    sprite_p4_avatar.draw(batch);

```

the sprite get inverted while revolving, as these sprites are profile pictures of users I want them to stay straight while orbiting at every point. Is there any way to move the sprites along a circular path without rotating.

# Answer
This is rather simple approach. To keep it pointing up, it'd be easier to translate sprites on your own.

* Calculate current angle of your rotation each frame
* Then calculate offset from origin (See this link for maths)
* Add offset to origin and set your position

```
public static Vector2 getCurrentPosition(float degrees, Vector2 origin, float radius) {
    //pre-calculate sin and cos
    float radians = degrees * MathUtils.degreesToRadians;
    float sin = MathUtils.sin(radians);
    float cos = MathUtils.cos(radians);

    float offsetX = cos * radius;
    float offsetY = sin * radius;

    float currentX = origin.x + offsetX;
    float currentY = origin.y + offsetY;

    //return your position or set it here, nevermind,  whatever suits you
}

```
> 1 votes

---
Tags: android, libgdx, sprites
---


# Question
Title: Java Libgdx Attaching Sprite to Box2D Body
So I am working on programming a java 2D platformer for fun on the side and I have a rendered TMX level and a box2d body (just a circle shape) that I am currently using as my player. All the controls work good, but the camera is off center but follows player perfectly. What I am trying to do is to get the sprite to be attached to the body. I am aware they don't work perfectly and that the sprite basically just has to follow the body but can't get it to work.

Right now my sprite displays off the map because it goes to the bottom left corner by default and my map is messed up. I have tried drawing the sprite animation to the x and y from the body position but that isn't working. Here is my code

This is my class and create \**I cut out some stuff that wasn't relevant so don't mind the random declarations\*

```
public class MyGdxGame extends ApplicationAdapter implements InputProcessor {
    Texture img;
    TiledMap tiledMap;
    OrthographicCamera camera;
    TiledMapRenderer tiledMapRenderer;
    SpriteBatch sb;
    Texture texture;
    Player player;
    Sprite sprite;
    static float w,h;

    //Box2D Variables
    World world;
    Box2DDebugRenderer b2dr;

    Animator mario;
    private Hud hud;
    public static final int V_WIDTH = 485;
    public static final int V_HEIGHT = 515;
    private static final int FRAME_COLS = 8;
    private static final int FRAME_ROWS = 1;
    public static final float PPM = 100f;
    public SpriteBatch batch;
    Animation runAnimation;
    Texture runSheet;
    TextureRegion[] runFrames;
    TextureRegion currentFrame;

    float stateTime;

    float sbX = 80;
    float sbY = 12;
    final float timeStamp = 1.0f / 30.0f;

@Override
public void create (){

    GdxNativesLoader.load();
    w = Gdx.graphics.getWidth();
    h = Gdx.graphics.getHeight();

    tiledMap = new TmxMapLoader().load("Level1-1.tmx");
    tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap, 1f / PPM);
    Gdx.input.setInputProcessor(this);

    world = new World(new Vector2(0, -10f), true); //Vector is for gravity
    b2dr = new Box2DDebugRenderer();
    player = new Player(world);
    BodyDef bdef = new BodyDef();
    PolygonShape shape = new PolygonShape();
    FixtureDef fdef = new FixtureDef();
    Body body;
    //Create ground bodies/fixtures
    for(MapObject object : tiledMap.getLayers().get(2).getObjects().getByType(RectangleMapObject.class)){
        Rectangle rect = ((RectangleMapObject) object).getRectangle();

        bdef.type = BodyDef.BodyType.StaticBody;
        bdef.position.set(((rect.getX() + rect.getWidth() / 2) / PPM), ((rect.getY() + rect.getHeight() /2) / PPM));

        body = world.createBody(bdef);
        shape.setAsBox((rect.getWidth() / 2) / PPM, (rect.getHeight() / 2 / PPM));
        fdef.shape = shape;
        body.createFixture(fdef);
    }
    //Create pipe bodies/fixtures
    for(MapObject object : tiledMap.getLayers().get(3).getObjects().getByType(RectangleMapObject.class)){
        Rectangle rect = ((RectangleMapObject) object).getRectangle();

        bdef.type = BodyDef.BodyType.StaticBody;
        bdef.position.set(((rect.getX() + rect.getWidth() / 2) / PPM), ((rect.getY() + rect.getHeight() /2) / PPM));

        body = world.createBody(bdef);
        shape.setAsBox((rect.getWidth() / 2) / PPM, (rect.getHeight() / 2) / PPM);
        fdef.shape = shape;
        body.createFixture(fdef);
    }
    //Create brick bodies/fixtures
    for(MapObject object : tiledMap.getLayers().get(4).getObjects().getByType(RectangleMapObject.class)){
        Rectangle rect = ((RectangleMapObject) object).getRectangle();

        bdef.type = BodyDef.BodyType.StaticBody;
        bdef.position.set(((rect.getX() + rect.getWidth() / 2) / PPM), ((rect.getY() + rect.getHeight() /2) / PPM));

        body = world.createBody(bdef);
        shape.setAsBox((rect.getWidth() /2 / PPM), (rect.getHeight() /2 / PPM));
        fdef.shape = shape;
        body.createFixture(fdef);
    }

    camera = new OrthographicCamera();
    camera.setToOrtho(false, w / PPM, h / PPM);
    camera.update();
    runSheet = new Texture("Squirrel-Run.png");

    TextureRegion[][] tmp = TextureRegion.split(runSheet, runSheet.getWidth()/FRAME_COLS, runSheet.getHeight()/FRAME_ROWS);

    runFrames = new TextureRegion[FRAME_COLS * FRAME_ROWS];
    int index = 0;
    for(int i = 0; i < FRAME_ROWS; i++){
        for(int j = 0; j < FRAME_COLS; j++){
            runFrames[index++] = tmp[i][j];
        }
    }
    runAnimation = new Animation(0.025f, runFrames);
    sb = new SpriteBatch();

    stateTime = 0f;

    hud = new Hud(sb);
    world.step(timeStamp, 6, 2);
}

```

this is my render, update and input methods

```
public void update(){

    camera.update();

}
public void handleInput(){
    if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE))
        player.b2body.applyLinearImpulse(new Vector2(0, 4f), player.b2body.getWorldCenter(), true);

    if(Gdx.input.isKeyPressed(Input.Keys.RIGHT) && player.b2body.getLinearVelocity().x <= 2)
        player.b2body.applyLinearImpulse(new Vector2(0.1f, 0), player.b2body.getWorldCenter(), true);
    if(Gdx.input.isKeyPressed(Input.Keys.LEFT) && player.b2body.getLinearVelocity().x >= -2)
        player.b2body.applyLinearImpulse(new Vector2(-0.1f, 0), player.b2body.getWorldCenter(), true);

}
@Override
public void render (){
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    tiledMapRenderer.render();

    tiledMapRenderer.setView(camera);
    handleInput();

    //Render our box2dDebugLines
    b2dr.render(world, camera.combined);

    world.step(timeStamp, 6, 2);
    camera.position.set(player.b2body.getWorldCenter().x, player.b2body.getWorldCenter().y, 0);
    camera.update();

    stateTime += Gdx.graphics.getDeltaTime();
    currentFrame = runAnimation.getKeyFrame(stateTime, true);

    sb.begin();
    sb.draw(currentFrame, player.b2body.getPosition().x / PPM, player.b2body.getPosition().y / PPM);
    sb.end();
    sb.setProjectionMatrix(hud.stage.getCamera().combined);
    hud.stage.draw();

```

And this is my player class

```
public final class Player {

public int x,y;
public Vector3 position;
public World world;
public com.badlogic.gdx.physics.box2d.Body b2body;

public Player(World world) {
    this.world = world;
    defineSprite();
}
public void defineSprite(){
    BodyDef bdef = new BodyDef();
    bdef.position.set(32 / MyGdxGame.PPM, 32 / MyGdxGame.PPM);
    bdef.type = BodyDef.BodyType.DynamicBody;
    b2body = world.createBody(bdef);

    FixtureDef fdef = new FixtureDef();
    CircleShape shape = new CircleShape();
    shape.setRadius(5 / MyGdxGame.PPM);

    fdef.shape = shape;
    b2body.createFixture(fdef);

}

public float getX() {
    return position.x;
}
public float getY() {
    return position.y;
}
public Vector3 getPosition() {
    return position;
}

public float getWidth() {
    return 32 / MyGdxGame.PPM;
}

public float getHeight() {
    return 32 / MyGdxGame.PPM;
}

}

```

I know my code is jumbled I am new to programming, I will clean up with separate classes once I get this working. I was looking into .setUserData but I don't know what else i need to put for this. Can anyone point me in the right direction of my camera/attaching the sprite to the body? Thanks

# Answer
Two (simple) solutions could look something like this:

---

## Give the player class a Sprite (best).

```
// In the player class, give the player a Sprite
private Sprite sprite = new Sprite(new Texture("your/texture/location.png"));

// Then we can add a simple render method to our player class.
public void render(SpriteBatch batch) {
    // First we position and rotate the sprite correctly
    int posX = b2Body.position.x * MyGdxGame.PPM;
    int posY = b2Body.position.y * MyGdxGame.PPM;
    float rotation = Math.toDegrees(b2Body.getAngle());
    sprite.setPosition(x, y);
    sprite.setRotation(rotation);

    // Then we simply draw it as a normal sprite.
    sprite.draw(batch);
}

// Then in your render method you can replace this
sb.draw(currentFrame, player.b2body.getPosition().x / PPM, player.b2body.getPosition().y / PPM);

// with this
player.render(sb);

```

---

## Attach a Sprite as user data to the body.

```
// Same as above, give the player class a sprite.
// Then in your defineSprite() method add this sprite to your body's user data.
b2Body.setUserData(sprite);

// Remember to position and rotate your sprite like the previous example.

// Then in your render method you can replace this
sb.draw(currentFrame, player.b2body.getPosition().x / PPM, player.b2body.getPosition().y / PPM);

// With this. This might throw a warning in your IDE we're
// that doing an unchecked / unsafe cast. But since we know that our
// body's user data will always be a Sprite we can ignore it for now.
((Sprite) player.b2Body.getUserData()).draw(sb);

```

Remember to dispose of all textures you use when you close the game! You can dispose of a Sprite's texture like this `sprite.getTexture().dispose();`.
> 4 votes

---
Tags: java, libgdx, sprites, box2d, platformer
---


title: Game Input for Single Actions

text:
# Question
Title: Game Input for Single Actions
So I'm not 100% sure what you would call this type of keypress, but it is essentially a `keyTyped` event but in reverse order. Instead of being triggered when the button is released, it is triggered when the button is first pressed, but can't be triggered again until the button is released and pressed again.

Right now I have events for `buttonDown` and `buttonUp` and I also have two `HashMap`s to keep track of the `currentInput` and `previousInput` of each action in the game (jumping, moving, crouching, etc...) How can I provide a function that when called returns true for this type of button push?

# Answer
> 1 votes
You are almost there : you need to detect whether the key has *just* been pressed. So it is currently down, but wasn't an instant ago, which is easy to test since you have both states.

```
bool pressed(Action action) {
    return !previousInput[action] && currentInput[action];
}

```

# Answer
> 1 votes
I suggest doing the following:

1. Create an integer variable.
2. Set it to zero if the current state is `up`.
3. Increment it if the current state is `down`.
4. Only activate the desired method when the value is zero and the state is down. Alternatively, if you increment prior to checking, only activate if and when the value is 1. Good luck!

---
Tags: java, events
---


title: Timer in turn based game

text:
# Question
Title: Timer in turn based game
I'm writing a small turn-based game using libgdx. How to make a timer on the player turn to make it work even when the game loses focus??

Or maybe there are some other ways to do it???

# Answer
When your Android app is in the background, you have no guarantee that the OS will not close it so that another app can have its resources.

Here are two options:

1. Android will notify your app of some events in it's lifecycle so you will know that your app is going into the background (you'll probably want to use `onPause` and `onResume`). Instead of creating a timer when a player's turn starts, you could store the timestamp when the player's turn starts. When the Android lifecycle notifies you that your app is going into the background, save this timestamp to a file in case your app is closed. Once your app is resumed, check the current time against the saved timestamp and simulate the game steps until it is caught up.
2. Create an Android service. Android services are just like windows services, except, in my experience, they are a bit trickier to write. The service would be the master timekeeper and you app would have to communicate with it. Once started, an Android service will keep running, meaning that once you are not using the service, you are responsible to shut it down.
> 0 votes

---
Tags: android, libgdx, google-play-services
---


# Question
Title: What's the use of bones in a 2D skeletal animation?
I'm trying to implement a renderer using a scene graph and skeletal animation. As far as I know the bones in a skeletal animation just represent a connection between two joints. However, if a Joint knows its parent- and child-Joints what would you even need bones for?

Also, why would you need a separate class, Skeleton to represent a 2D entity (whatsoever) when the Skeleton is just an array of joints? Isn't that just a waste of memory? Am I missing something?

# Answer
> 8 votes
Without knowing the details of your particular implementation it is hard to say, but in general a "bone" is just another term for either a "joint" (a 3D position that will be animated) or a "joint plus reference to the parent joint."

This

> However, if a Joint knows its parent- and child-Joints what would you even need bones for?

implies to me that you're using the latter definition in your system (have joints which know their parent) and thus "bone" is just another term for what you already have.

> Also, why would you need a separate class, Skeleton to represent a 2D entity (whatsoever) when the Skeleton is just an array of joints?

It sounds like you're asking why you'd want to have

```
struct Skeleton {
  Array<Joint> bones;
};

```

instead of

```
Array<Joint> skeleton;

```

If that's the case, it's generally for the same reason you'd want to have a structure for a 3D vector instead of passing three floats everywhere. It encapsulates the logical concept you're trying to express, improving readability to some degree and providing you a place to hook various related functionality (such as, perhaps, updating all the joints in the skeleton with new positions based on some input animation data).

---
Tags: java, 2d, skeletal-animation, bones
---


title: Libgdx FPS drop drawing alot of text

text:
# Question
Title: Libgdx FPS drop drawing alot of text
i'm drawing text above monster head and it's fine. But when there is to many monsters and their name gets render every second cause fps go down. When i disable the font drawing, then the fps is fine. Any idéa how to tackle this perfomence issue?

Thanks.

# Answer
> 3 votes
Every time you draw something actually you are sending data from CPU to GPU. its the slow part of drawing somethings.

So if you have unique names for each monster only thing you can do is drawing texts via opengl but i dont know if its possible or not in libgdx.

If you are using same text for all monsters so its quite possible.

1. Create pixmap
2. Load font texture and data
3. Write your string to pixmap
4. Convert pixmap to texture
5. Create sprite from texture
6. Change position of sprite for each monster position.
7. So when you drawing font you wont send data to GPU just going to change position of texture already exists on GPU.

Here is code for almost of them:

```
// load the background into a pixmap
Pixmap tile = new Pixmap(Gdx.files.getFileHandle("someFile.png", FileType.Internal));
// load the font
FileHandle handle=Gdx.files.getFileHandle("someFont.fnt",FileType.Internal);
BitmapFont font = new BitmapFont(handle);
// get the glypth info
BitmapFontData data = font.getData();
Pixmap fontPixmap = new Pixmap(Gdx.files.internal(data.imagePaths[0]));
 Glyph glyph = data.getGlyph(getLetterToDraw().charAt(0));
// draw the character onto our base pixmap
//You can use method for draw string to pixmap char by char.
tile.drawPixmap(fontPixmap, (TILE_WIDTH - glyph.width) / 2, (TILE_HEIGHT - glyph.height) / 2,glyph.srcX, glyph.srcY, glyph.width, glyph.height);
// save this as a new texture
sprite = new Sprite(new Texture(tile));

```

---
Tags: libgdx
---


title: cylindrical coordinate point in origin

text:
# Question
Title: cylindrical coordinate point in origin
I have a camera which has the following attributes:

* pos (position of the camera in the scene)
* look(either direction in which camera will face, or target vector)
* up vector( y axis)

I am using cylindrical coordinates system for moving camera around centre of scene. my question is 'how can I find look vector of the camera in a such a way that it will be pointing out in the origin of the scene under 45 degree?'.

According to this thread there is not such a way.

> And you can never look directly down at the focal point, no matter how high up you go.

P.S: I need somehow to get look vector if it's possible.

Thank you for you attention

# Answer
Yes, you are right! It is only possible if `height == radius`

Further Information - let there be horizontal angle `t Degree` of your green sector in image above.

```
camPos( x = r * cos(t * pi/180 ), y = sin(t * pi/180 ), z=z)

```

multiplying with `pi/180` makes it radian, so be careful.

Looking vector:

```
[x,y,z] = [focus.x - camPos.x, focus.y - camPos.y, focus.z - camPos.z]

```
> 0 votes

---
Tags: opengl, mathematics
---