# Question
Title: Should clients in an online game access the database directly or through a game server?
first im total noob about c# and mysql. Just trying to find which way is better. i believe your answers prevents me from losing plenty of time.

* Online game(not more than 50 users at pre-alpha. Not expecting than 500+ at the end.)
* Text based game / console like ( minimum graphics )
* PVP -\> Players are able to destroy other players.
* Simlpy a hacking simulation.
* There will be some servers.(NPC servers and player made servers)
* players can reach that servers made by other players.

Q: Which one is the good way to store that servers data?

game client --\> Mysql server ?
or game Client --\> a Server Client(which is localy running a mysqL server)

If it's totaly wrong to use mysql server how can i make it? Thank you...

# Answer
First of all, I think this question belongs more likely to Security.SE since you are asking about to expose or not a public database server.

Said that, I strongly recommend to **NEVER, EVER AND EVER** expose publicly a database server unless you know what you are doing and you know who you grant access. The key reason to recommend that is security and integrity of the database. Take a look around these tags on Security.SE to get an idea of what could happen:

Another reason to not to connect to a database server through the Internet is performance. Most databases servers' access protocols are so heavyweight to use as those tend to keep the connection alive, which is a end-to-end resources waste unless you close the connection explicitly.

Since you are developing a text-based game in the way that a player enters a command and waits to receive a response before thinking about the next step, a better way to manage your game data and make it accessible to your users could be to develop a public HTTP(S) REST API on your server with session control that provides a secure interface between your database server and your players game client.

**EDIT:** Other reason to develop a HTTP(S) REST API for your online game is because this way you will be able to develop and deploy your game for other devices and OSes, like Android and iOS, which doesn't allow the apps to open outgoing connections with most of (if not every) database server protocols.
> 3 votes

# Answer
Having a client connect to a database directly is never a good idea for security reasons.

Keep in mind what audience you attract and in what mindset you put them when you create a hacking-themed game. They *will* try to find security vulnerabilities in your game. Some might even mistake it for the intended way of playing it. So you need to implement security-by-design from the get go.

The permission handling system of MySQL is not fine-grained enough to control what the client can and can't do on a field level. You don't want me to do a query like `UPDATE scores SET score = 99999999999 WHERE player = "Philipp"`. You will need to do a plausibility check first if I actually did something to deserve that score. Actually, you shouldn't allow me to tell the server my score at all. All I should be able to send to the server is what I *intend* to do. The server then calculates

1. if I actually can do that right now
2. what effects my action has on the game state
3. which of these effects I should know about

and then tell me the result.

And you certainly don't want me to execute queries like `DELETE players WHERE player = "Corviuse"`.

And please don't believe that you can control what the player can and can't do and know about on the client. The player could simply develop their own client software, which does not sound particularly hard considering that you intend it to be "Text based game / console like ( minimum graphics )". There is no way for you to check if the player is actually running your software or a clone of it.

That being said, it is possible to implement all these checks I wrote above as stored procedures in MySQL and only give players the permission to interact with the database through these stored procedures. But stored procedures are an advanced feature of relational databases and the language is not vey suitable for writing complex game mechanics. So when you are a "total noob" as you say you will likely have enough on your plate with writing normal SQL queries.
> 1 votes

---
Tags: c#, text-based, mysql
---


# Question
Title: How to disable play automatically on animation in Unity3d 4.5.1
Where is the option to disable the 'Play Automatically' function for animations in Unity3d 4.5.1. In previous versions, there was a button under the Animation tab to disable the play automatically:

But now in Unity3d 4.5.1, there is no 'Play Automatically' checkbox, instead this is here:

If anyone knows how to disable the play automatically in this version of Unity, I would really appreciate if you could explain how to do it and where to go to do it because I am pretty new to Unity and am not too sure where things are. Thanks!

# Answer
With new animation system, animations are handled by `AnimatorController` component.

If your animation start automatically, it means that the clip is the default one (orange color) in the controller graph. To prevent this on Behavior on start you have 2 way:

1. Keep AnimatorController component disabled until you don't need it.
2. Use an empty state with no clip as default (inside the controller): transition to your animation clip must be explicitly activated
> 4 votes

# Answer
It seems that the title went from Animation to Animator which seems to indicate that you might need to look at a different menu. I found this in the unity manual. Perhaps look for an Animation menu.
> 0 votes

# Answer
I think you can make an empty transition and set that as the default transition and in JavaScript type this:

```
 var FallerObject : GameObject;

 function OnTriggerEnter (Other : Collider){
   if(Other.gameObject.tag == "Player"){
     FallerObject.animation.Play("TypeAnimationNameHere");
   }
}

```

It will play the animation when you collide with the object that has the tag of: `"Player"` and will play the animation that `FallerObject` has.
> 0 votes

---
Tags: unity, 3d, animation
---


# Question
Title: Player position not updating when referenced in seperate class?
In my player class I have my players position set to update when you tap the directional keys, that works fine, but when I access my Players position variables, in my projectile class constructor, they aren't updating, I don't know why. In my main.cpp file,I update my players position before I update the projectiles position. I want the projectile to look like its being shot by the player, So I am trying to make the projectile be in front of the player and move with the player.

Player class:

```
Player::Player()
{
    Health = 100;
    Position.x = Position.y = 0;
    Position.w = Position.h = 100;
}

void Player::Update(SDL_Renderer* rend)
{

    //saves keystates for the player
    const Uint8* keyState;
    keyState = SDL_GetKeyboardState(NULL);

    //Use the key board
    if (keyState[SDL_SCANCODE_LEFT])
    {
        Position.x -= moveSpeed * playerAnimation.deltaTime;

    }
    if (keyState[SDL_SCANCODE_RIGHT])
    {
        Position.x += moveSpeed * playerAnimation.deltaTime;
    }
    if (keyState[SDL_SCANCODE_UP])
    {
        Position.y -= moveSpeed * playerAnimation.deltaTime;

    }
    if (keyState[SDL_SCANCODE_DOWN])
    {
        Position.y += moveSpeed * playerAnimation.deltaTime;
    }
    //Make sure that player does not go out of bounds
    if (Position.x > 700)
        Position.x = 700;

}
SDL_Texture* Player::Draw(SDL_Renderer *gRender)
{
    playerTexture = LoadTexture("shipAnimation.png", gRender);
    playerAnimation.Animate(playerTexture, 8, 1, gRender,Position);
    return playerTexture;

}

```

Projectile Class:

```
Projectile::Projectile(SDL_Renderer* render)
{
    projectileTexture = LoadTexture("laser.png", render);
    /*SDL_QueryTexture(projectileTexture, NULL, NULL, &width, &Height);*/
    Active = true;
    Damage = 2;
    projectileMoveSpeed = 20.0f;
    //ProjectilesPostion.x = playersPosition.x + PlayersPosition.w divided by 2
    projRect.x = p.Position.x + p.Position.w / 2;
    projRect.w = projRect.h = 100;
    projRect.y = 0;
    fireTime = 0.15f;

}
void Projectile::Update()
{
    projRect.x += projectileMoveSpeed;
    if (projRect.x + projRect.w / 2 > 800)
        Active = false;
}
void Projectile::Draw(SDL_Renderer* render)
{
    SDL_RenderCopy(render, projectileTexture, NULL, &projRect);
}
void Projectile::DrawProjectile(SDL_Renderer* render)
{
    for (int i = 0; i < projectiles.size(); i++)
    {
        projectiles[i]->Draw(render);
    }
}
void Projectile::AddProjectile(SDL_Renderer* render)
{
    projectiles.push_back(new Projectile(render));
}
void Projectile::UpdateProjectiles(SDL_Renderer* render)
{

    for (int i = 0; i < projectiles.size(); i++)
    {
        projectiles[i]->Update();
        if (projectiles[i]->Active == false)
        {
            projectiles.erase(projectiles.begin() + i);
        }
    }
    if ((SDL_GetTicks() - previousFireTime)/1000.0f > fireTime)
    {
        //Reset our current time
        previousFireTime = SDL_GetTicks();
        //Add Projectile
        AddProjectile(render);
    }
}

```

Main.cpp

```
int main(int argc, char* args[])
{
    SDL_Window *window = nullptr;
    SDL_Renderer *gRenderer = nullptr;

    if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
        std::cout << "video initialization error: " << SDL_GetError() << std::endl;

    window = SDL_CreateWindow("Shooter", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, ScreenWidth, ScreenHeight, SDL_WINDOW_SHOWN);
    gRenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    ParallaxingBackground mainbg("mainbackground.png", gRenderer);

    Enemy enemyobj(gRenderer);

    if (window = NULL)
        std::cout << "Window creation Error: " << SDL_GetError() << std::endl;
    bool isRunning = true;
    Player p;
    Projectile proj(gRenderer);
    SDL_Event ev;

    //AddEnemy(gRenderer);
    //Game loop
    while (isRunning)
    {
        p.Draw(gRenderer);
        //Event Loop
        while (SDL_PollEvent(&ev) != 0)
        {
            if (ev.type == SDL_QUIT)
                isRunning = false;
        }
        SDL_RenderClear(gRenderer);
        //Updates characters in game
        p.Update(gRenderer);
        enemyobj.UpdateEnemies(gRenderer);
        proj.UpdateProjectiles(gRenderer);

        //Draws characters in game
        mainbg.Draw(gRenderer, mainbg.position);
        p.Draw(gRenderer);
        enemyobj.DrawEnemy(gRenderer);
        proj.DrawProjectile(gRenderer);

        //Checks for collsion
        enemyobj.Intersects(p);

        //Renders objects to screen
        SDL_RenderPresent(gRenderer);

    }
    SDL_DestroyWindow(window);
    SDL_DestroyTexture(p.Draw(gRenderer));
    SDL_DestroyRenderer(gRenderer);
    window = nullptr;
    gRenderer = nullptr;

    SDL_Quit();

    return 0;
}

```

# Answer
> 0 votes
From what I understand, you probably have a line like this:

```
Player p;

```

in your `Projectile` header, and you assume that it's the same thing that you declared in your `main` function.

It's not.

Both are different *instances* and they don't know about each other, they have their own separate life, like twins that have been separated at birth.

You could change this in your **Projectile.h**

```
Player p;

```

for this

```
static Player* P; // Make it a pointer, and the capital P is to indicate that it is a static
                  // variable (makes code easier to read).

Player* Projectile::P = nullptr; // This should be added to your Projectile.cpp file, this
                                 // will 'create' the variable.

```

and in your **Projectile.cpp**

```
projRect.x = p.Position.x + p.Position.w / 2;

```

for

```
projRect.x = P->Position.x + P->Position.w / 2; // to use P as a pointer

```

And change this in your **main**:

```
Player p;
Projectile proj(gRenderer);

```

for this:

```
std::unique_ptr<Player> p = std::make_unique<Player>(); // Make your player as a pointer
Projectile::P = p.get(); // Make sure the Projectile class use the right instance of player
Projectile proj(gRenderer); // Carry on

```

... and change everything `p.` to `p->` in your main function.

The goal here is to have a single instance of `Player` and have all the projectiles refer to it.

---

This will probably solve your current issue, but there is a lot of weird things going on with the rest of your code.

I understand you're new at this and it's not that easy to figure things out at the beginning.

In an OOP design, the collection of `Projectile`s would be managed *outside* of the `Projectile` class; the `Projectile` would not know about the `Player`, it would only know where it should be created (an external 'entity' would make the link between the two); I would expect the `Update` methods not needing the `gRenderer`, only a delta-time (a timestep).

That would be a good start :)

Also, we often use naming conventions to distinguish local variables, from class variables, from static class variables, from method parameters; this help read the code and figure out easily where the variable is coming from. This is a short example:

```
class MyClass
{
public:
  int mMyInt; // the code style for class attribute: start with a lowercase 'm' (for 'module')

  static int MyStaticInt; // the code style for class static: start with a capital letter.

  // the code style for the method attributes: start with a lowercase 'a' (for 'attribute')
  int method( int aParam1, int aParam2 )
  {
    // the code style for local variables: start with a lowercase (no special treatment)
    int localVar = mMyInt + aParam1 + aParam2;
    MyStaticInt = localVar * 2;
    return localVar;
  }
};

```

Of course, some conventions are more popular than others, but the idea is to be consistent across your code.

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


# Question
Title: What methods do game hacks use to counter anti hack systems?
In popular multiplayer first person shooter games, there are often hacks such as Aimbot, Noclip, Speed, and other similar hacks which I know game developers deploy anti hack features to combat, but, wanting to know why some of these hacks are able to get past these systems, I looked up a hack for the game I'm currently playing and they claim to deploy "counter measures" against the anti hack systems.

My question is, when everything happening is being seen by the game server, how can hacks avoid the anti-hack system? Movement that's too fast for example seems impossible to hide. Moving through walls also seems impossible to hide. Finally aimbot is a difficult one, maybe there's no very good solution to detecting it, if the hack developer, for example, purposely makes it imperfect.

My question to game developers is: How can anti hack systems fundamentally detect speed, noclip, and aimbot hacks, and how can hack developers fundamentally deploy counter measures against systems to detect those three types of hacks?

# Answer
> 2 votes
There are three types of "hacks" used for video games.

* Packet modification: Modifying the data sent to the server.
* Server hack: Gaining access to the server and performing unauthorized commands.
* Client modification: Modifying the client to perform something that only affects how you see the game.

We can sort these into different categories for examples.

**Speed hacks:** These are "packet modification" hacks. These modify the data that is sent to the server.

The best way to prevent this is to validate the information sent. Check if the player is moving faster than the default move speed.

**Aimbots:** These can be either "packet modification" or "client modification".

If it's client modification, it will just point yourself towards an enemy when it sends data to a server. To prevent this, make the player not able to turn extremely quickly, as that will be the result of this type of hack.

If it's packet modification, it will make your projectiles always point towards the nearest enemy. To prevent this, don't let the client update details about the bullet while it is moving.

**Noclip:** Another type of packet modification. Allows the player to move through walls, and if the server doesn't check if the player's in the wall, then this is possible.

**See through walls/similar:** This is client modification. There's no way to prevent this currently (correct me if I'm wrong).

# Answer
> 2 votes
> Moving through walls also seems impossible to hide

Let's look at a simple scenario:

In this diagram, a player is running around this protruding wall. However, due to some connection issues, all packets along the red line are dropped and the server never receives them. The connection improves and the server starts receiving packets with the player now on the other side of the wall. Did the player cheat? Of course not, they moved correctly around the wall on the client side, but the perception of the server is now that they moved through the wall. This kind of situation is exactly what makes anticheat so difficult to implement. As a result, they tend to focus on other situations/methods for detection of cheating.

I saw VAC mentioned in another answer, however I feel the information provided there is either misleading or wrong. VAC accomplishes cheat detection by looking for known cheats in the game, using a library of previously discovered cheats. Getting around VAC detection is as simple as writing your hack in a novel way. As long as it's not similar to some other hack in it's execution, it'll likely be undetected by VAC. VAC Documentation Punkbuster works in a similar way, along with scanning game files in memory to verify they've not changed periodically.

So, I guess to put it simply. Circumvention of anticheat really is not too hard; It's as simple as coming up with a new way to hack the client.

---
Tags: hacks
---


title: DirectX 11 Problem with texture loading

text:
# Question
Title: DirectX 11 Problem with texture loading
I am trying to load a texture into my 3d graphics application. I am having trouble with my sampler state specifically. There are no errors generated just my little popup window saying, "Texture failed to load". I did a bit of debugging and couldn't find why my sampler is having trouble loading. All of the HRESULTs return S\_OK and yet it throws a popup at me.

resourceManager.h

```
#pragma once

#include "renderer.h"
#include <d3dx11tex.h>

class ResourceManager
{
private:
    ComPtr<ID3D11SamplerState> m_Sampler;
    ComPtr<ID3D11ShaderResourceView> m_Texture;

    Renderer m_Renderer;
public:
    ResourceManager(Renderer& renderer);

    inline ComPtr<ID3D11SamplerState> GetSampler() const { return m_Sampler; }
    inline ComPtr<ID3D11ShaderResourceView> GetTexture() const { return m_Texture; }

    bool CreateTexture(LPCWSTR file_name);
};

```

resourceManager.cpp

```
#include "resourceManager.h"

ResourceManager::ResourceManager(Renderer& renderer)
    : m_Renderer(renderer)
{

}

bool ResourceManager::CreateTexture(LPCWSTR file_name)
{
    auto handlerR = D3DX11CreateShaderResourceViewFromFile(m_Renderer.GetDevice().Get(), file_name, nullptr, nullptr, m_Texture.GetAddressOf(), nullptr);
    if (FAILED(handlerR)) return false;

    D3D11_SAMPLER_DESC sampDesc;
    ZeroMemory(&sampDesc, sizeof(sampDesc));
    sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
    sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
    sampDesc.MinLOD = 0;
    sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
    auto handlerS = m_Renderer.GetDevice()->CreateSamplerState(&sampDesc, m_Sampler.GetAddressOf());
    if (FAILED(handlerS)) return false;

    return true;
}

```

# Answer
I figured it out lol. When I was checking to see if the function returned false, I forgot to negate the if statement using "!".

```
if (!resourceManager.CreateTexture(L"Resources/container.png"))

```
> 1 votes

---
Tags: c++, directx11
---


# Question
Title: How to fix the sprite that is not drawn on the same position as its body after implementing pixels-per-meter Division?
I had a problem where the sprite was not positioned on Body correctly which I solved and you can see it here.

After I solved that, I needed to divide everything by PIXELS PER METERS so that I can convert the sizes because of Box2D, but since I did that I have the same problem again, the sprite is not positioned on the Body correctly and it does not follow the body when it moves.

This is the image:

This is the code for the player class:

```
public class Player extends Sprite {

    public World world;
    public Body body;

    private Texture playerTexture;

    public Player() {
        super(new Texture(Gdx.files.internal("Player/Player 1.png")));
    }

    public Player(World world, float x, float y) {
        super(new Texture(Gdx.files.internal("Player/Player 1.png")));
        playerTexture = getTexture();
     // super(new Texture(Gdx.files.internal("Clouds/Cloud 1.png")));
     // playerTexture = new Texture(Gdx.files.internal("Player/Player 2.png"));
     // setTexture(playerTexture);

        this.world = world;
        setPosition(x, y);
        createBody();
    }

    void createBody() {

        BodyDef bodyDef = new BodyDef();

        // dynamic body is affected by other forces e.g. gravity and it has velocity
        // static body is not affected by other forces gravity and it does not have velocity
        // kinematic body is not affected by gravity but it can be manipulated by velocity
        bodyDef.type = BodyDef.BodyType.DynamicBody;

        // bodyDef.position.set(getX(), getY());
        bodyDef.position.set(getX() / GameInfo.PPM, getY() / GameInfo.PPM);

        // create body in the world using our definition
        body = world.createBody(bodyDef);
        body.setFixedRotation(true);
        // body.setUserData(new Sprite(
        // new Texture(Gdx.files.internal("Player/Player 1.png"))));

        // define the dimensions of the physics shape
        PolygonShape shape = new PolygonShape();
        // shape.setAsBox((getWidth() / 2),
            // (getHeight() / 2));

        shape.setAsBox((getWidth() / 2) / GameInfo.PPM,
                (getHeight() / 2) / GameInfo.PPM);

        // FixtureDef is a confusing expression for physical properties
        // Basically this is where you, in addition to defining the shape of the body
        // you also define it's properties like density, restitution and others
        // If you are wondering, density and area are used to calculate over all mass
        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = shape;
        fixtureDef.density = 1f;

        Fixture fixture = body.createFixture(fixtureDef);
        // fixture.setUserData(new Sprite(playerTexture));

        // shape is disposable now so get rid of it
        shape.dispose();

        this.setPosition((body.getPosition().x),
                (body.getPosition().y));

        System.out.println("PLAYER position " + this.getX() + " " + this.getY());
        System.out.println("BODY position " + body.getPosition().x
                + " " + body.getPosition().y);

    } // create body

        //    public void drawPlayer(SpriteBatch batch) {
        //        batch.draw(playerTexture, body.getPosition().x,
        //                body.getPosition().y);
        //    }

    public void updatePlayer() {
        this.setPosition(body.getPosition().x, body.getPosition().y);

        // this.setPosition(body.getPosition().x / GameInfo.PPM,
        // body.getPosition().y / GameInfo.PPM);
    }

        //    public void updatePlayer() {
        //        this.setPosition((body.getPosition().x - getWidth() / 2) / GameInfo.PPM,
        //                (body.getPosition().y - getHeight() / 2) / GameInfo.PPM);
        //    }

    public void movePlayer(float x) {
        body.applyForce(new Vector2(x, 0),
                body.getWorldCenter(), true);
    }

} // class

```

This is my code for the cloud(which works and its practically the same code):

```
public class Clouds extends Sprite {

    private World world;
    private Body body;

    public Clouds(World world, float x, float y) {
        super(new Texture(Gdx.files.internal("Clouds/Cloud 1.png")));
        this.world = world;
        setPosition(x - getWidth() / 2, y);
        createClouds();
    }

    void createClouds() {

        BodyDef bodyDef = new BodyDef();

        // dynamic body is affected by other forces e.g. gravity and it has velocity
        // static body is not affected by other forces gravity and it does not have velocity
        // kinematic body is not affected by gravity but it can be manipulated by velocity
        bodyDef.type = BodyDef.BodyType.StaticBody;

        // bodyDef.position.set(this.getX() + getWidth() / 2,
        // this.getY() + (getHeight() / 2 - 10));

        bodyDef.position.set((this.getX() + getWidth() / 2) / GameInfo.PPM,
                (this.getY() + (getHeight() / 2 - 10)) / GameInfo.PPM);

        // create body in the world using our definition
        body = world.createBody(bodyDef);

        // define the dimensions of the physics shape
        PolygonShape shape = new PolygonShape();

        // shape.setAsBox(this.getWidth() / 2, this.getHeight() / 2);

        shape.setAsBox((this.getWidth() / 2) / GameInfo.PPM,
                (this.getHeight() / 2) / GameInfo.PPM);

        // FixtureDef is a confusing expression for physical properties
        // Basically this is where you, in addition to defining the shape of the body
        // you also define it's properties like density, restitution and others
        // If you are wondering, density and area are used to calculate over all mass
        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = shape;
        fixtureDef.density = 1f;

        Fixture fixture = body.createFixture(fixtureDef);

        // shape is disposable now so get rid of it
        shape.dispose();

    } // create body
} // class

```

This is my Gameplay class where I run everything:

```
public class Gameplay implements Screen {

    GameMain game;

    private OrthographicCamera box2DCamera;
    private OrthographicCamera mainCamera;
    private Viewport gameViewport;

    Texture bg;

    private Hud hud;

    private Player player;

    private World world;

    // delete this later
    private Box2DDebugRenderer b2Renderer;

    Clouds cloud;

    private Array<Body> bodies = new Array<Body>();

    public Gameplay(GameMain game) {

        this.game = game;
        // box2DCamera = new OrthographicCamera(GameInfo.WIDTH, GameInfo.HEIGHT);

        box2DCamera = new OrthographicCamera();
        box2DCamera.setToOrtho(false, GameInfo.WIDTH / GameInfo.PPM,
                GameInfo.HEIGHT / GameInfo.PPM);

        box2DCamera.position.set(GameInfo.WIDTH / 2f,
                GameInfo.HEIGHT / 2f, 0);

        mainCamera = new OrthographicCamera(GameInfo.WIDTH, GameInfo.HEIGHT);

        gameViewport = new StretchViewport(GameInfo.WIDTH,
                GameInfo.HEIGHT, mainCamera);

        bg = new Texture(Gdx.files.internal("Backgrounds/Game BG.png"));
        hud = new Hud(this.game.batch);

        world = new World(new Vector2(0, -9.8f), true);
        b2Renderer = new Box2DDebugRenderer();

        player = new Player(world,
                GameInfo.WIDTH / 2,
                GameInfo.HEIGHT/ 2 + 200);

        cloud = new Clouds(world,
                GameInfo.WIDTH / 2,
                GameInfo.HEIGHT/ 2 - 100);

    }

    void handleInput(float deltaTime) {
        if(Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
            player.movePlayer(-7);
        } else if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
            player.movePlayer(7);
        }
    }

    void update(float deltaTime) {
        handleInput(deltaTime);
    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {

        update(delta);

        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        // box2DCamera.update();
        // world.step(1 / 60f, 6, 2);
        world.step(Gdx.graphics.getDeltaTime(), 6, 2);

        // player.updatePlayer();

        world.getBodies(bodies);

        game.batch.begin();
        game.batch.draw(bg, 0, 0);
        game.batch.draw(cloud, cloud.getX(), cloud.getY());

        //        for(Body body : bodies) {
        //            if(body == player.body) {
        //                if(body.getUserData() instanceof Sprite) {
        //                   Sprite jack = (Sprite) body.getUserData();
        //                    jack.setPosition(player.body.getPosition().x,
        //                            player.body.getPosition().y);
        //                    jack.draw(game.batch);
        //                }
        //            }
        //        }

        // player.drawPlayer(game.batch);
        game.batch.draw(player, player.getX(), player.getY());

        // b2Renderer.render(world, box2DCamera.combined);

        game.batch.end();

        b2Renderer.render(world, box2DCamera.combined);

        // game.batch.setProjectionMatrix(hud.stage.getCamera().combined);
        // hud.stage.draw();

        player.updatePlayer();
        // updatePlayer();

        // update the physics world
        //  world.step(Gdx.graphics.getDeltaTime(), 6, 2);
        // world.step(1 / 60f, 6, 2);

    }

    @Override
    public void resize(int width, int height) {
        gameViewport.update(width, height);
        // gameViewport.update(width / GameInfo.PPM,
            // height / GameInfo.PPM);
        // gameViewport.setWorldWidth(width / GameInfo.PPM);
        // gameViewport.setWorldHeight(height / GameInfo.PPM);
    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {
        bg.dispose();
        world.dispose();
        b2Renderer.dispose();
    }

    void updatePlayer() {
        player.setPosition(player.body.getPosition().x,
                player.body.getPosition().y);
    }

} // class

```

I'm really confused what is going on here, when I try to move the player he is not following the body and also he is not rendered on the body, but the same code in the Cloud class works for the cloud and the cloud is drawn on the body, I don't get what is going on here.

Any help would be highly appreciated.

# Answer
This ended up fixing the problem:

```
public void updatePlayer() {
    this.setPosition((body.getPosition().x) * GameInfo.PPM,
            (body.getPosition().y) * GameInfo.PPM);
}

```

Calling this in the render function and calling this in the render function:

```
game.batch.draw(player, player.getX() - player.getWidth() / 2f,
            player.getY() - player.getHeight() / 2f);

```

I multiplied the body positions by PPM as @ProRed suggested, so thank you @ProRed you helped me to solve it.
> 0 votes

# Answer
In your createBody function:

```
this.setPosition((body.getPosition().x),(body.getPosition().y));

```

Since the x and y position of the body is already divided by PPM you need to either multiply it by PPM again or remove this line completly because you already set the position in the constructor.
> 2 votes

---
Tags: libgdx, box2d
---


# Question
Title: Correct architecture for weapon class in RPG
So, I'm a little stuck on what the best way to implement weapons is. The problem I'm running into is, what exactly is a weapon.

I have a Player Class that has an attack method.

```
public class Character
{
    public int MaxDamage;

    public bool IsAlive = true;

    public Character Attack(Character target)
    {
        Random attackRange = new Random();
        int damageValue = attackRange.Next(0, MaxDamage);

        target.TakeDamage(damageValue);

        Random critCheck = new Random();
        int critCheckValue = critCheck.Next(0, 100);
        //hitChance = dex - target.dex;

         if (critCheckValue <= CritChance)
         {
          //dmg min = dmg min + (dmg min*crit damage);
          MaxDamage = MaxDamage + (MaxDamage * CritDamage);
         }
     }
}

```

So this works. But once I implement a weapon, it gets a little confusing.

* Does the player still have the attack method and the weapon just modifies the values?
* Does the weapon really have the attack method and the player just calls it?
* How would you handle something like a power swing that may hit 3 characters?
* Does the weapon contain the range or the player?

# Answer
This question is a bit broad, but a few things...

1) You could create a CLASS for weapons, and have the character object own a 'weapon' object, and then you can add in, say "Weapon.damageBonus" to damage dealt

2) Your "Attack" function returns a "Characer" object. I believe you want to return an int or double (or float if for some reason you need a float?) for your 'damage' amount, perhaps?

3) As nathan mentioned in his comment, you really could benefit from searching on this site. There is already a TON of info on here about good ways to implement what you want to accomplish.

Hope this helps.

EDIT:

I realize there was a lot of your question that I didn't address, so here:

The player **could** have the attack method. You could generalize it more and have it inherit the attack method as well.

The weapon is an item, it doesn't 'do' things, it 'is' things. I would argue that you should have your characters 'do' things (like figure out damage and whatnot) while your items (armor, weapons, etc) just 'are' things, and thus just tweak the formulas a bit.

To handle something like one swing hitting multiple characters, you could simply have the character return the damage they 'intend' to do, and then each thing hit can take that damage and do some math to figure out from that, how much they actually 'take'.

Like my above comment, I would argue for the player to have the range, but the weapon to **modify** it.

Again, hope this helps.
> 4 votes

# Answer
It depends on what you really needs. But if you you use relationship logic, the following statements may explain.

1. A **character** wields **weapon**.
2. A character **attack using weapon or unarmed**.
3. The **damage formula** differ **based on the weapon** wield. Swords depends on strength and agility, bows depends on skills etc.

So, basically you have to make something like this :

Solution(s) for case number 1:

---

1. The `GameCharacter` class has an attribute weapon which type is `Weapon` class.

---

Solution(s) for case number 2:

---

1. The `GameCharacter` has the method `attack(Target t)`.
2. The attack method check the character weapon attribute, **if the weapon is not present, use unarmed attack**.

---

Solution(s) for case number 3:

---

1. So **many weapons type** but, **all of them are weapons** anyway. Make the `Weapon` class `abstract`, add the **abstract method** `getRawAttackValue()` method. Swords, bows, staves etc. are sub-classes.
2. The **damage depends on the wielder status**. So, the **alter** the `getRawAttackValue()` method **into** `getRawAttackValue(GameCharacter wielder)`.

---

**The above statements may change** depends on the variables added into the formula. Like, for example, if you add the attribute `elementalType` in the Weapon class. So, the conclusion is, **you have to design the classes** using paper and pencil first. The methods with empty implementations then write the required codes in the method body later.

These are the code samples, it's just a sample though, I use java syntax :

```
//the classes are written in different files

public class PlayableCharacter implements Target{
    Weapon weapon;
    Armor armor;
    short strength, endurance, agility, skill, intelligence, spirit;

    public void attack(Target t){
        Random r = new Random();
        int damage;
        if(Weapon!=null)
            damage = weapon.getAttackingPower(this);
        else
            damage = this.strength * (r.nextInt(this.strength)/r.nextInt(this.strength) * 2;
        //determine whether the attack is critical hit or not
        if(r.nextInt(this.spirit)>r.nextInt(t.getSpirit())){
            damage*=2;
        }
        t.getDamage(damage);
    }
}

public abstract class Weapon{
    private short physicalAttack;
    private short magicalAttack;

    Weapon(short p, short m){
        physicalAttack = p;
        magicalAttack = m;
    }

    public short getPhysicalAttack(){
        return physicalAttack;
    }

    public short getMagicalAttack(){
        return magicalAttack;
    }

    public abstract int getAttackingPower(PlayableCharacter c);
}

public class Sword extends Weapon{
    @Override
    public int getAttackingPower(PlayableCharacter c){
        return physicalAttack + physicalAttack/9999 * c.getStrength() * + (physicalAttack + physicalAttack/9999 * c.getStrength()) * c.getAgility() * 0.6;
    }
}

public class Bow extends Weapon{
    @Override
    public int getAttackingPower(PlayableCharacter c){
        return physicalAttack + physicalAttack/9999 * (c.getSkill() + c.getSkill * c.getStrength/999);
    }
}

public class Staff extends Weapon{
    @Override
    public int getAttackingPower(PlayableCharacter c){
        return physicalAttack + physicalAttack/9999 * (c.getMagicalAttack() * 1.2 + c.getPhysicalAttack);
    }
}

```

I hope my comment will help.
> 1 votes

# Answer
Your question has lots of parts to it.

Here's a few terms I would add to your vocabulary based on your question:

**AOE - Area of Effect** \- Actions that impact an area rather than a specific target

https://en.wikipedia.org/wiki/Glossary\_of\_video\_game\_terms#Area\_of\_effect

**Ranged Weapons** \- Any weapon that impacts a user at a distance further than hand-to-hand combat (often via an attack NOT connected to the attacker, like a gun or laser or spell)

https://en.wikipedia.org/wiki/Ranged\_weapon

**Melee Weapons** \- Any combat item (including body parts) used in close hand-to-hand combat.

https://en.wikipedia.org/wiki/Melee

There are a ton of other relevant terms, but I didn't want to muddy up the answer with other things you weren't asking about.

In the case of a game I created, the TARGET character was a LISTENER, and WEAPONS broadcasted a POTENTIAL impact. The LISTENER actually calculated how much the aggregate impact was based on the totality of the stats and situation. In your model, it looks like you're trying to do the opposite (You're letting the ATTACKER decide all of the damage. I suspect you'll end up shifting your design to more of what I describe as you flush out your concept)
> 0 votes

---
Tags: c#, architecture
---


# Question
Title: Separate "Battle Character" class from "Character" class?
So I have a Class called Character which represents all the player, his companions, and all enemies. This class does a lot of things including performing actions upon other characters, and upon the environment, and so on.

I'm about to start work on a battle system for this RPG, and there will be the player controlled (and enemy controlled) units which will have a location on the screen, and a delay since their last action, and a ton of other properties and methods that apply entirely to the battle. But, this thing will also be associated in a one-to-one relationship with a Character which exists separate from a battle. It will need to access that characters stats for it's battle actions as well as some of it's methods.

So the root of my question is, is it better to create a new "Unit" class, which references the character it's associated with, or should I just expand upon the existing Character class with functions and properties that relate **only** to a battle? If it matters I'm writing this in C#.

# Answer
> 2 votes
There are two principles behind my suggestion, SoC and SRP. That is, Separation of Concerns and the Single Responsibility Principle.

The main thing to note in your case is that your character, so far, is totally unrelated to combat. Generally speaking, if something isn't going to be used somewhere, it shouldn't even *exist* there. Creating things like your combat Unit as wrappers has another related benefit: it is a perfect example of Composition, which is (in the universe of OOP) generally considered a **Good Thing**.

So, happily split things where you can, and where things aren't needed, don't put them. The result will be a non-coupled design which will be easy to extend and maintain. This is a core principle of OOP, no matter the application.

Good luck!

# Answer
> 1 votes
First, a comment: it doesn't sound like you're using an entity/component model. I highly suggest that, because it will help you with your design, and it will also address this problem.

The "core" problem is not "the current representation of the player (on the map) now needs to go into battle." The problem is sprites, etc. are all specific to your current "view" (let's say the map view, as opposed to the battle view).

What I suggest is this: distil your Player class down to the core, permanent attributes that are there regardless of which view you're looking at. This will likely include:

* Player name
* Current/total health
* Inventory
* Skills
* etc.

Once you have this done, it's just a matter of passing this data from view to view. When you pass it to the world map, it'll create the right sprite and render the player location, and allow you to move him.

When you pass it to the battle view, it'll recreate the right sprites, display health, turns, etc.

So the answer is not "new class" or "subclass," the answer is "extract your data from your current view and pass *that* around instead."

# Answer
> 0 votes
The main purpose of **inheritance** is to **exploit** the use of **polymorphism**. You may **put** the **sub-classes in a collection** data structure **which type is the super-class** of those sub-classes and then **iterate** over them, **calling the same method with different implementations**.

For example, when you create the class `Vehicle`. Suppose that when your game character calls forth a meteor down from the sky and then every vehicle in the surrounding AoE explodes. Based on this logic, you may create the method `explode()` in the `Vehicle` class. But, it would make no sense if a `Bicycle` explodes from a meteor crash, it has no fuel, why would it explode?.

The solution is to create the `Explosive` interface with the method `explode()` in it. Cars, buses, trains etc. implements the interface whilst Bicycle does not. So, the `Collection` type should be `Explosive`, iterate over it and call the explode method.

For your case, are you going to put the characters in the same group and call the same method in the future? If not, just create a new super-class.

---
Tags: c#
---


title: Terrain for MMORPG

text:
# Question
Title: Terrain for MMORPG
Im new in game development. I read some papers about LOD and they were always using heightmaps. I got the basic idea what is LOD and what it solves, but yet i am still not sure i understand what i need to do.

So i want to have terrain for open world mmorpg let's say 20x20km. If i say 1 opengl world space unit will be 1m, than i will have world 20\_000x20\_000units. Now if i can have max. resolution of heightmap 8192x8192, it means i will need to encode more than 2x2m in 1 PIXEL. That means every detail of the terrain mesh will be lost (for example little crater with diameter 0.3unit). What i am missing? So is the heightmap even used in real games?

# Answer
> 5 votes
Your problem lies in the fact that its almost impossible to load an entire 20x20 km map fully into memory. You mentioned LOD (I will talk about it later), but for now let's ignore it.

Consider a game like, let's say, Minecraft. It doesn't load all its map at once (It would be impossible, it's infinite), so it divides it in chunks (16mx16mx256m map pieces), and loads the x chunks nearest to the player. The rest of the map remains unloaded until you get closer to it. Thats a good approximation: Split the map into pieces, and only load the pieces near the player. This, however, will have one problem: Big objects far away (For example, mountains) will be invisible until player gets unrealistically close to them, unlike in real life.

LOD is the solution to that problem. The basis of LOD is, instead only loading the parts of the map you are closest, at full resolution, load a much bigger part of the map, but reduce its resolution proportionally to the distance to the player. This makes sense: The tiny details (Grass, little holes in terrain, etc.) are only visible when you are close to them in real life, so if you load them while the player is far away, he/she is not going to be able to see them anyways, so it is a enormous waste of resources. So, for near objects, you render the world as detailed as possible and, for far objects, you reduce the detail, as the player isn't capable of noticing it anyways. Reducing the resources used this way, you will be able to load a much higher map distance than using the last approximation.

So, for your particular problem. Without LOD, it's easy. Split the "big" heightmap into smaller heightmaps, and only load the nearest heightmaps to the player. With LOD it gets more difficult, as you should, for each little heightmap, store different levels of detail (one unit per cm at first for example, one unit per 10m, or even 100m, at the end), and load one or another of them depending to the distance to the player.

# Answer
> 2 votes
Calculating a whole 20x20 km open world with enough detail for a decent-looking first-person perspective all at once is too much for even the strongest hardware.

What we usually do in this case is divide the game-world into smaller zones and only render the zones around the player in full detail. Anything further away from the player is rendered in a much lower level of detail.

When it comes to heightmaps, you could solve this by having a low-res heightmap for the whole world where each pixel represents multiple meters while also having separate high-res heightmaps for all zones where a pixel is a few centimeters. So your 0.3m crater would be represented in the high-res heightmap of the zone it's in but not in the low-res heightmap used for the whole world.

---
Tags: terrain
---


title: 1D Perlin Noise Game in Unity

text:
# Question
Title: 1D Perlin Noise Game in Unity
I'm working on a 2D side-scrolling game in the Unity engine. I am using the 1-Dimensional Perlin Noise function and using pseudo-code. I can't use two links so I'll provide a link to imgur with the images and the links in numerical order. First link in imgur links to the pseudo-code/implementation of perlin noise I am using.

My implementation so far is showing good results.

Here is a picture:

This image uses the values:

* Persistance = 0.7
* Octaves = 4

From the first article I linked, it states:

> Now, you'll want several different random number generators, so I suggest making several copies of the above code, but use slightly different numbers. Those big scarey looking numbers are all prime numbers, so you could just use some other prime numbers of a similar size.

This block of text is referring to this part of code which is an Integer-noise function:

```
  float Noise (int x)
    {
        x = (x << 13) ^ x;
        return (float)(1.0 - ((x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0);
    }

```

Another site I found the author adjusts the Integer-noise function from discrete to continuous (allowing the range not to be limited). I've made this change although I am not sure if my implementation of both links I've provided is entirely correct. The results are promising but when you change these variables values to:

* Persistence = 1
* Octaves = 8

the terrain starts to have little gaps at the bottom like so:

I am not quite sure how to fix this, I know lowering the persistence provides smoother results resolving this issue but that makes the terrain's amplitude rather low for a side-scrolling platformer.

Here is the complete code:

```
    void Start ()
    {
        objectArray = new GameObject[width, height];

        for (int i = 0; i < width; i++) {

            float x = PerlinNoise_1D (i, persistances, octaves);

            for (int j = 0; j < height; j++){
                objectArray[i,j] = (GameObject)Instantiate (gameobject, new Vector3 (i, j + x, 0), Quaternion.identity);
            }
        }

    }

float Noise(int x){
    x = (x << 13) ^ x;
    return (float)(1.0 - ((x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0);
}

float CoherentNoise  (int x)
{
    int intX = (int)(Mathf.Floor(x));
    float n0 = Noise (intX);
    float n1 = Noise (intX + 1);
    float weight = x - Mathf.Floor (x);
    float noise = Mathf.Lerp (n0, n1, weight);
    return noise;
}

float SmoothedNoise (int x)
{
    return CoherentNoise (x) / 2 + CoherentNoise (x - 1) / 4 + CoherentNoise (x + 1) / 4;
}

float InterpolatedNoise (float x)
{

    int integer_X = (int)x;
    float fractional_X = x - integer_X;

    float v1 = SmoothedNoise (integer_X);
    float v2 = SmoothedNoise (integer_X + 1);

    return Cosine_Interpolate (v1, v2, fractional_X);
}

float Cosine_Interpolate (float a, float b, float x)
{
    float ft = x * (float)Mathf.PI;
    float f = (float) ((1 - Mathf.Cos ((ft))) * .5);

    return  a * (1 - f) + b * f;
}

float PerlinNoise_1D (float x, float persistance, int octaves)
{

    float total = 0;
    float p = persistance;
    int n = octaves - 1;

    for (int i = 0; i <= n; i++) {

        float frequency = (float)Mathf.Pow (2, i);
        float amplitude = Mathf.Pow (p, i);

        total +=  InterpolatedNoise (x * frequency) * amplitude;
    }

    return total;

}

```

Thank you for your help and time.

# Answer
The gaps at the bottom of the screen appear to be a result of your platforms having a fixed height, and some of them being shorter than necessary to reach the bottom of the screen. The simplest solution would be to set your platforms' heights so that they exactly fill the space they're intended to occupy.
> 2 votes

---
Tags: unity, procedural-generation, perlin-noise
---


# Question
Title: Is there a way to turn collision detection system off completely in Unity?
My world setup is 2D Top-Down. All collisions are disabled from the collision matrix.

There are no collisions in the scene as I wanted, but as I perceive, Unity is still trying to calculate collisions in the background. So I'm experiencing serious frame rate drops because of *Physics2D.Simulate* when I have about 2k colliders moving over each other on the scene.

I followed the suggestions about colliders and rigidbodies on the API exactly *(so I know the stuff about not to move static colliders without rigidbody, that's not the case here)*, but I somehow can't manage to tell Unity that I don't want her to calculate *"possible"* collisions.

I only want colliders for Raycast2D, OverlapCircle and making movements a bit realistic.

Thanks in advance for all suggestions.

# Answer
As far as I understand your needs, you would require to entirely disable Physics2D, which isn't something for what Unity has been prepared as the Physics engine is a built-in and fully integrated module from the game engine.

Nevertheless, as told in here some users have found a solution in applying the maximum to the fixed timestep:

> In the time settings, set the fixed timestep to 10 (the maximum). That's as disabled as it gets.

Hope this helps somehow.
> 2 votes

# Answer
You should be able to get away with using colliders and marking them as triggers.

Then in Project Settings -\> Physics2D, set the layer collision matrix to not even trigger when overlapping one another. (Uncheck all of the boxes)

Also, make sure the Queries Hit Triggers option is checked and for other options too.

*Picture displays checked collision matrix, which will ENABLE the detection, am just taking picture from currently open project. You should UNTICK them for your desired behaviour.*

And, voila! No collisions, but you can still check for ray hits and other casts.

*Have never worked with 2D though, but I feel this should be working.*

You can also change the behaviour via scripts (runtime) by utlizing:

Obviously, other stuff seen in the Physics2DSettings can be changed too: http://docs.unity3d.com/ScriptReference/Physics2D.html
> 2 votes

---
Tags: unity, performance
---


# Question
Title: Performance Optimization for 2D game developed using Unity 3D game engine
I have a game with almost 160 sprites in my resources folder. I need 15 randomly selected sprites on each level (there are 7 levels).

I load those sprites which are required e.g. my random generator scripts generate 15 random numbers (completely unique from previously generated 15 numbers) and based on those number I load the sprites (sprites are numbered from 1-158 so I can easily load them).

My levels take some significant time to load, I think that pre-loading the sprites at the start of each level is taking time. There are actually two folders, one for the questions and another for the answers. Each question has 5 possible answers so I actually load 15 * 5 sprites on each level and save them in an array.

Should I load all the sprites once the game is loaded? Or Should I pre-load all the Sprites in advance?

Thanks in advance I am really looking forward for answers.

NOTE: There are almost thousands of tiles(100px by 100px in size) on each level, I know this also has some impact on performance.

# Answer
> 1 votes
Load all of your sprites before your game starts, in a static class. This way, you only have to load your sprites once, and you can use them for the entirety of your game instance. Something like this:

```
public static class SpriteData
{
    public static Sprite[] Sprites;

    public static void Load()
    {
        if (Sprites == null) {
            Sprites = Resources.LoadAll<Sprite> ("sprites");
        }
    }
}

```

Then in your game logic, call the load function:

```
SpriteData.Load();

```

Then use your sprites where you need them:

```
Sprite sprite = SpriteData.Sprites[1];

```

---
Tags: unity
---


# Question
Title: Unity RaycastHit2D sprites error C#. Figured out that this code only works on 3D colliders so how do I change it so that I can use it on 2D colliders?
Figured out that this code only works on 3D colliders so how do I change it so that I can use it on 2D colliders?

Below is the c# code.

using UnityEngine;

// This script allows you to drag this GameObject using any finger, as long it has a collider public class SimpleDrag : MonoBehaviour { // This stores the layers we want the raycast to hit (make sure this GameObject's layer is included!) public LayerMask LayerMask = UnityEngine.Physics.DefaultRaycastLayers;

```
// This stores the finger that's currently dragging this GameObject
private Lean.LeanFinger draggingFinger;

protected virtual void OnEnable()
{
    // Hook into the OnFingerDown event
    Lean.LeanTouch.OnFingerDown += OnFingerDown;

    // Hook into the OnFingerUp event
    Lean.LeanTouch.OnFingerUp += OnFingerUp;
}

protected virtual void OnDisable()
{
    // Unhook the OnFingerDown event
    Lean.LeanTouch.OnFingerDown -= OnFingerDown;

    // Unhook the OnFingerUp event
    Lean.LeanTouch.OnFingerUp -= OnFingerUp;
}

protected virtual void LateUpdate()
{
    // If there is an active finger, move this GameObject based on it
    if (draggingFinger != null)
    {
        Lean.LeanTouch.MoveObject(transform, draggingFinger.DeltaScreenPosition);
    }
}

public void OnFingerDown(Lean.LeanFinger finger)
{
    // Raycast information
    var ray = finger.GetRay();
    var hit = default(RaycastHit);

    // Was this finger pressed down on a collider?
    if (Physics.Raycast(ray, out hit, float.PositiveInfinity, LayerMask) == true)
    {
        // Was that collider this one?
        if (hit.collider.gameObject == gameObject)
        {
            // Set the current finger to this one
            draggingFinger = finger;
        }
    }
}

public void OnFingerUp(Lean.LeanFinger finger)
{
    // Was the current finger lifted from the screen?
    if (finger == draggingFinger)
    {
        // Unset the current finger
        draggingFinger = null;
    }
}

```

}

# Answer
The `Physics` class is for 3D (as you guessed) so what you need to do is change your code to use the 2D Physics. Aka `Physics2D`, this will collide with 2D colliers. So for the OnFingerDown method you'll need to change the physics call:

```
public void OnFingerDown(Lean.LeanFinger finger)
{
    // Raycast information
    var ray = finger.GetRay();
    var hit = default(RaycastHit2D);

    // Was this finger pressed down on a collider?
    if (Physics2D.Raycast(ray, out hit, float.PositiveInfinity, LayerMask))
    {
        // Was that collider this one?
        if (hit.collider.gameObject == gameObject)
        {
            // Set the current finger to this one
            draggingFinger = finger;
        }
    }
}

```

That should work with 2D colliders:)

Side note, when you have somthing that returns a bool and your using things that evaluate true or false to work you don't need to have them work it out again. For the raycast it returns true/false already so there is no need to check if it's true. The more you know....
> 1 votes

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


# Question
Title: How can I make this day/night cycle computation repeat?
Here's my code for a day/night cycle. I have it set up so that when time (Statistics.duration) is the right number, the light levels switch. It works great, but I'm at a loss for how to make it work indefinitely - as an actual cycle. How can I make this code work for all numbers up to 10,000? I know there has to be an easy way to do this, but I'm at a loss...

```
public void updateTime()
{
    if (!dawn && (Statistics.duration <= 50 ) && Dungeon.depth <= 100){
        dawn = true;
        night = false;
        Dungeon.nightMode = false;
        GLog.i("It is now dawn.");
    }

    if (!noon && Statistics.duration > 50 && Statistics.duration <= 100 && Dungeon.depth <= 100){
       noon = true;
       dawn = false;
        GLog.i("It is now noon.");
    }

    if (!dusk && Statistics.duration > 100 && Statistics.duration <= 150 && Dungeon.depth <= 100){
        dusk = true;
        noon = false;
        GLog.i("It is now dusk.");
    }

    if (!night && Statistics.duration > 150 && Statistics.duration <= 200 && Dungeon.depth <= 100){
        night = true;
        dusk = false;
        GLog.i("It is now night.");
    }

    if (!dawn && Statistics.duration > 200 && Statistics.duration <= 250 && Dungeon.depth <= 100){
        dawn = true;
        night = false;
        GLog.i("It is now dawn.");
    }
}

```

I'm calling updateTime() whenever the player does something - moving, fighting, sleeping, etc. They perform the action, which gets added to the .duration.

# Answer
> 8 votes
Modular arithmetic can help you here. `%` is the modulus operator in Java, and the expression `X % Y` returns the remainder of the division operation `X / Y`. This is useful for making numbers "wrap around."

Based on your sample code, a full cycle of your day is 200 units of `Statistics.duration`. The first 50 are the day portion, the second 50 are the noon portion, the next 50 are dusk, the last 50 are night.

Thus, `Statistics.duration % 200` will give you a value between 0 and 199. If that value is less than 50, you're in the day time. Between 50 and 100, dusk. And so on. Your code can then become something like...

```
public void updateTime()
{
    int timeOfDay= Statistics.duration % 200;
    if (timeOfDay <= 50){
        // it's dawn...
    } else if (timeOfDay > 50 && timeOfDay <= 100) {
        // it's noon...
    } else if (timeOfDay > 100 && timeOfDay <= 150) {
        // it's dusk...
    } else {
        // it's night...
    }
}

```

You can wrap that entire block in your check for dungeon level as well as whatever else you might need.

# Answer
> 0 votes
Josh Petrie is right.

Futhermore, you could use an enum to avoid using if else if.

```
public enum DayTime {

    DAWN(0), NOON(1), DUSK(2), NIGHT(3);

    private int n;

    DayTime(int n) {
        this.n = n;
    }

    public static DayTime valueOf(int n) {
        for (DayTime value : values()) {
            int i = value.n;
            if (n == i) {
            return value;
            }
        }
        return null;
    }

}

public void updateTime() {
    int dayTimeIndex = Statistics.duration % 200 / 50;
    DayTime dayTime = DayTime.valueOf(dayTimeIndex);
...
}

```

# Answer
> 0 votes
# My first thought

If I understood correclty, you wants it to repeat the time as in a cycle, so you have a "class" which handles time by using modulus.

```
//I don't know how to write it on Java
class TimeHandler = {
   var current = 0;
   const max = 200;

   update() => {
      // it will make "current" eventually become 0 again
      current = (1 + current) % max;//it does not use "++" because some languages do not guarantee the order of operations
   }

   getPeriod() => {
     return PeriodFabric.for(current, max);
   }
}

```

The fabric return the right period for a given time

```
class PeriodFabric = {
   const periods = [DAWN, NOON, DUSK, NIGHT];

   for(time, max) {
     var qt = max / periods.length;
     var range = Math.floor(time / qt);
     return periods[range];
   }
}

```

This period can be forward to whatever classes need it, as the dungeon.

```
class Dungeon = {
   var nightMode = null;

   update(period) {
      nightMode = periord === NIGHT && depth > 100;
   }
}

```

Separating like this has the advantage of separing concers

* you could have multiple cycles which are concerned to time (as day/night, seasons, etc) or even better modify TimeHandler to make it generic.
* you can create more periods without modifying the TimeHandler
* you can pass periods forward to classes which behave based on it, as I did on the dungeon, so the responsabily to declare its nightMode lives there

# My friend's suggestion

I talked this answer to a friend, he's suggested me that instead of returning the period, classes would subscribe to "PeriodFabric" which would notify them when the period had changed, passing the new period to its subscrivers.

# Answer
> 0 votes
The easiest thing you can do is, for example, % the actual time.

```
actualtime %= MAX_TIME;

```

Very easy method!

# Answer
> -1 votes
You probably want to use the sine function.

Suppose you have the time of day t for a 24 for hour day, so 0 \<= t \< 24.

Then you want to map t to a value t' between 0 \<= t' \< \pi.

So t' = t * \pi / 24. At t = 0 we want t' = 0, at t = 12 we want t' = \pi / 2

Now let y = sin(t').

When y = 0 it is midnight, and when y = 1 it is noon.

Let L be your light level at noon and l be your light level as a function of time.

You can define l(t) = Ly = Lsin(t').

Your light level now transitions smoothly through the entire cycle as a function of t and you have removed branching entirely.

You can further parameterize t if you wish manipulate how time passes.

---
Tags: java, architecture
---


title: Funnel algorithm

text:
# Question
Title: Funnel algorithm
I'm implementing the funnel algorithm for pathfinding. After searching many resources I found those : https://skatgame.net/mburo/ps/thesis\_demyen\_2006.pdf http://digestingduck.blogspot.com.by/2010/03/simple-stupid-funnel-algorithm.html http://ahamnett.blogspot.co.at/2012/10/funnel-algorithm.html

I undestand how the algorithm works, but I didn't find the full working code, only pieces of it. So I misunderstand:

1)How the points are divided into "left" or "right" programmaticaly;

2)Is the channel represented as list of triangles(polygons) or just as a list of verticies;

# Answer
> 3 votes
There are MANY MANY aspects here. `Funnel algorithm` is also the wrong name. What you're doing is using nav-meshes instead.

Each poly of the nav mesh has the nice property of being convex. This means if you take any two points in the poly, the line between those two points stays in the poly.

Where two polys meat is a "portal". Imagine put a vertex at the centre of every portal.

You "want" to do what is essentially A\* on these vertices, but rather than moving along these non-optimum lines you want to keep a "funnel" as wide as possible going in the direction you want to go (just like in A\*). Whenever you have to narrow the funnel you create a vertex in your graph at the point that caused the narrowing.

The algorithm goes as follows (sort of)

> 1) Create a vertex at the start location, note the current nav-mesh poly
> 2) If the goal is inside the current poly, create another vertex at the goal, the path is from the current location to that vertex
> 3) For each neighbour to the poly (a neighbour is any adjacent poly connected by a portal) use your A\* heuristic with the centre of that neighbour to determin the "best" direction to test.
> 4) Start a "funnel" at the current location with an upper bound given by one side of the portal, and a lower bound given by the other side
> 5) Choose the best (heuristic) neighbour to the polygon the other side of the portal we chose for the funnel.
> 6) If the goal is inside the poly AND inside the funnel create a vertex at the goal's location. The path from the start to it is the shortest path.
> 7) If the goal is inside the poly but not in the funnel create a vertex along the most recent portal the funnel goes through on the "side" (left/right I guess?) of the goal. Then create a vertex at the goal. This is the shortest path.
> 8) If the goal isn't inside the poly choose the lowest heuristic neighbour again. If the funnel covers the portal, narrow the funnel on each side (creating a vertex when you do). If the funnel only covers one side, clamp that one side and create a new vertex. If the funnel doesn't overlap with the portal at all. Create a vertex on the portal-you-came-through's-to-get-to-this-poly line on the side which is nearest to the portal whilst still being in the funnel. Now start a new funnel from that vertex to the target portal.
> 9) Go to 6.

Will add pictures if you need them, I recommend you draw some!

# Answer
> 2 votes
I had the same problem while searching for funnel algorithm. Here it is a summarized procedure, considering one origin and target point:

1. Triangulate your polygon
2. Select origin and target points
3. find origin and target triangles
4. Do any graph search algorithm to find the path of triangles from origin to target
5. find the path of edges connecting the triangles between origin and target
6. reorder the edges to the same direction using cross product
7. perform the funnel algorithm on the order path of edges

i've implemented in haskell the code: you can look here , but it's quite messy. https://github.com/massudaw/funnel-triangulate/blob/master/src/Triangulation.hs

---
Tags: java, algorithm, path-finding
---


title: FXAA Parameter Confusion

text:
# Question
Title: FXAA Parameter Confusion
I have a question about the popular FXAA shaders that are out there written using HLSL or GLSL, and they all mainly feature these three parameters:

```
#define FXAA_REDUCE_MIN (1.0 / 128.0)  //0.0078125
#define FXAA_REDUCE_MUL (1.0 / 8.0)  //0.125
#define FXAA_SPAN_MAX 8.0

```

What is the function of each parameter?

# Answer
Thanks to user *kingeric1992* who answered in this other forum:

> the inquired algorithm performs 1D sampling on direction perpendicular to luminance gradient with varying range with following behavior:
>
> reduce sample range by nearby sum with scale factor defined by
>
> FXAA\_REDUCE\_MUL: reduce scale multiplier
>
> and
>
> FXAA\_REDUCE\_MIN : minimum reduce scale
>
> after that, FXAA\_SPAN\_MAX will force clamp the sample range.
>
> as the out come, the sampling vector (A, B ) will be characterize as (A', B') with min(A', B') \< 1, and if |A - B| \< scale factor, max(A', B') will also be less then 1, that == no blurring.
> 1 votes

---
Tags: fragment-shader, antialiasing
---


# Question
Title: How does billboarding 3D sprites affect performance?
I was reading the Unity manual on trees and one of the claims made is as follows:

> Unity uses optimisations (eg, billboarding for distant trees) to maintain good rendering performance...

I was planning on doing my own billboarding for a game I'm building anyway, so knowing that I'm going to gain a performance advantage is good to know. However, when I tried looking a little deeper at how billboarding is done in Unity, I found these sources:

http://wiki.unity3d.com/index.php?title=CameraFacingBillboard http://answers.unity3d.com/questions/20697/how-to-create-billboarding-planes.html http://answers.unity3d.com/questions/52656/how-i-can-create-an-sprite-that-always-look-at-the.html

Which all show that the way to do billboarding is to do a transform on the object each frame to make it face the camera. (I can't find much about billboarding in the official Unity documentation).

How does billboarding affect performance? Why would there be a performance boost if you have to transform *"dense forests with thousands of trees"* before each frame? Does unity have a native billboarding shader built in? If not, wouldn't billboarded sprites require, at the very least, the same amount of rendering power as other objects being drawn in a 3D scene?

# Answer
> 2 votes
In the more general sense, "Billboarding" means that an object in a 3d-scene (usually but not always a 2d-sprite) is always rotated to face the camera. A common use-case are spatial UI elements in a 3d scene. Take, for example, a real-time strategy game with a 3d engine where every unit has a health-bar below it. That health-bar would use billboarding to always be fully readable for the player no matter how they rotate the camera.

But in the specific context of performance optimization, Billboarding means that complex 3d models are rendered to 2d sprites and those sprites are then used in a billboarding manner. This means the object only needs to be rendered in full detail once and can then be inserted multiple times into the 3d scene as a simple textured square. This greatly improves rendering speed of a large number of identical, complex 3d objects (a forest of trees is the most obvious example). Such billboards are also called "imposters".

However, it has a price: This shortcut becomes very visible on short distances where it becomes obvious that shadows and clipping are way off. That's why it is usually only used for very far-away objects while closer instances of the same object are properly rendered in 3d.

Also, when you only use one sprite for each object, it might look a bit strange when the object is seen from a different angle than the billboard-screenshot was taken, for example when you are flying far above the forest and you still see all the trees from the side. That's why imposter systems often take screenshots from several directions of a 3d model and draw the one closest to the current view-angle when rendering.

Unity does have an imposter system built in, but unfortunately only allows you to use it for the Tree component in conjunction with the Terrain component. When you don't use the Unity terrain and want to use an imposter for something you can not generate through the SpeedTree system, then you will have to either use a 3d party asset or program it on your own.

# Answer
> 1 votes
Billboarding draws 2d sprites instead of 3d ones, when they are far away. This wouldn't look good, if you don't rotate them, so they always face the camera. This technique can make the game run a lot faster, because instead of drawing 1000 or more polygons for a single tree, you only draw a 2d rectangle with the image of the original tree.

---
Tags: unity, rendering, performance, billboarding
---


# Question
Title: Unity mesh collider detecting collision on object empty inside
I'm trying to get my first 3D game done with Unity. In this game the character will be flying through some rings.

I made the ring asset with MagicaVoxel, exported it in .obj and reimported in Unity withouth problems. I've set a rigidbody and a box collider on the character model and a mesh collider withouth rigidbody to the ring and I've also set Convex and added the default mesh of the ring.

The problem is that whenever I try to go inside the ring, I can't because I collide even with the empty part inside it. I'm not sure on how to made Unity collide only with the external part, but as far as I can see in the editor I'm using, I've no setting for it. I'm using Unity 5.3.4f1.

Can someone please explain me how to solve this problem?

Thank you very much.

**EDIT**

I'm sorry, I forgot to mention that I'm aware I can unset the ring mesh Convex property and get it to work. The problem of this solution, though, is that whenever I put adjacent rings I can glitch through them even if there's no space to fit. So basically I need a solid collider with Convex only on the external part of the ring and with empty space to fly through on the inside. Is this possible somehow?

# Answer
Unmark convex on the mesh collider. Convex mesh colliders will NOT have holes in them because that is required, by definition, to make them convex. Non-convex mesh colliders are only supported on kinematic rigidbodies and objects without rigidbodies, which should be fine for your usage.
> 1 votes

---
Tags: collision-detection, unity, assets, mesh, meshcollider
---


# Question
Title: How to draw a Minecraft-like world with Open GL
I recently completed the this Open GL tutorial. The tutorial shows how to set up a window and shaders, and teaches you how to draw a single cube in the middle of the screen, which all makes sense to me (I think).

I'd like to make just a simple flat world made of cubes like Minecraft, but I have no idea how to turn my single giant cube into a bunch of smaller cubes, or how to get the smaller cubes to be arranged in the proper way.

Mostly what doesn't make sense to me is the coordinate system being from 1 to -1 and trying to draw a bunch of cubes in that space. Is there a way to adjust that coordinate space to be more world-like, where each unit of coordinate space is roughly equivalent to a meter or something?

# Answer
> 2 votes
You start with "Object Space" which is unique to each piece of geometry. Each piece of geometry you load might be at a different scale, with (0,0) at seemingly random places. It is entirely arbitrary.

The World Matrix rotates, scales, and translates each of those coordinates into a common coordinate system, "World Space". After the world transform, all objects are measurable in world-units (feet/meters/furlongs/whatever).

The View Matrix is the camera's World Matrix, inverted. The view matrix actually "un-moves" the entire world as a single model. After the view transform, the camera becomes (0,0) and all coordinates become relative directions "away from" the camera. View-space units are usually the same as world-space units.

The Projection Matrix defines the dimensions of view-space visible at the nearplane and how those dimensions change as scene-depth increases. Orthogonal projection defines a cube of view-space while perspective projection defines a truncated pyramid shape. During projection, the shape is squished into a cube, altering view-space as necessary. Since orthogonal projection is already a cube, no squishing is performed. Perspective is usually wider at the farplane and, so, distant objects appear smaller.

The final result of projection is a universal coordinate system called Normalized Device Coordinates, or NDC, where (-1,-1) is the lower-left corner of any screen and (1,1) is the upper-right corner.

# Answer
> 2 votes
You need to read about coordinate/space transformations, in that site is explained well. You can't go far without understanding that.

https://open.gl/transformations

Without using any transformation, you are basically bounded by the OpenGL clip-space which is contained in a cube with opposite vertices (1,1,1) and (-1,-1,-1) , as you stated correctly.

# Answer
> 0 votes
I recently found a great tutorial of drawing Minecraft's graphics by drawing it in RT in Unity 4 but 5 is still compatible with the code. It's a basic tutorial and it can be made into a cube and the top has more- cubes on it but they're at different places like 3 down, 1 up you get the point basically a big cube but with smaller ones at the top. Here's the tutorial have fun (It does not include the sky but comes with pre-made sky assets) the title is misleading and it's quality with simplicity. Hope it helps http://in2gpu.com/2014/07/27/build-minecraft-unity-part-1/ and its all RNG. Although it's not OpenGL but it's the best I could find tutorial wise.

# Answer
> -2 votes
Think of it as a SimCity with treasure hunts and lost-in-the-jungle adventures of infinite potentialities. First-time players of Minecraft enter a blank “natural” landscape of trees. Discovering that the sun can shortly set and darkness is nigh, they need to gather wood and build a shelter or risk being destroyed by the monsters of the night. because the name of the sport suggests, players mine the surroundings for materials then craft things like pickaxes, fishing rods, even chocolate-chip cookies. (When Conan O’Brien reviewed Minecraft recently as a part of his series “Clueless Gamer,” he said: “Taking things out of the bottom then building things. … thus it’s like we’re in Wales within the nineteenth century and we’re urgently poor. What a fun game for youths.”) How to Draw Tutorials Once that task is perfect, different opportunities beckon: Mine for diamonds, tame cats, stock chests with found objects, produce glass windows by building kilns and gathering sand, create bows and arrows out of spiderwebs (but be careful—vanquish those spiders first!), lay out railroad-like roller coasters, style wonderlands for friends to go to. there's without stopping to the choices.

---
Tags: opengl, maps
---


# Question
Title: Should I Include the W-component of a vector when calculating it's length or dot product?
The reason I'm asking this is because I saw an implementation which did it that way but I don't quiet understand it. I mean, usually I want to get the distance between two points in 3d space and if W is something other than 0 the result is not correct. The same when calculating lighting using the dot product.

```
float Vector::Length() const{
    return sqrtf(X * X + Y * Y + Z * Z + W * W);    //W necessary?
}

float Vector::Dot(const Vector& other) const{
    return X * other.X + Y * other.Y + Z * other.Z + W * other.W;
}

```

Edit: There are suggestions that my question is a duplicate of already existing ones. But the questions referred to are about whether you need the W component at all and for what. I know what I need it for, I'm just not sure about it's role in the operations I specified.

# Answer
> 2 votes
The only reason you need to extend a vector to 4 dimensions (homogeneous coordinates, not 4-Dimensional space) is so that you can apply transforms or matrices (model, etc) to it. Unless you're explicitly making a game in a 4-Dimensional space you don't need to include the `w` component in the calculations you mentioned.

Indeed, as you noted, using a w different than 0 will of course yield wrong results for your typical 3D calculations.

---
Tags: c++, vector
---


# Question
Title: What is the maximum value of a LayerMask in Unity?
What is the maximum value of a LayerMask in Unity (the value when all layers are included)? And how can I find it using C# bitwise operations?

I tried `~0` but it shows `-1` in intellisense.

Thanks in advance.

# Answer
**Edit:** I actually realised there is a Physics.AllLayers field that is returning the same value.

---

I ran the following code, and it conviced me enough to believe that `~0` is the maximum value of layermask. All results were `true`.

```
int t1 = 1 << 1;
int t2 = 1 << 2;
int t3 = 1 << 3;
int t4 = 1 << 4;
int t5 = 1 << 5;

int max = ~0;

bool r1 = (max & t1) == t1;
bool r2 = (max & t2) == t2;
bool r3 = ((max | t3) & t1) == t1;
bool r4 = ((max | t4) & t2) == t2;
bool r5 = ((max | t5) & t5) == t5;

Debug.Log(r1);
Debug.Log(r2);
Debug.Log(r3);
Debug.Log(r4);
Debug.Log(r5);

```
> 0 votes

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


# Question
Title: How can I set up Unity so that 2d images are displayed in their original resolution?
I took images from my iOS game that I am developing in SpriteKit and put them in a Unity Android 1136x640 screen, which are the same dimensions for the iOS game but the images are a lot smaller. How can I get a similar representation that coincides with the screen size? I would like a 284x640 image to be displayed to take a quarter of the screen width, which is what happens in reality.

# Answer
There are several things which affect sprite scaling in Unity.

* When you import a sprite in Unity, there is a setting *Pixels per unit* for the sprite asset in your project folder structure. Use this setting to scale the sprite.
* All Game objects have a *Scale X, Y* and *Z* in their Transform-component which makes them larger or smaller. Note that the scale of a parent game-object also affects all of its child-objects.
* When your camera is set to *Projection: Orthographic*, then the property *Size* defines how many units fit on the screen.
* When your camera is set to *Projection: Perspective*, then objects closer to the camera will look larger than those further away. The *Field of View* also allows you to control the zoom factor.

When your camera is orthographic, then the vertical height of the viewport in Unity units is twice the camera size. That means to get 1 px image = 1px on screen, set the Pixels per unit to your vertical screen resolution divided by twice the camera size.

When you have a camera size of 5 (default) and you target a 640px high display, set the ppu to `640 / (5 * 2) =` 64.

You might also want to set the *Filter Mode* of your images to *"Point (no filter)"* to avoid sprites getting blurred when their positions are not perfectly on-pixel.
> 2 votes

# Answer
Select your canvas and set the canvas scaler to scale with screen size. This way whatever is your image size it will be resized according to your screen resolutions.
> 0 votes

# Answer
If you select your image and make sure it's set as a sprite, you'll notice an import property called pixels per unit. Changing this will change the scale of your sprite. There are other factors though, such as the camera settings. It sounds like what you're looking for is pixel perfect rendering. Here's a good resource for that: http://blogs.unity3d.com/2015/06/19/pixel-perfect-2d/
> 0 votes

---
Tags: unity
---


# Question
Title: How can I identify loaded models so I can efficiently avoid loading them twice?
I'm making a fairly basic OpenGL 3D engine, at the moment. In this engine, when you load an object, you would write

```
manager->LoadObjFile("cube.obj");
manager->AddParent("uvmap.bmp", "cube.obj", "cube", glm::vec3(10.0f, 1.0f, 0.0f));

```

"uvmap.bmp" being the texture, "cube.obj" is the `.obj` file path, "cube" being the ID for the object.

My question is, at the moment, when it loads an object, it stores the object in a struct with all of the buffer data and an ID, the ID being the path of the obj file, so when I load an `.obj`, it runs through all of the already loaded files and compared the ID of each using `strcmp`, which obviously when there's thousands of items, is going to start to get a bit slow.... it does the same for `AddParent`, and most of my other methods (different vector of data than where the obj data is stored).

What would be best in terms of identifying items, an integer? I really don't know, I want this to be as high level, user friendly as possible, but want to keep it as optimized and as efficient as possible.

# Answer
> 2 votes
Using integer ID's allows you to keep all your objects in an `std::vector<GameObject>`. Accessing a vector by index is a constant-time operation.

If you want to keep using strings as object keys (having human-readable keys might be more convenient for the user), consider using an `std::unordered_map<string, GameObject>` to map strings to objects. It is usually implemented as a hashtable, which means search time is also constant (but a far longer constant than a vector).

But the question is if you need such object-ID's and a central object index at all. You could instead have an object-oriented API where `manager->LoadObjFile` returns an object and any manipulation of that object are then performed by calling methods of that object, not indirectly through the manager:

```
cube = manager->LoadObjFile("cube.obj");
cube.setTexture("uvmap.bmp");
cube.setPostition(glm::vec3(10.0f, 1.0f, 0.0f));

```

---
Tags: opengl, c++, architecture
---


# Question
Title: How can I make the ball in pong move even if no event is taking place in Allegro5?
I've been trying to make a pong game with C++ and allegro5, I found moving the ball around easy with SFML, but in allegro5 I don't know what I can do to move it around, right now, it moves but only when one of the paddles is moving, could you please help me?

Here is the code I have now:

```
int main(){
  int d = 200;
  int f = 200;
  int x = 700;
  int y = 100;
  int a = 100;
  int b = 100;
  int ballx = 10;
  int bally = 10;
  bool ballmoving = true;
  al_init_image_addon();
  ALLEGRO_BITMAP *Player1;
  ALLEGRO_BITMAP *Player2;
  ALLEGRO_BITMAP *ball;
  ALLEGRO_DISPLAY *display = NULL;
  ALLEGRO_EVENT ev;
  ALLEGRO_EVENT_QUEUE *eventqueue = NULL;
  bool playing = true;
  al_init();
  al_init_primitives_addon();
  display = al_create_display(800, 600);
  al_install_keyboard();
  eventqueue = al_create_event_queue();
  al_register_event_source(eventqueue, al_get_keyboard_event_source());
  al_register_event_source(eventqueue, al_get_display_event_source(display));
  Player1 = al_load_bitmap("rectt.png");
  Player2 = al_load_bitmap("rectt.png");
  ball = al_load_bitmap("ball.png");

  while (playing){
    ballx = ballx + 5;
    bally = bally + 5;

    al_clear_to_color(al_map_rgb(255, 255, 0));
    al_wait_for_event(eventqueue, &ev);
    if (ev.type = ALLEGRO_EVENT_KEY_DOWN){
      switch (ev.keyboard.keycode){
      case ALLEGRO_KEY_UP:
        y -= 5;
        break;
      case ALLEGRO_KEY_DOWN:
        y += 5;
        break;
      case ALLEGRO_KEY_W:
        b -= 5;
        break;
      case ALLEGRO_KEY_S:
        b += 5;
        break;
      }
    }

    al_draw_bitmap(Player1, x,y, 0);
    al_draw_bitmap(Player2, a,b, 0);
    al_draw_bitmap(ball, ballx, bally, 0);
    al_flip_display();
  }

  al_flip_display();
  al_rest(5);
}

```

EDIT:- I'm now trying to use timers, but for some reason it isn't working, the ball isn't moving at all, could you please help? This is the new code:-

```
 #include <stdio.h>
#include <allegro5/allegro.h>
#include "allegro5/allegro.h"
#include "allegro5/allegro_image.h"
#include <allegro5/allegro_native_dialog.h>
#include <allegro5/allegro_primitives.h>
#include <allegro5/color.h>
#include <allegro5/allegro_color.h>
#include <allegro5/allegro5.h>
#include <allegro5/color.h>

ALLEGRO_EVENT ev;
int main(){
int d = 200;
int f = 200;
int x = 700;
int y = 100;
int a = 100;
int b = 100;
int ballx = 10;
int bally = 10;
bool ballmoving = true;
al_init_image_addon();
ALLEGRO_BITMAP *Player1;
ALLEGRO_BITMAP *Player2;
ALLEGRO_BITMAP *ball;
ALLEGRO_DISPLAY *display = NULL;

ALLEGRO_EVENT_QUEUE *eventqueue = NULL;
ALLEGRO_TIMER *timer = NULL;

bool playing = true;
al_init();
al_init_primitives_addon();
display = al_create_display(800, 600);
al_install_keyboard();
eventqueue = al_create_event_queue();
timer = al_create_timer(1.0 / 60.0);
al_register_event_source(eventqueue, al_get_keyboard_event_source());
al_register_event_source(eventqueue, al_get_display_event_source(display));
al_register_event_source(eventqueue, al_get_timer_event_source(timer));
Player1 = al_load_bitmap("rectt.png");
Player2 = al_load_bitmap("rectt.png");
ball = al_load_bitmap("ball.png");

while (playing){

    al_clear_to_color(al_map_rgb(255, 255, 0));
    al_wait_for_event(eventqueue, &ev);
    if (ev.type == ALLEGRO_EVENT_TIMER){

        ballx = ballx + 10;
        bally = bally + 10;
    }
        if (ev.type = ALLEGRO_EVENT_KEY_DOWN){
            switch (ev.keyboard.keycode){
            case ALLEGRO_KEY_UP:
                y -= 5;
                break;
            case ALLEGRO_KEY_DOWN:
                y += 5;
                break;
            case ALLEGRO_KEY_W:
                b -= 5;
                break;
            case ALLEGRO_KEY_S:
                b += 5;
                break;

            }
        }

        al_draw_bitmap(Player1, x, y, 0);
        al_draw_bitmap(Player2, a, b, 0);
        al_draw_bitmap(ball, ballx, bally, 0);
        al_flip_display();
    }

al_flip_display();
al_rest(5);
}

```

EDIT: I've solved the problem by actually starting the timer. Here is the code for anybody who needs help with their code. It's definitely not perfect, but I hope it can help who needs it.

```
ALLEGRO_EVENT ev;
int main(){
int d = 200;
int f = 200;
int x = 700;
int y = 100;
int a = 100;
int b = 100;
int ballx = 10;
int bally = 10;
bool ballmoving = true;
al_init_image_addon();
ALLEGRO_BITMAP *Player1;
ALLEGRO_BITMAP *Player2;
ALLEGRO_BITMAP *ball;
ALLEGRO_DISPLAY *display = NULL;

ALLEGRO_EVENT_QUEUE *eventqueue = NULL;
ALLEGRO_TIMER *timer = NULL;

bool playing = true;
al_init();
al_init_primitives_addon();
display = al_create_display(800, 600);
al_install_keyboard();
eventqueue = al_create_event_queue();
timer = al_create_timer(1.0 / 60.0);
al_register_event_source(eventqueue, al_get_keyboard_event_source());
al_register_event_source(eventqueue, al_get_display_event_source(display));
al_register_event_source(eventqueue, al_get_timer_event_source(timer));
Player1 = al_load_bitmap("rectt.png");
Player2 = al_load_bitmap("rectt.png");
ball = al_load_bitmap("ball.png");

while (playing){

    al_clear_to_color(al_map_rgb(255, 255, 0));
    al_wait_for_event(eventqueue, &ev);
    al_start_timer(timer);
    if (ev.type == ALLEGRO_EVENT_TIMER){

        ballx = ballx + 10;
        bally = bally + 10;
    }
        if (ev.type = ALLEGRO_EVENT_KEY_DOWN){
            switch (ev.keyboard.keycode){
            case ALLEGRO_KEY_UP:
                y -= 5;
                break;
            case ALLEGRO_KEY_DOWN:
                y += 5;
                break;
            case ALLEGRO_KEY_W:
                b -= 5;
                break;
            case ALLEGRO_KEY_S:
                b += 5;
                break;

            }
        }

        al_draw_bitmap(Player1, x, y, 0);
        al_draw_bitmap(Player2, a, b, 0);
        al_draw_bitmap(ball, ballx, bally, 0);
        al_flip_display();
    }

al_flip_display();
al_rest(5);
}

```

Thanks everyone for the help, I really appreciate it :)

# Answer
> 4 votes
If you use `al_wait_for_event`, then you need to use a `ALLEGRO_TIMER` as well to generate pulses (every 1/60th of a second for example) and you update your movement every pulse. That way there is always an event happening on Allegro.

If you still don't want to use a timer, you can use `al_wait_for_event_until` and then specify till when you wait for an event for then to continue with your program.

# Answer
> 1 votes
One way to do this is to only run physics and render code when the event queue is empty:

```
ALLEGRO_EVENT_QUEUE* e = al_create_event_queue();
al_register_event_source(e, al_get_keyboard_event_source());
al_register_event_source(e, al_get_mouse_event_source());
al_register_event_source(e, al_get_joystick_event_source());
al_register_event_source(e, al_get_display_event_source(&display));

al_clear_to_color(al_map_rgb(0, 0, 0));
al_flip_display();

auto start_time = std::chrono::high_resolution_clock::now();
auto end_time = std::chrono::high_resolution_clock::now();
auto accumulator_start = std::chrono::high_resolution_clock::now();

bool _isQuitting = false;

while(!_isQuitting) {
    _deltaTime = end_time - start_time;
    start_time = std::chrono::high_resolution_clock::now();

    ALLEGRO_EVENT ev;
    while(al_peek_next_event(e, &ev)) {
        //...Handle Events Here...
        al_drop_next_event(e);
    }

    while((std::chrono::high_resolution_clock::now() - accumulator_start).count() >= 16666666 /* 1/60 second in nanoseconds */ ) {
        if(!_IsQuitting) {
            //...Run Physics Code here...
        }
        accumulator_start = std::chrono::high_resolution_clock::now();
    }

    if(!_IsQuitting) {
        //...Run Render Code Here...
    }

    end_time = std::chrono::high_resolution_clock::now();
}

al_unregister_event_source(e, al_get_keyboard_event_source());
al_unregister_event_source(e, al_get_mouse_event_source());
al_unregister_event_source(e, al_get_joystick_event_source());
al_unregister_event_source(e, al_get_display_event_source(&display));

```

I did notice that you are not cleaning up your bitmaps. It is a good idea to clean up the memory used in your application.

---
Tags: c++, movement, allegro
---


# Question
Title: Translating a world position to an array position
Lets keep this simple, so, assuming I have an array like this ...

```
var array = new bool[10,10,10];

```

.. and then I have a start and end vector3 ...

```
var start = new Vector3(-21,-21,-21);
var end = new Vector3(-10,-10,-10);

```

... these booleans represent some data for a part of my virtual world, but they are a small chunk of that data between the start and end points in the world.

How do I, given a point in the virtual world translate that position to a point in the array ...

```
var pos = new Vector3(-20,-20,-20);

var result = GetValueAt(pos);

bool GetValueAt(Vector3 pos)
{
    // my question is:
    //what goes in here to translate from pos to array pos [1,1,1] ?
   return array[1,1,1];
}

```

# Answer
Simply subtract the start-vector from the position-vector and you get the array indices.

```
bool GetValueAt(Vector3 pos)
{
   return array[pos.x - start.x, pos.y - start.y, pos.z - start.z ];
}

```

You might also want to add some error-checking in case the caller provides a position outside of the array.

Also, this code assumes that all three coordinates of `start` are smaller than those of `end`. When that is not always the case, you need to find the smaller value on each axis and subtract that one from the corresponding axis of `pos`.
> 3 votes

# Answer
```
var pos = new Vector3(-20,-20,-20);

var result = GetValueAt(pos);

bool GetValueAt(Vector3 pos)
{
   return array[pos.x, pos.y, pos.z];
}

```

You can just pull the coords out separately.
> -3 votes

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


# Question
Title: What is the difference between resource.texture() and resource.image()?
```
image = pyglet.resource.image('spritesheet.png')
image.blit(0,0)

```

And

```
image = pyglet.resource.texture('spritesheet.png')
image.blit(0,0)

```

doing the same thing - they are drawing a spritesheet (or only one image), and they returns Texture type.

# Answer
From the documentation (link):

> **pyglet.resource.texture** is for loading stand-alone textures, and would be required when using the texture for a 3D model.
>
> **pyglet.resource.image** is optimised for loading sprite-like images that can have their texture coordinates adjusted. The resource module attempts to pack small images into larger textures (called an atlas) for efficient rendering (which is why the return type of this function can be TextureRegion).
> 1 votes

# Answer
Honestly, there is no difference. Both return the same thing and function the same exact way. It could just be personal preference, so choose what you want.

Cheers,

Bryce
> -3 votes

---
Tags: pyglet
---


title: Replace text in Unity

text:
# Question
Title: Replace text in Unity
i tried to look up my question but didn't really find an answer that works for my situation.

I'm using this unity asset called Dialoguer to create interactive dialogues. What I'm trying to do is to pass a test in the asset, that test if a condition is true, then replace a specific part of the output text.

My problem right now is I can't find the right code to check for a specific string and replace it with another.

Please help

# Answer
> 0 votes
This answer goes the normal Unity way and disregards that you use the 3rd party Dialoguer system. It might provide a better way to do this or might even conflict with this method, but please forgive me that I won't pay $30 just to better answer this one question. But I noticed that the marketing bullet points for it mentions an "integrated variable system" which might help you to do what you want to do.

---

The text of an UI Text component is stored in the property `text`. Its value is a `string`, which is one of the basic classes of the C# language, so we need to head to the Microsoft Developers Network to read its documentation. There we find the method `Replace(string oldValue, string newValue)`, which "Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string". So all you need to do in your script is get a reference to your Text UI element and then do:

```
 textUIElmenent.text = textUiElement.text.Replace("oldString", "newString");

```

---
Tags: c#, unity, text, text-based
---


# Question
Title: Do Game-Maker scripts save the variables or are they deleted after excecution?
When i make a script that excecutes at the beggining and has a var ammo and that finishes excecution, will i be able to call the var ammo in other scripts or it will be deleted? If it will not be deleted, will I be able to change its value on other scripts?

Thanks in advance.

# Answer
> 1 votes
This question can be expanded to almost all modern languages. The short answer is: no, it won't, the long answer is:

In programming, there's a word called `scope`, a scope is a chunk of code defined by the enclosing statements in the programming language (in most of the languages, they're brackets {}). There can be multiple scopes inside another scopes, creating a hierarchy system.

A scope has 2 types of variables. local and global. Global variables are defined in a parent scope, and can be overriden by local variables. Local variables are only available in that scope or the child-scopes. They get removed once the scope is removed. If you name a loca, variable the same as a global, the global gets overridden but it dodsn't get deleted, nor changed.

In your case, ammo is a local variable to script "A". Once script "A" is finished, ammo gets deleted, and can't be reached by other scripts.

---
Tags: scripting, game-maker
---