# Question
Title: Why is my character passing through in Box2D?
I have a collision problem in Box2D.

I am trying to do a simple platform game with Libgdx, Box2D and TiledMap.

I have a map made with TiledMap:

I load the map in my Android game. I read all the "objects" from the map and draw it on the screen with no problem:

But when I add a player made with Box2D , the player not collides with map objects. He simply passes through:

I have spent two days in this and I can't see my mistake.

Here is my level code:

```
package com.larralde.screens.gamescreens;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.maps.Map;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.larralde.GeometryConflict;
import com.larralde.config.Constantes;
import com.larralde.entities.EntityFactory;
import com.larralde.entities.PlayerContactListener;
import com.larralde.entities.PlayerEntity;
import com.larralde.entities.WorldEntity;
import com.larralde.screens.BaseScreen;
import com.larralde.utils.TiledMapLoader;
import com.larralde.utils.TiledMapObject;

import java.util.ArrayList;

public class Level_01_01 extends BaseScreen {

    private float SCREEN_X, SCREEN_Y;
    private Stage stage;
    private Skin skin;
    private TiledMapRenderer tiledMapRenderer;
    private TiledMap tiledMap;
    private PlayerEntity jugador;
    private World world;
    private Vector3 position;
    ArrayList<TiledMapObject> tiledMapObjects;
    private ArrayList<WorldEntity> actores;

    public Level_01_01(GeometryConflict game, String skinFile){
        super(game);

        SCREEN_X = game.getAppConfig().getScreenX();
        SCREEN_Y = game.getAppConfig().getScreenY();

        stage = new Stage(new FitViewport(SCREEN_X, SCREEN_Y));
        stage.setDebugAll(true);
        position = new Vector3(stage.getCamera().position);
        skin = new Skin(Gdx.files.internal(skinFile));

        world = new World(new Vector2(0, -10), true);
        world.setContactListener(new PlayerContactListener());

        tiledMap = new TmxMapLoader().load("levels/ACTO_01_01.tmx");
        tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap);

        tiledMapObjects = new ArrayList<TiledMapObject>();
        actores = new ArrayList<WorldEntity>();
    }

    @Override
    public void show() {
        EntityFactory factory = new EntityFactory(game.getManager());
        //Gdx.input.setInputProcessor(stage);
        jugador = factory.createPlayer(world, new Vector2(1f, 15f),game);
        stage.addActor(jugador);

        //Cargamos los objetos del mapa
        tiledMapObjects.clear();
        tiledMapObjects.addAll(TiledMapLoader.dameObjetos(tiledMap, 32f, world, "Objetos"));

        //Metemos los objetos en el mundo.
        actores.clear();
        for(TiledMapObject oAux : tiledMapObjects){
            actores.add(new WorldEntity(oAux,world));
        }

        for(WorldEntity aAux : actores){
            stage.addActor(aAux);
        }

        stage.getCamera().position.set(position);
        stage.getCamera().update();
    }

    @Override
    public void hide() {
        stage.clear();

        jugador.detach();

    }

    @Override
    public void dispose() {
        // Dispose assets.
        stage.dispose();
        skin.dispose();
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(0, 0, 0, 1f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        /*if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){
            //stage.getCamera().translate(-32,0,0);
            jugador.setPosition(jugador.getX() - 32, jugador.getY());
        }
        if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
            //stage.getCamera().translate(32, 0, 0);
            jugador.setPosition(jugador.getX() + 32, jugador.getY());
        }
        if(Gdx.input.isKeyPressed(Input.Keys.UP)){
            //stage.getCamera().translate(0, 32, 0);
            jugador.setPosition(jugador.getX(), jugador.getY() + 32);
        }
        if(Gdx.input.isKeyPressed(Input.Keys.DOWN)){
            //stage.getCamera().translate(0, -32, 0);
            jugador.setPosition(jugador.getX(), jugador.getY() - 32);

        }*/

        stage.act();
        world.step(delta, 6, 2);

        /*if (jugador.getX() > 150 && jugador.isAlive()) {
            float speed = Constantes.PLAYER_SPEED * delta * Constantes.PIXELS_IN_METER;
            stage.getCamera().translate(speed, 0, 0);
        }*/
        tiledMapRenderer.setView((OrthographicCamera) stage.getCamera());
        tiledMapRenderer.render();

        stage.draw();
    }

}

```

And the Class that load the objects from the Map:

```
 package com.larralde.utils;

import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.maps.MapObjects;
import com.badlogic.gdx.maps.objects.CircleMapObject;
import com.badlogic.gdx.maps.objects.PolygonMapObject;
import com.badlogic.gdx.maps.objects.PolylineMapObject;
import com.badlogic.gdx.maps.objects.RectangleMapObject;
import com.badlogic.gdx.maps.objects.TextureMapObject;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.math.Circle;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.ChainShape;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.Shape;
import com.badlogic.gdx.physics.box2d.World;
import com.larralde.config.Constantes;

import java.util.ArrayList;

public class TiledMapLoader {

    //El tamaño de los tiles. Ejemplo, si es 16x16 sera 16f. Siempre cuadrados¡¡
    private static float ppt = 0f;

    public static ArrayList<TiledMapObject> dameObjetos(TiledMap map, float pixels, World world, String layerName){
        ppt = pixels;

        MapObjects objects = map.getLayers().get(layerName).getObjects();

        ArrayList<TiledMapObject> tiledMapObjects =  new ArrayList<TiledMapObject>();

        for(MapObject object : objects) {

            if (object instanceof TextureMapObject) {
                continue;
            }

            //Creamos el objeto
            TiledMapObject tiledAux = new TiledMapObject();

            Shape shape;

            if (object instanceof RectangleMapObject) {
                shape = getRectangle((RectangleMapObject) object,tiledAux);
            }
            else if (object instanceof PolygonMapObject) {
                shape = getPolygon((PolygonMapObject)object,tiledAux);
            }
            else if (object instanceof PolylineMapObject) {
                shape = getPolyline((PolylineMapObject)object,tiledAux);
            }
            else if (object instanceof CircleMapObject) {
                shape = getCircle((CircleMapObject)object,tiledAux);
            }
            else {
                continue;
            }

            BodyDef bd = new BodyDef();
            bd.position.set(tiledAux.getX(),tiledAux.getY());
            bd.type = BodyDef.BodyType.StaticBody;
            Body body = world.createBody(bd);
            body.createFixture(shape, 1);

            tiledAux.setBody(body);
            tiledMapObjects.add(tiledAux);

            shape.dispose();
        }

        return tiledMapObjects;

    }

    private static PolygonShape getRectangle(RectangleMapObject rectangleObject,TiledMapObject tiledAux) {
        Rectangle rectangle = rectangleObject.getRectangle();
        PolygonShape polygon = new PolygonShape();
        Vector2 size = new Vector2((rectangle.x + rectangle.width * 0.5f) / ppt,(rectangle.y + rectangle.height * 0.5f ) / ppt);
        polygon.setAsBox(rectangle.width * 0.5f / ppt,rectangle.height * 0.5f / ppt,size,0.0f);

        //Obtenemos la posicion
        Vector2 posicion = new Vector2(0,0);
        rectangle.getPosition(posicion);
        tiledAux.setX(posicion.x);
        tiledAux.setY(posicion.y);
        tiledAux.setHeight(rectangle.getHeight());
        tiledAux.setWidth(rectangle.getWidth());
        tiledAux.setTipoFigura(Constantes.FIGURA_CUADRADO);
        return polygon;
    }

    private static CircleShape getCircle(CircleMapObject circleObject,TiledMapObject tiledAux) {
        Circle circle = circleObject.getCircle();
        CircleShape circleShape = new CircleShape();
        circleShape.setRadius(circle.radius / ppt);
        circleShape.setPosition(new Vector2(circle.x / ppt, circle.y / ppt));

        //Obtenemos la posicion
        Vector2 posicion = circleShape.getPosition();
        tiledAux.setX(posicion.x);
        tiledAux.setY(posicion.y);
        tiledAux.setHeight(circle.radius * 2f);
        tiledAux.setWidth(circle.radius * 2f);
        tiledAux.setTipoFigura(Constantes.FIGURA_CIRCULO);
        return circleShape;
    }

    private static PolygonShape getPolygon(PolygonMapObject polygonObject,TiledMapObject tiledAux) {
        PolygonShape polygon = new PolygonShape();
        float[] vertices = polygonObject.getPolygon().getTransformedVertices();

        float[] worldVertices = new float[vertices.length];

        for (int i = 0; i < vertices.length; ++i) {
            worldVertices[i] = vertices[i] / ppt;
        }
        tiledAux.setTipoFigura(Constantes.FIGURA_POLIGONO);
        polygon.set(worldVertices);
        return polygon;
    }

    private static ChainShape getPolyline(PolylineMapObject polylineObject,TiledMapObject tiledAux) {
        float[] vertices = polylineObject.getPolyline().getTransformedVertices();
        Vector2[] worldVertices = new Vector2[vertices.length / 2];

        for (int i = 0; i < vertices.length / 2; ++i) {
            worldVertices[i] = new Vector2();
            worldVertices[i].x = vertices[i * 2] / ppt;
            worldVertices[i].y = vertices[i * 2 + 1] / ppt;
        }

        ChainShape chain = new ChainShape();
        chain.createChain(worldVertices);

        tiledAux.setTipoFigura(Constantes.FIGURA_CADENA);

        return chain;
    }
}

```

I try to create other objects in Box2D instead of using the TiledMap but not collide.

# Answer
> 0 votes
I have found the problem.

TiledMAp is in Pixels. Box2D works in Meters. Scene2D works in Piexles

I need to convert the Units between meters and Pixels.

# Answer
> 0 votes
You are setting your Bodies to be Static, and this indicates that they are 0 mass, and do not move.

Try setting the body type of your character to Dynamic instead.

https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/physics/box2d/BodyDef.BodyType.html

---
Tags: libgdx, box2d, tiled
---


# Question
Title: Game Loop design that is speed hack proof
I'm not sure if this is possible, but it's worth a shot asking. How does one design a game loop in such a way that hooking and enabling a speed hack app to the game(dx11) doesn't matter?

I found this in stackoverflow:

> I think the reason why i does not work in some applications (mostly games) is because some games link the in game clock to the frames per second. Therefore your game will either tank or crash altogether if you try to speedhack it
>
> ref: https://stackoverflow.com/questions/17512906/how-does-cheatengines-speed-hack-work

# Answer
You can't.

Whatever code runs on the computer owned by the user is under the users control. Anything you program can be circumvented or patched by a determined enough hacker.

The only solution to avoid cheating in an online game is by calculating all game mechanics on the server. When the game is offline, then you have no chance at all.
> 7 votes

# Answer
If you build a networked game, never trust a player more than you trust their controller, just treat them as remote inputs as if they were another controller plugged into the local machine, run all of your final game state simulations on a trusted machine (the host). Most games where speedhacks and other hacks negatively affect players and ruin gameplay only rely on client side simulation for local rendering/sound/reference for state changes sent to server, if the client tells the server something that the server knows isn't true it doesn't matter.

Only trust the host to make authoritative simulations and issue game state corrections to players, it complicates your engine design, but if you want to mitigate hacking, it's a great option.

> Client 2 (Non-host): Player is flying through the air majestically at (100, 0, 100) with 200% health.
>
> Host: Client 2 is sprinting forward at (5, 0, 0) with 20% health.
>
> Host: Client 2 kicked for cheating.
> 2 votes

---
Tags: game-loop, anti-cheat
---


# Question
Title: Unity, how do I pause the Audio in the Level?
I wanna pause the Audio if I press the Pause Button also, I need help..

Pause Script:

```
#pragma strict

var pausemenu: GameObject;

public function pause()
{
    pausemenu.SetActive(true);
    Time.timeScale = 0;

}

public function Resume ()
{
    pausemenu.SetActive(false);
    Time.timeScale = 1;
}

public function Restart ()
{
    Application.LoadLevel("IntroScene");
    Time.timeScale = 1;
}

public function MainMenu ()
{
    Application.LoadLevel("string");
}

public function Quit ()
{
    Application.Quit();
}

```

# Answer
Call `AudioListener.pause = true` in function `pause` and then `AudioListener.pause = false` in function `Resume`. While the audio listener is paused, the whole sound system will be essentially frozen. When you set the paused state to false again, the audio system will resume playing as if nothing had happened.

If you have some sounds which you still want to play during pause (audio feedback from your pause menu, for example), set `ignoreListenerPause = true` on the `AudioSource`s of these sounds.
> 4 votes

---
Tags: unity, 2d, javascript, audio, menu
---


# Question
Title: Box2DLights in libGDX - Bad quality of the light gradient on Android
I am facing a problem while porting one of my libGDX project from desktop to Android : My game uses Box2DLights. While the light effect look very fancy on the desktop version of the game, it looks really ugly on the Android version. The light gradient is not smooth at all. Take a look at the comparative screenshot below :

To use Box2DLights in my game, I use this code in my GameScreen :

```
 rayHandler = new RayHandler(world);
 rayHandler.resizeFBO(Gdx.graphics.getWidth()/5, Gdx.graphics.getHeight()/5);
 rayHandler.setBlur(true);
 RayHandler.useDiffuseLight(true);
 rayHandler.setAmbientLight(new Color(0.15f, 0.15f, 0.15f, 0.1f));

```

Of course, I tried to play with different parameters, such as :

```
RayHandler.useDiffuseLight(fasle);

```

Or

```
rayHandler.diffuseBlendFunc.set(GL20.GL_DST_COLOR, GL20.GL_SRC_COLOR);

```

Or

```
rayHandler.shadowBlendFunc.set(GL20.GL_DST_COLOR, GL20.GL_SRC_COLOR);

```

Everything I tried so fare gave the same ugly light gradient. I already played games that uses Box2DLights that rendered very well on my tablet, thus, I don't think it's due to a limitation of Android.

Does anybody know what's the trick to overcome this problem ?

Thanks !

# Answer
> 2 votes
I suspect what's going on to cause that rainbow coloured banding is that the textures or render targets involved are of a low bit-depth on Android (maybe 5-6-5 instead of 8-8-8). There could also be some texture compression involved somewhere, as 5-6-5 usually only gives green and grey banding, because the green channel has an extra bit.

A quick search suggests that enabling dithering using `Gdx.gl.glEnable(GL10.GL_DITHER);` should help.

Alternatively, you could try changing the background to give it a bit of texture.

# Answer
> 1 votes
Here is the solution :

As Adam said in his answer, the problem was linked to a low bit depth on Android. If you look to the code of AndroidApplicationConfiguration.java, you'll notice at lines 30 and 31 this code :

```
/** number of bits per color channel **/
public int r = 5, g = 6, b = 5, a = 0;

```

Thus, Android applications with libGDX render, by default, low bit images. This can be easily modified in the **AndroidLauncher.java** of your application.

The default AndroidLauncher.java of your app looks like this :

```
public class AndroidLauncher extends AndroidApplication {
    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
        initialize(new MyGdxGame(), config);
    }
}

```

All you have to do, to have a render format of RGBA8888 for your Android app is :

```
public class AndroidLauncher extends AndroidApplication {
    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
        config.r = 8;
        config.g = 8;
        config.b = 8;
        config.a = 8;
        initialize(new MyGdxGame(), config);
    }
}

```

Et voilà ! Here is a comparative screenshot of Android RGB565 VS Android RGBA8888 VS Desktop :

You can see that the Android RGBA8888 is very close to the desktop version.

---
Tags: android, libgdx, box2d, lighting
---


# Question
Title: How do I get to ModPE to perform a function the first time a mod is opened?
I am making a Minecraft PE mod and I want to set a variable *only* on the first launch of the mod. So, how do I make it it set the variable and then not set it again until I import the mod again?

# Answer
> 1 votes
```
function newLevel() {
   if (ModPE.readData("firstLaunch") != true) {
         ModPe.saveData("firstLaunch", true);
         clientMessage("This is the first launch");
   } else {
         clientMessage("This is not the first launch");
   }
}

```

# Answer
> 0 votes
Anyway use newLevel template

```
function newLevel()
{
    //Content
}

```

This will get called at the start of a new level and only at the start

If you want even more flexibility then use rhino and run on the games ui thread. With ModPE you are limited to using the pre made templates and newLevel is your best bet unless you know rhino then you have more flexibility as you can use Java and android libraries at your disposal.

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


title: PS3 controller with Unity on Mac

text:
# Question
Title: PS3 controller with Unity on Mac
I am trying to use my PS3 Controller with Unity but it has been unsuccessful.

I followed this video to do so: https://www.youtube.com/watch?v=LcettC1QHu4

I have done the same thing as the video but for some reason unity is not getting ANY input from the controller.

I have tested the controller with another commercial game on my Mac and it works perfectly, so my controller is well connect to my computer.

here is a screenshot of the input manager:

**joystick button 0** is the **X button**

# Answer
Controllers and platforms have always been a tricky subject. I would suggest you to give a try to InControl ( unmaintained open source version or paid version from the Asset Store ). It's a great plug-in, and it knows how to handle several types of game controller on various platforms.
> 1 votes

---
Tags: unity, playstation3
---


# Question
Title: Why is my perspective layer is painted over ortho layer?
The entire game takes place in ortho with the exception of the background layer which is drawn on a perspective camera.

Everything seems to be working well except that the background is displaying over the orthographic layer. I've tried fidgeting with the layers, orders and depth of cameras but I'm coming up dry.

Take a look at the pics and you may see what I mean.

# Answer
> 4 votes
A higher `Depth`-setting means that the camera will rendered above cameras with a lower `Depth`-setting. As you have currently configured your cameras, the orthographic camera is drawn first and the perspective camera above it afterwards. Set the depth of the foreground-camera to a higher value than that of the background camera.

When you do that, you will only see the foreground and the skybox for now. The reason is that the `Clear Flags` of the foreground-camera is set to "Skybox", so the output of any lower-depth cameras gets replaced with the skybox. Set the clear-flag of the foreground-camera to "Depth Only" and only that of your lowest-depth camera to something else (in this case I would recommend "Solid Color" set to pure black).

---
Tags: unity, 2d, camera
---


title: How to make gravity in Blitz3D?

text:
# Question
Title: How to make gravity in Blitz3D?
I am making a game in Blitz3d and I made simple gravity, however once the object falls on the ground, it goes through it very slowly. The ground is a plane and I have collision on it.

This is a pretty old engine, and not a lot of people are using it but I decided to use it because it's easier than Unity3D for me and it's very basic and customizable.

Here's my code:

```
AppTitle "FPS"
Graphics3D 800,600,32,2
SetBuffer BackBuffer()
SeedRnd MilliSecs()
HidePointer

;Objects
Global player = CreatePivot()
Global camera = CreateCamera(player)
Global cube = CreateCube()
Global light = CreateLight()
Global plane = CreatePlane()
Global cube2 = CreateCube(player)
col_plane = 1
col_player = 2
col_cube = 3

;Vars
gravity# = -.00001
plx# = 0
ply# = 0
plz# = 0
pldx# = 0
pldy# = 0
pldz# = 0

;Textures
CameraClsColor camera,135,206,250
box = LoadTexture("models\box.png")
dirt = LoadTexture("models\dirt.jpg")

;Object Details
EntityType cube,col_cube
EntityType player,col_player
EntityType plane,col_plane
EntityRadius player,1.2
EntityRadius plane,1

PositionEntity player,0,10,5
PositionEntity cube,0,1,5
PositionEntity light,0,2,0
PositionEntity plane,0,0,0
EntityTexture cube,box
EntityTexture plane,dirt
ScaleTexture dirt,5,5
CameraRange camera,0.25,200

;Called Functions
While Not KeyHit(1)
    Cls
    ;Collisions
    Collisions col_player,col_plane,2,2
    Collisions col_player,col_cube,2,2

    If ply < -2 Then
        ply = 0
        pldy = -pldy*.39
    EndIf
    If ply < -1.8 Then
        pldx = .6*pldx
        pldz = .6*pldz
        If KeyDown(57) Then pldy = 2
    EndIf
    pldy = pldy + gravity
    plx = plx + pldx
    ply = ply + pldy
    plz = plz + pldz
    PositionEntity player,EntityX(player)+plx,EntityY(player)+ply,EntityZ(player)+plz

    control()
    RenderWorld()
    UpdateWorld()
    MoveMouse GraphicsWidth()/2, GraphicsHeight()/2
    Flip
Wend

End

;Functions
Function control()
    If KeyDown(42) ;Shift (for running)
        If KeyDown(17) And KeyDown(30) ;W and A
            MoveEntity player,-0.15,0,0.15
        ElseIf KeyDown(17) And KeyDown(32) ;W and D
            MoveEntity player,0.15,0,0.15
        ElseIf KeyDown(17) And KeyDown(30) ;S and A
            MoveEntity player,-0.15,0,-0.15
        ElseIf KeyDown(17) And KeyDown(32) ;S and D
            MoveEntity player,0.15,0,-0.15
        ElseIf KeyDown(17) ;W
            MoveEntity player,0,0,0.15
        ElseIf KeyDown(31) ;S
            MoveEntity player,0,0,-0.15
        ElseIf KeyDown(30) ;A
            MoveEntity player,-0.15,0,0
        ElseIf KeyDown(32) ;D
            MoveEntity player,0.15,0,0
        End If
    Else ;Walking
        If KeyDown(17) And KeyDown(30) ;W and A
            MoveEntity player,-0.1,0,0.1
        ElseIf KeyDown(17) And KeyDown(32) ;W and D
            MoveEntity player,0.1,0,0.1
        ElseIf KeyDown(17) And KeyDown(30) ;S and A
            MoveEntity player,-0.1,0,-0.1
        ElseIf KeyDown(17) And KeyDown(32) ;S and D
            MoveEntity player,0.1,0,-0.1
        ElseIf KeyDown(17) ;W
            MoveEntity player,0,0,0.1
        ElseIf KeyDown(31) ;S
            MoveEntity player,0,0,-0.1
        ElseIf KeyDown(30) ;A
            MoveEntity player,-0.1,0,0
        ElseIf KeyDown(32) ;D
            MoveEntity player,0.1,0,0
        End If
    End If

    While KeyDown(16) ;Q
        RotateEntity camera,MouseXSpeed(),10,10
    Wend
    While KeyDown(18) ;E
        RotateEntity camera,0,-10,-10
    Wend

    TurnEntity player, 0, -MouseXSpeed()/6.0, 0
    TurnEntity camera, MouseYSpeed()/6.0, 0, 0
    If EntityPitch(camera) < -70
        RotateEntity camera, -70, EntityYaw(camera), EntityRoll(camera)
    ElseIf EntityPitch(camera) > 70
        RotateEntity camera, 70, EntityYaw(camera), EntityRoll(camera)
    EndIf
End Function

```

If there's some one who can actually help me with this, I would appreciate it.

# Answer
(Blitz3D, blast from the past!)

It's been so long so a bunch of things I'm wondering about (these may or may not be relevant to your question): Why are you setting a collision radius for the plane? Why are you calling 'Collisions' every frame, rather than once when declaring the collision types? Shouldn't UpdateWorld() be before RenderWorld()?

All three of these things are related to collision detection, and are oddities I spotted in your code:

1) The plane shouldn't have a collision radius defined, since it will be used for polygon collisions and not sphere collisions.

2) The 'Collisions' command sets the relationship between various collision types, so it only needs to be set once to say "this type of object collides with that type of object"

3) Collision detection is actually applied during UpdateWorld(), so you would want the simulation to resolve collisions before drawing the frame.
> 2 votes

# Answer
I am posting my own answer saying exactly *what I did*.

First off, I moved

```
Collisions col_player,col_cube,2,2
Collisions col_player,col_plane,2,2

```

out of the `While Not KeyHit(1)` loop, as that might have conflicted with my current gravity code. Second off, I removed `EntityRadius plane,1`, and thirdly I put `UpdateWorld()` before `RenderWorld()`, and everything works just as expected now! Big thanks to **@jhocking**!
> 1 votes

# Answer
so this is pretty easy... collision detection is the best method- once you have the collisions between terrain or plane and your player entity then do this...

your code:

```
ElseIf KeyDown(30) ;
MoveEntity player,-0.1,0,0

```

change to:

```
ElseIf KeyDown(30) ;
MoveEntity player,-0.1,-0.1,0

```

This way there will be a downward Y force on the player- this will make it more difficult to climb rising terrain and also provide for a falling motion.
> 0 votes

---
Tags: software-engineering, blitzmax
---


# Question
Title: Gameobjects disappearing when changing renderer.material.color
I'm generating an array of objects using this code:

```
    while(currentPosition.z < poolSize){
        var ringObj = GameObject.Instantiate(ring) as GameObject;
        ringObj.transform.position = currentPosition;
        ringObj.GetComponent<Renderer>().material.color =  new Color (1.0f, 0f, 0f);
        // Adds the ring to the pool.
        pool[(int)currentPosition.z] = ringObj;
        updateCurrentPosition ();
    }

```

This works fine without this line:

```
ringObj.GetComponent<Renderer>().material.color =  new Color(Random.Range(0.0f,1.0f), Random.Range(0.0f,1.0f), Random.Range(0.0f,1.0f));

```

Which should randomize the color of the object. The problem is that instead of doing this, the whole code would generate only one object (I can see it on the hierarchy view) with the standard material color and then stops the generation. Also, the material is not changing color.

I can't understand why this happens. Can someone explain this to me, please? I'm using Unity 5.3.4f1. Thank you.

# Answer
Place this on an empty `GameObject` in the scene:

```
public class TestColourAndPosition : MonoBehaviour
{
    void Start ()
    {
        for (int i = 0; i < 10; i++)
        {
            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            cube.transform.position = new Vector3(i * 2.0f, 0, 0);
            cube.GetComponent<Renderer>().material.color =  new Color(Random.Range(0.0f,1.0f),Random.Range(0.0f,1.0f),Random.Range(0.0f,1.0f));
        }
    }

    void Update ()
    {
    }
}

```

...No problem with generating random material colours or simple `GameObject` positioning.

So I suspect your problem comes before that, and is corrupting some values leading to the crash.

I suggest you use the above and work slowly and steadily back toward what you want. And don't call `updateCurrentPosition()` (in `Update()` or `LateUpdate()`) until you can position the objects statically / once off, without experiencing *any* problems. And switch in your 3D model only once all else is working, in case there is a model problem - unlikely, but possible.

**Morals of the story** When stumped, revert to a minimal test case and make your way from there. Always test incrementally as you code - so you know the *exact* change where things begin to fail.
> 2 votes

---
Tags: rendering, unity, procedural-generation, color, materials
---


# Question
Title: Can't load own .obj-files from Blender to DX11
I'm currently trying to import objects to my game. My problem is that I'm able to load objects from online-sites but it doesn't work for my own objects. It gives me an error:

> Debug assertion failes. Expression: vector subscript out of range.

So I watched the value of my vector and realized that the faces are empty. The difference between my obj and these from the internet are that in mine the faces are like:

> f 53//51 69//51 54//51

And in the files from online they look like:

> f 3551/5154/3181 3666/5155/3182 3543/5151/3178

What do I wrong at exporting my blender-object. I took a screenshot of my settings:

I hope you can help me.

# Answer
> 1 votes
Sorry for this question. I solved my problem. But I'll leave this post with it's answer here. I forgot to add my uv texture cords correctly. To do this in blender I pressed 'u' and chose "Smart UV Project" in edit-mode. This worked but gave me interesting uv's. To mark your uv's on your own in the edit-mode you can select the vertices you need. Press ctrl + 'e' and select "Mark Seam". Then export your project again and it should work.

---
Tags: blender, obj
---


title: Why are so many games not fully voiced?

text:
# Question
Title: Why are so many games not fully voiced?
I'm wondering why so many MMOs are only partially voiced? I asked makers of games (Thimbleweed Park, in their Q&A) how expensive voiceover is, and they said it wasn't especially expensive unless you hire A-list stars. So why would so much game dialogue be only present as text to be read onscreen?

The only reason I can think of is the same that exists for localization in all software: You can't record VO until all the dialogue is finished and frozen, so it is another fixed delay between finishing the rest of the game and shipping. So it doesn't seem like it's not manageable.

To be clear: I'm not looking for opinions or theories (that would only make the mods close this question) but actual reasons and experiences from people who have shipped games with partial voiceover.

# Answer
> 88 votes
Because voice acting is more expensive than just the payment for the actors.

It's not just the voice actors you need to hire. First, you need to find voice actors which are suitable for your roles. That means you will have to do a casting with many actors, which takes you a lot of time. Then when you have picked the actors and made contracts with them, you need a professional sound studio with professional sound technicians to record their lines. These can be quite expensive too.

Also, voice-acted lines are a lot less flexible. Say you find out during pre-release QA testing that a certain line of text is confusing, doesn't have the effect you thought it had or is just plain wrong after you changed a few things in the game. When it's just text, then changing it is just a few keystrokes. But when the line is voiced, you need to re-hire the actor (hope he got time in his schedule), get him back into the studio and have him re-record that one line.

There is the problem with releasing additional content after release. Artists, writers and programmers are replaceable, but voice actors are not. When the voice actor for an important character got a different obligation, your whole DLC project might have to be cancelled.

And then there is the problem with dynamic text. When you have procedurally generated sentences like "Pick up \[item\] from \[person\] in \[location\]", adding a voice-over means you have to record the segments individually and then cut them together at runtime, which can sound quite strange and artificial. When your game is fully voice-acted but that line is not, then it might sound quite strange, so you better cut down the voice acting in general.

# Answer
> 14 votes
One element the other answers have not touched on is size. Sound files are substantially larger than text files. Every single spoken line is that much more data that must be downloaded to the player's system, written to their HDD, or usually both.

In turn, spoken dialogue takes up more memory when the game is executed. Memory that could be used for various other purposes, such as prefetching the next part of the cutscene or monster AI if it is spoken lines in combat. It also increases load times.

# Answer
> 9 votes
Time, is the problem. When you try to localize the voices for every language you publish, you would need to spend so much time on voice-over.

Synchronizing animations are another problem. When you are voice-overing a character, it would be so much unrealistic to watch that character making noises without moving it's mouth, or etc. So, less voice = less effort on syncing animations with voice.

And actually, considering most of the gamers usually skip the dialogs to read the summary, spending most of your efforts on voice-acting is some kind of "*playing for the audience*".

# Answer
> 5 votes
Producing voice content is time consuming, tedious, and requires a lot of prep work to cast people that can act to fit the role and get them engaged in that role, MMOs typically have a vast amount of textual content in comparison to other games which means much more time in a recording studio. It costs more money than you'd think, actors aren't the only people, you have designers, writers, audio engineers and producers in addition to your actors. Everyone has an hourly rate, people don't work for free. Game budgets go a lot more quickly than you'd like. (It really does take a significant part of a budget for most games that choose to include voice over)

Voice content isn't as flexible, it's not as simple as a content file edited by a writer and sent out in a patch, you actually have to go back to the studio and record more audio or rehash what you already have. You're not going to iterate and develop the content in your world as quickly if you have to deal with voice content matching your changes to your interactions/characters/environments.

---
Tags: mmo, project-management, voice
---


# Question
Title: SMFL C++: IntRect intersection not working?
I'm trying to find free space to place rectangles, but even though I check for a collision using `.intersects()` it still places them through each other and somehow doesn't see the intersection happening while it's blatantly there.

This is my code at the moment:

```
#include "dungeonGenerator.h"

std::map<int, dungeonGenerator::dungeon_room> dungeonGenerator::newDungeon(int x, int y, int n)
{
    srand(time(NULL));
    std::map<int, dungeon_room> rooms;
    bool canPlace;

    for (auto i = 0; i < n; ++i)
    {
        canPlace = false;
        dungeon_room dungeon_room;
        while (!canPlace)
        {
            int height = rand() % x;
            int width = rand() % y;

            int pos_x = rand() % 512;
            int pos_y = rand() % 512;

            sf::RectangleShape room;
            room.setSize(sf::Vector2<float>(height, width));
            room.setFillColor(sf::Color(rand() % 255, rand() % 255, rand() % 255));
            room.setPosition(sf::Vector2<float>(pos_x, pos_y));
            dungeon_room.image = room;
            dungeon_room.collider = sf::IntRect(pos_x, pos_y, width, height);

            if (!rooms.empty())
            {
                auto i = 0;
                for (auto& room : rooms)
                {
                    std::cout << ++i;
                    canPlace = canPlaceRoom(&dungeon_room, &room.second);

                    if (canPlace == false)
                    {
                        break;
                    }
                }
            } else
            {
                canPlace = true;
            }
        }
        rooms[i] = dungeon_room;
    }
    return rooms;
}

bool dungeonGenerator::canPlaceRoom(dungeon_room* room, dungeon_room* target)
{
    if (room->collider.intersects(target->collider))
    {
        return false;
    }
    return true;
}

```

# Answer
> 0 votes
Your collider uses a different width and height than your `sf::RectangleShape:` at line 22, you swapped width and height.

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


# Question
Title: How to move a Box2D body towards a mouse click?
In a **top down game using Box2D**, I would like the player's Box2D body to rotate towards the mouse click, and then **move to a point on mouse click** (move, not teleport). I have worked out the rotation part, but cannot figure out the movement.

Every time the screen is touched, the target point (mouse click) is updated:

```
if (Gdx.input.isTouched())
{
    Vector3 tmp = camera.unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0));
    touch_prev = touch_target;
    touch_target = new Vector2(tmp.x, tmp.y);
}

```

Here is the `Rot2D` class:

```
package com.elsealabs.ghostr;

public class Rot2D {

   public static Rot2D fromDegrees(double angle) {
      return fromRadians(Math.toRadians(angle));
   }

   public static Rot2D fromRadians(double angle) {
      return new Rot2D(Math.cos(angle), Math.sin(angle));
   }

   public static Rot2D fromVector(double dx, double dy) {
      float length = (float) Math.sqrt(dx * dx + dy * dy);
      return new Rot2D(dx / length, dy / length);
   }

   public double getAngle() { // radians
     return Math.atan2(sin, cos); // atan2(y, x)
  }

   public double cos, sin;

   private Rot2D(double cos, double sin) {
      this.cos = cos;
      this.sin = sin;
   }

   public Rot2D load(Rot2D that) {
      this.cos = that.cos;
      this.sin = that.sin;

      return this;
   }

   public Rot2D copy() {
      return new Rot2D(cos, sin);
   }

   public Rot2D rotate(Rot2D that) {
      double cos = (this.cos * that.cos) - (this.sin * that.sin);
      double sin = (this.cos * that.sin) + (this.sin * that.cos);

      this.cos = cos;
      this.sin = sin;

      return this;
   }

   public static double cross(Rot2D a, Rot2D b) {
      return (a.cos * b.sin) - (a.sin * b.cos);
   }
}

```

(Source)

I am showing these because it may be helpful, but what I need to get working is the movement. I do not want to use setTransform, as it may end up letting the player travel through walls.

Using the vectors below, and any other variables needed, **how would I move the player gradually towards a point on mouse click?**

```
private Vector2 touch_prev = new Vector2(0, 0);
private Vector2 touch_target

```

# Answer
> 1 votes
* Get vec2 from start point to target point (mouse coords in world space).
* Set b2body velocity to normalized version of that vec2, multiplied by your desired speed.
* Keep stepping - velocity will carry you closer to target point each time.
* On each step, if distance from current point to target point (magnitude) is less than velocity, set b2body position to the target point, and set velocity to zero.

# Answer
> 0 votes
Okay, So I think you're asking how to do it so here's my Bullet class remodeled to fit a player. Keep in mind this was a bullet class so edit it to fit for your player. Pay close attention to the use of Vectors.

```
public class MovingPlayer {

   static final float PLAYER_SPEED = 800;

   Vector3 position, velocity, acceleration;
   Texture texture;

   public Vector3 target;
   public Rectangle Bb;
   Player player;

   public Bullet(Texture texture, Player player) {
      this.texture = texture;
      this.player = player;
      reset();
      Pb = new Rectangle(0, 0, 10, 10);
      acceleration = new Vector3(0, -400, 0); // gravity

   }

   private void reset() {
      position = new Vector3(player.getX() + 20, player.getY() + 20, 0);
      target = new Vector3(Gdx.input.getX(), Gdx.input.getY(),0);
      GameScreen.cam.unproject(target);
      velocity = target.cpy().sub(position).nor().scl(BULLET_SPEED); // go towards target
   }

   public void render(SpriteBatch batch) {
      batch.draw(texture, position.x, position.y);
      Pb.setX(position.x);
      Pb.setY(position.y);
   }

   public void update(float delta) {
      // simple Euler integration
      position.add(velocity.cpy().scl(delta));
   }
}

```

This sends the object towards the mouse using Vectors at the speed "PLAYER\_SPEED". As you can see, most of the math is done in the `reset()` method

---
Tags: java, libgdx, box2d
---


title: Implementing black map in a 3d game

text:
# Question
Title: Implementing black map in a 3d game
I am struggling with designing black map and fog of war in a 3d game. Black map is the area that player hasn't explored (completely unknown), while fog of war is the area that player has explored and knows geospatial topology, but no friendly units or buildings are nearby to provide player with up-to-date info about enemy movements over the area.

The problem is that my terrain is 3D, varies in height greatly and camera can be placed at any position on the map at virtually any angle.

So far I've designed very heavy fog/clouds for area under fog of war, but not so heavy that the terrain underneath would not be visible, and am not rendering non-environment objects on those locations, but black map is another story.

Simply not rendering terrain over those locations looks and feels bad, and rendering terrain in pure black is not good as, when the camera is angled to view forward, player can still see elevation - very important information in the game and should not be given away without having to explore the map.

Are there any generally accepted ways of implementing such feature?

# Answer
Whatever your fog colour is - say black - you should be using simple linear fog to fade into that colour - consider for example how Minecraft does so here, using sky blue:

You can use this in conjunction with other aspects like colouring the base terrain with your fog colour. You could also have fog-coloured objects constantly drifting in front of distant terrain, like banks of thick fog, heavily obscuring what is there. So in the image above, the cloud at the top might totally obscure the top of that tree... and if there were more of them, they would obscure parts of the mountain as well. Doing this efficiently may be challenging if you want to use transparency, but will be simple if you use solid fog banks. (Easiest on desktop / consoles.)

I suppose if you don't want the player to know elevation information, you can either create flat decoy planes in far off locations, or you can randomise terrain there, or make subtle modifications to the *actual* terrain forms so that the player may *think* they know what's there... but actually don't.

Lastly you could blur the skyline using a fragment shader to further obscure distant elevations.
> 1 votes

---
Tags: 3d, terrain, fog-of-war
---


# Question
Title: Conveying a claustrophobic atmosphere in cavalier oblique projection
I need your collaborative knowledge in finding the best way to graphically represent a scene in a manner that would suit a SNES-era rôle-playing game. I've chosen to represent the game in what I'm informed is called "cavalier oblique" projection, which is the same sort of perspective employed in titles like EarthBound:  Wherein articles' fronts and one side are shown, but characters face the camera head-on. For as much reason as anything, this is to avoid the "top-down" view employed by 300% of *RPG Maker* titles. I don't want to look like a "me-too" player.

**The scenario**

In the title, the player character has their return path blocked off, with the only path to progression being one leading through a series of very tight-fitting caves. The claustrophobia of the area is *very* important, as it's one of the main sources of suspense to which the player is subjected.

**The problem**

I can't think of a single way to display claustrophobic, branching caves with dead-ends and very tight holes in the projection I've displayed above. There are a few works-around I can think of that revolve around changing the projection (either to a first-person view, which will be immensely difficult to navigate, or to a side-on view like *Dig Dug*, which is more intended to show branching paths across a *y* axis as opposed to an *x* axis) - doing this risks appearing jarring to the player, however, and I'm aiming for immersion above all else.

I ask you, GD - can you think of any such scenarios from your favourite retro games, and how did they display them to the player? Any reference I can get for a successful execution will be immensely appreciated.

# Answer
Reduce the players sight-range. You can do that by adding an overlay mask on top of the rendered scene. This simulates the reduced sight-radius of the player-characters due to darkness.

It forces the player to concentrate on a very small section of the screen giving a feeling of claustrophobia. But keep in mind that it disorients the player, so cut the player some slack and don't make the sequence too frustrating to navigate. Having less to look at at the same time also means that your map needs even more detail than usual to both keep it interesting to look at and provide navigational landmarks. More clutter will also contribute to the feeling of claustrophobia by making the map feel more crowded.
> 31 votes

# Answer
Use per-tile lighting to do sight-range reduction.

Shadowlands (1992) - 3 light levels:

Diablo (1997) - 8 light levels:

You can do much more with this dynamic, such as easily having monsters only spawn on dark tiles, have light streaming out of doorways and windows, etc.

To induce claustrophobia beyond just lighting, have a look at the way the Maggot Lair was designed in Diablo II (2000):

...constrict these tubular tunnels even further so that they tightly fit the standing height of your character. You can force the character to squat in these spaces, standing at perhaps 2/3 usual height. I don't want to mod a picture of D2 here, but try scaling up the hunch-backed sprite to see how you can pack it tightly into this tunnel. Hanging vines and roots from the ceiling of the tunnels will help too and could even obscure light / vision further up the passage. Dust falling from roof, flickers of movement / eyes blinking on the edge of your sight - cues like this will help for a closed-in feel. Slow movement and restrict combat in tight areas, upping the fear factor further.
> 20 votes

# Answer
As the two current other answers suggest, limiting visibility is a good way of doing this. There are other games which did this. One I can think of is Breath of Fire II, where early on in the game you are navigating a cave with only a candle for lighting. This restricts the visibility and creates tension (which mounts to a nice payoff in that game).

But I have an additional idea. Fear is a component of both darkness and claustrophobia. But for darkness it is because something you can't see could be lurking ahead, while for claustrophobia it is the fear of getting stuck somewhere without the possibility to return. For a short manga story which uses this fear to great effect, check "The Enigma of Amigara Fault". Warning: it is a disturbing read. I suggest you use that spatial aspect to convey claustrophobia.

How? A simple way would be to have the cave start more spacious, but as you progress through the paths make it increasingly narrower. If it is possible to have the visibility range start larger and decrease as you progress, that would help too. To help with the feeling of entrapment, make it so the player has to backtrack at some point but have part of the cave become obstructed, for example by a cave-in, to make it seem initially like there's no way out anymore. Of course you'd have to provide some exit from this in a way that is not as immediately straightforward as following the original path. These things are all quite feasible through level design.

Finally, although not part of your original question, using audio could be very effective too. For example, the sound of a heartbeat, which would increase in rate as you progress through the cave (while visibility is simultaneously limited and the space becomes narrower). To avoid making the effect too obvious, make it very silent and close to the lower limits of human hearing. The Silent Hill games are pretty good with using unsettling audio. An example is early in Silent Hill 2 where, while walking a long winding path, you start hearing footsteps behind you. They are almost, but not quite, synced to your footsteps, and the first time playing it they wouldn't be immediately obvious until you realize something sounds off.

What isn't there or can't be seen is often better at making us afraid than what is visible. The unknown is a large component of fear.
> 9 votes

---
Tags: rpg, projection
---


# Question
Title: How do I draw non-smoothed fonts in MonoGame 3.5?
I don't want to smooth the tiny fonts I'm building but even disabling ClearType system wide doesn't let me create SpriteFont files with sharp characters. There doesn't seem to be an option for smoothing in the `.spritefont` file I could set to "disabled". Are there any configs that affect how spritefonts are generated?

I'm using MonoGame 3.5 with Visual Studio 2015 and building the spritefonts via `Content.mgcb` thing that is added automatically into a MonoGame project.

I tried using Give Your Fonts Mono(spacing) tool but it doesn't have an option to disable smoothing.

Trying to follow this tutorial with BMFont generator and added the reference in the example, but the `MonoGame.Extended` thing doesn't appear and instead of automatically recognized importer I get `[missing] [null]`. After that I tried adding some other packages that come with MonoGame pipeline DLLs but no luck.

Tried to use XNA Content Compiler but it throws me an exception with some important object `contentBuilder` being null. Installing XNA framework doesn't fix the issue.

If there are ways to draw text without using SpriteFonts that allow to use non-smoothed characters, I'd like to know how.

# Answer
> 1 votes
I decided to pursue the BMFont path, it turned out that MonoGame Pipeline works just fine even if the format is displayed as `[missing] [null]`. All I had to do was add `using MonoGame.Extended.BitmapFonts;` to the top of my `.cs` files and swap `SpriteFont` with `BitmapFont` for everything to work perfectly.

# Answer
> 0 votes
It's possible that the problem isn't actually the font itself but the way you're rendering it with a sprite batch. Have you tried setting the sampler state to point clamp?

```
_spriteBatch.Begin(samplerState: SamplerState.PointClamp);

```

Btw, without any code to look at or a screenshot it's difficult to say what the problem might be. If this isn't the answer, please update you're question with some more details and I'll have another go at it.

# Answer
> 0 votes
You can try to set the `TextureFormat` to `NoChange` in the Content Pipeline app for your sprite fonts. That's what I do for all of my assets. I don't want to lose quality due to compression. Also there's some sprite font problem going on in the MonoGame repo on GitHub, they will be fixing it this week.

---
Tags: xna, monogame, spritefont
---


# Question
Title: Unity 5 - Textures look strange in Deferred Rendering
I've created an exterior terrain scene in Unity 5 which features lots of trees and grass but some textures look awful and I'm wondering why. Please see the attached image:

This texture problem is especially obvious at night (I'm using Time of Day unity asset for Day/Night cycle) but also during day light it doesn't look good. The tree bark looks like plastic and also the ground textures are too bright and lack contrast. Stone texture on the other hand look perfectly fine.

Can somebody point me into the right direction of what I'm doing wrong here with my lighting and rendering?

# Answer
Take a look on this:

https://issuetracker.unity3d.com/issues/tree-creator-bark-material-is-much-lighter-in-deferred-rendering-path-than-in-forward-rendering-path

They should fix that issue in few... months? weeks?
> 1 votes

---
Tags: textures, rendering, lighting, unity
---


# Question
Title: Following waypoints, condition is never fulfilled
Given a 2D-grid which is defined like below and is used to draw a grid consisting of cells:

```
int[,] grid; //filled with 0 (blocked) and 1 (walkable);

```

I also have a A\*-algorithm implemented which returns a `List<Vector2>` with the grid cell positions of the waypoints of the path. The actual screen-positions of the cells can be calculated using the cell width. So for example a `Vector2 waypoint = new Vector2(0,2);` is a Cell in the first row and third column.

I also have a `Player` class which holds and displays a texture. When I let the Player follow the path, the texture is moving towards the top waypoint in the List. Once the waypoint is reached with `position == currentgoal //comparing Vector2 here` I delete it from the list and set the next waypoint as the current goal.

Here is how I update the Player position, in this case it is moving down as the direction `Vector2` is set to `Vector2(0,1);`

```
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

position += new Vector2(0,1) * speed * elapsedTime; //direction * float * float

```

First I was using an integer as speed and omiting the `elapsedTime` in the calculation. As this is not how it is supposed to be implemented I changed the `speed` to `float` and added `elapsedTime`. Also with an speed value of `int speed = 1;` the texture was moving too fast already.

Unfortunately with the float values the `Vector2` comparison of position and waypoint vectors is almost never exactly reached and therefore the condition never fulfilled. This is because the goal values although being floats always hold values with a `0` after the point.

What I tried is to check for a `(+/-)1` value so if the position is somewhere between `currentgoal +/- 1`. This does lead to a inaccuracy and other side effects.

Is my position calculation a common and right way to do it? If so, how could I modify my code which is checking whether the goal is reached or not?

# Answer
(1) Refer to the idea of an *epsilon* value which represents the float error range within which you are willing to accept a "success" condition.

It is normal for floats to be compared using an epsilon, for example:

```
float e = 0.0001f; //epsilon

public bool FloatEquals(float a, float b)
{
    return Math.abs(a - b) <= e;
}

bool Vector2Equals(Vector2 a, Vector2 b, float e) //last param here or store as member
{
   return (a - b).magnitude <= e; //don't compare x and y individually - this ensures a is within some radius e of b
}

```

...thus if the absolute difference is greater than epsilon, then `a` and `b` are still too far apart to count as "equal".

(2) Alternatively, you can count millimeters, milliseconds etc. as integers rather than floats, via conversion. Then you can perform ordinary integer equality checks without any need for epsilon.

For example:

```
float elapsedSec = (float)gameTime.ElapsedGameTime.TotalSeconds;
int elapsedMs = elapsedSec * 1000; //this will give you integer milliseconds

```

Or

```
float xPos = ...; //some way of getting the float position
int xPosMm = xPos * 1000; //integer millimeters

```

With this approach you may experience some loss of accuracy over time, due to the constant rounding that occurs each game loop tick. But it simplifies equality checks.
> 1 votes

---
Tags: monogame, path-finding, waypoints
---


# Question
Title: Calculating a matrix to have the model follow terrain
So I've been messing around with 3D graphics in Java (using lwjgl), and I've hit a bit of a roadblock. I have a heightmap and a cube, and I want to find a way to have the cube rotate to follow the terrain smoothly. At the moment, the cube can rotate freely around the y axis (up is 0,1,0), and it can move directly in the direction it's facing.

Here's my idea: find the plane formed by projecting the bottom corners of the cube onto the terrain. That's the plane that I want to rotate my cube's bottom face into, so I took a cross product with the up vector and the normal vector of that plane. Then I took the angle between the two, and calculated an axis-angle rotation matrix around that plane. I mulitplied the y rotation matrix by that matrix, and used that as my model matrix:

```
    Matrix4 upTransform = Matrix4.createRotateY(yrot);
    // calculate plane of cube
    Vector3 bl = new Vector3();
    bl.x -= SCALE / 2;
    bl.z -= SCALE / 2;
    bl = upTransform.transform(bl);
    bl.y = game.getMap().getY(position.x + bl.x, position.z + bl.z);
    Vector3 tl = new Vector3();
    tl.x -= SCALE / 2;
    tl.z += SCALE / 2;
    tl = upTransform.transform(tl);
    tl.y = game.getMap().getY(position.x + tl.x, position.z + tl.z);
    Vector3 br = new Vector3();
    br.x += SCALE / 2;
    br.z -= SCALE / 2;
    br = upTransform.transform(br);
    br.y = game.getMap().getY(position.x + br.x, position.z + br.z);
    Vector3 normal = Vector3.cross(Vector3.diff(br, bl),
                                   Vector3.diff(tl, bl)).normalize();
    // calculate rotation axis
    Vector3 axis = Vector3.cross(normal, up).normalize();
    // calculate angle between plane of cube and plane of texture
    float angle = (float)Math.acos(Vector3.dot(up, normal));
    // calculate rotation
    Matrix4 terrainTransform = new Matrix4().setRotate(axis, angle);
    Matrix4 rot = Matrix4.multiply(upTransform, terrainTransform);

```

`game.getMap().getY(x, z)` returns the height of the map at the x,z coordinate provided. `Vector3.diff(a, b)` returns a - b, and `Matrix4.multiply(A, B)` returns A * B. My issue is that the cube rotates weirdly and has strange shear effects. Does anyone have comments on my general approach, or on my implementation? I'm really not sure what to do here, as this is pretty much where my linear algebra knowledge reaches its limits.

# Answer
> 0 votes
Solved my problem! I read an approach in XNA 3.0 Game Programming Recipes: A Problem-Solution Approach, and adapted it to my needs. Here's the code if anybody is curious:

```
    Matrix4 upTransform = Matrix4.createRotateY(yrot);
    // find the height at the front, back, left, and right
    Vector3 frontLeft = upTransform.transform(new Vector3(-SCALE / 2, 0, SCALE / 2))
                        .add(position);
    Vector3 frontRight = upTransform.transform(new Vector3(SCALE / 2, 0, SCALE / 2))
                        .add(position);
    Vector3 backLeft = upTransform.transform(new Vector3(-SCALE / 2, 0, -SCALE / 2))
                        .add(position);
    Vector3 backRight = upTransform.transform(new Vector3(SCALE / 2, 0, -SCALE / 2))
                        .add(position);
    // calculate front and back rotation
    Vector3 front = Vector3.sum(frontLeft, frontRight).scale(1 / 2.0f);
    Vector3 back = Vector3.sum(backLeft, backRight).scale(1 / 2.0f);
    Vector3 backToFront = Vector3.diff(front, back);
    float frontHeight = game.getMap().getY(front.x, front.z);
    float backHeight = game.getMap().getY(back.x, back.z);
    float frontBackDiff = frontHeight - backHeight;
    float frontBackAngle = (float)Math.atan2(frontBackDiff, backToFront.length());
    Matrix4 frontBackRot = Matrix4.createRotateX(frontBackAngle);
    // calculate left and right rotation
    Vector3 left = Vector3.sum(frontLeft, backLeft).scale(1 / 2.0f);
    Vector3 right = Vector3.sum(frontRight, backRight).scale(1 / 2.0f);
    Vector3 rightToLeft = Vector3.diff(right, left);
    float leftHeight = game.getMap().getY(left.x, left.z);
    float rightHeight = game.getMap().getY(right.x, right.z);
    float leftRightDiff = leftHeight - rightHeight;
    float leftRightAngle = (float)Math.atan2(leftRightDiff, rightToLeft.length());
    Matrix4 leftRightRot = Matrix4.createRotateZ(leftRightAngle);
    Matrix4 terrainTransform = Matrix4.multiply(frontBackRot, leftRightRot);
    Matrix4 rot = Matrix4.multiply(upTransform, terrainTransform);

```

---
Tags: rotation, models, terrain, transformation, heightmap
---


# Question
Title: How to display a lot of small objects using WebGL?
**Introduction**

The game scene contains a lot of 10x10 pixel elements: for 1980x1200 px. screen the number of elements on the scene can vary from 0 to 23760 (elements cannot intersect).

The live example: http://fintank.ru/game/

The entire game space comprised of tiles: each tile is responsible for some area and keeps elements for that area (similar to google maps).

Each tile exist as 2 entities: `S` and `G`. `S` is a set of elements in the tile, `G` is rendered image of a tile. When the server put/remove elements to the tile, we change `S` and then re-render the `G`.

To draw a frame (at 20 fps) I just put the `G` of each visible tile using the `putImageData()`. That is done without WebGL.

**The question**

What is the most CPU effective approach to implement such many-elements management using WebGL? Should I render each tile to a texture or each element may be implemented as a separate textured rectangle? The main concern is that each tile may be updated 30-60 times a second (elements adding/removal).

How to avoid memory leaks (how to reuse buffers?) if we make many new textures every second?

What is the most effective way to manipulate pixels during rendering a 100x100 tile?

How to avoid re-uploading the unchanged textures to graphic card?

# Answer
> 2 votes
There are several ways to approach this problem. When it comes to WebGL performance the key is to: (a) reduce number of drawcalls, (b) reduce gpu overdraw (fill-rate) and vertices. (c) reduce buffer data transfers. Because you're filling the screen at most once and scene complexity is low, we can totally ignore (b). (c) is a bit more complex and I'll get back to it later.

So, let's see how we can draw a whole tile of N by N elements in a single drawcall. First, let's make sure that you have all possible element images on a single texture atlas – this will enable us to draw any element without changing textures.

For each tile, create a vertex buffer that will hold N by N quads and initialize their positions so that they make the whole grid. To make an element appear, you just have to set the texture UV coords of the quad to the element image in texture atlas. You never change quad positions.

```
bufferData = new Float32Array(N*N*6*8);  // 6 vertices == 2 triangles, WebGL doesn't support quads natively
bufferId = gl.createBuffer();

// fill buffer data with coordinates, etc.

// now after each modification call:
gl.bindBuffer(gl.ARRAY_BUFFER, bufferId);
gl.bufferData(gl.ARRAY_BUFFER, bufferData, gl.DYNAMIC_DRAW);  // dynamic will make it optimized for frequent updates

```

You can reuse the vertex buffer and just update it's content after each change. Now rendering this vertex buffer will draw all the elements in N by N tile onto the framebuffer. There's even no need to cache it in a texture, it is so cheap.

And when it comes to (c): this should not be needed, but let's assume that your elements are mostly static and you would like to only ever draw what's changed. If you render your graphics to a texture, you can later draw to this texture without clearing it, thus updating only the changed parts. However this (not clearing before rendering) could potentially hurt performance on some older mobile platforms. Also, still remember to draw all the updated elements in one single drawcall as shown above.

---
Tags: javascript, html-canvas, webgl
---


# Question
Title: How to rotate an image on touch using RotateToAction in libGDX?
I want to rotate my image on touch but it never applies action, I'm using RotateToAction to achieve this.

```
class actorCark extends Actor
{
    Texture texture;
    Sprite sprite;
    Global g;
    GetActorByName a;
    public actorCark()
    {
        ses=new sesler();
        g=new Global();
        a=new GetActorByName();
        sr=new soruSor();
        texture=new Texture(Gdx.files.internal("images/carkifelek.png"));
        sprite=new Sprite(texture);
        setBounds(Global.screen_width / 2 - Global.screen_height * 0.9F * sprite.getTexture().getWidth() / sprite.getTexture().getHeight() / 2, Global.screen_height / 2 - Global.screen_height * 0.9F / 2, Global.screen_height * 0.9F * sprite.getTexture().getWidth() / sprite.getTexture().getHeight(), Global.screen_height * 0.9F);
        setTouchable(Touchable.enabled);
        addListener(new InputListener() {
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int buttons) {
                clearActions();
                RotateToAction rotateToAction=new RotateToAction();
                rotateToAction.setRotation(360);
                rotateToAction.setDuration(2);
                addAction(rotateToAction);
                dondur();
                sesler.donmeS.play();
                return true;
            }
        });
    }
    @Override
    public void act(float delta) {
        super.act(delta);
    }
    public void draw(Batch batch, float alpha)
    {
        sprite.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
        sprite.setBounds(Global.screen_width / 2 - Global.screen_height * 0.9F * sprite.getTexture().getWidth() / sprite.getTexture().getHeight() / 2, Global.screen_height / 2 - Global.screen_height * 0.9F / 2, Global.screen_height * 0.9F * sprite.getTexture().getWidth() / sprite.getTexture().getHeight(), Global.screen_height * 0.9F);
        sprite.setOrigin(sprite.getWidth() / 2, sprite.getHeight() / 2);
        sprite.draw(batch);
    }
}

```

# Answer
It seems that you are rotating your actor with the rotateTo action, but your sprite, which is doing the actual drawing, knows nothing about the actor's rotation. Try `sprite.setRotation(this.getRotation())` in your draw() code.
> 0 votes

---
Tags: libgdx
---


# Question
Title: Instantiating a prefab as a child to another game object (spawn point) - Unity 3D - C#
I am currently working on a 3d game in unity in C#. I've been following a series of tutorials on youtube (burgzerg arcade) for quite a while now, and i've came across the following error. This error only occurs when i instantiate prefabs to my game scene, opposed to dragging and dropping them into the scene hierarchy. In the tutorial, we work on many things including a targeting script and mob generation. The purpose of the targeting script, is to (when pressing tab), checks to see if there are any mobs (prefabs / game objects) within a certain distance, if they are, it adds them to a list, from which sorts them in order from closest to furthest. When the mob generation script instantiates the prefabs, it instantiates them as a child to the spawn points that i made (spawn point game objects), meaning that when the targeting script searches for the game objects, it doesn't recognize that the mobs are there (because they are childed to the spawn points). So what im asking is how can i make it so that when i press tab, it adds the instantiated children to the list? Here is the code for the mob regen script and targeting script. This is the error i get after i press tab using the instantiated mobs. (ps: when i manually drag the prefabs onto the game scene, opposed to instantiating, it works just the way i want because they aren't instantiated as a child).

This is the error i get when i press tab using the mob regen script:

```
Parameter name: index
System.Collections.Generic.List`1[UnityEngine.Transform].get_Item (Int32 index) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:633)
Targetting.TargetEnemy () (at Assets/Scripts/Targetting.cs:64)
Targetting.Update () (at Assets/Scripts/Targetting.cs:116)

```

The reason i think i am getting this error is because when the mob gen script generates mobs, it instantiates them as a child to the parent spawn points, so when the targetting script looks for tags with 'enemy', it can't find them ( so it doesn't add them to the list) because the cloned mobs are children to the spawn points. I am trying to find a work around but haven't found anything. Could someone please give me a hand to find a solution to my problem? I've tried things like searching for the children, checking for the child count ect ect. but still can't find a way.

Oh also, the spawn points are just empty game objects that i placed around the map.

Code for targetting.cs:

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

public class Targetting : MonoBehaviour
{
    public List<Transform> targets;
    public Transform selectedTarget;

    private Transform myTransform;

    // Use this for initialization
    void Start ()
    {
        targets = new List<Transform> ();
        selectedTarget = null;
        myTransform = transform;

        AddAllEnemies();

    }

    public void AddAllEnemies()
    {
        GameObject[] go = GameObject.FindGameObjectsWithTag ("Enemy");

        foreach (GameObject enemy in go)
        {

            Debug.Log ("Adding enemies to list....");
            AddTarget (enemy.transform);
        }

    }

    public void AddTarget(Transform enemy)
    {
        Debug.Log ("Added enemy to the list");
        targets.Add (enemy);
    }

    private void SortTargetByDistance()
    {
        targets.Sort (delegate(Transform t1, Transform t2)
                      {  return Vector3.Distance (t1.position, myTransform.position).CompareTo(Vector3.Distance(t2.position, myTransform.position));
                       });
    }

    private void TargetEnemy()
    {
        if(selectedTarget == null)
        {
            SortTargetByDistance();
            selectedTarget = targets[0]; //so the list is empty? well at first it is thats why its null, so it isnt adding them to list? doesn't seem like that, how can you output stuff? is there a comma
        }
        else
        {
            int index = targets.IndexOf (selectedTarget);

            if(index < targets.Count - 1)
            {
                index++;
            }
            else
            {
                index = 0;
            }
            DeselectTarget();
            selectedTarget = targets[index];

        }
            SelectTarget();
    }

    private void SelectTarget()
    {
        Transform name = selectedTarget.FindChild ("Name");

        if(name == null)
        {
            Debug.LogError("Could not find the Name on " + selectedTarget.name);
            return;
        }

        name.GetComponent<TextMesh> ().text = selectedTarget.GetComponent<Mob>().Name;
        name.GetComponent<MeshRenderer> ().enabled = true;
        selectedTarget.GetComponent<Mob> ().DisplayHealth();

        Messenger.Broadcast<bool> ("show mob vitalbars", true);

    }

    private void DeselectTarget()
    {
        selectedTarget.FindChild("Name").GetComponent<MeshRenderer>().enabled = false;

        selectedTarget = null;
        Messenger.Broadcast<bool> ("show mob vitalbars", false);
    }

    // Update is called once per frame
    void Update ()
    {
        if(Input.GetKeyDown (KeyCode.Tab))
        {
            TargetEnemy();
        }
    }
}

```

Code for mob regen script:

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

public class MobGenerator : MonoBehaviour
{

    public enum State
    {
        Idle,
        Initialize,
        Setup,
        SpawnMob

    }

    public GameObject[] mobPrefabs;  // an array to hold all of the prefabs of mobs we want to spawn
    public GameObject[] spawnPoints;  // an array will hold a reference to all of the spawn points in game

    public State state;  // our local variable that holds our current state

    void Awake()
    {
        state = MobGenerator.State.Initialize;

    }

    // USE THIS FOR INITIALIZATION
    IEnumerator Start()
    {
        while(true)
        {
            switch(state)
            {
            case State.Initialize:
                Initialize();
                break;

            case State.Setup:
                Setup();
                break;

            case State.SpawnMob:
                SpawnMob();
                break;

            }
            yield return 0;
        }
    }

    // make sure that eeverything is initialized before we go on to the next step
    private void Initialize()
    {
        Debug.Log("*** We are in the initialize function ***");

        if (!CheckForMobPrefabs())
            return;

        if (!CheckForSpawnPoints ())
            return;

        state = MobGenerator.State.Setup;
    }

    // make sure that everything is setup before we continue
    private void Setup()
    {
        Debug.Log("*** We are in the setup function ***");

        state = MobGenerator.State.SpawnMob;

    }

    // spawn a mob if we have an open spawn point
    private void SpawnMob()
    {
        Debug.Log ("*** Spawn Mob ***");

        GameObject[] gos = AvailableSpawnPoints ();

        for (int cnt = 0; cnt < gos.Length; cnt++)
        {
            GameObject go = Instantiate (mobPrefabs [Random.Range (0, mobPrefabs.Length)],
                                         gos [cnt].transform.position,
                                         Quaternion.identity) as GameObject;

            go.transform.parent = gos [cnt].transform;
            Debug.Log ("there are " + go.transform.childCount.ToString () + " children");

            state = MobGenerator.State.Idle;
        }
    }

    // check to see that we have at least one mob prefab to spawn
    private bool CheckForMobPrefabs()
    {
        if (mobPrefabs.Length > 0)
            return true;
        else
            return false;
    }

    // check to see if we have at least one spawnpoint to spawn mobs at
    private bool CheckForSpawnPoints()
    {
        if (spawnPoints.Length > 0)
            return true;
        else
            return false;

    }

    // generate a list of available spawn points that do not have any mobs childed to it
    private GameObject[] AvailableSpawnPoints()
    {
        List<GameObject> gos = new List<GameObject> ();

        for(int cnt = 0; cnt < spawnPoints.Length; cnt++)
        {
            if(spawnPoints[cnt].transform.childCount == 0)
            {

                Debug.Log ("*** Spawn point available ***");
                gos.Add (spawnPoints[cnt]);

            }
        }
        return gos.ToArray ();
    }
}

```

So as you can see, I am aware of the problem but I am not sure how to go about fixing the problem. Please let me know how or point me in the right direction.

# Answer
This line

```
GameObject[] go = GameObject.FindGameObjectsWithTag ("Enemy");

```

Looks for all **GameObjects** with the "Enemy" **tag**. It should find them no matter of their parent.

My guess is that your Mobs prefabs do not have the "Enemy" tag applied.
> 1 votes

# Answer
I can see several things wrong with your code. Your problems come from the way you're trying to observe your dynamically generated mobs.

First, in `Targetting.cs`, you only call `AddAllEnemies` once in the `Start` method. You're assuming that the mobs will be spawned first. But if `MobGenerator.cs` is started second, that would explain your problem: the enemies in the mob don't even exist yet.

The list of targets needs to be constantly updated as more mobs are spawned. So you need to either:

* Run `AddAllEnemies` in the first line of `Targetting.Update` to completely overwrite the previous list of targets.

```
// Update is called once per frame
void Update ()
{
    AddAllEnemies();
    if(Input.GetKeyDown (KeyCode.Tab))
    {
        TargetEnemy();
    }
}

```
* Write an `UpdateTargets` method to add targets from `GameObject.FindGameObjectsWithTag ("Enemy")` that are not present in the current list of targets. Use it in `Targetting.Update` instead.

```
public void UpdateTargets()
{
    GameObject[] go = GameObject.FindGameObjectsWithTag ("Enemy");

    foreach (GameObject enemy in go)
    {
        if (targets.Contains(enemy.transform)) continue;
        Debug.Log ("Adding enemies to list....");
        AddTarget (enemy.transform);
    }
}

```

This way should work no matter which of the two scripts runs first. Just a side note, but since you're dealing with enemies that can be removed from the scene, you should also write some code to remove null references from the list of targets. It'll help protect your game from null pointer exceptions.
> 0 votes

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


# Question
Title: What type of networking system should I use With LibGDX on Android?
I've been looking for a good way to implement multiplayer in an Android strategy game I'm working on, using LibGDX. What I found:

* The embedded LibGDX networking system
* Kryonet
* Google Play Services (I already used this system for a Unity game)

The only problem is that I don't know what system I want to use because I see multiple problems in each of these.

In LibGDX's networking and Kryonet, how can players connect to each other without having to tell each other their IP (which is not easy for everybody) ?
In Google Play Services, I don't know what are the requirement for users. Do the have to have Google Play, or maybe Google+ installed on their devices? Also, how easy is it to get Google Play Services to interface with LibGDX and Scene2D?

# Answer
I can't speak for Google play services, but between the embedded LibGDX networking and Kryonet, I would suggest Kryonet. After all, it was written partially by the authors of Libgdx :) . It's also a big plus that you can integrate kryonet using gradle.

By "Libgdx's embedded networking" I assume you mean the sockets that Libgdx provides. Kryonet handles all of the socket intricacies for you. Why reinvent the wheel?

Kyronet uses a UDP broadcast to discover servers. Its super easy:

```
InetAddress address = client.discoverHost(54777, 5000);
System.out.println(address);

```

(or there is a `discoverHosts()` function that allows you to get all servers listening on that port)

One caveat is that server discovery only works on the same subnet since UDP broadcasts usually don't travel beyond subnets without special configuration. If you want automatic server discovery outside of the same subnet, then you will likely have to use a matchmaking provider or create a matchmaking server yourself. It seems like Google play services may be a viable option for matchmaking.

To use Google Play services, there is an apk that does need to be installed on the user's device that needs to be present to interact with the services. It is best practice to check for Google Play services before you start using them and prompt the user to install them if they are missing. However, I would venture that most people these days use enough apps with Google Play services that it will already be on the user's device.

Google play services will only be available on the android platform so your android project will need to wrap these google play services in a callback object that would be injected into your core game. I.E.

Create interface in core project

```
public interface IGooglePlayServices{
   void callSomeService(object someParam);
}

```

Implement it in your android project

```
public class GooglePlayServices implements IGooglePlayServices {
   public void callSomeService(object someParam){
     handleToPlayServices.callSomeService();
   }
}

```

Then in your `AndroidLauncher` inject it into your game

```
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
    IGooglePlayServices services = new GooglePlayServices();

    initialize(new MyGdxGame(services), cfg);
}

```
> 1 votes

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


# Question
Title: Is Java AWT suitable for 2d game rendering?
\[Reposting this question from stackoverflow, as it was pointed out that it fits better here.\]

I'm currently porting my 2D game engine to Java. I looked at some of the game libraries pointed at here on stackoverflow. However, the ones I looked at were rather simplistic and didn't even state if they supported things like alpha transparency, so I decided to port my C++ renderer for which I had already written out the logic.

This renderer is a pure software renderer which uses tiling to avoid needless re-rendering. I optimized its scrolling performance by creating an "offscreen buffer" a little larger than my output pane, and blitting this offscreen buffer onto my output on every frame. This way, I could avoid redrawing tiles needlessly just because I scrolled a pixel on the map.

I used Java's AWT to implement it, using a large BufferedImage for the offscreen buffer. The CPU usage is okay(around twice of what I had in C++), but there's an odd problem with continuous scrolling, where every second or so, the renderer will lag out for around 0.2 seconds.

Since there's nothing in my own code that would occur in these periods, and since the spikes disappear if I don't draw my offscreen buffer onto the main view, I can only conclude that Java is doing some internal optimization of its own. However, I'm not sure what it does, nor do I know which of my own optimizations I would have to remove to get rid of the spikes. Also, it might be that java AWT wasn't made with continuous, high FPS scrolling in mind, and that's entirely unusable for this purpose.

Is there some way for me to get rid of these spikes?

# Answer
While I cannot be sure without looking at your code, it sounds like your problem is the garbage collector. In Java, you have major and minor garbage collections taking place every now and then. The minor use up some of your cpu but wont bug you too much. The major collections can be a real problem for real time apps such as games since they will actually pause everything while they are running.

There are two options to solve this. First you can tweak the JVM to make sure less major collections take place. Secondly (and recommended), you can make sure you do not leave too much garbage. Simply check where in your app you create a lot of objects(in my games those are usually the vector3 classes) and make sure you reuse them as much as possible (especially in inner loops etc).
> 4 votes

# Answer
# Yes.

For 2D sprite-based games, AWT can be used to handle the rendering to great effect. It can even be hardware accelerated, depending on the available hardware.

Without any code or detailed profiling snippets, it's hard to say what the issue is. Best I can do is offer some basic tips for working with Java and AWT when building games.

## Working with the Garbage Collector

The GC in Java is something that we have to really keep in mind as we are building our games. It will run periodically and look for objects that do not have any references to them, and remove them from memory. This removal process is slow and is likely the cause of the hitching you are experiencing.

My suggestion is to avoid creating object references that aren't going to be kept around for the lifetime of the execution (or at least, as much as possible). The ideal goal is to make sure the GC doesn't have anything to do whenever it runs.

In practice, you may end up with a lot of static variables that you reuse throughout the game. Here's is a very contrived example of how I tend to deal with that:

```
public final class Resources {
    public static Map<int, String> strings;
    public static Map<int, Texture> textures;
    public static Map<int, GameObject> objects;
    public static Map<int, SoundEffect> sounds;
}

```

During loading screens is where you can grow or shrink your `Map` instances using the `new` keyword. But during play, you'll want to avoid that as much as you can. If something is destroyed during play, set a flag on the object so you know it's not something that is currently active. If you need to spawn a new object, go through your `Map` until you find one that isn't active, and set it's properties and mark it as active.

This is something you'll want to keep in mind when using Java for performance-sensitive applications regardless if you are using AWT, JavaFX, or OpenGL to do the rendering.

## Canvas

For AWT in particular, I would highly recommend using the Canvas class to render everything on to for various reasons:

* You have better control of when things render. This means you can write your own game loop and do things like interpolation, extrapolation, rate-limiting, etc.
* It seems to perform better. I was able to get more things on screen at once at an acceptable frame rate as opposed to trying to animate a bunch of Label and Image objects.
* It's easier to embed in editors. Being able to setup a Frame with normal GUI controls and pointing your game's rendering logic to a Canvas meant I could re-use the game's rendering code in the editor tools.
* It gives you easy access to the Java2D API (aka, the Graphics2D class).
> 2 votes

---
Tags: 2d, java
---


title: My bullet keeps going up

text:
# Question
Title: My bullet keeps going up
So I have a bullet script that fires a bullet straight in the Y direction that gets called as the bullet is instantiated. The plan is to always shoot in the same direction, straight in the Y, but to just rotate the bullet upon instantiation so that the straight is the right kind of straight if that makes sense? What i really want to know i think is how to work out the value for the 3rd property of the instantiate based on the key pressed before the fire, what makes it worse is that i dont even know how to create a rotation variable.

```
Instantiate(Resources.Load("P1Bullet"), transform.position, transform.rotation);

```

this is how i move my bullet in the bulletmove script

```
void Update () {
    Vector3 pos = transform.position;
    Vector3 vel = new Vector3(0, speed * Time.deltaTime, 0);
    pos = pos + transform.rotation * vel;
    transform.position = pos ;
}

```

# Answer
What you need is a quaternion. The rotation variable that you mentioned.

To correctly create a quaternion in the direction you want you need to create it using the Euler method. To create your object:

```
Instantiate(Resources.Load("P1Bullet"), transform.position, Quaternion.Euler(-90f, 0f, 0f));

```

As I don't know the direction you want to face and the orientation of your model you might have to change the values a bit.

To make the bullet always look at the player (no matter were he is) use this:

```
Instantiate(Resources.Load("P1Bullet"), transform.position, Quaternion.LoopRotation(player.transform.position - transform.position, Vector3.up));

```
> 1 votes

---
Tags: unity, 2d, rigid-body-dynamics, rigidbody
---


# Question
Title: How do I quantize an image into an arbitrary bitdepth with dithering?
In the games I make, sometimes I need to balance the quality of the images I show with the amount of memory they consume. This is especially true for smartphones and other devices with very tight memory constraints.

Most of the time, images are saved in 24 or 32 bit formats, depending on whether or not there is an alpha channel, and graphic programs make use of the full 32 bits.

In order to reduce the memory used by some images, some times I have to reduce the memory they consume by loading them for example in 16 bits: 5 for red, 6 for green and 5 for blue. However, this process creates banding and other nasty artifacts, as the downsampling process is performed by fitting each pixel separately to the reduced palette.

I'm looking for a process to quantize an image to an arbitrary bitdepth, with dithering. In fact, I am a great fan of pngquant, which palettizes an image down to 256 colors, and applies dithering very intelligently to achieve some very impressive results. The problem is that the quantized colors are still 32 bits, and while this may reduce the size of the file, it won't reduce the amount of memory consumed once the image is loaded.

The tool I'm looking for should optimize on the decompressed size of the image, based on an arbitrary texture format, by reducing the amount of bits used by each pixel, and dithering where necessary to minimize the perceived detail and color loss. It doesn't really matter if the image is actually saved with 32 bits per pixel, as long as when it is loaded as a lower depth image, no further truncations occur. Optimally, this tool would also palettize the image, and minimize both file and uncompressed size.

In other words, how do I turn this image:

into, for example, this dithered R1G1B1 image?

Of course, I want to set the bitdepth myself. Notice that this is irrespective of the file format.

# Answer
Texture compression is the standard way of doing this; for mobile you'd typically use something like PVRTC, for desktop you'd use DXT/S3TC.

These will give smaller sizes for both the image file on disk and in GPU memory; for example, DXT1 compression (typically used where there is no alpha channel) will be one-eighth the size of the original. GPU hardware is able to sample directly from such a compressed texture, so there's no decompression step required in your program.

Modern versions of OpenGL and GL ES support an additional for of compression via the GL\_KHR\_texture\_compression\_astc\_hdr and GL\_KHR\_texture\_compression\_astc\_ldr extensions which allow you to use the same assets for mobile as you use for desktop, but of course you're limiting the target hardware if you use them.
> 1 votes

# Answer
Basically, the idea is to spread out the error to adjacent pixels. Let's take a grayscale image for simplicity (for RGB you'd just do the same thing for each channel), and say you had an 8-bit pixel value (255 max) of 116 that you want to scale to 4-bits. The closest 4-bit color (15 max) would be 116\*15/255, which rounds to 7. This, expanded back to 8-bits would be 7\*255/15, or 119. Therefore, your quantized pixel will be slightly brighter than the original by 3 units. To compensate, you spread 3 units out to adjacent pixels (there are several schemes for how the error gets distributed) and subtract them in before the quantization step on those pixels.

Let's take a really simple scheme -- one you'd never use in real life, but is simple enough for now -- and subtract those 3 units to the next pixel to the right. Say that pixel has a value of 67. You'd subtract 3 from 67 to get 64. 64\*15/255 rounds to 4, 4\*255/15=68, and now you've got an error of 4, which gets subtracted from the next pixel to the right, and so on.

The error accumulation above is a good reason why you usually spread the error to more than one pixel. Floyd–Steinberg dithering adds 7/16 of the error to the pixel to the right, 5/16 of it to the pixel below, 3/16 to the one below and to the left, and 1/16 to the one below and to the right:

```
     (pixel) 7/16
3/16   5/16  1/16

```

The general procedure, though, is the same.
> 1 votes

---
Tags: graphics, image
---


# Question
Title: Microsoft XNA Platformer Example, is the Collsion Detection implemented accurately?
The example provided by Microsoft seems as if the collision detection (from what I can see) will have a small error. When the user collides with an Unpassable tile, the depth of the intersection is calculated. The smaller of the depth values X and Y is used to fix the position of the user so it no longer collides with the tile. But if the user was travelling diagonally could this result in the user not ending up in precisely the point where the character would first collide with the tile?

I'm probably wrong but that's just the way I see it.

```
   private void HandleCollisions()
        {
            // Get the player's bounding rectangle and find neighboring tiles.
            Rectangle bounds = BoundingRectangle;
            int leftTile = (int)Math.Floor((float)bounds.Left / Tile.Width);
            int rightTile = (int)Math.Ceiling(((float)bounds.Right / Tile.Width)) - 1;
            int topTile = (int)Math.Floor((float)bounds.Top / Tile.Height);
            int bottomTile = (int)Math.Ceiling(((float)bounds.Bottom / Tile.Height)) - 1;

            // Reset flag to search for ground collision.
            isOnGround = false;

            // For each potentially colliding tile,
            for (int y = topTile; y <= bottomTile; ++y)
            {
                for (int x = leftTile; x <= rightTile; ++x)
                {
                    // If this tile is collidable,
                    TileCollision collision = Level.GetCollision(x, y);
                    if (collision != TileCollision.Passable)
                    {
                        // Determine collision depth (with direction) and magnitude.
                        Rectangle tileBounds = Level.GetBounds(x, y);
                        Vector2 depth = RectangleExtensions.GetIntersectionDepth(bounds, tileBounds);
                        if (depth != Vector2.Zero)
                        {
                            float absDepthX = Math.Abs(depth.X);
                            float absDepthY = Math.Abs(depth.Y);

                            // Resolve the collision along the shallow axis.
                            if (absDepthY < absDepthX || collision == TileCollision.Platform)
                            {
                                // If we crossed the top of a tile, we are on the ground.
                                if (previousBottom <= tileBounds.Top)
                                    isOnGround = true;

                                // Ignore platforms, unless we are on the ground.
                                if (collision == TileCollision.Impassable || IsOnGround)
                                {
                                    // Resolve the collision along the Y axis.
                                    Position = new Vector2(Position.X, Position.Y + depth.Y);

                                    // Perform further collisions with the new bounds.
                                    bounds = BoundingRectangle;
                                }
                            }
                            else if (collision == TileCollision.Impassable) // Ignore platforms.
                            {
                                // Resolve the collision along the X axis.
                                Position = new Vector2(Position.X + depth.X, Position.Y);

                                // Perform further collisions with the new bounds.
                                bounds = BoundingRectangle;
                            }
                        }
                    }
                }
            }

            // Save the new bounds bottom.
            previousBottom = bounds.Bottom;
        }

```

# Answer
**You are absolutely right**. I've had my share of problems with the collision routines on the XNA platformer sample. But I've managed to start from the code as provided in the sample, and modified it a bit until I achieved consistent results in every test scenario I could throw at it.

In particular, the sort of problem I was having was when trying to slide along a wall by moving diagonally against it. Because of the assumption the sample makes in order to resolve collisions based on the smallest axis of displacement, this resulted in the character not being able to move when pushing against a wall in *some* direction. For instance, using one sign, I would get stuck when hugging the ceiling and trying to move against it from left to right (can't remember the specifics). Switching the sign would solve that situation but a problem would appear in the opposite scenario. Bottom line is that with the provided implementation I couldn't get it to work correctly in *all sides and from every direction* \- it would always fail on at least one case.

So the core of the changes I did were all about starting to handle movement on the X axis independently from movement on the Y axis, on two separate steps. I've written about it before in this answer so head there for the details.

And if I remember correctly, the actual reason for it was something like this:
> 12 votes

# Answer
When you have multiple collisions if you rectify your collisions from closest to farthest away from the center of each rectangle involved, you will not have the issue of "hanging."

1) Find all the colliding rectangles

2) If there are more than one (depending on your use case this can be frequent or infrequent), find the closest.

3) Resolve collisions one at a time and check if the others are still valid collisions

In the accepted answer the collision and input logic are muddy; it has checks to determine the heading, etc. Implementing it in the described manner keeps the collision logic separate from the input logic at the cost of calculating distance when necessary.
> 1 votes

---
Tags: xna, c#, collision-detection, platformer, collision-resolution
---


# Question
Title: How to auto animate character movement - Unreal engine 4
I am learning Unreal 4. And basically I want to find out how to auto move character. Which means when I start playing I want the character to auto move forward without my interaction. I know how to do it in UDK, but can't do it in Unreal 4.

# Answer
Ok, lets take a look at this image:

What this function does is moving your pawn in a desired direction. Just put this into your tick event, add a direction, set the target to itself, and you are done.

This function can also be used multiple times per tick, this just adds to the movement vector, for example if you want to strafe left.
> 2 votes

# Answer
I have not registered yet as a user for the Unreal Engine 4, so not sure what kinds of tutorials are available.

But, from watching all the YouTube videos, I would assume you would just need to put in a change of vector in your level blueprint so that when the game initiates, you have it get actor vector, then alter the X,Y vector of your Main Actor.

Possibly even using a tick to give it some animation such as every second change the X or Y by 5 or something like that so that you don't have it jump from say 0 to 400 in a second. Basically teleporting your actor across the map.

That would be my assumption on a method to perform that.
> 0 votes

---
Tags: unreal
---