# Question
Title: Rendering model with multiple tiling textures
See edit:

How would I go about rendering a model with multiple tiling textures? I have a few ideas, but all of them have drawbacks, here are a few (by the way this is for an opengl game):

-Use a huge texture, but this comes at the cost of the texture being expensive

-Render diffrent objects for each textured object (eg: one model could be bricks for a house, another could by the roof, each with their own tiled texture), but this would become very messy, very quickly.

Here is an (amazing) image to help demonstrate what I'm trying to do.

The repeating "R" on the red area represents perhaps a repeating brick texture, while the green one represents a roof, maybe roof shingles. To add on to that, I've added a window texture.

My question is, how do most games deal with this? I can't seem to wrap my head around how I could fit this in one texture, but yet I see many other games do exactly what I want.

EDIT:

This should give a better visual demo. I want a large mesh (not very large in the demo) using one texture atlas. (Please keep in mind not all textures in the atlas will be the same size!)

Lets say this is my object, it uses each texture on the atlas, but not the same amount of repeats (brick repeats 3 times, when the smiley face repeats 9 or so times)

**How do most games achieve something like this?** Without using some huge file with repeating textures.

Example (from BOTW) I assume they didn't just repeat this texture on the atlas, considering how large that would be (and expensive).

# Answer
I seem to have found probably the best answer for my case, it may be lazy, but if you have time, I would try and do what @DMGregory suggested, as it is probably more efficient.

So what I ended up doing was using the material file that is exported with the OBJ, which lets me define when a face should use a different texture. So I would render one texture, then swap textures, render the rest of faces with this texture, do that again and so on until the whole model was rendered. Of course this means many extra draw calls, but for me, this seemed to be the easiest option.
> 0 votes

# Answer
I'm not very fluent in OpenGL, so I'll present a rough sketch here and leave it as a community wiki in case someone who knows the tech better would like to update it with precise code hints.

First, if you're targeting OpenGL 3.0 or higher, you can use Array Textures. These let you pack multiple tiling textures of the same resolution into a single sampler. Your workflow would look like this:

1. In your modelling tool, set up and export your model with 3-channel texture coordinates (often called UVW). U & V will be the normal 2D texture coordinates that you're used to, and can range over whatever parts of the texture space you want, even overlapping other parts of the UV net. The third component, W, will be a material index - so for instance the parts that are supposed to be "brick" might have a W coordinate of 0, "cobblestone" might be W = 1, and "shingles" might be W = 2.

Alternatively, you could set up an importer that reads a material or submesh index from your model and uses that to construct these W coordinates, if that's more convenient than authoring them.
2. Load your textures into a Texture Array, in the same order as the W coordinates you assigned (ie. 0 = brick, 1 = cobblestone, 2 = shingles, etc...)
3. In your shader, use a sampler2DArray to reference this texture, and pass it the 3D texture coordinate created above. It will use the third channel of the texture coordinate to select the right material "page" from the array and sample that.

If you need to target devices that do not support Array Textures, then you can do a flavour of this using a texture atlas, with a bit more fuss:

* Instead of storing your textures as pages in an array, they'll be laid out side-by-side in a single large 2D texture, like tiles.
* In your shader, you'll use the third texture coordinate to select an offset into this grid of tiles.
* In the pixel/fragment shader, you'll use the frac or fmod functions to wrap your texture coordinates into the 0...1 range (effectively doing what the Repeat texture sampling mode normally does in hardware), and scale this range to the size of a single tile within the atlas.
* Combining this tile offset and wrapped coordinates-within-tile you'll get your final sample position within the atlas.
* You may need to make your tiles slightly smaller to allow some padding between them, to ensure adjacent tiles don't bleed together at the smaller mip levels.
> 1 votes

---
Tags: opengl, textures, models, tiles
---


# Question
Title: Problem with animating in Android, using batcher.draw in LibGDX
I am having a problem with the last part of the `GameRenderer` class. I call `batcher.draw()` and receive this error:

> The method draw(Texture, float, float, float, float) in the type SpriteBatch is not applicable for the arguments (Object, float, float, float, float)

This only happens when I try to draw animation; images work fine. How do I fix this?

---

This is my `GameRenderer` class, which throws the error.

```
public class GameRenderer {
    private SpriteBatch batcher = new SpriteBatch();

    public void render(float runTime) {
        // Begin SpriteBatch
        batcher.begin();
        // The bird needs transparency.
        batcher.enableBlending();

        // Draw bird at its coordinates. Retrieve the Animation object from
        // AssetLoader
        // Pass in the runTime variable to get the current frame.
        batcher.draw(AssetLoader.birdAnimation.getKeyFrame(runTime),
                x, y, width, height);

        // End SpriteBatch
        batcher.end();
    }
}

```

---

Just in case, here is my `AssetLoader` class:

```
public class AssetLoader {
    public static Animation birdAnimation;

    public static void load() {
        Texture texture = new Texture(Gdx.files.internal("data/texture.png"));
        texture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);

        TextureRegion birdDown = new TextureRegion(texture, 136, 0, 17, 12);
        birdDown.flip(false, true);

        TextureRegion bird = new TextureRegion(texture, 153, 0, 17, 12);
        bird.flip(false, true);

        TextureRegion birdUp = new TextureRegion(texture, 170, 0, 17, 12);
        birdUp.flip(false, true);

        TextureRegion[] birds = { birdDown, bird, birdUp };
        birdAnimation = new Animation(0.06f, birds);
        birdAnimation.setPlayMode(Animation.PlayMode.LOOP_PINGPONG);
    }
}

```

---

The class where i call AssetLoader.load()

```
public class ZBGame extends Game {
    @Override
    public void create() {
        AssetLoader.load();
        /* Other stuff */
    }
}

```

# Answer
Try changing your last batcher draw in GameRenderer class to

```
batcher.draw((TextureRegion)AssetLoader.birdAnimation.getKeyFrame(runTime),
                bird.getX(), bird.getY(), bird.getWidth(), bird.getHeight());

```
> 0 votes

# Answer
The `Animation` class is generic (see docs) - meaning you should supply the type of object being animated which in your case would be `TextureRegion` since the keyframes are of type `TextureRegion`.

This means your code now becomes:

```
/* Declaration. */
public static Animation<TextureRegion> birdAnimation;

/* In your load() method. */
birdAnimation = new Animation<TextureRegion>(0.06f, birds);

```
> 0 votes

---
Tags: java, android, libgdx
---


title: draw only on stencil buffer monogame

text:
# Question
Title: draw only on stencil buffer monogame
Exactly as the question says. Is there a way i can draw vertices only into the stencil buffer.

Basically i want to perform some operations on some vertices of a mesh and based on the result, draw passing vertices only onto the stencil buffer of the screen

# Answer
> 2 votes
This is part of the `GraphicsDevice.BlendState`. Set `ColorWriteChannels` to none. (https://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.blendstate\_members.aspx)

# Answer
> 1 votes
I have to do like this:

```
//Disable writing to screen
BlendState disableColorBufferState = new BlendState();
disableColorBufferState.ColorWriteChannels = ColorWriteChannels.None;

spriteBatch.Begin(SpriteSortMode.Immediate, disableColorBufferState, null, stencilAlways, null, alphaTestEffect);
//draw here
spriteBatch.End

//Enable it again to draw another model
BlendState enableColorBufferState = new BlendState();
enableColorBufferState.ColorWriteChannels = ColorWriteChannels.All;
spriteBatch.Begin(SpriteSortMode.Immediate, enableColorBufferState);
spriteBatch.End();

//Draw another 3D model here

```

---
Tags: c#, graphics, monogame
---


# Question
Title: Simulate the player floating in the water
I am creating my first game in Unity and now I have a problem.

I created a waterpool (a blue quad) and I want to simulate the floating of the player, so when the player is in the water, its Y position would be equal to that of water.

I think a picture is clearer: the water is blue, the player is blue.

I tried to do it this way but it does not work:

```
public float myYpos;

void OnTriggerEnter(Collider other) {
   if(other.tag == "Water") {
      walkSpeed = walkSpeed - deltaWaterSpeed;
      jumpHeight = jumpHeight - deltaWaterJump;

      // DOESN'T WORK
      //myYpos = transform.position.y;
      //myYpos = myYpos + 1;
      //transform.position = new Vector3(transform.position.x, myYpos, transform.position.z);
   }
}

```

This is a gif of my game:

I also do not know why sometimes the player is hidden in the water (I see only water), why?

Thanks to anyone who wants to help me.

---

Thanks for the answers. It is a 2D game but I stupidly followed a tutorial for 3D and so now I go ahead with 3D.

I dont' have a rigidBody on the Player. I added the `OnTriggerStay` as recommended but the result is this:

```
   void OnTriggerStay(Collider other) {
      if(transform.position.y < other.transform.position.y) {
         transform.position = new Vector3(transform.position.x, other.transform.position.y, transform.position.z);
      }
   }

```

I deleted the `OnTriggerEnter()` and `OnTriggerExit()` methods.

Why the player jumps up and down? Why it doesn't float (a few mm below the surface), but quite a bit below?

---

Ok, now actually it does what it should have done, but I realized that was not what I wanted.

It behaves in this way:

The water quad has Y position = 8 and when the player is inside water its Y position is rightly 8. However, this generates this first effect while I prefer the second: the player is on the surface or nearly so, regardless of the height of the water.

How can I get this?

I know I have asked one thing and I got the correct answer but only now I realized that I didn't know what I wanted. Sorry...

In any case, why the player does not jump in the water? It jumps only if it is attached to a gray wall. If it is in the water it doesn't jump but parameters for the jump are setup...

# Answer
> 1 votes
Your code doesn't work because you use OnTrigger**Enter**, which is only called once. If you want to call a function for as long as the collider is in the trigger zone you should use OnTrigger**Stay**

PS: You should not change the position of the blue box directly but manipulate Rigidbody.velocity or use Rigidbody.AddForce to move it, otherwise the box may "teleport" inside other objects and cause odd behaviour.

PS2: You seem to be creating a 2D game. Are you using the 2D or the 3D physics components? If you are using the 2D components, you should use OnTriggerStay**2D**.

**EDIT:** I don't quite understand the third part of your question, but your second problem is exactly why you should not modify the transform directly. The problem you have now is that your box moves down and is "teleported" back up, but it keeps it downwards velocity. It's downwards velocity is also increasing due to gravity, which causes this odd behaviour. To fix this, you should use Rigidbody.AddForce (or manipulate Rigidbody.velocity) instead.

eg:

```
void OnTriggerStay(Collider col){
    // 'rigid' is the Rigidbody component.
    rigid.AddForce(Vector3.up);
}

```

or

```
void OnTriggerStay(Collider col){
    rigid.velocity = Vector3.up;
}

```

# Answer
> 0 votes
Simply variant **if you have RigidBody2D on player**

this variant also can modify for **RigidBody**

```
private void OnTriggerStay2D(Collider2D collision)
{
    if(other.tag == "Water") {
        if (transform.position.y < collision.transform.position.y)
        {
            GetComponent<Rigidbody2D>()
                .AddForce(new Vector2(0, collision.transform.position.y -
                transform.position.y - Physics2D.gravity.y));
        }
    }
}

```

You can replace

```
collision.transform.position.y - transform.position.y

```

On

```
(collision.transform.position.y - transform.position.y)*floatspeed;

```

and change speed of floating (**floatspeed**)

**if you don't usee RigidBody** *for fixation y* in **OnTriggerStay2D**:

```
if (transform.position.y < collision.transform.position.y){
    transform.position(new Vector3(transform.position.x, collision.transform.position.y));
}

```

Also you can modify this script to floating player.

---

**For fix twitching:** Use bool for check if player and water and run this script in LateUpdate if player in water:

**Declaration**

```
bool inWater;
float waterSurface;//y coordinate of water surface

```

**OnTriggerEnter()**

```
if(other.tag == "Water") {
    inWater = true;//player in water
    waterSurface = other.transform.position.y;//set y coord of water surface as center of water
    //you also can get Rect rect of the water sprite for find y coord of water surface
}

```

**OnTriggerExit()**

```
if(other.tag == "Water") {
    inWater = false;
}

```

**LateUpdate()**

```
if(inWater){
    //script for change position in water
}

```

script for change position in water may be different:

> so when the player is in the water, its Y position would be equal to that of water.

```
if (transform.position.y < waterSurface){
    transform.position(new Vector3(transform.position.x,waterSurface));
}

```

---
Tags: unity
---


# Question
Title: Setting Camera's Viewing parameters manually
I am working on Context-aware camera in Unity. in this project i have to set parameters of the camera each frame manually depending on what camera sees on the screen. New View (v) direction is given and Up (u) and Right (r) vectors should be such that they minimize torsion with previous frame's u and r. I have deployed the following code to accomplish the given task:

```
 Vector3 viewNew = -m_Normal;
 Vector3upNew=Vector3.Cross(viewNew,m_CameraPrevTransform.right).normalized;
 Vector3 rightNew = Vector3.Cross(viewNew, upNew).normalized;
         ...
 transform.forward = viewNew;
 transform.up = upNew;
 transform.right = rightNew;

```

The problem is: it seems like Unity tries to automatically adjust parameters when one of the directions (up, forward, right ) are set. Is there a workaround ? is it possible to get more control of the camera?

# Answer
> 0 votes
Expanding answer by @DMGregory

> It takes more than one axis to specify an orientation in 3D. So when we try to set just one axis, Unity has to guess at what we want from the other axes. (Its setter can't look at the surrounding lines of code to see we're providing values for those axes too - it can only work with what it's passed) That means it might guess wrong
>
> To avoid this, we need to combine our axis information into a complete orientation that we can set in one fell swoop. The Quaternion.LookRotation method is perfect for this: it takes up to two vectors (a desired forward and up direction, respectively) and returns a single quaternion representing the best fitting orientation, which we can assign to our transform in a single line.

Like so:

```
transform.rotation = Quaternion.LookRotation(viewNew, upNew);

```

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


# Question
Title: Playing two sound effects in a queue libgdx
I've been developing this game for which I need to play two sound instances one after another. Calling them one after another results in overlapping sounds. The issue is there is no way to know if a sound has finished playing, any workarounds anyone has found for this?

# Answer
> 3 votes
You could load your sound as music and then use the setOnCompletionListener

```
    Music s1 = Gdx.audio.newMusic(Gdx.files.internal("some1.wav"));
    Music s2 = Gdx.audio.newMusic(Gdx.files.internal("some2.wav"));

    s1.setOnCompletionListener(new Music.OnCompletionListener() {

        @Override
        public void onCompletion(Music music) {
            s2.play();

        }
    });

```

---
Tags: android, libgdx
---


# Question
Title: Issues with player movement and character interaction within Pygame
I am working on a small game that deals the main character, which is a cat, and dogs that chase it. The dogs are able to wander around like they are supposed to do, but the cat will only move a small space left and right; the cat will move down once but it will not move up. Would the size of the cat cause the camera not to follow or allow the cat to move more? Size is a thing inside the playerObj.

Also, when a dog collides with the cat, the cat is supposed to lose one bar of health. When the cat collides with the dog, it does not detect that that the dog "hit" the cat and the cat does not lose one bar of health, as it should. This is a problem with the collision detection in my code. The cat doesn't lose health at all. Not sure if there is a function in my code that isn't executing or what. I'm going to post the whole main code, which deals with both movement and the health.

### Main Game File

```
import pygame, sys, math, random
import time
# from pygame import *
from globals import *
from Start import *
from instructions import *

def main():
    pygame.init()
    FPSCLOCK = pygame.time.Clock()
    startScreen()
    displayInst()
    instructions()

def instructions():
        while True:
            for event in pygame.event.get():
                keyE = pygame.event.get(KEYUP)
                if event.type == pygame.QUIT:
                    terminate()
                if event.type == pygame.KEYDOWN:
                    DISPLAYSURF.fill(WHITE)
                    runGame()
                    if event.key == pygame.K_ESCAPE:
                        terminate()

def runGame():

    invulnerable = False   # if the player is invulnerable
    invulnerableStart = 0
    gameOverMode = False   # if the player has lost
    gameOverStartTime = 0  # time the player lost
    winMode = False        # if the player won
    INVULTIME = 2

    dogObjs = []  #stores all dog objects in the game
    # cameraX and cameraY are the top left of where the camera view is
    cameraX = 0
    cameraY = 0

    dogObjs = [] # stores all the non-player objects
    foodObjs = [] # stores all the food objects

    playerObj = {'surface': pygame.transform.scale(HungryCat, (STARTSIZE, STARTSIZE)),
                 'facing': RIGHT,
                  'size' : STARTSIZE,
                  'x': HALF_WINWIDTH,
                  'y': HALF_WINHEIGHT,
                  'health': MAXHEALTH}

    moveLeft = False
    moveRight = False
    moveUp = False
    moveDown = False

    while True:  # main game loop
        DISPLAYSURF.fill(WHITE)
        if invulnerable and time.time() - invulnerableStart > INVULTIME:
            invulnerable = False

        for dObj in dogObjs:
            # move all the dogs
            dObj['x'] += dObj['moveX']
            dObj['y'] += dObj['moveY']

            if random.randint(0,99) < DIRECTIONCHANGE:
                dObj['moveX'] = getRandomVelocity()
                dObj['moveY'] = getRandomVelocity()
                if dObj['moveX'] > 0:  # faces right
                    dObj['surface'] = pygame.transform.scale(TScaryDog, (dObj['width'], dObj['height']))
                else:  # faces left
                    dObj['surface'] = pygame.transform.scale(ScaryDog, (dObj['width'], dObj['height']))

        # go through all objects and see if any need to be deleted
        for i in range(len(dogObjs) -1, -1, -1):
            if isOutsideActiveArea(cameraX, cameraY, dogObjs[i]):
                del dogObjs[i]

        # if there are not enough dogs, make more
        while len(dogObjs) < NUMDOGS:
            dogObjs.append(makeNewDog(cameraX, cameraY))

        # adjusts the cameras X and Y if they are beyond the allowed camera slack value
        playerCenterX = playerObj['x'] + int(playerObj['size'] / 2)
        playerCenterY = playerObj['y'] + int(playerObj['size'] / 2)
        if (cameraX + HALF_WINWIDTH) - playerCenterX > CAMERASLACK:
            cameraX = playerCenterX + CAMERASLACK - HALF_WINWIDTH
        elif playerCenterX - (cameraX + HALF_WINWIDTH) > CAMERASLACK:
            cameraX = playerCenterX - CAMERASLACK - HALF_WINWIDTH
        if (cameraY + HALF_WINHEIGHT) - playerCenterY > CAMERASLACK:
            cameraY = playerCenterY + CAMERASLACK - HALF_WINHEIGHT
        elif playerCenterY - (cameraY + HALF_WINHEIGHT) > CAMERASLACK:
            cameraY = playerCenterY - CAMERASLACK - HALF_WINHEIGHT

        # draw all dogs
        for dObj in dogObjs:
            dObj['rect'] = pygame.Rect(dObj['x'] - cameraX,
                                          dObj['y'] - cameraY,
                                          dObj['width'],
                                          dObj['height'])
            DISPLAYSURF.blit(dObj['surface'], dObj['rect'])

        # draw the player
        flashIsOn = round(time.time(), 1) * 10 % 2 == 1
        if not gameOverMode and not (invulnerable and flashIsOn):
        # and not flashIsOn:
            playerObj['rect'] = pygame.Rect( (playerObj['x'] - cameraX,
                                                playerObj['y'] - cameraY,
                                                playerObj['size'],
                                                playerObj['size']) )
            DISPLAYSURF.blit(playerObj['surface'], playerObj['rect'])

        # draws the health meter
        healthMeter(playerObj['health'])

        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()

            elif event.type == KEYDOWN:
                if event.key in (K_UP, K_w):
                    moveDown = False
                    moveUP = True
                elif event.key in (K_DOWN, K_s):
                    moveUp = False
                    moveDown = True
                elif event.key in (K_LEFT, K_a):
                    moveRight = False
                    moveLeft = True
                    if playerObj['facing'] != LEFT:
                        playerObj['surface'] = pygame.transform.scale(THungryCat, (playerObj['size'], playerObj['size']))
                    playerObj['facing'] = LEFT
                elif event.key in (K_RIGHT, K_d):
                    moveLeft = False
                    moveRight = True
                    if playerObj['facing'] != RIGHT:
                        playerObj['surface'] = pygame.transform.scale(HungryCat, (playerObj['size'], playerObj['size']))
                    playerObj['facing'] = RIGHT
                elif winMode and event.key == K_RETURN:
                    return

            elif event.type == KEYUP:
                # stop moving the players
                if event.key in (K_LEFT, K_a):
                    moveLeft = False
                elif event.key in (K_RIGHT, K_d):
                    moveRight = False
                elif event.key in (K_UP, K_w):
                    moveUp = False
                elif event.key in (K_DOWN, K_s):
                    moveDown = False

                elif event.key == K_ESCAPE:
                    terminate()

        if not gameOverMode:
            # actually move the player
            if moveLeft:
                playerObj['x'] -= MOVERATE
            if moveRight:
                playerObj['x'] += MOVERATE
            if moveUp:
                playerObj['y'] -= MOVERATE
            if moveDown:
                playerObj['y'] += MOVERATE

            # check for collision with dogs
            for i in range(len(dogObjs)- 1, -1, -1):
                dgObjs = dogObjs[i]
                if rect in dgObjs and playerObj['rect'].colliderect(dgObjs['rect']):
                    # this means a collision has occured

                    if dgObjs['width'] * dgObjs['height'] <= playerObj['size']** 2:
                        playerObj['size'] += int((dgObjs['width'] * dgObjs['height'])** 2) + 1
                        del dogObjs[i]

                        if playerObj['facing'] == LEFT:
                            playerObj['surface'] = pygame.transform.scale(HungryCat, (playerObj['size'], playerObj['size']))
                        if playerObj['facing'] == RIGHT:
                            playerObj['surface'] = pygame.transform.scale(THungryCat, (playerObj['size'], playerObj['size']))

                        if playerObj['size'] > HOWBIG:
                            winMode = True

                    elif not invulnerable:

                        invulnerable = True
                        invulnerableStart = time.time()
                        playerObj['health'] -= 1
                        if playerObj['health'] == 0:
                            gameOverMode = True
                            gameOverStartTime = time.time()

        else:
            # game is over, show "game over" screen
            gameOverScreen = pygame.image.load('gameOver.png')
            DISPLAYSURF.blit(gameOverScreen, (0,0))
            if time.time() - gameOverStartTime > GAMEOVERTIME:
                return # end the current game

        # check if player has won
        if winMode:
            WinScreen = pygame.image.load('Win.png')
            DISPLAYSURF.blit(WinScreen, (0,0))

        pygame.display.update()
        FPSCLOCK.tick(FPS)

def healthMeter(currentHealth):  # draws the players health bar
    for i in range(currentHealth):
        pygame.draw.rect(DISPLAYSURF, RED, (15, 5 + (10 * MAXHEALTH) - i * 10, 20, 10))
    for i in range(MAXHEALTH):
        pygame.draw.rect(DISPLAYSURF, WHITE, (15, 5 + (10 * MAXHEALTH) - i * 10, 20, 10), 1)

def getRandomVelocity():
    speed = random.randint(DOGMINSPEED, DOGMAXSPEED)
    if random.randint(0, 1) == 0:
        return speed
    else:
        return -speed

def makeNewDog(cameraX, cameraY):
    dog = {}
    generalSize = random.randint(5, 25)
    multiplier = random.randint(1,3)
    dog['width'] = (generalSize + random.randint(0,10)) * multiplier
    dog['height'] = (generalSize + random.randint(0,10)) * multiplier
    dog['x'], dog['y'] = getRandomOffCameraPos(cameraX, cameraY, dog['width'], dog['height'])
    dog['moveX'] = getRandomVelocity()
    dog['moveY'] = getRandomVelocity()
    if dog['moveX'] < 0:  # faces right
        dog['surface'] = pygame.transform.scale(ScaryDog, (dog['width'], dog['height']))
    else:  #dog is facing left
        dog['surface'] = pygame.transform.scale(TScaryDog, (dog['width'], dog['height']))
    return dog

def getRandomOffCameraPos(cameraX, cameraY, objWidth, objHeight):

    cameraRect = pygame.Rect(cameraX, cameraY, WINWIDTH, WINHEIGHT)
    while True:
        x = random.randint(cameraX - WINWIDTH, cameraX + (2 * WINWIDTH))
        y = random.randint(cameraY - WINHEIGHT, cameraY + (2 * WINHEIGHT))

        objRect = pygame.Rect(x,y, objWidth, objHeight)
        if not objRect.colliderect(cameraRect):
            return x, y

def isOutsideActiveArea(cameraX, cameraY, obj):
    # Return False if camerax and cameray are more than
    # a half-window length beyond the edge of the window.
    boundsLeftEdge = cameraX - WINWIDTH
    boundsTopEdge = cameraY - WINHEIGHT
    boundsRect = pygame.Rect(boundsLeftEdge, boundsTopEdge, WINWIDTH * 5, WINHEIGHT * 5)
    objRect = pygame.Rect(obj['x'], obj['y'], obj['width'], obj['height'])
    return not boundsRect.colliderect(objRect)

if __name__ == '__main__':
    main()

```

# Answer
So I believe the problem stemmed from:

1). Having multiple "main game" loops and

2). issues with importing pygame.

I believe I had multiple "bad" imports with the different files I had along with "built-in" modules. I believe they were conflicting, because as soon as I commented out the rest of my files and made it one big main file, it was running how I intended.

Thanks to everyone who helped me with the basics of Stack Exchange!
> 0 votes

---
Tags: movement, collision-resolution, pygame
---


# Question
Title: Why do we put deltaTime as an argument in render() LibGDX?
I know that `deltaTime` is the time the last frame took to be rendered. However, I have no idea why we have to put it inside the parameter of the render method. I also don't know how the render method takes use of the `deltaTime`.

# Answer
It allows you to compensate for jitter in rendering using gpu-side prediction. For example you have an object moving at a constant speed.

You add the speed to the uniforms used when rendering the object and the delta time. Then in the vertex shader you can do `worldPos = worldPos + speed * deltaTime` before doing the camera and perspective transforms (or fold it into the transformation matrix).

Example:

```
absolute    deltaTime   render      (calculated)
time        (last frame)position
0           0           (w+0)+0     0
10          10          (w+10)+10   20
20          10          (w+20)+10   30
110         90          (w+110)+90  200
120         10          (w+120)+10  130
130         10          (w+130)+10  140
140         10          (w+140)+10  150
200         60          (w+200)+60  270
210         10          (w+210)+10  220
220         10          (w+220)+10  230
230         10          (w+230)+10  240

```
> 2 votes

# Answer
The `delta` variable can be used for many things. Mainly it is used to make your game framerate independent. Framerate independent means that your game behaves the same no matter how many frames per second your game is running at.

For example; let's say you want your player to move at 600 units per second. Since we know our game updates at 60 FPS we calculate that we should move at `600 / 60 = 10` units per update. So we write this code:

```
public void render() {
    position += 10; // Move 10 units per update = 600 units per second.
}

```

Fantastic, our player is now moving at 600 units per second, just like we wanted! But wait, there's more! Let's say we encounter some lag and our game drops down to 40 FPS. Now our code will move us `10 * 40 = 400` units per second! Yikes, not good!

But what if we instead took *actual time* elapsed into account and used this to calculate our speed instead? The code would change to something like this:

```
public void render(float delta) {
    position += 600 * delta; // 600 units per >second<.
}

```

Now, since speed is calculated in *"per second"* instead of *"per update"* we will always move at a constant speed no matter the framerate! Hurrah!
> 2 votes

---
Tags: libgdx, rendering, timestep
---


title: Collision Detection in Pygame

text:
# Question
Title: Collision Detection in Pygame
I'm making a game where the main character is a cat and has to avoid dogs and eat food. The collision detection works for the dogs and will subtract a bar of health from the cat, but when the cat collides with the food, it does not recognize that a collision has occurred.

Here is the code for the dog collision:

```
for i in range(len(dogObjs)-1, -1, -1):
                dgObj = dogObjs[i]
                if 'rect' in dgObj and playerObj['rect'].colliderect(dgObj['rect']):
                    # a player/dog collision has occurred

                        if not invulnerableMode:
                            # player is smaller and takes damage
                            invulnerableMode = True
                            invulnerableStartTime = time.time()
                            playerObj['health'] -= 1
                            if playerObj['health'] == 0:
                                gameOverMode = True # turn on "game over mode"
                                gameOverStartTime = time.time()

```

The above code is the code that works. Now here is the code for the food

```
for i in range(len(foodObjs)-1, -1, -1):
                fdObj = foodObjs[i]
                if 'rect' in fdObj and playerObj['rect'].colliderect(fdObj['rect']):

                    if fdObj['width'] * fdObj['height'] <= playerObj['size']**2:
                        playerObj['size'] += int( (playerObj['width'] * playerObj['height'])**0.2 ) + 1
                        del foodObjs[i]

                    if playerObj['facing'] == LEFT:
                        playerObj['surface'] = pygame.transform.scale(L_CAT_IMG, (playerObj['size'], playerObj['size']))
                    if playerObj['facing'] == RIGHT:
                        playerObj['surface'] = pygame.transform.scale(R_CAT_IMG, (playerObj['size'], playerObj['size']))

                    if playerObj['size'] > WINSIZE:
                        winMode = True # turn on "win mode"

```

I would like to make it where the size of the food does not matter, but I am more focused on just making the collision detection work between the cat and the food.

Both of these for loops are inside an if statement. I will show the whole thing below.

```
if not gameOverMode:
            # actually move the player
            if moveLeft:
                playerObj['x'] -= MOVERATE
            if moveRight:
                playerObj['x'] += MOVERATE
            if moveUp:
                playerObj['y'] -= MOVERATE
            if moveDown:
                playerObj['y'] += MOVERATE

            # check if the player has collided with any dogs
            for i in range(len(dogObjs)-1, -1, -1):
                dgObj = dogObjs[i]
                if 'rect' in dgObj and playerObj['rect'].colliderect(dgObj['rect']):
                    # a player/dog collision has occurred

                        if not invulnerableMode:
                            # player is smaller and takes damage
                            invulnerableMode = True
                            invulnerableStartTime = time.time()
                            playerObj['health'] -= 1
                            if playerObj['health'] == 0:
                                gameOverMode = True # turn on "game over mode"
                                gameOverStartTime = time.time()

            # check if player has collided with food
            for i in range(len(foodObjs)-1, -1, -1):
                fdObj = foodObjs[i]
                if 'rect' in fdObj and playerObj['rect'].colliderect(fdObj['rect']):

                    if fdObj['width'] * fdObj['height'] <= playerObj['size']**2:
                        playerObj['size'] += int( (playerObj['width'] * playerObj['height'])**0.2 ) + 1
                        del foodObjs[i]

                    if playerObj['facing'] == LEFT:
                        playerObj['surface'] = pygame.transform.scale(L_CAT_IMG, (playerObj['size'], playerObj['size']))
                    if playerObj['facing'] == RIGHT:
                        playerObj['surface'] = pygame.transform.scale(R_CAT_IMG, (playerObj['size'], playerObj['size']))

                    if playerObj['size'] > WINSIZE:
                        winMode = True # turn on "win mode"
        else:
            # game is over, show "game over" text
            DISPLAYSURF.blit(gameOverScreen, (0,0))
            if time.time() - gameOverStartTime > GAMEOVERTIME:
                return # end the current game

```

# Answer
> 0 votes
I figured it out. It was not a problem with the code I posted but with some code earlier in the file. My food objects did not have a 'rect' aspect to them, so when I tried to compare the two 'rect's of both the character and the food, nothing happened.

Here is the before code of the food Objects:

```
for fObj in foodObjs:
            gRect = pygame.Rect( (fObj['x'] - camerax,
                                  fObj['y'] - cameray,
                                  fObj['width'],
                                  fObj['height']) )
            DISPLAYSURF.blit(FOODIMAGES[fObj['foodImage']], gRect)

```

Here is the fixed and working code:

```
for fObj in foodObjs:
            fObj['rect'] = pygame.Rect( (fObj['x'] - camerax,
                                  fObj['y'] - cameray,
                                  fObj['width'],
                                  fObj['height']) )
            DISPLAYSURF.blit(FOODIMAGES[fObj['foodImage']], fObj['rect'])

```

---
Tags: collision-detection, python, pygame
---


# Question
Title: How Would I Design Realistic Fluid Handling?
I'm making a game that is like a mix of many other games (Minecraft, Factorio, Don't Starve, Terraria, etc). I want to make pipes and fluid handling like it works in Factorio. I can't seem to find much information on it. I thought about making fluid even out across all connect pipes with less fluid than this pipe, but the order in which I processed pipes would matter a lot. So, how exactly does Factorio work? I also want pumps, if that changes anything.

# Answer
> 1 votes
I don't know how Factorio does it, but I have a suggestion.

You have an issue with the order in which you process your pipes. One way to remove this issue is to store two sets of pipes in your code.

Set 1: The current frame's fluid values in all sections of the pipe.

Set 2: The next frame's fluid values in all sections of the pipe.

When you are processing your current frame's pipes, store the result in the next frame's pipes. By doing it this way, order does not matter. But after you are finished processing the pipes, you need to swap Set 1 and Set 2, so that the game uses the results and not the old values.

The cost of this would be that storing the pipes would require twice the space. Swapping the sets could be done efficiently by choosing which one to read, not copying one and overwriting the other.

A weakness with this technique is that it might take a long time before fluid moves through a very long pipe. Depending on how 'realistic' you want your game to be, this might be very acceptable. If you want or need fluid to move quickly or to not be compressible, then this problem becomes a different more tricky problem.

You could make pumps by transferring fluid values from one pipe section to a section next to it.

I am assuming your pipes are composed of 'blocks' or individual sections that are connected to each other. And that each section contains a fluid value like liters, pressure or density.

# Answer
> 1 votes
If you do not need to handle viscosity (some liquids flowing faster than others) and are OK with all of them flowing essentially immediately, you could do this:

1. Separate your pipe-network into individual sections of connected pipes and reservoirs (pumps would separate the pipeline flowing through them into two individual sections). Calculate the maximum capacity of each section by simply summing up the capacities of all their parts. You only need to recalculate the networks and their capacities when parts are added or removed, not every frame.
2. Keep track of the total amount of liquid in each section (producers, consumers and pumps add or remove liquid from the sections they are connected to)
3. Calculate the fill-state of each individual cell by simply taking the average fill-state of the whole section. Example: If a section has a total max capacity of 4000l, is currently holding 1000l and you are looking at a pipe section with a max capacity of 10l, it currently contains 2.5l (`10 * 1000/4000`)

Problems with this approach:

* It doesn't handle the case of multiple different liquids pouring into the same section. But the way Factorio handles it is not very realistic anyway and the realistic way of doing it (you get a mixture of liquids which might or might not be a useful resource for the player) might not actually be desirable either. You will have to consider for yourself what makes most sense in the context of your game for handling liquids interacting with other liquids.
* As I said before, liquids now flow through pipes with the speed of light. For some games this might be an acceptable break from reality, for others it might not. If you want to do this, you will have to go for the cellular automat approach as described in the answer by No.Manual.

---
Tags: fluid-dynamics
---


# Question
Title: What sprite size should I use for 2D game?
I try to create a 2D game for Android. It looks like **Cut the rope** (it isn't a clone but it have same level representation) if it has a value.
My problem that I can't understand that optimal sprite sizes I should use. I.e. what target screen resolution should I use to sprites didn't have anomalies on HD-devices (like Samsung Galaxy S7 and etc., phones and tablets)?

To make my question is clearer I ask about this **1 unit = X pixels** for xxhdpi-screens. What is **X**?

**P.S.** Sorry if it's a duplicate I will be grateful for link on this post cuz I couldn't find it.

# Answer
> 15 votes
As described in a comment above, there's **no one simple answer for what sprite resolution or Pixels Per Unit (PPU) setting to use**. I think the "why' of this will be a bit clearer if we work through some examples.

Google recommends icons be 144 pixels on xxhdpi displays, so let's arbitrarily choose that as a starting point for our PPU scale and see where this leads us...

## 1. Given a Pixels Per Unit number (PPU), how do we avoid "anomalies"?

To keep our art looking its best, **we need to work out an (orthographic) camera size that will map each sprite texel to a whole number of screen pixels**. If we get a fractional ratio here it can cause unsightly artifacts.

The Samsung Galaxy S7 or Google Pixel XL have a resolution of 2560x1440 in landscape mode. So with our 144 PPU that means we'd want to show 10 game world units vertically to get a 1:1 screen pixel per sprite texel ratio on these devices. (1440 ÷ 144 = 10) Assuming we want to draw at native resolution (more on that below)

Unity's cameras take their size in half-extents along the vertical axis, so that means we'd set our orthographic camera size parameter to 5 (half of 10)

## 2. What if we want a different PPU scale?

Of course this isn't the only size we could choose - 144 was completely arbitrary.

* Maybe for level design & UI layout reasons you'd prefer to see 8 game world units vertically instead of 10. Then you could use 180 pixels per unit instead (1440 ÷ 180 = 8) and a camera size of 4.
* Or maybe you want a bit more room to play in and would prefer 120 pixels per unit to fit 12 units vertically (1440 ÷ 120 = 12) and a camera size of 6.

Especially if your level art is tile-based, knowing how many tiles you want to fit on screen is key to selecting an appropriate resolution and PPU setting for your assets, so you can keep a convenient mapping of 1 world unit = 1 tile. **That means there's no one standard PPU setting** \- it's going to depend on how you want your game to look.

Try mocking up an example level and scaling it to how you want it to look on your device - that will help you identify what world unit scale is right for your game.

Consider too that rendering native res might be a bit too performance/battery intensive on some devices, so rendering to a 720p buffer & dropping to 72 pixels per unit (or 90, or 60...) is also an option, giving us 2 screen pixels per sprite texel. Doubling (or tripling) pixels keeps your art looking crisp after upscaling with nearest neighbour filtering, while still offering an acceptable level of detail on high-dpi devices typically.

## 3. What if we want to support more than one resolution?

This is where things get really complicated. Let's say we want to run this same game on the iPhone 7+, or the (non-XL) Google Pixel phone. These phones use the same 16:9 aspect ratio as the Galaxy S7/Pixel XL, but at 1920x1080 resolution. If we don't change anything, then our 1:1 rendering from the 1440-line screen becomes an 0.75:1 screen pixels per sprite texel ratio on the 1080p screens — not an integer anymore, which means we're going to get artifacts. Same goes for the smaller 2:1 options described above: porting them naively to 1080p gives us a 1.5:1 ratio.

If we reduce our camera size from 5 to 3.75 we get back to 1:1 rendering, but now we only see 7.5 units of our world vertically (eg. 1080 ÷ 144 PPU = 7.5), which is going to change how the gameplay feels. Players on the S7 will see more of the level than iPhone players, and that might not be fair.

This turns out to be a Hard Problem™.

We can solve it by **dropping down to a lower res that's a common factor** of the two display resolutions we're targeting. If we imagine we're rendering to an imaginary 360 pixel screen, then we can display that at 4x scale to hit 1440 and 3x scale to hit 1080 while keeping everything crisp. But we had to sacrifice a lot of detail to do it. This might be OK for a retro-style pixel art game, but if you're shooting for an HD look then it may not be what you want.

Another option is to change your camera settings based on the display resolution, **adding padding or letterboxing on larger displays** so you keep a 1:1 rendering ratio without changing how much level area is visible. If you need room for UI or on-screen controls, this can be a good place to stick that content so it's not covering gameplay area and so the padding itself is less objectionable.

The most flexible solution, but also the most work, is to **produce sprites at multiple resolutions**, and select a different asset and its associated PPU setting based on your display dimensions. You can use Unity's asset bundle variants to handle the swapping, as described in this article.

As an example, we might make two versions of a tile sprite: one 72 pixels tall and one 150% larger, 108 pixels tall. We'll configure the assets' Pixels Per Unit settings at 72 and 108 respectively, so they both correspond to the same 1 unit square in our game world, and the gameplay interactions don't need to change no matter which one is selected. We'll set our camera size to 5 so we display 10 tiles vertically on each device, again keeping the gameplay experience consistent across platforms.

* On a 720p display we'll use the 72 pixel assets (1:1 ratio).
* On a 1080p display we'll use the 108 pixel assets (1:1 ratio).
* And on a 1440 display we'll use the 72 pixel assets again (this time at a 2:1 ratio)

Now we have whole numbered ratios across a range of different screen resolutions, but with the downside that we had to make all or most of our art twice (ouch!)

---

So as you can see, selecting a sprite resolution that fits your game is a complex process, involving careful consideration of your gameplay, aesthetics, target hardware (both for resolution & performance), and production budget. There won't be a simple one-size-fits-all answer, but I hope the above gives you the tools you'll need to work through this process yourself.

If you need some help once you've identified your visual target and supported resolutions, feel free to post a follow-up question with these specific details, and users here may be able to help

---
Tags: unity, 2d, android
---


# Question
Title: Why isn't my PlayerPrefs key detected across multiple games?
I am developing a level based game; I created a key in the PlayerPrefs class called *"LevelNumber"*. It's default value is 0. If I pass level one, it increments by 1 and goes on.

Everything is working fine, but if I press *"restart level"* or if I close and reopen the game menu, the key is no longer detected. Every time I restart the game, it is printing *"key not found"* in the console. How do I fix this?

```
public class AppController : MonoBehaviour
{
    public int _currentLevel = 0;

    void Start ()
    {
        #if UNITY_ANDROID && UNITY_EDITOR
        if (PlayerPrefs.HasKey ("LevelNumber"))
        {
            Debug.Log("Key Found");
            _currentLevel = PlayerPrefs.GetInt ("LevelNumber");
            levels [_currentLevel].SetActive (true);
        }
        else
        {
            Debug.Log("Key not found");
            PlayerPrefs.SetInt ("LevelNumber",_currentLevel);
            levels [_currentLevel].SetActive (true);
            timeText.gameObject.SetActive (true);
        }
        #endif
    }

    public void nextLevelButtonClick()
    {
        int j = _currentLevel + 1;
        _currentLevel = j;
        PlayerPrefs.SetInt ("LevelNumber",_currentLevel);
        PlayerPrefs.Save ();
        SceneManager.LoadScene (0);
    }

    public void RestartLevelButtonClick()
    {
        SceneManager.LoadScene (0);
    }
}

```

# Answer
> -1 votes
The problem is that you're trying to check for a key that doesn't exist yet. Try getting the key and setting a default value in one line instead. Also, using the same line of code inside both the if and the else statement is redundant, something is wrong if you feel the need to do that. Try it this way instead (this will always go inside the if, and never run the else part):

```
_currentLevel = PlayerPrefs.GetInt ("LevelNumber", _currentLevel);
levels [_currentLevel].SetActive (true);
if (PlayerPrefs.HasKey ("LevelNumber")) {
    Debug.Log("Key Found");
}
else
{
    Debug.Log("Key not found");
    timeText.gameObject.SetActive (true);
}

```

`PlayerPrefs.GetInt ("LevelNumber", _currentLevel);` will check to see if there's a `LevelNumber` saved on the device, if not, it will set it with the `_currentLevel` parameter. Since you're doing `levels [_currentLevel].SetActive (true);` on both the if and the else part, you don't really need that inside the if statement either. If you use the `GetInt` part of the code without the second parameter, your code will not set a default value and will be able to go into the else part.

I'm not exactly sure what `timeText.gameObject.SetActive (true);` is doing, but are you sure you need it within an if statement?

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


# Question
Title: Unity - Adding more functionality to a List<T> Inspector
Let's say I have the following code:

```
public List<Armor> armors = new List<Armor> {
    new Armor() { name = "Black set",         folder = "black_set"},
    new Armor() { name = "Conquistador",      folder = "conquistador"},
    new Armor() { name = "Crusader",          folder = "crusader"},
    new Armor() { name = "Gothic Plate",      folder = "gothic_plate"},
    new Armor() { name = "K.D.",              folder = "kd"},
    new Armor() { name = "Lorica segmentata", folder = "lorica_segmentata"},
    new Armor() { name = "Rusty",             folder = "rusty"},
    new Armor() { name = "Spartan",           folder = "spartan"}
};

```

This appears in the editor like this:

While this is acceptable, there are a couple features I am missing: Lets take for instance the Sorting Layer list:

Here there are 2 features that I would like:

1. The ability to reorder elements on the editor
2. The ability to add more elements using + or -

Is there any way to add this functionality into my List?

# Answer
> 1 votes
You want to use Rotorz open-source Reorderable List to save yourself some time. This is the library I use to do exactly what you want. It makes Lists Reorderable in the inspector like the Sorting Layers and more without you having to write more custom inspector code then you need. Here's the library.

# Answer
> 0 votes
Being specific I would say

`public ReorderableList(SerializedObject serializedObject, SerializedProperty elements, bool draggable, bool displayHeader, bool displayAddButton, bool displayRemoveButton);`

Here is the tutorial to this. As it is always great to use which domain owners provide, so this Rotorz UI extensions are also good but I would recommend native library which Unity provides inside `UnityEditorInternal` dll

---
Tags: unity
---


# Question
Title: clip space, normalized device coordinate space and window space in OpenGL
I am learning OpenGL. **Clip space**, **normalized device coordinate space** and **window space** are confusing. I searched but still don't understand them clearly. So, the question is- what are differences between them and how are they converted from one to another? And what coordinate do the built-in OpenGL functions (e.g.: *glBufferData*) take as input?

# Answer
Clip space is the objects' position in a coordinate system relative to the camera. -Z is always in the same direction the camera is pointing. You get it by doing the necessary transformations on the world space positions.

Normalized device cooridnate (or NDC for short) is the same coordinate system, but the Z values are in the 0-\>1 range. This can be achieved by dividing the x and y with z.

Window space is the NDC converted to device coordinates. OpenGL multiplies x with the width of the screen, and y with the height.

Your last question makes no sense in it's current state. Buffers can store everything, and they could store the same data in multiple different formats.
> 2 votes

---
Tags: opengl, coordinates
---


# Question
Title: Getting error in gamemaker studio 2 when using function ord
I'm getting this error:

```
FATAL ERROR in
action number 1
of  Step Event0
for object obj_player2:

Variable obj_player2.D(100004, -2147483648) not set before reading it.
 at gml_Object_obj_player2_Step_0 (line 5) - var xadd = keyboard_check(ord(D))- keyboard_check(ord(A));

```

I followed a tutorial on youtube, I changed the vk\_left etc. to ord(a) instead since I need 2 players at the same time.

# Answer
You need to put "" around strings. So ord("A").
> 1 votes

---
Tags: game-maker
---


# Question
Title: Unable to hide / destroy AdMob Ads in Unity
I am currently working on a small game project and I want to monetize my game with AdMob ads. So I watched this YouTube Tutorial.

It works fine, but the problem is ad appears in all the scenes. So I don't want that. I want the ads on certain scenes.

For example, look at the image below.

I want the ad on Instruction scene. So when the player clicks on *Back To Main Menu* button ad should disappear.

I tried

```
bannerView.Hide ();
bannerView.Destroy();

```

but Unity gives some errors, it says:

> ```
> error CS0103: The name bannerView does not exist in the current context
>
> ```

Here is the script:

```
using UnityEngine;
using System.Collections;

// AdMob
using GoogleMobileAds.Api;

public class Instruction_Level_Manager_Script : MonoBehaviour
{
  // Audio
  public AudioClip My_Audio_Clip ;
  private AudioSource My_Audio ;

  // Use this for initialization
  void Start ()
  {
    My_Audio = GetComponent<AudioSource>();

    // AdMob Ad
    RequestBanner ();
  }

  // Update is called once per frame
  void Update ()
  {
  }

  // Back to Main Menu
  public void Back_To_Main_Menu(string Main_Menu)
  {
    //Playing Audio
    My_Audio.PlayOneShot(My_Audio_Clip);

    //Destroy when leaving the level
    bannerView.Hide ();
    bannerView.Destroy();

    Application.LoadLevel (Main_Menu);
  }

  // AdMob Advertisement
  private void RequestBanner()
  {
    #if UNITY_ANDROID
    string adUnitId = "ca-app-pub-xxxxxxxx/xxxxxxxx";
    #elif UNITY_IPHONE
    string adUnitId = "INSERT_IOS_BANNER_AD_UNIT_ID_HERE";
    #else
    string adUnitId = "unexpected_platform";
    #endif

    // Create a 320x50 banner at the top of the screen.
    BannerView bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);
    // Create an empty ad request.
    AdRequest request = new AdRequest.Builder().Build();
    // Load the banner with the request.
    bannerView.LoadAd(request);
  }
}

```

So what is wrong with this script? I Googled it, but couldn't find satisfying solution. If this method is not possible, how can I destroy the ad?

I am using Unity 5.

# Answer
You have an issue with the `bannerView` variable scope.

Instead of writing

```
BannerView bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);

```

in the `RequestBanner` method, do it in the class scope:

```
using UnityEngine;
using System.Collections;

// AdMob
using GoogleMobileAds.Api;

public class Instruction_Level_Manager_Script : MonoBehaviour
{
  // Audio
  public AudioClip My_Audio_Clip ;
  private AudioSource My_Audio ;

  private BannerView bannerView; // Put this here
  .
  .
  .

```

and in the `RequestBanner` mtehod, simply do:

```
bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);

```
> 1 votes

# Answer
Remove Banner

By default, banners are visible. To temporarily hide a banner, call:

```
Admob.Instance().removeBanner();

```

ref https://github.com/unity-plugins/Unity-Admob#3remove-banner
> 1 votes

# Answer
`bannerView` only exists in the context of `RequestBanner()` and does not exist in the context of `BackToMainMenu()`.

You can make bannerview available by declaring it in the outer scope like this:

```
using UnityEngine;
using System.Collections;

// AdMob
using GoogleMobileAds.Api;
private BannerView bannerView;

public class Instruction_Level_Manager_Script : MonoBehaviour

```

then in RequestBanner() changing your line to:

```
bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);

```

Scope is everything.
> -1 votes

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


title: How to achieve "concept art" graphics?

text:
# Question
Title: How to achieve "concept art" graphics?
I'm currently working on a 3D Game and I want a unique graphic style.

Concept Arts have a cool "painted" look. You can clearly see that this picture is painted on a graphic tablet. (https://i.stack.imgur.com/pnyzB.jpg) - Source: Destiny Concept Arts

How can you achieve that kind of graphics? I guess you draw the texture just like the concept art and apply a light cel-shader?

# Answer
> 2 votes
To get this effect, use the Kuwahara filter as a post processing shader!

There are several ways to implement this algorithm. The Internet should provide sufficient information for the respective purpose.

Edit: I have not tested it yet, but you should also use the Cel shader, so you have less depth in the lighting.

---
Tags: shaders, graphics
---


title: Sprite rotating to look towards mouse

text:
# Question
Title: Sprite rotating to look towards mouse
I am trying to figure out how to calculate the angle to rotate a sprite in z axis to look towards the mouse.

I declared one index -and vertexbuffer and set following vertices in it: VertexBuffer vBuffer; IndexBuffer iBuffer;

```
    VertexPositionColor[] vertices = new VertexPositionColor[4];
    short[] indices;

       vertices[0] = new VertexPositionColor(new Vector3(0, 0, 0) + position, Color.Blue);
        vertices[1] = new VertexPositionColor(new Vector3(1, 0, 0) + position, Color.Blue);
        vertices[2] = new VertexPositionColor(new Vector3(0, 1, 0) + position, Color.Blue);
        vertices[3] = new VertexPositionColor(new Vector3(1, 1, 0) + position, Color.Blue);

        indices = new short[] { 0, 1, 3, 3, 2, 0 };

        vBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionColor), 4, BufferUsage.WriteOnly);
        iBuffer = new IndexBuffer(GraphicsDevice, IndexElementSize.SixteenBits, 6, BufferUsage.WriteOnly);

        vBuffer.SetData<VertexPositionColor>(vertices);
        iBuffer.SetData<short>(indices);

```

Rendering:

```
            GraphicsDevice.SetVertexBuffer(vBuffer);
        GraphicsDevice.Indices = iBuffer;

      effect.View = Matrix.CreateLookAt(new Vector3(0, 0, -5), new Vector3(0, 0, 1), new Vector3(0, 1, 0));
        effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 0.1f, 1000.0f);
        effect.VertexColorEnabled = true;

        effect.World = Matrix.CreateRotationZ(radians);
        effect.CurrentTechnique.Passes[0].Apply();

        GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 2);

```

The variable radians is set in the update-method :

```
            center = new Vector3(0, 0, 0) + position;
        mousePosition = new Vector3(Mouse.GetState().X, Mouse.GetState().Y, 0);

        mousePosition = GraphicsDevice.Viewport.Unproject(mousePosition, effect.Projection, effect.View, Matrix.Identity);

        Vector3 dir = center - mousePosition;

        radians = (float)Math.Atan2(dir.Y, dir.X);

```

Now I want to solve this problem by avoiding using the method atan2.

Given is the xy-plane. How is it possible to calculate the angle of a vector with the direction (0,0,0) to (mouseX,mouseY,0)? Trying to use a reference vector and calculating then the dot product, dividing it by length to put it in the acos function had given false results.

Can You suggest a solution to this?

Thank you.

EDIT: I just read http://www.euclideanspace.com/maths/algebra/vectors/angleBetween/ which states that many acos implementations give a result between zero and pi... makes sense.

# Answer
> 1 votes
I would recommend not using angles. Use linear algebra instead. Once you know the world space location of the mouse pointer pass that onto a method that creates the world matrix for the sprite, then use that matrix for `effect.World`.

```
Matrix BuildWorldMatrix(Vector3 mouseWorldLocation, Vector3 spriteWorldLocation)//can eliminate spriteWorldLocation if its always at 0,0,0
{
   Vector3 dirToMouse = mouseWorldLocation - spriteWorldLocation;
   dirToMouse.Normalize();
   return Matrix.CreateWorld(spriteLocation, dirToMouse, Vector3.Forward);
}

```

---
Tags: xna, monogame
---


# Question
Title: Is there anything equivalent to Portal 2's linked_portal_door in any other engines?
I need the functionality of the linked\_portal\_door that's in Portal 2. I've searched a little in UDK and mostly got people trying to duplicate the portal gun. Does anyone know if UDK, CryEngine, Unity3D, or any other engine has something similar? I'm not against using Source, I just want to know what my options are.

# Answer
I'm pretty sure that the Source Engine is the only engine that will support this out of the box. You can read about some of the technical issues in an article I found on Gamasutra, copied here for future readers:

> "Another problem we ran across was the need to change distance-based systems such as level of detail (LOD) for models, because with our game, distance is relative to the portal locations.
>
> This means that the distance calculations became a choice of three lines connecting two points, rather than just one line. Also, line of sight can pass through a single portal more than once to reach its target.
>
> The Source Engine does many pre-computed visibility optimizations for culling. Allowing users to bridge visibility leaves with portals added another level of complexity.
>
> For better rendering, we implemented a stencil buffer drawing method for portal views, which gave us a lot of flexibility for handling the portal recursion depth. This allowed us to render an infinitely deep number of portals (limited only by performance), which made our "infinite" hallways look pretty neat.
>
> Stencil drawing also helped us solve the problem of integrating properly with other technology in the Source engine like HDR blooming. Since we have to render our scenes an additional two times for our portals we poured a lot of our effort into making portals render as fast as possible, such as special view frustum culling based on the portal's edges, and render list optimizations for portal drawing."

I also remember reading somewhere that there are a lot of special cases, like having portals on opposite sides of the same block. Making portals is not a simple task.

**EDIT:**

Found an other good article containing this:

> Quickly, we realized that we needed a more robust method for rendering the portals and allowing the player and other objects to move seamlessly between them. This required us to dig a little deeper into the Source engine's rendering and physics code, and we had to program our own portal system.
>
> Basically, we had to tell the Source physics system to make a temporary hole on only one side of a wall, and that everything behind the portal is connected to geometry in another part of the map. Getting this to work and optimizing the solutions to run in real-time was a major challenge.
> 8 votes

# Answer
You can in Unity3D, using render textures and teleporting the player behind the other one if he looks into the portal, and turning off the collision detection for the other portal, and then when the player moves out of the surface you could turn on its collision detection, or if he just goes through it without looking at it, just teleport him to the other portal (just a guess, dont know if it would work..), don't know about the other 2 though..
> 0 votes

---
Tags: portals
---


# Question
Title: Can I Debug.Log() on Android without all the callstack spam?
```
I get this:

I/Unity   ( 1908): Serialized file length: 754 bytes.
I/Unity   ( 1908): UnityEngine.Debug:Internal_Log(Int32, String, Object)
I/Unity   ( 1908): UnityEngine.Debug:Log(Object)
I/Unity   ( 1908): SerializeTest:Test() (at Z:\Pong\Devel2010\Src\UnityGames\BhvrDemo\BinarySerialization\Assets\Script\SerializeTest.cs:64)
I/Unity   ( 1908): UnityEngine.Events.InvokableCall:Invoke(Object[])
I/Unity   ( 1908): UnityEngine.Events.InvokableCallList:Invoke(Object[])
I/Unity   ( 1908): UnityEngine.Events.UnityEventBase:Invoke(Object[])
I/Unity   ( 1908): UnityEngine.Events.UnityEvent:Invoke()
I/Unity   ( 1908): UnityEngine.UI.Button:Press() (at C:\BuildAgent\work\d63dfc6385190b60\Extensions\guisystem\guisystem\UI\Core\Button.cs:36)
I/Unity   ( 1908): UnityEngine.UI.Button:OnPointerClick(PointerEventData) (at C:\BuildAgent\work\d63dfc6385190b60\Extensions\guisystem\guisystem\UI\Core\Button.cs:45)
I/Unity   ( 1908): UnityEngine.EventSystems.ExecuteEvents:Execute(IPointerClickHandler, BaseEventData) (at C:\BuildAgent\work\d63dfc6385190b60\Extensions\guisystem\guisystem\EventSystem\ExecuteEvents.cs:52)
I/Unity   ( 1908): UnityEngine.EventSystems.ExecuteEvents:Execute(GameObject, BaseEventData, EventFunction`1) (at C:\BuildAgent\work\d63dfc6385190b6

```

but I would like this:

```
I/Unity   ( 1908): Serialized file length: 754 bytes.

```

# Answer
> 5 votes
Yes, you can now. If you accept that stack traces also disappear from Debug.LogWarning() and Debug.LogError().

Just do this at startup:

```
// We do not want stack traces for all log statements. (Exceptions logged
// with Debug.LogException will still have stack traces though.):
Application.stackTraceLogType = StackTraceLogType.None;

```

# Answer
> 4 votes
I don't believe so. The best one can do is filter the logcat.

I discovered that a feature to toggle this behavior has been suggested in Unity Feedback, but it's over 3 years old. :(

# Answer
> 1 votes
I found this effective, rather than using Debug.Log I wrote directly to the Log.v android method. This also means you can use your own tag, for easy filtering.

```
#elif UNITY_ANDROID
    Log = new AndroidJavaObject("android.util.Log");
    Log.CallStatic<int>("v", TAG, message);
#endif

```

---
Tags: unity
---


# Question
Title: How to send data from compute shader to vertex shader
I have some shaders, every shader has the same constant buffer,

```
//-----------------------
//constant buffer
//---------------------
cbuffer cbPerFrame : register(b0)
{
    float3 gEyePosW;
    float4x4 gView;
    float4x4 gProj;
    float gDim;
    float3 gVoxelOffset;
    float gVoxelSize;
};

```

I think it's a waste to send these same constant buffer several times, so I want to pack them in one Constant Buffer, and share them to other vertex shaders.

I have tried send constant buffer to compute shader, but they don't work in vertex shader.

Do I need to pack these data in one structured buffer? Is it faster than send constant buffer several times?

Is deferred shading relevant to this problem? Which solution do we usually use to solve this problem?

# Answer
The whole purpose of the Direct3D 10/11 'constant buffer' model is to let you share them with many shaders. You only pay to transfer once per CB per change of the data, so reusing a CB between shaders is actually a win if you don't have to change the data.

Generally, the recommendation is to organize your data into CBs by "frequency of update" since the real cost is updating any element in a CB resends the whole CB.

```
cbuffer cbNeverChanges : register( b0 )
{
    matrix View;
};

cbuffer cbChangeOnResize : register( b1 )
{
    matrix Projection;
};

cbuffer cbChangesEveryFrame : register( b2 )
{
    matrix World;
    float4 vMeshColor;
};

```

> Note with Windows 8 or later, drivers can opt to support Direct3D 11.1's partial CB update and offset CB update features which let's you implement alternative CB update strategies.

DirectCompute shaders can only output to UAVs. I think you can create a `ID3D11Buffer` with both BIND\_UAV and BIND\_CB properties, but unless you are processing a lot of data to generate the output it probably doesn't make any sense to do it that way.
> 1 votes

---
Tags: shaders, directx, rendering
---


# Question
Title: Problem in bounding box collision detection in libGDX
I have a Background class containing 5 layers, I've created a collision box for 5th layer. Here is the code for my `Background` class:

```
package com.gitlab.runner.tiger;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Rectangle;
import com.gitlab.runner.tiger.utilities.ParallaxBackground;
import com.gitlab.runner.tiger.utilities.ParallaxLayer;

/**
 * Created by Pintu on 4/17/2017.
 */
public class Background extends AbstractGameObject {

    private World world;
    ParallaxLayer l1, l2, l3, l4, l5, l6;
    ParallaxBackground bg;

    final float bgSpeed = 10f;
    //collison box for 5th layer
    Rectangle hitBox, nextHitBox;

    public Background(float x, float y, float width, float height, World world) {
        super(x, y, width, height);
        this.world = world;
        //creating parallax layer(region,parallaxRatio,padding)
        l1 = new ParallaxLayer(Assets.bgLayerRegion1, bgSpeed, 0);
        l2 = new ParallaxLayer(Assets.bgLayerRegion2, 4, 0);
        l3 = new ParallaxLayer(Assets.bgLayerRegion3, 3, 0);
        l4 = new ParallaxLayer(Assets.bgLayerRegion4, 2, 0);
        l5 = new ParallaxLayer(Assets.bgLayerRegion5, 1, 0);
        l6 = new ParallaxLayer(Assets.bgLayerRegion6, bgSpeed, 0);
        ParallaxLayer[] layers = {l1, l2, l3, l4, l5, l6};
        bg = new ParallaxBackground(layers, world.getCamera());

        hitBox = new Rectangle(0, 0, World.GAME_WIDTH, 12.5f);
        nextHitBox = new Rectangle(hitBox.x+World.GAME_WIDTH,0, World.GAME_WIDTH, 12.5f);

    }

    @Override
    public void update(float delta) {
        scrolling(delta);
    }

    //Scrolls the background across the screen
    private void scrolling(float delta) {
        //Moving camera
        //posBck2 =0,posBck2=at width of bg

        //posBck2 = (int) (posBck1 + width);
        // if (world.getCamera().position.x >= (posBck2 + world.getCamera().viewportWidth / 2)) {
        //   posBck1 = posBck2;
        //}
        hitBox.x = l5.positionX;
        hitBox.y = l5.positionY;
        nextHitBox.x = hitBox.x + World.GAME_WIDTH;
        hitBox.y = l5.positionY;
        world.getCamera().position.x += bgSpeed * delta;
        bg.moveX(1f * delta);

    }

    @Override
    public void draw(SpriteBatch batch) {
       /* for (TextureRegion layer : layers
                ) {

            batch.draw(layer, posBck1, y, width, height);
        }
        for (TextureRegion layer : layers
                ) {

            batch.draw(layer, posBck2, y, width, height);
        }*/
        bg.render(batch);

    }

    public void drawDebug(ShapeRenderer renderer) {

        renderer.rect(hitBox.getX(), hitBox.getY(), hitBox.getWidth(), hitBox.getHeight());
        renderer.rect(nextHitBox.getX(), nextHitBox.getY(), nextHitBox.getWidth(), nextHitBox.getHeight());

    }

}

```

Here is the code for the `Player` class:

```
package com.gitlab.runner.tiger;

import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;

/**
 * Created by Pintu on 4/19/2017.
 */
public class Player extends AbstractGameObject {
    //Player Phyics Variable(acceleration,position,speed,gravity)
    final float ACC = 0.046875f * 10;
    final float FRC = 0.046875f * 10;
    final int TOP = 20;
    float GRAVITY = -0.21875f * 5;
    float xsp;
    //Test textureRegion
    TextureRegion texture;
    Animation<TextureRegion> run;
    TextureAtlas playerAtlas;
    //StateTime to keep track of animation frame
    float stateTime = 0;

    //gettter ,setters
    public float getPositionX() {
        return x;
    }

    public void stopGravity() {
        GRAVITY=0;
    }

    //enum states from each animation
    enum State {
        RUNNING
    }

    //currentState to keep track of current animation
    State currentState = State.RUNNING;

    //Constructor
    public Player(float x, float y, float width, float height) {
        super(x, y, width, height);
        texture = Assets.playerRegion;
        playerAtlas = Assets.playerAtlas;
        //Initialise Animation using frames
        run = new Animation<TextureRegion>(1 / 4f, playerAtlas.getRegions(), Animation.PlayMode.LOOP);

    }

    //Update and Draw code
    @Override
    public void update(float delta) {
        if (delta == 0)
            return;
        stateTime += delta;
        //Player Run pyhsics
       /* if (xsp < TOP) {
            xsp += ACC;
        } else {
            xsp -= Math.min(Math.abs(xsp), FRC) * Math.signum(xsp);
        }*/

        setPosition(getX(), getY() + GRAVITY);

    }

    @Override
    public void draw(SpriteBatch batch) {
        //based on the state get animation frame
        TextureRegion region = null;
        switch (currentState) {
            case RUNNING:
                region = run.getKeyFrame(stateTime);
                break;
        }

        batch.draw(region, getX(), getY(), width, height);

    }

    public void drawDebug(ShapeRenderer renderer) {
        renderer.rect(this.getBoundingRectangle().x, this.getBoundingRectangle().y, this.getBoundingRectangle().getWidth(), this.getBoundingRectangle().getHeight());
    }

}

```

In another `World` class, I'm checking the collisions between them but didn't get satisfying results. Here is the code for my `World` class:

```
package com.gitlab.runner.tiger;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Intersector;

/**
 * Created by Pintu on 4/17/2017.
 */
public class World {
    //Constants - GameWidth,GameHeight
    public static final int GAME_WIDTH = 100;
    public static final int GAME_HEIGHT = 100;
    float viewportWidth, viewportHeight;
    float aspectRatio;
    public OrthographicCamera camera;
    //All game object reference here
    public Background bg;
    public Player player;

    public World() {
        viewportWidth = Gdx.graphics.getWidth();
        viewportHeight = Gdx.graphics.getHeight();
        aspectRatio = viewportHeight / viewportWidth;
        //setting up camera,camera width -half of game width,camera height - multiplied by aspect ratio;
        camera = new OrthographicCamera(GAME_WIDTH, GAME_HEIGHT * aspectRatio);
        camera.position.set(GAME_WIDTH / 2, (aspectRatio / 2) * GAME_HEIGHT, 0);
        //All game object created here
        bg = new Background(0, 0, GAME_WIDTH, GAME_HEIGHT, this);
        player = new Player(100, 100f, 10, 10);
    }

    public void update(float delta) {
        //update camera every frame
        camera.update();
        //check collison

        checkCollision();
        player.setX(camera.position.x);
        //All game objects updated here
        bg.update(delta);
        player.update(delta);

    }

    private void checkCollision() {
        float oldX = player.getX(), oldY = player.getY();

        if (Intersector.overlaps(player.getBoundingRectangle(), bg.hitBox)) {
           // Gdx.app.log("TAG", bg.hitBox.y + bg.hitBox.getHeight() + ",");
            player.setPosition(bg.hitBox.x + bg.hitBox.getWidth(), bg.hitBox.y + bg.hitBox.getHeight());
            Gdx.app.log("TAG", "COLLISON");
        } else if (player.getBoundingRectangle().overlaps(bg.nextHitBox)) {
            player.setPosition(bg.nextHitBox.x + bg.hitBox.getWidth(), bg.nextHitBox.y + bg.nextHitBox.getHeight());
        }

    }

    public OrthographicCamera getCamera() {
        return camera;
    }
}

```

The problem is that I'm getting this

Please check my code to see if there is problem in my collision code or somewhere else. Thank you in advance.

# Answer
Thanks!you for your guidance that was a silly mistake ,this is the right way.

```
//All game objects updated here
bg.update(delta);
 player.update(delta);
//Checks collision
checkCollision();

```
> -1 votes

---
Tags: java, android, libgdx, collision-detection
---


# Question
Title: How do developers implement custom systems (lighting, physics, etc.) in premade game engines that already have these systems, like Unreal or Unity?
Unreal has built in systems for stuff like lighting, for example. If a developer wanted to create and use their own lighting system in Unreal, how do they go about doing that? Or are these systems already so customizable that creating a custom system isn't necessary?

# Answer
> 2 votes
We use the tools made available to us by the engine.

Major engines tend to try to cater to a reasonably large demographic of developers, which means trying to offer as many knobs and dials to turn as possible. If knobs and dials start to become cumbersome, engines typically support extension mechanisms such as writing plugins, replacement shaders, ways to disable or replace entire major subsystems or integrations, et cetera. This tends to get very engine specific.

At the lowest possible level, we simply(\*) change the source code to do what we need to do. Many engines these days permit source code access, either relatively directly (like Unreal) or if you arrange a special licensing deal (like Unity). The latter is usually *expensive* (the kind of expensive where they don't tell you the price until you call them kind of expensive), but usually fit into the budget of the larger-scale games that would really be needing to change this kind of stuff.

(\*) It's of course not usually *simple*, but fundamentally it's still just programming, almost exactly as if you were writing such a system from scratch, except you also have the benefit of being able to leverage the rest of the code provided by the engine and the challenge of having to fit it into the rest of the *assumptions* provided by the engine.

# Answer
> 0 votes
I work with Unity, and you do not need to create new systems for physics or lightning, as they are highly customizable with a lot of different variables that you can play with. These systems are also so advanced that creating a replica will be, in itself, a big project.

Having said that, if you want to create your own physical world based on new rules, you *can* do that; and for that project, the existing systems will only help in achieving the end result in a better and faster way.

This answer holds true for other big game engines, like the Unreal Engine or CryEngine. For game engines that do not have their own physics system, existing physics engines such as Box2D can work.

---
Tags: unity, unreal
---


# Question
Title: How do I create a 2D tile map, and implement movement within it?
How do I create a 2D tile map that I can use? How do I get the world coordinates of it so I can move something to that tile?

I'm learning OpenGL, at the moment, but I'm having a lot of issues understanding how to create a 2D tile map. I have rendered tiles to the world, but I have no way of using them. For example, I'm trying to implement movement, where when clicking on a tile, I would move the player to that tile.

To elaborate, I want a tiles coordinates when I click near/on it, so I can use that position when implementing movement. Right now, I have no idea how to do that; I am able to get the windows 2D coordinates on click, but I don't know how to turn that into a useful way of finding the coordinates I want based on where my tile is in the world.

# Answer
If you want to be able to get the position of a clicked tile: Store the tiles in a 2D array/vector. Assuming you use 16x16 tiles, divide and floor the mouse position by 16 to get the location in the 2D array of the tile.
> 0 votes

---
Tags: opengl, 2d
---


# Question
Title: IEnumerator Loop not Drawing Changes to Transform.position
So, I'm working on an IEnumerator() that is called to spawn objects in a fountain style (kinda flying up and out and landing at a random spot nearby). I feel like I had this working for a hot minute, but I don't know what I've done to screw it up. It's POSSIBLE that it was only working when it was a void() instead, but I need to function to be a coroutine (or otherwise run on something other than the main thread).

So, I have this. It works, except you only see the spawned objects after they've landed and the function has exited.

```
public IEnumerator ThrowFountain()
{
    System.Random rnd = new
    System.Random(System.Guid.NewGuid().GetHashCode());
    GameObject _go = Transform.Instantiate(go, t.position, Quaternion.identity);

    _go.transform.parent = t.parent.transform;
    _go.transform.position = t.position + new Vector3(0.0f, 1.5f, 0.0f);
    float trajectoryHeight = rnd.Next(3,6);
    bool closeEnough = false;

    Vector3 startVec = _go.transform.position;
    Vector3 newVec = new Vector3 (t.position.x + rnd.Next(-6,6), t.position.y, t.position.z + rnd.Next(-6,6));

    float distance = Vector3.Distance(startVec, newVec);
    float startTime = Time.timeSinceLevelLoad;
    float evalTime = startTime;

    while (!closeEnough)
    {
        float distCovered = (evalTime - startTime) * speed;
        float fracJourney = distCovered / distance;
        Vector3 currPos = Vector3.Lerp(startVec, newVec, fracJourney);
        currPos.y += trajectoryHeight * Mathf.Sin(Mathf.Clamp01(distCovered) * Mathf.PI);

        _go.transform.position = currPos;
        closeEnough = V3Close(currPos, newVec, 1.0f);
        Debug.Log("Time: " + Time.time.ToString());
        evalTime += Time.deltaTime;
    }

    yield return new WaitForEndOfFrame();
}

```

V3Close() just returns a bool so long as none of the vectors of the object and it's target are more than 1.0f apart. That part seems to be working as well. Not sure if maybe the IEnumerator loop won't draw the object (because it's not on the main thread or for some other reason)?

# Answer
This seems to happen to me a lot - post the question on SE, figure it out 30-60 minutes later. This one was after a few hours. The answer is simple:

Add a `yield return null` to the end of the `while()` loop. Now I just need to get my math better for the arc and such.
> 0 votes

---
Tags: unity, multithreading, coroutines
---


# Question
Title: Unity 3D recreation of Pitch/Roll from accelerometer
I have an accelerometer that is communicating serially to a PC. As I read in the data, I filter it to clean it up and calculate the angle of the pitch and roll. This all works great. Then I want to apply these angles to an object in Unity3D.

I created an object an try to rotate it using

```
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(new Vector3(pitchAngle, 0f, rollAngle)), Time.time);

```

I use this method because I read that if you try and apply Euler angles, there is potential to run into gimbal lock, so I attempted to use Quaternion to fix that. It seems I might still be running into the problem.

If I try something like

```
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(new Vector3(pitchAngle, 0f, 0f)), Time.time);

```

or

```
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(new Vector3(0, 0f, rollAngle)), Time.time);

```

The rotation is perfect, there is no 180 degree flip.

I also tried one more thing that can be ruled out that did not work, I tried,

```
transform.localRotation =
Quaternion.AngleAxis(rollAngle, Vector3.forward) *
Quaternion.AngleAxis(0, Vector3.up) *
Quaternion.AngleAxis(pitchAngle, Vector3.right);

```

To describe the numbers on the next three images, the very top line is the calculated angle of pitch and roll (respectively). The line below that is the m/sec^2 (g's) recorded from the accelerometer. The very last line is obtained by `transform.eulerAngles.ToString()`.

The picture above is before pitch crosses 90 degrees

The picture above is after pitch crosses 90 degrees, **notice the 180 degree turn**

This picture is removing roll from the equation. The angle of the pitch works perfectly fine. `transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(new Vector3(pitchAngle, 0f, 0f)), Time.time);` The 'roll' also works perfect if pitch is removed. They just don't work well together.
The one thing I noticed is when only rotating one axis, the other two both change from 0 to 180. But I can't simply subtract the 180 from one axis, as I lose my full range of motion.

* Question:
How to I fix this (gimbal lock) problem? After trying Quaternion and failing to use it properly, I am very confused with finding a solution. The math doesn't seem to be clicking in my head to manipulate the angles properly.

# Answer
> 1 votes
Whenever I can, I like to avoid explicitly working with angles.

Let's say we have an acceleration vector measured in gs, after you've applied any smoothing & filtering you're using. When the device is at rest this will be roughly a unit vector pointing in the direction of world up. Let's arrange the coordinates into Unity's coordinate system, so that...

* an x+ acceleration means the object is sitting on its left side
* a y+ acceleration means the object is sitting level and not upside-down
* a z+ acceleration means the object has its nose in the air

`Quaternion.LookRotation(acceleration, control)` gives us a rotation that points the z+ axis in the direction of this locally sensed acceleration, and the y+ axis as close as possible to some control vector.

We can apply a correcting pitch to get an orientation that maps y+ to this sensed direction, and z+ as close as possible to forward (since we don't get yaw information from the accelerometer, we'll just hint it toward zero yaw this way)

```
var worldToLocal = Quaternion.LookRotation(acceleration, Vector3.back)
                  * Quaternion.Euler(90f, 0f, 0f);

```

---

Or, alternatively, we can choose to not normalize the yaw component, and just choose whichever rotation gives us the least difference from our current orientation:

```
var worldToLocal = Quaternion.LookRotation(
                      acceleration,
                      transform.InverseTransformDirection(Vector3.back)
                   ) * Quaternion.Euler(90f, 0f, 0f);

```

Because we don't standardize a front/back axis, this will allow the object's yaw to drift over time, but can give less distracting results when rotating end over end (where an object's effective yaw jumps 180 degrees as it turns upside down).

You can also apply a hybrid approach, nudging the yaw back toward zero when the device appears to be at rest, to keep is somewhat leashed-in.

---

Either way, now we have an orientation describing how we think the world is oriented relative to our sensor. To apply this as a transformation to our object, we just need to invert this to get the orientation of our object relative to the world:

```
transform.rotation = Quaternion.Inverse(worldToLocal);

```

Instead of setting the rotation directly, you can of course apply a smoothing here with Quaternion.Lerp or RotateTowards to damp out remaining jitter or spikes in the sensor signal.

---
Tags: unity, gimbal-lock
---


# Question
Title: The script in the event trigger disappears when the player dies
I am making an 2D platformer for mobile in unity with c#. Right now it is setup in a way that I have one joystick that controls the players shooting, arm rotation and movement. But on that joystick there is an event trigger which is what I use to make the player shoot the gun when the joystick is pressed. The problem I am having is when the player dies the script in the event trigger disappears and I am no longer able to shoot. I am calling Destory() when the player dies and he does have lives. the location of that script is on the player I am not sure if that has anything to do with it but of anybody has any suggestions that would be great.

Here is the code for when the player dies and respawns

```
public static void KillPlayer (Player player)
{
    Destroy (player.gameObject);
    _remaningLives -= 1;
    if (_remaningLives <= 0)
    {

        gm.EndGame();

    }else
    {
        gm.StartCoroutine(gm._RespawnPlayer());
    }
}

```

# Answer
> 1 votes
When you call `Destroy()` on the player, that *also* destroys the script your trying to access.

Instantiating a new copy isn't sufficient, as it's *a new copy* the old reference is pointing to the wrong place.

You have to update the reference when you instantiate the new copy:

```
_RespawnPlayer() {
    //...other code
    GameObject newPlayer = Instantiate(...);
    joystick.playerScriptRef = newPlayer.GetComponent<PlayerScript>();
    //...other code
}

```

(I don't know what your script names are called, you'll have to massage it yourself).

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


title: Visual Basic PictureBox

text:
# Question
Title: Visual Basic PictureBox
**A description of my game:**

When you start the game, you have a few seconds to memorize the arrangement of the grids. By the arrangement, I mean each grid is one of two colors. After the time is up, all the grids are set to the 'off' color. The player must click on the grids to toggle them and put them in their correct color assignments as they were seen before.

**Okay so this is part of a game I am developing.Instead of using solid colors, I want use background images but I don't know how to edit the code to do so. Any help would be welcome.**

```
Dim GridOn As Color = Color.LightBlue
Dim GridOff As Color = Color.DarkBlue
Dim MaxTime As Integer = 40

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    For Each pic As Control In Me.Controls 'For every picture in form1's controls...
        If TypeOf pic Is PictureBox Then   'Then, only picks the pictureboxes, not the buttons, labels, etc.
            AddHandler pic.Click, AddressOf PictureBoxClick 'For each picturebox (grid), add an event handler (PictureBoxClick) to avoid
        End If                                              'typing 16 of them ourselves
    Next
End Sub

    Private Sub PictureBoxClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
    If AllowEdit = True Then
        Dim ctrl As PictureBox = DirectCast(sender, Control)
        If ctrl.BackColor = GridOn Then
            ctrl.BackColor = GridOff 'Set the backcolor to either GridOn or GridOff
        Else : ctrl.BackColor = GridOn
        End If
    Else
        'Do not allow the user to change the colors
    End If
  End Sub

```

# Answer
> 1 votes
You can try adding an image property:

```
Imports System.Drawing

Dim ImageA As Image = Image.FromFile("C:\ImageOn.jpg")
Dim ImageB As Image = Image.FromFile("C:\ImageOff.jpg")

  Private Sub PictureBoxClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
    If AllowEdit = True Then
        Dim ctrl As PictureBox = DirectCast(sender, Control)
        If ctrl.BackColor = GridOn Then
            ctrl.BackColor = GridOff
            ctrl.Image = ImageB
        Else : ctrl.BackColor = GridOn : ctrl.Image = ImageA
        End If
    Else
        'Do not allow the user to change the colors
    End If
  End Sub

```

---
Tags: vb.net
---


# Question
Title: Making a Randomize() Function not go past 0 (VB.Net)
I am wondering on how I can prevent a Randomize() function from returning a value less than 0. Thanks!

# Answer
> 1 votes
You could do it with a range:

```
CInt(Math.Ceiling(Rnd() * n)) + 1

```

or

```
Dim Generator As System.Random = New System.Random()
Dim rndValue As Integer = Generator.Next(min, max)

```

or you could just use the abs always, so every negative number would turn into the positive counterpart.

# Answer
> -2 votes
You can use this function

```
Function Rand(Low as Long, High as Long) As Long
   Return Random.Next(Low, High)
End Function

```

---
Tags: vb.net
---


# Question
Title: In the Unity Editor, how to push a parent's transform down to its children?
I've inherited a Unity scene with quite a deep object hierarchy. Some `GameObject`s in the hierarchy don't have any geometry of their own, and just exist to group their children and apply a `MonoBehaviour` to all of their children. Because of the way the scene was authored, some of these objects have arbitrary transforms, which makes it hard to edit the child transforms, to align the children with other objects outside the group.

As a one-off operation in the editor, I'd like to reset these objects' transforms, without changing the world-space positions and orientations of the children. Put another way, I'd like to push the effect of the transform down to the children.

What's the easiest way to achieve this in the editor? I've seen a lot of questions from people who want to achieve this in code, to have the effect of detaching the parent and child transforms while keeping the relationship, but that's **not** what I want. I'm just looking for a one-off, manual operation to make my scene file easier to edit.

# Answer
> 2 votes
In the Hierarchy tab, you could click-and-drag the child Transforms to a root-level empty Transform. This will keep the children's world position, scale, and rotation, while also keeping them within a Transform you can collapse/expand easily enough as you make your changes without cluttering your scene. While you have the child Transforms selected, use save selection (`Ctrl`-`Alt`-`1`).

With the children safely moved, select the parent object, and in the Inspector, right-click the **Transform** label and choose **Reset**. This is the quickest way to reset the Transform.

When it comes time to reparent them again, use restore selection (`Ctrl`-`Shift`-`1`) to select the children again, and click-and-drag them back to their desired parent; their position, scale, and rotation will again remain the same.

---

If there are lots of Transforms you don't fancy reparenting by hand, you could create a MenuItem with a static method to find and manipulate your Transforms as needed.

Ways to access your Transforms from a MenuItem method include:

# Answer
> 1 votes
Something like this should do it.I'm sure how you want to reset the parent game object so in my code I just return it to 0,0,0 on both position and rotation.

You attach this component to the gameObject you want to changee :

```
using UnityEngine;
[ExecuteInEditMode]
public class FixChildren : MonoBehaviour {

    // Use this for initialization
    public void FixTransforms()
    {
        // Make the changes to the transform here.
        transform.position = Vector3.zero;
        transform.rotation = Quaternion.identity;
    }
}

```

Then for easy use we create a custom Inspector for the component with a button that call the FixTransforms method :

```
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(FixChildren))]
public class CustomInspector : Editor {

    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        FixChildren myScript = (FixChildren)target;
        if (GUILayout.Button("Fix transforms"))
        {
            myScript.FixTransforms();
        }
    }
}

```

You can easily change this to go automatically trough all objects or leave it like this giving you finer control. Hope this helps.

---
Tags: unity, transformation
---


# Question
Title: How do I perform collision resolution for rigid bodies of varying volume?
I am currently trying to develop a small physics engine for my games. I have created bounding volumes for different rigid bodies. However, I am having problems handling collision resolution, more specifically with determining the direction to apply the impulse to the objects and their changes in velocities.

How do I perform collision resolution for rigid bodies of varying volume? Is there a general solution for resolving collision between all rigid bodies like sphere, AABB or OBB, or do I have to specifically arrive at a solution for each scenario?

# Answer
> 1 votes
You need to isolate your `CollisionDetector` and your `CollisionResolver`. The `CollisionDetector` must return data from the collision, i.e collision point, normal collision, interpenetration, etc.

Then you need pass this information to `CollisionResolver` and it must solve the collision with the information provided. In this step the rigidbody shape (AABB, OBB, sphere, etc) is irrelevant. You only need to find the impulse to apply, divide it into linear and angular component and apply it to the collision point (calculated previously in the `CollisionDetector`)

You can see a very simple example here: http://angelluispg.es/AL3D/ALPhysics.js

This is a very simple physics engine programmed by me that doesn't take in account angular movement, but you can see the general idea. The important parts for you problem is the class `ALPhysics.NarrowPhase` and the class `ALPhysics.CollisionResolver`

---
Tags: c++, collision-detection, physics
---