# Question
Title: How to convert isometric screen space coordinates to top-down world coordinates in Unity?
I have 2d grid in a 3d world facing the world up. My camera is setup so it shows an isometric view of the grid.

I want to get the player's input in screen space (cyan) and find the same point on the grid (purple) ignoring the z position which will ultimately select the nearest tile (red square) from the input. I want to do this without using colliders as there could be hundreds of tiles in the same scene.

I want to know how I can project the screen space point into the 2d grid in a 3d world. The image below summarizes what I want to achieve.

# Answer
You can add *one* collider which covers the *whole* grid. You can then use a usual mouse-into-scene raycast. The resulting `RaycastHit` object has a member `Vector3 point` which is the point in world space where the collider was hit.

Assuming your tiles are in a two-dimensional array, each tile is 1 unit in size and the origin of your tilemap is at world coordinates 0:0, you should be able to do something like this:

```
 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
 RaycastHit hit;
 if (Physics.Raycast(ray, out hit)) {
       // check if we actually hit the tilemap and not something else
       if (hit.collider.gameObject == myTilemap) {
           // convert world coordinates into tilemap coordinates
           // This might get a bit more complicated if the assumptions above do not apply
           int tileX = Mathf.FloorToInt(hit.point.x);
           int tileY = Mathf.FloorToInt(hit.point.z);
           Tile hitTile = tilemap[tileX][tileY];

           /* process hitTile */
       }
 }

```
> 2 votes

---
Tags: unity, camera, tiles, isometric, grid
---


# Question
Title: floating health bar above gameObject for 2D mobile game
I know it's been asked a lot but I can't find the best solution for mine this whole day. I'm new in programming, so I have a health bar which is a child of my character which is position above it. My script is working but not the way I want it to. the local position is not decreasing as the health does and the scales size is bigger. Now I have tried several tweeks but I just could not figure it out.

Here is my code attached on the healthbar object :

```
 Vector3 mylocalScale;

void Start() {

    mylocalScale = transform.localScale;
}

void Update() {
    mylocalScale.x = PlayerHealthSystem.PHS.P_Health;
    transform.localScale = mylocalScale;
}

```

this is the current health bar behaviour on how it it decreases which is not I want.

my desired result it should decrease from left to right, can anyone help me to do this and understand how to do it? thanks.

# Answer
Try updating the Origin Point of the health bar that you are scaling to be on the left of the bar. Right now the origin point is in the center (default), which causes uniform scaling on the x-axis. If you set the origin point to the left, the x-axis will scale "toward" it, giving you the intended behavior.
> 0 votes

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


# Question
Title: how to join the body of snake in 2D snake game
i'm making a snake game in javaScript from scratch. The problem is that the snake looks disjoint(see image). How can I connect the body(rectangles) of the snake?

here is the code of drawing snake:

```
    paintSnake(margin) {
    //draws the body of the snake
    this.snake.forEach((egg) => {
      //console.log(egg)
      const isSnakeHead = egg.cellX === this.headCellX && egg.cellY === this.headCellY
      if (!isSnakeHead) {
        this.ctx.fillStyle = "#9ef739"
        this.ctx.fillRect(egg.cellX * this.cellSize + margin,
          egg.cellY * this.cellSize + margin,
          this.cellSize - 2 * margin,
          this.cellSize - 2 * margin)
      }
    })
    //snake head
    // this.ctx.beginPath()
    // this.ctx.lineWidth = 4
    // this.ctx.strokeStyle = "red"
    // this.ctx.rect(this.headCellX * this.cellSize + margin, this.headCellY * this.cellSize + margin, this.cellSize - 2 * margin, this.cellSize - 2 * margin)
    // this.ctx.stroke()
    let head =
    {
      X: this.headCellX * this.cellSize + margin,
      Y: this.headCellY * this.cellSize + margin,
      width: this.cellSize,
      height: this.cellSize
    }

    const args = [head.X,
    head.Y,
    head.height,
    head.width]
    //draw the head of the snake
    if (this.direction === "up") {
      this.ctx.drawImage(
        snakeHeadUpImg,
        ...args)
    }
    else if (this.direction === "down") {
      this.ctx.drawImage(
        snakeHeadDownImg,
        ...args)
    }
    else if (this.direction === "right") {
      this.ctx.drawImage(
        snakeHeadRightImg,
        ...args)
    }
    else if (this.direction === "left") {
      this.ctx.drawImage(
        snakeHeadLeftImg,
        ...args)
    }
  }
}

```

to see the whole code go to: https://github.com/hackasaur/snake-game/blob/master/main.js

i know that the rectangles(body parts) need to be extended in the direction of the next rectangle but how can i achieve this?

# Answer
Assuming that your snake's body is stored in ordered sequence from head to tail:

```
for (let p = 0; p < snake.length; p++)
{
    if (p == 0)
    {
        //use head sprite with your given direction
    }
    else // p > 0
    {
        //check last piece against next piece.
        let o = p - 1;
        let previous = snake[o];
        let current  = snake[p];

        //...these look like {cellX: 2, cellY: 5}

        if (current.cellX == previous.cellX) //they're on the same column
        {
            if (Math.abs(current.cellY - previous.cellY) == 1) //and adjacent rows
            {
                //use vertical body sprite
            }

        }
        else
        if (current.cellY == previous.cellY) //they're on the same row
        {
            if (Math.abs(current.cellX - previous.cellX) == 1) //and adjacent columns
            {
                //use horizontal body sprite
            }

        }
    }
}

```
> 0 votes

---
Tags: javascript, sprites, html-canvas, snake
---


# Question
Title: In Hammer 3.4 where do I find the 'null' texure?
I'm using Valve's Hammer Editor v3.4 to make maps for Counter-Strike 1.6. I want to learn to use the 'null' texture to optimize my map by not drawing surfaces the player won't see, but when I search for it in the list of textures, I don't see it. I'm guessing I'm not loading some WAD that I need, but I'm not sure which one it is.

# Answer
Doing a quick search for "hammer null texture" yields this thread as the very first result. There, user KliPPy says:

> You can find null (and other special textures) in zhlt.wad, by downloading Zoner's Half-Life Tools.

Please remember to search for your keywords when you have a game dev question - you might be surprised how many great answers are already out there!
> 1 votes

---
Tags: level-design, hammer
---


# Question
Title: How does ECS handle systems which need to know more about the environment of the entities it processes?
I'm trying to wrap my head around the concept of ECS (Entity Component System). I think I grasp the concept of the different parts, Entities, Components, and Systems.

**Entities:** Basically just a container for components

**Components:** Data. E.g Transform component holding position, rotation and scale.

**System:** Runs on a subset of entities matching a combination of components. E.g. RenderSystem rendering all entities with a Mesh and a Transform.

What I'm having trouble wrapping my head around is how a system is supposed to assign data regarding the surrounding environment to the components without using global data. And it's probably because of a lack of understanding.

**Example of what I'm getting stuck on:**

Lets say I have a Player entity consisting of, among others, a Transform component. And lets say that there are multiple Zombie entities roaming the game world, which has a Transform and a AIPathfinding component. So I would naturally create a System that operates on Transforms and AIPathfinding to make the zombies chase the player.

My only problem is, how is the system supposed to know where the player is, or if there even is a player within range, without having to grab the player globally? Sure I could pass the player into the creation of the system. But what if along with the player the zombie are also chasing a constantly changing amount of civilians. Do I pass them to the system at creation as well? Or should I have some global way to fetch entities matching a component query, similarly to how the system detemines which entities to operate on?

I understand that this might be entirely up to the implementation of the ECS. But I'm having a hard time finding resources that explains any further that the most basic systems (RenderSystem etc.).

# Answer
My solution to this would be to create a component `AITarget` which marks an entity as something zombies are supposed to attack (like a player or a civilian).

Now the `ZombieAI` system would receive not one but two separate sets of component-tuples. One for all entities with the `Transform` and `AIPathfinding` components and another set with the `Transform` and `AITarget` components. The job of the system would be to find the "best" AI Target for each zombie.
> 4 votes

# Answer
> Entities: Basically just a container for components

Your entity, should only be an id. Usually an int. Not a pointer, but a handler. The ECS will associate components to that id, and will allow you to query them with some criteria returning a set of ids. *This is important.*

---

As usual, ECS lack spatial awareness. They are not the best tool if you want to collide nearby objects, query only the entities that would be visible in camera, or - in this case - find a path to a target.

If your ECS has support for events (attached component, removed component, updated component), you can work around this by keeping track of the positions and holding (ids of) entities in an auxiliary structure.

If your ECS does not have support for events, you can still do it. Attach a component to the entity that should trigger the event. A system picks it up, process it, and then removes it.

Another option is having an ECS that lets you set, on creation, custom containers for particular component kinds. This would allow you to define a custom structure to hold positional information, such that you can query it for locality or proximity.

Thus, you either set a custom container for positional components in the ECS, use an auxiliary structure keeping it in sync with the ECS, or don't store positional information in the ECS at all…

Either way, you really want some form of spatial structure. A grid, a quad-tree or oct-tree, a binary space partition tree… Those are the right tools.

For crowds chasing a target, I would strongly advice to use an Influence Map Pathfinding. The idea is that you will store an influence map, or rather I should say, you will store an influence value in each node of your spatial structure. And this value will represent distance to the target. Then, you query in what node of the spatial structure the current entity is, query the neighbors and that tells you in what direction to move it.

That means you do no need to call a path finding routine to find a path from each member of the crowd to the target. You only need to update the influence map as the target move. It is also possible to have multiple targets, then the influence value is the distance to the nearest.
> 0 votes

---
Tags: c#, monogame, entity-system, entity-component-system
---


# Question
Title: How to edit specific mipmap images in a DDS?
I am looking for a way to edit individual mipmaps within a DDS file. To my knowledge, the NVidia Plugin only lets you create the largest image and then computes the smaller ones automatically. However, the problem is that after long tests with the different available algorithms and sharpening strengths I still think that at least the 2nd and 3rd of the smaller mips could look better if created manually. Is there a way to do so?

# Answer
> 5 votes
I have had some luck by using GIMP 2.8.2 and the DDS plugin for GIMP. It allows for opening, editing, and modifying the main image and the sub-levels, and then saving them. The levels are presented as layers in GIMP. I don't have any experience for the *quality* of the exports, as I've only actually had to use one level of mips in my own projects.

GIMP here: http://www.gimp.org/

DDs plugin: http://code.google.com/p/gimp-dds/

# Answer
> 4 votes
DDS support is standard in GIMP since version 2.10, plugin installation is no longer required.

---
Tags: 2d, graphics, tools, art, dds
---


# Question
Title: Player won't move correctly due to gravity force pushing him into the ground
I am making a tilemap platformer with pygame ad I defined the X and Y movement for the player and also a Y force that represents the gravity force to make it jump correctly. However, when my player falls off to the ground and the game begins, it doesn't move correctly neither to the right nor to the left direction due to the gravity force that keeps pushing him to the down. In addition to that, when the player jumps and i move it to the right, it's like it doesn't recognize the collision with the bottom rect of the wall (see gif below for a visual explanation of that).

I tried disabling that gravity force when the player hits the ground and enable it when the player jumps but it didn't work as expected and I've got problems managing collisions (also, it doesn't make sense to disable gravity, right?)

Here's a gif of the issue i'm facing with:

Here's my Player class:

class Player(pg.sprite.Sprite): def **init**(self, game, x, y): self.groups = game.sprites pg.sprite.Sprite.**init**(self, self.groups)

```
    self.game = game

    self.image = pg.Surface((TILESIZE, TILESIZE))
    self.image.fill(GREEN)
    self.rect = self.image.get_rect()

    self.move_left = self.move_right = False

    self.pos = pg.math.Vector2(x, y)
    self.acc = pg.math.Vector2(0, GRAVITY)
    self.vel = pg.math.Vector2(0, 0)

def jump(self):
    self.vel.y -= 3

def update(self):
    self.vel.x = 0

    if self.move_left:
        self.vel.x = -PLAYER_SPEED
    if self.move_right:
        self.vel.x = PLAYER_SPEED

    self.vel += self.acc

    self.pos += self.vel
    self.rect.x = self.pos.x * TILESIZE
    self.rect.y = self.pos.y * TILESIZE

    if self.vel.y > 0.5:
        self.vel.y = 0.5

    hits = pg.sprite.spritecollide(self, self.game.walls, False)
    if hits:
        if self.vel.x > 0:
            self.pos -= self.vel
            self.rect.right = hits[0].rect.left
            self.vel.x = 0
        if self.vel.x < 0:
            self.pos -= self.vel
            self.rect.left = hits[0].rect.right
            self.vel.x = 0

    hits = pg.sprite.spritecollide(self, self.game.walls, False)
    if hits:
        if self.vel.y > 0:
            self.pos -= self.vel
            self.rect.bottom = hits[0].rect.top
            self.vel.y = 0
        if self.vel.y < 0:
            self.pos -= self.vel
            self.rect.top = hits[0].rect.bottom
            self.vel.y = 0

```

# Answer
You seem to assume the player will only collide with walls when it is moving to the side. I think this assumption causes the shaky sliding as the player also collides with the floor whenever it walks. You may want to rename your `game.walls` to something like `game.obstacles` to reduce the chance of confusing yourself. ツ
> 0 votes

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


title: Trouble Positioning Object In World

text:
# Question
Title: Trouble Positioning Object In World
I have a lightning effect that travels from point A to point B, I am having trouble placing placing point B correctly.

As you can see from the object hierarchy the points (LightningStart, LightningEnd) are nested 3 levels deep. `_parentReaction.affectorWidget.transform.position`is the position I would like the object to be at.

As you can see below I have tried setting the position equal to the other widgets transform, I have also tried using transform.InverseTransformDirection and transform.TransformDirection in varying combinations, I have tried many options the code below is just me going back to basics to see what I missed.

I am not sure even which object I am supposed to call TransformPoint from, the Widget with the effect )(Point A) or the Widget at Point B?

**Given the above scenario how would I position LightningEnd so that is at the same position as`_parentReaction.affectorWidget.transform.position`?**

*I understand this is a very common question and I have read many previous questions related to this but two hours later, I would just like to know how its done so I can understand where I am getting this wrong.*

---

Note: `_controller` is the Widget Running this effect, since it spawns as a child of this I don't need to worry about its position.

```
public override IEnumerator Do(Widget _controller, WidgetReaction _parentReaction)
{
    effect = _controller.GetComponent<Widget_Effect_Comp>().AddEffect(effect);

    while (true)
    {
        start = effect.effectPrefab.transform.Find("LightningStart").transform;
        end = effect.effectPrefab.transform.Find("LightningEnd").transform;

        Debug.Log("End Position : " + effect.effectPrefab.transform.Find("LightningEnd").transform.position);

        //Debug.Log("Widget World Pos : " + _controller.transform.position);
        //Debug.Log("Widget Local Pos : " + _controller.transform.localPosition);

        //Debug.Log("AffectorWidget World Pos : " + _parentReaction.affectorWidget.transform.position);
        //Debug.Log("AffectorWidget Local Pos : " + _parentReaction.affectorWidget.transform.localPosition);

       effect.effectPrefab.transform.Find("LightningEnd").transform.position = _parentReaction.affectorWidget.transform.position;

        Debug.Log("End Position : " + effect.effectPrefab.transform.Find("LightningEnd").transform.position);

     yield return new WaitForSeconds(2f);
    }

}

public class WidgetEffect : ScriptableObject
{
    public string effectName;
    public GameObject effectPrefab;
}

public WidgetEffect AddEffect(WidgetEffect _widgetEffect)
{
    if (!activeEffects.ContainsKey(_widgetEffect))
    {
        GameObject go = Instantiate(_widgetEffect.effectPrefab);
        go.transform.parent = effectContainer.transform;
        go.transform.position = Vector3.zero;
        go.transform.localPosition = Vector3.zero;
        activeEffects.Add(_widgetEffect, go);

        return _widgetEffect;
    }
    return null;
}

```

# Answer
> 1 votes
As @DmGregory pointed out, my problem was I was setting the position of the Prefab inspector reference instead of the Instance I had created In `AddEffect` and by also changing AddEffects Return Type to GameObject, returning `go` instead of `_widgetEffect`

Updated Code Below

```
public GameObject AddEffect(WidgetEffect _widgetEffect)
{
    if (!activeEffects.ContainsKey(_widgetEffect))
    {
        GameObject go = Instantiate(_widgetEffect.effectPrefab);
        go.transform.parent = effectContainer.transform;
        go.transform.position = Vector3.zero;
        go.transform.localPosition = Vector3.zero;
        activeEffects.Add(_widgetEffect, go);

        return go;
    }
    return null;
}

public override IEnumerator Do(Widget _controller, WidgetReaction _parentReaction)
{
    prefabInstance = _controller.GetComponent<Widget_Effect_Comp>().AddEffect(effect);
    start = prefabInstance.transform.Find("LightningStart").transform;
    end = prefabInstance.transform.Find("LightningEnd").transform;

    Debug.Log("End Position : " + end.position);

    //Debug.Log("Widget World Pos : " + _controller.transform.position);
    //Debug.Log("Widget Local Pos : " + _controller.transform.localPosition);

    //Debug.Log("AffectorWidget World Pos : " + _parentReaction.affectorWidget.transform.position);
    //Debug.Log("AffectorWidget Local Pos : " + _parentReaction.affectorWidget.transform.localPosition);
    start.position = _controller.transform.position;
    end.position = _parentReaction.affectorWidget.transform.position;

    Debug.Log("End Position : " + end.position);

    yield break;
}

```

---
Tags: unity, vector, position
---


# Question
Title: How to do you separate or do you separate a Player/Non Player movement, action, behavior states in one or more component?
Assume we are using Finite State Machine, what is the best way to organize states?

Given I have current `StateComponent`, all states are here.

```
MOVEMENT (Parallel) - Can be for player and non player
        [stand, walk, run]
        [forward, backward]
        [left, right]
        [jump, attack]
BEHAVIOR - For non player only
       [patrol, follow, chase, evade]

```

# Answer
It seems like the `BEHAVIOR` should *control* the `MOVEMENT` state, belonging to a different component. The `MOVEMENT` part I tend to call a `Controllable` which can be assigned to a `Player`, or have a `Brain` (`BEHAVIOUR`) component added to the same node, which then sets the controls in a `Think` function.
> 1 votes

---
Tags: fsm, entity-component-system
---


# Question
Title: Why doesn't my Pygame game scroll properly?
When I am clicking the arrow keys, in order to scroll my ground and my lucky block, I cant just press the key and it keeps on going scroll. So I need to press the key every second to get a kinda smooth scroll.

```
from os import environ
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'
import pygame
import config
import spriteSheetLoader as sSL

# Some standard setup variables
scr = config.SCREEN_SIZES[:]
capt = config.CAPTION
clock = pygame.time.Clock()

# load image
sheet = pygame.image.load('img/tiles.png')
sheet = pygame.transform.scale2x(sheet)
tiles = {
    "brown-broken-wall": sSL.loadTileInfo(0, 0),
    "brown-wall": sSL.loadTileInfo(0, 1),
    "lucky-block": sSL.loadTileInfo(0, 24)
}
ground = []
tiles_pos = []
setted = False

pygame.init()

# Setting up our window
win = pygame.display.set_mode((scr[0], scr[1]))
pygame.display.set_caption(capt)

def setup_ground():
    for i in range(15, 22):
        for j in range(0, 50):
            ground.append([j * 32, i * 32, tiles["brown-broken-wall"]])
    tiles_pos.append([14*32, 10*32, tiles["lucky-block"]])
    tiles_pos.extend(ground)

def draw():
    global setted

    win.fill((62, 152, 255))
    if not setted:
        setup_ground()
        setted = True
    for i in tiles_pos:
        win.blit(sheet, (i[0], i[1]), (i[2][0], i[2][1], 32, 32))

    pygame.display.update()

while True:
    clock.tick(40)
    keys = pygame.key.get_pressed()

    draw()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()
        elif keys[pygame.K_RIGHT]:
            for i in tiles_pos:
                i[0] -= 15
        elif keys[pygame.K_LEFT]:
            for i in tiles_pos:
                i[0] += 15

```

# Answer
Try calling `pygame.event.pump()` before the call to `pygame.key.get_pressed()`, to get the latest key states. In the documentation of `SDL_GetKeyState()` it says that one should use `SDL_PumpEvents()`, for which `event.pump()` is a wrapper.
> 0 votes

---
Tags: python, input, pygame
---


# Question
Title: DirectX11 how to use textures and samplers in slots in shaders
I have a system to render many objects, but I don’t know how to render more tan one object with same shader, let me explain:

I have a sphere and a cylinder, but both objects can be rendered by different shaders, example: Shader1: Shader to render object using 1 texture Shader2: Shader to render object using 2 textures

Both objects need to coexist in space, so if I want to render sphere with shader 1 and I use: shader1 resources:

```
context_->PSSetShaderResources(0, 1, &texture);
context_->PSSetSamplers(0, 1, &sampler);
…

```

shader2 resources:

```
context_->PSSetShaderResources(1, 1, &texture);
context_->PSSetSamplers(1, 1, &sampler);
context_->PSSetShaderResources(2, 1, &texture);
context_->PSSetSamplers(2, 1, &sampler);
…

```

in Shader1 the resources are references like this:

```
Texture2D colorTexture: register(t0);
SamplerState sampler: register(s0);

```

And in Shader2 the resources are references like this:

```
Texture2D colorTexture: register(t1);
SamplerState sampler: register(s1);
Texture2D colorTexture: register(t2);
SamplerState sampler: register(s2);

```

But what if I need to use shader1 resource’s in shader2???? How to manage those resources or do I need to replicate shader2 with shader1 registers?? this is the simplest example, this is part of a very much complex system with many many shaders and many textures, but I don’t know in what slot will be setted the resources, this can be absolutely generic, example, slot 5 will be used for texture 1 of shader2… It is possible to render many objects with minimal change of shaders, but the resources could be updated at any time.. I’m using directX11.

# Answer
> 1 votes
There are 2 approaches here. For the samplers, I would probably write a function that basically selects the sampler based upon the index you pass. But I think you will find, that you wont be switching samplers that much within your shader that much, if at all. You're more likely to switch to different shaders for different roles. Limit your samplers for starters until you have a firm grip, I think you will find you will create more shaders than samplers. Also, if you bind a sampler to a shader, then switch the shader, the original sampler is still bound. You dont need a different register per shader per sampler.

Now the 2nd part, in DX11 and DX12 (dx12 is more flexible), you can have texture arrays. Which you compile all your textures into one Shader Resource and reference it via an index. Effectively you can make your UV now UVW, where W is your texture index. This then means you can bind all your textures to one register, and reference this way. I went one step furher and use a constant buffer of lookups, that may return 1 or more texture samples based upon index (this becomes more a material type look up). But referencing the array directly should be enough for you to start.

---
Tags: shaders, directx11
---


# Question
Title: How do I make my level scroll side-to-side as the player moves?
I am trying to figure out how can I make a side-scrolling view in Pygame.

If I am moving right or left, I want the portion of the level shown on-screen to shift to follow the player character.

Here is an animation of my game:

```
import pygame
pygame.init()

window = pygame.display.set_mode((500,500))
pygame.display.set_caption("GET LOAD OF THIES")

# Character class
class players(object):
    def __init__(self,x,y,height,width):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.isJump = False
        self.JumpCount = 10
        self.fall = 0
        self.speed = 5

# enemy class 1
class enemys(object):
    def __init__(self,cordx,cordy,cordheight,cordwidth):
        self.cordx = cordx
        self.cordy = cordy
        self.cordheight = cordheight
        self.cordwidth = cordwidth

# enemy class 2
class enemyss(object):
    def __init__(self,xs,ys,sheights,swidths):
        self.xs = xs
        self.ys = ys
        self.sheights = sheights
        self.swidths = swidths

class lava(object):
    def __init__(self,lavax,lavay,lavawidth,lavaheight):

        self.lavax = lavax
        self.lavay = lavay
        self.lavawidth = lavawidth
        self.lavaheight = lavaheight

# enemy class 3
class enemysss(object):
    def __init__(self,velx,vely,velheight,velwidth):
        self.velx = velx
        self.vely = vely
        self.velwidth = velwidth
        self.velheight = velheight

# Colors
NiceBlue = (0,214, 82)
NiceGreen = (214,0,82)

# FPS
FPS = 60
clock = pygame.time.Clock()

# Defininition for the class player/enemys
playerman = players(50,390,20,20)
enemy1 = enemys(150,390,100,10)
enemy2 = enemyss(320,320,100,10)
enemy3 = enemysss(120,250,100,10)
enemy4 = lava(0,459,500,40)

# Main loop
runninggame = True
while runninggame:
    # Frames per second
    clock.tick(FPS)
    # Exit Event
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            runninggame = False
        #Draw The enemys and Main Characte
    window.fill((0,0,0))
    player = pygame.draw.rect(window, (NiceGreen), (playerman.x,playerman.y,playerman.height,playerman.width))
    enemy = pygame.draw.rect(window, (NiceBlue), (enemy1.cordx,enemy1.cordy,enemy1.cordheight,enemy1.cordwidth))
    soenemy = pygame.draw.rect(window, (NiceBlue), (enemy2.xs,enemy2.ys,enemy2.sheights,enemy2.swidths))
    dudeenemy = pygame.draw.rect(window, (NiceBlue), (enemy3.velx,enemy3.vely,enemy3.velheight,enemy3.velwidth))
    thisanotherenemy = pygame.draw.rect(window, (230,4,231), (enemy4.lavax,enemy4.lavay,enemy4.lavawidth,enemy4.lavaheight))

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        playerman.x -= playerman.speed
    if keys[pygame.K_RIGHT]:
        playerman.x += playerman.speed
    if not playerman.isJump:

        playerman.y += playerman.fall
        playerman.fall += 1
# ----------------------------------------------------- # enem1 collisio
# both of my 2 enemy squares collisions push me back when ever I Jump on the top of them on there sides but when I jump on the middle of of both of them it seems to work if I just want it so when I jump on both of my squares I just don't get pushed back
        player.topleft = (playerman.x, playerman.y)
        collide = False
        if player.colliderect(enemy):
            collide = True
            playerman.y = enemy.top - player.height
            if player.right > enemy.left and  player.left < enemy.left - player.width:
                playerman.x = enemy.left - player.width
            if player.left < enemy.right and  player.right > enemy.right + player.width:
                playerman.x = enemy.right

        if player.colliderect(soenemy):
            collide = True
            playerman.y = soenemy.top - player.height
            if playerman.y > soenemy.left and player.left < enemy.left - player.width:
                playerman.x = soenemy.left  - player.width
            if player.left < soenemy.left and player.right > soenemy.right + player.width:
                playerman.x = soenemy.right
        if player.colliderect(dudeenemy):
            collide = True
            playerman.y = dudeenemy.top - player.height
            if playerman.y > dudeenemy.left and player.left < dudeenemy.left - player.width:
                playerman.x = dudeenemy.left  - player.width
            if player.left < dudeenemy.left and player.right > dudeenemy.right + player.width:
                playerman.x = dudeenemy.right
        if player.colliderect(thisanotherenemy):
            collide = True
            playerman.y = thisanotherenemy.top - player.height
            if playerman.y > thisanotherenemy.left and player.left < thisanotherenemy.left - player.width:
                playerman.x = thisanotherenemy.left  - player.width
            if player.left < thisanotherenemy.left and player.right > thisanotherenemy.right + player.width:
                playerman.x = thisanotherenemy.right

        if player.bottom >= 500:
            collide = True
            playerman.isJump = False
            playerman.JumpCount = 10
            playerman.y = 500 - player.height

        if collide:
            if keys[pygame.K_SPACE]:
                playerman.isJump = True
            playerman.fall = 0
    else:
        if playerman.JumpCount > 0:
            playerman.y -= (playerman.JumpCount * abs(playerman.JumpCount)) * 0.3
            playerman.JumpCount -= 1
        else:
            playerman.JumpCount = 10
            playerman.isJump = False

        # update winodw event
    pygame.display.update()
# quit event
pygame.quit()

```

# Answer
> 0 votes
You'll basically want to define a `Camera` class. In this case you could make it as simple as being only a screen offset, but a zoom factor might be nice too. This camera could then have a function that converts *world coordinates* into *screen coordinates*, which you would call when drawing objects.
The position of this camera could then be changed based on the position of the target it is tracking.

As a side note: You may want to use `Rect`s for your collision detection, that would be provided by your player and enemy classes. `Rect`s have convenient functions like `clip`, `colliderect` and `collidelist` that could make your code a lot simpler.

---
Tags: camera, python, pygame, side-scroller
---


# Question
Title: Why does collision only work sometimes when there are multiple objects in the game?
when i was making a pygame in python for the first time i kinda have a problem where sometimes the player and the object would touch and the game would not close as intended i dint seem to find the solution to this problem mostly it would work but sometimes the collision would occur but the player would clip right through i have tried numerous collision techniques which i have heard but none seem to work as well the problem would still exit

here is my code

```
import math
import pygame
import random
RED=(255,0,0)
BLUE=(0,0,255)
bg_COLOR=(0,0,0)
WHITE=(255,255,255)

pygame.init()
font = pygame.font.SysFont('monospace', 15)
wid=720
hight=600

player_size = [40,40]
flag=0
player_pos = [int(wid/2),hight-2*player_size[1]]

enemy_size = 50
enemy_pos = [random.randint(0,wid-enemy_size),0]

en_list=[enemy_pos]
speed=10
en_num=4
block_evade=0

screen = pygame.display.set_mode((wid,hight))
pygame.display.set_caption('x wing shooter alpha v1')
game_over = False

clock = pygame.time.Clock()
def score_count(block_evade,block_attack=0):
    text = font.render('score:', 1,WHITE)
    text2 = font.render(str(block_evade + block_attack),1,WHITE)
    screen.blit(text,(0,0))
    screen.blit(text2,(50,0))

def game_quit():
     pygame.display.quit()
     pygame.quit()

def spawn_en(en_list):
    delay = random.random()
    if len(en_list)<en_num and delay < 0.2:#
        x_pos=random.randint(0,wid-enemy_size)
        y_pos=0
        en_list.append([x_pos ,y_pos])

def create_en(en_list):
    for enemy_pos in en_list:
        pygame.draw.rect(screen,BLUE,(enemy_pos[0],enemy_pos[1],enemy_size,enemy_size))

def detect_col(player_pos, enemy_pos):
    p_x=player_pos[0]
    p_y=player_pos[1]

    e_x=enemy_pos[0]
    e_y=enemy_pos[1]
    x1=int(e_x+enemy_size/2)
    x2=int(p_x+player_size[0]/2)
    y1=int(e_y+enemy_size/2)
    y2=int(p_y+player_size[1]/2)
    distance =int(math.sqrt((math.pow(x2-x1,2))+(math.pow(y2-y1,2))))

    if(e_x + enemy_size >= p_x > e_x):
        if(e_y + enemy_size >= p_y > e_y):
            return True
    elif(p_x + player_size[0] >= e_x > p_x):
        if(p_y + player_size[1] >= e_y > p_y):
            return True
    elif(distance <= int(enemy_size/2)):
        return True

def fall_en(en_list):
    block_evade=0
    for idx, enemy_pos in enumerate(en_list):
        if enemy_pos[1] >= 0 and enemy_pos[1]<=hight:
            enemy_pos[1]+=speed
        else:
            en_list.pop(idx)
            block_evade+=1
    return block_evade

def col_check(en_list, player_pos):
    for enemy_pos in en_list:
        if detect_col(player_pos,enemy_pos):
            return True
        else:
            return False

while not game_over:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
           game_quit()
           flag=1
           break
    if event.type == pygame.KEYDOWN:
        x = player_pos[0]
        y = player_pos[1]
        if event.key == pygame.K_LEFT and player_pos[0] >= 0:
            x-=10
        elif event.key == pygame.K_RIGHT and player_pos[0] <= wid-player_size[0]:
            x+=10
        elif event.key == pygame.K_DOWN  and player_pos[1] <= hight-player_size[1]:
            y+=10
        elif event.key == pygame.K_UP  and player_pos[1] >= 0:
            y-=10
        player_pos = [x,y]

    if flag != 1:
        screen.fill(bg_COLOR)

    spawn_en(en_list)
    block_evade+=fall_en(en_list)
    if col_check(en_list, player_pos):
        game_over=True
    create_en(en_list)
    score_count(block_evade,0)
    pygame.draw.rect(screen,RED,(player_pos[0],player_pos[1],player_size[0],player_size[1]))

    clock.tick(20)

    pygame.display.update()

else:
    game_quit()

```

# Answer
> 0 votes
You may want to create a `Player` and `Enemy` class that hold their position and size as member variables. These objects could have a `rect()` function that returns a `Rect` based on the position and size of that object. To detect overlap between two of these `Rect`s, you could then call `playerRect.colliderect(enemy.rect())`, which returns `True` if they do.
You could also use `player.rect().collidelist(enemyRects)` instead. This returns the index of the first colliding rectangle in the list, and `-1` when no collision is detected.

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


title: Rect Color Unity

text:
# Question
Title: Rect Color Unity
So I'm drawing a rectangle, but I want to change it's Background color to red because at the moment it just has the background to blue. My code is as such:

```
drawArea = new Rect(0, 0, Screen.width, Screen.height);

```

# Answer
> 1 votes
Rect is not a Drawable thing so you can't assign color to it. The Rect does not contain information for color, Unity Docs ref.

This is something you're going to change when you are drawing that Rect. Let suppose you want to draw button out of it then you do something like this:

```
drawArea = new Rect(0, 0, Screen.width, Screen.height);

 //Changing Button Color to Red.
 GUI.backgroundColor = Color.red;
 GUI.Button( rect, "red button", guiStyle );

//Changing Button Color to Blue.
 GUI.backgroundColor = Color.blue;
 GUI.Button( rect, "blue button", guiStyle );

```

The code is taken from Unity Answers.

I hope this helps.

---
Tags: unity
---


# Question
Title: Best way to implement a class or interface for a set of UI buttons that only differ in their Draw() function?
I have three types of UI buttons that go on a cooldown bar:

1. A traditional cooldown bar button where once the corresponding key is pressed, a timer shows over the button and dims the texture.
2. A button that shows a cooldown, doesn't dim and adds stacks counting upwards to a max (say 5) in the upper left
3. A button that acts like a toggle with no timer, but dims depending on if it's on or off

These all inherit from my AbilityButton class. I'd like to put all three Draw() functions in AbilityButton like:

```
public virtual DrawNormal() {...stuff...}
public virtual DrawStackable() {...stuff...}
public virtual DrawToggle() {...stuff...}

```

... and tell the children to implement the correct one. The problem is that I don't think it's possible to just tell my children to use one of those. From what I've seen, I'd need to make an instance of the parent in each child and call the corresponding method. This just feels weird and wrong - like I'm designing incorrectly to land in this position in the first place.

Is there a better way to do this? Is this better suited for interfaces? One interface per button type? The problem with interfaces is that I want to actually define the method functionality in the parent which interfaces do not allow.

# Answer
If you distinguish these button types by making derived classes for each, I would have the AbilityButton class have an abstract Draw() function and each of the derived classes would then implement the draw function their way. Then you would be able to have a list of AbilityButtons and call their Draw() method, not caring if it is one or the other from the calling code.

And yes, this could even be abstracted to an interface Drawable if you have more classes that should be able to be drawn. Then just have AbilityButton "inherit" from it, without implementing it, which would force the subclasses to do so. (Remember to make your AbilityButton abstract if it shouldn't be instansiable in itself)
> 1 votes

---
Tags: c#, architecture, oop, inheritance
---


# Question
Title: How do I get my team NPC to follow the player? | Game Maker Studio
I would like to have 4 teammate NPC's that would follow behind the Player. First off, I know how to get the movement and collisions working properly but getting the NPC's to follow the player is where I'm struggling.

This code checks if the player's x is greater than the x of the NPC so it can move right.

```
if obj_testPlayer.x > x - 34 { // want it to stop 34 pixels away from the players left
   xspd += 3
} else {
   xspd = 0;
}

```

Once the NPC is 34 pixels away from the Player it will stop, but when the player moves again, the NPC is stationary. Also, when I change this code to check if the player is on the left of NPC; The NPC won't move.

All I'm trying to do is get the NPC moving Horizontally when the player is on the right or the left side of the NPC but it's not working.

# Answer
> 1 votes
So technically, it already follows the player to the right, and you want it to move to the right and left side, while it stops if it gets too close?

In the given context, I think this is all you need:

```
if (obj_testPlayer.x > x + 34) { // want it to stop 34 pixels away from the players left
   xspd += 3
} else if (obj_testPlayer.x < x - 34) {
   xspd -= 3
}
else {
   xspd = 0;
}

```

In such situations, I usually visualise the problem to understand what's going on, similair like this:

```
player.x <  -34    NPC    +34   player.x >
   |         |      |      |       |

```

---
Tags: ai, game-maker, platformer
---


# Question
Title: What is the best way to create a square grid in Unity?
So I need to create a square grid like the one below. And be able to click on a square, the square you chose then is filled with a different color as well as all the squares right and below the square you have chose. My question is what will be the most efficient way to create this grid either in 3D or 2D in Unity.

# Answer
> 1 votes
The component you seem to be looking for is the TileMap.

A complete tutorial would be a bit too broad, and also redundant because there are many good tutorials for it available through your preferred search engine. So here just an overview:

* A tilemap is empty at first. You need to paint tiles on it, either by hand or programmatically.
* In order to do that, you need a tile image first. If you want a grid like this, you should create a sprite which is just a black rectangle with white fill.
* Clicks on tiles can be detected by adding colliders to all tiles or using the technique described here.
* When scripting, the `Tilemap` component allows you to access individual tiles with `tilemap.GetTile` and even has a convenient method for setting the color tint of a tile directly with `tilemap.SetColor`

---
Tags: unity, c#, 2d, 3d, grid
---


title: Mathematical equation for CHOMP AI?

text:
# Question
Title: Mathematical equation for CHOMP AI?
Players take turns in taking a rectangular bite out of the bottom right corner of the bar, by shading a square, tighter with all the squares below and/ or to the right it. The top left-hand square is poisoned, and the player forced to eat the square loses.

How do I determine who is currently winning while the game is being played? (Creating the game in Unity using c#)

# Answer
> 0 votes
For a square grid, there is a strategy which allows the player who is taking the next turn to always win. (it is actually mathematically proven that there is a winning strategy for the first player for *any* width and height except 1x1. But so far nobody found out what that strategy is, except for the special cases of a square board or a 2xn board).

A losing position in this game is any position where the board looks like this:

```
xxxxx
x
x
x
x

```
* The tile to the lower right of the poisoned tile is missing
* The two "arms" reaching horizontally or vertically from the poisoned tile have the same length.

The player who finds themselves in this situation has lost, because whatever the player does, the opponent can return to a game-state like this until there is only the poisoned tile remaining. The player in this situation has only 3 options:

* lose
* shorten the vertical arm
* shorten the horizontal arm

To which the opponent can respond by shortening the other arm so both have the same length again. Now the opponent is back in the same situation. This goes on until both arms are lost and only the poisoned tile remains.

Knowing the strategy for this situation, we can also derive a winning state for the game: "If the board is currently a square larger than 1x1, then the player whose turn it is is winning, because they can pull off the above strategy by taking the tile to the lower right of the poisoned tile."

OK, but how do we determine who is winning if the current player does not have one of the two positions outlined above? Much smarter mathematicians than us have tried to find a strategy and failed. So what can we mathematically challenged game programmers do?

We simply throw our computational power at the problem and brute-force it!

We map each possible move they can make right now and check if it's a winning move or a losing move. And if any moves are inconclusive, we can check all possible moves from there. And if those are also inconclusive, we again check all possible moves. And so on and so on until all branches of the game tree either end in a win or in a lose. That way we can figure out if there is a route through the tree through which the current player can force a win (which means they are winning) or if the other player can do that (they are losing). The number of possible moves in this game is small enough that this is feasible (at least as long as the board doesn't get much larger).

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


title: Client Side Game Local Storage

text:
# Question
Title: Client Side Game Local Storage
I'm coding (or at least *trying* to code) a single player game in pure JS. I was wondering how I was gonna be able to write data without having the user setting up a server or a database, only way I found is local storage.

I'm aware that this kind of data is attached to the browser but I don't think someone would swap between browser, IMHO people start with one and stick to it. What I'm more concerned about is what else in the local system can modify this storage?

For instance, can cleaning up applications remove the JSON I put in there?

# Answer
> 1 votes
Local Storage is very similar to how cookies work. It's basically saving some data locally. These data are only accessible to the same browser on the same machine only.

It may be possible for some browsers to share the same cookies, or export/import, but that's in general the exception.

The user clearing all browser data will wipe out your game's save, which is normal, and users are expecting this for the most part.

If you want users to share their saves across browsers/devices/platforms, then you *need* some way to save that online. There are some libraries that already do that for you, or websites that if you host your game there are willing to let you use cloud saving.

If it's your first game, or you are still learning, I would say to not bother with cloud saving. Making a game is already a difficult task as it is, and supporting cloud saves just adds to the complexity. At the minimum you can have a button to export all saves to a single file, and an import button to import such files, that way if a user wants to keep their save, there is a way to do it.

---
Tags: javascript, storage, client
---


title: Unity - Custom aspect ratio in build

text:
# Question
Title: Unity - Custom aspect ratio in build
I have made a game that was supposed to be for mobile but now I need to build it for PC. I want the aspect-ratio to be 2:3 but as you can see on the image that doesn't exist. How do I add a custom aspect-ratio for the build?

# Answer
> 2 votes
You can programmatically set the aspect ratio.

https://docs.unity3d.com/ScriptReference/Screen.SetResolution.html

Here is some sample code from Unity:

```
using UnityEngine;

public class ExampleScript : MonoBehaviour
{
    void Start()
    {
        // Switch to 640 x 480 full-screen
        Screen.SetResolution(640, 480, true);
    }
}

```

If you want to set it via an aspect ratio instead of a resolution, you can do some math: `Screen.SetResolution(Screen.height * (2.0f / 3.0f), Screen.height, true)`

Here is a generic script that you can run when your application launches. Attach the script to a GameObject in your starting scene, and change aspect ratio in the inspector.:

```
using UnityEngine;

public class AspectRatioManager : MonoBehaviour
{
    [Tooltip("Aspect Ratio to use for game.  If Vector2.zero, the default aspect ratio will be used.")]
    [SerializeField]
    private Vector2 aspectRatio = Vector2.zero;

    [Tooltip("Whether or not full screen will be used")]
    [SerializeField]
    private bool fullScreen = false;

    private void Awake()
    {
        if(aspectRatio != Vector2.zero)
        {
            float x = Screen.height * (aspectRatio.x / aspectRatio.y);
            float y = Screen.height;
            Screen.SetResolution(x, y, fullScreen)
        }
    }
}

```

This code assumes you have a "tall" app on a "horizontal" monitor. Would need to make changes if that were not the case.

StackOverflow also has a nice answer to this question.

---
Tags: unity
---


# Question
Title: Chunk Culling system causes deltatime to slow down
I am making a 2D top-down game in C++ and the graphics library SFML.

I have designed a chunk system by myself and have successfully made it so that when a chunk is off-screen, it isn't rendered, to allow bigger maps to be used without rendering every tile on the map, which would/could cause lag.

All this works fine, but the deltatime is slowed down, I think.

What happens is that the player presses 'wasd', this then moves the map in the opposite direction, e.g. 'w' moves the map down to act like the player is moving up on the map etc.

I'll put the code that handles whether a chunk should be rendered or not:

```
for(std::list<shared_ptr<Entity>>::const_iterator i=this->entities.begin(); i != this->entities.end(); ++i) {
    (*i)->tick(dt, *this);
    if((*i)->id == entityState::player) {
        Handler::playerVelX = -(*i)->velX;
        Handler::playerVelY = -(*i)->velY;
    }
 }

for(std::list<shared_ptr<Map>>::const_iterator j=this->maps.begin(); j != this->maps.end(); ++j) {
    (*j)->x += std::round(Handler::playerVelX);
    (*j)->y += std::round(Handler::playerVelY);
    view.setPosition(-(std::round(Handler::playerVelX)), -(std::round(Handler::playerVelY)));
    int vx = view.getX();
    int vy = view.getY();
    int vw = view.getWidth();
    int vh = view.getHeight();
    for(std::list<shared_ptr<Chunk>>::const_iterator i=this->chunks.begin(); i != this->chunks.end(); ++i) {
        (*i)->tick();
        (*i)->x = (*j)->x + ((*i)->cx * TileSprites::width * TileSprites::scaleX);
        (*i)->y = (*j)->y + ((*i)->cy * TileSprites::height * TileSprites::scaleY);

        int x = (*i)->x;
        int y = (*i)->y;
        int w = (*i)->width;
        int h = (*i)->height;

        if(x + w < vx || x > vx + vw || y + h < vy || y > vy + vh) {
            if((*i)->loaded) { (*i)->loaded = false; }
        } else { if((*i)->loaded == false) { (*i)->loaded = true; } }
    }
}

```

The `view` is the 'camera' that follows the player around the map, which lets me decide where the player is according to the map.

The map has an `x` and a `y`, the viewport `x` is the negative of map `x` and the same for the `y`.

The `(*i)->cx` is the chunks position that corresponds to the initial position of the chunk in the map, whereas the `(*i)->x` is the current position on the screen.

As I said, this all works fine but I thought I should explain the variables.

In the player `tick()`, this is the movement code. Keep in mind that the other keyboard handling is not shown, as this is the part that handles the movement:

```
if(keys[Keyboard::W]) { Player::velY = -180 * dt.asSeconds(); }
if(keys[Keyboard::S]) { Player::velY = 180 * dt.asSeconds(); }
if(keys[Keyboard::A]) { Player::velX = -180 * dt.asSeconds(); }
if(keys[Keyboard::D]) { Player::velX = 180 * dt.asSeconds(); }

```

Below is the main game loop. As this is my first game project, I'm not really sure how to make an engine in c++, although I've used the 'notch' engine in Java, so this engine might be fine but I feel like more is needed:

```
void Game::run() {
    sf::Clock gameClock;
    float lastTime = 0;
    while(window.window.isOpen()) {
        sf::Event event;
        while(window.window.pollEvent(event)) {
            if(event.type == sf::Event::Closed) {
                window.window.close();
            }
        }
        sf::Time dt = gameClock.restart();

        float currentTime = dt.asSeconds();
        float fps = 1.f / currentTime;
        lastTime = currentTime;
        std::cout << "FPS: " << fps << std::endl;

        this->tick(dt);

        window.window.clear(sf::Color(this->backgroundColor));

        this->render();

        window.window.display();
    }
}

```

My problem is: when a chunk or multiple chunks aren't being rendered due to the `(*i)->loaded = false` part, my player moves slower than before, but the FPS that is printed is the same.

---

# The profiler:

## This isnt a HTML snippet I've just put the profiler message there so it doesnt make the question absurdly long.

```
The above isnt a HTML snippet but the profiler.
```

```
 %   cumulative   self              self     total
 time   seconds   seconds    calls  Ts/call  Ts/call  name
 15.62      0.30     0.30                             Chunk::render(sf::RenderWindow&)
 13.02      0.55     0.25                             std::__shared_ptr<Tile, (__gnu_cxx::_Lock_policy)2>::get() const
 10.42      0.75     0.20                             sf::Sprite::operator=(sf::Sprite const&)
  9.38      0.93     0.18                             std::_List_const_iterator<std::shared_ptr<Tile> >::operator*() const
  8.33      1.09     0.16                             std::__shared_ptr_access<Tile, (__gnu_cxx::_Lock_policy)2, false, false>::operator->() const
  7.29      1.23     0.14                             __gnu_cxx::__aligned_membuf<std::shared_ptr<Tile> >::_M_ptr() const
  7.29      1.37     0.14                             __gnu_cxx::__aligned_membuf<std::shared_ptr<Tile> >::_M_addr() const
  6.77      1.50     0.13                             sf::Transformable::operator=(sf::Transformable const&)
  6.77      1.63     0.13                             std::_List_node<std::shared_ptr<Tile> >::_M_valptr() const
  5.73      1.74     0.11                             std::__shared_ptr_access<Tile, (__gnu_cxx::_Lock_policy)2, false, false>::_M_get() const
  2.08      1.78     0.04                             std::_List_const_iterator<std::shared_ptr<Tile> >::operator++()
  1.56      1.81     0.03                             std::_List_iterator<std::shared_ptr<Tile> >::_List_iterator(std::__detail::_List_node_base*)
  1.56      1.84     0.03                             std::operator!=(std::_List_const_iterator<std::shared_ptr<Tile> > const&, std::_List_const_iterator<std::shared_ptr<Tile> > const&)
  0.52      1.85     0.01                             sf::Transformable::setPosition(float, float)
  0.52      1.86     0.01                             sf::Transformable::setScale(float, float)
  0.52      1.87     0.01                             sf::Drawable::operator=(sf::Drawable const&)
  0.52      1.88     0.01                             std::_List_const_iterator<std::shared_ptr<Tile> >::_List_const_iterator(std::_List_iterator<std::shared_ptr<Tile> > const&)
  0.52      1.89     0.01                             std::vector<int, std::allocator<int> >::operator[](unsigned int)
  0.52      1.90     0.01                             std::__cxx11::list<std::shared_ptr<Tile>, std::allocator<std::shared_ptr<Tile> > >::end()
  0.52      1.91     0.01                             __gthr_win32_once
  0.52      1.92     0.01                             _fu19___ZN2sf12RenderStates7DefaultE
  0.00      1.92     0.00     1157     0.00     0.00  Player::tick(sf::Time, Handler&)
  0.00      1.92     0.00     1157     0.00     0.00  Player::render(sf::RenderWindow&)
  0.00      1.92     0.00        4     0.00     0.00  __gnu_cxx::new_allocator<sf::Sprite>::new_allocator(__gnu_cxx::new_allocator<sf::Sprite> const&)
  0.00      1.92     0.00        3     0.00     0.00  std::allocator<sf::Sprite>::~allocator()
  0.00      1.92     0.00        2     0.00     0.00  std::initializer_list<sf::Sprite>::begin() const
  0.00      1.92     0.00        2     0.00     0.00  std::allocator<sf::Sprite>::allocator(std::allocator<sf::Sprite> const&)
  0.00      1.92     0.00        2     0.00     0.00  std::allocator<sf::Sprite>::allocator(std::allocator<sf::Sprite> const&)
  0.00      1.92     0.00        2     0.00     0.00  std::_Vector_base<sf::Sprite, std::allocator<sf::Sprite> >::_Vector_impl::_Vector_impl(std::allocator<sf::Sprite> const&)
  0.00      1.92     0.00        1     0.00     0.00  Entity::Entity()
  0.00      1.92     0.00        1     0.00     0.00  Entity::~Entity()
  0.00      1.92     0.00        1     0.00     0.00  Player::Player(int, int)
  0.00      1.92     0.00        1     0.00     0.00  Player::~Player()
  0.00      1.92     0.00        1     0.00     0.00  Player::~Player()
  0.00      1.92     0.00        1     0.00     0.00  Collision::Collision()
  0.00      1.92     0.00        1     0.00     0.00  __gnu_cxx::__alloc_traits<std::allocator<sf::Sprite>, sf::Sprite>::_S_select_on_copy(std::allocator<sf::Sprite> const&)
  0.00      1.92     0.00        1     0.00     0.00  std::initializer_list<sf::Sprite>::end() const
  0.00      1.92     0.00        1     0.00     0.00  std::initializer_list<sf::Sprite>::size() const
  0.00      1.92     0.00        1     0.00     0.00  std::allocator<sf::Sprite>::allocator()
  0.00      1.92     0.00        1     0.00     0.00  std::_Vector_base<sf::Sprite, std::allocator<sf::Sprite> >::_M_create_storage(unsigned int)
  0.00      1.92     0.00        1     0.00     0.00  std::_Vector_base<sf::Sprite, std::allocator<sf::Sprite> >::_Vector_base(std::allocator<sf::Sprite> const&)
  0.00      1.92     0.00        1     0.00     0.00  std::_Vector_base<sf::Sprite, std::allocator<sf::Sprite> >::_Vector_base(unsigned int, std::allocator<sf::Sprite> const&)
  0.00      1.92     0.00        1     0.00     0.00  std::allocator_traits<std::allocator<sf::Sprite> >::select_on_container_copy_construction(std::allocator<sf::Sprite> const&)
  0.00      1.92     0.00        1     0.00     0.00  std::allocator_traits<std::allocator<sf::Sprite> >::max_size(std::allocator<sf::Sprite> const&)
  0.00      1.92     0.00        1     0.00     0.00  sf::Sprite* std::__uninitialized_copy<false>::__uninit_copy<sf::Sprite const*, sf::Sprite*>(sf::Sprite const*, sf::Sprite const*, sf::Sprite*)
  0.00      1.92     0.00        1     0.00     0.00  std::vector<sf::Sprite, std::allocator<sf::Sprite> >::_S_max_size(std::allocator<sf::Sprite> const&)
  0.00      1.92     0.00        1     0.00     0.00  std::vector<sf::Sprite, std::allocator<sf::Sprite> >::_S_check_init_len(unsigned int, std::allocator<sf::Sprite> const&)
  0.00      1.92     0.00        1     0.00     0.00  void std::vector<sf::Sprite, std::allocator<sf::Sprite> >::_M_range_initialize<sf::Sprite const*>(sf::Sprite const*, sf::Sprite const*, std::forward_iterator_tag)
  0.00      1.92     0.00        1     0.00     0.00  std::vector<sf::Sprite, std::allocator<sf::Sprite> >::vector(std::vector<sf::Sprite, std::allocator<sf::Sprite> > const&)
  0.00      1.92     0.00        1     0.00     0.00  std::vector<sf::Sprite, std::allocator<sf::Sprite> >::vector(std::initializer_list<sf::Sprite>, std::allocator<sf::Sprite> const&)
  0.00      1.92     0.00        1     0.00     0.00  std::iterator_traits<sf::Sprite const*>::difference_type std::__distance<sf::Sprite const*>(sf::Sprite const*, sf::Sprite const*, std::random_access_iterator_tag)
  0.00      1.92     0.00        1     0.00     0.00  sf::Sprite* std::uninitialized_copy<sf::Sprite const*, sf::Sprite*>(sf::Sprite const*, sf::Sprite const*, sf::Sprite*)
  0.00      1.92     0.00        1     0.00     0.00  std::iterator_traits<sf::Sprite const*>::iterator_category std::__iterator_category<sf::Sprite const*>(sf::Sprite const* const&)
  0.00      1.92     0.00        1     0.00     0.00  sf::Sprite* std::__uninitialized_copy_a<sf::Sprite const*, sf::Sprite*, sf::Sprite>(sf::Sprite const*, sf::Sprite const*, sf::Sprite*, std::allocator<sf::Sprite>&)
  0.00      1.92     0.00        1     0.00     0.00  std::iterator_traits<sf::Sprite const*>::difference_type std::distance<sf::Sprite const*>(sf::Sprite const*, sf::Sprite const*)
```

# Answer
> 1 votes
After looking around for a while I have come to another solution, that solution was to use another game loop, I've instead gone for the Gaffer on Games loop, this now works fine but if I go back to the old loop it no longer works.

Here is my new game loop, its not perfect as I havent completely got my head around loops yet, but here it is:

```
double t = 0.0;
double dt = 0.01;

double currentTime = Game::clock.restart().asSeconds();
double accumulator = 0.0;

while ( Game::window.window.isOpen()) {

    double newTime = Game::clock.getElapsedTime().asSeconds();
    double frameTime = newTime - currentTime;

    while(Game::window.window.pollEvent(Game::event)) {
        if(Game::event.type == sf::Event::Closed) {
            window.window.close();
        }
    }
    if ( frameTime > 0.25f )
        frameTime = 0.25f;
    currentTime = newTime;

    accumulator += frameTime;

    while ( accumulator >= dt ) {
        Game::tick(dt);
        t += dt;
        accumulator -= dt;
    }

    Game::window.clear();
    Game::render();
    Game::window.window.display();
}

```

The only part that doesn't make sense to me is the `currentTime` and `newTime`, it seems in my head like they are switched around, but when I do switch them the window doesn't respond.

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


# Question
Title: Trouble with Inventory System and Item References
I'm currently trying to get a simple inventory system to work but I'm having a lot of trouble.

This isn't the exact code I have, but it's a shorter version that I'm pretty sure would function the same:

```
public struct ItemSlot {
    public Item item;

    public ItemSlot(Item item) {
        this.item = item;
    }
}

public class Item : MonoBehaviour {
    public string itemName;
}

public class Accessory : Item {

}

public class Inventory : MonoBehaviour {
    public ItemSlot[] itemSlots = new ItemSlot[1];

    public void AddItem(ItemSlot slot) {
        itemSlots[0] = slot;
    }
}

public class Player : MonoBehaviour {
    public Inventory inventory;

    private void Update() {
        if (Input.GetKeyDown(KeyCode.E)) {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo;

            if (Physics.Raycast(ray, out hitInfo, 20)) {
                GameObject target = hitInfo.collider.gameObject;

                inventory.AddItem(new ItemSlot(target.GetComponent<Item>()));
                Destroy(target);
            }
        }

        if (Input.GetKeyDown(KeyCode.G)) {
            print(inventory.itemSlots[0].item);
        }
    }
}

```

For a bit more prefacing I have a capsule object with the `Player` script on it, an empty with the `Inventory` script on it, which is then attached to the `Player` script (I'm not sure if I want to make the inventory a scriptable object which is why I've done this), and then lastly I have a cube object with the `Accessory` script on it.

So, when I press E and pick up the item it gets added into the player's inventory and then destroyed from the scene. Then, when I press G to display that item in the inventory the console just says `null`. Not `Null`, which is what an actual null would show up as, but the string `"null"`. If I use visual studio's debugger and have a look at what the accessory's base is, it also says null, but for some reason if I then try and print the accessory's name then that works fine, even though that variable is defined in the `Item` class.

If I instead do this in the `Inventory` class:

```
public void AddItem(ItemSlot slot) {
    ItemSlot[0] = slot;
    print(ItemSlot[0].item);
}

```

It works fine and prints `Item (Accessory)` in the console. Even if I print it right after I destroy `target` in the `Player` class, that also prints `Item (Accessory)`, so I have no idea why it doesn't work on the next block of code.

Sorry this is so long and maybe an easy fix, but I'm lost.

Edit: I think everything should be fixed now.

# Answer
You've destroyed the object the Item component was attached to. That destroys the item component too.

For the rest of its lifetime until it's collected by the garbage collector, it will compare as equal to null, print as null, etc. It's effectively become just a tombstone marking the place of a destroyed object.

If you want to keep the thing around, don't destroy it. Or, store a reference to an item archetype data structure on your item component, and when you want to collect the item, store that archetype. Then you can destroy the container item with no problems, because you've already copied out the data about it that you need to use later.
> 0 votes

---
Tags: unity, inventory
---


# Question
Title: Audio Plays A Second Time When Going Back To Menu Unity
I am trying to have my background music keep playing in between scenes, but the music just plays another copy of itself instead of destroying itself to let only one copy play at a time. This is my code :

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

public class MusicManager : MonoBehaviour {

    public static MusicManager instance;

    void Awake() {
        if (instance != null && instance != this) {
            Destroy(gameObject);
            return;
        }

        DontDestroyOnLoad(gameObject);
    }
}

```

I'm not quite sure what I am doing right/wrong so any help is appreciated.

Edit: I found something that works

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

public class MusicManager : MonoBehaviour {

    private static MusicManager instance = null;
    private static MusicManager Instance {
        get {
            return instance;
        }
    }

    void Awake() {
        if (instance != null && instance != this) {
            Destroy(gameObject);
            return;
        } else {
            instance = this;
        }

        DontDestroyOnLoad(this.gameObject);
    }
}

```

This thread can be closed now.

# Answer
This works

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

public class MusicManager : MonoBehaviour {

    private static MusicManager instance = null;
    private static MusicManager Instance {
        get {
            return instance;
        }
    }

    void Awake() {
        if (instance != null && instance != this) {
            Destroy(gameObject);
            return;
        } else {
            instance = this;
        }

        DontDestroyOnLoad(this.gameObject);
    }
}
```

> 2 votes

---
Tags: unity, audio
---


title: Java Tilemap Collision

text:
# Question
Title: Java Tilemap Collision
I have tilemaps represented by values from 0 to 4. How can I make the player collide with tiles represented by 3 and stop the player from passing through it ? Here is my code for the player and tilemap:

```
public class tilemap {

private int x;
    private int y;

private int tilesize;
private int[][] map;
private int mapwidth;
private int mapheight;
public static Image img;
public static int camx,camy;

public String sl;

public tilemap(String s,int tilesize){
    this.tilesize = tilesize;

    try{

        BufferedReader br = new BufferedReader(new FileReader(s));

        mapwidth = Integer.parseInt(br.readLine());
        mapheight = Integer.parseInt(br.readLine());

        map = new int[mapheight][mapwidth];

        String del = " ";
        for(int row = 0; row < mapheight; row++){
            String line = br.readLine();
            String[] tokens = line.split(del);
            for(int col = 0; col < mapwidth; col++){
                map[row][col] = Integer.parseInt(tokens[col]);
            }
        }

    }catch(Exception e){}
}

public void update(){

}

public void draw(Graphics g){
    for(int row = 0; row < mapheight; row++){
        for(int col = 0; col < mapwidth; col++){

             int rc = map[row][col];

             if(rc == 0){
                 g.setColor(Color.green);
             }

             if(rc == 1){
                 g.setColor(Color.yellow);
             }
             if(rc == 2){
                 g.setColor(Color.GRAY);
             }
             if(rc == 3){
                 g.setColor(new Color(127,51,0));
             }
             if(rc == 4){
                 g.setColor(Color.BLUE);
             }

             g.fillRect(x + col * tilesize - camx, y + row * tilesize - camy,tilesize,tilesize);

        }
    }
}
}

public class player {

public static boolean camo = false, walkb = false, walkl = false,
        walkr = false, walkw = false;
public static int x = 431, y = 335, anim = 0;
public static String name = "Jack";
public static Image img;
public static int cx, cy;
public static int an = 0, mxan = 2;
public static int an1 = 0, mxan1 = 2;
public static int an2 = 0, mxan2 = 2;
public static int an3 = 0, mxan3 = 2;

public static void tick() {
    if (walkb) {
        // y+=2;
        tilemap.camy += 2;
        if (an <= mxan) {
            an++;
        }
    } else if (walkw) {
        // y-=2;
        tilemap.camy -= 2;
        if (an3 <= mxan3) {
            an3++;
        }
    } else if (walkr) {
        // x+=2;
        tilemap.camx += 2;
        if (an1 <= mxan1) {
            an1++;
        }
    } else if (walkl) {
        // x-=2;
        tilemap.camx -= 2;
        if (an2 <= mxan2) {
            an2++;
        }
    }

    if (an >= mxan) {
        an = 0;
    }
    if (an1 >= mxan1) {
        an1 = 0;
    }
    if (an2 >= mxan2) {
        an2 = 0;
    }
    if (an3 >= mxan3) {
        an3 = 0;
    }

}

public static void render(Graphics g) {
    g.setColor(Color.black);
    g.setFont(new Font("italic", Font.BOLD, 12));
    g.drawString("" + name, x + 10, y - 10);

    /** player **/

    if (anim == 0) {
        if (an1 == 0) {
            ImageIcon i3 = new ImageIcon("res/player.png");
            img = i3.getImage();
            g.drawImage(img, x, y, null);
        } else if (an1 == 1) {
            ImageIcon i3 = new ImageIcon("res/player.1.png");
            img = i3.getImage();
            g.drawImage(img, x, y, null);
        }
    } else if (anim == 1) {
        if (an2 == 0) {
            ImageIcon i3 = new ImageIcon("res/player2.png");
            img = i3.getImage();
            g.drawImage(img, x, y, null);
        } else if (an2 == 1) {
            ImageIcon i3 = new ImageIcon("res/player2.1.png");
            img = i3.getImage();
            g.drawImage(img, x, y, null);
        }
    } else if (anim == 2) {
        if (an3 == 0) {

            ImageIcon i3 = new ImageIcon("res/player3.png");
            img = i3.getImage();
            g.drawImage(img, x, y, null);
        } else if (an3 == 1) {
            ImageIcon i3 = new ImageIcon("res/player3.1.png");
            img = i3.getImage();
            g.drawImage(img, x, y, null);
        }
    } else if (anim == 3) {
        if (an == 0) {
            ImageIcon i3 = new ImageIcon("res/player4.png");
            img = i3.getImage();
            g.drawImage(img, x, y, null);
        } else if (an == 1) {
            ImageIcon i3 = new ImageIcon("res/player4.1.png");
            img = i3.getImage();
            g.drawImage(img, x, y, null);

        }
    }

}
}

```

# Answer
## AABBs

There are a couple of ways to handle collision, but the simplest way is to use AABBs (Axis-Aligned-Bounding-Box). AABBs are made up of four coponents: left, right, top, and bottom (in my code, I just call refer to them as min and max X/Y). You can check for collision be checking if the boxes are aligned with each other on all axis.

To implement this, you would create a class called "AABB". This class would contain four variables of a numerical type: left, right, top, and bottom. You would then have a method called something like `collidesWith`. This method would return a boolean and it would accept another AABB as an argument (we will name this argument `other` for now). This method would return `true` if all of the following conditions are met:

```
this.right  >=  other.left
this.left   <=  other.right
this.top    >=  other.bottom
this.bottom <=  other.top

```

An example implementation might look like this:

```
boolean collidesWith(AABB other)
{
    return other != null & // first make sure that the other AABB isn't null so we don't get an error
           this.right >= other.left &
           this.left <= other.right &
           this.top >= other.bottom &
           this.bottom <= other.top;
}

```

Once you have written this class you would then write a method inside of the `tilemap` class to return the AABB for the tile at the given X/Y coordinates. This method would return a new AABB instance with the left, right, top, and bottom variables set appropriately. Here is an example implementation:

```
public AABB getAABB_at(int x, int y)
{
    if(map[x][y] != 3) return null; // we made a null check inside of our collidesWith method, so this won't raise an error
    return new AABB(x * TILE_WIDTH, y * TILE_HIEGHT,
                    x * TILE_WIDTH + TILE_WIDTH, y * TILE_HEIGHT + TILE_HEIGHT);
}

```

Now that these methods have been written, you must also add an AABB variable to the player.

On each update, you move the player on the X axis, and then you check for collision between the player and the tiles that are surrounding the player. If the player collides with any of the tiles that you checked, you get the amount that the player is inside of the tile by. Keep in mind that this amount should be checked differently depending on which way the player is moving. Once you have this number, you then offset the player's X by this amount to ensure that they aren't colliding with the tile vertically.

You then repeat this step again, except on the Y axis. **And don't forget to update the AABB after each movement.**
> 2 votes

# Answer
Simply predict next player position. If it passes through a 3 block don't move.

Do this by creating a `checkCollide()` function before updating the tilemap.camx-y.

Take into account current position, x,y, ImageIcon height and width and compare to map values on the direction of player sprite.

PS : You should definitely use better named variables.

* walkr =\> walkRight
* an1-3 =\> ancorWest, East, ...
* mxan1-3 =\> maxAncorWest,...

Because it's otherwise hard for us to help you correctly, plus in one month you won't remember and understand anything of what you've done.
> 1 votes

# Answer
Easier way: Make a new Rectangle(x, y, width, height) for each of the objects, and check if rect.intersects(otherRect)
> 0 votes

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


# Question
Title: Super mario bros "rounded" tile collision detection
I'm working on a Mario bros clone with SDL and C++ (purely for educational porpuses / and for fun) I got collision detection working by using AABB collision detection and resolving one axis at a time:

1. Check collision with X-axis first
2. Move entity if not collision is detected
3. Check collision with the Y-axis.
4. Move entity if not collision is detected

This is working great! However, one thing that I really like about the original Mario bros is that tiles have some kind of "rounded" feel to them. I think this helps make the map feel more organic, see how Mario moves left when jumping on a corner in the original SNES game:

I thought of using a circle collider for mario instead of an AABB. This would make Mario "fall" off the tiles if you step too close to the edges. But perhaps someone knows a better approach. I've been thinking about collision detection for longer than I'd like to admit. I'd love to know if someone has a clean aproach to accomplish what the GIF shows.

# Answer
> 1 votes
Two things:

1. As you may have noticed the entity collision box is smaller than the sprite. It is actually a rectangle, taller than wider.
2. Do not move the entity outside of the block instantly. Move the entity out at some fixed speed.

---
Tags: collision-detection, collision-resolution
---


# Question
Title: Why does unlocking cursor with keyup behave the same as unlocking it with keydown?
To understand the difference, let me review a bit about the behavior of `GetKeyUp` and `GetKeyDown` with the following code snippet.

```
void Update()
{
    if (Input.GetKeyDown(KeyCode.Escape))
    {
        Debug.Log("Escape Key Down");
    }

    if (Input.GetKeyUp(KeyCode.Escape))
    {
        Debug.Log("Escape Key Up");
    }
}

```

Right after pressing the `Esc` key (and holding it), a message "Escape Key Down" is produced. Later right after releasing the key, a message "Escape Key Up" will show. The behavior does make sense.

Now I apply this for toggling (locking/unlocking) the mouse cursor. Here is my code snippet.

```
void Update()
{

    if (Input.GetMouseButtonDown(0))
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    if (Input.GetKeyUp(KeyCode.Escape))
    {
        Cursor.lockState = CursorLockMode.None;
        Cursor.visible = true;
    }
}

```

Right after clicking the left mouse button, the cursor becomes invisible. However, right after pressing down the `Esc` key, the cursor becomes visible again. **The expected behavior is that the cursor will be visible right after releasing the `Esc` key rather than right after pressing the key.**

# Question

How to fix this abnormal behavior?

# Answer
> 1 votes
DMGregory's comment is the answer.

> Doesn't pressing the escape key always break out of cursor lock, even if you delete your GetKeyUp code block entirely?

So I have to change `Escape` key to another key to avoid this problem.

---
Tags: unity, input
---


title: Temporary objects in opengl

text:
# Question
Title: Temporary objects in opengl
I want to write a game in which the player shoots projectiles (bullets, etc). Since I don't know how many and when these projectiles will be shot, I wonder how to buffer and render them (and when!).

Normal opengl pipeline (as I understand it):

1. Create and bind buffers (once)
2. Buffer data to these buffers (once)
3. In loop - Draw every frame/period.

What about temporary objects ? I buffer them only when used ? I suppose I get the player input as trigger, and then buffer them and draw them. Is this approach fast enough ?

Thank you

# Answer
Typically you allocate a buffer that's generously sized for the maximum number of items you *think* you might need.

Then when your temporary objects change, you fill that buffer from one end, with all the items you currently need, leaving space at the far end when you're drawing fewer items than the max. This way you're just paying the cost of a data upload to an existing buffer, not incurring all the cost of re-allocating a fresh one.

If you ever need more items than you have room for in the buffer, then you can...

* (In a development build): crash with an error message saying the predicted max count was too low, so the developer knows to increase it. Simple, but a bit harsh...
* Re-allocate a larger buffer automatically, and start using that one instead (and, in a development build, log a warning that the initial max might be too low)
* Recycle the oldest / most distant / least apparent objects to make room for new/more important ones
* Stop drawing items beyond the cap (usually a last resort, if you have no more memory to spend or no way to prune less-important items from the buffer)
> 0 votes

---
Tags: opengl, rendering, graphics
---


# Question
Title: What is the best time to implement Multiplayer system?
I have been starting a new online multiplayer game project this week and as the title says - Is it better to implement the Multiplayer feature right away, or is it ok to implement it when the game already has some other stuff, like maps and physics?

# Answer
How you implement the network will inform everything else you do in the game. Implementing networking later is always a bad idea.

Here's an example of a released game with local coop and what happened when they tried to implement networked coop later:

https://steamcommunity.com/app/408410/discussions/0/1697176044371195631/

> Unfortunately, despite our multiple attempts and best intentions, we have not delivered the online version of the co-op game mode. The main problem with the game is that it’s heavily physics based and it affects gameplay, thus we would have to make the physics 100% predictable or to completely rework the whole framework for it to be able to send physics information in multiplayer. Unfortunately, this would require 6-9 months of work for 2-3 programmers and so we decided that we won't be able to pull it off.
> 4 votes

---
Tags: multiplayer
---


# Question
Title: Multiplayer network architecture - why do we need to verify local movements?
I'm messing around with a 2D game using UDP. I've read some books and articles on the logic of a dedicated server to clients multiplayer game and I can't wrap my head around one thing:

**What I've read:**
When Client 1 moves, it sends it's input to the SERVER, the SERVER calculates the position, and then sends the new position back to all connected Clients, including Client 1 where the Client 1 player is drawn in the new position. Wouldn't this create a big amount of latency between the local player of Client 1 and their movements?

**How I think it should work:**
My question is, why not just move the local player based on the movement, and send the new position to the SERVER every time it moves? That what we you press a movement key, it's instant, instead of having to be calculated by the server and sent back and THEN moved.

*NOTE:* I'm not worried about anti-cheating verification

# Answer
> 1 votes
> **What I've read:**
>
> When Client 1 moves, it sends its input to the SERVER, the SERVER calculates the position, and then sends the new position back to all connected Clients, including Client 1 where the Client 1 player is drawn in the new position. Wouldn't this create a big amount of latency between the local player of Client 1 and their movements?

Almost. After Client 1 sends its input to the server, Client 1 *also* calculates its position, and continues advancing the local game state according to the best knowledge it has. This means you generally see no latency at all here - your immediate outcome is the same as if you were playing an offline game. This is called "client-side prediction".

Most of the time (if you're not using a hacked client, and there are no bugs in the game simulation that cause it to run significantly differently on your device versus the server), the server will agree with your simulation output. So when you get your validated position back from the server, it just confirms the simulation you've already been running and displaying in the meantime, and nothing surprising needs to happen.

But sometimes the server knows something you didn't when you sent that input. In actual fact, another player changed course and collided with you a fraction of a second ago, or put an obstacle in your way, or shot you, etc. but you're finding out about it late because of the communication delay.

In those cases, you'll need to adjust your simulation based on this new information about what happened in the very recent past, re-playing your inputs with this new knowledge of the game state to arrive at a new outcome that's consistent with the "consensus reality" the server has authoritatively determined and broadcast to all players. You can then gradually interpolate the displayed state to this corrected state over a few frames to make the adjustment less jarring.

This same adjustment can help cover smaller divergence in your simulation outcomes due to (hopefully minor) non-determinism in your simulation - like variations in floating point rounding or physics resolutions.

> **How I think it should work:**
>
> My question is, why not just move the local player based on the movement, and send the new position to the SERVER every time it moves?

The biggest problem with this is if the server just trusts any old position it's sent, then it becomes easy for players to hack the game to move faster or teleport or clip through walls etc. Even if you try to add server-side validation, it's generally more work to *verify* that a given position is a valid outcome of the game rules than it is to just run those game rules on the input directly.

But since you say you don't care about cheating, you can ignore that reason (at your own peril, some would say, but hey, it's your choice to make ).

The other reason is that when a conflict arises, simulating from input helps us find the correct resolution to that conflict. If all the server has is a list of positions - some of them based on false assumptions about past game state as we saw above - then it has to work backwards to figure out how those game entities got into those positions, to then figure out where it needs to move them to instead. This again is more work than just playing the game state forward with the history of player inputs, and simulating forward helps you get a more consistent, predictable, fair outcome too. So that's why we often prefer this route, even when stopping cheaters is not a top priority.

---
Tags: networking, multiplayer, logic, online, udp
---


# Question
Title: Calling Prefab MonoBehaviour Method before Start()
I'd like to do the following:

```
void Update()
{
   GameObject gob = Instantiate(Prefab);
   MyContainer comp = gob.GetComponent<MyContainer>();
   comp.SetName("something dynamic"); // We'll get an error here
}

```

The problem is, in the below class, `SetName` is accessing an object that is only instantiated in Start(). Unity's order of events won't have `MyContainer.Start()` called until the next frame (see example implementation below).

```
class MyContainer : MonoBehaviour
{
    TextMeshProUGUI textObj;
    void Start()
    {
        textObj = GetComponentInChildren<TextMeshProUGUI>();
    }
    void SetName(string name)
    {
        // Null Reference Here
        textObj.text = name; // textObj isn't set yet;
    }
}

```

Is there a recommended/sane way to go about dealing with objects in a scenario like this? I'd like to prevent too much boilerplate code in all my `MonoBehaviour` subclasses while mainting a solid separation of concerns.

The options I've thought of thus far are:

1. Use flags:

a. OnEnable, if `name` is set, set the text

b. On `SetName`, if `isActiveAndEnabled`, set the text
2. Change `SetName` to a coroutine and add a `yield return null` statement at the top.
3. Similar to 2, use `Invoke`

None of these seem ideal.

* 1 requires spaghetti-style state checks on every method.
* 2 requires the return values of methods to be `IEnumerator` even though nothing is actually intended to be returned.
* 3 requires an extra, 0-argument method for each public method and extra state in the `MyContainer` class to store the arguments.

# Answer
> 1 votes
The simplest solution is to take your initialization code and put it into `Awake` instead of `Start`. Like `Start`, `Awake` is guaranteed to run just once for each instance of a script (unlike `OnEnable` which can fire multiple times if the component is disabled and re-enabled)

But, like `OnEnable` (for already-enabled scripts), `Awake` runs before `Instantiate` or `AddComponent` return control to the calling method. So it behaves like a "pseudo-constructor", giving you an opportunity to prep all your script's dependencies so it's immediately ready to use by whoever instantiated it.

Or, you can do one better, and save doing this lookup at runtime at all, using a `public` or `[SerializeField] private` variable to wire up your references at edit time. When you instantiate, the deserializer fills-in these reference before `Awake` or `OnEnable` even run, very efficiently. You skip all the overhead of searching for the component reference at runtime (which isn't too costly individually, but does add up if you're awaking/starting dozens or hundreds of script instances on scene load).

If you miss the convenience of having the script find its own dependencies, you can have your cake and eat it too \- both automatic wire-up AND no runtime component search.

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


# Question
Title: How to increase points per second when speed increases
I am making an endless rider game that is crossed between tron legacy and cube field. I am trying to add a point system were the faster you go the more points you get because you are more likely to die so high risk high reward. I am really stuck on this however. This is my current script which is already connected to a point ui system that works. I am also probably going to post a question later about how to make speed correlate with emission/light intensity.

```
 public static int movespeed = 1;
    public Vector3 userDirection = Vector3.right;

    // Update is called once per frame
    void Update()
    {
        transform.Translate(Input.GetAxis("Horizontal") * Time.deltaTime * 50, 0f, Input.GetAxis("Vertical") * Time.deltaTime * 70, 0f);
        transform.Translate(userDirection * movespeed * Time.deltaTime * 40);
        scorecript.scoreValue += 10;

        if (Time.deltaTime > 10)
        {
            scorecript.scoreValue += 10;

        }
        if (Time.deltaTime > 11)
        {
            scorecript.scoreValue += 11;

        }

    }
```
This is how I translated MDgrgory's code:
```
[Tooltip("How fast the character should move with no input, in world units per second")]
public float autoMoveSpeed = 40.0f;
[Tooltip("The direction the character should move with no input")]
public Vector3 autoMoveDirection = Vector3.right;
// Enforce that this is always a unit direction vector, so it doesn't bias our speed.
void OnValidate() { autoMoveDirection = autoMoveDirection.normalized; }

[Tooltip("How much the player can affect the speed in the direction of auto movement")]
public float parallelMoveSpeed = 50f;
[Tooltip("How fast the player can affect the speed perpendicular to the auto movement")]
public float perpendicularMoveSpeed = 70f;

[Tooltip("How many points to earn per second with no input")]
public float scorePerSecondAtDefaultSpeed = 10f;
[Tooltip("How many extra points to earn per second for every extra unit of speed")]
public float extraScorePerVelocityUnit = 1.0f;

// Track how much "loose change" points we've accumulated.
float _scoreAccumulator = 0f;

void Update()
{
// Capture the player's input vector.
Vector3 input = new Vector3(
                    Input.GetAxis("Horizontal"),
                    0,
                    Input.GetAxis("Vertical")
                );

// Clamp the input to make sure we don't move faster on diagonals.
input = Vector3.ClampMagnitude(input, 1.0f);

// Extract the portion of the player's input parallel to the auto movement.
float parallelComponent = Vector3.Dot(autoMoveDirection, input);

// Leaving the component perpendicular to the auto movement.
Vector3 perpendicularComponent = (input - parallelComponent * autoMoveDirection);

// Compute how much to increase or decrease our auto movement based on our input.
float extraVelocity = parallelComponent * parallelMoveSpeed;

// Compute our net velocity, combining auto, parallel, and perpendicular movement.
Vector3 velocity = autoMoveDirection * (autoMoveSpeed + extraVelocity)
                 + perpendicularComponent * perpendicularMoveSpeed;

// Translate us according to that velocity and the elapsed time.
transform.Translate(velocity * Time.deltaTime, Space.Self);

// Scoring:
// Compute our increased (or reduced) scoring rate based on our forward velocity.
float extraScore = extraVelocity * extraScorePerVelocityUnit;

// Increase our score accumulator based on our current earning rate and time passed.
_scoreAccumulator += (scorePerSecondAtDefaultSpeed + extraScore) * Time.deltaTime;

// Whenever we earn a whole point, send it to the score display as an integer.
int scoreUnits = Mathf.FloorToInt(_scoreAccumulator);
scoreScript.scoreValue += scoreUnits;
// And decrement our accumulator to store just the "spare change".
_scoreAccumulator -= scoreUnits;
}
```

# Answer
From the code, it looks like...

* You want to move the character forward in some arbitrary direction at a particular speed, automatically, even when the player isn't providing input.
* You want the player to be able to speed up or slow down in that direction by holding toward / away from the direction of movement.
* You want the player to be able to move perpendicular to the direction of automatic movement, potentially at a different speed than they move along the direction of automatic movement.
* You want to give the player more points when they speed up along the automatic movement direction, or fewer points when they slow down in that direction.
* Movement perpendicular to the automatic movement shouldn't affect scoring (so you don't get more points for zig-zagging when there are no obstacles to dodge).

If this is accurate, here's an example of a script that will let you reach these goals, with clear control over each aspect. I've broken it into small steps and commented each line to explain how each part works:

```
[Tooltip("How fast the character should move with no input, in world units per second")]
public float autoMoveSpeed = 40.0f;
[Tooltip("The direction the character should move with no input")]
public Vector3 autoMoveDirection = Vector3.right;
// Enforce that this is always a unit direction vector, so it doesn't bias our speed.
void OnValidate() { autoMoveDirection = autoMoveDirection.normalized; }

[Tooltip("How much the player can affect the speed in the direction of auto movement")]
public float parallelMoveSpeed = 50f;
[Tooltip("How fast the player can affect the speed perpendicular to the auto movement")]
public float perpendicularMoveSpeed = 70f;

[Tooltip("How many points to earn per second with no input")]
public float scorePerSecondAtDefaultSpeed = 10f;
[Tooltip("How many extra points to earn per second for every extra unit of speed")]
public float extraScorePerVelocityUnit = 1.0f;

// Track how much "loose change" points we've accumulated.
float _scoreAccumulator = 0f;

void Update()
{
    // Capture the player's input vector.
    Vector3 input = new Vector3(
                        Input.GetAxis("Horizontal"),
                        0,
                        Input.GetAxis("Vertical")
                    );

    // Clamp the input to make sure we don't move faster on diagonals.
    input = Vector3.ClampMagnitude(input, 1.0f);

    // Extract the portion of the player's input parallel to the auto movement.
    float parallelComponent = Vector3.Dot(autoMoveDirection, input);

    // Leaving the component perpendicular to the auto movement.
    Vector3 perpendicularComponent = (input - parallelComponent * autoMoveDirection);

    // Compute how much to increase or decrease our auto movement based on our input.
    float extraVelocity = parallelComponent * parallelMoveSpeed;

    // Compute our net velocity, combining auto, parallel, and perpendicular movement.
    Vector3 velocity = autoMoveDirection * (autoMoveSpeed + extraVelocity)
                     + perpendicularComponent * perpendicularMoveSpeed;

    // Translate us according to that velocity and the elapsed time.
    transform.Translate(velocity * Time.deltaTime, Space.World);

    // Scoring:
    // Compute our increased (or reduced) scoring rate based on our forward velocity.
    float extraScore = extraVelocity * extraScorePerVelocityUnit;

    // Increase our score accumulator based on our current earning rate and time passed.
    _scoreAccumulator += (scorePerSecondAtDefaultSpeed + extraScore) * Time.deltaTime;

    // Whenever we earn a whole point, send it to the score display as an integer.
    int scoreUnits = Mathf.FloorToInt(_scoreAccumulator);
    scoreScript.scoreValue += scoreUnits;
    // And decrement our accumulator to store just the "spare change".
    _scoreAccumulator -= scoreUnits;
}

```
> 0 votes

# Answer
One way to do it, is that you set the userDirection Vector to be the direction of the input added by your forced right going vector. Then the movement speed is the magnitude and after getting that tou normalizing the userDirection. Something like:

```
userDirection = new Vector3(Input.getAxis("Horisontal"), 0, Input.getAxis("Vertical")) + Vector3.right;
moveSpeed = userDirection.magnitude;
userDirection.Normalize();

```

You could add a minimum of force to the right no matter the user input by adding

```
if(userDirection.x < 0.1) userDirection.x = 0.1;

```

Before normalizing. Adjusted by your needs ofcourse. Then you translate your transform by

```
transform.Translate(userDirection * movespeed * Time.deltatime)

```

Finally you can add points according to some formula depending on speed like:

```
scorescript.scoreValue += 10*movespeed.

```

Note: you would probably want to make your movement physics based, by working with Rigidbody (or Rigidbody2D) and as minimum set velocity instead of translating directly on your transform.
> 0 votes

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


# Question
Title: Unity particles rendering on top of camera space UI
I'm using LWRP in Unity 2019.1.12f1. The UI is in Screen Space - Camera. The shader used for the particles is Lightweight Render Pipeline/Particles/Unlit (Transparent, Premultiply).

Any ideas?

# Answer
> 3 votes
Increasing order in layer solved the problem.

# Answer
> 0 votes
Camera Stacks are now part of Unity's Universal Render Pipeline (URP). You can add an overlay camera over your main scene camera to render the particles - https://bdts.com.au/tips-and-resources/unity-ui-particles-in-urp-using-overly-cameras-and-camera-stacks.html

---
Tags: unity, rendering, gui, particles, draw-order
---