# Question
Title: How can I make a self-updating game launcher?
I have been creating a game with java, and before I release it I wanted to make a launcher that is connected to the game's website.

Basically I need to make a launcher that updates itself when I have changed the content.

Unfortunately I have no idea on how to do this. There would be a description in the main launcher which only I can change, and a large play button that will close the launcher and run the game. If I have changed the description, then it will change on the website download, and on the copy that anyone else owns (anywhere).

So, because of my lack of knowledge on this topic, does anyone know how I'm supposed to do this, and how it would work?

# Answer
> 1 votes
Here's a launcher I made about a year ago:

```
package Joehot200;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JProgressBar;

public class Main extends JFrame{

String version = "0.0";
boolean needDownload = false;
static JFrame fr;
public static void main(String[] args){
    fr = new Main();
}
public void needDownload(){
    {
        File f = new File(System.getProperty("user.dir") + "/ver.txt");
        try {
            List<String> lines = Files.readAllLines(Paths.get(f.getAbsolutePath()), StandardCharsets.UTF_8);
            for (String str : lines){
                version = str;
                System.out.println("Version: " + str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    progressBar.setValue(25);
    {
StringBuilder page = new StringBuilder();
URL google;
try {
    google = new URL("http://endcraft.net/ver");

//URL google = new URL("www.endcraft.net/Post");
URLConnection yc = google.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
progressBar.setValue(50);
while ((inputLine = in.readLine()) != null) {
    System.out.println(inputLine + " || " + version);
    if (!inputLine.contains(version)){
        needDownload = true;
        System.out.println("Downloading!");
        File f = new File(System.getProperty("user.dir") + "/ver.txt");
        if (f.exists()) f.delete();
        f.createNewFile();
        PrintWriter writer = new PrintWriter(f.getAbsoluteFile(), "UTF-8");
        writer.println(inputLine);
        System.out.println("Updated to version " + inputLine + " from version " + version);
        writer.close();
    }else{
        System.out.println("No downloaded needed!");
    }
}
progressBar.setValue(100);
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
    }
    //RES TODO
    {
/*StringBuilder page = new StringBuilder();
URL google;
try {
    google = new URL("http://endcraft.net/verres");

//URL google = new URL("www.endcraft.net/Post");
URLConnection yc = google.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
    System.out.println(inputLine + " || " + versionRes);
    if (!inputLine.contains(versionRes)){
        downloadRes = true;
        System.out.println("Downloading res!");
    }else{
        System.out.println("No res downloaded needed!");
    }
}
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}*/
    }
}
//boolean downloadRes = false;
JProgressBar progressBar;
JProgressBar oprogressBar;
int i = 0;
List<Thread> threads = new ArrayList<Thread>();
long lastTime = 0;
public Main() {
    fr = this;
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int width = (int) screenSize.getWidth();
    int height = (int) screenSize.getHeight();
    fr.setTitle("Downloading game...");
    fr.setBounds(width / 2 - 200, height / 2 - 50, 400, 100);
    fr.setVisible(true);
    progressBar = new JProgressBar(0);
    oprogressBar = new JProgressBar(0);
    progressBar.setBounds(0, 0, 400, 50);
    oprogressBar.setBounds(0, 50, 400, 50);
    fr.add(progressBar);
    fr.add(oprogressBar);
    progressBar.setValue(0);
    oprogressBar.setValue(0);
    needDownload();
    //if (downloadRes){

    {
        {
        File f = new File("res/");
        if (!f.exists()){
            if (!f.mkdir()){
                System.out.println("Unable to create dir!!");
                System.exit(1);
            }else{
                System.out.println("Created dir!");
            }
        }else{
            System.out.println("Dir already exists");
        }
        }
        {
            File f = new File("res/natives-win");

        if (!f.exists()){
            if (!f.mkdir()){
                System.out.println("Unable to create dir!!");
                System.exit(1);
            }else{
                System.out.println("Created dir!");
            }
        }else{
            System.out.println("Dir already exists");
        }
        }
        progressBar.setValue(10);
        try{
            {
                URL url = new URL("http://www.endcraft.net/webstart/res/download.txt");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("HEAD");
                File fi = new File("res/download.txt");
                System.out.println((fi.length() != conn.getContentLength()) + " " + fi.length() + " || " +  conn.getContentLength());
            if (!fi.exists() || fi.length() != conn.getContentLength()){
                System.out.println("Downloading resource!");
                download("http://www.endcraft.net/webstart/res/download.txt", "res/download.txt", conn.getContentLength());
            }else{
                System.out.println("No need to download resource!");
            }

        }
            progressBar.setValue(15);
            ArrayList<String> download = readTextFile("res/download.txt");

            for (final String str : download){

                URL url = new URL("http://www.endcraft.net/webstart/res/" + str);
                final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                progressBar.setValue(30);
                conn.setRequestMethod("HEAD");
                File fi = new File("res/" + str);
                if (!fi.getParentFile().exists()){
                    fi.getParentFile().mkdirs();
                }
                System.out.println((fi.length() != conn.getContentLength()) + " " + fi.length() + " || " +  conn.getContentLength());
            if (!fi.exists() || fi.length() != conn.getContentLength()){
                System.out.println("Downloading resource!");
                progressBar.setValue(50);
                Thread t = new Thread() {
                    @Override public void run() {
                        download("http://www.endcraft.net/webstart/res/" + str, "res/" + str, conn.getContentLength());
                    }
                  };
                  t.start();
                  threads.add(t);

            }else{
                System.out.println("No need to download resource!");
                progressBar.setValue(100);
            }

            }
             i++;
                oprogressBar.setValue((int) ((i * 100.0f) / download.size() - threads.size()));

        }catch (Exception e){

        }
        }
    progressBar.setValue(50);
     File f = new File("privateers.jar");
     System.out.println("Exists: " + f.exists());
     try{
     URL url = new URL("http://www.endcraft.net/webstart/privateers.jar");
        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("HEAD");
    if (needDownload || !f.exists() || f.length() != conn.getContentLength()){

        Thread t = new Thread() {
            @Override public void run() {
                download("http://www.endcraft.net/webstart/privateers.jar", "privateers.jar", conn.getContentLength());
            }
          };
          t.start();
          threads.add(t);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

     for (Thread t : threads) {
          try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    progressBar.setValue(95);
    try {
        File dir = new File("settings");
        if (!dir.exists()){
            dir.mkdirs();
        }
        String exec = (System.getProperty("user.dir") + java.io.File.separator + "privateers.jar");
        String[] command = {"java", "-jar", exec};
        ProcessBuilder pb =
                   new ProcessBuilder(command[0], command[1], command[2]);
        progressBar.setValue(100);
        System.out.println(pb.command());
        pb.start();
        //final Process process = Runtime.getRuntime().exec(command);
        System.out.println("Running " + exec);
        //while (true){
        //System.out.println(process.waitFor() + " || " + process.getOutputStream());
        System.exit(0);
        //}

    } catch (IOException e1) {
        e1.printStackTrace();
    }

}
void download(String source, String destination, int size) {

    // ten percent of the total download size
    File ofile = new File(System.getProperty("user.dir") + "", destination);
    System.out.printf("\nDownloading\n\t%s\nTo\n\t%s\n", source, destination);
    try {
        if (ofile.exists()) ofile.delete();
        if (!ofile.createNewFile()) {
            throw new IOException("Can't create " + ofile.getAbsolutePath());
        }

        int inChar = 0;
        URL url = new URL(source);
        InputStream input = url.openStream();
        FileOutputStream fos = new FileOutputStream(ofile);
        for (int i = 0; i < size && inChar != -1; i++) {
            if (System.nanoTime() > lastTime + 2000000000){
                lastTime = System.nanoTime();
            int percentage = (int) ((i * 100.0f) / size);

            progressBar.setValue(((int) ((percentage * 100.0f) / 100)));
            fr.setTitle(ofile.getName() + ": " + progressBar.getValue() + "%" + " Total: " + oprogressBar.getValue() + "%");
            }
            inChar = input.read();
            fos.write(inChar);
        }
        i++;
        oprogressBar.setValue((int) ((i * 100.0f) / threads.size()));
        input.close();
        fos.close();
        System.out.println("Downloaded " + ofile.getAbsolutePath());
    } catch (EOFException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static ArrayList<String> readTextFile(String fileName) {

      ArrayList<String> values = new ArrayList<String>();
      FileReader file = null;

      try {

        file = new FileReader(fileName);
        BufferedReader reader = new BufferedReader(file);
        String line = "";
        while ((line = reader.readLine()) != null) {
            //////System.out.println(line);

            //line = line.replace("~", "");
            //if (!line.endsWith("~")) line = line + "~";
            //if (line == "" || line.startsWith("~") || line.length() <= 1){
            //  line = ChatColor.GREEN + " ~";
            //}
          values.add(line);
          //////System.out.println(line);

        }
      } catch (Exception e) {
          e.printStackTrace();
          throw new RuntimeException(e);
      } finally {
        if (file != null) {
          try {
            file.close();
          } catch (IOException e) {
            // Ignore issues during closing
          }
        }
      }
      //String[] returnValue = new String[values.size()];
      //for ()
      return values;
    }
}

```

It pings http://www.endcraft.net/webstart/ver and sees if it's different than a current version stored in a file - If it is, download the updated JAR.

It also downloads all files listed at http://www.endcraft.net/webstart/download \- Unfortunately I lost that file, so vising it will point to a blank URL.

---
Tags: java, deployment
---


# Question
Title: Unity2D: Rendering multiple sprites as a single one
I'm creating NPCs in Unity 2D using C#, and I have 16x16 sprites for body, helmet, clothes and weapon. All these have a tile set which has been split in unity. I'd like to be able to render one of each part together, so I can drag the sprite to the field, and then it will be rendered on the NPC. IE, I drag a helmet sprite into the helmet field and that is the rendered helmet.

I intend on having multiple NPCs, so I'd prefer to minimise the child objects. Multiple sprites will need rendering, however there's only one sprite renderer. Is it possible for me to combine the sprites (in code), and then render the final sprite? Or is there perhaps a better way?

Thanks in advance!

# Answer
> 2 votes
Yes, you are stuck with needing a child object for each individual sprite that makes up your characters.

It's not as tricky as it sounds though.

You can create one generic "Humanoid Character" prefab with child objects like "Body", "Helmet", "Weapon", etc. You can then use this prefab for both PC and NPCs.

**Layers**
Pay attention to Sprites layering. Almost certainly you'll want the "Helmet" sprite to be rendered on top of "Body" sprite.

There are two levels of ordering:

My suggestion is to have the whole Character on the same Sorting Layer. You can then use Order in Layer to sort the individual parts which make up the character.

# Answer
> 0 votes
If you create a single material for the sprites, and they use a spritesheet, they should be batched into a single draw call automatically. :)

From the Unity3D answer hub (kindly answered by ivomarel):

> Yes, make sure that the sprites are in the same atlas. When you select a sprite, (Texture type should be sprite), look at the inspector and choose sprite mode 'Multiple'. Then, make sure you give the sprite a packing tag. Sprites with the same tag will be packed and batched together as soon as you run it in the Editor.
>
> Note: You also have to set Edit \> Project Settings \> Editor \> Sprite Packer Mode to 'Always Enabled'

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


# Question
Title: Height field/Shallow water eqation water simulation with ground height
Hey guys I found a lot of tutorials on 2D height field/swe water simulation but I have yet to find one that takes into account of ground height, i.e.

http://zejiazheng.com/?p=87

The overall water simulation results is fantastic however it does not takes into account of ground height and it doesnt work when the height of water is 0.

Would appreciate help on how to implement that as I've been stuck for several weeks on how to implement it. Thanks!

# Answer
> 4 votes
In a nutshell, what makes a shallow water equation a shallow water equation is that the water height is not zero and it assumes no variation in the seafloor.

Note: No fluid dynamics equation will allow for a water depth of 0, as that would mean you have no fluid.

You should read the Wikipedia article on the shallow water equation. Basically, in shallow water, the vertical velocity is ignored because the value is so small and has minor impact to the wave propagation.

To quote the section in case of modification of the source page:

> The equations are derived from depth-integrating the Navier–Stokes equations, in the case where the horizontal length scale is much greater than the vertical length scale. Under this condition, conservation of mass implies that the vertical velocity of the fluid is small. It can be shown from the momentum equation that vertical pressure gradients are nearly hydrostatic, and that horizontal pressure gradients are due to the displacement of the pressure surface, implying that the horizontal velocity field is constant throughout the depth of the fluid. Vertically integrating allows the vertical velocity to be removed from the equations. The shallow water equations are thus derived.
>
> While a vertical velocity term is not present in the shallow water equations, note that this velocity is not necessarily zero. This is an important distinction because, for example, the vertical velocity cannot be zero when the floor changes depth, and thus if it were zero only flat floors would be usable with the shallow water equations. Once a solution (i.e. the horizontal velocities and free surface displacement) has been found, the vertical velocity can be recovered via the continuity equation.

TL;DR: In order to do what you want to do, you should be using the Boussinesq Approximation, which does not assume a flat seafloor surface.

This is a very interesting question by the way, I don't see many people try proper water simulation often.

---
Tags: simulations, heightmap, water
---


# Question
Title: how to handle interactive choice in the middle of the game loop?
I am programming a turn-based game, 2D tile-based, overhead view. I have an update function and a render function running in separate threads. When it's the player's turn, the player can e.g.

* select a target tile from the map
* then a popup menu with the available interactions appears
* player selects interaction and the interaction gets executed

One tedious way is the following:

```
GameLoopUpdate():
        switch( interaction_state )
            case tile_selected:
                lookup_interactions_for_selected_tile()
                break
            case tile_and_interaction_selected()
                execute_interaction_at_tile()
                break
             default:
                break

```

Of course the above does not scale when the interactions get complex.

Conceptually, I would like it to be more like:

```
KeyListener():
    if tile is clicked
        set_tile_selected()

GameLoopUpdate():
    if tile is selected:
        interaction  = spawn_thread_interaction_selection()
        execute_interaction_at_tile( interaction )

```

where the spawned thread would somehow override the input listeners AND the rendering. But this looks bad as well.

Another idea (I'm starting to consider implementing this) is the following:

```
GameLoopUpdate():
    if it's player's turn
        set next state as PlayerState_Base
    else
        run ai turn

PlayerState_Base():
    if tile is selected
        set next state as PlayerState_TileSelected

PlayerState_TileSelected():
    if interaction is selected
        execute interaction
        set player's turn as done

```

where each state above would have dedicated key listener and rendering functions

Any other ideas?

# Answer
You can't block the main game loop waiting for input. Instead, create some sort of state where you display the popup and listeners for the buttons. When the button is clicked then update your state.
> 2 votes

# Answer
I would recommend you use event handlers. This can be found fairly easily online, but I will give you a quick run-down to save some time for you.

Lets say you have an object that, if hovered over and left-clicked, will fire off an event to be handled in the game class.

I would recommend having each of these objects encapsulated in its own class, and having an event fire from within said object.

https://github.com/shroeder/GameRPG/tree/LukesBranch/Game/Game : Please reference the code found in the Menu Button Class in my github. Here you can see :

1. How an event is declared
2. How an event is raised
3. How an event is handled in another class

You can see I have a class MenuButton, that can be instanciated on the fly and used over and over again. When I instanciate the Menu Button Class, It has events that can be raised on click, and handled in the PauseMenu Class. For additional examples you can reference my Checkbox Class and Slider Class.

Hopefully from my game's code you can see how you will raise your events and handle them. Event's are essentially just listeners that are waiting for a certain set of criteria (mouse hovering over a button, and clicked) to be met. When that criteria is met your objects fire events that tell the game class to handle them in a certain manner.

I hope this helps you, let me know if you have more issues during your project.
> 1 votes

# Answer
I think you should consider the various screens as many different programs. Or let's say, different screens. A screen can render and update by a given dt (delta-time).
The different screens should pile-up, and all should render in proper order, but only the top-most one should update (by dt).
Of course, you need some kind of messaging (through a hashmap/map?) in between screens to make this work.
> 1 votes

---
Tags: game-loop, gui
---


title: Double Jump causing problems?

text:
# Question
Title: Double Jump causing problems?
Here is my code. I have an empty Gameobject directly underneath the child with a small radius checking the ground every thing seems to be correctly covered, but for some reason the jumping mechanic is very finicky and broken feeling. Can you take a look a tell me what you see? Thank you for your time!

```
public class PlayerMovement : MonoBehaviour
{

    public float speed;
    public float height;

    public Transform groundCheck;
    public float groundCheckRadius;
    public LayerMask whatIsGround;
    private bool grounded;

    private bool doubleJumped;

    // Update is called once per frame

    void FixedUpdate ()
    {
        if (grounded)
        {
            doubleJumped = false;
        }

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

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

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

        if (Input.GetButtonDown ("Jump") && !doubleJumped && !grounded)
        {
            Jump();
            doubleJumped = true;
        }

        grounded = Physics2D.OverlapCircle(groundCheck.position,groundCheckRadius,whatIsGround);

    }

    void Jump()
    {
        transform.Translate (Vector3.up * height * Time.deltaTime);
        return;
    }
}

```

# Answer
> finicky and broken feeling

This should probably just be the issue because you're using `FixedUpdate()` instead of `Update()`, thus the groundcheck / jumpcheck, doesn't happen every frame, but every physics update, try changing that and it should be fixed.
> 1 votes

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


# Question
Title: Wall detection in maze game - On the fly or precomputed?
I've been a programmer for over a decade, professionally for the last five years, but I've never really done any games programming. I've had a look at some tutorials but most of what I've found is geared towards people with no programming experience, so I've tended to get bored and moved on. So, after grasping the basics of the game loop, I've decided to dive right in.

As my first project I am programming a basic 2D top down maze game (a Pac Man clone). I've got all the basics working fine, and am now thinking about optimizations. I have an idea to improve the performance of my wall collision detection but I'm interested to know the 'proper' way of doing it.

At the moment my algorithm is basically:

* Check direction player wants to move in
* Loop through all walls and see if any are at that position
* If there are no walls, move the player

This is working fine, but I imagine if I scale it up that the act of looping through all the walls each time will become an issue. Due to the simplicity of the game and the speed of modern computers, it might not ever be noticeable, but I'd rather be using the cycles for something else.

So it occurs to me that as this data is never changing, I could just build a lookup table as part of my map creation within my level editor. I've heard about similar things being done for more complex 3D games. I would then have a lookup table that stored each possible player position, each possible direction, and whether the player can move there. This means that on each move, I can just do a quick check to the lookup table to see if the move is possible, rather than repeatedly looping through a load of static data every single frame.

**Is this a common thing to do? Or are neither of these approaches any use, in which case what is the best way to handle this?**

# Answer
> 7 votes
Lets start with general rule of optimizing things, especially when it comes to games: **Profile it.** It's not worth working on something that works already, because especially with games, you will get stuck optimizing and refactoring what you have, instead of doing actual work.

When a player is playing a game, they usually are doing just that, because a game requires most attention, especially as this will only get called when the player is moving, so the CPU cycles you save are not needed for anything else.

But lets put that aside, this is a learning project, so you want to try what can you do.

The idea you describe has two big negatives:

* While it scales well on CPU speed, it scales very badly with memory.
* It doesn't support floating-point locations or moving directions, which are what you should be using for a smooth experience.(Well, its not a must, but very common)

Lets get to the part: Do they use this? Probably not, at least not like this or for this.

Do they use something similar? Definitely! The answer is in spatial data-structures which let you get a list of only the nearby walls from the player location. This is done in 2D using Quad-trees or BSP usually. In 3D with octrees and BSPs.

What is the best way to handle it? The best way is to get it to work, and when it starts to eat your CPU cycles(You know, because you **Profiled it**), come back and optimize it.

# Answer
> 3 votes
Fun fact: I used to work for the company that made Pac-Man.

Anyway... how are you storing the wall data for your maze? Are you using a tile map? (Relevant: Wikipedia entry on tile maps). If not, you should consider it because one of the biggest benefits to using one is the ability to detect walls purely by looking at the contents of (x, y) in the array storing the tile data.

In other words, you're kind-sorta using a lookup table as you mentioned, but with the ability to go to the exact spot you need to check.

For example, if you had a 10x10 tile maze, you would have a 2-dimensional array where 0 would be an open square and 1 would be a wall. Then, once you determined the tile the player was moving to you just check if tiles\[playerDesiredPosX\]\[playerDesiredPosY\] == 1. If it is, don't let the player move there.

Even if you're working in 3D and not using a tile map as the data structure representing your world, you can still add one purely for the collision data of the "floor" layer that the player moves around on, especially if the walls are squares/cubes/blocks.

So, yes; precomputed. Especially if the walls don't move.

---
Tags: collision-detection
---


# Question
Title: Minecraft Forge Look for Entities in a Certain Location
The title mostly explains it. I have a tile entity that is called Energizer. I want this energizer to check to see if there is an EntityItem on top of it and if so, consume it and create energy. The only problem is, I can't figure out how to check for (and receive) an EntityItem in a certain location (on top of it). I considered using a method that searches for nearby entities and then seeing if they were instanceof EntityItem, but I can't even find a method to do that.

# Answer
> 2 votes
First off, you want to override `ITickable#update()` in your *Energizer* `TileEntity`. Inside here is where you can scan for nearby `EntityItem`s. With the `TileEntity#worldObj` member you can use `World#getEntitiesWithinAABB(Class, AxisAlignedBB)` to find any entities of a given class within the defined bounding box (i.e., right above your tile entity).

```
@Override
public void update() {
    // Create bounding box for block directly above this tile entity.
    double x = (double)this.pos.getX();
    double y = (double)this.pos.getY() + 1.0d;
    double z = (double)this.pos.getZ();
    AxisAlignedBB scanAbove = new AxisAlignedBB(x, y, z, x, y, z);

    // Find entities above this tile entity.
    List entities = worldObj.getEntitiesWithinAABB(EntityItem.class, scanAbove);

    // TODO: Consume entities.
}

```

Imports:

```
import java.util.List;

import net.minecraft.entity.item.EntityItem;
import net.minecraft.util.AxisAlignedBB;

```

---
Tags: minecraft-modding
---


title: Rendering curved text in AndEngine

text:
# Question
Title: Rendering curved text in AndEngine
I'm trying to implement a small game using AndEngine and I have a question about the Text. More specifically, I'm wondering if it is possible to deform the text so that you can have a "curved" text or something like this.

I have searched on the Internet but I couldn't find an answer about this. I have seen that there exists a class Transformation in AndEngine but I don't know if its purpose is what I want to do.

# Answer
> 2 votes
You could try to render the font to a texture, and lay that texture onto an deformed strip of triangles. But maybe somebody knows an easier way, idk

# Answer
> 0 votes
The Text class is an Entity that has a VertexBuffer. If you want to transform the Text then just use a custom VertexBuffer with more vertices. If you have any questions concerning the calculation of the uv coordinates of the vertices to create the warp just ask.

---
Tags: java, andengine, transformation
---


# Question
Title: How to clip or mask entity in android/andengine?
I want to implement masking with sprite in **Andengine**. I want same functionality as in ios class called

> SKCropNode

which works like an masking node! Is there any workaround like this in andengine/opengl ? Thanks.

Edit: This is something I was trying to mask an entity, got no effect, any suggestion?

```
public class ClippingEntity extends Entity//BaseSprite
{

protected int mWidth;
protected int mHeight;

public ClippingEntity(float pX, float pY, int pWidth, int pHeight, TextureRegion t)
{
    super(pX, pY);//, pWidth, pHeight, t);
    mWidth = pWidth;
    mHeight = pHeight;
}

@Override
protected void onManagedDraw(GL10 pGL, Camera pCamera)
{

    pGL.glPushMatrix();
    {

        pGL.glEnable(GL10.GL_SCISSOR_TEST);
        pGL.glScissor(0 + (int) mX, 800 - mHeight + (int) mY, mWidth, mHeight);

        super.onManagedDraw(pGL, pCamera);

        pGL.glDisable(GL10.GL_SCISSOR_TEST);

    }
    pGL.glPopMatrix();

}

```

}

I have also tried Stencil Test but it just clears the color of rectangle. ref: opengl mask tests

Ultimate goal is to disable drawing changes in specific entity where it may aslo have transparent background.

# Answer
You miss some important things. You have to transform the clip-coordinates to camera coordinates and do the clipping with those. But you dont have to reinvent the wheel. Go to github - andengine - there is already a class called ClipEntity that does exactly what you want to achieve.
> 0 votes

---
Tags: android, opengl-es, andengine, masking
---


# Question
Title: Minecraft Forge setTextureName method not working
I am attempting to make an item using the latest version of Forge. For some reason, the setTextureName method gives me an error that says:

> The method setTextureName(String) is undefined for the type ItemKey

I have been trying to fix this for a while, and notice that when I remove the quotation marks from the colon the error for setTextureName disappears, but I get an error on the colon that says:

> Syntax error on token ":", delete this token

an error on the + sign that says

> The operator + is undefined for the argument type(s) String

and finally an error on "key" that says

> The method setTextureName(String) is undefined for the type ItemKey

This is my first time trying to make an item, so help would be greatly appreciated.

EDIT: I just figured out that if I change `MODID` to `modid` in the setTextureName method I stop getting an error message for setTextureName but instead get an error for `modid` saying that

> modid cannot be resolved or is not a field

```
package com.arti.artismod;

import net.minecraft.item.Item;
import net.minecraft.creativetab.CreativeTabs;

public class ItemKey extends Item {
    private String name = "key";
    public ItemKey() {
        setUnlocalizedName(ArtisMod.MODID + "_" + "key");
        setTextureName(ArtisMod.MODID + ":" + "key");
        setCreativeTab(CreativeTabs.tabMisc);
    }
}

```

# Answer
First off, it would be greatly beneficial to learn Java before attempting to create a minecraft mod. There are many great tutorials out there (I personally started out learning with thenewboston's tutorials on youtube) and you'll gain a new useful skill!

Now onto your question. As newton1212 said, texture management has changed in 1.8. In fact, nearly everything related to rendering as a whole has been changed in the base game. JSON is now used for almost the entire system. This tutorial covers updating a mod to 1.8 rather than creating one, however the updated files should be helpful to you anyways.

Good luck and feel free to ask any more questions you have.
> 0 votes

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


# Question
Title: Game video - same content in different sizes
This is more on presenting your content on app store rather than coding.

I wonder how people can capture the same gameplay video in different format.

I mean, if I have iPad and iPhone, the logical way to do it is to capture the gameplay at both device. But my game is like Bejeweled, which the tiles will be spawned randomly, so how do other people do it?

# Answer
> 1 votes
Fake it.

A trailer for a software distribution platform can be one of the most important pieces of marketing material, so it can be well worth the time to invest attention to detail and make sure it shows the customer exactly what you want to show them when you want to show it.

Program a "demo mode" in which your game plays automatically and where the random events happen in exactly the way you want them to happen to present the gameplay in the most attractive way.

By the way: Do you know those "gameplay trailers" where developers present games by playing them while commenting on the gameplay and then say something like *"I didn't expect this to happen, but this shows really well how the game handles..."* \- they are lying. They expected it because it was pre-scripted.

# Answer
> 0 votes
For what I see, the question is about being able to have the same and repeatable gameplay on different devices/screens/etc.

Usually the game can be instrumented to perfectly repeat itself.

For example randoms can be replaced with a pseudo-randoms - perfectly predicatable and repeating.

Physic simulations and floating-point math can be another source of differences. Usually it is kept out of the games logic, so only the details of visual effects are a bit different, but the games inner logic is the same.

---
Tags: video
---


# Question
Title: Working around the current sad state of mobile GPU drivers
I'm working on a OpenGL ES3 app for Android: for various reasons, I decided to roll my own mini-OpenGL rendering engine. So far so good.

Problem is, the GPU drivers in the mobile industry are such sad things, that dire bugs keep appearing with the most innocent actions.

For example: yesterday I added a point to my scene (you know: the kind with 3 coordinates, plus a mat4 for the projection matrix) and I got the following results:

* everything fine on a Samsung S4
* black screen with ANR on my Nexus 5
* hard freeze and reboot on my Nexus 7 (way to go, Qualcomm!)

I admit I use a number of not so common stuff in my rendering engine (the tougher probably being MRT), but we are still talking about features in the OpenGL ES 3 specification.

So the question is: how do you deal with this state of affair? Are there techniques that will minimise the risk of incompatibilities? Does the OpenGL ES 3 (and 2 since we are at it...) specification contains features better not using?

Mind that this is not the first time I stumble on problems like this (earlier during development I had a bug triggered by the GL\_TEXTURE\_EXTERNAL\_OES OpenGL ES2 extension that actually forced me to do a pre-rendering pass, just to avoid getting a purple screen...), and this is turning the whole development into a quite anxiety-provoking experience.

Thank you for any advice!

# Answer
Well, you have it easy. There's only a few hundred models available, with probably a few dozen representative configurations. It's not like most people build their own smartphones, like with custom PCs where you can have trillions of different configurations.

There's no way around this. Drivers are buggy, and you can either complain or act on that.

Generally speaking, what you want to do is test a lot, especially in the early stages where you're still building your engine. Try to base your game on the most basic features, and leave the functionality that requires the more obscure features optional.

For example, make your game with a single render target. If some of your effects can be enhanced with multiple render targets, then use that on devices that you know support that, but don't make it mandatory for the feature to work, because you will spend all your time looking for workarounds for each different configuration.

Really, there's no way around this. That's the path you chose when you started making your own engine. If you dislike this, you will probably have a more enjoyable time using a third party engine.
> 1 votes

---
Tags: opengl-es, debugging, compatibility, opengl-es3
---


# Question
Title: Does a basic game engine prototyping tool exist, for common game types?
There are a lot of classic game engines out there (Real Time Strategy, Turn Based, etc), of which you can find countless variations. All of them have a basic starting point which involves units, buildings that produce units, unit/building parameters like health, damage, etc, a map canvas. These can be simulated at a very basic level, no graphics, no animations.

I want to build a Tower Defense type of game, and it would be great if i could build a very basic prototype just to simulate parameters like health, damage, speed, range, etc.

Does such a tool exist?

# Answer
> 4 votes
Have you considered using a map editor of an existing game for building your prototype?

Since you've mentioned wanting to build a Tower Defense game, why not use the map editor from other strategy game to script your idea? StarCraft II has, as far as I know, a very powerful editor that has already been used to create a lot of different mods (MOBA maps, tower defense maps and even a third person shooter of sorts).

There are a number of advantages to using an already existing game editor instead of a bare-bones tool or engine:

1. It's much easier to get people to give you feedback if they don't need to install new tools in order to play your prototype. Also, some games (like StarCraft II), offer you ways in which you can publish your mod and get it front of as many players as possible;
2. You have an existing set of assets (unit models, sounds etc.) so your prototype can look decent while you're building it (having box graphics everywhere might turn some players away);
3. You may discover that, after developing your idea for a while, you don't want to rewrite it for another game engine. Instead, you have the option of developing your prototype as a mod of an existing game (as was the case with games like Counter-Strike or the original DotA).

# Answer
> 0 votes
Here at PreviewLabs, a company specialized in game prototyping, we're using Unity3D as an all-round tool for game prototyping.

We like having full control over the prototyping process, and the best way to do this is to write the entire prototype from scratch, while limiting the scope and focusing on what matters. This gives you the freedom to make any kind of change to your game's concept, without being limited by existing systems or code you didn't write.

If you're using a genre-specific game development tool (such as a specialized game engine, or a map editor of an existing game), you need to know whether any innovations you may want to add can be implemented easily using this tool - and that's not easy, as you don't necessarily know up-front what you'll want to change after playing your prototype for the first time.

One example of a tower defense game we prototyped was for the game Siege Breaker (a free-to-play game on iPhone and iPad). For this one we also used Unity3D, in combination with some pre-existing C# pathfinding code. Since Unity 3.5, they also have a built-in pathfinding solution, so you may want to have a look at that too.

There's also an article comparing the prototype and the final game for Siege Breaker on our blog: http://www.previewlabs.com/siegebreaker-game-vs-prototype/

# Answer
> 0 votes
Trabant is a *rapid* prototyping tool for nailing the game mechanics only. It sounds like a perfect fit for you, as it has ugly graphics, no animations, and it is very basic but also extremely powerful.

Disclaimer: I'm the author of Trabant. Hope you find it useful!

---
Tags: game-mechanics, rts, simulations, prototyping
---


# Question
Title: Equation for exponential deceleration so the objects “stops” at destination
Let's say my ship's velocity during deacceleration phase is given by:

```
v(t) = v0 * exp(-k * t)

```

where `v0` is the speed at the time of starting deacceleration and `k` is arbitrary constant.

My problem is: Is it possible to calculate such `k` that the ship "stops" (let's say slows to a velocity `vf`) at the target position given:

* v0
* distance to the target d0 ?

Or alternatively: given `k` calculating a distance at which deacceleration should start?

I'm making a space simulation game where the ship's warp drive needs to accelerate/deaccelerate exponentially. While accelerating to a maximum speed is easy the problem is with deaccelerating so that the ship "stops" at the destination.

Thank you in advance for any help.

# Answer
> 1 votes
The keyword you're looking for is "easing". There are lots of different easing functions that behave and look different but all of them interpolate some variable from A to B given a time T. If your ship is at A and you want it to decelerate until it hits B, you can give it a velocity by, for example, applying this function:

```
template<class T>
inline T EaseOutExponential(T time, T from, T to, T duration)
{
    static_assert(std::is_floating_point<T>::value, "<T>: T must be floating point");

    assert(duration != 0);

    return to * (-Pow<T>(2, -10 * time / duration ) + 1) + from;
}

```

This isn't "physical", it's just an interpolation. There are lots of other possible functions.

# Answer
> 0 votes
If you accelerate for half the journey and then decelerate at the same rate for the remaining half you will come to a stop at your destination. Did you mean for the velocity to be exponential? That implies a variable acceleration, which is not very realistic. If this is what you intend then just apply the same logic to jerk (which is the derivative of acceleration with respect to time). That would simply involve negating `k`.

Since you will end up at extremely high speeds if the distance is long it might be worthwhile to lock "warp drive" to an analytical model to prevent floating-point error from building up in a numerical integrator.

---
Tags: movement, kinematic
---


title: 2D movement issues

text:
# Question
Title: 2D movement issues
So I'm making a isometric game in javascript, so far it goes well. But I have some problems when a object it suppose to walk from point A to B.

```
Item.prototype.update = function(delta){
    var speed = 1; //<-- hard coded for now
    var deltaX = this.toX - this.x;
    var deltaY = this.toY - this.y;

    var radians = Math.atan2(deltaX, -deltaY) * (180 / Math.PI);
    var distance = Math.sqrt((deltaX*deltaX)+(deltaY*deltaY));

    this.x += Math.cos(radians) * Math.min(speed, distance) * delta;
    this.y += Math.sin(radians) * Math.min(speed, distance) * delta;
};

```

The problems I'm having is that the object that is moving does a strange 180 or 90 turn before it start to head in the right direction, and then slows down when it's near it's destination. I have no idea what causes the problems.

# Answer
> 1 votes
Your slow down is probably caused because you take the Math.min(speed, distance) when distance is lower than your speed (implying that you can't move by your speed each frame (since it's dependant on the delta)).

Your code does not allow me to see what causes the issue with the turn you are describing.

To find out where exactly is your issue, I would suggest you trace your variables by writing their content to the console to see there the bad behaviour comes from.

Edit:

Here is a fix for your situation (I haven't tested in JS, but it works in python)

```
Item.prototype.update = function(delta){
    var speed = 1; //<-- hard coded for now
    var deltaX = this.toX - this.x;
    var deltaY = this.toY - this.y;

    //var radians = Math.atan2(deltaX, -deltaY) * (180 / Math.PI);
    var radians = Math.atan2(deltaY, deltaX);
    var distance = Math.sqrt((deltaX*deltaX)+(deltaY*deltaY));
    var max_distance = delta * speed;
    var distance_this_frame = Math.min(distance, max_distance);

    this.x += Math.cos(radians) * distance_this_frame;
    this.y += Math.sin(radians) * distance_this_frame;
};

```

You had two issues with your use of atan2: first, as pointed in the question's comment, why did you multiply your calculation by `(180 / Math.PI)`, and second, the parameters for atan2 are `y, x`, not `x, y`.

And as I pointed early, your use of `min` was not appropriate. Spamming stuff to the console helps see what values that should be constant vary and helps track where the problem is coming from. When I say *variables* I suggest to also include in there *calculations results*.

---
Tags: javascript
---


# Question
Title: Has piracy ever resulted in a developer getting shut down?
**Has piracy EVER resulted in a developer getting shut down?** That is, has piracy *ever* been so detrimental that it brought about the downfall of a game studio? If I were to release a game, should I be extremely wary of pirates and plan accordingly, or is it safe to assume that it won't damage me or my studio whatsoever?

# Answer
After a little running around the internet I found an interesting article that shows a good example of how pirating can affect a game directly and shutdown a project.

iOS Game, Battle Dungeon, Forced To Shut Down Due To Piracy

In this article, Hunted Cow, the developers behind the iOS game Battle Dungeon ended up shutting down their servers. The reason they gave as quoted:

> “Unfortunately we have taken Battle Dungeon down for the forseeable future. This was due to high levels of server load created by large numbers of pirated copies of the game. The high load revealed technical issues which we don’t feel we can fix to the level that our paying customers deserve.”

I found this interesting because it shows that the piracy directly affected the performance of the servers rather than the revenue the developers were receiving to continue with development. Essentially (for those just wanting to skim the article) the pirated copy of the game hit the torrents of the web and multiplied the number of active players on their servers so drastically it reduced performance to a non playable standard. This resulted in them shutting down the project on December 3rd 2012.

Since then they have upgraded their server hardware and rereleased the app on the iTunes Store on April 8th 2013. However the piracy is what caused them to make these changes, costing money to company, down time of more than 4 months for the paying players and a reworking of their website which would have taken up valuable resources from their planned work.

Piracy may not affect companies directly from losing money from the initial sale, but as with Hunted Cow it can really set you back and potentially enough to shut you down. Hunted Cow were able to readjust and solve the problem after it happened, potentially with user based access to servers being validated for paying customers - however that is my own assumption.

It is something that you can prepare for in many different ways (DRM, payment authentication, server load access restrictions) and still be affected in ways you won't predict. Do your best to estimate what can happen to your services with extra pirated copies (extra load on servers, potential player griefing etc) and account for it as best you can within your budget so it doesn't affect your fair paying customers.
> 103 votes

# Answer
I've never heard of this happening as a loss of sales. There are situations where a company has had a direct loss of money that can be attributed to piracy.

Project Zomboid faced issues with this a few years ago when their updater was cracked. The updater was hacked to allow pirates to download the latest release of the game from Project Zomboid. Since Project Zomboid was using Amazon Cloud services to distribute their updates, the additional downloads were costing them money. This resulted in them taking the game down for a while.

This example, including the example in Blue's answer both show situations where, if the conditions were right, it could have caused the game company to go under.

**These examples show that when a company offers a service as part of their business (online servers, or even direct download updates), this service can be taken advantage of and cost the company more money than it generates.**

These examples show that it's possible to lose money directly as a result of piracy. This means it is possible to go out of business as a direct result of piracy, but as with both examples, the companies can take measures to avoid the continued "unauthorized expenses".
> 40 votes

# Answer
A case where it didn't take down the studio, but it must likely hurt sales and cost money:

Demigod by Stardock was pirated before launch and had a massive server load - 18,000 validated users and 140,000 concurrent users. This prevented everyone from playing:

> "Our stress tests had counted on having maybe 50,000 people playing at once at peak and that wouldn’t be reached for a few weeks by which time we would have slowly seen things becoming problematic... So during the day today, people couldn’t even log on, and in some cases, the Demigod forums, which use one of the affected databases for some piddly thing were even down," he wrote. "Even getting the game running was a pain today because a simple HTTP call to see what the latest version would get hung leaving people looking at a black screen. Stuff of nightmares."

The game took a huge hit in reviews - it was a multiplayer game where the multiplayer didn't seem to work.

As I remember, Stardock had to call people in over the weekend ($ for overtime), they had to spin up the servers sooner ($$ and time), and they had to sink more man hours in patching (probably would have happened anyway, but maybe not on "no one goes home tonight" urgency).
> 26 votes

# Answer
It's actually saved companies before! Leisure Suit Larry was not a very popular game before it was passed around on pirated floppy disks. I remember Al Lowe saying that they sold more strategy guides than copies of the game.

There were no plans on a second game until the piracy eruption(pun intended).
> 20 votes

# Answer
I would be quite wary of such reports, if there are any. Unless you have been or have worked for such an unfortunate developer and know the reason first hand, there is always the possibility that piracy is being used as a scapegoat, or a convenient quarter- to half-truth.

After all, "Our game is SO awesome that it was crushed by its own success and because people are scumbags." sounds a lot better to future customers and/or investors than the myriad reasons for why companies usually fail - all kinds of mismanagement, poor quality or desirability of the product, insufficient marketing, wrong time and place for the product, etc. etc.

See FUD for examples of that strategy.
> 15 votes

# Answer
I can think of one off of the top of my head where DRM and piracy caused a game to have poor(er) sales, and the company ultimate went defunct which may or may not have been directly related to the sales of the game.

Titan's Quest made by Iron Lore Entertainment had DRM where pirated copies were extremely glitchy and crashed a lot, and the pirates spread horrible word of mouth about it around and this affected the sales

I'm not sure if it was directly linked to them going defunct, but I'm sure it didn't help the situation.
> 4 votes

# Answer
I can't find the article right now but a while ago I read one about how the developers of one of the Spyro games spent 1/5 of the budget and development time on an experemental DRM system.

They calculated that this system slowed hackers down by only 6 days and increased revenue by almost 30%.

Though these are not studio closing numbers it does give you an idea of the effect piracy can have on a game. You should most definitely consider the impact it will have on you and plan accordingly.
> 2 votes

# Answer
I should clarify that a developer's job is not lost. Reason: It is not one game that is being pirated, there are loads of it, the piracy of games might increase the word of mouth for those games provided they become popular say GTA series and more. So if a game becomes popular because of piracy and if they achieve the cult status, the requirement of a new version for the same with more graphics, detailing and programming will come as a public demand. Hence a developer job is not lost, but increased.

If we look at the other way where the popularity too fails, the company making that game will either shut in worst case scenario or will make a new version, but in any case, the developer will have his most precious intellectual property and will invest in a new venture or product. So in this case also, his job is not lost.
> 2 votes

# Answer
This is impossible to prove because "loss of sales" is a complete fiction. It compares the actual world and events that have happened to an imaginary parallel universe in which all the users who copied the program were forced to pay for the program (whether or not they still wanted to use that program if they had to pay, and whether or not some of them could afford it).

If a game dev fails, whereas others are surviving, this is probably caused by differences between that game dev and others, since everyone is affected by piracy, but not everyone shuts down.
> 0 votes

# Answer
GreenHeart games was also hit by piracy quite hard, even tough they managed to punch back in a very unique manner.

They uploaded the game themselves to the torrent scene, but it was a modified version. Their game, GameDev tycoon, was modified for this release, so that your virtual game development company would go bankrupt sooner or later because of piracy.

They even had pirates posting at their forums about "piracy ruining them".

Original article

In this article you can also see statistics of genuine vs cracked versions.

While they didn't go bankrupt, I read another article, that I can't find, that stated the game didn't bring any profit, this also had a negative psychological effect on game developers not wanting to continue, in the end they did, and since it seems their game has taken off.
> 0 votes

# Answer
It can be good and bad. The good is it helps to popularize the software (I'm talking in general). Microsoft is the best example. They actually 'allowed' piracy, now 95% of the computers in the world has their software and now, we can't live without them.

Another theory is, don't worry much. If the user is using pirated version, he'll never pay for a non-pirated one, if pirated is not available. I mean, why he is using pirated, because he don't want to pay. So there is not much about lost sales, it may actually increase sales by the popularity and the 'good' people who want to buy. Give an option to register/buy. But the developer will feel bad when they see their software cracked.

Movies is a different game. Pirated will directly attribute to lost sales.

**Edit:** For those who are looking for source, here is a quote from M$. Just what I was saying about Microsoft. Most of their business strategies are opponent crushing ones.

Bill Gates famously said: *"As long as they're going to steal it, we want them to steal ours. They'll get sort of addicted, and then we'll somehow figure out how to collect sometime in the next decade."*
> -3 votes

# Answer
It's not mentioned yet, but some people cite the very piracy friendly CD format of the Dreamcast discs (you just had to burn the iso's, no modding just a bootloader) as one of the major factors in the system's failure. It didn't result in the total collapse of Sega, but we'll never see any hardware from them again.
> -3 votes

---
Tags: project-management, piracy
---


# Question
Title: How is the relationship between Scripts and Objects in Unity?
1. If I don't attach the Script to the Object, will be the code able to "see" the object?
2. When I need to manipulate (such as enabled() or a transform()) two or more Objects, do I need to attach the Script to both or just one?

I'm very confused on this subject because I don't need to specify which GameObject I'm targeting when the script it's attached, but there's also the Find() function which appear to do the same.

# Answer
> 0 votes
Properties like `transform` or `gameObject` are shortcuts for `GetComponent<Transform>()`. So yes, the GameObject your script is attached to is the Object the script "sees". To your second question im not sure what you mean with manipulate but most of the time the answer is yes. MonoBehaviours should (mostly) only affect the GameObjects they're attached to.

To the Find method you mentioned, i guess you mean the `GameObject.Find` method, you should not use it. Has bad performance and if you want a reference on a different GameObject just add a field to your MonoBehaviour and drag-n-drop the object you want to access in the inspector.

For more questions about the script system or other stuff in Unity feel free to ask me.

---
Tags: unity, scripting, objects
---


title: Unity Licensing

text:
# Question
Title: Unity Licensing
I'm sorry if this gets asked a lot but google gives up answers from back in 2008 and all sorts so could somebody please clear up a couple of questions for me please.

I want to make 2D games in Unity, I've made my first one following a tutorial online with Unity free version and I don't see that I will really need any more advanced features than what's available in there.

However, I do want to release to both Android and iOS. When I finished making the game it already lets me build to an APK which I can run on my phone and tablet so my question is really do I need the pro licenses?

Also I'm considering at some point in the future I may want to include paid adverts in my game, can this still be done with free versions?

# Answer
You don't need the pro license to release games for any platform. You just have to upgrade if you made more than 100k in funding or revenue.

I believe paid advertisements can be done with the free version.

https://unity3d.com/unity/faq
> 1 votes

---
Tags: unity, android, ios, licensing
---


# Question
Title: What are atan and atan2 used for in games?
I am having some trouble understanding `Math.tan()` and `Math.atan()` and `Math.atan2()`.

I have basic knowledge of trigonmetry but the usage of SIN, COS, and TAN etc for game development is very new to me.

I am reading on some tutorials and I see that by using tangent we can get the angle in which one object needs to be rotated by how much to face another object for example my mouse. So why do we still need to use atan or atan2?

# Answer
> 98 votes
The tangent formula is this:

`tan(angle) = opposite/adjacent`

Refer to this drawing:

Where `a` is the adjacent side, `o` is the opposite side and `theta` is the angle. Similarly, sine and cosine are sin(ang)=o/h and cos(ang)=a/h where `h` is the long side: http://www.mathwords.com/s/sohcahtoa.htm

Meanwhile `atan` (short for *arc-tangent*, also known as the *inverse tangent*) is the reverse of `tan`, like so:

`atan(opposite/adjacent) = angle`

Thus, if you know the values of both the opposite and adjacent sides (for example, by subtracting the object's coordinates from the mouse coordinates) you can get the value of the angle with `atan`.

In game development though, it can happen fairly often that the adjacent side is equal to 0 (e.g. the x coordinate of a vector being 0). Remembering that `tan(angle) = opposite/adjacent` the potential for a disastrous divide-by-zero error should be clear. So a lot of libraries offer a function called `atan2`, which lets you specify both the `x` and `y` parameters, to avoid the division by zero for you and give an angle in the right quadrant.

(diagram courtesy of gareth, please vote up his answer too)

---

The use of trigonometry in game development is pretty common, especially with vectors, but usually libraries hide the trigonometry work for you. You can use sin/cos/tan for a lot of tasks which involve geometric manipulations to find a value from a triangle. All you need is 3 values (side lengths / angle values) to find the other values of a rectangle triangle, so it's quite useful.

You can even use the "cycling" nature of the sine and cosine functions for special behaviors in a game, e.g. I've seen cos/sin used a lot to make an object turn around an other one.

# Answer
> 63 votes

# Answer
> 12 votes
Here's a slightly different way of thinking about trig functions - including atan() and atan2() - that I find helpful (explanations in terms of "opposite/adjacent" just confuse me for some reason).

You can get from one point to another by moving *x* units horizontally and *y* units vertically (called *rectangular* or *Cartesian* coordinates) or by moving distance *r* at an angle of *Ɵ* (called *polar* coordinates in 2D).

Say we have a polar coordinate (r,Ɵ) and we want to convert it to (x,y).

cos(Ɵ) gives you the proportion of *r* that lies along the *x* axis:

* If *r* = 1 then *x* = cos(Ɵ).
* If *r* = 100 then *x* = 100 * cos(Ɵ).
* In general *x* = *r* * cos(Ɵ).

Likewise sin(Ɵ) gives you the proportion of *r* that lies along the *y* axis:

* If *r* = 1 then *y* = sin(Ɵ).
* If *r* = 100 then *y* = 100 * sin(Ɵ).
* In general *y* = *r* * sin(Ɵ).

How about converting rectangular coordinate (x,y) into polar coordinate (r,Ɵ)?

*r* is the hypotenuse of the right triangle formed by *x* and *y*, so:

* *r* = sqrt( x*x + y*y )

tan(Ɵ) gives the slope - the rise over the run - of the line with length *r*. So:

* tan(Ɵ) = y/x
* Ɵ = atan(y/x)

However, when performing y/x, calculating 3/4 gives the same answer as calculating -3/-4. Likewise -3/4 gives the same answer as 3/-4. So we have atan2(y,x) that handles the individual signs correctly and prevents a divide-by-zero/infinity error.

* Ɵ = atan2(y,x)

# Answer
> 4 votes
Jesse and Sid are basically right, but I suspect you are really after insight into the problem.

Atan2() is needed as atan() doesn't tell you the angle from the horizontal you need as it doesn't cope with quadrants.

This means that using atan for vectors (-2,2) and (2,-2) will give the same value. You would then to switch on the sign of yours arguments and add pi to the result. In addition, you have the divide by zero special case to consider that Jesse mentioned. Also atan2() works better than atan when x is close to 0

So you if you want the angle of a vector between -pi and pi

```
x = -2
y = 2
angle = Math.Atan2(y, x)

```

or

```
x = -2
y = 2
angle = calculateAngle(y, x);

double CalculateAngle(double y, double x)
{
    double angle = 0;
    if (x == 0)
    {
        if (y == 0)
            angle = 0;
        else if (y > 0)
            angle = Math.PI/2;
        else
            angle = -Math.PI/2;
    }
    else
    {
        angle = Math.Atan(y/x);
        if (x < 0)
        {
            if (y > 0)
            {
                angle += Math.PI;
            }
            else if (y < 0)
            {
                angle -= Math.PI;
            }
            else
            {
                angle = Math.PI;
            }
        }
    }
    return angle;
}

```

# Answer
> 1 votes
One use for `atan2` I found in my code is "signed angle".

Normally the way you'd find the angle between two vectors is

```
inline float angleWith( const Vector2f& o ) const
{
    return acosf( this->normalizedCopy().dot(o.normalizedCopy()) ) ;
}

```

But this doesn't tell you which one "leads" (ie is "further ahead clockwise" than the other). This information may be important for gesture tracking.

You could find the angle from the x axis `(1,0)` for both vectors, but there is this nasty problem of ambiguity: a vector with an angle of 315 degrees returns 45 degrees using the `cos` method above, and so does an angle of 45 degrees. You could do a sign check on `y` to fix that, or you could use `atan2`.

```
// Returns + if this leads o.
// more expensive than unsigned angle.
inline float signedAngleWith( const Vector2f& o ) const
{
  float aThis = atan2f( y, x );
  float aO = atan2f( o.y, o.x ) ;
  return aThis - aO ;
}

```

# Answer
> 0 votes
I will clarify a few things in a concise manner. Please refer to trigonometry tutorials online for a detailed explanation.

Let a be an angle. Then tan(a) = tan(a+2\*pi).

atan is tan inverse, that is, gives you the angle given the tan. When you call atan(tan(a+2\*pi)), the answer will be a. This will be inadequate for your application.

atan2 will take 2 arguments to help this exact situations. atan takes x and y, which are basically cos(a) and sin(a).

atan2(sin(a), cos(a)) = a atan2(sin(a+2\*pi), cos(a+2\*pi)) = a+2\*pi /\* sin and cos has different signs, leading to a different answer \*/

Please find some tutorials to explain why this is this way.

Your code should be something like this:

```
if (mouseMoved)
{
  double angle = atan2(mousey - objecty, mousex - objectx);

  object. setTransform to Rotate(angle);

  // If you want to print it
  print angle * Mathf.Rad2Deg; // Because angle provided is in radians
}

```

# Answer
> 0 votes
Please Note atan is not broken. arctan or tan inverse is only a function between -PI/2 and PI/2. It repeats this pattern but then it isn't a function which is a problem for a computer as it doesn't handle multiple answers.

This is the same for asin between -PI/2 and PI/2 and acos between 0 and PI. These are the simplest ranges for a function to occur. For atan and asin it goes from its most negative to its most positive. For acos its goes from its most positive to its most negative. (this assists in interpolating more accurate answers)

so asin, acos and atan are the mathematical functions.

atan2 however is much more usefull for programming as it provides the complete revolution (PI in radians or 360 degrees or 400 gradians). Note they only produced one for tan not for sin or cos. Tan is the only one that uses horizontal and vertical (x,y)

---
Tags: mathematics
---


# Question
Title: Xcode project runs on device, but not simulator
I built a 2D game using Unity3d 5.1.1. When i build and run the project with iPhone connected, the game runs fine on the device. But when i select simulator instead of device, i get an error : " does not have an architecture that can execute" . I run the game on iPhone 4S, but cannot run on the iPhone 4S simulator. Similarly, i selected iPhone 6, 5 etc and get this error every time.

# Answer
> 0 votes
In *Player settings → Optimizations → SDK*, I had to select *simulator SDK*, instead of *device SDK*. That resolves this.

---
Tags: unity, xcode
---


# Question
Title: Determine if AI can traverse a given spline
I have some AI Agents that I want to navigate along a spline. The agents have a speed and a maximum turning radius. For some splines the curvature is too tight for the AI agents to navigate around and they end up shooting of the spline and then turning, which looks weird. How can I take a given spline and find the segments that are too tightly curved for a given agent to traverse without shooting off?

I thought about just taking the angle between control points, but that alone won't account for the speed limitations that I want to impose as well. Can someone point me in the right direction?

I am using Curvy for my spline implementation but using my own agent movement system to walk along the splines. http://www.fluffyunderware.com/pages/unity-plugins/curvy.php

# Answer
If I understand correctly, what you want to compute is the spline's radius of curvature at each point. Then you want to compare that value to an agent's turning radius to determine if the agent will leave the track there. **\[1\]**

To do this, you need to calculate`R(s)`as you see here: https://en.wikipedia.org/wiki/Curvature (under "Curvature of plane curves" \> "Precise definition")

I don't believe Curvy offers second derivatives`T'(s)`(possibly because some of its spline algorithms do not have continuous second derivatives). So, I'll see if I can cook up an approximation here using Curvy's API: **\[2\]**

So, we have`T(s)`for free, just using Curvy's `CurvySplineBase.GetTangent(float)`method. We can use this call to estimate `T'(s)`. Here I am taking the average of just before and just after, but in practice it may not matter, and it does complicate the endpoint code somewhat.

```
public bool checkCurvature(float position, CurvySpline spline, Agent agent)
{
    // This may be too small a difference for Curvy - try larger values
    //   if it behaves poorly.
    float epsilon = float.epsilon;

    // You'll need to enhance this to account for the beginning/end
    //   of the spline (s = 0.0 or 1.0)
    Vector3 tanPrev = spline.GetTangent(position-epsilon);
    Vector3 tanCurr = spline.GetTangent(position);
    Vector3 tanNext = spline.GetTangent(position+epsilon);

    Vector3 prevDiff = tanCurr-tanPrev;
    Vector3 nextDiff = tanNext-tanCurr;

    // average the two, hopefully a better approximation
    Vector3 acceleration = (prevDiff + nextDiff) / (2.0f*epsilon); // dT / ds

    float curvature = acceleration.magnitude(); // k(s)
    float radius = 1.0f/curvature; // R(s)

    // if the agent can turn faster than the curve at this point, return true
    if( agent.turnRadius <= radius )
    {
        return true;
    }
    return false;
}

```

Notes:

\[1\] You may be using a different interpretation of "maximum turning radius" than I am here - perhaps yours is a diameter instead of radius, so you may need to divide by 2. (Or multiply`R(s)`by 2)

\[2\] I do not have Curvy right now so I haven't compiled this or tested it. Sorry. :)
> 1 votes

---
Tags: unity, c#, mathematics, ai, splines
---


# Question
Title: Best way to deal with Collision in JavaFX
This question I'ts no exactly a fix for the current game I'm working on, but I am showing it as an example to explain my problem. I just want to know the best way to handle collision in JavaFX.

My problem is that I cant seem to make collision work with javaFX using the `.intercept()` function. the way I'm doing it is making a Pane that has the image and different overlapping rectangles that make the collision box. then i add this pane to another pane(the game world). then when I try to get the collision boxes that i want to compare and use `.intercept()` function it doesn't work, they seem to always collide no matter what, I am using `.setLayoutX` and Y to move my pane(the ship pane) if that matters and yes I am using `.getBoundsOnParent()`

The only way i have found that kind of works is comparing the panes themselves but that doesn't work since it just tries to compare the fills.

This is my ship:

This is my Collision Box:

Here is colliding by using the whole pane(see it doesn't work)

# Answer
> 2 votes
(i just want to feel like i am helping a game developer)

From my little knowledge in game development i think they are actually intercepting but not appearing as such, you see you have a rectangle ship-in respect to its bounds

```
  ________________
 |               |
 |               |
 |    ship one   | // your rectangle shaped ship in layout
 |               |
 |_______________|           //about to collide with another rectangle shaped
         ________________
        |               |
        |               |
        |  ship two     | // your rectangle shaped ship in layout
        |               |
        |_______________|
 //collision
          //same as these two potions
            !
  __________v______
 |          !     |
 | ship one !     |
 |          !     |
 |        __v_____|______
 |_______|_______| <- --|<----- //this portion(s) does not exist in your shaped ship
         |              |
         |              |
         | ship two     |
         |______________|

```

Here you can see both rectangles are touching each other, so you have a collision but your shaped ship dont appear that way because they are not rectangles, your blue vertical portion starts at the middle-same goes for the other, if you look at your image carefully you see that they are touching each other but maybe with a 2dip space. so if i am to give one of my ignorant solutions(i am now trying to enter deep into game development hence that vocab) i will say move your objects past their surface area..

EDIT

Also you are using boundsInParent- which is bigger or than local bounds, a boundsInParent leaves extra room for your nodes so they can go through transformation, rotation etc, without having to overlap other nodes, that explains the etxra 2dip space or my theory

Hope it wasn't bad enough

---
Tags: java, collision-detection
---


title: Unity C# new Vector3 problem

text:
# Question
Title: Unity C# new Vector3 problem
I get an error every time I try making a line with "new Vector3".

Example 1: `private Vector3 playerPos = new Vector3 (0, .5, 0);` **gives the error:**

> The best overload method match for 'UnityEngine.Vector3.Vector3(float, float, float)' has some invalid arguments

Example 2: `playerPos = new Vector3 (Mathf.Clamp (xPos, -8, 8), .5, 0f);` gives the same error.

I followed the exact line from this video except my y's are different (my doing) and this isn't the first time I had a new Vector3 problem either.

I'm also using 5.0.1 (DX11 if that helps also) and I have not found any solutions. I am quite new to this but Copy and Pasting isn't very hard. (If I do his y axis I get the same problem so it's not that.) I really need help and thanks in advance.

# Answer
If you don't specify an `f` at the end of a decimal value in C#, it's assumed to be of type `double`. To preserve precision, `double` does not implicitly cast to `float`.

So because of the .5 you put in the y (rather than the -9.5f in the tutorial's code), your examples have the signatures:

```
new Vector3(int, double, int)
new Vector3(int, double, float)

```

...both of which can convert implicitly to `new Vector3(float, double, float)`, but that middle argument won't convert to the `float` type the constructor is expecting unless you explicitly cast it or append an `f`.
> 3 votes

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


# Question
Title: How to design basic physics and movement behavior for 2D platformer?
I want to make a simple 2D platformer.

I know some basic 2D physics and how to implement them in a game. How to make a character jump, accelerate, decelerate, etc.

But I have no idea how to actually make a 2D platformer, regarding the character's movement.

For example, I'm not sure how to implement:

1. The character stops moving when running into a wall, but can still move in the opposite direction.
2. Same for ceiling and floor, while taking gravity, acceleration, etc into account.
3. Similar basic physics and behavior related things.
4. Make all of this "natural" in how it's designed. This isn't what I mean:

```
if (character touches ceiling) {fall}

```

but this is what I mean:

```
if (character touches object) {move accordingly}

```

It's a little hard for me to explain what I'm looking for, but I hope you understand.

If you could point me to some good source or tutorial on the subject, that would be great. Or explain these basic fundamental mechanisms yourself. Thanks.

(Without an engine)

# Answer
> 0 votes
You are asking about *collision detection*. Make certain you try learning 2D first, and there are plenty of youtube and wiki tutorials for you to find.

As an example, imagine Mario is represented by a rectangle with position and size. A fireball can also be represented by a point. Then you can check each frame like this:

```
if(fireball.x > mario.x  && fireball.x < mario.x + mario.width &&
    fireball.y > mario.y && fireball.y < mario.y + mario.height){
   //The fireball is inside Mario's bounds! Ohhh nooooo!
}

```

There are lots of types of collision detection, so if you want to keep it simple, make everything the same shape (usually rectangles or circles). Have fun!

# Answer
> 0 votes
In this answer I assume you are using C++ Object Oriented Programming. If you are using another language, then hopefully you are still able to make use of my answer.

1. Do what drumbumLOLcatz said, and do collision detecting. This link has some good examples in JavaScript, which is easy enough to understand and convert to any other language. And a quick Google search should bring up plenty of pages describing in depth collision detecting and how to implement it.
2. Do the same as 1
3. If your trying to set up a physics system that uses Gravity and acceleration, I recommend using a 2d Vector:

```
struct Vector2D {
    float x;
    float y;
}

```

A Vector can be used to represent a Location and Velocity (along with many other things). To set up a simple physics system you have a Vector for Position `Vector2D Position = { 0, 0 };`. Then you have a Vector represent Velocity `Vector2D Velocity = { 1, 1 };`, with each value hold the rate of change for that axis, and each time you update your objects add the Velocity Vector to the Position Vector, causing your object to move based off of velocity:

```
Position.x += Velocity.x;  // Increase the X position by the X velocity
Position.y += Velocity.y;  // Increase the Y position by the Y velocity

```

To add gravity, simply take a Gravity Vector `Vector2 Gravity = { 0, 9.8 };` and add it to the Velocity Vector, increasing your fall speed.
4. As for making it natural? Well... You closest you could get visually to:

```
if (character touches object) {move accordingly}

```

Would be to create a method in your Character class that will check for collision with a given object.

```
if (character.touches(object)) {move accordingly}

```

The .touches() method should look something like drumbumLOLcatz's example. However, in that example, you can only check if they are touching. You wouldn't be able to tell which object is on which side of the other, which is on top, etc. That is fine for the case of a fireball, but when a player hits a block, you need to know what side it was on. What you might want to do is have the `touches()` method return a number, indicating what side the player is on. You could then have a switch to handle each direction.

```
switch character.touches(object)
{
case 1:  // Character is on top
    { move accordingly }
case 2:  // Character is on left
    { move accordingly }
...
{

```

In that way, you would be able to tell what side the character is on the object. I hope this was of some help to you.

---
Tags: 2d, physics, platformer
---


title: Story game loop

text:
# Question
Title: Story game loop
I have been playing story based games such as lifeline or choice of games. I was wondering what game loop best describes what's happening logically? As when mauling over it myself in my head I am trying to come up with the patterns for developing something similar and I keep hitting a brick wall. Essentially allowing for choices. Text. Variables and conditions. Some text can even be re-used with additions to condition blocks.

# Answer
> 0 votes
This is a super broad question. I have no idea what you want to do with the game, the only thing I can say is everything needs to be contained within a while 1 infinite loop. There's not a lot of advice to give besides that. Just don't think about it too much, actually go start programming the game and you will realize what you need as you go. I mean it's pretty clear where you will need certain loops and stuff so just start working on that.

Try starting your code off with just something like

```
string userInput = "";
bool quit = false;
while(!quit)
{
    Console.WriteLine("Hello, press a key to start your quest or type no to quit");
    userInput = Console.ReadLine().ToString();
    if(userInput.ToUpper() == "NO")
    {
        quit = true;
    }
    else
    {
        Console.WriteLine("Alright, moving on to the quest then!");
    }
 }

```

obviously this would create an infinite loop if you hit a key I'm just trying to give you the general idea.

# Answer
> 0 votes
My partial solution to your "brick wall" is... a **Node**. Lots of nodes.
Something along the line of....
First node(Head node):
NodeID:1
Message:"You see a path on the left leading to a gloomy forest. You could taste the hint of the sea from the wind blowing from the right.
Options:
-Option: Title:"Go Left" TargetNodeID:2
-Option: Title:Go Right" TargetNodeID:3
after the above, develop the game loop to run based on the nodes you've created.
The actual game loop could be event based, where you press a button to load next page with little to no animation running.
Or the usual while(true) loop.
Hope it softens the "brick wall" and hope it's the correct "brick wall" we're talking about.

# Answer
> 0 votes
Make methods that seals each of the stages you have(possibly make them into a class), and a infinite loop is will be running on the Start() function along with your storyline.

**Your Story class**

```
public void stage_1()
{
    int choice = 0;
    //Do something at your stage
    if(choice == 1)
        stage_2();
    else if(choice == 2)
        stage_4();
    else
        //Something went wrong
        //By default use the first choice
        stage_2();
}
public void stage_2()
{
    int choice = 0;
    //Do something at your stage
    if(choice == 1)
        stage_3();
    else if(choice == 2)
        stage_4();
    else
        //Something went wrong
        //By default use the first choice
        stage_3();
}
public void stage_3() { //Do something at your stage }
public void stage_4() { //Do something at your stage }
//etc.

public void stage_final()
{
    //Same procedures as above
    MessageShow("Do you want to start again at the beginning?");
    if(choice == 1)
        stage_1();
    else
        end();
}

```

**Your running script**

```
void Start()
{
    stage_1();
}

```

---
Tags: c#, game-mechanics, storyboard
---


# Question
Title: How can I follow the player sprite with the camera?
I've spent the last 4 days trying to figure out how to get a camera to follow the player sprite. I've followed every tutorial I could find and none of them worked.

My Camera script looks like this.

```
namespace CameraTest
{
    public class Camera2D
    {
        #region Fields

        protected float _zoom;
        protected Matrix _transform;
        protected Matrix _inverseTransform;
        protected Vector2 _pos;
        protected float _rotation;
        protected Viewport _viewport;
        protected MouseState _mState;
        protected KeyboardState _keyState;
        protected Int32 _scroll;

        #endregion

        #region Properties

        public float Zoom
        {
            get { return _zoom; }
            set { _zoom = value; }
        }
        /// <summary>
        /// Camera View Matrix Property
        /// </summary>
        public Matrix Transform
        {
            get { return _transform; }
            set { _transform = value; }
        }
        /// <summary>
        /// Inverse of the view matrix, can be used to get objects screen coordinates
        /// from its object coordinates
        /// </summary>
        public Matrix InverseTransform
        {
            get { return _inverseTransform; }
        }
        public Vector2 Pos
        {
            get { return _pos; }
            set { _pos = value; }
        }
        public float Rotation
        {
            get { return _rotation; }
            set { _rotation = value; }
        }

        #endregion

        #region Constructor

        public Camera2D(Viewport viewport)
        {
            _zoom = 1.0f;
            _scroll = 1;
            _rotation = 0.0f;
            _pos = Vector2.Zero;
            _viewport = viewport;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Update the camera view
        /// </summary>
        public void Update()
        {
            //Call Camera Input
            Input();
            //Clamp zoom value
            _zoom = MathHelper.Clamp(_zoom, 0.0f, 10.0f);
            //Clamp rotation value
            _rotation = ClampAngle(_rotation);
            //Create view matrix
            _transform =    Matrix.CreateRotationZ(_rotation) *
                            Matrix.CreateScale(new Vector3(_zoom, _zoom, 1)) *
                            Matrix.CreateTranslation(_pos.X, _pos.Y, 0);
            //Update inverse matrix
            _inverseTransform = Matrix.Invert(_transform);
        }

        /// <summary>
        /// Example Input Method, rotates using cursor keys and zooms using mouse wheel
        /// </summary>
        protected virtual void Input()
        {
            _mState = Mouse.GetState();
            _keyState = Keyboard.GetState();
            //Check zoom
            if (_mState.ScrollWheelValue > _scroll)
            {
                _zoom += 0.1f;
                _scroll = _mState.ScrollWheelValue;
            }
            else if (_mState.ScrollWheelValue < _scroll)
            {
                _zoom -= 0.1f;
                _scroll = _mState.ScrollWheelValue;
            }
            //Check rotation
            if (_keyState.IsKeyDown(Keys.Left))
            {
                _rotation -= 0.1f;
            }
            if (_keyState.IsKeyDown(Keys.Right))
            {
                _rotation += 0.1f;
            }
            //Check Move
            if (_keyState.IsKeyDown(Keys.A))
            {
                _pos.X += 0.5f;
            }
            if (_keyState.IsKeyDown(Keys.D))
            {
                _pos.X -= 0.5f;
            }
            if (_keyState.IsKeyDown(Keys.W))
            {
                _pos.Y += 0.5f;
            }
            if (_keyState.IsKeyDown(Keys.S))
            {
                _pos.Y -= 0.5f;
            }
        }

        /// <summary>
        /// Clamps a radian value between -pi and pi
        /// </summary>
        /// <param name="radians">angle to be clamped</param>
        /// <returns>clamped angle</returns>
        protected float ClampAngle(float radians)
        {
            while (radians < -MathHelper.Pi)
            {
                radians += MathHelper.TwoPi;
            }
            while (radians > MathHelper.Pi)
            {
                radians -= MathHelper.TwoPi;
            }
            return radians;
        }

        #endregion
    }
}

```

And I've been running the update function from the Game1 class but it does nothing.

```
camera.Update();

```

Is it even possible to do a camera that follows the player with XNA 4.0?

# Answer
If you are using XNA's normal 2D graphics routines (i.e. Spritebatch) to draw your scene, a 3D camera script will not be helpful. Instead, store your camera position and scale as Vector2s and update your drawing code in this manner:

```
spriteBatch.Begin();

spriteBatch.Draw(gameObject.texture, (gameObject.location - cameraOffset) * cameraScale, null, Color.White, 0, Vector2.Zero, cameraScale, SpriteEffects.None, 0);
spriteBatch.End();

```
> 0 votes

# Answer
To follow an object I would recommend using Lerp and setting the camera's position to to your player object. You can achieve this by doing something like:

```
camera.Pos = Vector2.Lerp(camera.Pos, player.Position);

```

This should follow your player in a smoothly.
> 0 votes

---
Tags: xna
---


# Question
Title: Using world coordinates instead of pixels
I've been told that having a set pixels-per-world unit number is bad practice because it will not look the same at different resolutions. Because of this, I am trying to learn about using abstract world-space coordinates instead, however I am having some trouble understanding.

I've setup a quick test project for learning this: http://pastebin.com/GiUiR2NS As I understand it, CAM\_WIDTH and CAM\_HEIGHT should be the dimensions of the world in world units. However, I must be missing something because the end result seems to have made the world 50 pixels by 30 pixels. (My "wall" texture drawn at (0,0) in the bottom left is 16x16 pixels)

I am trying to achieve a view with which I can see 50 walls on the x-axis and 30 on the y-axis. I was able to do this when using direct pixel coordinates and multiplying by 16 (the pixels-per-world-unit number), however as stated before, I don't think I want to use this method anymore because of negative affects at different resolutions.

# Answer
You need to specify the width and height when you draw the texture.

`batch.draw(texture, x, y, width, height);`

In your case you want to set the width and height to one since one wall tile is one world unit big. Because you don't specify a width and height the batch uses the width and height of the texture. That is why it covers 16 world units instead of one.
> 2 votes

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


title: Generating mesh along path

text:
# Question
Title: Generating mesh along path
I'm currently trying to generate a path along an array of points (Vector3) This is the result I'm currently getting:

* **The dark gray points are the given path**
* **The red points are the generated vertices**
* **And the triangles are obviously the mesh I failed to generate correctly**

And from the bottom it looks like this, which is odd, because I'd expect all the missing triangles to be at the bottom. But some of them just don't exist:

here's the code i wrote that generates the path mesh

```
//Removed code since there's no need in showing something that doesn't work

```

And here's a quick example of what it looks like when I drag a path:

SOLUTION FOUND

As the accepted answer states, I was skipping triangles in my triangle for loop. Here is my new working code:

```
public static Mesh extrudeAlongPath(Vector3[] points, float width){
    if (points.Length < 2)
        return null;
    Mesh m = new Mesh();
    List<Vector3> verts = new List<Vector3>();
    List<Vector3> norms = new List<Vector3>();

    for (int i = 0; i < points.Length; i++) {
        if(i != points.Length-1){
            Vector3 perpendicularDirection = new Vector3(-( points[i+1].z-points[i].z ), points[i].y, points[i+1].x -points[i].x).normalized;
            verts.Add (points[i]+perpendicularDirection*width);
            norms.Add (Vector3.up);
            verts.Add (points[i]+perpendicularDirection*-width);
            norms.Add (Vector3.up);
        }else{
            Vector3 perpendicularDirection = new Vector3(-( points[i].z-points[i-1].z ), points[i].y, points[i].x -points[i-1].x).normalized;
            verts.Add (points[i]+perpendicularDirection*-width);
            norms.Add (Vector3.up);
            verts.Add (points[i]+perpendicularDirection*width);
            norms.Add (Vector3.up);
        }
    }
    m.vertices = verts.ToArray ();
    m.normals = norms.ToArray ();

    List<int> tris = new List<int> ();
    //Changed i+=3 to i++
    for(int i = 0; i < m.vertices.Length-3; i++){
        if(i%2 == 0){
        tris.Add(i+2);
        tris.Add(i+1);
        tris.Add(i);
        }else{
            tris.Add(i);
            tris.Add(i+1);
            tris.Add(i+2);
        }
    }
    m.triangles = tris.ToArray ();

    m.name = "pathMesh";
    m.RecalculateNormals ();
    m.RecalculateBounds ();
    m.Optimize ();
    return m;
}

```

# Answer
> 1 votes
Try to change the tris for loop to ++ instead of +=3:

```
for(int i = 0; i < m.vertices.Length-3; i++){
    tris.Add(i+2);
    tris.Add(i+1);
    tris.Add(i);
}

```

Each 2 neighboring triangles have 2 shared vertices, so += 3 would skip 2 triangles each time.

---
Tags: unity, c#, procedural-generation, mesh
---


# Question
Title: Inverting the Z coordinate of the light vector
I noticed that in some vertex shaders they invert the Z coordinate of the light vector, i.e.

```
// Compute denormalized light vector in world space
float3 vLightWS = g_LightPosition.xyz - vPositionWS.xyz;
// Need to invert Z for correct lighting
vLightWS.z = -vLightWS.z;

```

Shouldn't be that the light vector starts at the light's position and ends at the vertex position, but in order to use it in the diffuse lighting calculation it is reverted to start at the vertex position and end at the light's position as `float3 vLightWS = g_LightPosition.xyz - vPostionWS.xyz` suggests?

In this case what is the meaning of the Z coordinate inversion?

# Answer
> 1 votes
Z inversion simply means that the data somewhere is wrong. It is completely unnecessary in lighting calculations and can only do good when all vertex/light positions *or* normals happen to be scaled by the vector (1,1,-1) somehow.

# Answer
> -4 votes
It simply inverts the color rendered by your shader

---
Tags: lighting
---


title: Enemy Follow Player Orthogonal Movement

text:
# Question
Title: Enemy Follow Player Orthogonal Movement
I have a Enemy class that Seeks a player if he is in his field of view. Problem is i want the enemy only to move up/down/right/left, not like for example up and left at the same time (diagonal movement).

**EDIT**: **Code updated**

```
    private void SeekPlayer(GameTime gameTime, Player player)
    {
        directionToPlayer = player.Image.Position - Image.Position;
        directionToPlayer.Normalize();

        if(Image.Position != player.Image.Position)
        {
            if (directionToPlayer.X != player.Image.Position.X)
            {
                if(directionToPlayer.X < player.Image.Position.X)
                    Image.Position.X += directionToPlayer.X * MoveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
                else
                    Image.Position.X -= directionToPlayer.X * MoveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
            }
            else if (directionToPlayer.Y != player.Image.Position.Y)
            {
                if (directionToPlayer.Y < player.Image.Position.Y)
                    Image.Position.Y += directionToPlayer.Y * MoveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
                else
                    Image.Position.Y -= directionToPlayer.Y * MoveSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
            }

        }
        UpdateFOV();
    }

```

With the current code the enemy sometimes follows the play on the X coordinates, and when it's the same has the player's, doesn't continue to follow on the Y coordinate. And vice-versa for Y.

# Answer
Your code has some serious issues. First of all, in games, you generally don't want to be moving objects on the screen by a flat amount per frame, because then the frame rate can make you go faster or slower, which is not a good thing. The way you want to be moving your objects is with delta time, which is the elapsed time between this and the previous Update() call.

As far as 'moving to target location' goes, you will need something better than a magical hard-coded number `0.1f`. Check out this question, on how to move an object from one point to another, in XNA/Monogame.

Looking at your code, I don't see any reason for your `directionToPlayer` and `Velocity` variables to not be declared inside your `SeekPlayer()` function, so I declared them there. Also, you have the exact same code in an `if-else` statement. There is no point on doing that, since it is going to get called either way. So you might as well call it after the `if-else` statement. And finally, there is no point in using `return;` as the final command of a `void` function. It is going to return anyway.

```
float speed = 2;
Vector2 velocity = player.Image.Position - Image.Position;
velocity.Normalize();

if(velocity.X > 0.1f) // still not close enough on X-axis
    Image.Position.X += speed; // move on X-axis
else if(velocity.Y > 0.1f) // still not close enough on Y-axis
    Image.Position.Y += speed;  // move on Y-axis
UpdateFOV();

```
> 1 votes

---
Tags: xna, c#, monogame
---