# Question
Title: How to resolve collision between a dynamic AABB and static AABB?
I wanted to ask, how do I resolve collision between 2 cubes - in my case I want to push a moving / dynamic cube (used for the player) out of another static cube (used for the floor or objects in the scene)?

I tried various things, but in the end I don't know how to make the dynamic cube stay smoothly on top of the floor or not able to go through other objects (everything AABB vs AABB for now).

Below are the most important snippets to understand my problem better.

From PhysicsEngine.cpp

```
IntersectData intersectData =
                m_objects[i]->getCollider().intersect(
                    m_objects[j]->getCollider());

                // if they intersect, reverse movement to have solid box collisions.
                if(intersectData.getDoesIntersect())
                {
                    // revert movement (later push?) collision response.
                    glm::vec3 diff = m_objects[i]->getPosition() - m_objects[j]->getPosition();
                    glm::vec3 sep = glm::normalize(intersectData.getDirection()) * diff;
                    // std::cout << "Separation between: " << m_objects[i]->

                    // if testCollisionResponse - push back.
                    if (m_objects[i]->testCollisionResponse)
                    {
                        m_objects[i]->setPosition(m_objects[i]->getPosition() + sep);
                        // m_objects[i]->setVelocity(glm::vec3(0.0));
                        // m_objects[i]->testGravity = false;
                        // m_objects[i]->testGravity = false;
                    }
                    else if (m_objects[j]->testCollisionResponse)
                    {
                        m_objects[j]->setPosition(m_objects[j]->getPosition() - sep);
                        // m_objects[j]->setVelocity(glm::vec3(0.0));
                        // m_objects[j]->testGravity = false;
                    }
                }

```

AABB.cpp

```
uGE::IntersectData uGE::AABB::intersectAABB(const AABB& other) const

```

{ glm::vec3 distances1 = other.getMinExtents() - m\_maxExtents;

```
// test the other way around.
glm::vec3 distances2 = m_minExtents - other.getMaxExtents();

// pick the biggest values between the vectors on each axis.
glm::vec3 distancesOnEachAxis = glm::max(distances1, distances2);

float maxDistance = distancesOnEachAxis[0];
for (int i = 0; i < 3; i++)
{
    if (distancesOnEachAxis[i] > maxDistance)
    {
        maxDistance = distancesOnEachAxis[i];
    }
}

return uGE::IntersectData(maxDistance < 0, distancesOnEachAxis);

```

}

IntersectData.hpp

```
class IntersectData

```

{ public: IntersectData(const bool doesIntersect, const glm::vec3 direction) : m\_doesIntersect(doesIntersect), m\_direction(direction) {}

```
inline bool getDoesIntersect() const { return m_doesIntersect; }
inline float getDistance() const { return glm::length(m_direction); }
inline const glm::vec3 getDirection() const { return m_direction; }

```

private: const bool m\_doesIntersect; const glm::vec3 m\_direction; };

These are the project files (if you want to see more): https://github.com/BigThinker/CPPGame/blob/master/uGE/uGE/Physics/PhysicsEngine.cpp

All the best, Aldo

# Answer
I think you may need to look further than simple collision detection to make this happen. Due to the discrete nature of a simulation such as this, it's hard to achieve a smooth "flooring" of one object onto a surface as it will constantly collide, then be adjusted, then collide, then be adjusted again.

One approach in projects I've used in the past is to manage this via a set of different phyics "states" which an object could be in. Examples might be: `Grounded, Airbourne` etc.

In this way, you run a different set of phyics rules depending on the state your object is currently in, and use hitbox detection differently in each, and to help transition between the two.

For example, imagine the case of a player character who appears in midair, above the floor. THe inital state is set to `Airbourne` and the physics system applies gravity to the character to start them falling.

Eventually, the AABB hitbox detection system detects a collision between the player physics hitbox and the floor hitbox. At this point the physics state transitions to `Grounded` and the position is adjusted to ensure there is no collision (as you discuss).

Now, the physics system knows the player is grounded, so can use different techniques to track the floor, rather than relying on the hitbox. Depending on your game, you might have a defined "floor" plane which you can query the height of at the current location. You might be able to ray-cast downwards (a short distance) to ensure you are still near the ground, and then transition back to 'Airbourne' when not.

There are many approaches to this, but the principal is that simple hitboxes are probably not sufficient for "smoothly" adhering one object to another where movement is possible. Use them to detect collisions, and use that information to inform transitions in your physics system to control character movement.
> 3 votes

# Answer
Optional approach: I read through Game Physics Engine Development by Ian Millington to find out that before he resolves the impulse (velocity) and interpenetration, he removes the change in velocity by gravity like so:

```
// resting contact implementation.
    // what is the velocity due to acceleration only?
    glm::vec3 velocityDueAcc = particle[0]->getAcceleration();

    // separation velocity due to acceleration (i.e. gravity)
    // contact normal is the normalized vector between 2 objects's positions.
    // duration is the frame duration (delta time).
    float sepVelocityDueAcc = glm::dot(velocityDueAcc, contactNormal) * duration;

        // if there's separation velocity from acceleration,
        // remove it from the new separation velocity.
        // (turn back the movement from y acceleration before resolving v and p).
        if (sepVelocityDueAcc < 0)
        {
            newSepVelocity += restitution * sepVelocityDueAcc;

            // make sure there wasn't removed more than there
            // was to remove.
            if (newSepVelocity < 0) newSepVelocity = 0;
        }
    // ...
    // use newSepVelocity to resolve velocity.

```

Kind of an ad hoc approach to solving this problem, but it's working well so far.
> 0 votes

---
Tags: c++, collision-detection, aabb, response
---


# Question
Title: Unity3d iOS build - where are the textures?
First time building and running my Unity3D app on my iPhone and it appears that all the textures are missing. Everything is just a solid block of whatever color I made it. When running in Unity I see everything correctly. See images below.

To complicate things I'm using custom shaders, and all the objects are custom procedural meshes. Quads that I build in script. If I switch the paper backplate shader to a built in shader I still only see white on the iPhone.

So I suspect that somehow the textures just aren't making it to the iOS project. When I look in the iOS project I can't find any textures. Where would they be in the iOS project? For example in Xcode under Build Phases \> Copy Bundle Resources the only thing there is the Images.xcassets, which only contains the splash screens and icons.

Surely I'm missing something simple.

I tried renaming the folder where I keep my textures to "Textures". Also my textures are not built in to the shader but added programmatically like this:

```
void Awake ()
{
    meshFilterComponent = GetComponent<MeshFilter>();
    Material material = GetComponent<MeshRenderer>().material;
    material.SetTexture(0, paperTexture);
    material.color = new Vector4(1f, 1f, 1f, 1f);
}

```

Where paperTexture is set up in the GameObject to point to the correct texture. Is there any way to force a texture to be part of a build? Let's say that you swap out textures in code, like swapping themes, how would you make sure they're all there to be loaded as needed?

Running On iPhone:

Running In Unity3D:

# Answer
I fixed it by changing this:

```
material.SetTexture(0, paperTexture);

```

to this:

```
material.SetTexture("_MainTex", paperTexture);

```

I don't know why the first one worked fine in the unity window but not on the phone. But that's what fixed it. For some reason the more explicit assignment works better. But now everything is rendering properly on the device.
> 1 votes

---
Tags: unity, textures, ios, xcode
---


# Question
Title: Relation between "Run in background" setting and OnApplicationPause method
I'm working on a game for mobile platforms (Android at the moment, in the future it should be available for iOS and WinPhone) and I want to trigger a certain method when the game is un-paused. For this I'm trying to use OnApplicationPause(bool paused) method (when the "paused" variable is false), but the process is not working as expected. These are my questions:

* In the player settings, does the "Run in background" setting influence the build (since this setting can be found only in Web player/Desktop build tabs, and I'm creating an Android build).
* The problem that we started to experience is that when the game is paused, it crashes and the player has to restart the game. Is this connected to the "Run in background" setting?
* What is the relation between "Run in background" and OnApplicationPause - will the OnApplicationPause be called if the "Run in background" is checked?
* What is the difference between OnApplicationPause and OnApplicationFocus (meaning, which actions change the focus and which will pause the game)?

The code that I'm trying to execute at the moment is fairly simple:

```
void OnApplicationPause(bool paused)
{
  if(!paused) AddCoins( x => PlayerPrefs.SetInt("CoinCount", PlayerPrefs.GetInt("CoinCount")+x));
}

```

The idea of this code is to add a certain number of coins if the player watches an advert (the number of coins is calculated by the ad provider).

Thanks in advance

# Answer
> 3 votes
**OnApplicationPause(bool state)** is called when the user pauses and unpauses the game, normally by hitting the Pause button found in your game (which you need to implement the functionality for - by setting `Time.timeScale = 0`).

Sometimes it's called when the application is put in (or comes back from) the background too (user hits Home button for example). But this behavior differs on each platform and you cannot safely rely on it.

**OnApplicationFocus(bool state)** is called when the app goes into (or comes from) background, usually because the user hits the Home button, and/or switches to another application. This behavior should be consistent on all the platforms.

In order to be safe I believe it's best to implement both functions.

* If the state is false (the application goes into the background) you should pause the game - `Time.timeScale = 0`
* If the state is true (the application comes back to foreground) you should unpause the game - `Time.timeScale = 1`

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


title: Real-Time Terrain Deformation

text:
# Question
Title: Real-Time Terrain Deformation
I can't really find anything at all on this topic. There's a bunch of YouTube videos that show people doing it, but there aren't any articles that I can find explaining the mechanics of it. In my game, terrain is loaded from a .RAW heightmap, and saved to a .RAW heightmap. But the player will be able to modify the terrain. I don't really understand his this terrain deformation works, but so far, I've only created things using vertex buffers which as far as I know can't be changed efficiently. Here and there I've read a few things about GPU tessellation and compute shaders. I understand tessellation and I can do that, but there's also very little I can find about compute shaders.

Are there any good books or websites that explain these things in detail? I'm not really looking for tutorials, because they tend to be pretty specific. But I really just want anything to bring me out of the dark on this subject.

# Answer
Forget about tessellation and compute shaders. You simply want to maintain a system copy of the terrain and send it (or parts of it) to the GPU every frame. Yes it's slow, but it ain't that slow :)

The trick is to make the section your updating small enough to not bog down the computer. So you don't want to be updating a terrain 1000x1000 tiles. Use chunks of terrain, I use 16x16 tile chunks with 4 tri's per tile, indexed. I can update a terrain chunk in real time no problems.

I was going to suggest a dynamic vertex buffer, but you don't even need that.. here's the code i use to update geometry, just use the default resource usage :

```
    public void SendToBuffer()
    {
        DataStream data = new DataStream(vertices, true, true);
        DataBox dataBox = new DataBox(0, 0, data);
        device11.ImmediateContext.UpdateSubresource(dataBox, VertexBuffer, 0);
    }

```

you just have to provide the vertex data, which you've edited during the frame. Maybe even read about dynamic buffers, they might give you even better performance, but I don't know about that yet.

edit : Just to clarify, this is SlimDX (DX11) code, so it should translate easily to straight DX11 code.

edit2 : And just to answer one of your questions above, you can also have flat geometry and use the vertex shader to shape your terrain, but you still need to get the height data in to your shader. So you can avoid sending new geometry in, but then you have to send a height map in. So you are still updating gfx resources. Which is faster depends upon your vertex and height map formats.. importantly, their data sizes. In my case, the terrain only has Position & Normal, so it's not too large. My UV's are derived from position. And I think by updating the vertex buffer itself, then it's done, and you've got your vertex heights precalculated, rather than having to sample from a heightmap, which does have a cost.
> 3 votes

# Answer
I would highly recommend that you look into "Dual contour" Mapping using "Voxel space"... This method will allow you to make deformable terrain on the fly.

Another method you might run into is called "Marching Cubes" but stay away from this as it will cost you a lot of time, jsut to learn that Dual contouring is a superior method anyway, and so I suggest you focus on that (Dual cont.) from the start.

At the core (of these dynamic landscapes) is a process that designates the density of space in a 3d grid...(this would be the Voxel side of things; Voxel refers to Volumed pixels and in this implementation the "volume" refers to density)
By altering these density values, you can recreate a chunk of landscape on the fly... This means, digging tunnels, making caves, or creating mountains etc.

It's going to take a lot of research to completely understand, but once you achieve it, you will never have need of another terrain method again. This is potentially a lifetime investment for endless possibilities in 3d terrain.

This (below) is a good place to start but be prepared for having more questions... http://www.frankpetterson.com/publications/dualcontour/dualcontour.pdf
> 2 votes

---
Tags: directx11, terrain
---


title: How can I do sprite batching in SFML?

text:
# Question
Title: How can I do sprite batching in SFML?
I'm new to game dev and using SFML. I need to use lots of sprites at the same time, so I will probably need sprite batching.

I know that sprite batching is used to draw multiple sprites with a single drawcall, but I have no idea on how it works or how to do it.

How does sprite batching work? (An SFML example would be appreciated.)

# Answer
This usually depends. Are the sprites static? If they are, you could use a Vertex Array for storing all of your static geometry and such. I believe there is an example of this in the SFML tutorials, under Vertex Arrays. This is a great way to store maps, but it isn't always suitable for moving sprites, like the player sprite.

http://www.sfml-dev.org/tutorials/2.2/graphics-vertex-array.php
> 1 votes

---
Tags: c++, sfml, spritebatch
---


# Question
Title: Do SpriteBuilder's Smart Sprite Sheet need to be loaded to memory?
When I create an Smart Sprite Sheet Folder using SpriteBuilder and publish it, must I load that SpriteSheet into memory "FrameCache" with code or does SpriteBuilder do this automatically (so I just have to access any image inside of SpriteSheet?)

# Answer
> 1 votes
As far as I know, whenever you make a sprite using any spritesheet, that spritesheet will be loaded automatically. So you don't have to load anything.

---
Tags: graphics, cocos2d, memory
---


# Question
Title: How can I retain the soundtrack state across levels to have continuous play?
Suppose I have two levels. I want the same soundtrack to play on both of them.

At the moment I have an audio source in each level, playing the soundtrack. However, when you move from one level to the other, the soundtrack will of course restart over (because it's a different audio source).

How can I "resume" the soundtrack? Or rather, how can I retain the soundtrack state across levels to have continuous play?

# Answer
> 12 votes
Put the audio source that's playing your music on an object that you've marked as DontDestroyOnLoad

---
Tags: unity
---


title: Bukkit shoot tnt & help with vectors

text:
# Question
Title: Bukkit shoot tnt & help with vectors
I want to shoot a piece of tnt from the players face and then let it explode when it hits the target block.

```
        if (cmd.getName().equalsIgnoreCase("cannon")) {
        if(!perrmissionCheck(sender, "Needs.cannon", "cannon")){
            return true;
        }
        if (!(sender instanceof Player)){
            sender.sendMessage(nameC+"You must be a player to preform this command.");
            return true;
        }
        Block block = ((Player) sender).getTargetBlock(null, 50);
        Location location = ((Player) sender).getLocation();
        //float power = 4;
        //if (args.length == 1){
            //power = Float.parseFloat(args[0]);
        //}
        sender.sendMessage(name+"BOOM!");
        double x = block.getX();
        double y = block.getY();
        double z = block.getZ();
        TNTPrimed tnt = (TNTPrimed) ((Player)sender).getWorld().spawn(location, TNTPrimed.class);
        Vector v = new Vector(x, y, z);
        tnt.setVelocity(v);
        //block.getWorld().createExplosion(location, power);
        //block.getWorld().spawn(tntLoc, TNTPrimed.class);
        return true;
    }

```

This kinda just ramdomly throws the tnt and then exploads i want to get where the player is looking and then shoot it that way if someone could also describe how the args work for new Vector(arg0, arg1, arg2) i would appreciate it...

Thanks any help is great

***EDIT*** I relize this is really old but i wanted to share how I did it,

```
    int v = 2;

    if (args.length > 1){
        v = Integer.parseInt(args[0]);
    }

    final Vector direction = user.getEyeLocation().getDirection().multiply(v);

    TNTPrimed tnt = user.getWorld().spawn(user.getEyeLocation().add(direction.getX(), direction.getY(), direction.getZ()), TNTPrimed.class);

    tnt.setVelocity(direction);

    user.sendMessage(name + "Boom!");
    plugin.inGameMsg.msgAdmins(plugin.chatDark_AQUA + user.getName() + plugin.chatGray + " used cannon command!");
    return true;

```

this sends the tnt right where the player is looking

# Answer
> 6 votes
The three arguments taken by Vector are its (x, y, z) components. Here's a visual representation of a Vector in 3D space:

A vector can be used to store either a displacement (e.g. movement) or a position. In this case since you're passing the vector to `setVelocity()` it's a displacement - it specifies in which direction the TNT will be *moving*.

But it's probably not working because your Vector is currently holding the *position* of the target block in the world, and what you want is the *direction* the player is facing.

Try to see in the Player class if there's already a way to get a Vector representing the way it's facing. Otherwise you'd need to calculate one from the player's rotation values.

# Answer
> 0 votes
I know this is an old question, but here is the answer for someone else stumbling over this problem. :)

To get the Vector for the direction of the head you have to use,

```
player.getEyeLocation().getDirection()

```

Here is a working example of the code, you may have to play around with the multiplier to get the desired result.

I also rewrote some of the chatcolors to make it work for me.

```
// Get the player and the location of the eyes (head)
Player player = (Player) sender;
Location location = player.getEyeLocation();

// Send the player a message
sender.sendMessage(ChatColor.DARK_AQUA+"BOOM!");

// Prime a tnt and place it at the location of players head
TNTPrimed tnt = (TNTPrimed) player.getWorld().spawn(location, TNTPrimed.class);
// mulitiply the direction from the location by 2 and store it as vector
Vector v = location.getDirection().multiply(2);
// Apply the vector to the primed tnt
tnt.setVelocity(v);

```

---
Tags: java, vector, minecraft-modding
---


# Question
Title: What are the advantages of tangent space shading/lighting, and what about attenuation?
In several topics here it was suggested by people that doing lighting in tangent space is better than doing it in world space. Right now I am doing it in camera space, but it's really similar to world space. My question is, why would tangent space be a better choice for this (I am using normal maps if it matters)? Secondly, when going from model space to world space and vice-versa, a scale is applied. This produces a problem when it comes to attenuated light, because the distances are quite different than in world space, which is where my light positions are. How would I deal with this? Thanks in advance

EDIT: Attenuation problem illustrated

# Answer
> 2 votes
I'm not an expert about it but I'll try to explain.

When you compute per pixel lighting in camera space, you transform your normal map from tangent space to camera space. The idea of working in tangent space is to transform the camera and lights to tangent space then perform lighting computations. So instead of transforming normals from your normal map to camera space, you transform other objects to tangent space.

You can perform this transformation in the vertex shader once per face, then you do not need to transform your normals.

Lets consider an example where we work in tangent space and we want to draw a quad that uses a 256x256 normal map (all texels are drawn). In a forward renderer we will transform the lights and the camera to tangent space, lets say 5 objects, and we do it in the vertex shader (once per face), so we do not have to transform the 256x256 normals (they are already in tangent space).

*What's the catch ?* It works well in a simple forward renderer but wont work with a deferred one. In a deferred renderer you would perform the camera and light transformation in the fragment shader which would be overkill. And if you're interested in clustered rendering it wont work in both forward and deferred, because you get a per pixel list of lights.

For attenuation it does not matter, as long as you are in the same space computations are the same.

---
Tags: opengl, glsl, lighting, shading, spaces
---


# Question
Title: Adding movement to a text-based rpg battle
**Outline**

I have the bones of a text-based RPG - the player can progress through a branching storyline and activate some simple events (recieivng/giving/trading items).

As I am designing the battle system (turn-based obviously) I decided it would be nice to have the player be able to "move" during battle - i.e. a heavy armour clad warrior would charge straight up to the foe but the ranger should pick his foes off from a distance and try to move to a better vantage point as the enemy approaches.

**Main question**

Rather than just giving the fleet of foot character a higher probability to dodge an attack (to compensate their lower defence) I wanted to give them the option to move to different points within the area of battle (jump on top of a rock, climb into that tree, etc) to make it more tactical but have become stumped.

Can anyone suggest a way to approach this (pseudo code would be nice)?

I am using C++ to write the program, if anyone wants to know.

# Answer
> 3 votes
You could define how these would affect the character and add flavor text. If you group them into something like biomes, you can randomly select a few at a time for each battle depending on where the battle takes place.

For example, if you has just two attributes - Offense and Defense:

```
"Rocky Biome" : {
    "Rock : {
        "Take cover behind rock" : {
            Defense : 10,
            Offense : -15,
            OnEnter : "%s takes cover behind a rock",
            OnLeave : "%s leaves their rocky cover"
        }

        "Climb on top of rock" : {
            Defense : -5,
            Offense : 10
        }
    }
}
"Forest Biome" : {
    "Tree" : {
        "Climb up tree" : {
            Defense : 5,
            Offense : -5
        }
        "Hide behind tree" : {
            Defense : 10,
            Offense : -10
        }
    }
}

```

Then you'd just display these as an extension of a "Move" option.

```
> Move
Where to move?
1. Take cover behind rock
2. Climb on top of rock
3. Climb up tree
4. Hide behind tree
> 3
So-and-so climbs up a tree

```

If you ever wanted to add graphics, you'd just attach some more information to each definition:

```
    "Rock : {
        Image : "BigRock.png",

        "Take cover behind rock" : {
            Defense : 10,
            Offense : -15,
            SetCharacterOffset : {-32,0}
        }

        "Climb on top of rock" : {
            Defense : -5,
            Offense : 10,
            SetCharacterOffset : {0,64}
        }
    }

```

---
Tags: movement, rpg, text-based, combat
---


# Question
Title: Showing keyboard on SKScene and performing action on a sprite node based on key tapped
I am trying to learn SpriteKit and play with some simple sample apps.

Currently I am trying to achieve below things:

1. Show keyboard over SKScene
2. If user taps 'A', perform some action on a sprite node, if user taps 'B' perform some other action on other sprite nodes

I tried to google 'Showing keyboard over SKScene' but could not get any suitable answer :(

Any clues or suggestions?

# Answer
I think your should implement `UIKeyInput` protocol for your relevant view, set the view's `canBecomeFirstResponder` to `true`. When you need the keyboard, just call

```
view.becomeFirstResponder

```
> 1 votes

---
Tags: ios, spritekit
---


# Question
Title: How to resolse collision between moving and static AABB?
What I have is a map represented as list of Rectangles and player's rectangle. Also I have function to determine depth of the collision: Point TestAABBAABB(Rectangle a, Rectangle b) { Point mt = new Point();

```
    double rcx = Math.abs(a.getCenterX() - b.getCenterX());
    double rx = (a.width / 2 + b.width / 2);
    if (rcx > rx) {
        return new Point();
    }
    double rcy = Math.abs(a.getCenterY() - b.getCenterY());
    double ry = (a.height / 2 + b.height / 2);
    if (rcy > ry) {
        return new Point();
    }
    double overlap_x = rx - rcx;
    double overlap_y = ry - rcy;

    mt.x = 0;
    mt.y = 0;
    //this is the line
    if (overlap_x < overlap_y) {
        mt.x = (int) overlap_x;
        if (a.getCenterX() < b.getCenterX()) {
            mt.x = -mt.x;
        }
    } else {
        mt.y = (int) overlap_y;
        if (a.getCenterY() < b.getCenterY()) {
            mt.y = -mt.y;
        }
    }
    return mt;
}

```

It works fine if a player jumps "inside" the width of the wall, far from edges. //tail representation But if player tries to jump near an edge, he moves through the wall and to the side as a result of non-zero X penetration depth of collision.

How do I avoid this situation so player slides under platform instead of getting pushed left or right and without having to set vx or vy to zero?

# Answer
> 1 votes
A simple approach might be to first resolve the movement in the X axis and after that in the Y axis. This way you'll always know which component of the movement caused the collision, and you can resolve the collision for that component without even having to touch the other one. For instance:

This will make sure we don't pull movement out of nowhere. Keep in mind that this works best for small steps because of the following:

I don't know if this is appropriate to the way you're doing things, but I hope it helps.

---
Tags: java, collision-resolution, aabb
---


# Question
Title: How does one write a wrapper for a game server?
From what I gathered, wrappers mimic the game server in question, receiving packets from client and sending them to the server (and vice versa). It acts like a bridge between the client and server, allowing data to flow and modifying/reading it as it travels through it.

Am I right in how wrappers work? What is the general gist of them? How would one go about writing one?

I plan to write one for Starbound in Java, using https://github.com/StarryPy/StarryPy as a reference to the packets.

# Answer
> 1 votes
Yes, you'd essentially create a bridge - no wrapper - but that's terminology.

* The basic idea is to use two network connections.
* You've got one listen port that will act to the actual game as if it was the actual game server.
* The bridge will also establish a connection to the real server and pretend to be the actual game client.
* The rest is pretty simplistic: You pass through packages:
    + Stuff sent by the game client is passed to the game server.
    + Stuff sent by the game server is passed to the game client.

As a suggestion, start easy. Write a simple pass through bridge that works with any simple protocol. For example, IRC or HTTP.

Read the incoming data on one end, send it out on the other end, and possibly print it to a console window.

Once your "http proxy" works, you should be able to use it for Starbound or any other game with some minor modifications.

---
Tags: java, software-engineering, multiplayer, server, client
---


# Question
Title: atan2 : inversed result? (angle 180 is on the right side, angle 0 on the left side)
the result of the angle between my touch and the middle,bottom of the screen gives me 180 when the touch is on the right side of the screen, and 0 when it is on the left. I don't understand why...

```
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
    let refPoint = CGPointMake(self.frame.size.width/2, self.frame.size.height)
    let anyTouch: UITouch = touches.anyObject() as UITouch
    let touch = anyTouch.locationInView(self.view!)

    //180 is inversed? 180 is when touch is on the right side...
    let dy = (refPoint.y - touch.y) //opposite
    let dx = (refPoint.x - touch.x) //adjacent

    let rad = atan2(dy, dx)
    let angle = rad * 180 / CGFloat(M_PI)
    println("angle : \(angle) ")
}

```

Would someone know how to solve this?

Thanks

# Answer
You're not taking into account the inverted Y axis in comparison to the normal X axis in most (maybe all?) programming languages. The top left corner of the screen is (0, 0), and is positive in the right and down directions.

So if the bottom middle of your screen is, for example, (300, 400), and you click at (0, 400), then your triangle will be a first quadrant triangle instead of the second quadrant triangle you expected.

let dy = (refPoint.y - touch.y) --\> let dy = (400 - 400)

let dx = (refPoint.x - touch.x) --\> let dx = (400 - 0)

This will give you a triangle with two points at (300, 400) and one point at (400, 400) in the normal X/Y coordinate plane. Therefore, to fix this, simply change your code to:

```
let dy = (refPoint.y - touch.y)
let dx = (touch.x - refPoint.x)

```

This should fix your inversed angles issue. Something you should note however is that since the Y axis is inverted, it causes the coordinate plane to be practically "flipped" across the X axis, and that angles in screen space will increase going clockwise and decrease going counterclockwise.

Hope this helps!
> 2 votes

# Answer
You wil want to subtract the touch with the ref point:

```
//180 is inversed? 180 is when touch is on the right side...
let dy = (touch.y - refPoint.y) //opposite
let dx = (touch.x - refPoint.x) //adjacent

```

This results in the (dx, dy) vector being from the refPoint to the touch point (as you would expect).
> 2 votes

---
Tags: mathematics, touch, angles, trigonometry, spritekit
---


title: Vector3.Angle() Never Reaching 0

text:
# Question
Title: Vector3.Angle() Never Reaching 0
I'm having trouble understanding why with this script, Vector3.Angle() sometimes will never reach 0.

This question comes from me trying to make a "turret" that rotates to face a target position. It was not quite working (the angle between the turret and target would get very close to 0 and start flipping between + and - values, and never actually 0).

So to debug it I stripped the script down, and used transform.LookAt(), trying to isolate the problem. However, even using LookAt(), the Vector3.Angle() method still -sometimes- refuses to report the angle as 0, and I'm not sure why.

```
                //Turret does not care about any Y position differences...
                Vector3 currCustom = currentTargetPosition;
                currCustom.y = transform.position.y; //ignore Y differences...
                Debug.Log("currCustom is: " + currCustom);

                Vector3 directionVector = currCustom - transform.position;
                Debug.Log("directionVector is: " + directionVector);

                float angle = Vector3.Angle(transform.forward, directionVector);
                Debug.Log("angle is: " + angle);

                transform.LookAt (currCustom);

```

The attached image should also help demonstrate what is going on (note that the object doing the checking is an empty GameObject located roughly where the orange square is).

Any ideas as to what I'm doing wrong are appreciated, thank you for reading.

# Answer
> 2 votes
```
if (Math.abs( angle) > mindelta )
      transform.LookAt (currCustom);

```

I think it depends on floating point math errors, I suggest to define a min angle (mindelta in my code example) inside wich, the turret doesn't move

# Answer
> 0 votes
Does normalizing the vectors make a difference?

> @Jon: Good catch, normalizing "directionVector" seems to make the math work out (transform.forward is already normalized). So if you make this an answer I'll mark it as correct. If possible, could you elaborate on how normalizing the vector makes the math work out? I'm familiar with the concept of normalization, but I just don't fully understand the mathematical significance in this case. Either way, thanks again.

Borrowed from this question:

```
double Vector3AngleBetweenTwoPoints(Vector3 p1, Vector3 p2)
{
return acos(Vector3DotProduct(p1, p2) / (Vector3Magnitude(p1) * Vector3Magnitude(p2)));
}

```

When p1 and p2 are both unit vectors, this condenses to:

```
return acos(Vector3DotProduct(p1, p2));

```

Since p2 was not normalized, the angle coming out of acos() was being arbitrarily scaled by a factor of (1 / distanceBetweenObjects).

It's worth noting that the length of a 2X-scale world matrix's forward vector is 2.0. To find the angles between world objects, you'll definitely need to normalize.

Edit:
Although you aren't really close to it, I'd also mention a constant float value called Epsilon. It represents the smallest value that can be precisely represented by the float equation and anything that evaluates to less than that is usually considered "0 enough".

---
Tags: c#, unity, rotation, vector, angles
---


# Question
Title: How to calculate alpha for n channels, so the sum equals 1 (100% coverage)?
Having "n" number of overlaying channels (bitmaps in the same place, layers etc.) how to calculate required alpha for each of them, so they "hide" background completely?

Each layer can have equal value, sum should be exactly 1 ("full alpha"). "n" is 2 or more (likely up to dozens).

\[Game example of this would be a Smoke Grenade in FPS game - multiple ("n") bitmaps, making area behind it completely invisible for player - if standing before smoked area (standing inside results in partly-covered vision).\]

# Answer
Unfortunately, the only way to (theoretically) get stuff to layer together into a *full-alpha* pixel is to have a completely opaque layer.

Reasoning: The alpha channel is a multiplier for applying the other colour channels. Painting a region with opacity `opacity`,`n` times, gives you `1 - opacity^n` final alpha.

Here's a demo:

The leftmost is black at opacity 0.5. Each consecutive one is one more copy of it stacked on top of it. The opacities are approximately 0.5, 0.75, 0.87, 0.97. They tend toward 1, but won't reach it:

Querying Wolfram Alpha with `1 - 0.5^n`:

As n→∞, the function tends toward (but never reaches) 1.

---

In practice, floating point rounding error would hit at some point due to sometimes unpredictable hardware-dependent limitations.

Even so, 0.9 opacity is probably good enough. Could you tell the difference in a fast-paced game? The right rectangle is actually 0.9 opacity:

We can solve for what value of `n` would produce 0.9 opacity:

*0.9 = 1 - 0.5^n* implies *n = 3.32193*

So for layers with opacity 0.5, four layers should be enough. Try it with your own values.
> 3 votes

# Answer
This is the result of `1 / log(n)`. Using "Double Float" for calculations, alpha values in pictures are rounded to 2 decimal places.

Black on White:

White on Black:
> 1 votes

---
Tags: graphics-programming, alpha
---


# Question
Title: Are shaders the only way to implement 2d lighting?
I'm working on a 2d top down game with libgdx and I think i got the basics. No want I want to implement lighting, I don't know anything about lighting. I want just to have some light sources and shadows, but how do i do it?

**Is using glsgl the only wayto do lighting in a 2d game?** I've already tried to learn opengl and gave up because i thought it was too dificult and could take too long to do something even if i got the basics. Mabye glsl is different anyways

Any examples/tutorials would be welcome. Thanks in advance

# Answer
> 1 votes
There are ways to do dynamic lighting without shaders, although they're usually not as efficient. They often involve raycasting. The link below has some links to useful resources regarding dynamic lighting.

http://www.java-gaming.org/topics/2d-dynamic-lighting/27012/view.html

# Answer
> 1 votes
If you're also working with box2D, you could try box2Dlights, it's a pretty nice wrapper and it's easy to implement as well.

---
Tags: java, libgdx, lighting
---


title: Collision Detection in OpenGL

text:
# Question
Title: Collision Detection in OpenGL
For a 3D Game using OpenGL i have to implement a simple collision detection. After thinking about that, i have had the idea to read out the `glm::mat4 MVP` values and compare them to each other. Is that a practicable approach? As a first step, i output each MVP Matrix with `glm::to_string(MVP)` but to my surprise, that causes a big loss of performance (frame rate is decreased factor 5). So is that a bad idea to fulfill my task?

# Answer
Why do you need to convert the MVP matrix to a string? You could use the raw values even faster than you could parse a string.

Furthermore, That doesn't supply you with enough information. That could tell you where the object is, how it's rotated, and how RELATIVELY large it is, it couldn't tell you how large it ACTUALLY is or where it could collide relative to that. eg. you could render a dragon and the player with the exact same MVP matrix and see that their collisions are going to be completely different.

I would first start with an AABB around each object. Basically, you go through each point of each mesh, find the maximum (x, y, z) of each vertex on the mesh, minimal vector (x, y, z) on each mesh. Multiply each of those points by the MVP and you have a cube that every point of the object is in (A bounding volume.) to test if anything is within that, you see if it's between the min and max points of the bounding volume. That is the basics of collision detection.

This concept has many other forms, OBB (Oriented Bounding Box), Bounding Sphere, Bounding Capsule, etc.

Pseudo Code:

```
struct
{
    float x, y, z;
} Vec; // use the GLM alternative

struct
{
    Vec min; // no particular order, as long as they are ordered.
    Vec max;
} AABB;

AABB GetAABB(const Mesh& mesh)
{
    Vec min, max;
    foreach position in mesh.vertices
    {
        if (p.x < min.x) min.x = p.x;
        if (p.y < min.y) min.y = p.y;
        if (p.z < min.z) min.z = p.z;

        if (p.x > max.x) max.x = p.x;
        if (p.y > max.y) max.y = p.y;
        if (p.z > max.z) max.z = p.z;
    }

    AABB box;
    box.min = min;
    box.max = max;

    return box;
}

bool Collides(AABB a, AABB b)
{
    int meetingAxies = 0; // how many axies are colliding between the AABBs (must be at least 3 to be true)

    if ( (b.min.x > a.min.x) && (b.min.x < a.max.x) ) meetingAxies++;
    if ( (b.min.y > a.min.y) && (b.min.y < a.max.y) ) meetingAxies++;
    if ( (b.min.z > a.min.z) && (b.min.z < a.max.z) ) meetingAxies++;

    return meetingAxies == 3;
}

```
> 1 votes

---
Tags: opengl
---


# Question
Title: How to use a buffer in GLSL to do a LUT-lookup?
I am currently on a medical application which needs different kinds (up to totally individual) lookup tables (LUT) for image display. And this done with 10bit finish. So it is most of the time required to use 16-bit gray scale pixels.

I chose to use modern OpenGL and thus I'll want the lookup to happen in a GLSL shader program.

I had a try in uploading a 1D-Tedture (R16) using *sampler1D* to do the lookup as such:

```
        uniform sampler2D tex;
        uniform sampler1D lutData;
        in vec2 fragTexCoord;
        out vec4 finalColor;
        void main()
        {
            float primaryLvl = texture(tex, fragTexCoord);
            // index image 'color' in Lut-Texture
            float red = texture(lutData, primaryLvl);
            finalColor = vec4(red, red, red, 1.0);
        }

```

It works about as expected - however Textures (also 1D aparently) are limited to 8192 in size (on my machine). So the requirement for full range 16-bit images is not met.

For this above test I upload my images as R16 (for me it is gray) - normalized float 0-1.0.

Would it be feasible to upload a buffer (arbitrary data) and do the lookup there? How would I do this (Syntax)?

And will my current pixel format interfere with my idea so I have to upload it as R16\_INT instead. Or can (and should) I convert it in the shader from Normalized to Int (how is this done)?

**Thanks**

# Answer
The answer is spread across the following links. Due to size constraints / requirements it had to be a **Buffer Texture**.

Overview listing of possible technologies: https://stackoverflow.com/questions/7954927/glsl-passing-a-list-of-values-to-fragment-shader

OpenGL reference to Buffer Texture: https://www.opengl.org/wiki/Buffer\_Texture

Different question but the poster has a nice **usage** pattern provided: https://stackoverflow.com/questions/20681347/openglwith-glsl-using-gltexbuffer-and-texelfetch

OpenGL reference how to fetch pixels directly: https://www.opengl.org/wiki/Sampler\_%28GLSL%29#Direct\_texel\_fetches \- however it will be called *samplerBuffer* in GLSL.

Details to my solution:

* Using OpenTK and C# BTW.
* I started up loading my Image (DICOM 12 bit) with as ushorts with the internal Format *GL\_R16* (one channel, normalized float). This is because I want to fetch the texture with interpolation and even mipmapping using **texture()** in GLSL.
* The Lookup table is declated as ushort\[\] with 64k items. Those are actual int values but for the conversion precesision between normalized and *ushort* it does not matter. The right values will map to the same bit patterns.
* The Buffer Texture is loaded off a Buffer of those ushort\[\] (length: 64k). At initialization of the Buffer Texture I use the internal format *GL\_R16* again. This implies some kind of 'conversion' (but bit patterns are equal) from my ushort\[\] to the buffer texture (noop).
* Probably *GL\_R16I* would have worked, too. But At the end in GLSL I want to get a normalized float value in order to fill the final color attribute. So I went right into normalized upload.

My shader source:

```
        #version 150

        uniform sampler2D tex;
        uniform samplerBuffer lutData;
        in vec2 fragTexCoord;
        out vec4 finalColor;

        void main()
        {
            float primaryLvl = texture(tex, fragTexCoord);
            int index = int(primaryLvl * 65535);
            float gray= texelFetch(lutData, index);
            finalColor = vec4(gray, gray, gray, 1.0);
        }

```

Fetch the texel from the image texture (normalized) so we have to convert to int index. Index in LUT buffer texture - get normalized float again. Use right away for pixel color.

```
        var buf = GL.GenBuffers(1);
        GL.BindBuffer( BufferTarget.TextureBuffer, buf);
        GL.BufferData( BufferTarget.TextureBuffer,sizeof(texData),texData,BufferUsageHint.DynamicRead)

        var handle = GL.GenTexture();
        GL.BindTexture(TextureTarget.TextureBuffer, handle);
        GL.TexBuffer(TextureBufferTarget.TextureBuffer, SizedInternalFormat.R16, buf);

```

In the main loop you'll use the buffer texture just as a texture:

* Activate texture unit X
* Bind texture
* set uniform value to texture unit X
> 1 votes

---
Tags: opengl, shaders, glsl, fragment-shader
---


# Question
Title: Unity 5 2D drawing sprites programmatically
How can I draw sprites in Unity 5 programmatically ? I am looking for something similar to `spriteBatch.Draw()` in XNA. The results I get when I search about it are either outdated http://wiki.unity3d.com/index.php?title=SpriteManager (this was written in 2012), or they are done using the unity interface. All I can find is a `Sprite` class in UnityEngine.dll. Is this what I need ? How would the drawing work ? I really don't get it.

# Answer
> 19 votes
Unity does not have this kind of "direct mode" rendering, you won't be calling `Draw` in any update loops for Unity.

In Unity you need to create a game object, then attach scripts to that game object. Those scripts will control how the object behaves, if and how it's displayed on screen, if it's part of the physics system etc.

To create a new sprite to draw on screen you'll need to create a new game object, then attach the SpriteRenderer script to it and set its sprite.

```
GameObject go = new GameObject();
SpriteRenderer renderer = go.AddComponent<SpriteRenderer>();

renderer.sprite = Resources.Load("Sprites/Player", typeof(Sprite)) as Sprite;

```

This assumes a directory structure of

```
-Assets
--Resources
---Sprites
----<Your 2D assets, set with their texture type to Sprite (2D and UI)>

```

For example:

Then you'd had a different script for changing the position, rotation etc, depending how you want it to behave.

The easiest way to accomplish all of this without having to write as much code? Create the game object in the Unity editor first. Once the game object is equipped with the sprite you want and the behavior scripts and all that. Drag and drop it into a resources directory. This creates a prefab. Prefabs are just what they sound like, pre-fabrications. They're complete objects that you can then reference and create on the fly.

You'd create those like:

```
public void CreateObject(string prefabName) {
   GameObject newObject =
      GameObject.Instantiate(Resources.Load(prefabName)) as GameObject;
}

```

This will spawn a clone of the prefab you created before. So, if for example, you'd given your prefab the behavior of moving towards the player and attacking, every time you spawn a new prefab of that type, they will start moving towards the player and attacking. The scripts you only had to write once control all of those game objects.

I think the main difference you're seeing here is the heavy use of components. Which you likely haven't seen in other game engines like XNA. Unity really is a powerful engine, but your frustration comes from trying to use it like other engines, when it's not like other engines. Check out my profile for some training, I added a link for a free trial so you don't have to pay.

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


# Question
Title: How to Incorporate two loops: One for Turn Based Gameplay, and another for ongoing actions
I'm working on a roguelike using libtcod.

So far everything works well with the turn-based functions. Essentially, when a player takes a turn, it triggers everything to advance.

What if I have an item, such as a torch, and I want to animate that cell? Whether or not the player has taken a turn, purely for aesthetics, I'd like this torch's cell to rotate between some various colors.

How would you incorporate animation like this?

# Answer
> 5 votes
I wouldn't do the turn-based gameplay in a separate loop. Instead, just have the one main game loop like any other game, and that loop checks if it's time to advance a turn yet.

---
Tags: animation, turn-based, roguelikes
---


title: Wrong distance in Depth-buffer

text:
# Question
Title: Wrong distance in Depth-buffer
I am currently trying to get the Depth Buffer as a texture to use it for edge detection algorithms. Since XNA4 does not allow direct access to the Depth Buffer as texture i have to render it into a texture. The effect i currently use looks like this:

```
float4x4 World;
float4x4 View;
float4x4 Projection;

struct DEPTH_VS_OUTPUT
{
    float4 Position : POSITION;
    float2 Depth : TEXCOORD;
};

DEPTH_VS_OUTPUT DepthTextureVS(float4 Position : POSITION)
{
    DEPTH_VS_OUTPUT output;

    float4 worldPosition = mul(Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);
    output.Depth = output.Position.zw;

    return output;
}

float4 DepthTexturePS(DEPTH_VS_OUTPUT input) : COLOR0
{
    float4 result;
    result.rgb = input.Depth.x / input.Depth.y;
    result.a = 1.0;
    return result;
}

technique DepthTextureRender
{
    pass P0
    {
        CullMode = NONE;
        ZEnable = TRUE;
        ZWriteEnable = TRUE;
        AlphaBlendEnable = FALSE;

        VertexShader = compile vs_2_0 DepthTextureVS();
        PixelShader = compile ps_2_0 DepthTexturePS();
    }
}

```

It looks like this:

The cubes in this scene are 1x1x1 the projection matrix is made like this:

```
var projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 16f / 9f, 0.1f, 1000f);

```

As far as I understood the Depth Buffer concept z/w should give me the distance from the camera position to the pixel as value between 0-1 where 0 would be the Near-plane and 1 the Far-plane but since the cubes in this scene are only about 5 Units away they shouldn't be white.

# Answer
> 0 votes
I really doubt that the depth Buffer is inaccurate, the issue is much more likely the the boxes are further than the far pane or your shader is calculating something incorrectly.

Anyways XNA has built in functionality for generating a Depth Texture.

```
RenderTarget2D shadowRenderTarget;

shadowRenderTarget = new RenderTarget2D(GraphicsDevice,
    graphics.GraphicsDevice.Viewport.Width,
    graphics.GraphicsDevice.Viewport.Height);

DepthStencilState depthStencilState = new DepthStencilState();

depthStencilState.DepthBufferFunction = CompareFunction.LessEqual;
GraphicsDevice.DepthStencilState = depthStencilState;

GraphicsDevice.SetRenderTarget(shadowRenderTarget);

// Render the depth texture
Rectangle rect = new Rectangle(
    graphics.GraphicsDevice.Viewport.X,
    graphics.GraphicsDevice.Viewport.Y,
    graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height);

spriteBatch.Begin();
spriteBatch.Draw(map, rect, Color.White);
spriteBatch.End();

GraphicsDevice.SetRenderTarget(null);

```

---
Tags: c#, shaders, xna-4.0, depth-buffer
---


# Question
Title: Skeletal animation with ASSIMP, COLLADA, and glm
I have been trying to learn how to implement skeletal animation (skinning) from COLLADA files using ASSIMP and glm. But after a week of being stuck reading different tutorials and posts I have found here and there I still can not get even the simplest animation to work correctly. My results are just bones that look like they are incorrectly translated and rotates around wrong axes.

This mesh have three bones starting at origo and going straight up through a tube, they then swing from side to side when the animation is played. LEFT: My result at key frame 2. RIGHT: Blenders result at key frame 2.

So now I have two questions related to the animation matrices and hopefully someone might help me understand what I am doing wrong.

First, when I read the bone data ( or joints but I called it bone in my code so I will refer to it as bone here also ) I get the bones matrix from mOffsetMatrix. I am not 100% sure if this matrix contains a bones transform relative to its parent bone or if it contains the final position. I have tried to use it as both relative and absolute transform but my final result is still wrong so I dont know which is right.

If the mOffsetMatrix contains the relative transform of a bone then I have to calculate the absolute transform by multiplying it with the transform of its parent bone? I tried doing this with the following code.

```
// struct for storing bones (joints)
struct Bone
{
    std::string name;
    glm::mat4 relativeTransform;
    glm::mat4 absoluteTransform;
    int parent; // id to parent bone
};

std::vector<Bone> skeleton; // contains all the bones

for (int i = 0; i < skeleton.size(); ++i)
{
  // if bone have no parent, relative transform is absolute transform
  skeleton[i].absoluteTransform = skeleton[i].relativeTransform;

  // if bone have parent, add parent absolute transform
  if (skeleton[i].parent != -1)
  {
    skeleton[i].absoluteTransform = skeleton[skeleton[i].parent].absoluteTransform * skeleton[i].relativeTransform;
  }
}

```

Skeleton is a vector containing all of the bones where parent bones always appear before its children so as long as I start calculating from the beginning of the list it should be correct. Also i should mention that i have a function that identify bone parents so the parent id is correct.

Then in regards of the animation step. For now I try to only animate individual key frames so I do not currently do any interpolation, this is so that incorrect interpolation does not affect my result. But I dont know if i calculate the current animation transforms correct. In the end it is the bonesAnimation.current matrices that I calculate for each bone/frame and send to my shaders.

```
// struct containing keyframe data for each bone
struct BoneAnimationChannel
{
    std::string name;
    std::vector<float> positionTime;
    std::vector<float> rotationTime;
    std::vector<float> scalingTime;
    std::vector<glm::vec3> positionKeys;
    std::vector<glm::quat> rotationKeys;
    std::vector<glm::vec3> scalingKeys;
    glm::mat4 current; // current transform to be used
};
std::vector<BoneAnimationChannel> bonesAnimation; // contain animation data for all bones

```

I store the animation data for each bone in a struct and have one instance of the struct for each bone in the vector bonesAnimation. Then i calculate the current transform for each bone at a certain time using the following code.

```
// update animation
std::vector<glm::mat4> unMultiplied;
for (int i = 0; i < skeleton.size(); ++i)
{
  // current bone
  auto bone = boneAnimation[i];

  int id = 1; // id to keyframe

  glm::mat4 currentPose = glm::toMat4(bone->rotationKeys[id]);
  currentPose[3][0] = bone->positionKeys[id].x;
  currentPose[3][3] = bone->positionKeys[id].y;
  currentPose[3][2] = bone->positionKeys[id].z;
  currentPose = glm::scale(currentPose, bone->scalingKeys[id]);

  // add to list of animation transforms
  unMultiplied.push_back(currentPose);

  // bones parent id
  int parentId = skeleton[i].parent;

  // transform for current bone
  glm::mat4 result = unMultiplied[i]; // if no parent bone

  // if bone have parent, add parents transform
  if (parentId != -1)
  {
    result = unMultiplied[parentId] * unMultiplied[i];
  }

  boneAnimation[i].current = result;
}

```

It is possible that my problem lays elsewhere but I think that these two places are the most likely sources for my problems so I start by asking if these calculations look correct. I have tried every different combination of matrices I can think of, I have even tried to invert them or transpose them to see if that is the problem but still I am completely stuck.

Maybe i even need some more transform other than the mOffsetMatrix for each bone and the position vector, scaling vector and rotation quaternion for the animation channels.

I hope this make some kinda of sense and i really appreciate any help i can get.

Thanks in advance :)

EDIT: This is the whole file where i load mesh and animations https://db.tt/EG965vuz, and in the end of this file is where i calculate current animation pose https://db.tt/cBbYZck2

# Answer
> 5 votes
If you were using assimp's implementation (AssimpViewer source) as reference, then you probably too missed the fact that **Assimp's and glm use reverse matrix multiplication order**. To clarify, we are talking about matrix-matrix multiplication, and the order is reverse relative to each other

And we know that matrix multiplication is not commutative.

So the line

```
result = unMultiplied[parentId] * unMultiplied[i];

```

becomes

```
result = unMultiplied[i] * unMultiplied[parentId];

```

And the final transform for a bone is given by

```
bone.OffsetMatrix * result * GlobalInverseMeshTransform;

```

Where `GlobalInverseMeshTransform` is the inverse of the root node's transform.(Might be identity)

---

Here you are reading outside of bounds. The second row should also be 0 - 3. Consider making it a simple function.(assimp mat4 to glm mat4).

```
glm::mat4 rootTransform(
    m[0][1], m[0][2], m[0][3], m[0][4],
    m[1][1], m[1][2], m[1][3], m[1][4],
    m[2][1], m[2][2], m[2][3], m[2][4],
    m[3][1], m[3][2], m[3][3], m[3][4]);

```

You are forgetting to invert the root transform

```
anim.rootTransform = rootTransform; // should be glm::inverse( rootTransform );

```

Are you sure this is getting called? Its not a good idea to compare floats like this.

```
if (vertices[vertID].boneWeights[k] == 0.0f)
{
    vertices[vertID].boneIndices[k] = i;
    vertices[vertID].boneWeights[k] = mesh->mBones[i]->mWeights[j].mWeight;
    break;
}

```

I am not sure whether the construction of the actual frame's matrix is correct. This works:

```
mat = glm::mat4_cast( currentrotation );
mat[0][0] *= currentscale.x; mat[1][0] *= currentscale.x; mat[2][0] *= currentscale.x;
mat[0][1] *= currentscale.y; mat[1][1] *= currentscale.y; mat[2][1] *= currentscale.y;
mat[0][2] *= currentscale.z; mat[1][2] *= currentscale.z; mat[2][2] *= currentscale.z;
mat[0][3] = currentposition.x; mat[1][3] = currentposition.y; mat[2][3] = currentposition.z;

```

Again, you are missing the `GlobalInverseMeshTransform`

```
eMeshes["test"]->animations[0].bones[i].current = eMeshes["test"]->skeleton[i].relativeTransform * result; // ... result * <youranim>.rootTransform;

```

Apart from these errors, your code looks like a mess. You should make the animation routine as part of the model you are animating. Maybe with a function like this `EvaluateAnimation( double time );` where time is the animation time you want to load.

Also a map lookup at each access to an object will be a great performance hit later, even with unordered\_map, so if you have long-term plans, I suggest you look for a better solution.

---
Tags: c++, skeletal-animation, assimp, collada, skinning
---


title: How to invert a damage formula?

text:
# Question
Title: How to invert a damage formula?
I have created simple damage formula based on source percent, which return fixed percent of damage.

```
DAMAGE_PERCENT = Exp(Log(100) * (1 - (100 - SOURCE_PERCENT) / 150)

```

Here is the result:

```
percent[0]: 4.641589
percent[1]: 4.786301
percent[2]: 4.935525
....
percent[98]: 94.04449
percent[99]: 96.97654
percent[100]: 100

```

How can I make it return same results but with reversed SOURCE\_PERCENT value?

So percent\[0\] should return 100 and percent\[100\] return 4.641589?

# Answer
Just write a wrapper that takes your input and subtracts it from 100

```
float GetDamageInverse(int percent) {
    return GetDamage(100-percent);
}

```

Or you can change your equation to replace the `100 - SOURCE_PERCENT` with `SOURCE_PERCENT`.
> 3 votes

---
Tags: mathematics, algorithm
---


# Question
Title: Space Shooter Unity 5 Collisions not working
After upgrading the official Space Shooter Tutorial to **Unity 5**, collisions stop working.

Additionally, the following error is reported:
***Non-convex MeshColliders with non-kinematic Rigidbodies are no longer supported in Unity 5.0.***

# Answer
> 8 votes
Luckily the error message is quite self explanatory.

The solution to this problem is to **check Convex** for all the **Mesh Colliders** found in the project.

Only the **Player** *GameObject* should have a **Mesh Collider** in this project. So check **Convex**, and make sure that **Is Trigger** is checked as well.

---
Tags: unity, meshcollider, convex
---


# Question
Title: Class design and data structures for a Tower Defense
I was trying to come up with a structure for a simple TD game that has following elements

1. Tower Each Tower has a set of properties like range, damage, health etc There could be different types of Towers with different attack types. For eg Tower A can perform attackType 1 and 2 and Tower B can perform attackType 3 and 4
2. Creep Each Creep has a set of properties like damage, health, bountyPoints etc. There could be different types of Creeps with different abilities just like the Towers

For now I am trying to come with a good design that is scalable and well structured for the above two game elements

This is the skeleton of a Tower class that I have come up with so far. Please comment and suggest changes. Any design patterns that could make life easier

```
using System.Collections;
using System;

    public enum TowerType
    {
        tA,
        tB,
        tC
    };

    public class Tower {

        private TowerType type;
        private int damage;
        private int range;
        private int health;

        public Tower(TowerType type)
        {
            this.type = type;
            initializeVariables();
        }

        private void initializeVariables()
        {
            if (this.type != null)
            {
                if (this.type == TowerType.tA)
                {
                    this.damage = 20;
                    this.range = 40;
                    this.health = 50;
                }

                else if (this.type == TowerType.tB)
                {
                    this.damage = 30;
                    this.range = 50;
                    this.health = 60;
                }

                else if (this.type == TowerType.tC)
                {
                    this.damage = 60;
                    this.range = 60;
                    this.health = 80;
                }

            }
        }

        public int getDamage()
        {
            return this.damage;
        }

        public int getRange()
        {
            return this.range;
        }

        public int getHealth()
        {
            return this.health;
        }

        public TowerType getTowerType()
        {
            return this.type;
        }

        public string getType(int value)
        {
            return Enum.GetName(typeof(TowerType), value);
        }
    }

```

So using enums to define various types of towers. But is this a good design? Each Tower would have different damage, range and health.

What if there are 100 different towers? So in my InitializeVariables() would have a cluster of 100 if else statements. How can I improve on this or is there a better way to implement this?

# Answer
Here is how i think it could be done

```
class Class1 {
    public enum TowerType { A, B, C };
    static private Dictionary<TowerType, Tower> towerTypesInfo;

    static void init()
    {
        towerTypesInfo= new Dictionary<TowerType, Tower>(100);//100 tower types
        towerTypesInfo.Add(TowerType.A, new Tower(20, 40, 50));
        towerTypesInfo.Add(TowerType.B, new Tower(30, 50, 60));
        //... fill in the rest 98 tower types with their values ...

        //example of making a tower named tower1
        Tower tower1 = new Tower(TowerType.A);
    }

    public class Tower {
        public TowerType type { get; private set; }
        public int damage { get; private set; }
        public int range { get; private set; }
        public int health { get; private set; }

        public Tower(int d, int r, int h)
        {
            damage = d;
            range = r;
            health = h;
        }
        public Tower(TowerType type)
        {
            damage = towerTypesInfo[type].damage;
            range = towerTypesInfo[type].range;
            health = towerTypesInfo[type].health;
}   }   }

```

You don't need to make a function for every single variable you have, like in java. Just use `public int damage { get; private set; }`, C# has automated way of doing this with overwriting the default get; set; properties.

Also, You could fill this `dictionary` from a .txt if you wanted to. you could format the .txt to make it a bit easier to edit

`TowerTypesInfo.txt`:
A 20 40 50
B 30 50 60
C ...
> 1 votes

# Answer
Instead of having a `TowerType` enum and a lot of `if`/`else`/`case` constructs in your code which handle differences between types, you could make your types of towers separate classes which inherit from an abstract `Tower` base class.

These classes would set their properties in their constructors. Using sub-classes would also allow you to have a different implementation for the `attack`-method in each class thus allowing you to implement the different ways of attacking in an elegant way. The same pattern applies to any other situation where you want to run different code depending on the tower type. Like, for example, drawing the tower to the screen.
> 3 votes

# Answer
I would avoid the general idea of a tower type.

Let tower contain a set of properties that matter. An Attack object (that has its own range, RoF, damage, sound effects, onHit() effect for DoTs, etc.), a model, health, location...

Then build factory classes that are asked to build a "type" of tower by figuring out how to initialize a tower to be a "cannon" or a "mortar". This way your systems never need to look at a tower type. Graphics for instance just draws the model specified at the location specified. It doesn't have to lookup the appropriate model for towertype X each frame for each tower.

What makes this great is that if you want a new tower type, you just make a new initializer that builds those towers with different defaults. Your systems won't need to be "upgraded" to support it.
> 2 votes

# Answer
You might have misunderstood me a little bit. Not all objects HAVE to use factories. Perhaps only your tower and enemy objects. Maybe your Attack object as well as a Projectile. You'll need to tinker to see what fits the pattern.

Some people would create a generic Entity/GameObject class though. You could do some research on Entity Component Systems to see how that works.

Ultimately though, if a "cannon" is built, you could call `public static ITowerFactory.GetFactoryByType(TowerType type);` to get a `CannonTowerFactory`. Just pass it `TowerType.Cannon`

Then use that to call `public Tower ITowerFactory.BuildTower(Vector position);`

This method (implemented in `CannonTowerFactory`) will make a `new Tower()` and set all its properties accordingly for a cannon tower.

You could do something similar for stamping out enemies of various "types" as well.
> 0 votes

---
Tags: c#, unity, data-structure, oop
---


title: LibGDX scene2d good practices

text:
# Question
Title: LibGDX scene2d good practices
I'm developing a game using LibGDX and in a part it has a pretty complex UI for profile selection and stuff. I have some general problems.

I'd like to know good practices when generate good looking layouts using the Scene2d that comes bundled with it. I've found examples online but they don't usually get to the level of complexity that I require. Is the use of a table recommended always? How can I set positions and widths precisely (I've managed to fake it using paddings but there has to be a better way). I'd need something like absolute positioning in CSS.

I need to use different font files, colors and sizes for instance. How can do that in the skin and the use it in my code?

I also need different designs on buttons (different backgrounds). How can I do that?

Also for some reason my text is very bad looking. How can I make it look sharp?

Thanks in advance.

# Answer
> 1 votes
I'm just getting into libgdx/scene2dui as well, but maybe I can offer some help.

I found using tables quite handy and accurate. It also has the benefit of relative positioning of objects. I don't know about CSS, but why would you use absolute positioning, it screws up if you want the game to be playable in different resoultions and aspect ratios and makes working on your UI really hard. If you want to add something you'd have to manually move everything else.

You create a root table and add tables to it, to which you add tables and ... eventually some things. Every Object in your UI (called Widgets: buttons, textfields, labels, images, any class extending actor) needs a Container. Tables are the containers with most control over positioning your stuff. So even if they have just one cell they are a good choice.

Position things by specifying table.add(...) with methods of the Cell class.

For example: `table.add(yetAnotherTable).align(Align.topLeft).expandX().colspan(2)`.

You can also set the absolute size of the cell with this, even better, you can use a min, max and preffered size.

To make it short: I don't know any other reasonable way to do an UI in libgdx.

> I need to use different font files, colors and sizes for instance. How can do that in the skin and the use it in my code?

As the method `void add(java.lang.String name, java.lang.Object resource)` suggests you can add just about everything to a skin and give it a name (string).

When you need the ressource you can call it by it's name with the appropriate method. A big benefit is that i gives you Drawables for everything that can be converted to a Drawable by calling `getDrawable(java.lang.String name)`, which can otherwise be unhandy for some classes. Also, you can call dispose() on a whole skin. It just makes handling a lot of objects easier.

> Also for some reason my text is very bad looking. How can I make it look sharp?

Do you use BitmapFonts and scale them? You need a different BitmapFont for every size. Or you just store .ttf files in your assets folder and create a new BitmapFont with the Freetype fontGenerator whenever you need it.

Check out the wiki on that

---
Tags: java, libgdx, gui, fonts, scene2d
---


# Question
Title: Imported Blender modular mesh lighting/shadows issue - Unity
Hi I've very recently started using Unity and am creating a game level. I've created my environment in blender and am currently using a modular design as I'd like to include destructible environments.

I've applied test textures and colours to the mesh but have noticed problems when importing into unity.

In blender the lighting appears to cast shadows smoothly across the modular design, but once imported into unity I get random "light spots" and consecutive pieces appear slightly different shades in places.

Each module of a particular type shares a linked material and texture.

I've attached the Blender render first and then the Unity render (they have different lighting as I haven't added all the lights to blender, but the difference is obvious)

The walls are made up of cuboids 2.4 x 1.0 x 0.15

And the floors 1.0 x 1.0 x 0.1

It seems that some of the 'pieces' are receiving/casting shadows differently.

# Answer
I believe I've solved most of the issues.

The very light wall pieces on the left of the unity render were caused by them actually being duplicate pieces. Deleting the duplicates solved that issue.

I then swapped my Main camera rendering path setting to "Vertex Lit" instead of "Forward".

The other probs seem to have been caused by the point lights. I had the ranges high on these at and the intensities low. By decreasing the ranges and increasing the intensities and then adding in additional point lights to the darker sections of the level I have managed to almost remove the probs completely.
> 0 votes

---
Tags: unity, rendering, lighting, blender, materials
---


# Question
Title: LibGDX how to efficiently handle button presses
I'm making a simple 2D game for android using LibGDX. My game needs to have many buttons in it that fire off a method when pressed, and I was wondering what the best way to do this would be.

I tried a simple solution using an InputProcessor and a bunch of if statements but it seems really unscalable and inefficient. Here's my attempt:

```
InputProcessor inputProcessor = new InputProcessor() {
        @Override
        public boolean keyDown(int keycode) {
            return false;
        }

        @Override
        public boolean keyUp(int keycode) {
            return false;
        }

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

        @Override
        public boolean touchDown(int screenX, int screenY, int pointer, int button) {
          //  message = "Touch down: " + screenX + ", " + screenY;
            if (screenY >= 2280) {
                if(screenX >= 31 && screenX <= 281) {
                    yellowButtonPressed = true;
                } else if(screenX >= 313 && screenX <= 563) {
                    redButtonPressed = true;
                } else if(screenX >= 595 && screenX <= 845) {
                    blueButtonPressed = true;
                } else if(screenX >= 877 && screenX <= 1127) {
                    greenButtonPressed = true;
                } else if(screenX >= 1159 && screenX <= 1409) {
                    orangeButtonPressed = true;
                } else {
                    //regular click
                    if (monster.isAlive()) {
                        monster.takeDamage(1);
                    }
                }

            } else if(screenY <= 1690 && screenY >= 1510 && screenX <= 1430 && screenX >= 1280) {
                    xPressed = true;

            } else {

                    //regular click
                    if (monster.isAlive()) {
                        monster.takeDamage(1);
                    }

                }

            return true;
        }

        @Override
        public boolean touchUp(int screenX, int screenY, int pointer, int button) {
     //       message = "Touch up: " + screenX + ", " + screenY;
            if(yellowButtonPressed) {
                if(screenX >= 31 && screenX <= 281) {
                    xButton.show();
                    menuShown = true;
                    tempCurrentMenu = "Heroes";
                }
                yellowButtonPressed = false;
            } else if(redButtonPressed) {
                if(screenX >= 313 && screenX <= 563) {
                    xButton.show();
                    menuShown = true;
                    tempCurrentMenu = "Fighters";
                }
                redButtonPressed = false;
            } else if(blueButtonPressed) {
                if(screenX >= 595 && screenX <= 845) {
                    xButton.show();
                    menuShown = true;
                    tempCurrentMenu = "Researchers";
                }
                blueButtonPressed = false;
            } else if(greenButtonPressed) {
                if(screenX >= 877 && screenX <= 1127) {
                    xButton.show();
                    menuShown = true;
                    tempCurrentMenu = "Artifacts";
                }
                greenButtonPressed = false;
            } else if(orangeButtonPressed) {
                if(screenX >= 1159 && screenX <= 1409) {
                    xButton.show();
                    menuShown = true;
                    tempCurrentMenu = "Purchases";
                }
                orangeButtonPressed = false;
            } else if(xPressed) {
                if(screenY <= 1690 && screenY >= 1510 && screenX <= 1430 && screenX >= 1280) {
                    menuShown = false;
                    xButton.hide();
                    tempCurrentMenu = "";
                }
                xPressed = false;
            }
            return true;
        }

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

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

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

```

Is there a better way to do this?

# Answer
A much better option is to create a small class (or reuse a suitable one like Rectangle) and keep them in a list, the code becomes simpler and it will be easy to add more buttons over time.

```
InputProcessor inputProcessor = new InputProcessor() {

  private final static List<Button> buttons = ...
  private Button lastButton = null;

  abstract class Button {
    public final int top, left, bottom, right;
    public boolean isHit(int x, int y) {
      return top <= y && bottom >= y && left <= x && right >= x;
    }
    public void doClick() {}
    public boolean performDrag() { return false; }
  }

  public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    for (Button b : buttons) {
      if (b.isHit(screenX, screenY) {
        b.doClick();
        lastButton = b;
        return true;
      }
    }
    // No button was clicked, perform other checks
  }
  public boolean touchUp(int screenX, int screenY, int pointer, int button) {
    if (lastButton.performDrag(screenX, screenY)) {
      lastButton = null;
      return true;
    }
    lastButton = null;
    // Button didn't accept the drag gesture, check other things
  }
}

```

As you can see Button has doClick and performDrag that can be overridden in the classes for each specific button, as an example for your yellow button

```
class YellowButton extends Button {
  @override
  public boolean performDrag() {
    if(screenX < 31 || screenX > 281)
      return false;

    xButton.show();
    menuShown = true;
    tempCurrentMenu = "Heroes";
    return true;
  }
}

```

Another thing is that you could implement doClick as `boolean doClick(x,y)` instead of having an `isHit` function to check with first, in the same way as the `performDrag` function works, whichever way you feel more comfortable with. In this case I made it two functions mostly because then you don't need to implement the coordinate checkup in your specific button classes.
> 0 votes

---
Tags: libgdx, input
---


# Question
Title: Unreal Engine 4 is now only free or open source as well?
Recently Unreal Engine 4 become free with Royalty fees. What about the code? Is it opensource or no?

# Answer
> 8 votes
From their website

> Full Source Code Access
>
> With C++ source code for all of Unreal Engine 4, you can customize and extend Unreal Editor tools and Unreal Engine subsystems, including physics, audio, online, animation, rendering as well as Slate UI. With complete control over engine and gameplay code, you get everything so you can build anything.

This is not the same as open source however, and since you pay royalties instead of an upfront price it is unlikely that there is an open source license available.

---
Tags: unreal, unreal-4
---


# Question
Title: What does the update button in the Unreal Engine launcher actually update the engine to?
Unreal Engine 4 seems to have a very handy way of managing different versions of the engine - mainly you get to keep several copies and choose which one to launch.

That said, not having used the new launcher recently I see that I am quite behind in engine versions but where previously I had to download the new version (as can be seen by my several copies of the engine) there is now an update button on the engines.

My internet is really slow so I'm curious if anyone could tell me what the update button actually does? For example, in the circled one, will it update to some 4.2.x minor version or will it update to the 4.7.2 version that I can freshly install? If I can save some bandwidth by upgrading to 4.7.2 over downloading a fresh copy that would be ideal.

# Answer
This button will only perform a minor update on the engine. I do not see any options to further update the installed engines so it seems the latest version needs to be downloaded separately.
> 1 votes

---
Tags: unreal-4
---


# Question
Title: What is the better way to speed up gameplay as the level rises?
I started with game programming couple of weeks back. For the starters I tried to develop ZigZag (link takes you to 2 min gameplay).

I am done with the logic of gameplay by now. It runs well and all. Now I want to speed up the gameplay as user passes some score. Say after 100 points increase the speed of the ball.

I have two options:

1. Control the speed using time-delay by varying time.delay(var).
2. Actually increasing the speed of the moving ball

Not sure which one is a good idea in long term, I'm looking for help from experienced game developers.

You can checkout the source code: https://github.com/ravi-ojha/zigway/blob/master/zigway.py

# Answer
Time delays are usually not a good idea because you can't go below zero. Also keep in mind that differently powerful systems will take shorter or longer to execute your actual game-loop without the artificial delay. When you want the game experience to be independent from the power of the users hardware, get a time measurement at the beginning of your game-loop, run the loop and then pause by the time which is still left.

But the better solution would likely be to increase the movement speed of all game objects. In that case you can go as high as you want, no matter how powerful the users hardware is.
> 0 votes

---
Tags: game-design, game-mechanics, game-loop, pygame
---


title: Simulate popularity

text:
# Question
Title: Simulate popularity
I'm working on a music game. It has genres like pop and rock. Different centuries have different music popularities. (Influences the sales)

I thought about building an object like this:

```
var rock = {
 0: 0.8,
 2: 1.0,
 5: 0.5,
 10: 0.3
}

```

So if I am in the year 1.0, the popularity value would be 0.9. Is this the "best" way to do it?

# Answer
> 1 votes
This is a simple example of linear interpolation.

In this formula:

* timeA and valueA are your first fixpoint
* timeB and valueB are your second fixpoint
* timeN and valueN are the point you are looking for

valueN = valueA + (valueB-valueA) * ( (timeN - timeA) / (timeB - timeA) )

When you want a smoother interpolation around your fixpoints, you could go for a more fancy spline interpolation. But the additional complexity is usually only worth it when it is something in direct view of the player and not something they perceive indirectly through another value. It's also very frustrating for players interested in meta-gaming because spline interpolation is a lot harder to grasp than linear interpolation (although this can be an advantage when you want to discourage players from meta-gaming and instead get more immersed in the intended game).

---
Tags: mathematics, javascript, simulations
---


# Question
Title: In unity game appears dark exporting to ios what happened?
Everything appeared darker when I exported my game to iOS. I only updated my Unity to 4.6.3 . Any idea why?

# Answer
> 0 votes
OK I think I got it: Using "vertex lit" instead of "forward".

---
Tags: unity, ios
---


# Question
Title: exit application on double tap with message (Please click BACK again to exit ) ......unity
Can anyone please help me here? This is not quite related to programming.

I want to exit my Android application on back button tap with conformation for exit

```
@Override
public void onBackPressed()
{
    if (back_pressed + 2000 > System.currentTimeMillis())
        super.onBackPressed();
    else
        Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
    back_pressed = System.currentTimeMillis();
}

```

# Answer
in c#

```
void Update(){
   if (Input.GetKeyDown(KeyCode.Escape))
    Application.Quit();
 }

```

or in .js

```
function Update(){
   if (Input.GetKeyDown(KeyCode.Escape))
    Application.Quit();
 }

```

This is the function for exit app when back button pressed, if you want to exit the app when back button pressed twice, implement the logic in the java code you have posted in question into equivalent code in unity i.e initialise a variable to store current time in millis on first back button press and show message to press once again to exit, and if next back button press is within two seconds of first press, then exit app.

If you want this to work on a button click etc, implement the same technique and call `Application.Quit()` instead of `super.onBackPressed()` in java.

Hope this helps.
> 1 votes

---
Tags: unity, android
---


# Question
Title: Unity 5 The Editor has stopped working Windows 7 64bit
As soon as I press the play button to attempt to run any of my updates games crashes the editor immediately and I can't run my games.

Does anyone know how I could debug this or where to start? Does Unity keep a log of errors when it crashes?

I have both a 2D and 3D game that do not work and the editor is not throwing any errors or telling me there are compile time issues.

EDIT: If it makes any difference it is the 64bit version and I am using a Student Pro License

# Answer
Unity3d does keep logs, for editor and player.

You should check those to see what is going on.

You can find the location of your logs in this documentation page here: Unity Docs: LogFiles

That said, you should check if you are not using any imported DLL file that is meant (compiled for) for 32bit when running 64bit versions of the editor. Make a new empty project to test this out.
> 1 votes

---
Tags: unity
---


# Question
Title: Getting warning after importing plugin to unity5 project
I am getting following warning when I import any plugin to my unity5 project.Whats the solution for this warning? Is there any problem with that which will affect my project.

# Answer
The reason for that warning is because the scripting API has changed slightly in Unity 5. Clearly (and unsurprisingly, since Unity 5 was just released) the code in this plugin was written using commands from Unity 4 that were changed.

When you click "I made a backup, go ahead" the scripts will be automatically updated, replacing all the Unity 4 functions with their equivalent in Unity 5. This update will actually change the code, which is why it says to make a backup first (in case the changes break something in your project).

In the long run, the plugin author should update their code to work in Unity 5, but obviously that is a consideration for *them* not *you*.
> 1 votes

# Answer
The solution is having a backup and clicking the button "I made a backup, go ahead".

You are hopefully already under version control (are you?), so backup shouldn't be an issue.
> 0 votes

---
Tags: unity
---


# Question
Title: Is it possible to control what script is active on what sprite/object in Unity?
I have 2 objects, and I have a script which makes the player change their characteristics. I applied the script to both, and as you'd expect, pressing X button does the color, size, translation change effect on both objects at the same time.

Now how can I give the player the choice thanks to a key input, to be able to choose which item to apply the script to?

I am trying to make it work like a toggle..

```
if (toggle == 1) { // player can only change color of item 1 }

else if (toggle == 0) { //player can only change color of item 2 }

```

So what's the syntax to be able to select if a script is enabled or not on 2 different sprites?

# Answer
It would be better to add a bool variable into your Script and then toggle it on/off.

```
var object1Script = object1.GetComponent<MyScript>();
var object2Script = object2.GetComponent<MyScript>();

object1Script.enabled = toggle;
object2Script.enabled = !toggle;

```
> 1 votes

# Answer
something like this?

```
if (GetComponent<NameOfScript>().enabled == true)

```
> 0 votes

---
Tags: c#, unity, sprites, objects
---


# Question
Title: Is Minecraft component-based or does it have class for every block?
I'm wondering if Minecraft has class for every type of block or blocks are just IDs in code.

**EDIT**

And what about data like transparency, resistance, hardness, tool, etc? Are they hardcoded or stored external?

# Answer
> 3 votes
Class Based as a quick lookup learns. Every block is defined in a loose file and extends Block.

```
package tutorial.generic;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;

public class GenericBlock extends Block
{

    public GenericBlock (Material material)
    {
            super(material);
    }
}

```

---
Tags: design-patterns, minecraft-modding
---


# Question
Title: Sprite movement only works the first time, can't figure out why
In my libGDX game I have finally managed to get the sprite to move the way I want him to but for some reason my desired outcome only works the first time I run the code. If I try to run it again, he immediately flies off the screen. If I then comment out one of the brackets, save and then put it back in and run a test, he moves as I want him to (but only the first time). Am I missing something?

***EDIT****: Ok I changed the code and now I have a new problem, he moves but not smoothly like he does when I move him with the keyboard. now he sort of teleports forwards or backwards about 5pixels every time the screen is clicked (or touched).*

Partial Player class:

```
public class Player extends Entity implements InputProcessor{

OrthographicCamera camera;
Rectangle rectangle;
Vector3 touchPos;

public Player(Vector2 pos, Vector2 direction) {
    super(TextureManager.PLAYER, pos, direction);
    rectangle = new Rectangle(); //for hitbox
    }

@Override
public void update() {

    camera = new OrthographicCamera(240, 400);
    camera.position.set(240 / 2, 400 / 2, 0);
    rectangle.set(pos.x, pos.y + 40, 32, 22); //hitbox
    touchPos = new Vector3();

    pos.add(direction);{

        Gdx.input.setInputProcessor(this);

    //the keyboard inputs below work exactly how I want them to
    if(Gdx.input.isKeyPressed(Keys.A)) // left
        setDirection(-300, 0);
    else if(Gdx.input.isKeyPressed(Keys.D)) // right
        setDirection(300, 0);
    else
        setDirection(0, 0);
    }

    // make sure player stays inside stage
    if (pos.x < 0) pos.x = 0;
    else if (pos.x > 240 - 32) pos.x = 240 - 32;

}

public void moveLeft() {
    setDirection(-300, 0);
}

public void moveRight() {
    setDirection(300, 0);
}

public void Still() {
    setDirection(0, 0);
}

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    // TODO Auto-generated method stub
    if (screenX < ManicMeltdowns.WIDTH / 2 && screenY > ManicMeltdowns.HEIGHT / 2){
        moveLeft();
    }

    if (screenX > ManicMeltdowns.WIDTH / 2 && screenY > ManicMeltdowns.HEIGHT / 2){
        moveRight();
    }
    return true;
}

@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
    // TODO Auto-generated method stub
    if (screenX < ManicMeltdowns.WIDTH / 2 && screenY > ManicMeltdowns.HEIGHT / 2){
        Still();
    }

    if (screenX > ManicMeltdowns.WIDTH / 2 && screenY > ManicMeltdowns.HEIGHT / 2){
        Still();
    }
    return true;
}

```

Thanks

# Answer
> 1 votes
The issue is the `else` condition after you check the A and D keys, since if no key is pressed it will reset the direction to 0, 0 every time the `update()` method is called. Instead of calling `moveLeft()` and `moveRight()` in the `touchDown` and `touchUp` you should keep track of each pointer passed by the `touchDown` and `touchUp` methods and check whether the pointers are in the zones for a left or right movement in the `update()` method.

For example, create a class Pointer:

```
public class Pointer {
    public int x = 0, y = 0;
    public boolean down = false;
}

```

Then, create an array of pointers, `touches[]`, in either the game class or the `Player` class to keep track of the touches. The length of `touches[]` should be however many touches you plan on recognizing, I usually use 10 just as a safe maximum. It would be best to put your array in the class that is the `InputProcessor`, which seems to be your `Player` class although it is typically the game class. Your `touchDown`, `touchDragged` and `touchUp` methods would change the values of `x`, `y`, and `down` for the `Pointer` at its index in `touches[]`. Then in `update()` iterate through the array and check for each touch.

For example:

```
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    if (pointer < touches.length){
        touches[pointer].x = screenX;
        touches[pointer].y = screenY;
        touches[pointer].down = true;
        return true;
    }
    return false;
}

@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
    if (pointer < touches.length){
        touches[pointer].x = screenX;
        touches[pointer].y = screenY;
        touches[pointer].down = false;
        return true;
    }
    return false;

@Override
public boolean touchDragged(int screenX, int screenY, int pointer, int button) {
    if (pointer < touches.length){
        touches[pointer].x = screenX;
        touches[pointer].y = screenY;
        return true;
    }
    return false;
}

```

Side Notes: It seems like your `update()` method would only work with a fixed framerate, which may make movement speeds different on different devices unless a fixed framerate loop is implemented elsewhere in the code. In addition, you may want to move `Gdx.input.setInputProcessor(this)` to the constructor of the Player class.

---
Tags: java, libgdx, movement, input
---


# Question
Title: Slick2D crashes on Image.getGraphics() on some machines
On some machines, creating a new Image and calling getGraphics() on it causes lwjgl to enter into some kind of faulty state that crashes when swapping buffers. Any idea what causes this and how to make Slick clean up after itself properly?

Reproduction code:

```
package crashrepro;

import org.newdawn.slick.*;

public class CrashRepro extends BasicGame {
    public static void main(String[] args) throws Exception {
        CrashRepro cr = new CrashRepro("CrashRepro");
        // Crash only happens in fullscreen mode.
        AppGameContainer agc = new AppGameContainer(cr, 800, 600, true);
        agc.start();
    }

    public CrashRepro(String title) { super(title); }

    @Override
    public void init(GameContainer gc) throws SlickException {}

    @Override
    public void update(GameContainer gc, int i) throws SlickException {}

    @Override
    public void render(GameContainer gc, Graphics grphcs) throws SlickException {
        Image img = new Image(128, 128);
        img.getGraphics(); // This crashes the game.
    }
}

```

Stack trace:

```
Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j  org.lwjgl.opengl.WindowsContextImplementation.nSwapBuffers(Ljava/nio/ByteBuffer;)V+0
j  org.lwjgl.opengl.WindowsContextImplementation.swapBuffers()V+35
j  org.lwjgl.opengl.ContextGL.swapBuffers()V+3
j  org.lwjgl.opengl.DrawableGL.swapBuffers()V+0
j  org.lwjgl.opengl.Display.swapBuffers()V+39
j  org.lwjgl.opengl.Display.update(Z)V+44
j  org.lwjgl.opengl.Display.update()V+1
j  org.newdawn.slick.AppGameContainer.gameLoop()V+78
j  org.newdawn.slick.AppGameContainer.start()V+17
j  crashrepro.CrashRepro.main([Ljava/lang/String;)V+27
v  ~StubRoutines::call_stub

```

# Answer
Turns out to have been caused by a lwjgl bug I reported here.
> 1 votes

---
Tags: opengl, graphics, lwjgl, slick
---


# Question
Title: Unity 5 Animator controls - What are their Unity 4 correspondent?
I am following a tutorial that is made with Unity 5, but claims to be compatible with Unity 4.6

I am working with the Animator panel, and I was wondering where could I find certain controls on the Unity 4 version. I highlighted them in a red square.

Basically stuff that has to do with duration of transitions and checking the transition as not having an exit time.

# Answer
> 0 votes
Exit Time is a condition parameter in Unity 4 -\> you'll have to add it / assign it to the specific transition you're working on.

The transition duration you can tweak using the timeline just below this in your image. The offset and interrupt are new features AFAIK.

Hope this helps.

---
Tags: unity
---


title: Delay in bullets

text:
# Question
Title: Delay in bullets
I made my character shoot but the amount of bullets he shoots is way too much. I'm trying to add a delay between bullets. I've tried this:

```
int shootTime = System.currentTimeMllis();

public void tick() {
    if(input.shoot && System.currentTimeMillis() - shootTime > 1000)
    {
        shootTime = (int) System.currentTimeMillis();
        shots.addBullet(new Bullet(xPos, yPos + 50));
    }
  ........
  ........
}

```

I'm sure I'm doing something stupid but this is not working.

# Answer
`currentTimeMllis` returns a `long` for the number of milliseconds *since Jan 7, 1970* (~1,425,579,434,000 at the time of this post!), not an `int` since program start, so that might be one problem.

Also, minor point of clarity, I'd suggest using something like:

```
long nextShot = 0;
long recoilTime = 1000;

public void tick() {
    if(input.shoot && System.currentTimeMillis() > nextShot)
    {
        nextShot = System.currentTimeMillis() + recoilTime;
        shots.addBullet(new Bullet(xPos, yPos + 50));
    }
// ...

```
> 0 votes

# Answer
How many milliseconds since Jan 1 1970? About 1425579436439. That's more than fits in a integer. You need to use a `long`.
> 1 votes

---
Tags: java
---