# Question
Title: Best approach for level specific textures
**TL;DR:** Best way to handle level-specific textures without overkilling memory usage and killing performance and keeping things clean in OpenGL for mobile (also lower-end devices) and desktop using power-of-two-textures. Any thoughts? (Check my idea in the update).

---

I'm developing a game for desktop and mobile using OpenGL and I've come to the point where I would like to add textures that are specific to one single level. Adding these textures to the atlas that is used in all levels feels wrong and is eventually a bad thing, since the amount of levels could become arbitrary large and so could be the amount of level-specific images, and thus the atlas would become too big.

So, I'm looking for a mechanism or approach to load/prepare/use level-specific textures. I've thought of a couple of solutions, but I don't like any of them:

* Use two textures: one global atlas and one level specific atlas. I don't like this because this would make it impossible to use textures of both atlases in one texture render batch. Using a cool shader that uses two samplers is something I don't like either, since samplers accessing by dynamic index is not allowed in a shader. The solution to this is to introduce an if-statement in the fragment shader. I would rather avoid that since I'm targeting a wide range of devices, so I would like to avoid branches in the shader.
* Use one big texture that contains the global atlas and a level-specific atlas. I don't like this because I don't know in advance how much space will be required for the level-specific textures. So I would have to greatly oversize this big atlas while not using it 95% of the time. The oversizing might be huge, since I'm using power-of-two-texture dimensions. Given the fact that my current atlas at lowest texture quality is already 1024x256 pixels large, and texture quality for iPad is already 2048x1024 pixels large. This approach would allow me to update a sub-area of the texture when loading the level and would require constant memory usage.

Of the two proposed techniques, I think I like the second one the most, however, the expensive memory usage might become a problem on some devices. There is one last technique I came up with while writing this question:

* Completely rewrite my rendering system so that I could render arbitrarily from each of both textures (global vs. level-specific) and the system would split the batches when a new texture should be bound. This would increase my number of OpenGL draw calls from let's say 10 to 16. This is not really an obstacle I think, however, I guess I would have to rewrite big parts of my rendering system and would take me probably a couple of days (since I'm also drawing plain (non-textured) geometry, using a different shader. This is done by 5 draw calls in by depth sorted layers: textures, geometry, textures, geometry, textures).

Has anyone experience with this? A good suggestion? A technique I didn't think of? Any input that might help me take a decision is welcome.

Thanks for reading and for help in advance,
Martijn

---

**Update** (possibly a good solution): When thinking about the last idea, I think that this might be the best solution, since that would solve some of my depth-sorting problems as well, since I'm bound to those 5 layers, I pretty much run every month of active development into the situation where the number of render layers I have available is too low for proper depth sorting. So this generic system to which you could submit arbitrary jobs would solve that. The system I'm thinking about sort of works like this:

1. Request a draw batch buffer of a certain type (global textures, level-specific textures or geometry).
2. The system checks if this type is the same as the last type, if so, just return the current buffer that is being built (and if the request size fits in the remaining buffer capacity). If not, submit the previous batch to the GPU (bind textures, configure shaders, etc) and return a new buffer of the requested type.
3. The requesting code gets the requested buffer of its type and fills it up.
4. Finally flush the last buffer to the GPU.

To keeps things fast, you should keep the amount of draw calls low, which ultimately comes down to intelligent depth sorting of the objects in the level editor. This seems no obstacle.

I think I like this approach pretty much. However, if people still want to share their own experience on this topic, that would be great.

# Answer
I've done it the way I described in the update of the question. I'll refer to that.
> 0 votes

---
Tags: opengl, textures, opengl-es2, optimization, memory-efficiency
---


title: Importing materials from blender to UE4

text:
# Question
Title: Importing materials from blender to UE4
So my problem is that I have a nice green glass material in blender which I imported to UE4 (4.8.1) but in the editor the material was just a simple green colour.

I have no idea what I should do to fix this problem.

I appreciate any help. If you need any more details or pictures, let me know.

Thank you

Glass in blender:

Material in blender:

Glass in UE4: Material in UE4:

# Answer
If you want to create a transparent material you have to make your material "translucent". Glass also has the property that its surface is very shiny, so you also have to change the "Translucency Lighting Mode" to "Surface", otherwise you can not control highlights on the surface.

Be sure to adjust the "Opacity" output pin of your material. You can have a look here for more information.
> 3 votes

---
Tags: blender, materials, unreal-4, unreal
---


# Question
Title: How can I enable flat surface reflections in UE4 on mobile?
Could someone please tell me how do I enable reflections on flat surfaces on a mobile in UE4? I have a simple room with one directional light. I need reflections on the tables and ground planes. I have tried every single setting and variation possible and nothing works.

I have tested the Sun Temple demo project and the Reflection Content Example demo project and nether of those projects have reflections on the mobile (iPhone 6). Those projects do have some kind of glare on the ground plans but noting close to what would be classified as a realistic reflection.

SSR does not work on mobile, neither do Sphere or Box Reflection captures. An alternative solution to get reflections working may be to use a Scene Capture Cube, but they don't work on mobile either.

UE4 is suppose to be an amazing game engine but it doesn't even offer the ability to support reflections on mobile. Reflections are quite simple to get running in Unity.

I have spent so much time trying to get reflections to work, and the worst thing is, every post or document that i have read about this subject does not offer a solution.

If someone could please confirm for me that reflections do not work on mobile or offer me a solution to get detailed reflections displaying on the ground and tables I would be so appreciative.

# Answer
> 1 votes
UE4 does not support real-time reflections because of its render strategy.

You can have pre-computer reflection with special reflection-caption spheres, but I guess they are turned off for mobile due to a) size constraints of the resulting files and b) performance constraints.

---
Tags: mobile, unreal-4, reflection-rendering
---


# Question
Title: Authoritative movement with client side prediction
I don't fully understand how client side prediction works with authoritative movement.

Let's say we have:

1. client at position(0,0)
2. server at position(0,0)

Now the client wants to move forward and calls a client side function `move` and then sends the server that the client wants to move forward.

Now the client has moved to `position(10,0),` while the server is still at `position(0,0)`. Now the server moves to `position(10,0)` and sends an update to all clients.

But the client has now moved to `position(20,0)` and now receives the position state from the server that the client should be at `position(10,0)`.

What happens now? The client can't just apply the position from the server otherwise the client would jitter around.

One simple solution that I could think of would be a distance check.

```
if(Distance(position(10,0),position(20,0) > SomeNumber){
   ForceUpdatePos();
}

```

But this is probably not a good idea because `SomeNumber` depends on the MovementSpeed and latency.

I probably also would have to include a timestamp of the package because maybe the client has not heard back from the server for several ticks and then receives a bunch of unordered position updates.

What is a common technique to solve this problem?

# Answer
The concept is that the new position is just predicted. When the next server-side position is received, client prediction is disabled. The client just guesses the future positions until the server verifies them.

Most game servers take the delay in account as well. In every client message the timestamp of the local player is sent. The server can now speed up the movement of the affected client character for a short period of time to conceal the delay between the input command of the player and the serverside movement which removes the jittering.
> 1 votes

# Answer
Input prediction generally works as following: Client sends commands to Server AND runs the same code as the Server to predict its actions. Client stores a number of timestamped commands. Now in the same step:

* Client receives new state from server.
* Client (knows its latency) rolls back in time for \[latency\] seconds (undo commands relative to \[latency\] seconds back).
* Client updates past state using received state (from Server).
* Client re runs commands to retrieve corrected present state.

In the server side: Server receives commands from Client. Server runs Client commands. Server sends new Client state.
> 1 votes

---
Tags: networking, multiplayer, movement-prediction
---


# Question
Title: How to enable and disable scripts on a Game Object?
This worked briefly yesterday, I believe I did something to mess this up. All my inputs that I put in are correct; therefor, it must be the code. I want to switch players. While the red cube's script is enabled and can move under the movement script I want the blue cubes movement script to be disabled and vice versus. Can you give me some insight into what I'm doing wrong? Please and thank you!!

```
using UnityEngine;
using System.Collections;

public class PlayerMovementScript : MonoBehaviour {

    public float speed = 2f;
    public float height = 2f;

    public Component playerMovement;
    public GameObject redCube;
    public GameObject blueCube;

    void Start()
    {
        var bc = blueCube.GetComponent<PlayerMovementScript>();

        bc.enabled = !bc.enabled;
    }

    // Update is called once per frame
    void Update ()
    {
        if (Input.GetButton ("Right"))
        {
            transform.Translate(Vector3.right * speed * Time.deltaTime);
        }

        if (Input.GetButton ("Left"))
        {
            transform.Translate(Vector3.left * speed * Time.deltaTime);
        }

        if (Input.GetButton ("Jump"))
        {
            transform.Translate(Vector3.up * height * Time.deltaTime);
        }

        var bc = blueCube.GetComponent<PlayerMovementScript>();
        var rc = redCube.GetComponent<PlayerMovementScript>();

        if (Input.GetButton ("Switch"))
        {
            bc.enabled = !bc.isActiveAndEnabled;
            rc.enabled = !rc.enabled;
        }
    }
}

```

# Answer
I eliminated the script's start function and just called the components in the update function.

```
var bc = blueCube.GetComponent<PlayerMovementScript>();
        var rc = redCube.GetComponent<PlayerMovementScript>();

        if (Input.GetButton ("Switch"))
        {
            bc.enabled = !bc.enabled;
            rc.enabled = !rc.enabled;

```
> 1 votes

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


# Question
Title: 2D World - How to represent my Game Objects graphically?
I want to code my own topdown 2D game with SFML+C++ that later shall have multiplayer functionality. Therefor I want to seperate the graphical and logical Parts of my game. All of my ingame Objects are thought to have Polygon-Hitboxes as their physical representation. What I now need is a graphical Representationn to draw them onto the Screen... I dont want to use tiles, because I want to have Support for rotated objects to and my Objects Are not evenly distributed so they wouldnt fit a grid.

My Question now is what would be the best way to graphically represent my Objects?

I thought of some ways but am not sure how you would ''normally'' do sth like that :)

Thought 1: As I only need two layers (For now(Floor and Things that you can collide with)) I thought my Floor could consist of tiles and then I draw my other Objects as sf::RectangleShapes or sf::Sprites onto it. (I would mix sprites and a more flexible approach here)

Thought 2: I only take sprites and include the objects that are ontop into each sprite that they should be drawn onto. (I think that it gets too messy and doesnt really ''solve'' my Problem)

Thought 3: I take each Object (Box, Part of the Floor(maybe each brick?)) and create an own textured sf::ConvexPolygon or sf::Rectangle for them. (Idk how big the impact on performance would be there)

PS: My approaches might seem a bit weird because I recently worked much with 3D-Software(eg Blender) and so I think of every Object to be a (2D) Mesh of Polygons that needs to be textured :)

I hope some of you can provide me some clarity on how to solve my Question :)

# Answer
Your best bet is probably Thought 1: A simple tile map and sprites. Unless you're going full-blown OpenGL then doing things like texturing quads is a bit overkill since you're already using a graphics library.

Also, you don't need to make a polygon for your hitboxes; a simple rectangle will do in most cases.
> 0 votes

---
Tags: c++, 2d, graphics, sfml
---


# Question
Title: How does matrix based game physics (collision detection & response) work?
I'm familiar with how to do collision detection and response using shape intersection tests, the separating axis theorem, and by using MPR and GJK with minkowski sums and support vector defined shapes.

I know that there is another way to do collision detection and response using matrices, but I don't know anything about it.

Can anyone explain to me the basics of how that works, or link me to some resources? I've been unable to come up with the right terms to ask google apparently.

Thanks!

# Answer
> 1 votes
The Wikipedia article on collision detection has this to say on the topic of matrices and collision detection;

> So we reduce the problem to that of tracking, from frame to frame, which intervals do intersect. We have three lists of intervals (one for each axis) and all lists are the same length (since each list has length n, the number of bounding boxes.) In each list, each interval is allowed to intersect all other intervals in the list. So for each list, we will have an n \times n matrix M=(m\_{ij}) of zeroes and ones: m\_{ij} is 1 if intervals i and j intersect, and 0 if they do not intersect.
>
> By our assumption, the matrix M associated to a list of intervals will remain essentially unchanged from one time step to the next. To exploit this, the list of intervals is actually maintained as a list of labeled endpoints. Each element of the list has the coordinate of an endpoint of an interval, as well as a unique integer identifying that interval. Then, we sort the list by coordinates, and update the matrix M as we go. It's not so hard to believe that this algorithm will work relatively quickly if indeed the configuration of bounding boxes does not change significantly from one time step to the next.

So it seems to me that you would use the matrices to store the results of various intersections gotten by more traditional calculations - IE, comparing points against bounding cubes.

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


# Question
Title: Sliding DOOM style collision resolution against arbitrary 2D geometry
I've been working on a HTML5 canvas raycasting engine for the web browser, with the end goal of making a simple FPS game in the style of the early 90s. The engine sits somewhere between Wolfenstein 3D and Doom in terms of complexity and capabilities - there are fixed-height floors and ceilings, skies, and wall geometry made using line segments, which can be non-orthogonal.

Development was going fairly well until I started trying to implement a simple 2D collision system. The collision detection itself is not a problem - I've written collision and vector maths modules which I've tested and have confidence in. The issue is resolving the collision in an acceptable manner. What I'm trying to make is a basic collision resolution algorithm which will detect when the player collider (circle) is colliding with one or more walls (line segments), and resolve the collision so the player slides along the wall(s) they are colliding with. Basically I want the exact same collision behaviour as DOOM has.

Some googling around led me to the following tutorial:

http://peroxide.dk/papers/collision/collision.pdf

This seemed to describe a method for achieving the desired collision response in a robust and pleasing way, but after a couple of weeks of trying various approaches, mostly following this tutorial's method, I'm still no closer to having a working implementation.

Rather than asking for code-specific advice on one of my failed implementations, I'm here looking for guidance from someone experienced in this sort of programming. I need to learn "The Right Way" to approach the problem, from someone who has got similar systems working before, and knows how it's meant to be done.

Any help is sincerely appreciated.

Here is a stable build of the game from just after I got the first basic collision resolution system working: http://188.226.167.230:346/raycaster.html

(Shrink your browser window to see the 2D map below the main game canvas. WASD and arrow keys, mouse support is dodgy at best, I think this build has 360 controller support but I can't remember.)

# Answer
> 1 votes
It's been a while since I did anything like this, but if I recall correctly you want to test a point on the circle against the line that defines the wall, and if the point has bypassed the line (IE, the line is closer to the center of the circle than the radius of the circle), a collision has occurred. The "pushing" effect comes from blocking the ability to move on a certain axis; IE, you're checking to see if the player has crossed the X boundary of the line and/or the Y boundary of the line, and if so, block movement on that axis. Since the player is still free to move along the non-blocked axis, they will "slide" along the wall if their movement velocity in that axis is non-zero.

---
Tags: physics, software-engineering, geometry, collision-resolution, collision-avoidance
---


# Question
Title: How do I ensure my custom TF2 model shows its texture?
I'm trying to make a new model for the Pyro's default Flamethrower, and I've run into a problem. When I load the new flamethrower model in HLMV or the game, I can't see the texture I made for it, all I see is the pink-and-black checkerboard.

I double-checked my QC, thinking I did something wrong, but the line that says where the texture is:
`$CDMaterials "models\weapons\v_flamethrower"`
is the same as the default (I even decompiled the default model and used its QC.)

The model is stored in the folder "\[Path to TF2 folder\]\tf\custom\newflamer\models\weapons\c\_models\c\_flamethrower\c\_flamethrower.mdl", and the texture is stored in "\[Path to TF2 folder\]\tf\custom\newflamer\models\weapons\v\_flamethrower\v\_flamethrower.vtf". Even still, all it gives me is the checkered texture.

I removed just the flamethrower model, and the texture still worked (although it was deformed because it was on the wrong model.) So the problem is in my QC. I'm not using a custom .vmt file, just a .vtf and .mdl.

Does anyone know what I did wrong, and how I can fix it?

# Answer
> 1 votes
Your issue is likely a mismatch between material name in the .mdl file and material name in the QC file. Open the decompiled flamethrower model in your 3D modeling program, copy the assigned material name text, and paste it so your new model has the same material name. I believe the stock flamethrower's material name is `models/weapons/c_items/c_flamethrower.bmp`.

From there, export your .mdl file and it should work without any issues, as long as everything else matches up.

---
Tags: source-engine
---


# Question
Title: How can the Unreal Development Kit be used with Android?
I've read the UDK will support Android development, I checked the download page on the site and found nothing related to Android.

also read that Dungeon Defenders Android game was built with Unreal engine.

so is there a way to use the UDK with Android ?

# Answer
> 5 votes
I think that only the licensees have the access to android part of udk as the below page clearly mentioned about this

**`Android support is available to full UE3 source licensees. If you are developing a UDK title and wish to explore moving from UDK to UE3 in order to target additional platforms, please contact the sales team at Epic to discuss our competitive terms and licensing options.`**

http://udn.epicgames.com/Three/MobileHome.html

But if you want to confirm you can probably ask this on there development forums to the people who have there games out there.

Here is the link to epics forum.

# Answer
> 2 votes
We are currently dealing with the licensing for our upcoming game, and how it works is this: You can build for android, but only from the source code. And guess how much it costs to buy a source code license...

$50,000 per platform. D:

Kickstarter time I suppose!

you can distribute for iOS for as little as $99, and $2500 for a commercial license if I remember correctly. This was according to my recent phone conversation with their licensing team.

It's a shame, but I understand why they have to do it. I assume they had to sign some huge deals with Apple to even be allowed to make games in UDK for iOS, because Apple's terms changed when Epic Citadel Came out. While Fragmentation is of course an issue, I guarantee Apple has something to do with the lack of Android support as well. Just speculation, but Id be surprised if I'm completely off base.

# Answer
> 1 votes
It seems that the UDK only support iOS for the moment and so there is no way to make it works on Android:

http://www.udk.com/mobile

As you say Dungeon Defenders was built with Unreal Engine and not with the UDK. According to Epic Game some problems such as performance and app size issues on Android prevent them to release an Android version of the UDK.

# Answer
> 1 votes
UE4 now supports Android AND has a new licensing program. Now its free, source code and everything, to develop games for any platform they support. They now charge a 5% fee on all gross revenue after the first $3000 per game per quarter. They currently support Android, iOS, web, Windows, Linux, and Mac OS.

# Answer
> -1 votes
Use Unity 3D instead of UDK, they support iOS and Android. Mattering which technologies your game needs will define the licensing levels (shader support requires pro licensing). Building for each platform is an add on. iOS development has to be done on Mac OSX due to Apples EULA. Lot less expensive than UE3.

UE3 is a more powerful platform, but more expensive. Unity has better cross platform support and is more than capable for most indie games, UE3 fits better with big budget games.

---
Tags: android, udk, unreal
---


title: Missing keyup event

text:
# Question
Title: Missing keyup event
I have a pretty generic input class. In the main app, I forward an event to the game. The game an input object that manages Keyup and Keydown presses. It stores the keys pressed in a `vector<key>` until the keyup function is called. For some reason, the keyup isn't always caught. I will add the relevant code, but let me know if you need more.

input.cpp

```
void Input::update() {

    //iterate held keys vector and perform held functions for them.

    for( std::vector<key>::iterator it = HeldKeys.begin(); it != HeldKeys.end(); it++ ) {
        std::map<key,std::function<void()>>::iterator func = OnHoldFuncs.find(*it);
        if( func != OnHoldFuncs.end() )
            func->second();
    }

}

void Input::KeyDown(SDL_KeyboardEvent pkey) {
    //Check the keyboard event if the key is held and return if it is.  We've already dealt with it.
    if( pkey.repeat == 1 )
        return;

    //Create the key object (struct is in header)
    key nkey(pkey.keysym.scancode,pkey.keysym.mod);

    //Look for registered call back on the keydown event
    std::map<key,std::function<void()>>::iterator func = OnDownFuncs.find(nkey);
    if( func != OnDownFuncs.end() )
        func->second();
    else
        std::cout << "unknown key " << pkey.keysym.scancode << " is pressed" << std::endl; //just debug message

    //look for held key function
    func = OnHoldFuncs.find(nkey);
    if( func != OnHoldFuncs.end() )
        HeldKeys.push_back(nkey); //function exist, store the key in the vector
    else {
        //to add a debug so I don't have to manually register keys right now for testing.
        RegOnKeyHold(pkey.keysym.scancode,pkey.keysym.mod,[=](){
            std::cout << "I AM BEING HELD AGAINST MY WILL " << pkey.keysym.scancode << std::endl;
        });
        HeldKeys.push_back(nkey);
    }

    return;
}

void Input::KeyUp(SDL_KeyboardEvent pkey) {
    //create key object
    key nkey(pkey.keysym.scancode,pkey.keysym.mod);

    //look for registered call back
    std::map<key,std::function<void()>>::iterator func = OnUpFuncs.find(nkey);
    if( func != OnUpFuncs.end() )
        func->second();
    else
        std::cout << "unknown key " << pkey.keysym.scancode << " is released" << std::endl; //debug msg

    for( std::vector<key>::iterator it = HeldKeys.begin(); it != HeldKeys.end(); it++ ) {
        if(*it == nkey) {
            HeldKeys.erase(it); //remove it from the vector
            break;
        }
    }

}

```

And the game.cpp, game is passed all events by default right now.

```
void Game::Handle(SDL_Event* Event) {
    switch(Event->type) {

    case SDL_KEYDOWN:
        input.KeyDown(Event->key);
        break;
    case SDL_KEYUP:
        input.KeyUp(Event->key);
        break;
    default:
        break;

    }

    return;
}

```

EDIT: Polling loop from application forwards all events to application Handle function. Here is the polling loop and handle function and game handle function.

```
while(GameState == RUNNING) {
    while(SDL_PollEvent(&Event)) {
        Handle(&Event);
    }

    Update();

    if( SDL_GetTicks() > Time + 100) {
        Render();
        Time = SDL_GetTicks();
    }
    else
    {
        SDL_Delay(1);
    }
}

```

Handle function that forwards to game for all cases but quit. Probably should forward that one too so the game can ask to save first or stop the quit.

```
void KApp::Handle(SDL_Event* Event) {

    switch (Event->type)
    {
    case SDL_QUIT:
        GameState = HALTED;
        break;

    default:
        game.Handle(Event);
        break;
    }

}

```

And the game handle function which handles all up and down events.

```
void Game::Handle(SDL_Event* Event) {
    switch(Event->type) {

    case SDL_KEYDOWN:
        input.KeyDown(Event->key);
        break;
    case SDL_KEYUP:
        input.KeyUp(Event->key);
        break;
    default:
        break;

    }

    return;
}

```

# Answer
> 1 votes
I'm using SDL-2 also. Your code, at a basic reading, looks all correct to me. To help debug it, you could put a switch or printf right in the main loop, like

```
while(GameState == RUNNING) {
    while(SDL_PollEvent(&Event)) {
        printTheEventIfItsKeyUpOrKeyDown(&Event); // as needed
        Handle(&Event);
    }

```

A modifier key down also generates an event (shift key is value 0x400000e1). Even with the shift-key down, and 'A' key press will be 0x61 (lower case 'a').

My main monster SDL-2-based loop looks like:

```
while (!quit)
{
    SDL_GL_SwapWindow(this->mainwindow);
    while (SDL_PollEvent(&e))
    {
        switch(e.type)
        {
            case SDL_QUIT:
                quit = true;
                break;

            case SDL_KEYDOWN:
            {
                int key = e.key.keysym.sym;
                switch(key)
                {
                   // ... some stuff
                }
                break;
            }

            case SDL_KEYUP:
            {
                int key = e.key.keysym.sym;
                switch(key)
                {
                   // ... some stuff
                }
                break;
            }
        }
    }
}

```

The only difference from your code is mine is monolithic...

Hope that may help a little bit.

---
Tags: c++, events, keyboard
---


# Question
Title: Smallest, most memory-efficient way to have tiles? (C++/OpenGL)
I need to have tiles in my game, just 16x16 images, there would be hundreds (or even thousands) that make up a level. Of course it's not viable to have thousands of memory-hog normal entities, but tiles are just repeated images. What's the most memory-efficient way to do tiles?

# Answer
Load each image once then bind the texture before you draw the tile. Efficiency can be improved if you only draw tiles that will be visible or partially visible by the camera.

http://docs.gl/gl4/glGenTextures

http://docs.gl/gl4/glGenerateMipmap

http://docs.gl/gl4/glBindTexture

```
void init()
{
    //load geometry
    //load textures

    //Setup entities (geometry buffer ids and texture ids)
    //glGenTexture is very similar to glGenBuffer/glGenVertexArray
}

void draw()
{
    Entity e = //...

    glBindTexture(e.textureID);
    glBindVertexArray(e.vaoID);

    glDrawArrays(...);
}

```
> 0 votes

# Answer
Honeybunch answered for video memory I believe, I'm not that familiar with GL. But to store a map like that in memory and eventually on disk you need to think about what you want with the map. If you have less then 256 types of tiles and nothing else simply use a unsigned bytes in a array (vector in c++ right?). Having thousands of tiles is not that special anyway, I'm currently drawing 10K on my phone and not doing it efficiently ;).
> 0 votes

---
Tags: opengl, c++, tiles, memory-efficiency, memory
---


# Question
Title: which state to add main menu for simple browser game with phaser
In which state should I add the main menu, or should i make it into another separate state? My main confusion here is how I manipulate states properly. Im a phaser/gamedev noob and I dont know how to start a game from the main menu syntax and mechanics-specific.

My idea for a main menu would be a simple background picture with a start button. But then, how do i jump start the game when the start button is clicked?

just for details, Im showing you this :

```
var game = new Phaser.Game(800,600, Phaser.AUTO, 'phaser-demo', {preload: preload, create: create, update: update, render: render});

```

# Answer
Unfortunately most of the tutorials you'll see will teach you some bad habits as far as state management goes. What you'll want to do here is **avoid the object literal state declaration** in favor of adding states from separate JS files in your index.html.

(Don't forget to include them as `<script>`'s as well.)

```
    var game = new Phaser.Game(800, 600, Phaser.CANVAS,'YourGameName');
    game.state.add("Boot", Boot);
    game.state.add("Preload", Preload);
    game.state.add("MainMenu", mainMenu);
    game.state.add("Play", Play);
    game.state.add("GameOver", GameOver);
    game.state.start("Boot");

```

I recommend reading the guide to Phaser state management here when it's finished.

Until then we're stuck with kinda skimpy tutorials like this one, that still do the job, but aren't ideal.
> 2 votes

# Answer
Jordan replied the question properly, I have given here some resource that might be helpful.

using state in Phaser

github template for phaser game

in-phaser-how-should-i-be-managing-state
> 1 votes

---
Tags: javascript, browser-based-games, phaser
---


# Question
Title: Is it possible to detect contact with every frame change when using an animation in SpriteKit?
Is it possible to detect contact with every frame change when using an animation in SpriteKit? For example, if I have two nodes of a person walking, I want to detect contact with the ground each time the frame changes (the character is walking on a surface). Just can't seem to get it.

I've tried using a for loop to add a physics body and the contact and collision properties to each node, but that doesn't seem to work. It detects contact once, but that's it. Anyone have any ideas?

Thanks in advance!

# Answer
> 0 votes
Set the `Person1` and `Person2` `SKPhysicsBody` a little smaller than the `SKSpriteNode`.

Then, add your `Person1` and `Person2` to update loop. You can do this by subclassing both `SKSpriteNode`s and then setting the `name` property to, for example, `person`. Implement a method in `Person1` and `Person2` that looks like this:

```
//Objective C
-(void)update:(CFTimeInterval)currentTime

//Swift
func update(_ currentTime: NSTimeInterval)

```

Then, in your `GameScene` \- that already has an `update:` method- use this to call `Person1` and `Person2` update methods:

```
//Objective C
[self enumerateChildNodesWithName:@"person" usingBlock:^(SKNode *node, BOOL *stop) {
    [(Person *)node update:currentTime];
}];

//Swift
self.enumerateChildNodesWithName("person", usingBlock: {
    (node: SKNode!, stop: UnsafeMutablePointer <ObjCBool>) -> Void in
    var person = node as? Person
    person.update(currentTime)
})

```

This will call `Persons update:` method each frame. Now we want to check in this `update:` if we are collisioning with the floor, for example, like this:

```
//Objective C
GameScene *parentScene = (GameScene *)self.parent;
if (CGRectIntersectsWithRect(self.frame, parentScene.floor.frame)){
    //Colliding with the floor.
}

//Swift
var parentScene : GameScene = self.parent as? GameScene
if(CGRectIntersectsRect(_ rect1: parentScene.floor.frame, _ rect2: self.frame){
    //Colliding with the floor.
}

```

You don't really need to call the `Person` update, you could check the collision in your `GameScene's update:` method, but it's always cleaner to subclass and implement it on the other class (or you will end with a really big update).

---
Tags: collision-detection, ios, spritekit, xcode, swift
---


# Question
Title: Animation package from Assert Store not working probably with Unity Model/Custom Model?
I downloaded the animation pack from here: https://www.assetstore.unity3d.com/en/#!/content/25794 The assert contains a fbx file, which contains a bunch of animations.

Then in Animator window I added a State and transitions between states and have set the Motion in the inspector of the state. Then I look at the preview in Animator's inspector with it original Model, the animation works properly:

If I apply Unity Model or my custom Model in the preview, its became:

Why is that? How can I fix it? Or did I use it incorrectly?

# Answer
> 0 votes
I just notice the animation package Model is set as Generic, in order to match the Unity Model its has to set as humanoid as well. Now is working perfectly fine!

---
Tags: unity, animation, models
---


# Question
Title: Getting positions of static entities in a Tiled Map
I'm creating a 2D game that uses a Tiled Map with an underlying 2D array to store where entities are in the world. At the moment, I'm just creating one instance of an entity, assigning it a number, and storing that in the array to determine what entity is at what position in the array/world. However, this is presenting some issues. The most prevalent being getting the position of an entity from the entity object, because there is only one object being used throughout the whole world.

Would it just be easier to have non-static entities and populate the array with many instances of the entity object or is there a simple way I could get the position of an entity on the tile map through the object?

# Answer
> 0 votes
Just store the position in the entity object as well. For dynamic objects I am using both arrays and I store the position of the object inside the object as well for various reasons. One reason is to use the array for drawing, if I only want to draw from coordinate (10,10) to (26, 19) because my screen does not reach the others anyway I can use the various arrays. But if I have an object and want to know it's position I have to iterate the whole array if I do not store it inside it.

Sometimes I just use vectors for storing the position but a much better way is to create your own point/coordinate class with equals and hashtag overrides to compare. You can put (static) methods in this class to convert from screen and camera coordinates which are often vectors to your points for easy shifting between them.

You know what? Here is a basic one I use:

```
public class Point {
    public int x;
    public int y;

    /**
     * Creates point
     * @param x X - coordinate
     * @param y Y - coordinate
     */
    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    /**
     * Creates point from world vector
     * @param v World vector
     */
    public Point(Vector2 v)
    {
        this.x = (int)(v.x / tileWidth);
        this.y = (int)(v.y / tileHeight);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Point point = (Point) o;

        if (x != point.x) return false;
        if (y != point.y) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = x;
        result = 31 * result + y;
        return result;
    }

    @Override
    public String toString() {
        return "Point: (" + x + ", " + y;
    }

    /**
     * Returns the world coorinate of the point.
     * @return world vector.
     */
    public Vector2 toWorld()
    {
        return new Vector2(x * tileWidth, y* tileHeight);
    }

    /**
     * Returns point from world vector
     * @param v World vector
     * @return
     */
    public static Point getPoint(Vector2 v)
    {
        return new Point((int)(v.x / tileWidth), (int)(v.y / tileHeight));
    }

    /**
     * Returns point from Vector3 where Z is discarded.
     * @param v world vector
     * @return
     */
    public static Point getPoint(Vector3 v)
    {
        return new Point((int)(v.x / tileWidth), (int)(v.y / tileHeight));
    }
}

```

The only thing you need is to hookup `tileWidth` and `tileHeight` to your variables. You might want to change the variables to private with get/set, but since they are only coordinates I like to have quick access to them.

-Edit-

Here is a basic example of how a Tile class looks like.

```
public class Tile {
    boolean walkable;
    //here I make use of "your way" to lookup the texture of this tile.
    int textureId;
}

```

when I want to create the map, I populate and draw the array:

```
Tile[][] tileMap = new Tile[width][height];
        for (int y = 0; y < width; y++)
        {
            for (int x = 0; x <= height; x++)
            {
                spriteBatch.draw(textureDictionary.get(tileMap[x][y].textureId), position, etc);
            }
        }

```

Now this is not much different then your method, only mine stores if the tile can be walked upon too. Your walls should probably never be walked upon and floors should so why bother changing to my method?

**Scalability** is the answer. What if you decide that you want to add objects to your map? If you have say 10 objects like tables, chairs, pillars, etc then for each int that represents a floor you need 10 more of those. Where I just add another int for the objects texture or perhaps the object itself if it has more properties like a tile.

Yes you could add another array to represent your objects and draw that over your tiles. But then you decide that object a can damage the player in a certain state. Now you need to make another array or a extra int to refer too. Where I change the behavior of a object in it's class. This is why you use a object oriented language anyway.

---
Tags: java
---


title: Need help with Physics

text:
# Question
Title: Need help with Physics
I'm using Unity to develop a game. Basically i want the player/rocket to follow a point on the screen where user touches. But It's based on physics. Force must be added when user touches somewhere and the rocket has to reach that point. Gravity is there too. If the rocket passes the point then it has to come by using forces. This is the game http://www.flashyland.com/219-jeux-flash-vol-Space-Oil.html (click the red button on the bottom left side and then green button. Arrow keys to play).

The rocket rotates too. I'm not good in physics at all.

# Answer
I may have interpreted what you want to do incorrectly, but it sounds like what you want to do is have the rocket rotate to look at a point, and then accelerate if the user is touching the screen. I'm not going to help you with the touch input part, but I will assist you in the rotation and actual movement as that seems to be what you asked for

What we need to do first is get the touches position, we need to get it in world space and we want it as a `Vector 2`. The touch will be in screen space, to convert we can simply run (assuming you have one camera):

```
Vector3 targetPos = Camera.main.ScreenToWorldPoint(touchPosition);

```

http://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html

Now we have the target position we need to figure out the size of the angle needed to point to targetPos

```
Vector3 dir = targetPos - transform.position;
float rotZ = Mathf.Atan2(dir.x, dir.y) * Mathf.Rad2Deg;

```

We call it rotZ because as we are in unity 2d we want to rotate on the z axis.

Next we need to do the actual rotation, for this we need a Rigidbody2D attached. We should access this in the start method of the script

```
Rigidbody2D RB;
void Start()
{
    //Other start work
    RB = GetComponent<Rigidbody2D>();
}

```

Now we have the rigidbody we can do the rotation, we will use the MoveRotation() Method

```
RB.MoveRotation(-rotZ);

```

Now the ship is pointing in the right direction we need to add the acceleration, to do this we can use RB.AddForceAtPosition

```
float Thrust = 5.0f //The amount of force used in the push
RB.AddForceAtPosition(transform.up * Thrust, transform.up);

```

Hopefully this helps you. I created the post using one of my old scripts, please note that it was used in a hackathon type thing to create a gimmicky control system, so that's why there's calls to retrieve web data. https://github.com/EverlessDrop41/GravityTest/blob/master/Assets/Scripts/Ship/ShipControll.cs

EDIT: After some discussion in chat we figured out increasing drag and thrust then having and overlap circle on the point to stop the acceleration on arrival did the trick
> 0 votes

---
Tags: unity, physics, touch
---


# Question
Title: Fragment shader compiling in webGL but not in OpenGL
I am programming in `Haxe` (language compiling to multiple platforms) and I have written some shaders.

My fragment shader runs fine in html5, but when I try to compile for native (OS X and/or Neko, a VM for Haxe) I get a shader compilation error, but no details (I am using `lime` which is a platform abstraction that does these things for me).

Here is the shader:

```
precision mediump float;

varying vec4 v_color;

void main() {
    gl_FragColor = v_color;
}

```

Very simple as you can see. It runs fine in webGL, but it seems it won't compile in OpenGL. I am no expert in shaders so I have no idea what might be wrong. Am I using some syntax that only exists in webGL?

Also just in case, here is my vertex shader (which compiles fine):

```
attribute vec3 a_position;
attribute vec4 a_color;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;

varying vec4 v_color;

void main() {
    gl_Position = uMVMatrix * vec4(a_position, 1);
    v_color = a_color;
}

```

# Answer
As suggested in the comments, the precision directives are not supported in the OpenGL version that haxe/lime compiles to.

Adding a `#version 130` doesn't work either, maybe haxe or lime doesn't read these I don't know.

Anyway I found the solution reading through the lime samples:

```
#if !desktop
"precision mediump float;" +
#end
"varying vec4 v_color;

void main() {
    gl_FragColor = v_color;
}

```

That's not really beautiful but it works. If someone knows a way to get precision in desktop shaders, that would be better though.
> 1 votes

# Answer
WebGL is based on OpenGL ES. Precision qualifiers (like "precision mediump float;") were introduced in OpenGL ES to optimize performance on embedded systems with lower hardware (like smartphones). In desktop OpenGL these precision qualifier do nothing. They only exist for compatibillity to OpenGL ES / WebGL. Source: https://www.opengl.org/wiki/Type\_Qualifier\_%28GLSL%29#Precision\_qualifiers

Pehraps you need a newer version of desktop gl to support those qualifiers?
> 0 votes

---
Tags: opengl, shaders, webgl
---


# Question
Title: How can check a collision between 2 non-axis aligned boxes?
I'm making a simple and easy game and I need to detect the collision between 2 boxes. It only needs to return trueor false, no physics involved.

I started working and couldn't find an algorithm that would check the collision for turned squares.

Here I visualized the problem.

As you can see squares 1, 2 and 3 would return true because they collide with the green squares. 4 would return false because it isn't colliding.

I do have all the squares of both colors in separate array lists.

Does anybody know a library or algorithm for this problem? Thanks in advance.

# Answer
> 2 votes
Box2D has a Java library. It might be a bit more than you need but it's pretty robust and used in all sorts of projects. Maybe someone else can recommend a better library solely for collision detection.

If you want to roll your own solution, which would probably be better if you want to keep it simple, you'll need to look into Oriented Bounding Box (OBB) collision detection. The Axis Aligned Bounding Box (AABB) algorithm is super simple but OBB is not nearly as nice. It requires a fair amount of math involving matrices so if you're not solid on that this is a great opportunity to learn.

Separating Axis Theorem (SAT) might be a bit much for 2d OBBs but it's a solid multi-purpose collision detection algorithm. Gilbert–Johnson–Keerthi (GJK) is another algorithm that's used more for objects that are in motion but may also be good for your needs.

Real-time Collision Detection by Christopher Ericson has some really great samples and the book is great for all things related to collision detection. The book actually has a really great example method that I don't think I can paste here because of copyright. However there are always more examples online.

http://rocketmandevelopment.com/blog/separation-of-axis-theorem-for-collision-detection/

http://back2basic.phatcode.net/?Issue\_%231:2D\_Convex\_Polygon\_Collision\_using\_SAT

# Answer
> 0 votes
You're assumption that you do not need any physics is wrong, anytime you are dealing with moving objects in 1D, 2D, 3D... environments and you need to detect if two objects will collide then you are doing physics calculations. You can not get away from it.

Returning true or false is easy, but figuring out if a collision has happened or not can range from simple to extremely complex. Let's say you have something like this:

```
class RenderModel {
private:
    Vector3 m_size;      // For 2D Set Z to 0 and Ignore
    Vector3 m_origin;    // Center Point Of The Model
    Vector3 m_position;  // Position In World Space
    std::vector<Vector3> m_vMeshCoordinates;
    std::vector<Vector2> m_vTextureCoordinates;

public:
   Model( Vector3& worldPosition, Vector3& size );
   virtual ~Model();

   virtual void render() = 0; // Purely Virtual
   virtual void update() = 0; // Purely Virtual

private:
    RenderModel( const RenderModel& c ); // not implemented
    RenderModel& operator=( const RenderModel& c ); // not implemented

}; // RenderModel

class Box : public RenderModel {
public:
    Box( Vector3& worldPosition, Vector3& size );
    virtual ~Box();

    virtual void render() override;
    virtual void update() override;

private:
    Box( const Box& c ); // not implemented
    Box& operator=( const Box& c ); // not implemented
}; // Box

```

Here we have a class hierarchy were RenderModel is abstract and can not be instantiated but a derived class can be. With this setup each model type would have to implement its own render & update function.

The render call will only draw its contents and the update function is where the object's world position will change.

If you are working with only a 2D environment then I would use an Edge Detecting system with simple ray tracing or Bounding Circles around each object and check the distance between each radius and if they intersect. You need to incorporate a property to these boxes or objects to define them if they are static or dynamic. All static objects will not move in the game or simulation. Anything dynamic will move.

```
Class WorldMap {
public:
    enum BoundingType {
        // 2D
        BT_BOUNDING_TRIANGLE,  // Rarely Used
        BT_BOUNDING_BOX,
        BT_BOUNDING_CIRCLE,
        BT_BOUNDING_ELIPSE,
        // 3D
        BT_BOUDNING_PYRAMID,   // Rarely Used
        BT_BOUDNING_CUBE,      // Doesn't Have To Be Perfect Cube Just A 3D Box
        BT_BOUNDING_CYLINDER,
        BT_BOUNDING_SPHERE
    }; // BoundingType

    enum CollisionType {
        CT_RAY_TRACE,
        CT_LINE_INTERSECTION,
        CT_SHAPE_TO_SHAPE_INTERSECTION
  }; // CollisionType

private:
    std::vector<std::shared_ptr<RenderModel>> m_vStaticObjects;
    std::vector<std::shared_ptr<RenderModel>> m_vDynamicObjects;
    Vector3  m_origin;  // Center Location of World
    Vector3  m_size;    // Size Of World for 2D set Z to 0 and ignore

    // ... other various world elements, objects, properties etc.

public:
    WorldMap();
    ~WorldMap();

    void render();
    void update();

    bool testCollisions( const RenderModel& modelTested, const Vector3& velocity, const enum BoundingType& bt, const enum CollisionType& ct,   );

}; // WorldMap

bool WorldMap::testCollision( const RenderModel& modelTested, const Vector3& velocity, const enum BoundingType& bt, const enum CollisionType& ct ) {
    // Here you would need different case statements based on bounding type
    // as well as collision type you are using.

    // The simplest for 2D is Circle against Circle, and you would return
    // true or false if their radius intersects at the given moment of detection.

    // Since this WorldMap Class has two containers of shared ptrs of Render Model Objects
    // where one is static and their world positions are fixed and
    // the other container are objects that can be moved around in the world;
    // these two containers will help you simplify and reduce the number of calls to test for collisions.

    // Since you know that the static container of objects will not move
    // you do not have to test them against another static object.

    // This leaves you with only testing Dynamic against Static and Dynamic against Dynamic.

    // If you want to get a little more advanced you can still use Circle to Circle
    // intersection and use the velocity direction vector to add in ray tracing
    // and if that ray doesn't see any other object then you know this object
    // will always return false and can skip it.

    // If the ray does intersect into another object then this object will probably
    // collide within a period of time.

    // You would then return true when the collision happens.

} // testCollision

```

The nice thing about ray tracing is due to the fact that it looks ahead the entire time in that direction. If their are no bounding shapes in its sight then no collision will happen, this is cheaper then testing each object against every other object!

Think of the ray tracing algorithm in this manner. Your character has a bow and arrow and when you fire the arrow, you do not want your collision detection system to have this arrow test against every single block object etc each frame for that is very expensive. So what you do is use this arrows velocity - facing direction of motion and use that ray. Then you test to see if any object is inline with that ray. If anything does come into contact with that ray (peeking ahead) then you know a collision is possible within a short period of time. Now in 3D this same concept will apply however the Ray will not exactly work because of the Parabola that the arrow will cause as it moves over a long distance versus time due to simulation of gravity, but for short distances it can still be applied. So what I would do is have two bounding circles around your object of interest to be detecting for collision. The first radius is very close and encompasses all edges of your model. This inner circle is when the collision takes place and returns true, the outer circle is a specified radius to check to see if a collision is near! The larger you make the outer circle will be more tests that will be called on this render frame, the smaller this circle the less tests there will be called this render frame but more frames will be called before collision is detected. Keep this in mind to keep a nice balance between the two otherwise it can lead to a bottle neck in your application because one thread is stuck in a for loop doing many calculations and other threads are waiting on it.

Here is a website for reference to simple 2D collision detection algorithms devmag

---
Tags: java, libgdx, algorithm, eclipse
---


# Question
Title: How to access Collider in c# script with its tag name
I want to access a Collider in c# script file with its tag name I Tried this

```
if (Collider2D == Physics2D.OverlapPoint(touchPos))
{
    Some Code to be Performed
}

```

I want to access this Collider2D with its Tag Name like this

```
if (GameObject.FindGameObjectWithTag("tag name") == Physics2D.OverlapPoint(touchPos))
{
    Some Code to be Performed
}

```

But Its not working Please Help...

```
public GameObject[] targets,targetss;

    void Start () {
        targets = GameObject.FindGameObjectsWithTag ("right screen");
        targetss = GameObject.FindGameObjectsWithTag ("left screen");
    }

    void Update () {
        if (Input.touches.Length <= 0) {

        } else {
            Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
            Vector2 touchPos = new Vector2(wp.x, wp.y);

            foreach(GameObject target in targets)
            {
                if (target.collider2D == Physics2D.OverlapPoint(touchPos))
                {

                    GameObject.FindGameObjectWithTag("player2").transform.position =
                    new Vector2(GameObject.FindGameObjectWithTag("player2").transform.position.x, wp.y);

                }
            }

            foreach(GameObject target in targetss)
            {
                if (target.collider2D == Physics2D.OverlapPoint(touchPos))
                {

                    GameObject.FindGameObjectWithTag("player1").transform.position =
                    new Vector2(GameObject.FindGameObjectWithTag("player1").transform.position.x, wp.y);

                }
            }

        }
    }

```

# Answer
> 1 votes
Stated that your examples clearest statement is "Some Code to be Performed" ... You must do some things:

Not confuse classes with objects

Search all objects ( istance not class) like this

```
public GameObject[] targets;
targets = GameObject.FindGameObjectsWithTag("tagName");

foreach (GameObject target in target) {
// get collider of each object
       if (target.collider!= null){
           if (target.collider.OverlapPoint(touchPos)){
              //Some Code to be Performed
           }
       }
}

```

# Answer
> 0 votes
There is something to correct, in my humble opinion..

When you do

```
public GameObject[] targets,targetss;
    void Start () {
            targets = GameObject.FindGameObjectsWithTag ("right screen");
            targetss = GameObject.FindGameObjectsWithTag ("left screen");
        }

```

parhaps you should do instead

```
public GameObject targets,targetss;
void Start () {
        targets = GameObject.FindGameObjectWithTag ("right screen");
        targetss = GameObject.FindGameObjectWithTag ("left screen");
    }

```

just because I assume you want to have ONE collider per side.

Then would be interesting to understand what you want to achieve. Here I assume again you want the circle to detect collision with side bars.

If the circle is moved with physics you should add to the side bars an

> OnCollisionEnter2D(Collider2D coll)

function to describe what is to be done when collisions occur.

---
Tags: unity, 2d, monodevelop
---


# Question
Title: Get current position of instantiated prefab
I wrote two little scripts to manage platform spawning. 1st - is attached to the Spawner gameObject. It's uset to spawn new platform. 2nd - is something like Platform Manager which not extend MonoBehaviour.

I want to set Spawner to create new platforms after old one goes off screen. But I dont know how to get current position of instantiated platform for example to check if platform is actualy off the screen.

Below my scripts:

1st. Spawner

```
void Update() {

    NewPlatform();
}

public void NewPlatform() {

    if (active) {
        newTransform = transform;
        PlatformManager.Instantiate(prefabs[Random.Range(0, prefabs.Length)], newTransform.position);
    }
}

```

}

2nd. PlatformManager

```
using UnityEngine;
using System.Collections;

public class PlatformManager {

public static GameObject Instantiate(GameObject prefab, Vector3 pos) {

    GameObject instance = null;

    instance = GameObject.Instantiate(prefab);
    instance.transform.position = pos;

    return instance;
}

```

}

Briefly - haw can I get current position of instantiated object (or other parameters) from Spawner script?

Thank you in advance.

# Answer
> 0 votes
Try attaching a script to your platform instances. Then in that scripts `Start()` method use `Debug.Log` to log the parent platforms `Transform`

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


title: How can I clearify users my controlls?

text:
# Question
Title: How can I clearify users my controlls?
In my game I use a really simple control mechanic to control a character on screen. But my problem is that users do not understand this control.

Beside a little delay problem they work this way:

> As soon as I do a swipe `+x` or `-x` my character moves left or right. And as long as I hold my finger it continuous to move to the direction in that I swiped. When I swipe into the opposite direction of my last swipe without leaving my finger from the touch ground, my character should move into this direction. When I release my finger from the touch screen, my character should stops instantly.

a) Do you think this mechanic could work, if my users learn to use it?

If yes: what would be the best way to show them how it works? A short video? Or some graphics? Maybe a tutorial level?

My concern is that it might be not a good mechanic, because people do not understand it when playing my prototype the first time. That could be because they only know swipe and tap, but not swipe-hold-swipe.

I do not know if there is a right answer or if it is just a question of opinions.

# Answer
Whenever a game introduces a relatively new or relatively unique control scheme, some users are definitely going to be confused. The easiest way to retain these users is by introducing and allowing them to test out the scheme in some sort of tutorial level, which may even just be a set of controllable graphics. So I'm going to say **Yes** on the tutorial level.
> 2 votes

---
Tags: ios, touch, control
---


# Question
Title: My "puck" model object falls right through the "table" model in jMonkeyEngine
So I am trying to learn jMonkey, I have understood everything so far, and I thought I understood how to make objects solid, so things can't go through each other. When I create my Collision shapes, I turn on the debugger which shows the shapes, and they appear correct. But when I run the code the puck falls right through the table and I have no idea why? I have been trying to learn from http://wiki.jmonkeyengine.org/doku.php/jme3:beginner:hello\_collision.

```
public class Main extends SimpleApplication {

    public static void main(String[] args) {
        Main app = new Main();

        AppSettings settings = new AppSettings(true);
        settings.setResolution(1024,768);
        settings.setFrameRate(60);
        app.setSettings(settings);

        app.start();
    }

    private BulletAppState bulletAppState;

    private RigidBodyControl    table_phy;
    private RigidBodyControl    puck_phy;

    @Override
    public void simpleInitApp() {

        bulletAppState = new BulletAppState();
        stateManager.attach(bulletAppState);
        bulletAppState.getPhysicsSpace().enableDebug(assetManager);

        DirectionalLight sun = new DirectionalLight();
        sun.setDirection(new Vector3f(-0.1f, -0.7f, -1.0f).normalizeLocal());
        rootNode.addLight(sun);

        cam.setLocation(new Vector3f(0.0f, -2.0f, 7.0f));

        initTable();
        initPuck();
        initPusher1();
        initPusher2();

    }

  //My hockey table
    public void initTable() {
        Spatial table = (Node)assetManager.loadModel("Models/airTable/airTable.j3o");
        table.setLocalTranslation(0.0f, -5.0f, -2.0f);
        CollisionShape tableShape = CollisionShapeFactory.createMeshShape((Node) table);
        table_phy = new RigidBodyControl(tableShape,0.0f);
        table.addControl(table_phy);
        rootNode.attachChild(table);
        bulletAppState.getPhysicsSpace().add(table_phy);
    }

    //My puck
     public void initPuck(){
        Spatial puck = assetManager.loadModel("Models/puck/puck.j3o");
        puck.setLocalTranslation(1.0f, -3.0f, 0.0f);
        CollisionShape puckShape = CollisionShapeFactory.createMeshShape((Node) puck);
        puck_phy = new RigidBodyControl(puckShape, 0.05f);
        puck.addControl(puck_phy);
        rootNode.attachChild(puck);
        bulletAppState.getPhysicsSpace().add(puck_phy);
    }
}

```

# Answer
> 1 votes
From testing you code with my own models the only thing I can think of is your puck is clipping with the table on load.

---
Tags: collision-detection, jmonkeyengine
---


# Question
Title: What's better - drawing every interval that the window updates, or drawing when necessary and updating when drawing?
So what's better?

In case the title is a bit confusing I mean:

1) Drawing every window update interval. For example, for a 60FPS window, every 17 milliseconds. For example:

```
window.setFramerateLimit(60); //Update every 17 milliseconds for 60FPS
while(window.isOpen()) {
window.display();
}

```

Or

2) Drawing when you need to (for example, when a sprite moves) and displaying it straight after. For example:

```
void func(sf::RenderWindow& window) {
window.draw(sf::Sprite()); //Whatever you're drawing
window.display();
}

```

Or is there a much better way?

# Answer
> 1 votes
You should draw everything, and swap the buffer (display), at most once per frame (usually 1/60th second).

You should definitely *not* call window.display() more than once per frame.

If nothing at all has moved, you might choose to skip drawing and displaying entirely for that frame, especially on a mobile device to conserve power. On a desktop, typically, may as well draw every frame, to keep the loading predictable.

Last note -- your game logic updates might or might not also be at the same 1/60th per second update. Easiest if they are, if possible.

---
Tags: opengl, sfml, c++
---


# Question
Title: Diagonal Movement with Pygame Rect Class
I have been using pygame and have been struggling to understand how to implement vectors and the pygame rect class to make an image move diagonally on the screen at the correct speed.I know it must be normalised else it moves at 2x the correct speed.I don't know how to implement vectors with pygame.rect.x and pygame.rect.y

This is the code I have so far

class Player(pygame.sprite.Sprite):

```
def __init__(self, location, *groups):
    super(Player, self).__init__(*groups)
    self.image = pygame.image.load('player.png')
    self.rect = pygame.rect.Rect(location, self.image.get_size())

    # movement in the X direction; positive is right, negative is left
    self.direction = 1
def update(self, dt, game):

    # take a copy of the current position of the player before movement for
    # use in movement collision response
    last = self.rect.copy()
    clock = pygame.time.Clock()

    # handle the player movement keys
    key = pygame.key.get_pressed()
    if key[pygame.K_LEFT]:
        self.rect.x -= 300 * dt
        self.direction = -1
    if key[pygame.K_RIGHT]:
        self.rect.x += 300 * dt
        self.direction = 1
    if key[pygame.K_UP]:
        self.rect.y -= 300 * dt
    if key[pygame.K_DOWN]:
        self.rect.y += 300 * dt

```

Thanks

# Answer
> 0 votes
A simple solution for your case without implementing vectors by yourself and it's common operations (although I'd recommend to learn about such subject) would be to normalize X and Y when going diagonal:

```
def update(self, dt, game):

    # take a copy of the current position of the player before movement for
    # use in movement collision response
    last = self.rect.copy()
    clock = pygame.time.Clock()

    # handle the player movement keys
    last = self.rect.copy()
    key = pygame.key.get_pressed()
    x, y = 0, 0
    if key[pygame.K_LEFT]:
        x = -300
        self.direction = -1
    if key[pygame.K_RIGHT]:
        x = +300
        self.direction = 1
    if key[pygame.K_UP]:
        y = -300
    if key[pygame.K_DOWN]:
        y = +300
    if x != 0 and y != 0:
        x = x*(math.sqrt(2)/2)
        y = y*(math.sqrt(2)/2)
    self.rect.x += x * dt
    self.rect.y += y * dt

```

For a 2d vector implementation this is an excellent class to have as reference: Vector2 libgdx

Hope I could help.

---
Tags: game-mechanics, python, pygame
---


title: Unity not showing full text

text:
# Question
Title: Unity not showing full text
This is simple issue, I'm trying to put in text, but it keeps cutting off, I found nothing in it's settings for text limited

Screenshot http://puu.sh/jbx9B/d6ab34678f.png

# Answer
> 1 votes
Vertical Overflow is set to Truncate. In other words, the text cuts off when it reaches the boundaries of the text element. Note the Height 30 above? That's the vertical boundary; you want that to be taller. You probably also want to make the element wider, so that it wraps at the edge of the window instead of in the middle.

---
Tags: unity
---


# Question
Title: How to calculate coordinates of ball when collided with a wall?
I'm developing a game like bubble shooter and need to implement bounce of ball off the vertical wall. I have the following inputs:

1. Starting position of bubble: `{left: 382, right: 378}`
2. Firing angle in radians: `1.34`
3. Game board sizes: `{width: 760, height: 620}`.

I have two walls to the left side of the bubble and to the right side of the bubble.

How could I calculate bubble's center point coordinates to stop it on collided left of right wall?

# Answer
I believe the simpler way would be to find the collision between the ray caster from the center of the bubble to two imaginary walls which are 1: left wall moved to the right by the radius of the bubble and 2: right wall moved to the left by the radius of the bubble.

The point where this ray (center of the bubble) hits any of the two imaginary walls will be the point where the bubble hits the real walls.

Hope this helps.
> 1 votes

---
Tags: game-mechanics, linear-algebra
---


title: How to load scene after a set delay?

text:
# Question
Title: How to load scene after a set delay?
**I have tried using IEnumerator and Invoke("method",delay\_in\_seconds).** My first scene is just an image with my studio name on it. I have script that will load the next scene **("Main Menu")** 3 seconds after the first scene is loaded. For this, I tried using IEnumerator and Invoke with 3 seconds delay before calling Application.LoadLevel.

However, on the device, game is launched, unity splash screen is displayed and "Main Menu" scene appears. it looks like the image scene loads while unity splash screen is displayed and by the time unity screen is completed, the image scene has done executing.

Is there any way to ensure a scene stays on screen before loading the next scene? I could add a button that player should tap to start game. But I don't want to do that.

# Answer
> 3 votes
Create your own timer, and attach it to the scene that is doing the image presentation. This is something that is very simple to do.

```
float delay = 3;

public Update()
{
    delay -= Time.deltaTime;
    if (delay <= 0)
        LoadLevel("NextLevelToLoad");
}

```

**EDIT**

Apparently mobile runs the Update() of the first loaded scene while the splash is running? I haven't personally confirmed this, but it is plausible.

If that is the case, possibly try tapping into OnPreRender to initiate your timer.

Code would be:

```
float delay = 3;
bool timerEnabled;

public Update()
{
    if (timerEnabled)
    {
        delay -= Time.deltaTime;
        if (delay <= 0)
            LoadLevel("NextLevelToLoad");
    }
}

void OnPreRender()
{
    timerEnabled = true;
}

```

# Answer
> 0 votes
It looks like there's a bug in Unity. I added another blank screen that would just load my image scene after 3 seconds.The blank scene doesn't show up, but my image scene is displayed.

---
Tags: unity
---


# Question
Title: Which opcodes are faster at the CPU level?
In every programming language there are sets of opcodes that are recommended over others. I've tried to list them here, in order of speed.

1. Bitwise
2. Integer Addition / Subtraction
3. Integer Multiplication / Division
4. Comparison
5. Control flow
6. Float Addition / Subtraction
7. Float Multiplication / Division

Where you need high-performance code, C++ can be hand optimized in assembly, to use SIMD instructions or more efficient control flow, data types, etc. So I'm trying to understand if the data type (int32 / float32 / float64) or the operation used (`*`, `+`, `&`) affects performance at the CPU level.

1. Is a single multiply slower on the CPU than an addition?
2. In MCU theory you learn that speed of opcodes is determined by the number of CPU cycles it takes to execute. So does it mean that multiply takes 4 cycles and add takes 2?
3. Exactly what are the speed characteristics of the basic math and control flow opcodes?
4. If two opcodes take the same number of cycles to execute, then both can be used interchangeably without any performance gain / loss?
5. Any other technical details you can share regarding x86 CPU performance is appreciated

# Answer
> 28 votes
Agner Fog's optimization guides are excellent. He has guides, tables of instruction timings, and docs on the microarchitecture of all recent x86 CPU designs (going back as far as Intel Pentium). See also some other resources linked from https://stackoverflow.com/tags/x86/info

Over on Stack Overflow, see also some basics about OoO exec meaning that the "cost model" can't be reduced to a single cost number for each instruction that you can just add up to find total cost in cycles.

---

Just for fun, I'll answer some of the questions (numbers from recent Intel CPUs). Choice of ops is not the major factor in optimizing code (unless you can avoid division.)

> Is a single multiply slower on the CPU than an addition?

Yes (unless it's by a power of 2). (3-4x the latency, with only one per clock throughput on Intel.) Don't go far out of your way to avoid it, though, since it's as fast as 2 or 3 adds.

> Exactly what are the speed characteristics of the basic math and control flow opcodes?

See Agner Fog's instruction tables and microarchitecture guide if you want to know *exactly* :P. Be careful with conditional jumps. Unconditional jumps (like function calls) have some small overhead, but not much. Branch prediction for control-flow is a much bigger problem than actually executing the instructions (to check the prediction once the inputs are actually ready.)

> If two opcodes take the same number of cycles to execute, then both can be used interchangeably without any performance gain / loss?

Nope, they might compete for the same execution port as something else, or they might not. It depends on what other dependency chains the CPU can be working on in parallel. (In practice, there's not usually any useful decision to be made. It occasionally comes up that you could use a vector shift or a vector shuffle, which run on different ports on Intel CPUs. But shift-by-bytes of the whole register (`PSLLDQ` etc.) runs in the shuffle unit.)

> Any other technical details you can share regarding x86 CPU performance is appreciated

Agner Fog's microarch docs describe the pipelines of Intel and AMD CPUs in enough detail to work out exactly how many cycles a loop should take per iteration, and whether the bottleneck is uop throughput, a dependency chain, or contention for one execution port. See some of my answers on StackOverflow, like this one or this one.

Also, http://www.realworldtech.com/haswell-cpu/ (and similar for earlier designs) is fun reading if you like CPU design.

Here's your list, sorted for a Haswell CPU, based on my best guestimates. This isn't really a useful way of thinking about things for anything but tuning an asm loop, though. Cache / branch-prediction effects usually dominate, so write your code to have good patterns. Numbers are very hand-wavey, and try to account for high latency, even if throughput is not an issue, or for generating more uops which clog up the pipe for other things to happen in parallel. Esp. the cache / branch numbers are very made-up. Latency matters for loop-carried dependencies, throughput matters when each iteration is independent.

**TL:DR these numbers are made-up** based on what I'm picturing for a "typical" use-case, as far as tradeoffs between latency, execution-port bottlenecks, and front-end throughput (or stalls for things like branch misses). **Please don't use these numbers for any kind of serious perf analysis**.

* 0.5 to 1 Bitwise / Integer Addition / Subtraction /
shift and rotate (compile-time const count) /
vector versions of all of these (1 to 4 per cycle throughput, 1 cycle latency)
* 1 vector min, max, compare-equal, compare-greater (to create a mask)
* 1.5 vector shuffles. Haswell and newer only have one shuffle port, and it seems to me it's common to need a lot of shuffling if you need any, so I'm weighting it slightly higher to encourage thinking about using fewer shuffles. They're not free, esp. if you need a pshufb control mask from memory.
* 1.5 load / store (L1 cache hit. throughput better than latency)
* 1.75 Integer Multiplication (3c latency/one per 1c tput on Intel, 4c lat on AMD and only one per 2c tput). Small constants are even cheaper using LEA and/or ADD/SUB/shift. But of course compile-time constants are *always* good, and can often optimize into other things. (And multiply in a loop can often be strength-reduced by the compiler to `tmp += 7` in a loop instead of `tmp = i*7`)
* 1.75 some 256b vector shuffle (extra latency on insns that can move data between 128b lanes of an AVX vector). (Or 3 to 7 on Ryzen where lane crossing shuffles need many more uops)
* 2 fp add/sub (and vector versions of the same) (1 or 2 per cycle throughtput, 3 to 5 cycle latency). Can be slow if you bottleneck on latency, e.g. summing an array with only 1 `sum` variable. (I could weight this and fp mul as low as 1 or as high as 5 depending on use-case).
* 2 vector fp mul or FMA. (x\*y + z is as cheap as either a mul or an add if you compile with FMA support enabled).
* 2 inserting/extracting general-purpose registers into vector elements (`_mm_insert_epi8`, etc.)
* 2.25 vector int mul (16-bit elements or pmaddubsw doing 8\*8 -\> 16-bit). Cheaper on Skylake, with better throughput than scalar mul
* 2.25 shift / rotate by variable count (2c latency, one per 2c throughput on Intel, faster on AMD or with BMI2)
* 2.5 Comparison without branching (`y = x ? a : b`, or `y = x >= 0`) (`test / setcc` or `cmov`)
* 3 int-\> float conversion
* 3 perfectly predicted Control flow (predicted branch, call, return).
* 4 vector int mul (32-bit elements) (2 uops, 10c latency on Haswell)
* 4 integer division or `%` by a compile-time constant (non-power of 2).
* 7 vector horizontal ops (e.g. `PHADD` adding values within a vector)
* 11 (vector)FP Division (10-13c latency, one per 7c throughput or worse). (Can be cheap if used rarely, but throughput is 6 to 40x worse than FP mul)
* 13? Control Flow (poorly-predicted branch, maybe 75% predictable)
* 13 int division (yes really, it's slower than FP division, and can't vectorize). (note that compilers divide by a constant using mul/shift/add with a magic constant, and div/mod by powers of 2 is very cheap.)
* 16 (vector)FP sqrt
* 25? load (L3 cache hit). (cache-miss stores are cheaper than loads.)
* 50? FP trig / exp / log. If you need a lot of exp/log and don't need full accuracy, you can trade accuracy for speed with a shorter polynomial and/or a table. You can also SIMD vectorize.
* 50-80? *always*-mispredicted branch, costing 15-20 cycles
* 200-400? load/store (cache miss)
* 3000??? read page from file (OS disk cache hit) (making up numbers here)
* 20000??? disk read page (OS disk-cache miss, fast SSD) (totally made-up number)

**I totally made this up based on guesswork**. If something looks wrong, it's either because I was thinking of a different use-case, or an editing error.

**Someone else's take on making a table like this** has a chart with cost-range bars (which look like throughput at the lower end, latency at the higher end of the range). But remember, you can't add up throughput numbers for two dissimilar operations and get meaningful results, if they can overlap. And the FP add vs. FP mul ranges look suspect; mulps and addps (and FMA) are literally identical in cost on Skylake and Ice Lake for example. Also the cost of a "virtual function call" highly depends on predictability, and the vtable being hot in cache.

The relative cost of things on AMD CPUs will be similar, except they have faster integer shifters when the shift-count is variable. AMD Bulldozer-family CPUs are of course slower on most code, for a variety of reasons. (Ryzen is pretty good at a lot of stuff).

Keep in mind that it's really **impossible to boil things down to a one-dimensional cost**. Other than cache-misses and branch mispredicts, the bottleneck in a block of code can be latency, total uop throughput (frontend), or throughput of a specific port (execution port).

A "slow" operation like FP division can be very cheap if the surrounding code keeps the CPU busy with other work. (vector FP div or sqrt are 1 uop each, they just have bad latency and throughput. They only block the divide unit, not the whole execution port that it's on. Integer div is several uops.) So if you only have one FP divide for every ~20 mul and add, and there's other work for the CPU to do (e.g. an independent loop iteration), then the "cost" of the FP div could be about the same as an FP mul. This is probably the best example of something that's low throughput when it's all you're doing, but mixes very well with other code (when latency isn't a factor), because of low total uops.

Note that integer division is not nearly as friendly to surrounding code: On Haswell, it's 9 uops, with one per 8-11c throughput, and 22-29c latency. (64bit division is *much* slower, even on Skylake.) So the latency and throughput numbers are somewhat similar to FP div, but FP div is only one uop.

For examples of analysing a short sequence of insns for throughput, latency, and total uops, see some of my SO answers:

IDK if other people write SO answers including this kind of analysis. I have a much easier time finding my own, because I know I go into this detail often, and I can remember what I've written.

# Answer
> 16 votes
It depends on the CPU in question, but for a modern CPU the list is something like this:

1. Bitwise, addition, subtraction, comparison, multiplication
2. Division
3. Control flow (see answer 3)

Depending on CPU there may be a considerable toll for working with 64 bit data types.

Your questions:

1. Not at all or not appreciably on a modern CPU. Depend on CPU.
2. That information is something like 20 to 30 years outdated (School sucks, you have now got proof), modern CPUs handle a variable number of instructions per clock, how many depend on what the scheduler come up with.
3. Division is a bit slower than the rest, control flow is very fast if the branch prediction is correct, and very slow if it is wrong (something like 20 cycles, depend on CPU). The result is that a lot of code is limited mainly by control flow. Don't do with an `if` what you can reasonably do with arithmetic.
4. There is no fixed number for how many cycles any instruction take, but sometimes two different instructions may perform equally, put them in another context and maybe they don't, run them on a different CPU and you are likely to see a 3rd result.
5. On top of control flow the other big time waster is cache misses, whenever you try to read data that is not in cache the CPU will have to wait for it to be fetched from memory. In general you should try to handle data pieces next to one another simultaneously rather than picking data out from all over the place.

And finally, if you are making a game, don't worry too much about all this, better concentrate on making a good game than chopping CPU cycles.

# Answer
> 3 votes
I made a test about integer operation witch looped a million times on x64\_64 , reach brief conclusion like below,

add ---116 microseconds

sub----116 microseconds

mul----1036 microseconds

div----13037 microseconds

the data above have already reduced the overhead induced by loop,

# Answer
> 2 votes
The intel processor manuals are a free download from their website. They are fairly large but technically can answer your question. The optimization manual in particular is what you are after, but the instruction manual also has the timings and latencies for most of the major CPU lines for simd instructions since they vary from chip to chip.

In general I would consider full branches as well as pointer-chasing (link list traverals, calling virtual functions) the top to perf killers, but the x86/x64 cpus are very good at both, compared to other architectures. If you ever port to another platform you will see how much of a problem they can be, if you are writing high performance code.

---
Tags: c++, performance, optimization
---


title: What you think about Digital-Tutors?

text:
# Question
Title: What you think about Digital-Tutors?
I want to ask if there is any one try Digital-Tutors site as content

i see it's very good but i want to make sure before i rush into it .

# Answer
This is very subjective. Digital Tutors is very good tutorial site offering top quality tutorial. It can teach you how to use a tool and goes on showing how they use it. But in the end it is not the tool that creates the art, it is you using the tool and be creative with it. That is something nobody can teach you.

Digital tutors does have tutors and specialized learning methods other then your average youtube playlist. However I cannot judge the quality of that but I expect it to be good. I come from the time 3Dbuzz was a free source of knowledge. It teached me a lot of things. They had free courses you could enter and learn from others. It definitely helped me understand the tools so I guess Digital Tutors does too.
> 1 votes

---
Tags: unity, game-design
---


title: Marketing PC/Android 2d Physics Game

text:
# Question
Title: Marketing PC/Android 2d Physics Game
I've been working on a game for couple years now, its fairly original, has definite potential within an indie market, and appeal for the masses also.

I want to deploy on Android and PC, green-light it on steam and looking into Kickstarter. I'm also going to set up a website where it can be played, have a dedicated server to link 'matches' and post demos on sites like mofunzone and armorgames.

I've used Jbox2d, and am also curious about the licencing with this engine and can't seem to find documentation on that.

I'm almost done the 'demo' and my question is, how should I market it?

I was thinking I'd make the game free on android, charge something like $10 on steam, and charge say 1$ month to play online (for the pc version)

If anyone has any good links, research or advice from personal experience, it would be greatly appreciated.

# Answer
> 2 votes
Why would you make the game free on android and let PC users pay $10 + $1/month?

The big trend for most indies is building a fanbase as soon you have something to show from your game. Blogging about everything that involves your game and perhaps let your fans influence your design.

You can find a lot of sources at open indie developers like Grid Sage Games. They just released there game Cogmind two month's ago and started blogging about it in September 2013. They just released sales information less then a month ago and you see that a fan base can greatly impact your initial sales. But not every game fits the bill to create a dedicated fan-base like Cogmind.

There are some great articles on gamedev.net, two new ones talk about launching your game and analytics. Perhaps the best thing to know is how not to do it. There is basically a ton of information laying around.

Good luck with your games launch!

---
Tags: android, game-design, box2d, marketing, advertisements
---


# Question
Title: How can zoom into my object when that object is being clicked?
Suppose that I have the three game(cube,Quard,sphere) object. When I click on a particular game object suppose think I have clicked on the cube,the cube object should get zoomed in on the screen.

how can I do that?

How do I center and zoom into my cube game object after selecting the cube? I think it has something to do with the camera but how do I center the view with the camera?

I have used the below code for zooming the object.For one object its working.But when I place different object and apply this code then when i click on one object all the three object is getting zoomed.

Can anyone help me out in solving this issue

Here is the code

```
  function OnMouseDown()
{
 OrthoZoom(1.5);
}
function OrthoZoom(size : float) {
 var cam = Camera.main;

 while (cam.orthographicSize != size) {
     cam.orthographicSize = Mathf.MoveTowards(cam.orthographicSize, size, speed * Time.deltaTime);
     yield;
 }

```

}

# Answer
One way to solve this, is by parenting the object to the camera, when the object receives the *OnMouseDown* signal.

This could look similar to this:

```
function OnMouseDown()
{
    Camera.main.transform.parent = this.transform;

    // Optionally, set some flag and smoothly move towards a Vector, same with the size
    Camera.main.transform.position = someVector;
    Camera.main.transform.orthographicSize = sizeBasedOnCurrentObject();
}

```

Note, that the pivot of the object itself, should be centered for this to be "truly" centered.

You will also have to calculate *someVector*, based on the current Camera's transforms. E.g. if the Camera's viewing ray is equal to (0,0,1), *someVector* should be (0,0,z), where z should be great enough to not lie inside the centered object.
> 1 votes

---
Tags: unity, javascript
---


title: What's wrong with my HLSL depth shader?

text:
# Question
Title: What's wrong with my HLSL depth shader?
I'm trying to render depth texture in XNA 4.0. I'm read few different tutorials several times and realy cannot understand what I'm doing wrong.

Depth shader:

```
float4x4 WVPMatrix;

struct VertexShaderOutput
{
    float4 Position : position0;
    float Depth : texcoord0;
};

VertexShaderOutput VertexShader1(float4 pPosition : position0)
{
    VertexShaderOutput output;
    output.Position = mul(pPosition, WVPMatrix);
    output.Depth.x = 1 - (output.Position.z / output.Position.w);
    return output;
}

float4 PixelShader1(VertexShaderOutput pOutput) : color0
{
    return float4(pOutput.Depth.x, 0, 0, 1);
}

technique Technique1
{
    pass Pass1
    {
        AlphaBlendEnable = false;
        ZEnable = true;
        ZWriteEnable = true;

        VertexShader = compile vs_2_0 VertexShader1();
        PixelShader = compile ps_2_0 PixelShader1();
    }
}

```

Drawing:

```
this.depthRenderTarget = new RenderTarget2D(
    this.graphicsDevice,
    this.graphicsDevice.PresentationParameters.BackBufferWidth,
    this.graphicsDevice.PresentationParameters.BackBufferHeight);

...

public void Draw(GameTime pGameTime, Camera pCamera, Effect pDepthEffect, Effect pOpaqueEffect, Effect pNotOpaqueEffect)
{
    this.graphicsDevice.SetRenderTarget(this.depthRenderTarget);
    this.graphicsDevice.Clear(Color.CornflowerBlue);
    this.DrawChunksDepth(pGameTime, pCamera, pDepthEffect);

    this.graphicsDevice.SetRenderTarget(null);
    this.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, SamplerState.PointClamp, null, null);
    this.spriteBatch.Draw(this.depthRenderTarget, Vector2.Zero, Color.White);
    this.spriteBatch.End();
}

private void DrawChunksDepth(GameTime pGameTime, Camera pCamera, Effect pDepthEffect)
{
    // ...

    this.graphicsDevice.RasterizerState = RasterizerState.CullClockwise;
    this.graphicsDevice.DepthStencilState = DepthStencilState.Default;

    // draw mesh with pDepthEffect
}

```

Result:

As I see output.Position.z always equals output.Position.w, but why?

# Answer
> 1 votes
> If you work out your matrix math, you'll see that the resulting w component of a vector/matrix multiplication depends on what's in the 4th column of the matrix. If the last column is \[0 0 0 1\] (which it typically is for most translation/orientation matrices), then the w component will be whatever the w component of the vector was. However for a typical perspective projection matrix, the last column will be \[0 0 1 0\]. This means it will be equal to the z component of the vector, which in this case means that w will be the view-space z value of the vertex position.

This means that if you are using a typical projection matrix, position.z = position.w. Instead maybe you could try passing the maximum Draw Distance of the current camera to the shader and divide position.z by that. That way you'll get a smooth transition from closer to further depth.

---
Tags: xna, hlsl, depth
---


title: Creating interiors in Unity

text:
# Question
Title: Creating interiors in Unity
I'm trying to use the vanilla Unity Editor to make some interiors (with primitives like cubes etc). It's a hard process by itself because you have to do all sorts of calculations for scale and position of the primitives but it gets worse when I have to make a door or a window, which requires me to divide a primitive into smaller ones and do even more calculations (again, all by hand, which usually come out wrong and make the game look like crap)

How can I avoid this whole process? Is there a way to simply slice a primitive like you do in BSP mapping?

# Answer
Is there any reason you are using primitives over meshes? The engine shines if you import custom models. So you can avoid the tedious process of modeling in unity by modeling in a program that is actually designed for that.

The only other way I know off creating something like a door in unity without using multiple primitives is coding a mesh for it by hand. Which is probably even worse then your method.
> 2 votes

# Answer
What you try to do is practically impossible. The primitives are there just for prototyping/placeholders. You will have to "get" those from outside of Unity. Or you can look at asset store, there are some assets sold that can do limited 3d modeling.
> 1 votes

# Answer
To build level geometry within Unity, probably the best tool available is ProBuilder: http://www.protoolsforunity3d.com/probuilder/

However, the usual approach is *don't* build your level geometry within Unity. Build the level geometry in a 3D modeling tool, like Maya or Blender, and import that into Unity.
> 1 votes

---
Tags: unity, level-design, map-editor
---


# Question
Title: libgdx continuous movement while touch and hold (even after jump)?
So, I have these buttons where I have implemented a method to handle 'touch and hold' (without polling). If the player touches and holds the walk button ..it will keep walking till the button is released. Problem is when I combine jump with it ...
In the update method,

```
if (activeTouch) {
        translateScreenToWorldCoordinates(touchCoords.x, touchCoords.y);
         if (touchPoint.x < 5) {
           // Code for walk left
        } else if (touchPoint.x > VIEWPORT_WIDTH - 5)
        {
            // Code for walk Right
        } else if ((touchPoint.x > 6 && touchPoint.x < VIEWPORT_WIDTH - 6) && player.isGrounded() && player.getState() != Player.State.Falling) {
           // Code for Jump
        }
    }

```

The touchdown and touchup events,

```
 public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        touchCoords.set(screenX, screenY);
        activeTouch = true;

        return false;
    }

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

```

So i can move right,left and also jump. But my problem is, while walking if I jump ... it will jump and then stop walking. How to continue walking after the jump if the player is still holding onto the walk button?

# Answer
You should register the pointer you are walking with. Pointers are the number of touches on the screen and they are provided by the listeners you are using.

I think if you change this it to something like below you can get it to work:

```
@Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        if (int pointer != 0) //Guessing first is 0, might be 1.
        {
            activeTouch = false;
        }
        return false;
    }

```

Just log the pointers to see the output and set accordingly.

But why do you need the active touch? Coding the movement straight into the listeners is no problem. Or better to make two extra methods for walking and jumping. I cannot look into the rest of your code but something like this should work. The listeners only trigger when there are actual touches so do not bother setting up a boolean for that.

```
private void move(screen x, screen y)
{
    translateScreenToWorldCoordinates(touchCoords.x, touchCoords.y);
    if (touchPoint.x < 5) {
           // Code for walk left
        } else if (touchPoint.x > VIEWPORT_WIDTH - 5)
        {
            // Code for walk Right
        }
}

private void jump(int screenX, int screenY)
{
    translateScreenToWorldCoordinates(touchCoords.x, touchCoords.y);
    if ((touchPoint.x > 6 && touchPoint.x < VIEWPORT_WIDTH - 6) &&
        player.isGrounded() && player.getState() != Player.State.Falling)
    {
           // Code for Jump
    }
}

```

Then just add both to the listener.

```
public boolean touchDown(int screenX, int screenY, int pointer, int button)
{
        move(screenX, screenY);
        jump(screenX, screenY);
        return false;
}

```
> 2 votes

---
Tags: android, libgdx
---