title: Collision avoidance not only AI wrong

text:
# Question
Title: Collision avoidance not only AI wrong
I am trying to implement the game similar to Dota 2 or Warcraft 3. I want this: when user clicks the right mouse button I want to navigate to the click position. However if there is an obstacle in my way I want to go around it.

Here's what I've got so far:

```
// p - where user clicked
// stepSize - something like movement speed
// minDistance - not important for this problem
// objects - all the colliding objects
// shouldStepInto - not important for this problem
public boolean moveTowardsPoint(Point p, double stepSize, double minDistance, ArrayList<GameBodyObject> objects,  boolean shouldStepInto) {

    ArrayList<GameBodyObject> others = (ArrayList<GameBodyObject>) objects.clone();
    others.remove(this);

    double dx = p.getX() - getPosition().getX();
    double dy = p.getY() - getPosition().getY();

    boolean isClose = false;

    Point lastPosition = getPosition().clone();
    if (Math.sqrt(dx * dx + dy * dy) < Math.max(minDistance, stepSize)) {
        isClose = true;

    } else {
        setRotation(Math.atan2(dy, dx));

        // Though the sqrt is expensive operation
        // We check first without using sqrt
        if (shouldStepInto && Math.abs(dx) + Math.abs(dy) < stepSize) {
            if (Math.sqrt(dx * dx + dy * dy) < stepSize) {
                getPosition().setX(p.getX());
                getPosition().setY(p.getY());
            }
        } else {
            getPosition().setX(getPosition().getX() + (stepSize * Math.cos(getRotation())));
            getPosition().setY(getPosition().getY() + (stepSize * Math.sin(getRotation())));
        }
    }

    // -- COLLISION AVOIDANCE -- //

    ArrayList<Double> movements = new ArrayList<>();
    for (GameBodyObject obj : others) {
        // Check collision with all the other GameBodyObjects
        if (checkCollision(obj)) {
            // How much have I moved lastly
            double distanceMoved = getPosition().distance(lastPosition);
            if(!isStatic() && distanceMoved > 0.01) {
                // calculate vector between me and a collider
                Vector v = new Vector(getPosition().getX() - obj.getPosition().getX(), getPosition().getY() - obj.getPosition().getY());
                // Calculate 2 normal vectors
                Vector n1 = v.getNormal(stepSize, 1);
                Vector n2 = v.getNormal(stepSize, -1);
                Point p1 = getPosition().clone();
                Point p2 = getPosition().clone();
                // Try to move in the directions of two normal vectors
                p1.moveByVector(n1);
                p2.moveByVector(n2);
                double dist1 = p1.distance(p);
                double dist2 = p2.distance(p);
                // If I got closer with normal vector n1
                if (dist1 < dist2) {
                    // Store the angle
                    movements.add(n1.getAngle());
                // Otherwise if I got closer with normal vector n2
                } else {
                    // store the angle
                    movements.add(n2.getAngle());
                }
            };
        }
    }

    // If I have stored any angles:
    if(movements.size() > 0) {
        // Reset my position to where it was before moving
        setPosition(lastPosition.clone());
        // Calculate the sum of angles
        double totalAngle = 0;
        for (double angle : movements) {
            totalAngle += angle;
        }

        // Create a vector with total angle and step size.
        Vector v = Vector.createFromLengthAndAngle(stepSize, totalAngle);

        // Move in the direction of calculated vector
        Point newPos = getPosition().clone();
        newPos.moveByVector(v);
        setRotation(totalAngle);
        getPosition().moveByVector(v);
    }

    return isClose;

}

```

Simply I calculate two normal vectors (perpendicular to the vector) pointing from me to colliding element. Then I store angle and after all I create new vector with total of angles.

It works on collision between 2 elements. However when there are multiple elements it starts jiggling (bouncing) and sometimes it even breaks the collision constraints (rules) and walks into a tree.

What am I doing wrong here?

**EDIT** btw my colliders are all circles

# Answer
I found out logical mistake, I should do the sum of angles as `totalAngle` and then divide it by the count of angles so I get `totalAngle / movements.size()`. With that I get a middle vector (in the middle of all the normals). Another thing is that my `checkCollision` wasn't working properly so I had to change that. I also had to check if the collision occurs on the calculated points moved by normal. So my final code looks like this:

```
public boolean moveTowardsPoint(Point p, double stepSize, double minDistance, ArrayList<GameBodyObject> objects,  boolean shouldStepInto) {

    ArrayList<GameBodyObject> others = (ArrayList<GameBodyObject>) objects.clone();
    others.remove(this);

    // -- COLLISION AVOIDANCE -- //

    double dx = p.getX() - getPosition().getX();
    double dy = p.getY() - getPosition().getY();

    boolean isClose = false;

    Point lastPosition = getPosition().clone();
    if (Math.sqrt(dx * dx + dy * dy) < Math.max(minDistance, stepSize)) {
        isClose = true;

    } else {
        setRotation(Math.atan2(dy, dx));

        // Though the sqrt is expensive operation
        // We check first without using sqrt
        if (shouldStepInto && Math.abs(dx) + Math.abs(dy) < stepSize) {
            if (Math.sqrt(dx * dx + dy * dy) < stepSize) {
                getPosition().setX(p.getX());
                getPosition().setY(p.getY());
            }
        } else {
            getPosition().setX(getPosition().getX() + (stepSize * Math.cos(getRotation())));
            getPosition().setY(getPosition().getY() + (stepSize * Math.sin(getRotation())));
        }
    }

    ArrayList<Double> movements = new ArrayList<>();
    for (GameBodyObject obj : others) {
        if (checkCollision(obj)) {
            double distanceMoved = getPosition().distance(lastPosition);
            if(!isStatic() && distanceMoved > 0.01) {
                Vector v = new Vector(getPosition().getX() - obj.getPosition().getX(), getPosition().getY() - obj.getPosition().getY());
                int av = (int)(v.getAngle() * 180 / Math.PI);
                Vector n1 = v.getNormal(stepSize, 1);
                int an1 = (int)(n1.getAngle() * 180 / Math.PI);
                Vector n2 = v.getNormal(stepSize, -1);
                int an2 = (int)(n2.getAngle() * 180 / Math.PI);
                Point p1 = lastPosition.clone();
                Point p2 = lastPosition.clone();
                p1.moveByVector(n1);
                p2.moveByVector(n2);
                double dist1 = p1.distance(p);
                double dist2 = p2.distance(p);
                if (dist1 < dist2) {
                    movements.add(getAngleIfNotColliding(n1, p1, n2, p2, others));
                } else {
                    movements.add(getAngleIfNotColliding(n2, p2, n1, p1, others));
                }
            };
        }
    }
    movements.removeIf(Objects::isNull);
    if(movements != null && !movements.isEmpty()) {
        setPosition(lastPosition.clone());
        double totalAngle = 0;
        for (double angle : movements) {
            totalAngle += angle;
        }

        Vector v = Vector.createFromLengthAndAngle(stepSize, totalAngle/movements.size());
        Point newPos = getPosition().clone();
        newPos.moveByVector(v);
        setRotationWithMaxRotation(totalAngle/movements.size(), GameLogicConstants.MAX_ROTATION_ON_COLLISION);
        getPosition().moveByVector(v);

    }

    return isClose;

}

private boolean checkCollisionWithCircle(Point p, double radius, ArrayList<GameBodyObject> objects) {
    for(GameBodyObject obj : objects) {
        if(CircleCollider.collide(p, radius, obj.getPosition(), obj.getRadius())) {
            double dx = obj.getPosition().getX() - p.getX();
            double dy = obj.getPosition().getY() - p.getY();
            return true;
        }
    }
    return false;
}

private Double getAngleIfNotColliding(Vector n, Point p, Vector alternativeN, Point alternativeP, ArrayList<GameBodyObject> others) {
    if (!checkCollisionWithCircle(p, getRadius(), others)) {
        return n.getAngle();
    } else {
        if(!checkCollisionWithCircle(alternativeP, getRadius(), others)) {
            return alternativeN.getAngle();
        } else {
            return null;
        }
    }
}

```
> 1 votes

# Answer
You can use *NavMesh* for that purpose. Mark the objects that you want to *bake* in *NavMesh* as *Navigation Static*. Attach a *NavMeshAgent* component to the object you want to move. *Bake* the *NavMesh* for the scene.

To Move to a position on click first save the click position into a variable say *clickPosition* and use the *SetDestination()* method of *NavMeshAgent* class:

```
 GetComponent<AI.NavMeshAgent>().SetDestination(clickPosition);

```

It will automatically calculate the required path and will move to the click position.

***for details read the documentation :*** https://docs.unity3d.com/Manual/Navigation.html
> 0 votes

---
Tags: collision-detection, collision-resolution, collision-avoidance, collision-prediction
---


# Question
Title: Creating Dialog Trees in Unity with Python?
I was thinking to create dialog trees with Python in Unity. I was curious if I will using in one project c# scripts and python will not cause problems with compiling scripts. Also I did found few articles about adding Python to unity, but I am not 100% sure if they are actual and they didn't been really detailed enough. Right now I am using the newest version of unity and vs 2017. I already install PythonIron, but also the newest version of it (I lazily just follow where download page leads me).

I was wondering if somebody could enlighten me with how to actually add Python to Unity and how does it work with other scripts (for example, could I have a function in c# script which could be coming from python script?)

Thanks for any kind of help.

# Answer
> 1 votes
https://blogs.msdn.microsoft.com/charlie/2009/10/25/running-ironpython-scripts-from-a-c-4-0-program/

The websites shows how to run IronPython Script in Visual Studio. It looks promising, although after consideration I do not think that creating Dialog Trees in Unity with Python is the best idea any more.

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


# Question
Title: Mathematics: matrix-to-quaternion conversion in left-hand coordinate system
I am implementing a typical skeletal animation system, and it requires the usage of quaternion to interpolate rotations between each poses. The asset I import only has a transform matrix for each joint, so I need code to convert a rotation matrix to a quaternion. However, my game is in left-hand system, and most code snippet online out there are for right-hand system only. I tried the code for such conversion in a right-hand system from this gamasutra post. The animation interpolates correctly in some cases, but most of the time it's not working correctly, and here's the symptom:

Say I am animating a guy, in the first key frame he is in bind pose, and in the second key frame he's supposed to raise his right arm by 30 degrees. If my system interpolates the rotation correctly, his arm would slowly raise up to 30 degrees in the interval, maybe first frame it's 10 degrees, then its 15 degrees, and eventually 30 degrees. However, with the code I have, the guy's arm is rotating the longest path. First frame, the guy's arm rotates -30 degrees, then -60 degrees, and comes to the same place to where 30 degree is. Can anyone give me the code snippet that's equivalent to the gamasutra one, but for left-hand coordinate system? Thanks!

# Answer
It sounds like you are (s)lerping the quaternion the long way around.

in your `slerp` (or `nlerp`) you should have a check that the `dot(a,b)` is greater than 0. Otherwise negate one of them.
> 1 votes

---
Tags: mathematics, matrix, quaternion
---


# Question
Title: How to share image in persistentDataPath to facebook feed?
I'm trying to share an image taking from `CaptureScreenshot()` using `FB.ShareLink(...)` to Facebook.

My code is the following: (After calling FB.Init(), etc..)

```
 string tmpScreenshotPathname = "file:///" + currentScreenshotPathname;
 System.Uri contentUri = new System.UriBuilder(tmpScreenshotPathname).Uri;
 System.Uri imageUri = new System.UriBuilder(tmpScreenshotPathname).Uri;
 FB.ShareLink(contentUri, "Test", "Test desc", imageUri);

```

However, when open the FB share, the page opens for a split second before returning me back to the game. I tried using a normal Uri such as `http://........jpg` and it works fine, but when I try to use a local Uri, it fails.

Is there any way to share the image to the feed without uploading it to the user's Facebook gallery using FB.API? Because there's the case where the user might decide not to share the image to the feed.. but it would have already been uploaded to his gallery from FB.API.

# Answer
Its not possible to upload a local image to Facebook. The image has to be on the cloud. You can try the alternative approach described in this answer - https://stackoverflow.com/a/32264318/3148917
> 0 votes

# Answer
Follow these steps

1. First login using FB.LogInWithPublishPermissions by adding"publish\_actions" permission in parameters.
2. Use Facebook Graph API to upload image

For more details link is here.. http://kayam83.blogspot.com/2017/08/how-to-share-screenshotimage-using.html
> 0 votes

---
Tags: unity, facebook
---


# Question
Title: Finding cells within range on a hexagonal grid
I'm looking for a way to get the cells based on a N range. But no luck.

I'm converting Row Column offset to Cube Coordinate system QR -\> XYZ

```
$range = 1;
for ($dx = -$range; $dx <= $range; $dx++)
{
    for ($dy = max(-$range, -$dx - $range); $dy <= min($range, -$dx + $range); $dy++)
    {
        $dz = -$dx-$dy;
        $points = $hexagon->cube_to_oddq(array($dx,$dy,$dz));
        $x = $hexagon->ver + $points[0] * $hexagon->size * 1.5;
        $y = $hexagon->height + $points[1] * $hexagon->height + ( ($points[0]%2) * ( $hexagon->height / 2 ) );
        $points = $hexagon->drawHex($x,$y, true);
        $pointss = array();
        foreach($points as $p) {
            $pointss[] = $p[0];
            $pointss[] = $p[1];
        }
        imagefilledpolygon ( $png_image , $pointss , 6 , $black );
    }
}

```

Result: Inside every hex cell (First line is QR coordinate) (Second line is XYZ converted coordinate)

Any advice what I'm doing wrong?

Update:

As requested, the Oddq (Q,R) to Cube conversion XYZ

```
    $i = $hex[0] = ROW
    $j = $hex[2] = COLUMN
    public function oddq_to_cube($hex){
        $hex[2] = $hex[1];
        $x = $hex[2];
        $z = $hex[0] - ($hex[2] - ($hex[2]&1)) / 2;
        $y = -$x-$z;
        return array($x, $y, $z);
    }
    $curr_cube = $hexagon->oddq_to_cube(array($i,$j));

```

# Answer
> 1 votes
I think you have the "offset-q" coordinate system mixed up with the cubical coordinate system. In general, it's easier to translate from the cubical coordinates to screen coordinates because it's a simple linear transformation.

```
for ($dx = -$range; $dx <= $range; $dx++)
{
    for ($dy = max(-$range, -$dx - $range); $dy <= min($range, -$dx + $range); $dy++)
    {
        $x = 96 + $hexagon->ver + $hexagon->size * 1.5 * $dx;
        $y = 54.6 + $hexagon->height + $hexagon->height * $dy + $hexagon->height/2 * $dx;
        $points = $hexagon->drawHex($x,$y, true);
        ...

```

---
Tags: php, hexagonal-grid
---


title: Psychology of pixelated lighting

text:
# Question
Title: Psychology of pixelated lighting
# The situation

The game I'm working on has a **16-bit** inspired art theme. It's consistency is relatively relaxed. (i.e. pixels don't *have* to line up.)

Since it has a slightly dark theme, I decided to light up only the surrounding area of the player. Though I'm town because I'm not sure which of the three methods are most appealing.

## Method 1: Smooth lighting

I.e. a smooth gradient between the player and the surrounding area.

I fear it's smooth nature might feel off compared to the rest of the game's art,

## Method 2: Pixelated lighting (without pixel alignment)

I.e. a pixelated gradient that doesn't necessarily have to line up with background tiles.

This is more in tune with the game's art, but it's lack of alignment is noticeable.

*yellow lines are tile borders while teal lines are lighting borders*

## Method 3: Pixelated lighting (with pixel alignment)

Essentially the same as the previous method, except without the lack of alignment. This fits the game's art style well, but almost *too* well. I mean that in a way that the lighting is almost too pixelated.

# Conclusion

Perhaps a combination of these methods is the most psycologically pleasing or maybe something completely differn't will fit the bill.

What are your guys' thoughts? / What have other games done in this situation?

# Answer
> 0 votes
I would experiment having an ambient lighting zone, this way, you can keep the discovery feeling just like in Age of Empires 2. Once you have the ambient lighting, additional methods would blend in easier.

---
Tags: lighting, pixel-art, psychology
---


# Question
Title: How to make Flood fill algorithm return different Lists of separate groups in the grid?
So i have this flood fill method :

```
 public int groupedCells(int y, int x, int value)
{
    //base state
    if (!gSetup.isValidLocation(y, x) ||
        gSetup.getCell(y, x).value != value ||
        gSetup.getCell(y, x).cMAtch.isInMatchPool)
    {
        return 0;
    }

    // keep track of matched cells
    gSetup.getCell(y, x).cMAtch.isInMatchPool = true;

    // collect
    int up = groupedCells(y + 1, x, value);  //  up
    int left = groupedCells(y, x - 1, value);  //  left
    int right = groupedCells(y, x + 1, value);  //  right
    int down = groupedCells(y - 1, x, value);  //  down

    // sum
    int total = up + left + right + down + 1;

    return total;
}

```

basically i have this grid :

and currently if i click on a yellow triangle, the method above will tell me how many of them are next to each other.

What i want is a solution that will run all over the grid, and check if a group has :

* less than 3-triangles then do (A)
* if it has 3-triangles then do (B)
* if it has 4-triangles then do (C)

etc ...

Am not sure about this, but i thought the best way is to have a list for every group, and then check those conditions over the lists.

I tried it here but the list keep re-initializing itself, so it always either have 0 cells or 1 :

```
  public List<CellSetup> listedCells(int y, int x, int value)
{
    List<CellSetup> cList = new List<CellSetup>();
    //base state
    if (!gSetup.isValidLocation(y, x) ||
        gSetup.getCell(y, x).value != value ||
        gSetup.getCell(y, x).cMAtch.isInMatchPool)
    {
        return cList;
    }

    // keep track of matched cells
    gSetup.getCell(y, x).cMAtch.isInMatchPool = true;
    cList.Add(gSetup.getCell(y, x));
    // collect
    List<CellSetup> up = listedCells(y + 1, x, value);  //  up
    List<CellSetup> left = listedCells(y, x - 1, value);  //  left
    List<CellSetup> right = listedCells(y, x + 1, value);  //  right
    List<CellSetup> down = listedCells(y - 1, x, value);  //  down

    return cList;
}

```

The result of that method when its called here :

```
for (int y = 0; y < gSetup.cell2DArray.GetLength(0); y++)
        {
            for (int x = 0; x < gSetup.cell2DArray.GetLength(1); x++)
            {

                print(listedCells(y, x, 1).Count);
            }
        }

```

is printing "1" three times and "0" 22 times.

Thank you

# Answer
as written, your listedCells function needs to take cList as a parameter so you don't create a new list for every recursive call.
> 0 votes

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


title: Visual Glitch When Drawing Rects

text:
# Question
Title: Visual Glitch When Drawing Rects
I have the following code:

```
import pygame,random

pygame.init()
screen=pygame.display.set_mode((480,360))

map=[]
for y in range(32):
    row=[]
    for x in range(32):
        row.append(random.randint(0,2))
    map.append(row)

camera=[0,0]
running=True

while running:
    screen.fill((255,255,255))
    for y in range(32):
        for x in range(32):
            tile_position_x = (x*16)-camera[0]
            tile_position_y = (y*16)-camera[1]
            pygame.draw.rect(screen,(255,0,0),(tile_position_x,tile_position_y,tile_position_x+16,tile_position_y+16))
    pygame.display.flip()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running=False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                camera[1]-=10
            elif event.key == pygame.K_DOWN:
                camera[1]+=10
            elif event.key == pygame.K_LEFT:
                camera[0]-=10
            elif event.key == pygame.K_RIGHT:
                camera[0]+=10

pygame.quit()

```

When running this I find that when you scroll a few pixels in any direction the screen looks like this:

Notice the long unsightly white line on the left side. Why is that there? I've read and reread all of my code and it doesn't make any sense why these problems are happening. My only explanation would be that there is some kind of rounding problem going on in my code. But I haven't found any.

# Answer
> 1 votes
The rect argument to `pygame.draw.rect` has the form `(left top, width, height)` not `(left, top, right, bottom)`.

A quick fix is to modify the call to it to look like:

```
pygame.draw.rect(screen, (255,0,0), pygame.Rect(tile_position_x,tile_position_y,16,16))

```

---
Tags: tiles, pygame, scrolling
---


# Question
Title: Android: Make game look the same on all devices
I'm trying to get my android application to look the same on all screen devices. I assume I have to do something regarding the density, I just can't figure it out. And while I have seen very similar questions to this I'm not getting clear answers or I'm just not understanding things resulting in inconsistent results.

So how do I get, for example, my game to look exactly the same on a Samsung Galaxy 7 as on an LG tablet?

Side note: I have looked into scaling the `Canvas` but can't quite figure out how to do this correctly.

**Example**

```
package com.haas.ryan.example;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * Created by Ryan on 8/4/2017.
 */

public class Drawing extends SurfaceView implements SurfaceHolder.Callback {
    private Rect rect;

    public Drawing(Context context) {
        super(context);
        getHolder().addCallback(this);
        rect = new Rect(100, 100, 500, 500);
    }

    public void surfaceCreated(SurfaceHolder sh) {
        Canvas canvas = sh.lockCanvas();
        draw(canvas);
        sh.unlockCanvasAndPost(canvas);
    }

    public void surfaceDestroyed(SurfaceHolder sh) {}
    public void surfaceChanged(SurfaceHolder sh, int format, int w, int h) {}

    public void draw(Canvas canvas) {
        super.draw(canvas);
        System.out.println("call");
        Paint p = new Paint();
        p.setColor(Color.RED);

        canvas.drawRect(rect, p);
        invalidate();
    }
}

```

**Device 1 Screenshot**

**Device 2 Screenshot**

While it's a lot harder to tell on the emulator (my bad I chose 2 phones, should'be chosen a tablet) you can see that the rectangles don't take up the same amount of relative space. In fact on the larger screen the rectangle is actually smaller.

# Answer
> -1 votes
The problem that you are facing comes from different densities of different devices. When you use this constructor `rect = new Rect(100, 100, 500, 500);` you give these values as **pixels**. And the device which has larger number of pixels in its screen, will display the same shape with smaller size. For example:

Imagine you have two devices with the width of;

* 1000 pixels
* 4000 pixels

When you display a line which has a length of 500 pixels, it will cover;

* The half of the first device's width
* The 1/8 of the second device's width.

And users will see different length of lines. You need to calculate the pixels that you give the Rect's constructor accordingly to the density of the device. And here is a way you can do this:

```
int discreteHeight = 500;
int discreteWidth = 400;
float scale = getResources().getDisplayMetrics().density; //This scale value is proportional to device, and it will handle your problem.

int heightInPixels = discreteHeight * scale;
int widthInPixels = discreteWidth * scale;

rect = new Rect(100, 100, 100 + discreteWidth, 100 + discreteHeight);

```

Note that you also need to calculate coordinates with the scale value inorder place the shape to the same position in all different devices. This code is just for you to get the idea.

Hope it helps!

---
Tags: android, scale
---


title: Any GL transformation not working

text:
# Question
Title: Any GL transformation not working
Today I was trying to make a test camera, with a new method(I usually use gluLookAt)

So I got a problem,

```
void GameDraw()
{
    glPushMatrix();
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(90, WIDTH / HEIGHT, 0.001, 10000.0);
    pitch += 1;
    glRotatef(pitch, 1.0, 0.0, 0.0);
    glRotatef(yaw, 0.0, 1.0, 0.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    s->bind();
    test->drawMesh();
    glPopMatrix();
}

```

And my draw function is:

```
glDrawElements(GL_TRIANGLES, indices, GL_UNSIGNED_INT, nullptr);

```

if it isn't working with glDrawElements is there any alternative to use?

Edit: Disabling shader it works fine, but how I can use this with Shader

Please don't use glm examples, because I don't like to use it, I feel more comfortable by using the my math

# Answer
> 1 votes
> Edit: Disabling shader it works fine, but how I can use this with Shader

There is you problem, the default shader gets and uses the matrix stack but your shader probably doesn't. You should multiply the position with `gl_ModelViewProjectionMatrix` in the vertex shader:

```
gl_Position = gl_ModelViewProjectionMatrix * position;

```

The Matrix stack was removed in modern opengl (core version 3.1+) however, which requires you to use a 3rd party lib for your matrix math on cpu and use uniforms to pass it to the shader.

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


title: LibGDX - managing zoom

text:
# Question
Title: LibGDX - managing zoom
Zooming an OrtographicCamera effectively changes the amount of world units that can be shown in the camera window. Should thus the camera viewport dimensions be correspondingly updated upon zoom? For example,

```
...
camera.zoom -= 0.01;
camera.viewportWidth *= camera.zoom;
camera.viewportHeight *= camera.zoom;
camera.update();
...

```

EDIT: Here's the full code:

```
private float CAMERA_WIDTH = 50;
private float CAMERA_HEIGHT = 50;
camera = new OrthographicCamera(CAMERA_WIDTH,CAMERA_HEIGHT);
camera.position.set(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2, 0);
camera.update();
// prints 1.0, 50.0, 50.0   --> OK
System.out.println(camera.zoom + ", " + camera.viewportWidth + ", " + camera.viewportHeight);
...

camera.zoom += 0.1;
camera.update();
// prints 1.1, 50.0, 50.0   --> NOT Ok
System.out.println(camera.zoom + ", " + camera.viewportWidth + ", " + camera.viewportHeight);
...

```

**Executive summary**: if you need the zoomed camera viewportWidth and viewportHeight, maintain them as separate variables. They must not be changed in the camera otherwise zoom calculation messes up (obviously, since the zoom is relative to the values the camera was created with, so the original values are always needed). If you absolutely want or need to reassign camera.viewportWidth and camera.viewportHeight, you have to reset camera.zoom to 1 immediately after.

# Answer
The camera viewport width and height do not need updated after the camera zoom is changed as this is done already inside the update method.

The OrthographicCamera update method:

```
@Override
public void update (boolean updateFrustum) {
    projection.setToOrtho(zoom * -viewportWidth / 2, zoom * (viewportWidth / 2), zoom * -(viewportHeight / 2), zoom
        * viewportHeight / 2, near, far);
    view.setToLookAt(position, tmp.set(position).add(direction), up);
    combined.set(projection);
    Matrix4.mul(combined.val, view.val);

    if (updateFrustum) {
        invProjectionView.set(combined);
        Matrix4.inv(invProjectionView.val);
        frustum.update(invProjectionView);
    }
}

```

After your camera has been updated you should then update your rendering system such as spritebatch to use the new values with:

```
    cam.update();
    batch.setProjectionMatrix(cam.combined);

```
> 1 votes

---
Tags: libgdx, camera
---


# Question
Title: Scaling material texture to be 1pixel = 1 unit
I have a mesh I use to render a sprite texture I set up in a material. This mesh is planar XY-aligned and stationary. It's vertexes are generated from a PolygonCollider.

The problem is that I'm using 1 PPU in the rest of my sprites, but the sprite rendered in the texture looks extremely small.

How can I make the scale of the texture's material, so the size of a pixel in the material is equal to 1 unit?

I can't just scale it, because I need it to be EXACTLY 1 unit.

# Answer
> 2 votes
As luck would have it, the previous script I gave you already assigns UVs so that 1 unit of texture space = 1 Unity scene unit. So as long as you're not scaling or twisting your object, and its pivot (local origin) is exactly on an integer coordinate, then the texture repeat grid and the Unity world space grid will already match.

So, all we need to do now is account for the number of pixels in our texture.

Here I've used a texture that's 16 x 16 pixels. So at the default 1:1 material scale, when the full texture repeats once for each Unity scene unit of space, it maps to 16 pixels per unit. (standard cube added for reference)

If we only want one pixel per unit, then we need to slow down our traversal of the texture space, so we stay on each pixel longer. Specifically, we want to cross only one sixteenth of a unit of texture space for each full unit we have now.

So we change the texture tiling parameters in the Material inspector to 1/16 = 0.0625

Now each texture pixel (texel) covers exactly one Unity scene unit (again, shown with standard 1x1 unit cubes to demonstrate the alignment)

---
Tags: unity
---


# Question
Title: How to make top-down AABB collision response work properly in MonoGame?
I have a problem with top-down racing game I'm working on. I need to implement AABB collision with other cars and objects. But when going fast enough, the car can go through thin objects when hitting top and left sides or bottom right corner if the surface is limited with colliders on each side. Here's da codez of collision response:

```
private void OnCollision(BoundsCollider sender, BoundsCollider collider)
{
    // TODO: question stackexchange gamedev what's wrong with left and top
    // maybe i should compare the center point...
    if (sender.Rect.Left < collider.Rect.Right) // right
    {
        sender.GameObject.Transform.Position += new Vector2(1, 0);
        if (GameObject.IsAI)
        {
            if (collider.GameObject != null)
            {
                Velocity = new Vector2(-collider.GameObject.Rigidbody.Velocity.X, Velocity.Y);
            }
            else
            {
                Velocity = new Vector2(-Velocity.X, Velocity.Y);
            }
            AngularVelocity = 0.01f;
        }
        else
        {
            Velocity = new Vector2(-Velocity.X, Velocity.Y);
        }
    }
    else if (sender.Rect.Right >= collider.Rect.Left) // left (working wrong)
    {
        sender.GameObject.Transform.Position += new Vector2(-1, 0);
        if (GameObject.IsAI)
        {
            if (collider.GameObject != null)
            {
                Velocity = new Vector2(-collider.GameObject.Rigidbody.Velocity.X, Velocity.Y);
            }
            else
            {
                Velocity = new Vector2(-Velocity.X, Velocity.Y);
            }
            AngularVelocity = -0.01f;
        }
        else
        {
            Velocity = new Vector2(-Velocity.X, Velocity.Y);
        }
    }
    if (sender.Rect.Top < collider.Rect.Bottom) // bottom
    {
        sender.GameObject.Transform.Position += new Vector2(0, 1);
        if (GameObject.IsAI)
        {
            if (collider.GameObject != null)
            {
                Velocity = new Vector2(Velocity.X, -collider.GameObject.Rigidbody.Velocity.Y);
            }
            else
            {
                Velocity = new Vector2(Velocity.X, -Velocity.Y);
            }
        }
        else
        {
            Velocity = new Vector2(Velocity.X, -Velocity.Y);
        }
    }
    else if (sender.Rect.Bottom >= collider.Rect.Top) // top (working wrong)
    {
        sender.GameObject.Transform.Position += new Vector2(0, -1);
        if (GameObject.IsAI)
        {
            if (collider.GameObject != null)
            {
                Velocity = new Vector2(Velocity.X, -collider.GameObject.Rigidbody.Velocity.Y);
            }
            else
            {
                Velocity = new Vector2(Velocity.X, -Velocity.Y);
            }
        }
        else
        {
            Velocity = new Vector2(Velocity.X, -Velocity.Y);
        }
    }
}

```

How do I do it right? If you'll need the whole project, I'll share one with you.

BTW I also use MonoGame.Extended for RectangleF and other stuff

UPD: I've partually fixed it but now you can get out from the corners. How do I fix this? Don't suggest intersection, it doesn't work right (when colliding the wall from left/right, it sends you up and down)

```
    private void OnCollision(BoundsCollider sender, BoundsCollider collider)
    {
        if (sender.Rect.Center.X > collider.Rect.Center.X) // right
        {
            sender.GameObject.Transform.Position += new Vector2(1, 0);
            if (GameObject.IsAI)
            {
                if (collider.GameObject != null)
                {
                    Velocity = new Vector2(-collider.GameObject.Rigidbody.Velocity.X, Velocity.Y);
                }
                else
                {
                    Velocity = new Vector2(-Velocity.X, Velocity.Y);
                }
                AngularVelocity = 0.01f;
            }
            else
            {
                Velocity = new Vector2(-Velocity.X, Velocity.Y);
            }
        }
        else if (sender.Rect.Center.X < collider.Rect.Center.X) // left
        {
            sender.GameObject.Transform.Position += new Vector2(-1, 0);
            if (GameObject.IsAI)
            {
                if (collider.GameObject != null)
                {
                    Velocity = new Vector2(-collider.GameObject.Rigidbody.Velocity.X, Velocity.Y);
                }
                else
                {
                    Velocity = new Vector2(-Velocity.X, Velocity.Y);
                }
                AngularVelocity = -0.01f;
            }
            else
            {
                Velocity = new Vector2(-Velocity.X, Velocity.Y);
            }
        }
        if (sender.Rect.Center.Y > collider.Rect.Center.Y) // bottom
        {
            sender.GameObject.Transform.Position += new Vector2(0, 1);
            if (GameObject.IsAI)
            {
                if (collider.GameObject != null)
                {
                    Velocity = new Vector2(Velocity.X, -collider.GameObject.Rigidbody.Velocity.Y);
                }
                else
                {
                    Velocity = new Vector2(Velocity.X, -Velocity.Y);
                }
            }
            else
            {
                Velocity = new Vector2(Velocity.X, -Velocity.Y);
            }
        }
        else if (sender.Rect.Center.Y < collider.Rect.Center.Y) // top
        {
            sender.GameObject.Transform.Position += new Vector2(0, -1);
            if (GameObject.IsAI)
            {
                if (collider.GameObject != null)
                {
                    Velocity = new Vector2(Velocity.X, -collider.GameObject.Rigidbody.Velocity.Y);
                }
                else
                {
                    Velocity = new Vector2(Velocity.X, -Velocity.Y);
                }
            }
            else
            {
                Velocity = new Vector2(Velocity.X, -Velocity.Y);
            }
        }
    }

```

# Answer
I made a solution to precisely detect on which side the object was hit. The previous solution was firing both top and right if object was hit from right and in the upper half.

I use sub-rects from top, bottom, left and right. Then the object is pushed back by width/height intersection between the object's sub-rect and collider's main rect.

But the problem is left and right still work wrong. After a bit of testing various cases (I'd create two 10x10 RectangleFs, one of them is at (0;0) while another one is at (5;0) and write in the VS debug output console. It wrote `{X: 0, Y: 0, Width: 0, Height: 10`! The width is 0 when it supposed to be 5! It was clearly a Monogame.Extended bug. I've reported it: https://github.com/craftworkgames/MonoGame.Extended/issues/414
> -1 votes

---
Tags: monogame, collision-resolution
---


# Question
Title: Trigger an action only once when a condition is met, not every frame after that
I want to avoid check if a particular function is returning true, and perform an action (Set Active) once it does return true for the first time.

Currently my code looks like this:

```
Update() {
    if ( IsTaskCompleted() ) {
        object.SetActive( true );
    }
}

```

SetActive gets called every frame after the task is completed. How can I avoid this, and call SetActive only once?

# Answer
> 4 votes
Create a flag which says if there is a pending task:

```
class TaskListener : MonoBehaviour {

    private bool taskIsRunning = false; // set to true when you start the task

    Update(){

        if (taskIsRunning && IsTaskCompleted()){
           taskIsRunning = false;
           gameObject.SetActive(true);
        }

    }

    //...

```

Another option is to make the task itself aware of which objects need to be activated when it's finished and make that a part of the task.

When the task can't know which objects it needs to notify at its end, you could also use an Unity Broadcast Message to call a specific method on every script which has it in a specific branch of your scene tree. But keep in mind that this isn't very fast, especially when you have a large branch.

Or you could use the Unity Event System. Have the task trigger a custom event when it's finished and have each script which is supposed to react on that event implement a custom event handler interface.

# Answer
> 3 votes
If you don't want to use events, this is pretty simple to solve with a coroutine (a function that can span multiple frames). You just add your "cleanup" code at the end of the function. Just make sure to call the function using "StartCoroutine()" instead of a standard function call.

```
IEnumerator MyTask(){
    //Do task here
    //You may need a different kind of yield return depending on the type of task.
    yield return null;
    //Cleanup code goes here
    object.SetActive(true);
}

```

This way you're avoiding a (usually) useless conditional statement in Update. here's the unity doc for coroutines for further reading.

https://docs.unity3d.com/Manual/Coroutines.html

---
Tags: unity
---


title: Snake movement in monogame

text:
# Question
Title: Snake movement in monogame
Noobie here... I've started learning monogame development and currently working on a simple snake game. I'm having trouble with the snake's movement, I figured I could make it tile-based movement but eventually decided to create turning points everytime the head changes direction, insert those into a list and remove a point when the last body unit have passed through it.

The method that gets keyboard input and creates the turning points:

```
 protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();
        player.update();
        if (Keyboard.GetState().IsKeyDown(Keys.Up) || Keyboard.GetState().IsKeyDown(Keys.Down))
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Up))
                player.direction.Y = -3f;
            else
                player.direction.Y = 3f;
            player.direction.X = 0;
            /**
             * Creating a turnPoint that will save the change in movement
             * and where it occured.
             * **/
            player.turnPoint.Add(new Player.turningPoint(player.position, player.direction));
            return;
        }
        if (Keyboard.GetState().IsKeyDown(Keys.Left) || Keyboard.GetState().IsKeyDown(Keys.Right))
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Left))
                player.direction.X = -3f;
            else
                player.direction.X = 3f;
            player.direction.Y = 0;

            player.turnPoint.Add(new Player.turningPoint(player.position, player.direction));
        }

        base.Update(gameTime);
    }

```

GameObject which is used as the snake's tail basically consists of 2 Vectors, one for position, the other for movement direction.

```
 public struct turningPoint // Used to save the point and specific change in movement
    {
        public Vector2 location { get; }
        public Vector2 velocityChange { get; }

        public turningPoint(Vector2 location, Vector2 velocityChange)
        {
            this.location = location;
            this.velocityChange = velocityChange;
        }
    }
    public List<turningPoint> turnPoint = new List<turningPoint>();
    private List<GameObject> bodyUnits = new List<GameObject>();

```

And finally, the method in whic I update the body units:

```
        private void updateBodyUnits()
    {
        for(int i = 0; i < bodyUnits.Count; i++)
        {
            //Update the unit's position using it's current movement direction
            bodyUnits[i].position.X += bodyUnits[i].direction.X;
            bodyUnits[i].position.Y += bodyUnits[i].direction.Y;

            foreach(turningPoint point in turnPoint)
            {
                if(bodyUnits[i].position.X == point.location.X && bodyUnits[i].position.Y == point.location.Y)
                {   //If the unit is currently on a specific turning point, change it's direction
                    bodyUnits[i].direction.X = point.velocityChange.X;
                    bodyUnits[i].direction.Y = point.velocityChange.Y;

                    if (i == bodyUnits.Count - 1) //Remove turn point if the last
                                                  //unit passed through
                        turnPoint.Remove(point);
                    break;
                }
            }
        }
    }

```

Basically it kinda works, if the movement the snake is low. If I set direction. X\Y to 1, or 2 even it kinda works, but above that it seems as if the units just speed through the turning point, ignoring it (and currently there just the head with 3 units of tail). So, is my code ridiculously inefficient? Or the method I am using is wrong altogether?

# Answer
The problem is using equality with floats.

```
if(bodyUnits[i].position.X == point.location.X &&
   bodyUnits[i].position.Y == point.location.Y)

```

While your turning point might be at

`x:1.43, y:5.23`

Your body unit might be at

`x:1.430000001, y:5.23`

Those are not equal, therefore, the point will not be triggered. Using your current strategy, you can alter your code to instead look for something that's close enough. Like defining the maximum tolerance like so:

```
float maxDelta = .01f;

if(Math.Abs(bodyUnits[i].position.X - point.location.X) < maxDelta &&
   Math.Abs(bodyUnits[i].position.Y - point.location.Y) < maxDelta)

```
> 1 votes

# Answer
Why use turning points? It's much easier to use a queue based approach to this instead. Like this:

```
#include "lib/renderer.h";

void main() {
    int head_x=0;
    int head_y=0;
    int dir_x=1;
    int dir_y=0;
    struct segmentList segments;
    bool running=true;
    while (running == true) {
        head_x+=dir_x;
        head_y+=dir_y;
        segments.push([head_x,head_y]);
        segments.remove(0);
        for (int i=0;i<segments.length;i++) {
          render(segments.get(i));
        }
    }
}

```
> 0 votes

---
Tags: c#, monogame, snake
---


# Question
Title: OpenGL: Frame partially jumps back and forth
I'm working on a project with SDL and OpenGL. The game works great on Windows, Linux, OS X and iOS. However, the Android version is showing a problem on my phone in particular. I have tested another device and there it works great as well.

The problem I'm facing is a visual glitch. It happens in bursts: for example: 90 frames okay and then 40 frames the glitch. The glitch itself is kind of hard to describe but I'll try. The screen is being updated partially correct (from the top of my phone to approximately halfway down) and partially flickering. The flickering effect is some sort of back and forth jumping. I'm thinking that it is related to double buffering. I think that because what I get to see on the screen is jumping back and forth every frame. It is like half of the screen is one frame in time and the next frame 2 frames late. Pretty much like a procession of Echternach, I guess you could say. If I plot it in a chart where time goes on when moving down the chart, I think I'm seeing this (numbers in the table are the indices of the frames in my game loop I am actually seeing):

```
          left half | right half  (phone is in landscape)
         ------------------------
time  1 |      1           1
time  2 |      2           2
time  3 |      3           1
time  4 |      4           4
time  5 |      5           3
time  6 |      6           6
time  7 |      7           5
time  8 |      8           8
time  9 |      9           7

```

So the right half is one frame in time, and the next frame, it shows the previous frame. This is supports my theory that there is a problem with double buffering. It looks like it somehow doesn't get to completely update the backbuffer before it is put on the screen, or something.

Also, the split between good and glitch on the screen is different from frame to frame, which points I think proves it is a synchronisation issue and heavily depends on timing of what is going on. Adding `glFinish();` before the `SDL_GL_SwapWindow();` call doesn't help.

*Version info:* SDL reports vsync to be turned on. However, I believe that this isn't tearing. My phone a Samsung Galaxy S3 mini and is running Android 5.1.1 (CM12) and the GPU (Mali-400) supports OpenGL ES 2.0. Other games run okay on my phone.

# Answer
> 0 votes
A section of the readme talks about it:

> **A note regarding the use of the "dirty rectangles" rendering technique**
>
> \[...\] where you only update a portion of the screen on each frame, you may notice a variety of visual glitches on Android, that are not present on other platforms. This is caused by SDL's use of EGL as the support system to handle OpenGL ES/ES2 contexts, in particular the use of the eglSwapBuffers function. As stated in the documentation for the function "The contents of ancillary buffers are always undefined after calling eglSwapBuffers".
>
> Setting the EGL\_SWAP\_BEHAVIOR attribute of the surface to EGL\_BUFFER\_PRESERVED is not possible for SDL as it requires EGL 1.4, available only on the API level, so the only workaround available on this platform is to redraw the entire screen each frame.

---
Tags: opengl, android, opengl-es, sdl, gpu
---


# Question
Title: Is it legal to use elements of the outfit of a character in another game as an optional cosmetic in my own game?
In my game, I plan on implementing various optional unlockable costumes, earned by collecting in-game items. One hypothetical example of such a costume would be Banjo's (from Banjo-Kazooie) shorts, backpack, and shark-tooth necklace. In trying to find the answer to this, I've found plenty of information about directly using Banjo himself (clearly illegal without a license), but I haven't found any form of direct answer when it comes to his outfit placed onto the main character.

The closest thing I've found to an answer are similar cosmetics being used in other games -- In TF2, for example, there's a hat that references Mario's hat, but replaces the M with an E, while in Terraria, there's a direct recreation of Mario's entire outfit. Obviously, though, just because another company was able to do such a thing doesn't mean I necessarily will be able to as well.

Lastly, I'm not sure if it makes much of a difference, but it's also worth mentioning that the art assets used for these costumes would be entirely created by me in the image/likeness of the other characters' outfits -- obviously, ripping said assets from the games themselves would NOT be legal. Also, I do plan on selling the game and making a profit on it.

Would creating these homage outfits be legal, or would it violate the copyright and/or trademark (not sure which applies) of the character?

# Answer
IANAL, get one, but....

If you don't mention, that it's the short/backpack/necklace from Banjo Kazooie, then there's little to no chance that Microsoft could dedend them.

If you search for "yellow shorts", "blue backpack" or simply "sharktooth necklace", then I can guarantee you you'll find very similar clothes. And you can't trademark or copyright everyday objects.

You mentioned Terraria. It also has the "hero outfit" which is basically Link's costume and the "plumber's costume" which is mario's outfit. So you can make the chance even lower if you name the costume "a bear's costume" or something similar

It's important to mention, that the mobile port of Terrarian changed most references (e.g. the Hero outfit became purple) to avoid any potential lawsuit just in case.
> 1 votes

---
Tags: legal
---


# Question
Title: My attempt at a drunkard walk algorithm seems to generate large groups instead of more linear paths
...and I'm not sure if that's normal due to the random nature of the algorithm or am I doing something wrong. What I'm doing is:

* Set a random point within map boundaries (which I called a sandbox).
* Pick a random direction
* Check if a tile at that position is not outside of map boundaries or already occupied.
* If it is a valid tile to move to then move to it
* If it isn't then pick a new random direction
* If after 4 random direction picks it's still invalid then move back one step (to avoid boxing in and doing an infinite loop)

Here's the result and the code will be posted at the bottom:

```
initial point hr.mlovrekov.castlegame.util.Point(0, 4)
moving RIGHT
moved to point hr.mlovrekov.castlegame.util.Point(1, 4)
moving BOTTOM
moved to point hr.mlovrekov.castlegame.util.Point(1, 5)
moving LEFT
moved to point hr.mlovrekov.castlegame.util.Point(0, 5)
moving BOTTOM
moved to point hr.mlovrekov.castlegame.util.Point(0, 6)
moving RIGHT
moved to point hr.mlovrekov.castlegame.util.Point(1, 6)
moving BOTTOM
moved to point hr.mlovrekov.castlegame.util.Point(1, 7)
moving LEFT
moved to point hr.mlovrekov.castlegame.util.Point(0, 7)
attempts over 4 moving back
moved back to hr.mlovrekov.castlegame.util.Point(1, 7)
moving RIGHT
moved to point hr.mlovrekov.castlegame.util.Point(2, 7)
moving TOP
moved to point hr.mlovrekov.castlegame.util.Point(2, 6)
moving RIGHT
moved to point hr.mlovrekov.castlegame.util.Point(3, 6)
moving TOP
moved to point hr.mlovrekov.castlegame.util.Point(3, 5)
moving RIGHT
moved to point hr.mlovrekov.castlegame.util.Point(4, 5)
moving BOTTOM
moved to point hr.mlovrekov.castlegame.util.Point(4, 6)
moving BOTTOM
moved to point hr.mlovrekov.castlegame.util.Point(4, 7)
moving LEFT
moved to point hr.mlovrekov.castlegame.util.Point(3, 7)
attempts over 4 moving back
moved back to hr.mlovrekov.castlegame.util.Point(4, 7)
moving RIGHT
moved to point hr.mlovrekov.castlegame.util.Point(5, 7)
moving TOP
moved to point hr.mlovrekov.castlegame.util.Point(5, 6)
moving RIGHT
moved to point hr.mlovrekov.castlegame.util.Point(6, 6)
moving TOP
moved to point hr.mlovrekov.castlegame.util.Point(6, 5)
moving LEFT
moved to point hr.mlovrekov.castlegame.util.Point(5, 5)

```

Final result for a sandbox of size `[8][8]`

```
false   false   false   false   false   false   false   false
false   false   false   false   false   false   false   false
false   false   false   false   false   false   false   false
false   false   false   false   false   false   false   false
true    true    false   false   false   false   false   false
true    true    false   true    true    true    true    false
true    true    true    true    true    true    true    false
true    true    true    true    true    true    false   false

```

As you can see lower quadrants seems to be the most truthy while upper quadrants are not visited at all. Is there a way I could implement some sort of guided randomness wherein every quadrant would be visited at least twice but still have them all connected?

As promised, here's my code:

```
private void constructMapPath(Random random) {
    def point = new Point(random.nextInt(SANDBOX_WIDTH), random.nextInt(SANDBOX_HEIGHT))

    def stepsMade = new ArrayList<Point>(STEPS)

    println "initial point $point"
    sandbox[point.@y][point.@x] = true

    stepsMade << new Point(point)

    Direction direction

    //point used for checking if a new position is valid
    //initialized here so that a new point isn't initialized each time a validation is performed
    def validationPoint = new Point(point)

    int attempts
    for (int step = 0; step < STEPS; ++step) {
        attempts = 0
        while (!isValidDirection((direction = Direction.randomDirection(random)), point, validationPoint)) {
            if (attempts++ > MAX_ATTEMPTS) {
                println "attempts over $MAX_ATTEMPTS moving back"
                moveBack(stepsMade, point)
                println "moved back to $point"
                attempts = 0
            }
        }

        println "moving ${direction.name()}"
        move(direction, point)
        sandbox[point.@y][point.@x] = true
        println "moved to point $point"
        stepsMade << new Point(point)
    }

}

static void moveBack(List<Point> stepsMade, Point point, int steps = 1) {
    Point previousStep = stepsMade[-1 - steps]
    point.@x = previousStep.@x
    point.@y = previousStep.@y
}

private boolean isValidDirection(Direction direction, Point point, Point validationPoint, int steps = 1) {
    validationPoint.@x = point.@x
    validationPoint.@y = point.@y
    move(direction, validationPoint, steps)
    return validationPoint.@x >= 0 && validationPoint.@x <= SANDBOX_WIDTH - 1 && validationPoint.@y >= 0 && validationPoint.@y <= SANDBOX_HEIGHT - 1 && !sandbox[validationPoint.@y][validationPoint.@x]
}

static void move(Direction direction, Point point, int steps = 1) {
    switch (direction) {
        case Direction.TOP:
            point.y -= steps
            break
        case Direction.BOTTOM:
            point.y += steps
            break
        case Direction.LEFT:
            point.x -= steps
            break
        case Direction.RIGHT:
            point.x += steps
            break
    }
}

private static enum Direction {
    TOP,
    BOTTOM,
    RIGHT,
    LEFT

    private static final Direction[] VALUES = values()
    private static final int SIZE = VALUES.size()

    static Direction randomDirection(Random random) {
        return VALUES[random.nextInt(SIZE)]
    }
}

```

# Answer
> 1 votes
One common approach to generating more corridors than open spaces is to store the direction that you took in the last step and bias your random direction choice so that it's more likely to choose to continue on in that direction.

In your code, you could just have the randomDirection method generate a number up to SIZE + n and return a stored lastDirection member variable if the value \>= SIZE.

# Answer
> 0 votes
The algorithm you stated sounds a lot more like that of a recursive back-tracker maze generator. For the drunkard walk algorithm I believe you can move to the next cell regardless of whether it is occupied or not. As for the generation of large groups, a way to go would be to bias the next direction by the previous direction as stated by 4026.

You can look here for more information:

---
Tags: algorithm, procedural-generation, random
---


# Question
Title: Filter game data according to player unlocks
I'm currently developing an online "empire management" style game in HTML and Node. Along the game, the player will be able to raise resources (by creating farms, mines, raiding) to unlock new structures and rare items, etc. The same old drill.

All game data is in a server-side file which gets called and processed before sending to the player.

Now, when I serve the game data (containing information on building costs, paths to all imagery, etc) over to the client, I took a good care to filter it accordingly to the player's unlocked features (so to avoid people fiddling in the client-side code and getting access to the whole game data). I didn't really think about it when I made this, it just seemed "natural" to hide locked content. But now it is becoming a bit hard to keep data synced when the player starts to unlock stuff. I just regret this a bit and I'm starting to think it's not worth the hassle.

Now some questions arose in my mind: what is the usual approach to this? Do this kind of games usually send everything (which increases sightly bandwidth usage) or pre-process like I did (which increases server load)? Would it hurt the game experience somehow, especially considering many games have their own wikis nowadays?

(note that this is more of a concept question rather than technical)

# Answer
> 1 votes
It's likely not worth the hassle.

With a HTML+Javascript application, most of that data on the client will live in memory. Accessing it requires some serious fiddling with the debugger. Most players won't be able to do this. Those who are able to do this will just look it up on a wiki. The only information you must really hide from the client-side is any information which gives an **unfair** advantage **in multiplayer** if known (like enemy positions the player isn't supposed to know). Not because it would hurt their own gameplay (that would be their own fault), but because it would hurt the gameplay of other players.

Hiding locked content in the UI is mostly for the convenience of the player. It prevents them from getting distracted and confused while they are still learning the game. Another reason is giving the player a feeling of exploration. But anyone who takes the step of looking at the game code with a debugger has decided that they are not interested in the intended exploration experience and have chosen to pursue a completely different kind of exploration.

Regarding the bandwidth argument: How much data are we *really* talking about? Do the mere numbers and strings for each unlocked piece of content even exceed one kB? Images and audio, however, are a different story. When they are relatively large then it can make sense to only load these on demand. Not just because it saves you a bit of bandwidth but also because it reduces the initial loading time of your game. On the other hand, preloading everything can improve the experience during play. This is a tradeoff specific to the unique experience of each game.

# Answer
> 1 votes
I agree with Phillip that most of the time, people messing with the code is only going to hurt their own experience. He mentioned multiplayer as an exception to this, but I would also add in-game purchases (like with real money, not game currency), but it doesn't sound like you are going in that direction. A third way it might affect others is if you have some difficult-to-get unlock-able content that you want the player community to struggle to discover some time after the initial release of the game. Most games don't even bother trying to hide things like that, with maybe the exception of some MMORPGs.

Even if those things don't concern you, your current approach still has its benefits. Since the game is designed to run in a browser, your target players would get impatient in the case of a long initial download. Console and standalone PC games can get away with having the player download everything at once because they only need to do it *once*. With web development, though, you need to assume that everything goes away when you close your browser. Sure, the game could be cached, but you can't count on that.

On the other hand, it would get annoying having to wait a couple seconds between when you unlock something and when it is actually download it. It can definitely get messy on the programming side, since certain gameplay cannot happen until a download completes, and you don't know exactly when or if the download will happen.

### Manage downloads by predicting unlocks.

To keep downloads from getting in the way of the game, you can predict what content will be unlocked next, and then begin the download before it is ever unlocked. It sounds messy, but it doesn't have to be. Just do the following:

1. Start the game with an initial list of unlockables. Since this list is only the names, or even just the IDs of them, it won't slow things down significantly at the start.
2. Each unlockable is assigned an initial state of "not downloaded" and "locked."
3. As soon as the game launches, the thing most likely to be unlocked first (probably the first thing on the list) begins to download in the background.
4. The thing will almost definitely download before it is unlocked. Set the status of the thing to "downloaded"
5. When the player actually *does* unlock the thing, set the status to "unlocked." Since it has a status of both "unlocked" and "downloaded," it is allowed to appear in the game menus. At this time, trigger the download of the thing most likely to be unlocked next, and repeat steps 4 and 5.

In the case that the player is really fast, or the download is really slow, you will, of course, need to block access to it from the menus until it is also downloaded. Depending on how you want the game to play out, you might only trigger the message that it is unlocked once it is both downloaded *and* unlocked. If this would not work well for the game, you may need to stall it with an error, but assuming that the player has an active Internet connection, this should be a rare case. If the player is not online, there's not really much you can do.

---
Tags: architecture, client-server
---


# Question
Title: Spreading server load for a multiplayer game
My online game is more of a "highly interactive website", as it is played in-browser using webpages and AJAX to communicate with the server, which uses PHP to generate output.

The server is fairly standard, using PHP7, MariaDB, and Memcached (to avoid constantly reloading data from the DB, cache hit rate is about 95%).

All of this works. Fairly well, at that, and it can comfortably handle about 1,000 users actively hammering at the core gameplay element. The problem is that it's not scalable. The only scaling strategy we've had so far is "throw stronger hardware at it", which again works but it's not sustainable.

I want to look into options for spreading the load over multiple servers, but it's daunting.

Most of the game involves manipulating your own characters, and then visiting other player profiles to "interact" with their characters (which awards EXP and bonuses to both parties). There is also trading between players.

Of course if this were just a regular website then I could probably just replicate everything and stick a load-balancer in front of it, but I'm not sure that'll really work here.

I think the most sensible option would be some system of assigning users to a specific server. When you log in a cookie is set to indicate which server you're on, which the load balancer can use to direct your actions to the server your data is on. When visiting another player's profile, the server will request that data from the other player's server. Things like trading will also be handled by having "player one" send a request to their server, which will communicate with "player two"'s server to move data around and complete the action.

Is this realistic? Or am I overthinking it? Are there other options? Ideas?

# Answer
This is one of those questions where there are so many options that it's hard to pick the one right answer without doing some serious "try it and see" work.

**TL;DR**

* Your solution is a solid option, that gives you control and will probably scale indefinitely, at the cost of some on-going management effort.
* I'd suggest (if you haven't already) you separate your database and PHP layers to see if simply adding load balanced PHP servers connecting to the single Database engine will solve your problems in the short term.

The first thing I'd do, and you may already have done this, is separate the PHP and the MariaDB, possibly only as a trial. This way, when you start hitting performance issues at around 1000 users, you can tell whether it's the database bit or the php bit that's having the issues.

If you do this, and the database server is unruffled, but the PHP server is sweating bricks, then you can use a simple load balancer, with sticky sessions. Sticky sessions means that all requests from the same browser would go to the same PHP server, meaning you can use sessions, and the caching works all good.

That's a great solution, because you can add more PHP servers to the load balancer until your database server starts to struggle. It also means you can use your load balancer to manage downtime/ upgrades etc.

If it's the database component that's struggling, the options get trickier.

With your suggestion, you're adding a chunk of code, and a chunk of management effort. But it will probably work, and if each server has it's own database, it will probably scale indefinitely.

It's also one of the more "available" solutions in that it doesn't need a great deal of specialist knowledge.

You'll need to have a way to keep track of which server the other player's profiles are on. Player A will have a cookie that says Player A's data is on Server 1, but it probably won't have a cookie that will tell it where Player Z's profile is. To do this you might have a dedicated "keep track of profiles" server, which all it does is answer queries about where to find a profile. This is another chunk of management effort.

Your suggestion is quite attractive because it eliminates the question of database replication lag (and expertise to set it up).

One of the major alternative strategies is duplicating the database load across several servers, either via replication or one of the NoSQL Database engines. This lets you spread the database load across several devices keep the whole data set available in one place. But it comes with considerable configuration complexity, and in some situations a degree of lag - it might take a second or two (or more) for updates on Server 1 to be copied to Server 2.

If you go to a NoSQL database, these are generally designed to be very highly scalable, at little effort. But it would probably mean rewriting your app, which sounds like regretful effort. And you also have the "eventually consistent" issue. Basically, the scaling out to multiple nodes is easy to do, but the data updates are not available between the servers immediately, and that could be an issue.

The replication option would work with MariaDB. This would allow you to have a copy of all of the data on each server, but add more nodes as load requires. Configuring replication like this is tricky.

Another option which you might want to consider is to stick all or part of it on the cloud. If your database can be separated from your app server, you could go with AWS's MySQL compatible RDS service. This will cost, but it also allows you to scale your database performance in ways that is hard to do with your own physical hardware. You'd want to look hard at the cost implications, but the AWS stuff is real clever, and real easy to work with (and the backups and failovers just work!!).
> 1 votes

---
Tags: server, online
---


# Question
Title: How can I calculate respective 2D world/mouse position through different resolutions?
I have been at this game of trial-and-error for days now. I cannot find a consistent method to calculate the respective mouse position in my game world after the calculations are done to stretch the game's render view to the current resolution. I've seen other, similar questions and answers on this site, but after looking at them long and hard, I can't translate the answers to my project.

I'm using XNA. First, I render everything to a RenderTarget2D at a resolution of 800x600. Then I render said RenderTarget to the screen by calculating it's size and location through a method that returns a Rectangle:

```
public Rectangle CalculateRenderTargetPosition()
    {
        Rectangle rec;
        Single preferredAspect = Globals.RenderSize.Width / (Single)Globals.RenderSize.Height;
        Single outputAspect = Globals.WindowSize.Width / (Single)Globals.WindowSize.Height;
        if (outputAspect <= preferredAspect)
        {
            // output is taller than it is wider, bars on top/bottom
            Int32 presentHeight = (Int32)((Globals.WindowSize.Width / preferredAspect) + 0.5f);
            Int32 barHeight = (Globals.WindowSize.Height - presentHeight) / 2;
            rec = new Rectangle(0, barHeight, Globals.WindowSize.Width, presentHeight);
        }
        else
        {
            // output is wider than it is tall, bars left/right
            Int32 presentWidth = (Int32)((Globals.WindowSize.Height * preferredAspect) + 0.5f);
            Int32 barWidth = (Globals.WindowSize.Width - presentWidth) / 2;
            rec = new Rectangle(barWidth, 0, presentWidth, Globals.WindowSize.Height);
        }
        return rec;
    }

```

The Camera's position is rendered during rendering to the RenderTarget2D through a Matrix in the SpriteBatch.Draw method, so there's nothing weird going on there. The Camera itself works fine at any resolution.

After days of guesswork, this is the closest method I've got:

```
Rectangle r = Globals.Draw.CalculateRenderTargetPosition();
MouseState ms = Mouse.GetState();

Single aspect = Globals.WindowSize.Width / (Single)Globals.WindowSize.Height;
Single pmx = (ms.X - r.X);
Single pmy = (ms.Y - r.Y);
Single mx = (pmx == 0 ? pmx : pmx / aspect);
Single my = (pmy == 0 ? pmy : pmy / aspect);
Vector2 pos = Vector2.Transform(new Vector2(mx, my),
    Matrix.Invert(Globals.Camera.GetViewMatrix()));
Globals.RelativeMousePosition = new Vector2(pos.X, pos.Y);

```

Even if this is almost close enough, it's still off. I don't know if there's some magical Matrix method I don't know about or if I just suck at math.

# Answer
Well, after even more searching, tinkering, guessing, repeat, I've *mostly* (not 100% perfect but close enough to work with) got the mouse translation working.

```
Rectangle r = Globals.Draw.CalculateRenderTargetPosition();
MouseState ms = Mouse.GetState();
Matrix cam = Globals.Camera.GetViewMatrix();

Single aspect = Globals.WindowSize.Width / (Single)Globals.WindowSize.Height;
Vector2 pos = Vector2.Transform(new Vector2(
        Extra.SafeDivision((ms.X - r.X), aspect) * Extra.SafeDivision(1, Globals.Camera.Zoom),
        Extra.SafeDivision((ms.Y - r.Y), aspect) * Extra.SafeDivision(1, Globals.Camera.Zoom)),
    Matrix.Invert(cam));
this.Position = new Vector2((Single)Math.Round(pos.X), (Single)Math.Round(pos.Y));

```

This isn't flawless, it's still off, but only a little bit, the code thinks the mouse is actually a few more pixels ahead of the real cursor's X/Y positions. But I decided to just hide the real cursor and render an in-game one, works fine and you can't even tell the difference. I'm not going to mark this as solved, because it's wrong, but it's still a close-enough answer.
> 1 votes

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


# Question
Title: Collision detection with isometric tiles stored in rectangular files
So I'm working with a player moving across a grid of isometric tiles. Each tile is stored in a .png file. I have a class that crops out BufferedImages from different sprite sheets and initializes them for use in my game. When I crop out a tile image, the image is cropped out like this (minus the black border):

Because the four corners of this rectangle are transparent, I'm able to tessellate the tiles perfectly. I'm now trying to implement collision detection and having a tough time. The player moves by following the mouse around. In the player's tick/update method, I am checking to see if his new position will be in a tile marked as being solid. If the tile is solid, I don't update his position so that movement doesn't occur. My problem is that when I check to see if the player is moving into a solid tile, I'm checking the entire .png image, including the transparent corners.

So, if I'm moving towards these 'stone' tiles and I mark them as being solid, the player isn't colliding with the tiles in a natural way.

In the image you see here, I've updated these stone tiles with a black border showing the edge of the BufferedImage, and I've updated my player with a red rectangle indicating his bounding box. I've marked these tiles as solid. As I approach the tiles from the left moving right, I collide with these black lines rather than the colored portion of the tile. Actually, sometimes I collide with nothing to the left of the tile, like in this image (I'm sure that's just my math somewhere.)

I considered trying to attach a Polygon object to each solid tile that covers only the visible pixels of each .png file and doing collision against the polygon instead of the whole tile. I'm currently trying to implement this and having troubles.

My question here then is, **how would you implement collision detection in this scenario?** Would you draw polygons in the shape of the visible portion of each BufferedImage and do collision against these polygons like this? Is there a change that I can make or a technique I can use to implement smooth collision detection? Should I use a polygon object to crop my tiles in the first place? I'm looking for the simplest way to go about this.

# Answer
In my opinion, the best way to do this would be "convert" map into simple 2D topdown plane, then check the collision with more simple figure.

So you've got Screen World, which is drawn with tiles and stuff, but also your world's Computer Representation, just a 2D grid\matrix\array or anything. You can easily find different approaches of translating world coordinates into screen coordinates and vice-versa.

**Use plain 2D world for collsion and use isometric tiles for drawing the world onto the screen.**
> -1 votes

---
Tags: java, collision-detection, sprites, tiles, rpg
---


title: Licensing (or similar) for my fan-game?

text:
# Question
Title: Licensing (or similar) for my fan-game?
For the past 8 years, I've been working on a Pokémon fan-game. It's been awesome, well-received by players, and I'm very proud of the community we've built. But, as with all things "fan-game", there's always that looming grey cloud of "will a C&D arrive tomorrow?"

Now, I've taken some steps to ensure we're as respectful as possible towards Nintendo's property:

* We stay as true as possible to the source material. While we have added our own variants and original characters ("Fakemon"), we've made great efforts to keep them consistent.
* We make it clear that we are a fan-game, not affiliated with Nintendo, and that it is entirely unofficial. I also include a link to a shareholder Q&A (Q14) where Satoru Iwata confirmed that they are not interested in treating people like myself as criminals.
* Our game concept is original. It's not a clone of any existing game, and I like to think it fills a nice little hole for fans of the series.
* I (briefly) met C-level people from Game Freak and Nintendo, including Junichi Masuda and Tsunekazu Ishihara, and given them "business cards" for our game. However, it wasn't a formal meeting, rather they were signing autographs at the Pokémon World Championships, so for all I know I was probably just some fan and they didn't pay much attention to the card (they've got enough to do already, right?)

But, all that being said, we're still unofficial, using intellectual property that doesn't belong to us.

My friend and I quit our jobs to work on this game full-time. If we do get shut down, we're going to have to seriously struggle to put our lives back together. So for now, the game has mostly been kept "under the radar", with basically zero marketing and only word-of-mouth of players to keep it populated.

The biggest thing here is that I *want* to give back to Nintendo. Thanks to them, and to my project, I've made incredible progress as a developer, designer and just as a person in general.

As mentioned earlier, my biggest fear is that one day they'll shut us down. And we'd have no choice but to do so. But it's been 8 years now...

So I'm trying to figure out what options I have, if any. I think what I want to do is to reach out and ask about some kind of licensing, but I don't want to draw too much attention. I don't want to lift my head over the parapet only to have it blasted off, you know? I'm not looking for Pokémon GO levels of attention, or even Magikarp Jump. (Our single server would melt either way - I'm working on it!) Just some way of having actual "permission" to do what I'm doing.

I expect the answer will probably be along the lines of "IANAL, get one", but what kind of lawyer would be best? And any insights or advice besides that would be helpful too.

# Answer
> 51 votes
> I don't want to draw too much attention. I don't want to lift my head over the parapet only to have it blasted off, you know?

Either you raise your head and get out, or you starve behind the parapet. If you want to make a living as a game developer, you must get as much exposure as you can. Your revenue is proportional to the number of people who know your game exists. As long as you keep living in fear of getting too big and attract the attention of Nintendo's legal department, your chances to succeed in this overcrowded market are minimal.

As their Pokémon Go collaboration with Niantic shows, Nintendo doesn't seem to be *completely* against working with other game developers anymore when it comes to their Pokémon IP (Intellectual Property). So if you have a good product, there is a slight chance to convince them. But personally, I wouldn't bet on it.

But even when it turns out that they don't want to collaborate with you, there is still hope for your product.

> •we have added our own variants and original characters ("Fakemon")
>
> •Our game concept is original. It's not a clone of any existing game, and I like to think it fills a nice little hole for fans of the series.

You have an original game concept and you are capable of creating original characters. This sounds like you don't actually *need* the Pokémon IP. My recommendation for you would be to get rid of all the content which is based on Nintendo IP, rebrand the game and build your own franchise.

Maybe soon *you* will be the one whose IP gets infringed by fangame creators.

A good example of a game which went down that road is Freedom Planet. It started out as a Sonic the Hedgehog fangame. But then they realized that they had a game with original characters and gameplay ideas which was perfectly capable of carrying itself without having to piggyback on the success of some other IP. I would argue that taking this step even improved their game, because it allowed them to do things with characters, setting and gameplay which would not have worked within the confines of the existing Sonic universe. It sold over 250,000 copies. They are currently developing the sequel.

# Answer
> 29 votes
So, yea "IANAL, get one".

However, it seems obvious from your question that your goal is to profit from this game. And the phrase "not interested in treating people like myself as criminals", has little bearing on civil penalties which is your main concern.

Use of a trade mark or IP opens you up to financial damages. And companies have to actively defend trade marks, so they must pursue C&D every time they find an infringement, or they may lose the rights to their property.

My suggestion would be to talk to an IP/Copyright lawyer, one specifically with game industry experience. And be prepared to start replacing all of your assets with original concepts and content.

Also, if you haven't yet, incorporate. Either as an LLC or corporation (dependent on your state), as a means of possibly protecting your personal assets.

It sounds like you're so far invested that you can't take the risk of not getting licensing. Now to be very blunt, if your game's success really hinges on the Pokemon name and content, then you should take a hard look at the game. Don't succumb to the sunk cost fallacy and keep trying to force it.

# Answer
> 12 votes
By the time you can make a living from your fan project, it isn't a fan project anymore.

Nintendo is **not** one of the (extremely few) Megacorporations that lets the community use their IP to make money. Link to Angry Joe being angry about unusually strict Nintendo IP policy.

Chances are, once they become aware of you, **they will go after the money you already earned** with this project in the past. Therefore approaching them to license your project may not be the best option, but it would have been a good option before you started to earn money.

Unless you live outside of the US or Japan, there's nothing you can do, other than pay a lawyer to tell you the same thing. If you do live outside of the US or Japan there's a chance you have some protections depending on where you live, where your servers are located, where the companies you work with (paypal? patreon?) are located. Ask a copyright lawyer what these protections are.

If you want to go forward with selling your game, I suggest you create version 2.0 without any Nintendo IP. In any case immediately stop relying on the money you make from IP you don't own, and start treating all the money already earned as something that can be taken away from you at any time (either directly, or through lawyer fees).

# Answer
> 11 votes
IANAL, get one

Specifically, you probably need an IP/Copyright lawyer.

From my fairly uninformed point of view (CS background, took some law courses in uni), I'd say that in your current state, Nintendo would certainly have no trouble shutting you down if they wanted to.

It sounds like your game is online, a la Pokemon Revolution Online or something (maybe it's actually that? idk). I don't know how much traction you have - if your peak online player count is something around or below 5000 they're probably not likely going to notice you for some time, but if you grow beyond 15k online players you may have some legal trouble ahead.

It's also worth noting - if they decide to go for you at some point, they *could* potentially take *everything* you own, depending on damages, etc.

You need to seriously consider at least these two things:

1. Incorporation - at least an LLC to limit liability, or else a bad lawsuit will mean you are literally homeless
2. Licensing - this will (of course) be very complex, but if you have any sort of high goals set for your game, you absolutely need some form of licensing and official acknowledgement from Nintendo.

# Answer
> 3 votes
Add me to the chorus of "You need a lawyer" but with an extra reason.

You are not a "fan game". You are a company with income sufficient to (I assume) cover your overheads and also pay enough wages to two staff to be their sole income. How many tens of thousands of dollars a year is that? When Nintendo find you, they will demand that you stop. If you don't close your game down (and quite possibly, even if you do) they will sue you into the dark ages.

Now, suppose you *do* shut your game down. Your income comes from your paying customers, with whom you have a contractual relationship to supply a service. You just stopped supplying that service. Now what? My guess is that the contract is legally unenforceable because you can't make a binding contract to do illegal stuff. But that doesn't mean they can't sue you: it just means they shouldn't win. You need a lawyer for this, too.

# Answer
> 2 votes
*This answer is based purely on common sense, I have no experience with Cease and Decist procedures.*

The surest way to get noted by Nintendo is to announce your product, which is essentially what you would be doing by asking them to license you.

Based on the number of legally licensed pokemon games that I have seen around, I would say the chance that they reject you is (much) closer to 1 than to 0.

Therefore I would focus more on risk mitigation, rather than licensing. Here are some things you could do:

1. Stop making the game (and stop making money from it)
2. Focus new development on makeing the game as much pokemon independent as possible, so you can switch to a 'normal' game as soon as it would be required
3. Set up additional companies to protect your assets, for instance one that is making money with pokemon, and one that holds the generic game and its IP.

# Answer
> 1 votes
I'd follow the good advice from others, and add a twist.

You know that saying, "trust in God and keep your powder dry"? Like that.

If it's reasonable to do so, separate the Nintendo specific stuff (character 3d model,, graphics and scenes clearly representing Nintendo's world, whatever - things they would have a good reason to *not* be agreeable on), from everything else (game engine and original content). Then run a Nintendo-verse version and a non-Nintendoverse version of the models and world, using the same engine.

Its a bit of extra work but it has a big payoff. Until the sh\* hits the fan (if it does), you'll have more to offer fans and you'll enrich your game, and benefit. If your game gets very popular you have a way to "test the water" with gradually channeling the fanbase and game to minimise the Nintendo stuff, without making a sudden huge change that will spoil it for people. You can present it as a bonus - choose original world or new world, 2 different games on the same framework, so until Nintendo get upset (if they do) you can offer both, so you don't have to force people to play one or the other, they're both "out there" and players can choose what they like between them.

Best of all, if one gets shut down, fans already have something to migrate to, you've already got the legally vulnerable stuff separated in the code so you don't have to go back 20 miles to sort it out, just keep them separate from now on in the codebase. So you can offer to take out the stuff they object to much easier, without losing your work, and you don't lose momentum because you've still got the engine, framework and World "B" going fine, so you can tell fans that out of respect for Nintendo, you've shut down world "A" and hope they'll like world B - and as fans tend to be understanding and many will like world B if its not rammed down their throats and not by your own choice, you'll probably have more support not less.

Most of all, peace of mind that even a C&D won't shut the thing and waste your time.

Concrete example in another universe - look what happened to a Windows utility called "Autopatcher". It let users install patches offline. Mixrosoft sent a C&D about including the patches. Outcome - they split the engine from the patch collection, and killed the built-in "bundled" patch collection by having it download the patches from Microsoft servers when run by the user, instead. Same outcome, fans happy, and Microsoft content that users were only getting patches from them, not from 3rd parties. Nintendo, if upset, will be fine if you remove the copyright imagery, and from your point of view that's easy to give them, this way.

---
Tags: legal, licensing
---


# Question
Title: Do game engines compile games or just interpret them
I know that many game engines like Unity3d use scripting languages like c# or java script but does that mean that a game engine is just an interpreter?

If so, does that mean that if I move the executable of a game made with Unity to the folder of another game made with the same engine then the game will run fine because all the engine is doing is interpreting the code?

If not does the engine just ship with a compiler and turns scripting code into compiled code?

# Answer
**For the case of Unity specifically**, C# and UnityScript code is compiled to what's called CIL, or Common Intermediate Language, a kind of "pre-digested" version of the code that's not quite machine code yet, but easy to translate that final step.

For desktop versions (Windows, Mac, and Linux), this intermediate representation can be stored directly in the built game as a .NET-style managed assembly. On Windows you'll see them as `.dll` files inside your game's `Data\Managed` folder.

When you run the game, this managed code is Just-In-Time Compiled (or "jitted") into actual machine code for your specific hardware. This is the usual flow for .NET applications on Windows, though Unity uses a cross-platform runtime called Mono to perform the same trick everywhere.

Some platforms don't allow runtime generation of code, either due to capabilities, permissions, or policy, so for these platforms Unity uses Ahead-of-Time compilation (AOT) to build executable machine code (or for WebGL, a low-level dialect of JavaScript called asm.js, via Emscripten).

**The ahead-of-time / just-in-time distinction doesn't make much of a difference for most things we do in games**.

Hypothetically, compiling just-in-time lets the game take advantage of features of the specific CPU that it's running on, without us needing to generate separate builds for every variation of chip out there, but this type of optimization is generally low-impact compared to, say, making good architecture and algorithm choices, like picking an efficient pathfinding strategy for our game AI.

There are some (questionable) tricks we can pull on platforms that can compile code at runtime which won't work on platforms where our machine code must be generated in advance. There are also some gotchas described here where we need to hint the ahead-of-time compiler to generate certain code that it can't automatically detect is needed.

See this forum post for another explanation, going into a bit more depth.

Unity also does a compilation-like process for all your non-script content, like textures/sprites, sounds, meshes, scene files, etc., turning them into a format that's more readily processed by the game at runtime. This is called data baking, and I explain a little about the reasons for it here.
> 2 votes

# Answer
Most game engine packages simply build/compile the code you write. But engines that let you use Lua for example are parsed and interpreted to the underlying system your engine is build with.

The game engine is at its core nothing more than a heap of libraries working together. You can still build scripting environment on top of you game, regardless of engine.

> If so, does that mean that if I move the executable of a game made with Unity to the folder of another game made with the same engine then the game will run fine because all the engine is doing is interpreting the code?

No. Unity builds an executable containing project specific compiled code.

> If not does the engine just ship with a compiler and turns scripting code into compiled code?

Scripting languages are bound to your source code. When you parse your script under the hood there are all sorts of calls made to your game. For example you can have a function to spawn enemies -\> in your implementation you expose this function to your scripting environment. Then when you call this function in your script after being parsed it actually calls the "native" function to spawn an enemy.

Here is a good answer.

How does Lua work as a scripting language in games?
> 0 votes

---
Tags: architecture, software-engineering
---


# Question
Title: How to handle keyboard controls in Arkanoid game
I'm making simple Arkanoid clone in Unity with both keyboard and mouse controls available. When I gave it to my colleagues to test one complain was that keyboard controls are not precise enough,. The problem is that I don't really know how to find a balance between two factors:

* If I make paddle speed too high then it lacks precision to position it just right to make ball go to the last few blocks.
* If I make paddle speed too slow then it's going to be difficult to reach ball in time.

I thought about it and I don't recall any version of arkanoid that solved that problem. Currently I have 3 ideas:

1. Make two (or more) keys to go in each direction. One will go faster and another slower.
2. Instead of making multiple buttons lets allow player to change speed of paddle during the game. Probably by entering number from 0-9 on keyboard.
3. Just leave it like it is now. Other control schemes are not intuitive enough.

Does anyone have any experience with this? Which approach is the most reasonable?

Edit: Code I'm using:

```
    Vector3 pz = transform.position;
    pz.y = y;
    pz.z = 0;
    if (Input.GetKey(KeyCode.LeftArrow)) {
        pz.x -= Time.deltaTime * KEYBOARD_SPEED_MULTIP;
    }
    if (Input.GetKey(KeyCode.RightArrow)) {
        pz.x += Time.deltaTime * KEYBOARD_SPEED_MULTIP;
    }
    pz.x = Mathf.Clamp(pz.x, -60, 60);
    rb.MovePosition(pz);

```

I simply move paddle by constant speed which includes timedelta. And then I clamp position to screen.

# Answer
> 1 votes
Since 2 people commented right answer, but none of them has posted response I'm going to respond to my own question.

Adding acceleration seems to be right option. Controls are still not that good as mouse, but I don't think that it can be made significantly better without mouse or touch screen.

I changed rigidbody type to dynamic and removed multiplier constant because I used mass instead. I also added additional code to clamp position and assure that paddle only has inertia when player is holding button.

Result code looks like this:

```
    if (Input.GetKey(KeyCode.LeftArrow)) {
        if (direction > 0) {
            rb.velocity = Vector2.zero;
        }
        rb.AddForce(new Vector2(-Time.deltaTime, 0), ForceMode2D.Force);
        direction = -1;
    }
    else if (Input.GetKey(KeyCode.RightArrow)) {
        if (direction < 0) {
            rb.velocity = Vector2.zero;
        }
        rb.AddForce(new Vector2(Time.deltaTime, 0), ForceMode2D.Force);
        direction = 1;
    }
    else
    {
        rb.velocity = Vector2.zero;
        direction = 0;
    }
    Vector3 pz = transform.position;
    if (Mathf.Abs(pz.x) > 60) {
        pz.x = Mathf.Clamp(pz.x, -60, 60);
        rb.MovePosition(pz);
    }

```

---
Tags: unity, 2d, keyboard, user-experience
---