# Question
Title: In Pygame, why does my sprite only move each time the button is pressed?
As quite obviously stated in my title, why does my sprite only move each single time the key is pressed, (as opposed to moving WHILE the key is pressed.) By the way, really sorry, you won't be able to run it properly as I removed all the blocks that stop you walking into walls to allow it to run Here is my code:

```
import pygame
from pygame.locals import*
import pygame

pygame.init()

WHITE = (255,255,255)

start_in_bed = 0
#counts which sprite you should be on when running

#create screen
screen_width = 160
screen_height = 144
screen_multiplier = 4
screen = pygame.display.set_mode(((screen_width*screen_multiplier),(screen_height*screen_multiplier)))
pygame.display.set_caption('Pokemon Blood Red')

#Sprite stuff
sprite = pygame.image.load('player_south_still.png')
#Reform the sprite
sprite = pygame.transform.scale(sprite, (10*screen_multiplier, 14*screen_multiplier))
sprite.set_colorkey(WHITE)

class Player(pygame.sprite.Sprite):

    def __init__(self):
        super(Player, self).__init__()
        self.player_sprite = pygame.Surface((10*screen_multiplier, 14*screen_multiplier))
        self.player_sprite.fill(WHITE)
        self.rect = self.player_sprite.get_rect()
        self.rect.x = 160/2
        self.rect.y = 144/2

class Blocks(pygame.sprite.Sprite):

    def __init__(self, width, height):
        super(Blocks, self).__init__()
        block_width = width
        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)
        self.rect = self.image.get_rect()
        self.block_width = width
        self.block_height = height
#######################################################################

#Create all blockades ever

player = Player()
player.rect.x = (126*screen_multiplier)
player.rect.y = (100*screen_multiplier)
################################################################################
class Doors(pygame.sprite.Sprite):

    def __init__(self, width, height):
        super(Doors, self).__init__()
        self.player_house_door = pygame.Surface((width, height))
        self.player_house_door.fill(WHITE)
        self.rect = self.player_house_door.get_rect()
        self.rect.x = 40*screen_multiplier
        self.rect.y = 75*screen_multiplier
player_house_door = Doors(8*screen_multiplier, 2*screen_multiplier)

player_group = pygame.sprite.Group()
player_group.add(player)

inside_house_door = Doors(22*screen_multiplier, 18*screen_multiplier)
inside_house_door.rect.x = 80*screen_multiplier
inside_house_door.rect.y = 13*screen_multiplier
screen.blit(inside_house_door.player_house_door, (inside_house_door.rect.x, inside_house_door.rect.y))

extra_door = Doors(8*screen_multiplier, 2*screen_multiplier)
################################################################################
nt_blocks = pygame.sprite.Group()
nt_blocks.add(nt_trees_left)
nt_blocks.add(nt_trees_top)
nt_blocks.add(nt_trees_right)
nt_blocks.add(nt_trees_right_bottom)
nt_blocks.add(laboratory)
nt_blocks.add(nt_trees_bottom)
nt_blocks.add(nt_player_house)
nt_blocks.add(nt_friend_house)

home_upstairs_blocks = pygame.sprite.Group()
home_upstairs_blocks.add(home_upstairs_back_wall)
home_upstairs_blocks.add(home_upstairs_back_back_wall)
home_upstairs_blocks.add(home_upstairs_tree)
home_upstairs_blocks.add(home_upstairs_left_wall)
home_upstairs_blocks.add(home_upstairs_right_wall)
home_upstairs_blocks.add(home_upstairs_bottom_wall)
home_upstairs_blocks.add(home_upstairs_banister)

home_downstairs_blocks = pygame.sprite.Group()
home_downstairs_blocks.add(home_downstairs_tree)
home_downstairs_blocks.add(home_downstairs_left_wall)
home_downstairs_blocks.add(home_downstairs_bottom_left_wall)
home_downstairs_blocks.add(home_downstairs_bottom_left_tree)
home_downstairs_blocks.add(home_downstairs_counter)
home_downstairs_blocks.add(home_downstairs_table)
home_downstairs_blocks.add(home_downstairs_sink)
home_downstairs_blocks.add(home_downstairs_tv)
home_downstairs_blocks.add(home_downstairs_fridge)
home_downstairs_blocks.add(home_downstairs_kitchen_back_wall)
home_downstairs_blocks.add(home_downstairs_banister)
home_downstairs_blocks.add(home_downstairs_bottom_right_wall)
home_downstairs_blocks.add(home_downstairs_top_wall)

lab_blocks = pygame.sprite.Group()
lab_blocks.add(lab_machine)
lab_blocks.add(lab_ball_table)
lab_blocks.add(lab_table)
lab_blocks.add(lab_stuff)
lab_blocks.add(lab_fridges)
lab_blocks.add(lab_bottom_left_fridges)

place = 3
def area_load():
    global background

    if place == 0:
        global start_in_bed
        if start_in_bed == 0:
            player.rect.x = 126*screen_multiplier
            player.rect.y = 105*screen_multiplier
            sprite = pygame.image.load('player_south_still.png')
        else:
            player.rect.x = 110*screen_multiplier
            player.rect.y = 50*screen_multiplier
            sprite = pygame.image.load('player_west_still.png')
        inside_house_door.rect.x = 130*screen_multiplier
        inside_house_door.rect.y = 50*screen_multiplier
        sprite = pygame.image.load('player_west_still.png')
        background = pygame.image.load('player_house_upstairs.png').convert()
        background = pygame.transform.scale(background, (160*screen_multiplier, 144*screen_multiplier))
        screen.blit(background, (0, 0))
        screen.blit(player.player_sprite, (player.rect.x, player.rect.y))
    if place == 1:
        start_in_bed += 1
        inside_house_door.rect.x = 110*screen_multiplier
        inside_house_door.rect.y = 24*screen_multiplier
#Player rect.x and rect.y are determined in collisions of doors so you end up at the right place
        player_house_door.rect.x = 73*screen_multiplier
        player_house_door.rect.y = 130*screen_multiplier
        door_enter = pygame.sprite.spritecollide(player_house_door, player_group, False)
        if door_enter:
            while door_enter:
                player.rect.y -= 1*screen_multiplier
                door_enter = pygame.sprite.spritecollide(player_house_door, player_group, False)
        background = pygame.image.load('player_house_bottom.png').convert()
        background = pygame.transform.scale(background, (160*screen_multiplier, 144*screen_multiplier))
        screen.blit(background, (0, 0))
    if place == 2:
        player_house_door.rect.x = 40*screen_multiplier
        player_house_door.rect.y = 75*screen_multiplier
        background = pygame.image.load('neuory_town.png').convert()
        background = pygame.transform.scale(background, (160*screen_multiplier, 144*screen_multiplier))
        screen.blit(background, (0, 0))
    if place == 3:
        player.rect.x = (70*screen_multiplier)
        player.rect.y = (112*screen_multiplier)
        inside_house_door.rect.x = 70*screen_multiplier
        inside_house_door.rect.y = 133*screen_multiplier
        extra_door.rect.x = 114*screen_multiplier
        extra_door.rect.y = 47*screen_multiplier
        sprite = pygame.image.load('player_north_still.png')
        background = pygame.image.load('lab.png').convert()
        background = pygame.transform.scale(background, (160*screen_multiplier, 144*screen_multiplier))
        screen.blit(background, (0, 0))
area_load()

#######################################################################

#Random variables for later use

pygame.init()

amount_caught = 0
catch1 = {'pokemon':'none',
          'hp':0,
          'attack':0,
          'defence':0,
          'sp_attack':0,
          'sp_defence':0,}

(x) = 160*0.45
(y) = 144*0.45
def caught():
    if amount_caught == 0:
        pass
        #catch1 values are equal to wild one's

#Mainloop
crashed = False
while not crashed:

    x_change = 0
    y_change = 0

    #Different buttons
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True
            pygame.quit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_change = -3*screen_multiplier
                player.rect.x += x_change
                screen.blit(player.player_sprite, (player.rect.x, player.rect.y))
                if place == 3:
                    hits = pygame.sprite.spritecollide(player, lab_blocks, False)
                    if hits:
                        while hits:
                            print ('Collision!')
                            x_change = 1*screen_multiplier
                            player.rect.x += x_change
                            hits = pygame.sprite.spritecollide(player, lab_blocks, False)
                if place == 2:
                    hits = pygame.sprite.spritecollide(player, nt_blocks, False)
                    if hits:
                        while hits:
                            print ('Collision!')
                            x_change = 1*screen_multiplier
                            player.rect.x += x_change
                            hits = pygame.sprite.spritecollide(player, nt_blocks, False)
                if place == 1:
                    hits = pygame.sprite.spritecollide(player, home_downstairs_blocks, False)
                    if hits:
                        while hits:
                            print ('Collision!')
                            x_change = 1*screen_multiplier
                            player.rect.x += x_change
                            hits = pygame.sprite.spritecollide(player, home_downstairs_blocks, False)

                if place == 0:
                    hits = pygame.sprite.spritecollide(player, home_upstairs_blocks, False)
                    if hits:
                        while hits:
                            print ('Collision!')
                            x_change = 1*screen_multiplier
                            player.rect.x += x_change
                            hits = pygame.sprite.spritecollide(player, home_upstairs_blocks, False)
                sprite = pygame.image.load('player_west_still.png')
            elif event.key == pygame.K_RIGHT:
                x_change = 3*screen_multiplier
                player.rect.x += x_change
                screen.blit(player.player_sprite, (player.rect.x, player.rect.y))
                if place == 3:
                    hits = pygame.sprite.spritecollide(player, lab_blocks, False)
                    if hits:
                        while hits:
                            print ('Collision!')
                            x_change = -1*screen_multiplier
                            player.rect.x += x_change
                            hits = pygame.sprite.spritecollide(player, lab_blocks, False)
                if place == 2:
                    hits = pygame.sprite.spritecollide(player, nt_blocks, False)
                    if hits:
                        while hits:
                            print ('Collision!')
                            x_change = -1*screen_multiplier
                            player.rect.x += x_change
                            hits = pygame.sprite.spritecollide(player, nt_blocks, False)
                if place == 1:
                    hits = pygame.sprite.spritecollide(player, home_downstairs_blocks, False)
                    if hits:
                        while hits:
                            print ('Collision!')
                            x_change = -1*screen_multiplier
                            player.rect.x += x_change
                            hits = pygame.sprite.spritecollide(player, home_downstairs_blocks, False)

                if place == 0:
                    hits = pygame.sprite.spritecollide(player, home_upstairs_blocks, False)
                    if hits:
                        while hits:
                            print ('Collision!')
                            x_change = -1*screen_multiplier
                            player.rect.x += x_change
                            hits = pygame.sprite.spritecollide(player, home_upstairs_blocks, False)
                sprite = pygame.image.load('player_east_still.png')
            elif event.key == pygame.K_UP:
                y_change = -3*screen_multiplier
                player.rect.y += y_change
                screen.blit(player.player_sprite, (player.rect.x, player.rect.y))
                if place == 3:
                    hits = pygame.sprite.spritecollide(player, lab_blocks, False)
                    if hits:
                        while hits:
                            print ('Collision!')
                            y_change = 1*screen_multiplier
                            player.rect.y += y_change
                            hits = pygame.sprite.spritecollide(player, lab_blocks, False)
                if place == 2:
                    hits = pygame.sprite.spritecollide(player, nt_blocks, False)
                    if hits:
                        while hits:
                            print ('Collision!')
                            y_change = 1*screen_multiplier
                            player.rect.y += y_change
                            hits = pygame.sprite.spritecollide(player, nt_blocks, False)
                if place == 1:
                    hits = pygame.sprite.spritecollide(player, home_downstairs_blocks, False)
                    if hits:
                        while hits:
                            print ('Collision!')
                            y_change = 1*screen_multiplier
                            player.rect.y += y_change
                            hits = pygame.sprite.spritecollide(player, home_downstairs_blocks, False)

                if place == 0:
                    hits = pygame.sprite.spritecollide(player, home_upstairs_blocks, False)
                    if hits:
                        while hits:
                            print ('Collision!')
                            y_change = 1*screen_multiplier
                            player.rect.y += y_change
                            hits = pygame.sprite.spritecollide(player, home_upstairs_blocks, False)

                sprite = pygame.image.load('player_north_still.png')
            elif event.key == pygame.K_DOWN:
                y_change = 3*screen_multiplier
                player.rect.y += y_change
                screen.blit(player.player_sprite, (player.rect.x, player.rect.y))
                if place == 3:
                    hits = pygame.sprite.spritecollide(player, lab_blocks, False)
                    if hits:
                        while hits:
                            print ('Collision!')
                            y_change = -1*screen_multiplier
                            player.rect.y += y_change
                            hits = pygame.sprite.spritecollide(player, lab_blocks, False)
                if place == 2:
                    hits = pygame.sprite.spritecollide(player, nt_blocks, False)
                    if hits:
                        while hits:
                            print ('Collision!')
                            y_change = -1*screen_multiplier
                            player.rect.y += y_change
                            hits = pygame.sprite.spritecollide(player, nt_blocks, False)
                if place == 1:
                    hits = pygame.sprite.spritecollide(player, home_downstairs_blocks, False)
                    if hits:
                        while hits:
                            print ('Collision!')
                            y_change = -1*screen_multiplier
                            player.rect.y += y_change
                            hits = pygame.sprite.spritecollide(player, home_downstairs_blocks, False)

                if place == 0:
                    hits = pygame.sprite.spritecollide(player, home_upstairs_blocks, False)
                    if hits:
                        while hits:
                            print ('Collision!')
                            y_change = -1*screen_multiplier
                            player.rect.y += y_change
                            hits = pygame.sprite.spritecollide(player, home_upstairs_blocks, False)
                sprite = pygame.image.load('player_south_still.png')
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                x_change = 0
            elif event.key == pygame.K_RIGHT:
                x_change = 0
            elif event.key == pygame.K_UP:
                y_change = 0
            elif event.key == pygame.K_DOWN:
                y_change = 0
    x += x_change
    y += y_change
    player.rect.x += x_change
    player.rect.y += y_change
    #Check for collisions
    hits = pygame.sprite.spritecollide(player, nt_blocks, False)
    if place == 3:
        door_enter = pygame.sprite.spritecollide(inside_house_door, player_group, False)
        if door_enter:
            print('n')
            player.rect.x = 100*screen_multiplier
            player.rect.y = 50*screen_multiplier
            place = 2
            area_load()
    elif place == 2:
        door_enter = pygame.sprite.spritecollide(player_house_door, player_group, False)
        if door_enter:
            print('n')
            player.rect.x = 70*screen_multiplier
            player.rect.y = 110*screen_multiplier
            place = 1
            area_load()
        door_enter = pygame.sprite.spritecollide(extra_door, player_group, False)
        if door_enter:
            print('n')
            player.rect.x = 70*screen_multiplier
            player.rect.y = 110*screen_multiplier
            place = 3
            area_load()
    elif place == 1:
        door_enter = pygame.sprite.spritecollide(inside_house_door, player_group, False)
        if door_enter:
            print('n')
            player.rect.x = (38*screen_multiplier)
            player.rect.y = (80*screen_multiplier)
            place = 0
            sprite = pygame.image.load('player_east_still.png')
            if start_in_bed != 0:
                player.rect.x = 130*screen_multiplier
                player.rect.y = 30*screen_multiplier

            area_load()

        door_enter = pygame.sprite.spritecollide(player_house_door, player_group, False)
        if door_enter:
            print('outside door')
            player.rect.x = (38*screen_multiplier)
            player.rect.y = (80*screen_multiplier)
            place = 2
            sprite = pygame.image.load('player_north_still.png')
            area_load()
    elif place == 0:
        door_enter = pygame.sprite.spritecollide(inside_house_door, player_group, False)
        if door_enter:
            print('n')
            place = 1
            player.rect.y = 25*screen_multiplier
            player.rect.x = 132*screen_multiplier
            area_load()

    if place == 0:
        sprite = pygame.transform.scale(sprite, (10*screen_multiplier*2, 14*screen_multiplier*2))
    elif place == 1:
        sprite = pygame.transform.scale(sprite, (10*screen_multiplier*2, 14*screen_multiplier*2))
    elif place == 3:
        sprite = pygame.transform.scale(sprite, (10*screen_multiplier*2, 14*screen_multiplier*2))
    else:
        sprite = pygame.transform.scale(sprite, (10*screen_multiplier, 14*screen_multiplier))
    #Draw everything
    screen.blit(player.player_sprite, (player.rect.x, player.rect.y))
    screen.blit(background, (0, 0))
    #screen.blit(lab_bottom_left_fridges.image, (lab_bottom_left_fridges.rect.x, lab_bottom_left_fridges.rect.y))
    sprite.set_colorkey(WHITE)
    screen.blit(sprite,(player.rect.x,player.rect.y))
    pygame.display.flip()
pygame.quit()

```

Thanks for the help!

# Answer
> 1 votes
Here is the section of relevant code from your program:

```
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        crashed = True
        pygame.quit()
    elif event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            x_change = -3*screen_multiplier
            player.rect.x += x_change
            screen.blit(player.player_sprite, (player.rect.x, player.rect.y))

```

When the player hits the left arrow key Pygame sends a KEYDOWN event. For each KEYDOWN event your program sees, it adjusts the player's position by 'x\_change' pixels. Note that this happens ONCE per KEYDOWN event, which is why nothing happens when you hold down the key.

You have a couple basic options (there are lots more, but just as a quick overview). First, you could redesign your event logic so that the KEYDOWN event sets a velocity property of the player, and then a KEYUP event (fired on key release) sets it to 0. This will result in the player having a constant speed while the key is held. The other option, which is a bit better in my opinion, is to use Pygame's get\_pressed() method to check which keys are currently pressed. This way you can adjust the player position every frame based on the keyboard state.

# Answer
> 0 votes
Your game loop seems malformed. Your loop looks essentially like this:

```
while running:
    for event in pygame.event.get():
        if keypress:
            set_velocity()
            update_position()
            render()
        elif keyrelease:
            reset_velocity()

```

The issue here is that you render the sprite in the event loop and that's not really a good way to do things. So, to make it simpler and clearer, you want your loop to be something like this instead:

```
while running:
    for event in pygame.event.get():
        if keypress:
            set_velocity()
        elif keyrelease:
            reset_velocity()

    window.fill((0, 0, 0))
    update_position()
    render()
    pygame.display.flip()

```

The key part that makes your sprites move continuously is the `update_position()` section, which will apply the velocity set in your events loop to the player sprite.

If you're wondering where collision resolution should happen in this case, it should probably be it's own function under `update_position()`.

---
Tags: python, pygame
---


# Question
Title: Java - Lemmings - How to detect mouse over lemming
My first post on gamedev :) And my first go at game dev :D

To ease me in, I'm starting with a lemmings clone.

I have my lemmings moving about and already have a `MouseAdapter` for moving around the map with the mouse.

In order to detect when the mouse is over a lemming I thought the easiest way would be to override the `mouseMoved` method. This would iterator over the lemmings and check if the mouse coords are in the lemmings rectangle. Is the normal way to do this?

I realised this wouldn't work for a lemming walking under/past the mouse cursor.

# Answer
Solved it by having a second mask just for the "lemmings", then I can check this every time it paints.
> 0 votes

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


# Question
Title: How do I stop "StartServer listen failed" when I start a new server after a previous server has been destroyed?
I am trying to allow my users to be able to host servers for my game. Hosting works great, until a user decides to stop their server, and then start a new one. The game does not allow this to happen, and calls a network error:

> StartServer listen failed.

How do I get around this error?

---

Here is my current code for disabling the current server and starting a new one:

```
//disconnect client/server
NetworkManager.networkManager.Disconnect ();

//set the port
NetworkManager.networkManager.networkPort = port;
//start the server
NetworkManager.networkManager.StartServer ();
//set the map
ServerInfoManager.serverInfoManager.ChangeMap (map);

```

Here is `NetworkManager.Disconnect()`:

```
public void Disconnect () {
    if (isServer == true) {
        StopServer ();
    }

    if (isClient == true) {
        StopClient ();
    }
}

```

The `isServer`, `isClient`, `args[]`, and `port` variables have been set before these code sections.

# Answer
> 1 votes
Figured it out myself. This was a Unity glitch and it has been patched in Unity version 5.6

---
Tags: unity, c#, networking, server, client
---


# Question
Title: Required initial velocity (fixed launch angle) for projectile to hit a target
The scenario:

I have an enemy tank (AI) chasing my friendly tank (player). When the enemy gets close enough he tries to shoot the player. Now the enemy prefab has an empty game object attached as a child which is used as the projectile (shell) spawn point. It's tilted 10 degrees up (X axis, the actual value in inspector is 350).

Example:

Now I'm trying to figure out what velocity or force must I apply to the projectile in order to hit the player. The angle is fixed (10 degrees) and is always the same. I have tried using the equation (from wikipedia):

Which I solved for `v` and got:

and translated into code which looks like this:

```
private float requiredForceToHit(Transform target)
{
    float turretAngle = 360.0f - this.turretTransform.eulerAngles.x; //Turret is 10 deg tilted up (350 in inspector)
    float g = Physics.gravity.magnitude; //G force
    float y = 0.0f; //Height of the target
    float x = Vector3.Distance(target.transform.position, this.turretTransform.position); //distance to hit, slight off because turret is lifted up

    float tanG = Mathf.Tan(turretAngle);
    float upper = Mathf.Sqrt(g) * Mathf.Sqrt(x) * Mathf.Sqrt(tanG * tanG + 1.0f);
    float lower = Mathf.Sqrt(2 * tanG - ((2 * y) / x));

    float velocity = upper / lower;

    return velocity;
}

```

But the projectile falls short from the target. It does launch farther when farther away but the farther away the target the more distance between the point of shell impact and the actual target. What I'm trying to say is that it is pushing with greater velocity the farther away I am but it falls short.

**What is wrong and how do I fix it?**

Appendix:

The actual shooting code:

```
private void fire(float force)
{
    Rigidbody shellInstance = Instantiate(this.shell, this.turretTransform.position, this.turretTransform.rotation) as Rigidbody;
    shellInstance.velocity = this.turretTransform.forward * force;
}

```

# Answer
\[Reposted as an answer, at the asker's request\]

`turretAngle` is in degrees, so you need to convert it to radians before passing it to `Mathf.Tan`.

Rather than doing the math that way, and having to "just know" that `360 - this.turretTransform.eulerAngles.x` is the angle, you could use the components of `this.turretTransform.forward` to calculate `tanG` directly. That would be

```
Vector3 forward = this.turretTransform.forward;
float tanG = forward.y / Mathf.Sqrt(forward.x * forward.x + forward.z * forward.z);

```
> 2 votes

---
Tags: unity, physics, projectile-physics, trajectory
---


title: Cutting up a Sprite sheet to frames

text:
# Question
Title: Cutting up a Sprite sheet to frames
*I'm new to game development, so please be kind if this is a very simple question.*

I have a Sprite sheet with 18 frames of the same character (6 col x 3 rows) moving slightly. I want to get the frames cut out of the sheet into cocos2dx project. There is no xml or plist defining the boundaries but obviously I want the Sprite to be in the same place as it animates as it's an idle action. What's the quickest way to get the frames? I tried texture packer but it seems designed to build a sheet not unpack one?

# Answer
what are you looking for is ShoeBox sprite sheet editor.
> 1 votes

# Answer
This probably isn't answering much, but if you take a look at Coco's documentation, they explain how to do so with SpriteFrame. It's also done with a mixture of Rectangles it seems.

So it looks like you need to initialize a sprite frame, and mark it with the correct rectangles. Store it in a vector or , rinse and repeat. It might seem a bit redundant, but truth of the matter is that this is the most graceful thing I have seen for 2D APIs. :/

I guess if you want it to be specific for each file you load in, than you'll need to add that feature yourself. Most of the time, the sprite rectangles are the same size, with the sprite centered correctly enough that they won't move.

I hope this helped!

http://www.cocos2d-x.org/reference/native-cpp/V3.1rc0/d3/d35/classcocos2d\_1\_1\_sprite\_frame.html

http://www.cocos2d-x.org/wiki/Sprite\_Sheet\_Animation
> 0 votes

---
Tags: cocos2d-x, texture-atlas
---


# Question
Title: Shadows are choppy on Android, but look fine in Unity Editor on my PC
Here is a gif of what I'm seeing with my shadows on my Android device:

https://gfycat.com/VapidTestyFrigatebird

That shadow looks perfectly fine from any angle / distance in my Unity editor, however. I don't know much about shadows in Unity yet, but here's a bit more info about my settings:

**Directional Light Settings**

**Shadow Quality Settings**

Has anyone experienced an issue similar to this before? How do I fix this shadow choppiness?

# Answer
If I remember correctly shadow cascades aren't supported (yet) on Android / Mobile.

Try disabling the shadow cascades.
> 1 votes

---
Tags: unity, android, lighting, shadows, settings
---


title: Map Positions in LibGDX

text:
# Question
Title: Map Positions in LibGDX
I am developing an RPG game where there is a main world map, locations such as towns or ruins on that map and buildings in those locations where players can interact to go into. For example, I have a map and my character goes to a local town where there is a inn that I can freely enter and interact in. Once I wish to leave the building, I leave and I'll be at the same position that I had once entered the building from, albeit facing the opposite direction. The one problem that I have with imagining a map system that could be complex like this are the coordinates. Is there a way of accomplishing this with the use of universal coordinates, such as only one x and y position throughout all 3 stages of this map system, or would I need to have 3 coordinates, a Map coordinate system for the world map, a Local coordinate system for the town or ruin and a Temporary coordinate system for when I am in a building? Also, is there something in libGDX that could help out with this?

# Answer
Use user data in your tiled map. If you use tiled, you can create object layers and use the objects as spawn and teleport points. For instance, when you exit a cave, you have a spawn point object on your main map set as exit\_cave, then set the player position to the exit\_cave x and y.

If you're not using a tiled map, I suggest creating a map class and create a hashmap using a string and vector2 for each map you have loaded. That way when you exit a cave, you can easily get the position of the exit from your map to be loaded.

Example. At init: create instance of map class, Main map and Cave map. In your Main map hashmap, put two objects. \<"Cave\_enter", new vector2 (0,5)\> and \<"cave\_exit", new vector2 (0,4)\>. In your cave map hashmap, put two objects. Main\_enter and main\_exit. When you want to change from main to cave, load the cave map and set the player position to Main\_enter. When you leave the cave, load the main map and set player position to cave\_exit.

Sorry if this is confusing to you. English isn't my first language
> 1 votes

---
Tags: libgdx, software-engineering, coordinates
---


# Question
Title: LibGDX - Turning TiledMapTiles into objects
I'm working on a harvest moon type game and I've already created lots of assets and have a working player. Now the issue is with the tile map. I use Tiled Map Editor to make the map and it renders fine.

But if I want to be able to turn grass into farmland and plant seeds and such to allow crops to grow, how would I do that?

It would be rather simple using different classes like a `Farmland` and `Crop` class and make so that `Farmland` has a `Crop currentCrop;` attached to it. But putting this together while still using a Tilemap editor seems rather difficult, since I don't actually get any Tile objects from the .tmx.

The way I could do it with Tiled is in my `MapManager` class I could have a

```
public void setCell(int x, int y, int type) {
    Cell cell = new Cell();
    switch(type) {
    case 0:
        cell.setTile(map.getTileSets().getTile(0);
    break;
}

```

etc.

But it feels like that would be a pain to keep track on how much thing have grown and so on and just feels like a clumsy system.

Am I going about this the right way?

Thanks in advance!

# Answer
> 0 votes
If anyone else wonders the same thing, instead of directly editing the tile map itself you just add objects above it.

For example have a `Farmland` class and when using let's say a `Hoe` you add a new object to an `ArrayList` which keeps track on all your placed objects in the game which could be anything. A tree, farmland, furniture etc.

Then to get the tile, add a method which checks if a temporary `Rectangle` collides with one of the `Rectangle`'s in your object list.

---
Tags: java, libgdx, tilemap, tiled
---


# Question
Title: Pathing-finding with teleporting squares
So I see one other question of this nature, but it doesn't answer my question, so I figured I'd ask another. I have a simple game, that includes a grid, and the ability to create a maze with walls and portals. Simply enough a portal is a 2-way portal connecting 2 nodes, and a wall makes the node unpassable. I've been doing path-finding with A\*, knowing my heuristic wasn't perfect and I'd occasionally get less-than-optimal paths, and I'm OK with this for now, but I've had a few instances where solvable paths, show with no solution.

Here is a quick example of a path my algorithm can't solve:

```
   A B C D E F G H I
1> - - - - - - - s -
2> - w w w w w w w p
3> - w - - - - - - -
4> - w - - - - - - -
5> p w - - - - - - -
6> w - - - - - - - g

s - start
w - wall
p - portal
g - goal

```

When I'm evaluating potential neighbors in A\*, I wrote in that portal nodes should only evaluate their neighbors if they came from a portal, otherwise their only neighbor is where they teleport to. This prevents evaluating node I-3, from I-2 getting there from I-1 (because I-1 isn't I-2's connecting portal), so that's not valid.

However because of the nature of A\*, when I get around to evaluating I-2 coming from A-5 it gets thrown out, since that's not the fastest path to I-2. So I never actually get a path to I-3, and never get a path to the goal. I've been thinking through several tweaks that handle this case as well as every other case, but haven't come up with anything. If it helps I can post my code, but it's basic A\*, with the assumption of not evaluating nearby nodes unless the parent is a portal.

Any thoughts on how I can tweak my algorithm to handle these cases (and of course not break for every other case)?

Edit: The code isn't too long, so I'll just go ahead and post it in it's entirety:

```
private static int heuristic(Node current)
{
    return Constants.MapSize.Y - current.simplePos.Y;
}

internal static List<Node> findBestPath(Node[,] nodes, List<Node> startNodes, List<Node> goalNodes)
{
    List<Node> available = new List<Node>(startNodes);
    HashSet<Node> visited = new HashSet<Node>();
    Dictionary<Node, Node> cameFrom = new Dictionary<Node, Node>();
    Dictionary<Node, int> gScore = new Dictionary<Node, int>();
    Dictionary<Node, int> fScore = new Dictionary<Node, int>();

    foreach(Node n in startNodes)
    {
        gScore[n] = 0;
        fScore[n] = heuristic(n);
    }

    while (available.Count != 0)
    {
        Node current = available.OrderBy(n => fScore.ContainsKey(n) ? fScore[n] : int.MaxValue).First();
        if (goalNodes.Contains(current))
        {
            List<Node> bestPath = new List<Node>();
            bestPath.Add(current);
            while (cameFrom.ContainsKey(current) && !startNodes.Contains(current))
            {
                bestPath.Add(cameFrom[current]);
                current = cameFrom[current];
            }
            return bestPath;
        }
        available.Remove(current);
        visited.Add(current);
        Node currentNodeParent = cameFrom.ContainsKey(current) ? cameFrom[current] : null;
        foreach (Node n in current.getNeighbors(nodes, currentNodeParent))
        {
            if (visited.Contains(n))
            {
                continue;
            }
            int possibleScore = gScore[current] + 1;
            if (!available.Contains(n))
            {
                available.Add(n);
            }
            else if (gScore.ContainsKey(n) && possibleScore >= gScore[n])
            {
                continue;
            }
            cameFrom[n] = current;
            gScore[n] = possibleScore;
            fScore[n] = possibleScore + heuristic(n);
        }
    }
    return null;
}

```

Node.cs:

```
public List<Node> getNeighbors(Node[,] nodes, Node parent)
{
    List<Node> neighbors = new List<Node>();
    if (portal && (parent != null && !parent.portal))
    {
        neighbors.Add(portalsTo);
    }
    else
    {
        if ((simplePos.Y + 1) <= Constants.MapSize.Y && !nodes[simplePos.X, simplePos.Y + 1].wall)
        {
            Node tempNode = nodes[simplePos.X, simplePos.Y + 1];
            neighbors.Add(tempNode);
        }
        if ((simplePos.Y - 1) >= 0 && !nodes[simplePos.X, simplePos.Y - 1].wall)
        {
            Node tempNode = nodes[simplePos.X, simplePos.Y - 1];
            neighbors.Add(tempNode);
        }
        if ((simplePos.X + 1) <= Constants.MapSize.X && !nodes[simplePos.X + 1, simplePos.Y].wall)
        {
            Node tempNode = nodes[simplePos.X + 1, simplePos.Y];
            neighbors.Add(tempNode);
        }
        if ((simplePos.X - 1) >= 0 && !nodes[simplePos.X - 1, simplePos.Y].wall)
        {
            Node tempNode = nodes[simplePos.X - 1, simplePos.Y];
            neighbors.Add(tempNode);
        }
    }

    return neighbors;
}

```

# Answer
The problem here is, that you think of portal as single node - which would be true only if taking the portal would be optional. What you need to do is have (logically, does not have to be physically) two nodes at the portal location. First, the portal start which is only one-way connected to neighbors and to the portals other end node. Second the portal exit which acts as normal node at that location, except it is one way only linked to its neighbours (you can implement the optional portals still by connecting those two nodes of same portal).
tl;dr: instead of one two-way linked node:

```
n <-> P <-> n

```

have two one-way linked nodes:

```
n <- P2e -> n        //and P2s at same location not connected to P2e
     ↑
     | c = 0
     |
n -> P1s <- n        //and P1e at same location not connected to P1s

```

With this setup, the algorithm cannot discard node `A5->I2` simply because it never seen the I2 as exit node.

---

note under line: the `available.OrderBy().First()` has *n(log n)* computational (and likely *n* memory complexity). You can use `.Aggregate()` for *n* computational and *O(1)* memory complexity instead.
> 4 votes

---
Tags: c#, path-finding
---


title: Smooth mesh from voxel grid

text:
# Question
Title: Smooth mesh from voxel grid
Im trying to implement smooth voxel grid meshing using marching cubes algorithm but I dont quite understand how to do the interpolating (I understand that this would solve the problem) to achieve the smooth transitions on the borders between the empty space and filled space.

In the picture above I have rendered my voxel grid cells as cubes. Currently the voxel grid is just a 3d array which stores the values if the cell is empty (0.0) or filled(1.0) (not sure if this is ok, do I need to store each cell corners instead).

When processing marching cubes iteration I have to sample my data at floating point indices e.g. I need to look up if position (3.316, 0.16, 0.5) is empty space / on the surface of the data / inside the data.

Currently I just check the cell value where the position is e.g. (3, 0, 0) for the example above which results with cube mesh.

This shows what I want to do more or less:

# Answer
> 0 votes
I got something working more or less using trilinear interpolation (Wiki).

When the marching cubes vertex is sampled, I look for the neighbouring data in my voxel data, use this data for interpolation described in wiki.

Example: in(3.14, 0.4, 1)

x0 = 3, x1 = 4

y0 = 0, y1 = 1

z0 = 1, z1 = 2

which are used directly in wiki algorithm.

Heres an example of the output I got

# Answer
> 0 votes
The voxel map doesnt contain enough date to go back to the perfect spherical mesh in the image. I have seen a page, searching for voxel spheres, where a guy creates a mesh by expanding outwards from the sphere and averageing it, but his methods arent shown on the page: https://www.cgl.ucsf.edu/chimera/data/falloff-sep2012/falloff.html

The most round antialias you can get from your graph is by keeping only the voxel corners and edges and throwing out all the flat voxel faces. that afterwards gives you kind of a point cloud which can only have the corners of the sphere and not the flat staircase bits, which encourages a better sphere. you cant interpolate backwards from voxel to round shapes very easily, and i think that antialiasing the voxel space is best done by throuwing out all the face voxels and the inner voxels and using only the edge and corner voxels as points of a new sphere/shape. if you can find a poisson disk library for your project, use the described points to make a new sphere, it will be ok. afterwards, to antialias further, all voxels that are not under a higher voxel pointing towards it should also be taken away, i.e. some of the staircases are also made of corner voxels where some of them are above others in flat strata.

---
Tags: 3d-meshes, voxels, interpolation, marching-cubes
---


# Question
Title: Unity look at rotation on one axis only problem
Hey I would like an object to look at another object only at one axis, when I rotate the white cube all around the gray cube (gray has look at script), the gray cube flips as soon as the target passes the middle and is on the right side. How can I fix this, so that rotation is normal.

Below is when the cube (target, white).

Below is what happens when the cube (target) passes on the other side, as you can see by the texture the gray cube flips horizontally.

Below is how it should be (texture shows difference)

Code:

```
    Quaternion lookAngle = Quaternion.LookRotation(targetPos, Vector3.up);

```

Thanks in advance!

# Answer
> 1 votes
Solved it, the working code is below:

```
Vector3 dif = targetPos - transform.position;
    dif.z = 0;

    Quaternion lookAngle = Quaternion.LookRotation(dif, transform.up);

```

---
Tags: unity, c#, rotation, quaternion, angles
---


# Question
Title: Achievement / Upgrade / Unlockable Bonus Calculations
I'm trying to figure out a good way of handling a system of upgrades in a game where multiple upgrades (including things the player can't directly purchase, e.g. achievement bonuses) can affect the same value (e.g. "+X% more income" or "Y% faster production").

I've seen at least three different approaches and I'm not keen on any of them and was wondering if there was another pattern that would work.

The approaches I know of:

* Keep an array of all possible upgrades, loop over them any time the value needs to be retrieved. Computationally expensive, as the value is not cached.
* Keep a cached value and recompute only when the upgrades are purchased. Requires having a value for every possible modifier as a variable in the code.
* Keep a list of all achievements/upgrades (likely already done) and if-check only the ones relevant. Requires large blocks of code in cases where multiple upgrades affect the same value.

# Answer
> 3 votes
What you'd generally do is make a system that optimizes along the following criteria:

* Easy to implement
* Easy to debug
* Fast enough

To make it easy to maintain, put it in a class:

```
class Upgrades
{
    void Add(Upgrade u)
    void Remove(Upgrade u)
    float GetSpeedBonus()
    float GetProductionBonus()
    float GetIncomeBonus()
}

```

As you can see from the class interface, there's never a need to iterate through all possible updates. You need to tell the code if a new update applies, and telling the code means telling the `Upgrades` class (if you don't want to create a mess of spaghetti code). You do not "enable" an upgrade by setting a magic flag on an achievement. You enable an upgrade by telling the `Upgrades`class that the upgrade is enabled.

How you optimize the code inside the class is then pretty much irrelevant: it's a problem you can solve when it becomes a problem. If you want solve it, you solve it by caching values for speed, production, income, etc.

A possible pseudocode implementation looks somewhat like this:

```
public class Upgrades
{
    public void Add(Upgrade u)
    {
       // toDo: if some kind of update can or cannot
       // be added multiple times, implement that here
       _container.Add(u);
       RecalculateCache();
    }

    public void Remove(Upgrade u)
    {
       _container.Remove(u);
       RecalculateCache();
    }
    public float SpeedBonus() { get { return _speed; } }
    public float ProductionBonus() { get { return _production; } }
    public float IncomeBonus() { get { return _income; } }

    void RecalculateCache
    {
       // this can be a very complicated function depending on
       // the rules you have for combining different upgrade types
    }
}

```

A tempting optimization is to change the code to only do a partial recalculation of the cache on adding or removing a update. The downside of such an optimization is that changing the formula for aggregating updates will become much more challenging. It is likely that the formula will be changed at some point, e.g. to ensure the effects of upgrade "foo" and upgrade "bar" don't stack. So I advise against this particular optimization, unless updates change excessively often (multiple times per frame). A more worthwhile optimization may be a way that enables/disables the recalculation of the cache while multiple updates are being added.

# Answer
> 0 votes
Have you think about implementing a Decorator pattern in here?

Every unlocked bonus would then "decorate" a specific property regardless of the number of modifiers already unlocked and active.

With such a system you'd be able to add bonuses on the fly, activate them, deactivate them, and have an efficient and precise computation.

Also, even if computation time won't be that long, as you seem to want optimization when possible I guess you can even put the bonus value in cache every time a property gains/loses a layer of decoration.

# Answer
> 0 votes
The best way I know right now is using `Dictionary<IUpgrade>`. Now you don't have to loop, you just need to get an appropriate key when you need this upgrade. I would suggest using an `enum`, because you can simply make it `[Serializable]` if it was `private` (I mean the field of class, not enum declaration - it should be public) and chose appropriate type for a key in this dictionary. Also, in the editor it's easy to choose the type for an item or some shop or anything, even in code. You can get a key by casting an enum to (int). Performance: very good, as an enum is `int` after compilation, though don't use an enum for a key without casting - it has much worse performance.

Now you have to implement behavior where you get right data for right event. For example, you have an event `public class Payment` for which you need to take into acount an `income % bonus`, you go to Player that has this dictionary and say to him - hey give me a data for `income % bonus`. `IncomeUpgrade incomeUpgrade player.GetUpgrade<IncomeUpgrade>(UpgradeType upgradeType);` \- though I would do it not in Player class (In some component player has), it's just an example. Now that you have it, you can give player his payment with `PayPlayer(Player player) { here you use code above - then : player.TakePayment(standartPayment * incomeUpgrade.percent + incomeUpgrade.bonusGold) }` where `UpgradeType` is an enum.

```
public T GetUpgrade<T>(UpgradeType upgradeType){
    return upgradeComponent.DictionaryOfUpgrades[(int)upgradeType] as T;
    // If you don't want to cast an object by as T look at this question,
    // I have the same problem: [Without Object Cast][1] , though you shouldn't really care about casting because it's done once in a time and it will mean nothing to performance.
    // In my case I have 100000 calls per second, 1666 calls per frame.
    // Also if you look at this benchmark [Type Cast Performance][1] - casting even 1 million takes only 0.5+- ms.
    // I guess I shouldn't worry about this at all too, but I'm just curious about the ways it can be implemented.
}

```

Without Object Cast

Type Cast Performance

I will write here other solution without using enum mb, because for every class you would have to add new upgradeType in enum, but for now it's the most performant way. No O(n) or something like this, just O(1) with Dictionaries and components.

---
Tags: c#, achievements
---


# Question
Title: Restrict Up/Down rotation, detect angle upwards/ downwards
I have an object using Quaternion.LookRotation() to look at target object, I would like to be able to restrict the rotation by being able to set the range that the object can rotate at, for example from 45 degrees to 180 degrees, this would mean the object does not rotate lower than 45 degrees and does not rotate higher than 180 degrees, currently my code looks like this:

```
void Start(){
    baseRotation = transform.localEulerAngles;
}
    Vector3 targetPos = Target.position;
    Vector3 dif = targetPos - obj.position;
    dif.z = 0;

    Quaternion lookAngle = Quaternion.LookRotation(dif, obj.up);
    print("angle: "+ Quaternion.Angle(lookAngle, Quaternion.Euler(baseRotation)));
    if (Quaternion.Angle(lookAngle, Quaternion.Euler(baseRotation)) < rangeMax - rangeMin)
    {
        targetR = lookAngle;
    }
        obj.rotation = Quaternion.Lerp(obj.rotation, targetR, Time.deltaTime * 100);
}

```

However this code makes sure that rotation both upwards and downwards equally does not exceed the same angle, which is not quite what I want, as I said I would like to set the start angle and the end angle. How would I do that? Could you post the code that would give me an idea?

Thanks in advance!

# Answer
> 1 votes
With the somewhat limited info you wrote, you could try:

1. Calculate 3D points (or 2D) for the edge *Target.position*'s, by the allowed maximum angles (-45 and +180 degrees).
2. Resolve a point exactly in the middle of those two points.
3. Grab the Quaternion.LookRotation for that point.
4. Calculate the maximum diverge angle by: (-45 + 180) / 2 = 112.5 degrees.
5. Always compare (using Quaternion.Angle) to that quaternion.

The only diference would be that -45 and +180 degrees now are relative to an angle 67.5 degrees (instead of 0), so diverging in either direction with 112.5 degrees will hit the limit. Ie. you don't need to know in which direction it happened, as you "are in the middle".

# Answer
> 0 votes
To clamp a rotation on just one axis:

1. convert your quaternion to euler angles
2. use `Mathf.clamp` on the axis you want to limit.
3. convert it back to a quaternion

Example:

```
 Vector3 eulerRot = lookAngle.eulerAngles;
 eulerRot.y = Mathf.clamp(eulerRot.y, -45f, 180.0f);
 lookAngle.eulerAngles = eulerRot;

```

---
Tags: unity, c#, rotation, quaternion, angles
---


title: Move car at same speed

text:
# Question
Title: Move car at same speed
I want to move car on each game play run with same speed. At present I was getting each time different velocity. I want to fix that.

Here is game play area on which I was moving car:

At present I was moving car in infinite motion without any kind of control. When it collide with wall, it will its direction based on collision calculation.

Here is my source code that I was using to move car:

```
void Start ()
 {
     direction = new Vector2 (Random.Range (-1f, 1f), Random.Range (-1f, 1f));
 }

 void FixedUpdate ()
 {

     float angle = Mathf.Atan2 (direction.y, direction.x) * Mathf.Rad2Deg;
     float targetRot = Mathf.LerpAngle (myRigidbody.rotation, (angle - 90f), 0.1f);
     myRigidbody.MoveRotation (targetRot);

     myRigidbody.velocity = direction * speed;
//        myRigidbody.MovePosition (myRigidbody.position + direction * Time.deltaTime * speed);

     Debug.Log("vel mag: " + myRigidbody.velocity.magnitude);
 }

 void OnCollisionEnter2D (Collision2D other)
 {
     ContactPoint2D contact;
     contact = other.contacts [0];

//        direction = 2 * (Vector3.Dot(direction, Vector3.Normalize(contact.normal))) * Vector3.Normalize(contact.normal) - direction; //Following formula  v' = 2 * (v . n) * n - v

//        direction *= -1;// Dont know why I had to multiply by -1 but it's inversed otherwisae
     Vector2 reflectedVelocity = Vector2.Reflect(direction, contact.normal);
     direction = reflectedVelocity;
 }

```

At present on each run of car, I was getting different velocity that I have checked via debug statement. So my target is to move car with same speed always.

# Answer
Try replacing your random direction with

```
float angle = Random.Range(0f, 2f * Mathf.PI);
direction = new Vector2(
                  Mathf.Cos(angle),
                  Mathf.Sin(angle)
               );

```

This will ensure the direction always has unit length, avoiding the singularity where both x & y get a random value of 0. It also selects directions with uniform probability, compared to normalizing a random value in a square, which is biased toward the diagonals of the square.
> 2 votes

---
Tags: unity
---


# Question
Title: FBX model from Blender doesn't show it's surface in Unity3D
I've create a model from Blender and exported it as .FBX file. However when I import this into Unity, the surface is missing.how can i fix?

Screenshot attached:

in Blender it look like this:

in Unity it look like this which only shows it inside:

# Answer
3D objects are made up of a collection of vertices (points in space) that are used to create what we call 'faces' or 'polygons'. Usually, these faces only have 1 visible side. We do this because in normal circumstances we dont want to render the inside of the object (think about a rock, we want to see the outside of the rock, but not the inside). Which side of each face is visible is decided with what we call normals. If you click on the link you can see the blue lines reprisenting the direction of the faces. In your case, the blue lines will be pointing towards the inside of the sphere.

This problem is most easily fixed in Blender. You need to invert the direction of the normals.

In edit mode select ALL the faces of your mesh ‣ Tool Shelf ‣ Shading/UVs ‣ Shading ‣ Normals: Flip Direction
> 2 votes

---
Tags: unity
---


# Question
Title: Does Unity support tree data structures?
I'm really confused. Is it possible to use trees like binary trees or data structures in Unity?

I need to introduce artificial intelligence into my game, and use the A\* algorithm.

# Answer
> 2 votes
Sure it's possible to use trees! Just to name a few, we use...

As Tyyppi\_77 notes in a comment above, it's hard to imagine a useful programming system in which it's *not* possible to use trees. Have you encountered any difficulty implementing a particular tree-based algorithm that you're looking for help with?

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


# Question
Title: How to start the game at the same time across two phones?
I am trying to synchronize two devices so that they can start the game at the same time.

The mechanism that I've thought about is that I would use the phones' time and set the intervals at, for example, ten seconds each. Then, when the start button is clicked, it will start the game on the beginning of the next interval. So, as long as the start buttons on both devices are clicked in a short time frame of each other, the game should start at the same time.

For the game, near perfect synchronization is important.

**Will this work**? I am assuming that every phone receives a timestamp from a single source, so that internal clocks are at the same time.

If that doesn't work, what is an alternative/better solution to offline multi-device synchronization?

# Answer
The best resource on how to do all kinds of synchronization of advanced physical simulations over unreliable networks in games is the excellent blog posts/articles of Mr. Glenn Fiedler.

You can find it here, and the spesific article you want is here. Search for the topic "Measuring Round Trip Time" in that article.

To summarize (copied verbatim):

> 1. For each packet we send, we add an entry to a queue containing the sequence number of the packet and the time it was sent.
> 2. Each time we receive an ack, we look up this entry and note the difference in local time between the time we receive the ack, and the time we sent the packet. This is the RTT time for that packet.
> 3. Because the arrival of packets varies with network jitter, we need to smooth this value to provide something meaningful, so each time we obtain a new RTT we move a percentage of the distance between our current RTT and the packet RTT. 10% seems to work well for me in practice. This is called an exponentially smoothed moving average, and it has the effect of smoothing out noise in the RTT with a low pass filter.
> 4. To ensure that the sent queue doesn’t grow forever, we discard packets once they have exceeded some maximum expected RTT. As discussed in the previous section on reliability, it is exceptionally likely that any packet not acked within a second was lost, so one second is a good value for this maximum RTT.
> 2 votes

# Answer
The delay of an internet network packet is usually \< 100 ms. For a single action like you describe, this difference is usually too short to be noticed.

In comparison, the clock in 2 different phones on 2 different operators is rarely more than 2 minutes (120'000 ms) apart, if you account for time zones correctly.

If you can't - or don't want to - use the internet, you could use wifi direct or bluetooth.

If you don't want to use these either: Do your devices have microphones? If you're up for the challenge, you can have a "beep" based activation, where the game starts as soon as the second device hears the first device beep.

A possibly easier solution is to simply have 2 users press the start button at the same time, with audible feedback so they know the other user started at the same time. That way they would be within 200 ms of each other.
> 0 votes

---
Tags: android, synchronization
---


# Question
Title: Drawing huge amount of tiles in Monogame (XNA) efficiently
I'm asking this question because I haven't found a definitive answer to it.

Let me first of all state a few things about the game and what I have already done. The game is a going to be a RTS set in a procedurally generated world using Simplex noise. The world consists of chunks which are 16 x 16 in size made of sprites that are 64 x 64. I've managed to load and unload chunks dynamically, which works just fine. The world is going to look a bit like Rimworld, so top-down with different layers of sprites (terrain first, transition sprites, trees, decals etc). Newly generated worlds may contain entities that may affect the environment (eg. a village that has become a town) and thereby the chunk. I'm sure this can be calculated using some sort of function, but it's something to take note of.

The **main issue** I have is when I zoom out, more and more tiles are drawn which severely affects the performance. At about 30000 sprites, the draw section takes 8 ms which is half of what is required to run at 60 FPS. And that's just the terrain. I am using texture atlases to limit draw counts (30000 sprites drawn in 6 counts).

The **goal** is to be able to zoom out from town/village/city level all the way to being able to see an entire country. This **has** to be done dynamically (eg. not by clicking on a minimap icon, but just scroll back just like in Supreme Commander).

I've read many articles about this issue, but I haven't found or seen a clear example of where it would work. Here's a list of techniques I have found that are supposed to work:

* Dirty rectangles, as described here, where you only draw new stuff and keep the rest in the backbuffer. This makes a lot of sense, but I am clueless as to how to implement this in Monogame.
* My preffered choice: make extensive use of RenderTargets, as described here, where you draw to a RenderTarget and then save it as a texture. In my case a 16 x 16 chunk consisting of 64 x 64 would create a 1024 x 1024 texture. I really doubt this will work in terms of performance, but the result would consist of highly detailed textures and is also great to use considering the fact that most of it is static (terrain/trees etc), and doesn't change as much. But this also means that everytime a change is made to a chunk, that Texture2D has to be changed using SetData, which from what I've experienced is quite CPU intensive. However if the textures were 16 x 16 it may actually work, and it would also cut down own memory and disk usage.
* Til textures by specifying the SourceRectangle in SpriteBatch. For huge grasslands/oceans this is a plus, since only one sprite is drawn. However for detailed terrain with different colours and different sprites mixed together (biomes and biome transitions) I'm afraid it won't make a huge difference.
* My own solution, which compromises detail, was to use a standard white 64 x 64 tile, give it the colour of the surrounding 4 tiles and then scale it so it covers the 4 previous tiles. The difference here (besides the tile having a plain colour) is that the landscape visibly changed. I should also mention that forests still have to be drawn individually since they aren't perfectly square.

If anyone has any idea on how to tackle this problem, even if it means compromising certain things (such as detail, or using 16 x 16 sprites), I would love to hear it.

# Answer
> 3 votes
I found out that SpriteBatch is not suitable for drawing tiles. One reason is that sprites are meant for **dynamic objects** and are used for multiple purposes. Another reason is that it's incredibly **CPU-bound**, eg. as explained in the description drawing 30.000 objects costs 8 ms (while my chipset maxed out at 30%). Also, up to 3000 sprites may be drawn before a new draw call has to be made to the GPU (batched and all).

The solution was to draw my own tiles using **textured quads**. This in combination with a **VertexBuffer** allowed me to draw up to 500.000 textured tiles in **1 draw call** where the draw method consumed roughly 1/20th of a millisecond. Of course I probably won't have to draw that many, but either way I finally got my GPU to have a workload of 75% at a steady 60 fps.

# Answer
> 4 votes
Graphics cards are optimised to draw a few things lots of times rather than the other way around.

In your case, you have a lot of things (different textures) that you want to draw a lot of times (number of tiles).

IMO, the simplest optimisations you can do to get significant performance gains are:

1. Combine your texture into atlases. This should significantly speed things up since your graphics card is now only drawing one (or a couple) of textures instead of a lot of small ones.
2. Batch your tiles with SpriteBatch in SpriteSortMode.Texture mode. This will sort your sprites by texture and minimise the number of texture switches to the actual number of different textures. The downside of this approach is that your sprites won't get sorted by depth. Which is presumably fine since your tiles are all at the same depth. I assume you have other stuff as well so it makes sense to have separate a SpriteBatch for tiles and another one for everything else (set to SpriteSortMode.BackToFront).

I would recommend doing both things. Good luck.

---
Tags: xna, monogame, tiles, tilemap
---


# Question
Title: Spawning 5 bullets at once and checking if alive, gives an error
I am developing a game for my University project and came across a problem with pointers. I have a vector of bullets that has every bullet checked for collisions. But, when I try to spawn 5 bullets at once (shotgun shot), it spawns everything correctly, then I go through the vector and check if the bullet is alive. For some reason it finds a NULL pointer or a corrupted data of a pointer. Would be really appreciated if someone knew how to fix this. Thanks!

Bullet check:

```
void Bullet::checkOutOfRange()
{
    if(type == "enemy_bullet")
    {
        if(body->GetPosition().x <= -10.0f)
        {
            alive = false;
        }
    }
    // checks if the body is out of the window size
    else if (body->GetPosition().x > 510.0f || body->GetPosition().x < -10.0f || body->GetPosition().y > 291.0f || body->GetPosition().y < -10)
    {
        alive = false;
    }
}

```

Bullet collision detection:

```
class MyContactListener : public b2ContactListener
{
    void BeginContact(b2Contact* contact) override
    {
        if (contact && contact->IsTouching())
        {
            Entity* A = static_cast<Entity*>(contact->GetFixtureA()->GetBody()->GetUserData());
            Entity* B = static_cast<Entity*>(contact->GetFixtureB()->GetBody()->GetUserData());

            //------
            if((A->type == "player_bullet" && B->type == "enemy") || (A->type == "enemy" && B->type == "player_bullet"))
            {
                Bullet *bullet = nullptr;
                Enemy *other = nullptr;
                if (A->type == "player_bullet" && B->type == "enemy")
                {
                    bullet = dynamic_cast<Bullet*>(A);
                    other = dynamic_cast<Enemy*>(B);
                }
                else if (A->type == "enemy" && B->type == "player_bullet")
                {
                    bullet = dynamic_cast<Bullet*>(B);
                    other = dynamic_cast<Enemy*>(A);
                }
                if ((A && B) || (B&&A))
                {
                    other->bodySprite.set_animation("death");
                    bullet->alive = false;
                    other->alive = false;
                }
            }
        }
    }
}

```

Bullet check in game:

```
    for (auto itr = player_bullets.begin(), itrEnd = player_bullets.end(); itr != itrEnd; ++itr)
    {
        (*itr)->checkOutOfRange(); // go to declaration to see where the bullets stop
        (*itr)->bodySprite.set_position((*itr)->body->GetPosition().x, (*itr)->body->GetPosition().y);
        (*itr)->bodySprite.set_rotation((*itr)->bulletDir * 180 / PI);
        (*itr)->moveBullet(20.0f);
        if ((*itr)->alive == false)
        {
            input_world->DestroyBody((*itr)->body);
            delete *itr;
            itr = player_bullets.erase(itr);
        }
    }

```

Shotgun shot spawn:

```
void spawnShotgunShot(float x, float y, float dir, b2World *world)
{
    // maybe bad pointer management?
    Bullet *bullet_ptr1 = new Bullet(x, y, dir, world, "player_bullet", PLAYER_BULLET, ENEMY);
    player_bullets.push_back(bullet_ptr1);
    Bullet *bullet_ptr2 = new Bullet(x, y, dir + 0.5, world, "player_bullet", PLAYER_BULLET, ENEMY);
    player_bullets.push_back(bullet_ptr2);
    Bullet *bullet_ptr3 = new Bullet(x, y, dir + 0.25, world, "player_bullet", PLAYER_BULLET, ENEMY);
    player_bullets.push_back(bullet_ptr3);
    Bullet *bullet_ptr4 = new Bullet(x, y, dir - 0.5, world, "player_bullet", PLAYER_BULLET, ENEMY);
    player_bullets.push_back(bullet_ptr4);
    Bullet *bullet_ptr5 = new Bullet(x, y, dir - 0.25, world, "player_bullet", PLAYER_BULLET, ENEMY);
    player_bullets.push_back(bullet_ptr5);
}

```

And here is a testbuild with the sln in it: Link to testbuild

# Answer
`std::vector::erase` returns a value that points to the next value.

It returns an iterator to the *next* element. You should not keep a pointer to `itrEnd` because all iterators *after* the erased value pointed by the iterator are invalidated.

*But...*

Since `erase` returns an iterator to *the next element*, you should not use `++itr` in the 3rd part of your loop definition, because, if you erase an element, you will *skip* that *next element* because `itr++` is performed at the end of the loop, effectively going to *the next element* twice.

Instead of using a `for` loop, here, use a `while`:

```
auto itr = player_bullets.begin();
while (itr != player_bullets.end())
{
    // stuff
    if ((*itr)->alive == false)
    {
        input_world->DestroyBody((*itr)->body);
        delete *itr;
        itr = player_bullets.erase(itr);
    }
    else
    {
        itr++;
    }
}

```

You update the value of `itr` yourself, whether the item needs to be erased or not.
> 1 votes

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


# Question
Title: How can I represent a tile-based map and related properties on disk?
I'm trying to load a tile-based map in my game. I've been watching SDL tutorials for a while now but they never covered how to represent the map in a file? How can I represent a tile map on-disk in a way that also lets me store information about collision and other properties?

# Answer
> 1 votes
There are several well-used methods.

One of the simplest, to implement and to work with, is to use some sort of **text grid**, used in a lot of roguelikes. Here's an example from puzzlescript:

```
=======
LEGEND
=======

. = Background
# = Wall
P = Player
* = Crate
@ = Crate and Target
O = Target

=======
LEVELS
=======

#########
#.......#
#.....@.#
#.P.*.O.#
#.......#
#.......#
#########

```

Each tile is represented as a single character in a plain text file. One advantage is that you can edit levels using a text editor. You can also use lots of different characters to represent different tile types, so there's some amount of flexibility.

Sometimes you have lots of tile types/properties and not enough ASCII characters to represent them, so another approach is to use **tile IDs**. That is, each tile is represented by an ID number, and the entire map is a 2D array of these numbers, followed by tile definitions. So you might have:

```
1,1,1,2,256,190,...
3,5,7,3,0,0,0,...

1 = Wall
2 = Floor
3 = Grass
256 = Excalibur
...

```

This is how Tiled does it; the actual file could be XML, JSON, or anything that can represent 2D arrays.

Sometimes you could have gigantic maps; imagine a tile-based space game where most of the space is empty but the map is massive. Representing it as a 2D array would be impractical - a 1 million squared map would take one *trillion* elements to represent. Here you may want to go with something like a **sparse matrix storage**, i.e. you only store where interesting tiles are, and not the whole map. There are also certain **procedural generation** techniques you can use to cut down on storage requirements.

# Answer
> 0 votes
Loading the tile map has many different possibilities. Probably the most common is an XML file, but I personally dislike XML files because they are way bigger than they need to be. What I do 95% of the time for this, is have a text file that does a diagram of it. Here is an excerpt from a tile map in one of my own games.

```
~begin
~enemy_rate 50
#
#
#
#       ###
####
#
#
#
#
#
########
#
#
#
#       ^
################
~end

```

They are extremely easy to read with the human eye, extremely fast to load because they are just .txt files, and quite versatile. As you can see, ~begin, means that it is the beginning of a tile map, ~enemy\_rate is a parameter I use to specify things about that map, and ~end means that it is the end. I can have as many of those I want in a file, since they have beginnings and endings in the file.

However, since this is ASCII, you are limited to a total of ~93 different possible drawn ASCII characters. For most cases, 93 different tiles is more than enough, and you could make modifiers, but something to consider.

As for checking for collisions, I have a really basic version in C++ that does this exact job, but it's not perfect. This is what it looks like:

```
bool GameRoom::checkCollision(double x, double y, GameObject * object)
{
    return (getCollGrid((x + object->hitBoxX1) / wallWidth, (y + object->hitBoxY1) / wallHeight) != 0 ||
        getCollGrid((x + object->hitBoxX2) / wallWidth, (y + object->hitBoxY1) / wallHeight) != 0 ||
        getCollGrid((x + object->hitBoxX1) / wallWidth, (y + object->hitBoxY2) / wallHeight) != 0 ||
        getCollGrid((x + object->hitBoxX2) / wallWidth, (y + object->hitBoxY2) / wallHeight) != 0);
}

```

In this example `getCollGrid(x, y)` returns the value at `(x, y)` position; and checks that it isn't 0. I use that in an example game, so it does work.

# Answer
> 0 votes
What you are trying to do is storing a grid of numbers into an array, there is unlikely to be one, best solution. We've used Paolo's example for some projects.

For others we've used something as simple as a bitmap where eacht pixel's color meant a different tile-type. The tile-type determined the properties of the tile. This made the map easy to observe and edit with basic image editors. You could decide to store aditional information in different color channels or in an accompanying file.

# Answer
> 0 votes
**TL;DR** MsgPack

**Long one**

I developed a game and asset management library in ActionScript using msgpack. Msgpack -as its slogan says- is like json but... smaller. msgpack is available on a lot of languages, like C and C++. This is the repository.

There is a counterpart here: although the people recommending me this format was the Python group, I never heard about it before, so I don't know how maintained is right now, but it never failed me.

Another alternatives with their caveats:

1. XML: Usually good and human readable, but pretty heavy for your porpose.
2. JSON: Better than XML, readable almost like XML, but still heavy.
3. Plain array or custom format: The best it can be depending on how good are you coding the serializer and deserializer for it.

I think you will have several layers here (tiled map games have several layers for floor, decals, objects to pick, **objects to collide against**, ceilings, extra effects like clouds... you choose). My suggestion is to think the format carefully, and pack the objects using msgpack as a bidimensional array \[x,y\] or small arrays \[layer\]. This means, somewhere you will have something like this:

```
uint width = 100;
uint height = 100;
uint FLOOR = 0;
uint DECALS = 1;
uint PICKABLE = 2;
uint COLLIDERS = 3; //players and other colliding objects would be here
uint CEILING = 4;
uint EXTRA = 5;
uint[,,] map = new uint[width, height, 6];

map[0,0,3] = (numerical id for your player);

//YOUR NEXT TASK IS TO SERIALIZE AND SAVE THIS MAP VARIABLE INTO A FILE.

```

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


# Question
Title: How can I add my custom mob to my minecraft game?
So, I'm obviously not a very experienced mob maker, so ill just get to the point. after I made a custom mob, I had no idea where to put it, how to make sound, how to make an egg for it etc. would anyone be able to walk me through the process of adding it to my game?

# Answer
> 0 votes
I'm afraid there is quite a bit more to making a minecraft mob than animating it. The behavior, drop table, spawn egg items, interaction events etc all need to be built from scratch (or largely copied from existing mobs, but it still requires code).

Entities are NOT the most basic thing to work with in any version of minecraft, and I would not bother trying to learn it for just this purpose. Instead, learning an application that generates the code for you like MCreator may be a better option.

In the future, do mention the version of Minecraft you are working with, as interface standards have shifted significantly between versions :)

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


# Question
Title: Game Maker 8.0 - Can a local instance's parent object type be changed?
I have an object I am adding in dynamically. The object type is a generic object that has two strings that are executed in the step and draw events using `execute_string(string);`. I find this to be better and more stable than the built-in resource modification functions.

Is there a way to change a local instance's parent object type? I wish to change its type so that it becomes a wall. There will be no conflict in terms of events. I've been reading through the Game Maker 8.0 documentation for some time and haven't been able to find confirmation one way or the other.

It would be greatly appreciated if anyone could solve this issue for me. It would make it far easier for me to deal with my issue.

# Answer
You can't directly change a particular instance's parent because it would violate the concept of inheritance, which applies to *objects* and not *instances*.

*Objects* are the blueprints the engine refers to when computing *instances*' behaviors; only local variables are independent among instances of the same object, while other properties such as `object_index`, the object parent, and so on are referring to the object definition (it would be redundant storing this kind of information multiple times, since its value is the same for every instance of the same object).

Generally speaking, class (read: "object") properties are stored in one places only to be shared among instances; changing even just one of these properties for one instance only will require you to create a new class ("object") in order to store them.

A workaround I can think of is creating as many objects as many parents you need to refer to when creating your dynamic instances: inheritance hierarchy is defined statically, on the other hand the single instances' behavior depends on the `execute_string()` function you provide.
> 1 votes

---
Tags: game-maker
---


# Question
Title: Flipping the game so that the local player is always on the left side of the screen?
I'm making a 1v1 game with each player at one end of the screen. The game is an online client-server game. I would like the local player to be on the left side of their screen and their opponent (the remote player) on the right side. Similar to Clash Royale where the local player is always on the bottom and their enemy always on top.

**What is the easiest way for me to accomplish this?**

Some solutions I've thought of so far:

1. The server checks every time it sends data back to the players that if it's sending the data back to player 2, it flips it before sending it back. I don't particularly like this solution because it will greatly complicate the code, increasing the chances of bugs, and make it less flexible / re-usable in the future.
2. The client checks if it is player 2 and flips the data it received back from the server if it is. I don't like this solution for the same reasons as above.
3. Some camera tricks I don't know about.

# Answer
I found out how to do it. I used this script from the wiki: http://wiki.unity3d.com/index.php?title=InvertCamerahttp://wiki.unity3d.com/index.php?title=InvertCamera

It's in JS and a bit outdated so here's a revised version:

```
using UnityEngine;

public sealed class CameraFlipper : MonoBehaviour
{
    private void OnPreCull()
    {
        Camera.current.ResetWorldToCameraMatrix();
        Camera.current.ResetProjectionMatrix();
        Camera.current.projectionMatrix = Camera.current.projectionMatrix*Matrix4x4.Scale(new Vector3(-1, 1, 1));
    }

    private void OnPreRender()
    {
        GL.invertCulling = true;
    }

    private void OnPostRender()
    {
        GL.invertCulling = false;
    }

```

Now, this will literally flip everything from left to right. Text will become illegible. To prevent certain objects from being flipped by the camera, put them all in a new layer (ie. "Text Layer") and on the flipped camera's culling mask, unselect "Text Layer". This will make the camera not render any object inside the "Text Layer" layer. To get the text to render properly, create a 2nd camera that is not flipped and set the culling mask to only "Text Layer".

Hope that makes sense.
> 0 votes

---
Tags: unity, client-server
---


# Question
Title: LookRotation() make X axis face the target instead of Z
I use LookRotation() in order for an object to look at another, but since I'm using 2D I would like to make the axis looking/facing the target to be X instead of Z. I have the code below currently:

```
Vector3 dif = targetPos - obj.position;
Quaternion angle= Quaternion.LookRotation(dif, obj.up);
obj.rotation = Quaternion.Lerp(obj.localRotation, angle, Time.deltaTime);

```

Now-\>

What I'm trying to achieve-\>

Thanks!

# Answer
I've answered a few flavours of this before.

The basic idea is to chain together two rotations: one that takes the axes you want to align and points them along z+ and y+ respectively, and then the standard LookRotation to take z+ and y+ to the desired destination axes.

For a straight 3D analogue of LookRotation that positions the x+ axis instead of z+, but still treats y+ the same way as ordinary LookRotation:

```
Quaternion XLookRotation(Vector3 right, Vector3 up = default)
{
    if(up == default)
      up = Vector3.up;

    Quaternion rightToForward = Quaternion.Euler(0f, -90f, 0f);
    Quaternion forwardToTarget = Quaternion.LookRotation(right, up);

    return forwardToTarget * rightToForward;
}

```

Or, to keep an object locked in 2D with z+ forward, as in the second link above:

```
Quaternion XLookRotation2D(Vector3 right)
{
    Quaternion rightToUp = Quaternion.Euler(0f, 0f, 90f);
    Quaternion upToTarget = Quaternion.LookRotation(Vector3.forward, right);

    return upToTarget * rightToUp;
}

```
> 4 votes

---
Tags: unity, c#, rotation, transformation, quaternion
---


# Question
Title: How to clip game objects to a rectangular area
I'm trying to figure out how to do this but am coming up short. I'm making a slot machine in unity 2d and would like to clip the tile prefabs when they leave a given rectangular area.

I can't seem to figure out how to do this. All of the references I've found say to use a clipping shader with a mask texture, but it seems like massive overkill to use a masking texture when I just need an easy pre-defined rectangular area.

# Answer
What your are looking for, is called scissor test in OpenGL/Direct3D vocabulary. But unfortunately you don't have direct access to that feature in unity. I've been looking for a solution to same problem a few weeks ago, and I came across people suggesting to use multiple cameras with different render area to simulate this behavior.

Here are some articles that I've found back then, which you can read for further explanations.
> 4 votes

# Answer
If it's a 2D game and you want to clip to some rectangular area, why not just use an overlay with a cutout for the area you want exposed? There would be no runtime tests required. Just place all the tiles, then place your mask layer over top.

This is the same sort of technique that is used for most HUDs. Eg. A border around the edge of the screen.

The caveat would be that your mask would be a static image, so if you want the background outside of the clipping area to be dynamic (such as a generated or animated image), then it will be more complicated and you may need to use another method of clipping like what you or Ali.S has suggested.
> 2 votes

# Answer
I ended up doing something different. I used a shader to clip the sprites I was scrolling to a certain area of screen space. And here's the code for that shader since I know I was looking for it and could never find it.

```
Shader "Sprites/Clipped"
{
    Properties
    {
        [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
        _Color ("Tint", Color) = (1,1,1,1)
        [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
        _ClipX ("Clip X", Range(0.0, 2000.0)) = 0
        _ClipY ("Clip Y", Range(0.0, 1000.0)) = 0
        _Width ("Width", Range(0.0, 2000.0)) = 2000
        _Height ("Height", Range(0.0, 1000.0)) = 1000
    }

    SubShader
    {
        Tags
        {
            "Queue"="Transparent"
            "IgnoreProjector"="True"
            "RenderType"="Transparent"
            "PreviewType"="Plane"
            "CanUseSpriteAtlas"="True"
        }

        Cull Off
        Lighting Off
        ZWrite Off
        Blend One OneMinusSrcAlpha

        Pass
        {
        CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile _ PIXELSNAP_ON
            #include "UnityCG.cginc"

            struct appdata_t
            {
                float4 vertex   : POSITION;
                float4 color    : COLOR;
                float2 texcoord : TEXCOORD0;
            };

            struct v2f
            {
                float4 vertex    : SV_POSITION;
                fixed4 color     : COLOR;
                half2 texcoord   : TEXCOORD0;
                float2 screenPos : TEXCOORD1;
            };

            fixed4 _Color;

            v2f vert(appdata_t IN)
            {
                v2f OUT;
                OUT.vertex = mul(UNITY_MATRIX_MVP, IN.vertex);
                OUT.texcoord = IN.texcoord;
                OUT.color = IN.color * _Color;
                #ifdef PIXELSNAP_ON
                OUT.vertex = UnityPixelSnap (OUT.vertex);
                #endif
                OUT.screenPos.xy = ComputeScreenPos(OUT.vertex).xy * _ScreenParams.xy;

                return OUT;
            }

            sampler2D _MainTex;
            float _Width;
            float _Height;
            float _ClipX;
            float _ClipY;

            fixed4 frag(v2f IN) : SV_Target
            {
                if ((IN.screenPos.x < _ClipX) || (IN.screenPos.x > _ClipX + _Width) || (IN.screenPos.y < _ClipY) || (IN.screenPos.y > _ClipY + _Height))
                {
                    fixed4 transparent = fixed4(0, 0, 0, 0);
                    return transparent;
                }

                fixed4 c = tex2D(_MainTex, IN.texcoord) * IN.color;
                c.rgb *= c.a;
                return c;
            }
        ENDCG
        }
    }
}

```
> 2 votes

# Answer
Thanks ReaperUnreal, your Shader solution is great. Unity changes the Sprites/Default shader with almost every release, but provides the source code available https://unity3d.com/get-unity/download/archive.

One improvement I would suggest... Conditionals in Shaders can be slow because of GPU reasons, so I rewrote the clip test as:

```
c *= step(_ClipX, IN.screenPos.x) * step(IN.screenPos.x, _ClipX+_Width) *
    step(_ClipY, IN.screenPos.y) * step(IN.screenPos.y, _ClipY+_Height);

```

which of course happens just before the return c;
> 1 votes

---
Tags: unity, clipping
---


title: Breakout angle calculation

text:
# Question
Title: Breakout angle calculation
I am making my first game in python and I am really stuck at with a physics problem. The game I am trying to make is a copy of the game Breakout. In Breakout, the player controls a "paddle" at the bottom of the screen, which the ball will bounce off of.

I have got the collision to work, but I want the angle between the ball's direction vector and the "paddle" to have an impact on the angle at which the ball leaves the paddle. How can I make this work? I have tried a lot of things, but I can't get it to work.

In these situations I want the angle to be sharper when the ball hit's closer to the edge of the paddle. How can I calculate and make these angles to work?

# Answer
> 1 votes
If you think in terms of the horizontal and vertical velocities of the ball then this may make the problem more tractable.

So I assume that when a collision is detected that this is handled by adjusting the vertical velocity. The most trivial way to do this would be to invert it so that the ball will start travelling up instead of down. You could for example do this by multiplying the y-velocity by -1. So this gives you the basic bounce, but you want it to bounce differently based on where it hits the paddle so you want to change the x and you velocity by different amounts depending on where the paddle collides with the ball. In the case you describe for example - assuming that you don't want to alter the speed that the ball is travelling you will need to create a function that uses pythagorus's formula to proportionately split the x and y velocities to a new ratio as a function of where it colliding with the bat.

In your example it looks like you want to transfer more of the y velocity to x velocity in your right-hand picture. In your left hand picture it looks like you want to invert the x velocity as well as the y velocity but also redistribute the combined x+y velocity so that more is transferred to the inverted x than the inverted y.

Perhaps a few more examples to demonstrate the desired behaviour across the bat and we could explore some functions?

# Answer
> 1 votes
> ```
> r = d - 2 (d * n) n
>
> ```
>
> where `d * n` is the dot product, and `n` must be normalized.
>
> source: https://math.stackexchange.com/questions/13261/how-to-get-a-reflection-vector

In your case `n` is looking up. To change the angle near the edges, make `n` tilt to the side near the edge.

---
Tags: collision-detection, physics, game-mechanics, python
---


title: how to fix pushing and popping error?

text:
# Question
Title: how to fix pushing and popping error?
when i write a code with begin and end area ,i get this error, though i did it right,am quite sure that EndArea() is executed in the algorithmic flow of the code,and not escaped ,how to fix that??

the summary of the code:

```
 void OnGUI() {
        GUILayout.BeginArea(new Rect(10, 10, 100, 100));
        some code
              -  if (statement)
               -   for {}
                -other
        GUILayout.EndArea();
    }

```

# Answer
Managing resources (clip area in this case could be seen as a resource) is not trivial especially in programs with complex control flow. While this question was originally about debugging a specific case, I would rather suggest leveraging C# tools of handling resources - namely implement the IDispoable interface/pattern and solve the problem universally.
A very minimalist example for clipping could look like this:

```
public class ClipArea : IDisposable
{
    // Track whether Dispose has been called.
    private bool disposed = false;

    public ClipArea(Rect area)
    {
        GUILayout.BeginArea(area));
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if(!this.disposed)
        {
            if(disposing) GUILayout.EndArea();
            disposed = true;
        }
   }

  ~ClipArea() { Dispose(false); }
}

```

*note: implementing IDisposable correctly is not trivial, see linked MSDN page or other renomed resources for details*
This implementation of `ClipArea` can be used within using statement, which ensures freeing resource(=clip), replacing all your `BeginArea`/`EndArea` calls.

```
using(var ca = new ClipArea(new Rect(10, 10, 100, 100)))
{//note opening parenthesis, the syntax is similar to if statement
   //your complex code here e.g.
    some code
       -  if (statement)
          -   for {}
       -other
   //you can also nest using statements or call methods
}//at this point .EndArea() will be called automatically no matter what
 //even when exception was thrown within your code

```

---

important note under line: **do not mix** `using`/`IDisposable` with bare approach - if you manually call `BeginArea` elsewhere you are still responsible to call `EndArea` at correct time, possibly re-introducing the bug. If you do the `using` approach exclusively poping clips *should* never cause problems.
*included code is illustrative - not tested*
> 1 votes

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


# Question
Title: Networking in a strategy, city management game
I'm developing a city management mobile game with its' share of multiplayer elements (leaderboards, achievements, social interactions). It's built using Unity and GameSparks as a backend. I'm a little bit confused on how I should be implementing the networking.

At the end of every in-game month, the game should go through every business building, calculate the revenue (each building generates different amounts of money depending on the number of workers), then add this value to the player's funds. These funds can then be used to continue building more businesses and houses, which increase the population.

I have to save the states for the city (buildings, population, etc) and player (funds, premium currency, etc) in the cloud.

I'm afraid people will exploit the game (due to the leaderboards) if I entrust data with the client, and I feel it would be best to keep the system deterministic, but I'm not completely sure I'm doing the right thing. How would you solve the problem?

# Answer
> 1 votes
**Never trust the client** (If you care about player experience and want to limit the possibility of cheaters, that is).

It seems you already have the right idea by storing the states of all relevant data on the cloud, and keeping it deterministic. Then at the end of each month your cloud server(s) can calculate each player's stats, based on the data already stored.

You want to be careful about how the clients affect the server state. You should maintain a set of rules on the server that validate incoming data.

For example, the server will probably track funds and land area, so if a player wants to place a building, the server should:

1. Verify the player has sufficient funding
2. Verify the placement of the building is valid
3. If valid, adjust the player's funds, building data, and land grid

It gets a little more tricky when dealing with offline play. You will probably want to simulate everything without requiring a response from the server, so players can play without Internet access. You will have to store a queue of actions to send to the server upon a connection, which will then verify the game state. The server can then replicate the game state back to the client--it is the authority.

---
Tags: networking, software-engineering, rts
---


title: Unity procedural smooth normals

text:
# Question
Title: Unity procedural smooth normals
I have a Unity project, which heavily relies on the marching cubes algorithm. Because this algorithm doesn't return the triangles in order, I can only index them in the order they are present in the vertices array.

For example:

```
vertices: {Vector3(0, 0, 0), Vector3(1, 0, 1), Vector3(1, 1, 0)...}
triangles: {0, 1, 2, 3...}

```

Because of this, Unity's `RecalculateNormals` method doesn't work properly and it gives me the following result:

Is there anyway I can make the normals smoother? Keep in mind, that I need to possibly recalculate these vertices everytime the values change, so I can't rely on very heavy methods.

# Answer
> 1 votes
I don't think it's the order in which you generate the triangles that's the problem, but the way you generate your vertices. If you generate a vertex position once for every voxel touching that vertex, then Unity will take that to mean that each of these copies should use its own normal, leading to hard edges between adjacent triangles.

Instead, you want to re-use previously created vertices. Two ways to approach this:

* As you generate each voxel's mesh, keep track of the indices of the vertices it uses. If a vertex you want to generate is on an edge shared with a neighbouring voxel that's already been generated, ask that voxel for the index to the existing vertex, instead of creating a copy.

or

* Each time you create a new vertex, stick it into a dictionary cache, using its position as a key, and its index in the vertices array as its value. When you're about to create a vertex, first look it up in the cache. If it exists, use the existing index instead of adding to the vertex array.

This should reduce the size of your vertices array, and make your normals smooth.

# Answer
> 0 votes
Maybe I can give you a little bit of light in your problem. First of all, the reason, recalculate normal works properly, you problem is in the triangles generation. You are creating each triangle one by one, so it's mean that two triangles placed together don't share any edge and the light is not interpolated between two triangles(this effect is use in low poly games). So the solution of your problem is create the triangles sharing the edges.

Cheers!

---
Tags: unity, 3d, vertex, normals
---


# Question
Title: One dimensional, bi-directional terrain generation
I'm developing one-dimensional terrain generation in my game.

I give the program a seed and based on that I need to be able to walk forwards and backwards on a line that is drawn between a series of points with the same interval but a different height.

So I need a random number generator where I can request both the next and previous number from a given state.

Most PRNGs I can find generate numbers only in the forward direction, and have no ability to operate in reverse. Is there a random generator I can use that can run both forwards and backwards?

# Answer
> 3 votes
It sounds like what you may want is a hash function.

With this you can feed in the "address" or index of a particular spot along your terrain, and get out a corresponding pseudorandom result value that will always be the same for that input.

This lets you scrub both forward and backward along the pseudorandom sequence, as well as load/teleport into any arbitrary spot along it.

Check out Perlin Noise for a well-documented method using this hashing strategy to create smoothly varying random outputs in any number of dimensions.

---
Tags: c#, terrain, random
---