# Question
Title: How can i remove the margins in Window_Base?
So i am remaking `Window_Status` for my game where i have the character battler displayed in the background. bellow is the portion of the script which adds the battler image taken from `def refresh` (the first part, i omitted the at-the-time experimental code for Status Icons and Stats)

```
bitmap = RPG::Cache.battler(@actor.battler_name+"_menu", @actor.battler_hue)
cw = bitmap.width
ch = bitmap.height
src_rect = Rect.new(0, 0, cw,ch)
self.contents.blt(0,0, bitmap, src_rect, 75)
draw_actor_name(@actor, 0, 0)
draw_actor_level(@actor, 80,0)
draw_actor_class(@actor, 0, 32)

```

and this is the result

now the battler image used is about 5x larger than the regular one (because stretching it using code made it look pixely, this way it's a bit more smoother) and also i've chopped off the left side because some of the battlers i use don't have their head perfectly centered (this way they can all can get set at 0,0)

however as you can see the bottom, which isn't cropped in the original image, is still being chopped off at the bottom. also despite the bitmap being at 0,0 it's not flesh against the sides.

i'd like to know how i can remove these margins? ideally at the `Window_Base` level since i can see myself running into the same problem with `Window_Command`

NOTE: this is in RPG Maker XP so i'm using RGSS

# Answer
I found a way. the margin is being set by the hidden Window Class which makes it that much harder to alter.

However i came across this script

```
#==============================================================================
# ? Window - Hidden RGSS Class
#------------------------------------------------------------------------------
# ?by Selwyn
#==============================================================================

#==============================================================================
# ? Bitmap
#==============================================================================

class Bitmap
  #--------------------------------------------------------------------------
  # ? erase
  #--------------------------------------------------------------------------
  def erase(*args)
    if args.size == 1
      rect = args[0]
    elsif args.size == 4
      rect = Rect.new(*args)
    end
    fill_rect(rect, Color.new(0, 0, 0, 0))
  end
end

#==============================================================================
# ? SG
#------------------------------------------------------------------------------
# ?Selwyn's Graphics module
#==============================================================================

module SG
#==============================================================================
# ? SG::Skin
#==============================================================================

class Skin
  #--------------------------------------------------------------------------
  # ? instances settings
  #--------------------------------------------------------------------------
  attr_reader   :margin
  attr_accessor :bitmap
  #--------------------------------------------------------------------------
  # ? initialize
  #--------------------------------------------------------------------------
  def initialize
    @bitmap = nil
    @values = {}
    @values['bg'] = Rect.new(0, 0, 128, 128)
    @values['pause0'] = Rect.new(160, 64, 16, 16)
    @values['pause1'] = Rect.new(176, 64, 16, 16)
    @values['pause2'] = Rect.new(160, 80, 16, 16)
    @values['pause3'] = Rect.new(176, 80, 16, 16)
    @values['arrow_up'] = Rect.new(152, 16, 16, 8)
    @values['arrow_down'] = Rect.new(152, 40, 16, 8)
    @values['arrow_left'] = Rect.new(144, 24, 8, 16)
    @values['arrow_right'] = Rect.new(168, 24, 8, 16)
    self.margin = 16
  end
  #--------------------------------------------------------------------------
  # ? width
  #--------------------------------------------------------------------------
  def margin=(width)
    @margin = width
    set_values
  end
  #--------------------------------------------------------------------------
  # ? set_values
  #--------------------------------------------------------------------------
  def set_values
    w = @margin
    @values['ul_corner'] = Rect.new(128, 0, w, w)
    @values['ur_corner'] = Rect.new(192-w, 0, w, w)
    @values['dl_corner'] = Rect.new(128, 64-w, w, w)
    @values['dr_corner'] = Rect.new(192-w, 64-w, w, w)
    @values['up'] = Rect.new(128+w, 0, 64-2*w, w)
    @values['down'] = Rect.new(128+w, 64-w, 64-2*w, w)
    @values['left'] = Rect.new(128, w, w, 64-2*w)
    @values['right'] = Rect.new(192-w, w, w, 64-2*w)
  end
  #--------------------------------------------------------------------------
  # ? []
  #--------------------------------------------------------------------------
  def [](value)
    return @values[value]
  end
end

#==============================================================================
# ? SG::Cursor_Rect
#==============================================================================

class Cursor_Rect < ::Sprite
  #--------------------------------------------------------------------------
  # ? instances settings
  #--------------------------------------------------------------------------
  attr_reader   :height, :width, :skin, :margin
  #--------------------------------------------------------------------------
  # ? initialize
  #--------------------------------------------------------------------------
  def initialize(viewport)
    super(viewport)
    @width = 0
    @height = 0
    @skin = nil
    @margin = 0
    @rect = {}
    @rect['cursor_up'] = Rect.new(129, 64, 30, 1)
    @rect['cursor_down'] = Rect.new(129, 95, 30, 1)
    @rect['cursor_left'] = Rect.new(128, 65, 1, 30)
    @rect['cursor_right'] = Rect.new(159, 65, 1, 30)
    @rect['upleft'] = Rect.new(128, 64, 1, 1)
    @rect['upright'] = Rect.new(159, 64, 1, 1)
    @rect['downleft'] = Rect.new(128, 95, 1, 1)
    @rect['downright'] = Rect.new(159, 95, 1, 1)
    @rect['bg'] = Rect.new(129, 65, 30, 30)
  end
  #--------------------------------------------------------------------------
  # ? margin=
  #--------------------------------------------------------------------------
  def margin=(margin)
    @margin = margin
    set(x, y, width, height)
  end
  #--------------------------------------------------------------------------
  # ? skin=
  #--------------------------------------------------------------------------
  def skin=(skin)
    @skin = skin
    draw_rect
  end
  #--------------------------------------------------------------------------
  # ? width=
  #--------------------------------------------------------------------------
  def width=(width)
    return if @width == width
    @width = width
    if @width == 0 and self.bitmap != nil
      self.bitmap.dispose
      self.bitmap = nil
    end
    draw_rect
  end
  #--------------------------------------------------------------------------
  # ? height=
  #--------------------------------------------------------------------------
  def height=(height)
    return if @height == height
    @height = height
    if @height == 0 and self.bitmap != nil
      self.bitmap.dispose
      self.bitmap = nil
    end
    draw_rect
  end
  #--------------------------------------------------------------------------
  # ? set
  #--------------------------------------------------------------------------
  def set(x, y, width, height)
    self.x = x + @margin
    self.y = y + @margin
    if @width != width or @height != height
      @width = width
      @height = height
      if width > 0 and height > 0
        draw_rect
      end
    end
  end
  #--------------------------------------------------------------------------
  # ? empty
  #--------------------------------------------------------------------------
  def empty
    self.x = 0
    self.y = 0
    self.width = 0
    self.height = 0
  end
  #--------------------------------------------------------------------------
  # ? draw_rect
  #--------------------------------------------------------------------------
  def draw_rect
    return if @skin == nil
    if @width > 0 and @height > 0
      self.bitmap = Bitmap.new(@width, @height)
      rect = Rect.new(1, 1, @width - 2, @height - 2)
      self.bitmap.stretch_blt(rect, @skin, @rect['bg'])
      self.bitmap.blt(0, 0, @skin, @rect['upleft'])
      self.bitmap.blt(@width-1, 0, @skin, @rect['upright'])
      self.bitmap.blt(0, @height-1, @skin, @rect['downright'])
      self.bitmap.blt(@width-1, @height-1, @skin, @rect['downleft'])
      rect = Rect.new(1, 0, @width - 2, 1)
      self.bitmap.stretch_blt(rect, @skin, @rect['cursor_up'])
      rect = Rect.new(0, 1, 1, @height - 2)
      self.bitmap.stretch_blt(rect, @skin, @rect['cursor_left'])
      rect = Rect.new(1, @height-1, @width - 2, 1)
      self.bitmap.stretch_blt(rect, @skin, @rect['cursor_down'])
      rect = Rect.new(@width - 1, 1, 1, @height - 2)
      self.bitmap.stretch_blt(rect, @skin, @rect['cursor_right'])
    end
  end
end

#==============================================================================
# ? SG::Window
#------------------------------------------------------------------------------
# ?
#==============================================================================

class Window
  #--------------------------------------------------------------------------
  # ? set instances variables
  #--------------------------------------------------------------------------
  attr_reader(:x, :y, :z, :width, :height, :ox, :oy, :opacity, :back_opacity,
              :stretch, :contents_opacity, :visible, :pause)
  attr_accessor :active
  #--------------------------------------------------------------------------
  # ? initialize
  #--------------------------------------------------------------------------
  def initialize()
    @skin = Skin.new
    @viewport = Viewport.new(0, 0, 0, 0)
    @cr_vport = Viewport.new(0, 0, 0, 0)
    @width = 0
    @height = 0
    @ox = 0
    @oy = 0
    @opacity = 255
    @back_opacity = 255
    @contents_opacity = 255
    @frame   = Sprite.new()
    @bg      = Sprite.new()
    @window  = Sprite.new(@viewport)
    @pause_s = Sprite.new()
    @arrows = []
    for i in 0...4
      @arrows.push(Sprite.new(@cr_vport))
      @arrows[i].bitmap = Bitmap.new(16, 16)
      @arrows[i].visible = false
    end
    @cursor_rect = Cursor_Rect.new(@cr_vport)
    @cursor_rect.margin = @skin.margin
    @cursor_fade = true
    @pause_s.visible = false
    @pause = false
    @active = true
    @stretch = true
    @visible = true
    self.x = 0
    self.y = 0
    self.z = 100
    self.windowskin = RPG::Cache.windowskin($game_system.windowskin_name)
  end
  #--------------------------------------------------------------------------
  # ? contents=
  #--------------------------------------------------------------------------
  def contents=(bmp)
    @window.bitmap = bmp
    if bmp != nil
      if bmp.width > @viewport.rect.width
         bmp.height > @viewport.rect.height
        draw_arrows
      end
    end
  end
  #--------------------------------------------------------------------------
  # ? contents
  #--------------------------------------------------------------------------
  def contents
    return @window.bitmap
  end
  #--------------------------------------------------------------------------
  # ? dispose
  #--------------------------------------------------------------------------
  def dispose
    @bg.dispose
    @frame.dispose
    @window.dispose
    @cursor_rect.dispose
    @viewport.dispose
    @pause_s.dispose
    @cr_vport.dispose
    for arrow in @arrows
      arrow.dispose
    end
  end
  #--------------------------------------------------------------------------
  # ? update
  #--------------------------------------------------------------------------
  def update
    @window.update
    @cursor_rect.update
    @viewport.update
    @cr_vport.update
    @pause_s.src_rect = @skin["pause#{(Graphics.frame_count / 8) % 4}"]
    @pause_s.update
    update_visible
    update_arrows
    if @cursor_fade
      @cursor_rect.opacity -= 10
      @cursor_fade = false if @cursor_rect.opacity <= 100
    else
      @cursor_rect.opacity += 10
      @cursor_fade = true if @cursor_rect.opacity >= 255
    end
  end
  #--------------------------------------------------------------------------
  # ? update_visible
  #--------------------------------------------------------------------------
  def update_visible
    @frame.visible = @visible
    @bg.visible = @visible
    @window.visible = @visible
    @cursor_rect.visible = @visible
    if @pause
      @pause_s.visible = @visible
    else
      @pause_s.visible = false
    end
  end
  #--------------------------------------------------------------------------
  # ? pause=
  #--------------------------------------------------------------------------
  def pause=(pause)
    @pause = pause
    update_visible
  end
  #--------------------------------------------------------------------------
  # ? update_arrows
  #--------------------------------------------------------------------------
  def update_arrows
    if @window.bitmap == nil or @visible == false
      for arrow in @arrows
        arrow.visible = false
      end
    else
      @arrows[0].visible = @oy > 0
      @arrows[1].visible = @ox > 0
      @arrows[2].visible = (@window.bitmap.width - @ox) > @viewport.rect.width
      @arrows[3].visible = (@window.bitmap.height - @oy) > @viewport.rect.height
    end
  end
  #--------------------------------------------------------------------------
  # ? visible=
  #--------------------------------------------------------------------------
  def visible=(visible)
    @visible = visible
    update_visible
    update_arrows
  end
  #--------------------------------------------------------------------------
  # ? x=
  #--------------------------------------------------------------------------
  def x=(x)
    @x = x
    @bg.x = x + 2
    @frame.x = x
    @viewport.rect.x = x + @skin.margin
    @cr_vport.rect.x = x
    @pause_s.x = x + (@width / 2) - 8
    set_arrows
  end
  #--------------------------------------------------------------------------
  # ? y=
  #--------------------------------------------------------------------------
  def y=(y)
    @y = y
    @bg.y = y + 2
    @frame.y = y
    @viewport.rect.y = y + @skin.margin
    @cr_vport.rect.y = y
    @pause_s.y = y + @height - @skin.margin
    set_arrows
  end
  #--------------------------------------------------------------------------
  # ? z=
  #--------------------------------------------------------------------------
  def z=(z)
    @z = z
    @bg.z = z
    @frame.z = z + 1
    @cr_vport.z = z + 2
    @viewport.z = z + 3
    @pause_s.z = z + 4
  end
  #--------------------------------------------------------------------------
  # ? ox=
  #--------------------------------------------------------------------------
  def ox=(ox)
    return if @ox == ox
    @ox = ox
    @viewport.ox = ox
    update_arrows
  end
  #--------------------------------------------------------------------------
  # ? oy=
  #--------------------------------------------------------------------------
  def oy=(oy)
    return if @oy == oy
    @oy = oy
    @viewport.oy = oy
    update_arrows
  end
  #--------------------------------------------------------------------------
  # ? width=
  #--------------------------------------------------------------------------
  def width=(width)
    @width = width
    @viewport.rect.width = width - @skin.margin * 2
    @cr_vport.rect.width = width
    if @width > 0 and @height > 0
      @frame.bitmap = Bitmap.new(@width, @height)
      @bg.bitmap = Bitmap.new(@width - 4, @height - 4)
      draw_window
    end
    self.x = @x
    self.y = @y
  end
  #--------------------------------------------------------------------------
  # ? height=
  #--------------------------------------------------------------------------
  def height=(height)
    @height = height
    @viewport.rect.height = height - @skin.margin * 2
    @cr_vport.rect.height = height
    if @height > 0 and @width > 0
      @frame.bitmap = Bitmap.new(@width, @height)
      @bg.bitmap = Bitmap.new(@width - 4, @height - 4)
      draw_window
    end
    self.x = @x
    self.y = @y
  end
  #--------------------------------------------------------------------------
  # ? opacity=
  #--------------------------------------------------------------------------
  def opacity=(opacity)
    value = [[opacity, 255].min, 0].max
    @opacity = value
    @contents_opacity = value
    @back_opacity = value
    @frame.opacity = value
    @bg.opacity = value
    @window.opacity = value
  end
  #--------------------------------------------------------------------------
  # ? back_opacity=
  #--------------------------------------------------------------------------
  def back_opacity=(opacity)
    value = [[opacity, 255].min, 0].max
    @back_opacity = value
    @bg.opacity = value
  end
  #--------------------------------------------------------------------------
  # ? contents_opacity=
  #--------------------------------------------------------------------------
  def contents_opacity=(opacity)
    value = [[opacity, 255].min, 0].max
    @contents_opacity = value
    @window.opacity = value
  end
  #--------------------------------------------------------------------------
  # ? cursor_rect
  #--------------------------------------------------------------------------
  def cursor_rect
    return @cursor_rect
  end
  #--------------------------------------------------------------------------
  # ? cursor_rect=
  #--------------------------------------------------------------------------
  def cursor_rect=(rect)
    @cursor_rect.x = rect.x
    @cursor_rect.y = rect.y
    if @cursor_rect.width != rect.width or @cursor_rect.height != rect.height
      @cursor_rect.set(@cursor_rect.x, @cursor_rect.y, rect.width, rect.height)
    end
  end
  #--------------------------------------------------------------------------
  # ? windowskin
  #--------------------------------------------------------------------------
  def windowskin
    return @skin.bitmap
  end
  #--------------------------------------------------------------------------
  # ? windowskin=
  #--------------------------------------------------------------------------
  def windowskin=(windowskin)
    return if windowskin == nil
    if @skin.bitmap != windowskin
      @pause_s.bitmap = windowskin
      @pause_s.src_rect = @skin['pause0']
      @skin.bitmap = windowskin
      @cursor_rect.skin = windowskin
      draw_window
      draw_arrows
    end
  end
  #--------------------------------------------------------------------------
  # ? margin=
  #--------------------------------------------------------------------------
  def margin=(margin)
    if @skin.margin != margin
      @skin.margin = margin
      self.x = @x
      self.y = @y
      temp = @height
      self.height = 0
      self.width = @width
      self.height = temp
      @cursor_rect.margin = margin
      set_arrows
    end
  end
  #--------------------------------------------------------------------------
  # ? stretch=
  #--------------------------------------------------------------------------
  def stretch=(bool)
    if @stretch != bool
      @stretch = bool
      draw_window
    end
  end
  #--------------------------------------------------------------------------
  # ? set_arrows
  #--------------------------------------------------------------------------
  def set_arrows
    @arrows[0].x = @width / 2 - 8
    @arrows[0].y = 8
    @arrows[1].x = 8
    @arrows[1].y = @height / 2 - 8
    @arrows[2].x = @width - 16
    @arrows[2].y = @height / 2 - 8
    @arrows[3].x = @width / 2 - 8
    @arrows[3].y = @height - 16
  end
  #--------------------------------------------------------------------------
  # ? draw_arrows
  #--------------------------------------------------------------------------
  def draw_arrows
    return if @skin.bitmap == nil
    @arrows[0].bitmap.blt(0, 0, @skin.bitmap, @skin['arrow_up'])
    @arrows[1].bitmap.blt(0, 0, @skin.bitmap, @skin['arrow_left'])
    @arrows[2].bitmap.blt(0, 0, @skin.bitmap, @skin['arrow_right'])
    @arrows[3].bitmap.blt(0, 0, @skin.bitmap, @skin['arrow_down'])
    update_arrows
  end
  #--------------------------------------------------------------------------
  # ? draw_window
  #--------------------------------------------------------------------------
  def draw_window
    return if @skin.bitmap == nil
    return if @width == 0 or @height == 0
    m = @skin.margin
    if @frame.bitmap.nil?
      @frame.bitmap = Bitmap.new(@width, @height)
      @bg.bitmap = Bitmap.new(@width - 4, @height - 4)
    end
    @frame.bitmap.clear
    @bg.bitmap.clear
    if @stretch
      dest_rect = Rect.new(0, 0, @width-4, @height-4)
      @bg.bitmap.stretch_blt(dest_rect, @skin.bitmap, @skin['bg'])
    else
      bgw = Integer((@width-4) / 128) + 1
      bgh = Integer((@height-4) / 128) + 1
      for x in 0..bgw
        for y in 0..bgh
          @bg.bitmap.blt(x * 128, y * 128, @skin.bitmap, @skin['bg'])
        end
      end
    end
    bx = Integer((@width - m*2) / @skin['up'].width) + 1
    by = Integer((@height - m*2) / @skin['left'].height) + 1
    for x in 0..bx
      w = @skin['up'].width
      @frame.bitmap.blt(x * w + m, 0, @skin.bitmap, @skin['up'])
      @frame.bitmap.blt(x * w + m, @height - m, @skin.bitmap, @skin['down'])
    end
    for y in 0..by
      h = @skin['left'].height
      @frame.bitmap.blt(0, y * h + m, @skin.bitmap, @skin['left'])
      @frame.bitmap.blt(@width - m, y * h + m, @skin.bitmap, @skin['right'])
    end
    @frame.bitmap.erase(@width - m, 0, m, m)
    @frame.bitmap.erase(0, @height - m, m, m)
    @frame.bitmap.erase(@width - m, @height - m, m, m)
    @frame.bitmap.blt(0, 0, @skin.bitmap, @skin['ul_corner'])
    @frame.bitmap.blt(@width - m, 0, @skin.bitmap, @skin['ur_corner'])
    @frame.bitmap.blt(0, @height - m, @skin.bitmap, @skin['dl_corner'])
    @frame.bitmap.blt(@width - m, @height - m, @skin.bitmap, @skin['dr_corner'])
  end
end

end

```

the creator says it's the same Window Class with the added functionality to alter the margin. do to use this i had to first add the script in (i put it at the very top) then edit `Window_Base` and replace which class it inherits from `Window` to `SG::Window`. from there i was able to alter the margin

running though all the default Scene classes (like `Scene_Equip`, `Scene_Item`, etc) everything remains the same. setting the margin to 0 will cut off the Windowskin border

as you can see on the right the background battler is now flesh against the borders by setting `self.margin=3`. you can also see that there is a slight glitch that the corners of the border are being tiled as well (only really evident with a gradient border) if the margin is altered as on the left is the default `Scene_Equip` which does not have this problem, however this is easily fixed with a bit of tinkering in the Windowskin image
> 1 votes

---
Tags: ruby, rpg-maker-xp
---


# Question
Title: how to save data in a visual novel with shared object
I've been looking for ways to save data in a visual novel, I have seen that the best way to do is with shared object but the tutorials are usually saved scores and I want to save the history progression

how can I do it?

Which variable should be used?

What should contain the variable?

shared object works for android and ios?

Thanks for reading

# Answer
It doesn't really matter what you call your variable when you save it. Just figure out what you need and go from there.

For example, if you need to save page number, scroll position and audio level, you may just have direct variables like page\_position, scroll\_position etc.

You can also save objects, so your variable could be named "state" with state being an object like

```
{ page: 1,  scroll:45%, audio:80% }

```

Then it's up to you to read this variable (likely at the start of the app) and handle it appropriately (such as returning the user to that location)
> 1 votes

---
Tags: actionscript-3
---


title: Phaser: show text when overlap sprites

text:
# Question
Title: Phaser: show text when overlap sprites
I am trying to work out a way to add a text to the top left corner of the viewport when two of my sprites overlap. One of them is a item and the other is my character. I can already detect for overlap and even "pick" the item (kill the sprite) when I click a key. However I would like that a text saying something like "Click "E" to pick the sword!" appeared while the collision function is active and when I kill the sprite by picking it up the text would vanish.

I tryed including the text in the collision function itself but I suppose this way I am rendering the text multiple times ( the fps drop a lot) and I just want to create it once and remove it according to my purposes. My code:

```
function collisionHandler(dude,the_sword) {
pickObject.onDown.add(function () {
        the_sword.kill();
    }, this);
 }

game.physics.isoArcade.overlap(dude, the_sword, collisionHandler, null, this);

 // message saying to pick // Where to put this?
var style = { font: "30px Arial", fill: "#ff0044"};
var pick_message = this.game.add.text(0,20,"Click 'E' to pick up the sword!",style);
pick_message.fixedToCamera = true;

```

Any idea on how to do this? Thank you.

# Answer
> 0 votes
The simplest way would be to create the text beforehand but have it hidden. Then your overlap handler will show the text, and if there is no overlap, hide it again. Something like:

```
mytext.alpha = 0;
game.physics.isoArcade.overlap(...); // mytext.alpha = 1;

```

You can turn the text on and off using `alpha`, or directly changing the text. See this phaser example: http://phaser.io/examples/v2/text/update-text

---
Tags: text, phaser
---


# Question
Title: Collisions between players in multiplayer racing game
I'm creating a simple racing game (spaceships, no gravity) using p2.js, phaser and node.js.

What I have done: Client receives world state from server:

* extrapolate other players based on latest velocity/position from server
* check if client-side prediction was correct - if no apply position from server and process inputs that server was not aware of.
* fixed physics step

Server:

* receives inputs from clients and apply
* fixed physics step
* sends world state to each client

Now I'm struggling with collisions between players. Colliding player is jumping all time during collision. I think it's because client-side prediction is not calculating similar results to the server.

Server doesn't know all inputs from player (lag).

Player doesn't have the same position of colliding player as the server (lag).

Combining this two makes the client to resolve collision different than the server and when world state arrives player has to make a big correction.

# Answer
Do physics only on server. Here is an example workflow:

1. Client presses "steer left".
2. Client sends "steer left" request to server
3. Server receives the data.
4. Server steers instance of client on server to left.
5. Server detects there is a collision between players.
6. Server makes corrections based on collision.
7. Server sends position data to client.
8. Client receives the position data.
9. Client adjusts it's position.
> 1 votes

# Answer
If you want the player interaction to feel instantaneous then there are a few choices. If not then just do physics on server side.

**Option 1**: Client side detects collision and collision data is sent to server and/or directly to other client. Certain multiplayer shooters do this kind of collision detection because otherwise the shooting mechanics would not feel accurate.

**Option 2**: Server side does physics, but makes many different predictions. You can just use more instances of each player and predict them to do slightly different things. Make sure they don't self-collide and send the data to the clients. Each time the player motion matches an prediction you use the data that has already been sent to the client.
> 0 votes

---
Tags: collision-detection, multiplayer, collision-resolution, node.js
---


# Question
Title: Must I buy licenses if my rhythm game lets users load music from their own library to be played in-game?
I want to create a music rhythm game, where any user can load the "map" for a song from the game server, if they have a song's sound file in their own library. Each "song map" contains information about its rhythm structure (for the game to interpret) but doesn't include any sound.

I want to monetise the game (through advertising or cosmetic items), but I don't intend to sell any music or song maps.

Do I need to pay any money to artists in this case?

# Answer
> 10 votes
Most users on this site, including myself, are not lawyers, so we are not able to give you legal advice. The best way to be sure is to consult a lawyer.

From the system you describe, it sounds like an artist or someone with the distribution rights to a song could claim that you are making unauthorized use of their identity/intellectual property, just for using the name of the artist & song. They might be able to claim you are using this property commercially (ie. you expect to attract more players, and more ad views, by using artists' names & song titles in shared maps than you would if the maps were based solely on your own IP).

Whether or not these claims would hold up in court is hard to say. Just keep in mind that you can be legally in the right and still be unable to afford defending against a lawsuit in court.

I think there's enough cause for concern here that you should definitely consult a lawyer before proceeding.

---
Tags: legal, music
---


# Question
Title: Unity, Which side of Collider2D was hit by raycast?
I've got a player firing out 2d raycasts. If one of them hits a boxcollider2d I would like to know if it hit the top side, bottom side, left side, or right side. How would I go about doing this? I've tried using Bounds but that didn't work out very well.

# Answer
Compare contact point with bounds of your collider. You can get center and extents of collider to get coordinates of each side of collider, and see, which side contact point belongs to.

See image below for example.

Red line is raycast line, green square - collider. You can get contact point from RaycastHit2D. Then simply check: if contact point X coordinate is equal to bound `center.X + extents.X` \- it is either corner or right side. Same goes for left side - contact point X will be equal to `center.X - extents.X`. For upper and lower check you just should change X to Y.

Also, don't forget, that it is possible for raycast to hit corner - X and Y of contact point in such situation will be equal to both `center.X +- extents.X` and `center.Y +- extents.Y` correspondingly.

For more details, see Bounds reference.
> 0 votes

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


# Question
Title: What is the difference between Non-Player Characters and Enemy Characters?
> *Non-Player Character* also known as *NPC* is a character that is controlled by a computer itself with an Artificial Intelligence and friendly behavior. (Ex. Merchant, Blacksmith, Pet)
>
> *Enemy Character* is a character that also has an Artificial Intelligence but with a different behavior. (Ex. Monster, Troll, Slime)

What is the difference between Non-Player Characters and Enemy Characters?

I need to create a `Character` class which is divided into three types, a PC, NPC and Enemy Character. I want to know what are the possible attributes or data of NPC and Enemy.

Based on the below code example, I have added a target and steering-behavior data for both Enemy & NPC. As you may have noticed, they both have the same data, the only difference is they have a Good and a Bad or Can attack or Cannot attack.

```
public class Character {
    // Traits or Stats, Skills & Abilities
}

public class NonPlayerCharacter extends Character {
    Vector2 target
    // friendly behavior, it means it doesn't attack
    // can follow, attack, pursue, evade, flee (Some steering behaviors)
    // can stall & sell items, save point, bank etc.
}

public class Enemy extends Character {
    Vector2 target
    // Not friendly, it means it does attack player
    // Also have steering behaviors
}

```

# Answer
> What is the difference of Non-Player Character between Enemy Character?

Interpretation, basically.

From the perspective of data and methods, an "NPC" and an "Enemy" type are almost the same. So much so that I would argue that you should not be creating your `NonPlayerCharacter` and `Enemy` types the way you are. `Character` is generally sufficient on its own. In you case I think this is especially true because you're having trouble coming up with what the distinguishing features of the various types should be: consider that if you can't think of any good reasons to make the types unique, maybe you shouldn't actually make the types unique.

Instead, give the `Character` class additional properties you may need to represent the desired behavior (for example, you can give it a `bool canAttack` field, which you always set to true for instances that should be enemies but false for instances that should be non-combat NPCs. Rather than hard-code the behavior of the type as a member function, use a pointer or reference to a script (or if you don't have scripts, a behavior component, object, or member function pointer).

You can, in fact, extend this concept to cover the player character as well.
> 4 votes

# Answer
An enemy is also an NPC.

Yes, they behave differently and have different abilities and functionality. But you will likely also have many different kinds of enemies with different behavior patterns and different abilities. The same applies to friendly NPCs. So the AI and moveset is no strict distinction.

The only *substantial* difference is that one can be damaged by the player and the other can not. Or when your game allows friendly fire then maybe not even that and the only difference is the color of the dot on the minimap.

I would add an attribute for your NPC which says which side they are on. In the simplest case this can be a simple `bool isEnemy`, in a more complex game you could have a complicated faction system which determines who is fighting with whom. Note that changing that variable at runtime could be a very simple way to have a friendly NPC suddenly attack the player or have an enemy surrender and turn into a friendly NPC.

`Shopkeeper`, `Bank`, `SavePoint`, `Questgiver` etc. should either be subclasses of `NPC` or if you want an NPC to be able to fulfill multiple roles it could be a component.

Each NPC should also have another component `AI` which controls its movement. You could split that into `CombatAI` and `IdleAI` to have the NPC act differently depending on whether or not they are currently in combat.
> 3 votes

# Answer
adding to Josh's answer, you could do somtething similar to how Dark Souls 1 deals with enemies and allies, the game basically has three teams for the entirety of NPCs:

* ally: this is the player's team, members of this team can not hurt each other.
* neutral: this is the basic NPC team, they are not aggressive by default, and only become aggressive if specifically triggered (game event or player attacking), these can hurt and be hurt by anybody, you could say these are sort of teamless
* enemy: these are the monsters, aggressive by default and cannot hurt team-mates, just like the ally team.

basically when in multiplayer, when you get invaded the other player joins the enemy team, and when summoning help, they join the ally team.

So what does this mean for you? Well, if you can't think of any specific differences between basic NPCs and enemies, you could use a similar team based system by implementing a team attribute.

Hope this helps a bit.
> 0 votes

---
Tags: terminology
---


# Question
Title: Camera does not travel the way it is rotated
I've implemented camera control with mouse and keyboard. My problem is that camera goes crazy when I'm using mouse and camera does not travel the way it is rotated. Could you explain me why and how to fix that?

My code:

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Game_01
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
int windowWidth, windowHeight;
VertexPositionTexture[] floorVerts;
BasicEffect basicEffect;
Texture2D floorTexture;
Vector3 cameraPosition;
Vector3 cameraTarget;
float cameraYaw;
float cameraPitch;
Matrix projectionMatrix;
Matrix viewMatrix;
Matrix worldMatrix;
float speed;
float mouseSpeed;
Model model;
MouseState oldMouseState;
public Game1()
{
    graphics = new GraphicsDeviceManager(this);
    Content.RootDirectory = "Content";
}

/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content.  Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
    // TODO: Add your initialization logic here
    cameraPosition = new Vector3(0, 18, 0);
    cameraTarget = cameraPosition + Vector3.Forward;
    cameraYaw = 0;
    cameraPitch = 0;
    projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), graphics.GraphicsDevice.Viewport.AspectRatio, 1, 1000);
    viewMatrix = Matrix.CreateLookAt(cameraPosition, cameraTarget, Vector3.Up) * Matrix.CreateFromYawPitchRoll(cameraYaw, cameraPitch, 0);
    worldMatrix = Matrix.CreateWorld(Vector3.Zero, Vector3.Forward, Vector3.Up);
    speed = 0.5f;
    mouseSpeed = 0.025f;
    windowWidth = graphics.PreferredBackBufferWidth;
    windowHeight = graphics.PreferredBackBufferHeight;
    Mouse.SetPosition(windowWidth / 2, windowHeight / 2);
    oldMouseState = Mouse.GetState();
    basicEffect = new BasicEffect(graphics.GraphicsDevice);
    base.Initialize();
}

/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);

    // TODO: use this.Content to load your game content here
    floorTexture = Content.Load<Texture2D>("Textures/Ground");
    model = Content.Load<Model>("Models/Test");
}

/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// game-specific content.
/// </summary>
protected override void UnloadContent()
{
    // TODO: Unload any non ContentManager content here
}

/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
        Exit();

    // TODO: Add your update logic here
    if (Keyboard.GetState().IsKeyDown(Keys.W))
    {
        cameraPosition += Vector3.Forward * speed;
        cameraTarget += Vector3.Forward * speed;
    }
    if (Keyboard.GetState().IsKeyDown(Keys.S))
    {
        cameraPosition += Vector3.Backward * speed;
        cameraTarget += Vector3.Backward * speed;
    }
    if (Keyboard.GetState().IsKeyDown(Keys.A))
    {
        cameraPosition += Vector3.Left * speed;
        cameraTarget += Vector3.Left * speed;
    }
    if (Keyboard.GetState().IsKeyDown(Keys.D))
    {
        cameraPosition += Vector3.Right * speed;
        cameraTarget += Vector3.Right * speed;
    }
    if (Keyboard.GetState().IsKeyDown(Keys.Space))
    {
        cameraPosition += Vector3.Up * speed;
        cameraTarget += Vector3.Up * speed;
    }
    if (Keyboard.GetState().IsKeyDown(Keys.C))
    {
        cameraPosition += Vector3.Down * speed;
        cameraTarget += Vector3.Down * speed;
    }
    if (Mouse.GetState().X < 0 || Mouse.GetState().Y < 0 || Mouse.GetState().X >= windowWidth || Mouse.GetState().Y >= windowHeight)
    {
        Mouse.SetPosition(windowWidth / 2, windowHeight / 2);
    }
    else
    {
        if (Mouse.GetState().X - oldMouseState.X < 0)
        {
            cameraYaw -= mouseSpeed;
        }
        if (Mouse.GetState().X - oldMouseState.X > 0)
        {
            cameraYaw += mouseSpeed;
        }
        if (Mouse.GetState().Y - oldMouseState.Y < 0)
        {
            cameraPitch -= mouseSpeed;
        }
        if (Mouse.GetState().Y - oldMouseState.Y > 0)
        {
            cameraPitch += mouseSpeed;
        }
    }
    viewMatrix = Matrix.CreateLookAt(cameraPosition, cameraTarget, Vector3.Up) * Matrix.CreateFromYawPitchRoll(cameraYaw, cameraPitch, 0);
    oldMouseState = Mouse.GetState();
    base.Update(gameTime);
}
void DrawGround(Vector3 groundPosition)
{
    float x = 200, y = 200;
    int repetitions = 20;
    floorVerts = new VertexPositionTexture[6];
    floorVerts[0].Position = new Vector3(-x, -y, 0);
    floorVerts[1].Position = new Vector3(-x, y, 0);
    floorVerts[2].Position = new Vector3(x, -y, 0);
    floorVerts[3].Position = floorVerts[1].Position;
    floorVerts[4].Position = new Vector3(x, y, 0);
    floorVerts[5].Position = floorVerts[2].Position;
    floorVerts[0].TextureCoordinate = new Vector2(0, 0);
    floorVerts[1].TextureCoordinate = new Vector2(0, repetitions);
    floorVerts[2].TextureCoordinate = new Vector2(repetitions, 0);
    floorVerts[3].TextureCoordinate = floorVerts[1].TextureCoordinate;
    floorVerts[4].TextureCoordinate = new Vector2(repetitions, repetitions);
    floorVerts[5].TextureCoordinate = floorVerts[2].TextureCoordinate;
    basicEffect.Projection = projectionMatrix;
    basicEffect.View = viewMatrix;
    basicEffect.World = worldMatrix * Matrix.CreateTranslation(groundPosition);
    basicEffect.World *= Matrix.CreateRotationX(MathHelper.ToRadians(-90)) * Matrix.CreateRotationY(MathHelper.ToRadians(-90)) * Matrix.CreateRotationZ(MathHelper.ToRadians(0));
    basicEffect.TextureEnabled = true;
    basicEffect.Texture = floorTexture;
    foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
    {
        pass.Apply();
        graphics.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, floorVerts, 0, 2);
    }
}
void DrawModel(Model model, Vector3 modelPosition, Vector3 modelRotation, Vector3 modelScale)
{
    foreach (ModelMesh mesh in model.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.PreferPerPixelLighting = true;
            effect.Projection = projectionMatrix;
            effect.View = viewMatrix;
            effect.World = worldMatrix * Matrix.CreateTranslation(modelPosition);
            effect.World *= Matrix.CreateRotationX(MathHelper.ToRadians(modelRotation.X)) * Matrix.CreateRotationY(MathHelper.ToRadians(modelRotation.Y)) * Matrix.CreateRotationZ(MathHelper.ToRadians(modelRotation.Z));
            effect.World *= Matrix.CreateScale(modelScale);
        }
        mesh.Draw();
    }
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);

    // TODO: Add your drawing code here
    DrawGround(new Vector3(0, 0, 0));
    DrawModel(model, new Vector3(0, 5, 0), Vector3.Zero, new Vector3(2, 2, 2));
    base.Draw(gameTime);
}
}
}

```

# Answer
I don't have XNA setup to test any of this but looking at the code I would check a few things.

1) The changes in the camera relate vectors need to occur at elapsed time, not a constant time. Your code shows alot of: cameraPosition += Vector3.Forward * speed;

Should probably look like: cameraPosition += (Vector3.Forward * speed) * elasped\_frame\_time;

2) Your camera view matrix creation line shows you dropping the vectors into '\* Matrix.CreateFromYawPitchRoll(cameraYaw, cameraPitch, 0);'. The vectors are still in degree format? Need to change to radians?

3) I think there is a fundamental problem with your logic on moving the camera. I'm guessing at your intention here, but I don't think you can apply those matrix by setting the cam position and target, then applying a rotation and getting the effect you want. Lets say it's kinda of FPS perspective with respect to the input your using. When the player hits 'W' are they really suppose to be moving in the direction of 'Vector.Forward', I would think they should be moving the the direction of whereever the camera is pointed (CameraTarget - CameraPosition). Your setup is placing the camera at some position, then rotating it. Well that rotation happens around 0,0,0, not the camera itself. If the camera's position is not 0,0,0 and then you rotate it, your not gonna get what you want.

Calculate the rotation first. Put the Camera at 0,0,0, and the camera target at 0,0,1 or whatever FORWARD is. Then rotate the camera target and camera up by your Y/P/R matrix. Then translate that by the camera position. Otherwise, leave the camera target alone.

Forget about the move input for the moment. Rebuild your code with hard coded input so you can remove that as a variable. Do something simple like have the yaw change rate match it's forward velocity such that it should move in a circle. Then you can see how a yaw input, plus forward movement effects the camera.
> 1 votes

---
Tags: c#, camera, monogame
---


# Question
Title: XNA - Isometric View not rendering mesh correctly
New to XNA (3D) -- familiar with OpenGL (but it has been a few years).

I've been working on an engine that should be a 3D Isometric View, but I'm having issues with things rendering. I wouldn't be shocked if I'm doing it the "wrong" way.

To start -- I'm assembling a bunch of terrain, which is procedurally generated into a Vertex. I'm using X/Y as my ground (N/S/E/W) coordinates and Z as my vertical (Up/Down). I assemble a map into the VertexBuffer based on its absolute world coordinates, i.e. Map is 256x256 tiles; a Map is a Tile on the world, also 256x256, so 0,0 Position of the Map on the World would be 0,0 -\> 255,255; world position 1,0 would contain 256,0 -\> 511,255 (top left -\> bottom right).

I've followed a few tutorials and thankfully gotten some help on setting things up, but I feel as though something is still "wrong." My scene is not drawing correctly. It looks as though only ONE face of my scene is being drawn -- perhaps I haven't setup the Depth buffer correctly? When I rotate (I just change Rotation on the object pCamera), once I turn ~90-180 degrees, I start missing pieces of the Mesh. To me, it seems like the Depth isn't configured properly. I know in GL, we had to manually set the DEPTH\_BIT / flag to on. I haven't set a World matrix to this BasicEffect, since the VertexBuffer is already built in the World coordinates.

I've confirmed the VertexBuffer is properly written/assembled. The values are all correct. The VertexBuffer is full of triangles only -- so I'm just using a TriangleList.

The VertexBuffer (TileMeshVertexBuffer) is being attached to a BasicEffect (TileMeshEffect), and this is the extent of my code:

```
            TileMeshEffect = new BasicEffect( GraphicsDevice );

            if ( _priorResolution != pCamera.Resolution )
            {
                Single Width = pCamera.Resolution.Width / MapTile.DIMENSION;
                Single Height = pCamera.Resolution.Height / MapTile.DIMENSION;

                TileMeshEffect.Projection = Matrix.CreateOrthographic( Width, Height, 1, 2000 );

                _priorResolution = pCamera.Resolution;
            }

            if ( _priorCenter != pCamera.Center || _priorRelativePosition != pCamera.RelativePosition || _priorRotation != pCamera.Rotation )
            {
                Single AngularUnit = pCamera.Resolution.Height / MapTile.DIMENSION;
                //pCamera.RelativePosition is 0, 0, 20
                //pCamera.Center is 128,128,60 (center of the mesh -- current elevation for the tile is at 50, so the middle tile it is focused above is 128,128,50; or composed of 127,127,50 -> 128,127,50 -> 128,128,50 and 127,127,50 -> 128,128,50 -> 127,128,50 (two triangles).
                //I've confirmed the other faces are correct for this tile as well, since it is actually rendering a cube.

                //The goal is to rotate around the Z axis -- perhaps this is the part that is wrong, but I feel as though I'd still see cubes, just rendered unusually.

                Vector3D CameraLocation = new Vector3D( pCamera.Center.X + pCamera.RelativePosition.X + AngularUnit * Math.Cos( pCamera.Rotation ),
                    pCamera.Center.Y + pCamera.RelativePosition.Y + AngularUnit * Math.Sin( pCamera.Rotation ), pCamera.Center.Z + pCamera.RelativePosition.Z );

                TileMeshEffect.View = Matrix.CreateLookAt( CameraLocation.ToVector3(), pCamera.Center.ToVector3(), Vector3.UnitZ );

                _priorCenter = pCamera.Center;
                _priorRelativePosition = pCamera.RelativePosition;
                _priorRotation = pCamera.Rotation;
            }

            //Texture is good -- all tiles are only mapping to one tile, statically on the texture, nothing else.
            TileMeshEffect.Texture = TileMeshTexture;
            TileMeshEffect.TextureEnabled = true;

                TileMeshEffect.CurrentTechnique.Passes[0].Apply();
                GraphicsDevice.SetVertexBuffer( TileMeshVertexBuffer );
                GraphicsDevice.DrawPrimitives( PrimitiveType.TriangleList, 0, TileMeshVertexBuffer.VertexCount / 3 );

```

I've cut and pasted things -- but this is essentially all I have. Aside from that, the GraphicsDeviceManager has the following set:

```
        Graphics = new GraphicsDeviceManager( this )
        {
            PreferredBackBufferHeight = 720,
            PreferredBackBufferWidth = 1280,
        };

```

I'm setting normals on each of the Triangles in my VertexBuffer -- so they're VertexPositionNormalTexture's -- and again, I've confirmed that these values are all correct.

This is what I see: https://i.stack.imgur.com/q6jg3.jpg

EDIT:

I've added the following code (Culling!) before I render the scene, and I get MUCH closer. However, I still have some issues with rotation, wherein pieces do not render.

```
                GraphicsDevice.RasterizerState = new RasterizerState()
                {
                    CullMode = CullMode.None
                };

```

https://i.stack.imgur.com/WhuGw.jpg

There are now "holes" in the terrain as it rotates.

# Answer
...as we should always do -- check your code over and over -- for some reason, my code wasn't drawing the "bottom" set of triangles (user-error). Oy.
> 1 votes

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


# Question
Title: LAN multiplayer game for desktop and Android in Unity 3D
How can I add an option "Multiplayer on LAN" to my desktop and Android game? I am using Unity 3D, and I am currently building a chess game.

Just give me the source or a specific path that I have to follow. Any shared material or criticism will be appreciated.

# Answer
This is just from my experience in creating something using LAN.

When you create your UI, under your connection buttons etc (You probably have this by now) for connecting via lan, have the IP created start with something like 192.168... This will absolutely not work over the internet, but will allow your unity game to connect VIA the lan network, you will of course need all your code for creating a local client and a server etc on the local client, but i assume you have that already (If not i can update my answer to give advice on that)

http://forum.unity3d.com/threads/help-setting-up-a-lan-connection.117092/ : This question is good help for a direction to go in, and that forum has allot of resources if you do some digging.

Hope it helps.
> 1 votes

# Answer
if you have working online that's either p2p or has server running on the host's machine (minecraft, terraria, etc..) you already have working LAN, the only difference is the IP would be a local IP instead of a public IP.

if you have no online whatsoever you should probably be looking for that instead of just LAN, since it's the same thing, playing over network, size of the network is irrelevant.
> 0 votes

---
Tags: unity, multiplayer
---


# Question
Title: Simulate dirt spread (Normal distribution?)
-This question is technically more math related, but it has to do with a simulation so I am here first. I can post this in the math SE instead if needed.

I am in the process of trying out some mesh deformation simulating the effect of sand/dirt being poured in a pile (Think hourglass sand) and I am trying to determine the best way to calculate the spread instead of becoming increasingly taller. I don't intend on actually matching sand/dirt physics, I just want to get my mesh to be somewhat close to the shape that pile would make as it grows.

I'm pretty sure that Normal Distribution is what I want, so in my desmos graph below, think of f(x) -green line- as the current dirt/sand piling up (where I am at in my code) and f1(x) -purple line- as the spread version (what I want to happen instead).

f1(x) is not correct but I *think* it is pretty close. Essentially i need the area of f1(x) to always equal the area of f(x) but as f(x) gets taller, f1(x) gets wider and taller, but not as tall as f(x).

https://www.desmos.com/calculator/ir8if2u8qq

```
<a title="View with the Desmos Graphing Calculator" href="https://www.desmos.com/calculator/ir8if2u8qq">  <img src="https://s3.amazonaws.com/calc_thumbs/production/ir8if2u8qq.png" width="200px" height="200px"     style="border:1px solid #ccc; border-radius:5px"  /></a>
```

I hope this makes sense to you gurus. If not, I can try to clarify more.

Edit: Also, if you open that graph, the slider for variable 'h' is the one im essentially trying to work with.

# Answer
If you want/need to follow real world physics, the key factor you need is called the critical angle of repose, which refers to the steepest angle of descent or dip relative to the horizontal plane to which a granular material can be piled without slumping. At this angle, the material on the slope face is on the verge of sliding. The value varies depending upon material and conditions is influenced by things such as material density, surface area and shapes of the particles, the coefficient of friction of the material, additions of solvents & electrostatic attraction.

According Thomas Glover's Pocket Reference (used by contractors, engineers), the critical angle of repose for earth is 30 to 45°. As context, the values for dry & wet sand are 34° & 45° respectively. At present, these & other values are available on the Wikipedia entry I linked above.

If you're making a game, there's something to be said for using values that work for your game rather than following real life. Case in point, Mario isn't subject to standard Earth gravity. On the other-hand, if you're building an engineering tool, you should probably check with some engineers.
> 1 votes

# Answer
If you're looking at different symmetrical graphs to simulate a natural thing (like sand piles in your case) then you're doing something wrong.

Sand doesn't work like a math equation. Sand is a particle system. Imagine each sand particle as a separate object with momentum and gravity. Those two plus the friction between 2 particles define how it moves.

Sand moves the same as if you would throw actual rocks on each other. The first hits the ground, maybe bounces a bit, but then stays at a place. The second hits it, loses it's momentum a bit (the other takes it up and some of it becomes heat too), and as gravity dictates, it starts to roll off from it. This happens multiple times. At a point it will be hard to roll off from the already existing small pile because it's big, so one eventually stays at the top of the current pile and it starts over again.
> 0 votes

---
Tags: 3d-meshes, simulations
---


title: Windows Forms game loop

text:
# Question
Title: Windows Forms game loop
There is a very good game loop in the link which is tailored for windows forms. I need it in c++/cli so I converted the code as below. Here is my main loop.

```
using namespace System;
using namespace System::Windows::Forms;

HWND g_theAppHandle = nullptr;

bool IsApplicationIdle()
{
  MSG msg;
  return PeekMessage(&msg, g_theAppHandle, 0, 0, 0) == 0;
}

void OnIdle(System::Object ^sender, System::EventArgs ^e)
{
  while (IsApplicationIdle())
  {
    if (PunkEd::ABTCLI::g_initSuccess)
    {
      PunkEd::ABTCLI::Frame(0.0f);
    }
  }
}

[STAThread]
int CALLBACK WinMain(
  _In_ HINSTANCE hInstance,
  _In_ HINSTANCE hPrevInstance,
  _In_ LPSTR     lpCmdLine,
  _In_ int       nCmdShow
  )
{
  _CrtMemState memstate;
  _CrtMemCheckpoint(&memstate);

  PunkEd::PunkEdMain^ theApp = gcnew PunkEd::PunkEdMain;
  g_theAppHandle = (HWND)theApp->Handle.ToPointer();

  Application::Idle += gcnew System::EventHandler(&OnIdle);
  Application::Run(theApp);

  _CrtMemDumpAllObjectsSince(&memstate);
  return 0;
}

```

This loop triggers **PunkEd::ABTCLI::Frame(0.0f);** every time the application is idle. And **Frame(float deltaTime);** function triggers everyting related to game. Like render and physics. However my rendering window is a panel. And I override its mouse move callback as below.

```
private: System::Void panel1_MouseMove(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e) {
  Debug::WriteLine(e->Location);

  glm::vec3 cp = glm::vec3(e->Location.X, e->Location.Y, 0);
  glm::mat4 view = g_camera->GetViewMatrix();
  glm::mat4 project = g_camera->m_projection;
  glm::unProject(cp, view, project, glm::vec4(0.0f, 0.0f, (float)panel1->Width, (float)panel1->Height));

  cp.x -= panel1->Width / 2.0f;
  cp.y -= panel1->Height / 2.0f;

  g_cursor->m_node->m_translation = cp.xzy;
}

```

This function updates my curser's position in the game. ***However my render function is get called after I stop moving the mouse.*** How can I overcome this stuation such that my curser position gets update and renders immediatly after I moved mouse.

# Answer
For the technique presented in the answer you linked to work well, you need to keep the event queue as empty as possible, because the emptying of the queue is what drives your update and render callbacks.

The scenario you are seeing likely occurs because mouse movements are Windows events (`WM_MOUSEMOVE`), and by hooking them in the panel and doing a bunch of work during one, you keep the event queue full longer than usual (this is partly because `WM_MOUSEMOVE` is a bit special, and if the mouse is moving you'll basically get one event every time `GetMessage` is called on your behalf).

While the event queue is "full" of these events, you won't receive `OnIdle` callbacks and your game won't "remain idle" for the purposes of `OnApplicationIdle`. Since you only render when the game is idle, you thus defer rendering noticeably while moving the mouse.

When you don't do anything for mouse-move events, they process out quick enough that you don't notice (that `Debug::WriteLine` is going to be particularly slow).

One possible solution then is to avoid hooking mouse move events or doing expensive stuff in them, and instead directly querying the state of the mouse every update tick (which should also happen inside your "is idle" loop).
> 1 votes

---
Tags: game-loop, windows-forms, c++cli
---


# Question
Title: AI: dealing with movement driving the same inputs as the player
My AI design is pretty simple. I have different entities that can be possessed either by the player or the AI. Those entities have an "Input" component that holds the states of the actual inputs, like right, left, up, down, fire. (and wasRight, wasLeft, wasUp, wasDown, wasFire to perform checks on whether the input was just triggered or not).

My PlayerController class is driving that component by reading inputs from either the keyboard or the gamepad.

In a similar way, my AIController comes up with that same input through logic functions.

Now I've hit a wall with this kind of approach when dealing with movement.

Let's say that I'm in 2D space and that I'm moving the AI horizontally. I am moving from (0, 0) to (10, 0) so I'm activating the "right" input all the way until I reach the (10, 0) position.

But if the speed of my entity is high, I might actually go over the position and trigger a movement back, and then again forward and so on as it can't actually settle. I know that I could just check if the previous movement was in the same direction and that if I went through the target I could just force the position to be in the exact spot that I want to reach. But it doesn't really look like a clean solution.

Is this approach completely wrong? I would like to try and keep it simple and modular at the same time.

# Answer
Several possible solutions; one or a combination may be right for you.

**Steering Behavior**

Basically, in this case, that means that you AI needs to slow down as it approaches the target location. This would mean that you need non-binary movement commands, which might be good if you ever plan to support gamepads (thumbsticks) anyway.

**Wider Targets**

Essentially, add a tolerance to the target location. Then, overshooting is less likely to cause the oscillation. Also, this can avoid micro-oscillations caused by floating point inaccuracy. If you're already using tolerances, maybe make them bigger.

**Physics/Controller Ticks**

You mention that if "speed is high" the AI might overshoot. This speaks to a fundamental problem you have: your speed can be *too high per update tick*. For stable physics, you really want a max speed per tick (to avoid tunneling and other problems). If you need objects that move really fast, that just means that you need multiple physics ticks per frame.

This can then easily combine with the player controller and AI. Allow the controller and AI to update per physics tick. That lets the AI re-evaluate if it should stop much more frequently so even fast-moving AI entities will only move very small distances per check.

Doing this is particularly helpful with networking where you want to synchronize per-tick for smoothest behavior.
> 2 votes

---
Tags: movement, ai, entity-system, component-based
---


# Question
Title: Rotating, moving and scaling a mask in a shader
I want to rotate, move or scale a mask in a shader. But I have no clue to how perform these actions.

My code:

```
@Override
public void create() {
batch = new SpriteBatch();

background = new Texture(Gdx.files.internal("images/background.png"));
spritebackgournd = new Sprite(background,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());

foreground = new Texture(Gdx.files.internal("images/foreground.png"));
mask = new Texture(Gdx.files.internal("images/mask.png"));

 spriteforegournd = new Sprite(foreground,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());

shader = new ShaderProgram(Gdx.files.internal("shaders/shader1.vert"), Gdx.files.internal("shaders/shader1.frag"));
}

@Override
public void render() {

batch.begin();
spritebackgournd.draw(batch);
 batch.setShader(shader);
    Gdx.graphics.getGL20().glActiveTexture(GL20.GL_TEXTURE0);
    spriteforegournd.getTexture().bind(0);
    //texture.bind(0);
    shader.setUniformi("u_texture", 0);
    Gdx.graphics.getGL20().glActiveTexture(GL20.GL_TEXTURE1);
    //spritemask.getTexture().bind(1);
    mask.bind(1);
    shader.setUniformi("u_mask", 1);
    Gdx.graphics.getGL20().glActiveTexture(GL20.GL_TEXTURE0);
    spriteforegournd.draw(batch);
    batch.end();
    batch.setShader(null);
   }

```

The vertex shader:

```
attribute vec4 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;

uniform mat4 u_projTrans;

varying vec2 v_texCoords;

void main() {
v_texCoords = a_texCoord0;
gl_Position = u_projTrans * a_position;
}

```

The fragment shader:

```
varying vec2 v_texCoords;
uniform sampler2D u_texture;
uniform sampler2D u_mask;
uniform mat4 u_projTrans;

void main() {
vec4 texColor = texture2D(u_texture, v_texCoords);
vec4 maskColor = texture2D(u_mask, v_texCoords);

gl_FragColor = texColor * maskColor.a;
}

```

What I would like to be able to is to scale, rotate and move the mask in the shader. How can I do this?

# Answer
> 1 votes
When I was running into this, this tutorial saved me. Google saves lives. Multiple Texture Units

Most of this comes from there. You have a foreground, a background, and a mask.

So trying getting the alpha layer of the mask and use 'mix'

```
//get the mask; we will only use the alpha channel
float mask = texture2D(u_mask, vTexCoord).a;

//interpolate the colours based on the mask
gl_FragColor = vColor * mix(texColor0, texColor1, mask);

```

So your code would look like this:

```
//"in" attributes from our vertex shader
varying vec4 vColor;
varying vec2 vTexCoord;

//our different texture units
uniform sampler2D u_texture; //default GL_TEXTURE0, expected by SpriteBatch
uniform sampler2D u_texture1;
uniform sampler2D u_mask;

void main(void) {
    //sample the colour from the first texture
    vec4 texColor0 = texture2D(u_texture, vTexCoord);

    //sample the colour from the second texture
    vec4 texColor1 = texture2D(u_texture1, vTexCoord);

    //get the mask; we will only use the alpha channel
    float mask = texture2D(u_mask, vTexCoord).a;

    //interpolate the colours based on the mask
    gl_FragColor = vColor * mix(texColor0, texColor1, mask);
}

```

For scaling, you can scale through the texture coordinates. They are in range from 0-1 so here is what I found if you want to scale from the center of the texture:

```
    texCoords = (texCoords - 0.5) * scale + (0.5 * scale);

```

---
Tags: libgdx, shaders
---


# Question
Title: What is the math behind rendering isometric with the aid of Depth Maps?
I am currently in the process of designing an Isometric game, and one of the features we are trying to add, is using sprite depth maps to render geometry in the correct order.

The reason we are trying to do this, is a number of our game objects make use of overlapping sprites, and the animation is not always in sync with it's other parts.

I do have experience with working in 3D. But the issue comes to using something that is normally generated on the fly, pre baking it, and then retrofitting it to work with what ever distance.

So... something similar to what the sims has done with it's objects.

Linky

# Answer
You can pretty much think of this as deferred shading.

At least if I understand your question correctly, you are asking how to handle depth information that is stored in a texture for a sprite you are rendering.

If you have experience with 3d reading up on how deferred shading works shouldn't be hard.
The method used in the sims seems to be very similiar to just adding the appropriate depth to how you would render a billboard into a G-buffer.
> 1 votes

---
Tags: 2d, graphics, sprites, isometric, depth-buffer
---


# Question
Title: Save data in scene without transferring game object in Unity
My game requires the user to continuously come back to a particular scene

`DontDestroyOnLoad` transfers the gameobject from one scene to another (without destroying it).

Is there a way to save the data in a scene without transferring the game object, but when the user comes back to the 'particular' scene, it continues from there.

for e.g

```
inputgiven = false

if(input.anyKeyDown){

inputgiven = true;
Application.LoadLevel("Scene2");
}

```

So when the user comes back to this scene `input.given = true`.

*I am sorry if the question or some aspects of the question are unclear. This was really hard to explain. (please just leave a comment if it is unclear)*

# Answer
The usual method would be to use `DontDestroyOnLoad` on something like a manager or "bookkeeping" object - something that's invisible to the player, but keeps track of important state information so it can be carried from scene to scene.

If you do this, you'll want to be careful to ensure this object is always available, even if you jump straight into testing scene 5 without going through the previous scenes, and that you don't build up unwanted copies of the object. Some ways to do this are:

* Put the manager object in every scene, and have it destroy itself on load if a copy has been carried over from a previous scene. This gets messy and error-prone though.
* Have the manager object create itself the first time it's needed, using something like a Singleton pattern with a static `GetInstance()` method to return the current instance, or create one if it's missing.
* Write an Editor script that adds the manager object to the scene when you hit play, or redirects the editor to load an initialization scene (containing your manager objects) and *then* load the scene you want to test.

This can also be done with a static class, which handles keeping the data always accessible and unique, but it can do so *too well* in a sense:

* the data is always accessible, even if you don't need it in the current game state - the static members keep occupying space in memory whether you want them there or not. (While a manager object on the other hand can always be deleted/destroyed once you're done with it)
* the data is unique, even if you want to duplicate the data in order to add multiplayer or parallel universes or other mechanics. (While on the other hand you could have multiple copies of a manager object, one for each player/universe, so long as each piece of gameplay knows which manager to use)

So, providing this feature structurally via a static class makes it simple to set up, but changing the behaviour down the line can mean big structural changes.

Either of these methods may require some re-wiring once you load back to a previous scene. From Unity's perspective, the GameObjects in the scene are all newly-created, and have no relationship to their previous incarnations - even their ID values will be different. How exactly you solve this will depend on the needs of your scene, and may be worth a detailed question of its own.

We can partly farm out the saving responsibility to the individual objects whose state needs to be saved, though you still need a central manager object or static member to store the data. To do this you'd generate a unique ID on each object that needs saving, so it can identify data from its past lives. On quitting a level, the object would submit its data to the manager to be saved, indexed by its unique ID. On loading, it would ask the manager if data already exists for its ID, and override its initial state with the manager's response if so. This simplifies the rewiring logic, since all we need is that the saveable objects can find the manager.

Lastly, if the data you're saving needs to be persistent between runs of the game, you can use PlayerPrefs. Just note that this data is stored in plaintext, so don't put anything there that you don't want the player peeking at or modifying outside the game.

You can also serialize this data to a custom file format yourself, but in that case you'll still want a manager object to hold the current state in memory & handle serialization, so you don't have to read & write a file every time a script uses this state.
> 1 votes

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


title: Unity Editor windows went black

text:
# Question
Title: Unity Editor windows went black
I recently bought a new laptop, with Intel i5-5200U HD graphics 5500 and AMD Radeon R5 M230 2GB and 8gb ram, and heres what happens with my Unity: If open it, minimize it and then maximize again, it'll render some weird black screen in random areas of the editor, like this:

But, if I instead of minimizing unity and just opened other window , when I go back to unity nothing happens, no black weird "squares". So this just happens when I minimize unity itself and then maximize it, if I maximize another program over unity and then open unity again, it will not happen. Can anyone please tell me why this happens??? I always have to restart unity.... Is this a problem with my video card? plz help

# Answer
If you have dual graphics: force Unity not to use integrated graphics, and then restart Unity.

I switched from Intel integrated graphics to nVidia graphics for Unity in

```
NVIDIA Control Panel
  -> Manage 3D Settings
    -> Program Settings
      -> Unity
        -> High-performance NVIDIA processor

```

This solved the problem for me.
> 1 votes

# Answer
According to this thread, an issue similar to this is known and a fix is in the works.

As a temporary workaround, users report that running Unity with the command line flag:

```
-force-gfx-direct

```

will force the editor to run single-threaded and stop the issue from occurring.

You can add this flag to the shortcut you use to run Unity. Let me know if you need instructions how.
> 0 votes

---
Tags: graphics, unity, bug
---


# Question
Title: Is it possible to create a homemade depth buffer?
Studying the case of isometric rendering, I'm facing a big and well-known problem : depth sorting.

After many researches it seems that without tile mapping or 'height-leveling' it's impossible to solve this problem in a 2D game.
So I imagined a depth buffer that I could use with sdl\_textures . The process : each sprite would contain pixels , with rgba AND a depth variable . When it comes to blit, I would check in a backbuffer the pixels that are nearer than the current pixels and replace them. Then I would convert the buffer to a texture with only four channels (rgba without depth) in order to SDL\_Rendercopy it .

**My questions are:**

* Is it possible to do so ?
* Isn't it too slow to check each pixel of a 1024×768 screen in this kind of scheme ?
* How do I create a sdl\_texture from an simple array of int ?

# Answer
> 2 votes
Of course it is possible, if people can write a depth buffer you can too, but it will be **hideously slow**. Reading from and updating SDL2 textures is very slow because it's all via software, i.e. not hardware accelerated. Proper depth buffers operate at the rasterisation step and are accelerated via your massively parallel graphics hardware.

Since SDL2 doesn't do z-ordering, your options are:

* Do per-texture z-ordering (note: SDL2 textures) yourself. Add every texture you want to render into a collection, sort it using an algorithm that is fast on almost-sorted data (like insertion sort or Timsort), then `SDL_RenderCopy` in back-to-front order.
* Use a 3D graphics library like OpenGL, render everything as 3D textured quads, and let the built in depth buffer solve the problem.
* If your sprites have complex depth or overlap, you may be able to split the sprite into multiple parts and order the parts independently. Otherwise, the only performant method (without going full 3D) would be to write a custom shader that works with the depth buffer.

---
Tags: depth-buffer, sdl2
---


title: Stomp on Enemies in Unity to Kill them

text:
# Question
Title: Stomp on Enemies in Unity to Kill them
I want to create a game where the main character can pass through all the zombies that are chasing him but he can also jump up and bounce on their heads to kill them (like in old mario)...

The problems I am running into are:

1. When I am in the same position as the zombie and jump to kill him the trigger collider triggers the Destroy(Zombie) method. I only want them to be killed when you "Stomp" on them.
2. How do I make the character able to pass through the zombies without falling through the floor?

Here is my code for the trigger event that is attached to the "Stomper" box collider on my character.

```
     void OnTriggerEnter2D (Collider2D other) {
    if (other.tag == "EnemyHead") {

        //Destroy
        Rigidbody2D playerRB = transform.parent.gameObject.GetComponent<Rigidbody2D> ();
        playerRB.velocity = new Vector2 (0, 0);
        playerRB.AddForce(Vector2.up * 10, ForceMode2D.Impulse);

        Destroy (other.transform.parent.gameObject);

    }
}

```

Let me know if you need anything else. I am trying to explain this as well as possible...

# Answer
> 2 votes
As mentioned in the comments you can add the zombies to another layer and ignore it for collision with the player.

For your stomp mechanic: A quick solution would be to check the velocity of the player. When the player is 'stomping' you can define that the player needs to be on the downward part of the jump. So you check if your y component is less than 0, the destroy and apply the new velocity.

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


# Question
Title: What algorithm to use for random terrain?
(Please note, I am aware that the generation is not truly random and relies on mathematical equations, and that my language of choice is C++)

So I've been learning programming for a while now and I'm looking to make a top down 2D game. I want this game to generate random terrain pretty much like Dwarf Fortress but with sprites, however for this question let's just say that there just ASCII characters. I want it to generate mountains, rivers, inland lakes etc. I know of algorithms but have not been able to find a list of them all. The ones i know of are:

Perlin Noise, Diamond Square, Midpoint Displacement and some other minor ones.

However I don't know which one to use and struggle to find a good article on any of them. Is there one right for the job, or does it just come down to personal opinion? And if you can find a list of all the algorithms and maybe a good article on one it would really help. Thanks!

# Answer
> 1 votes
This is the code that generate this kind of terrain (background for my "platform" game): https://drive.google.com/open?id=0B5yRPbmIAqr0X2wwX1BwNTZZMHc

(I hate python so sorry if this is an horrible code, and english is not my main language, so be patient pls)

```
import sys
import random
import pprint
import math
w = 350 #width of the terrain
h = 350 #height "  "    "

sz = 10 #size of a tile

sz_x = w / sz
sz_y = h / sz
area = sz_x*sz_y

bkg = [[' ' for x  in range(sz_x)] for y in range(sz_y)] #initialinzing background matrix

plates = [' ', '/', '.', 'I', '#'] #tile types
#each plates has it own probability to be "spawned", the following array is
#defined as couples of (total_previous_probability + this_probability / 2, (this_probability / 2) ^2)
probability = [[2.5, 2.5**2], [35, 30**2], [72.5, 7.5**2], [85, 5**2], [95, 5**2]] #5, 60, 15, 10, 10
temp_probability = [0, 0, 0, 0, 0]
nm_plates = [0,0,0,0,0] #for debug purpose

def get_random_plate(temp_prob):
    plate = 0
    max_prob = 0
    i = random.randint(0, 100)
    for p in range(len(plates)):
       prob = -(i - probability[p][0])**2 + probability[p][1] + math.sqrt(temp_prob[p] / 9);
    if(prob > 0 and prob + temp_prob[p] > max_prob):
        max_prob = prob+ temp_prob[p]
        plate = p
return plate

#list of predefined point (x, y, types), you can make this random
#in the link you can see five different "big areas" of one types built around theese point
#you can have a lot more of this points, more points of the same time you
#have in a little area more this area will be filled with the type of that points
sp_point = [
[10, 10, 0],
[27, 5, 0],
[15, 25, 2],
[25, 25, 2],
[5, 29, 3],
[16, 16, 4],
]

def create_bkg(temp_prob):
for y in range(sz_y):
    for x in range(sz_x):
        temp_prob = [0, 0, 0, 0, 0]
        for p in sp_point:
            sqrDist = (x - p[0])**2 + (y - p[1])**2
            temp_prob[p[2]] += (area / (sqrDist + 0.1))**3

        plate = get_random_plate(temp_prob)
        nm_plates[plate] += 1
        bkg[x][y] = plates[plate]

def print_bkg():
    for y in range(sz_y):
        for x in range(sz_x):
            sys.stdout.write(bkg[x][y])
        print ''
    print '\n'
create_bkg(temp_probability)
print_bkg()
pprint.pprint(nm_plates)

```

This generates the tile map, then I think you can create something like an height map: you read each tile of the matrix and "make it higher or lower" (I don't know how to say that) based on the surrounding tiles:

```
#pseudo code
if (this_tile_is_a_mountain) count mountain tiles in an area of x tile;
this_height += (number_of_mountain_tiles_found * x)^y / z
#and so on, same for lakes

```

In the code above you can edit some line to change the behaviour of the algorithm:

```
temp_prob[p[2]] += (area / (sqrDist + 0.1))**3 #you can change how temp_prob is computed

#more higher it is more "dense" will be the "one type" areas
#or you can reduce the effect it has on the result editing the following lines:
prob = -(i - probability[p][0])**2 + probability[p][1] + math.sqrt(temp_prob[p] / 9); #change this nine, remove the sqrt, add another sqrt sqrt(sqrt(x))
if(prob > 0 and prob + temp_prob[p] > max_prob): //add a here: sqrt(temp_prob[p])
    max_prob = prob+ temp_prob[p] //or add it here, or both
    plate = p

```

Just try

(I really need someone who can rewrite this in real english...)

---
Tags: terrain, random, procedural
---


# Question
Title: Platform Cannot move down when player collide buttom of platform Unity?
In my unity game I've arrange different platform ,when my player collide with upper part of the platform so platform falling down but issue that when my player collide to platform buttom of part so platform falling down.

```
void OnCollisionEnter2D(Collision2D target)
{
        if (target.gameObject.tag == "Player") {
        gameObject.GetComponent<Rigidbody2D> ().isKinematic = false;
    }
 }

```

# Answer
```
void OnCollisionEnter2D(Collision2D target)
{
    if (target.gameObject.tag == "Player")
    {
        Vector2 normal = target.contacts[0].normal;
        if (normal.y < 0)
        {
            gameObject.GetComponent<Rigidbody2D>().isKinematic = false;
        }
        else
        {
            //Make player pass trough platform if you want this behaviour.
        }
    }
}

```

This code should work as you expect it to. I did a rudimentary test with it and it does work. Note this does not allow the player to pass trough the platform if hitting it from the bottom. I have added a comment where you need to implement this.
> 1 votes

---
Tags: unity, rigidbody
---


# Question
Title: What's the best way to generate an NPC's face using web technologies?
I'm in the process of creating a web app. I have many randomly-generated non-player characters in a database. I can pull a lot of information about them - their height, weight, down to eye color, hair color, and hair style.

For this, I am solely interested in generating a graphical representation of the face. Currently the information is displayed with text in the nicest way possible, but I believe it's worth generating these faces for a more... human experience.

Problem is, I don't know where to start. Were it 2007, I'd naturally think to myself that using Flash would be the best choice. I'd love to see "breathing" simulated. However, since Flash is on its way out, I'm not sure of a solid solution.

With a previous game, I simply used layered .PNGs to represent various aspects of the player's body: their armor, the face, the skin color. However, these solutions weren't very dynamic and felt very amateur. I can't go deep into this project feeling like that's an inferior way to present these faces, and I'm certain there's a better way.

Can anyone give some suggestion on how to pull this off well?

# Answer
The way you are thinking to do it is fine. You should drop inhibitions about Flash and just use it. You aren't writing a bank system here, you're writing a single game. Even if it does have a sequel, Flash is still installed on pretty much every computer today.

Just a note that the best face generator I've ever come across is facegen.

There is a FaceGen SDK. I don't really know what it costs, but I'm guessing it must be in the thousands. Then, you have FaceGen create a face, using your inputted parameters (for eyes spacing, skin color etc - FaceGen can do all that). Then, you render the face to a texture, save it out, and send it over to the other application.
> 1 votes

# Answer
Have you ever seen old movies where they use an Identikit (little strips of transparent plastic beside each other) to reconstruct a perpetrator's face? Basically, that's what you want to do. Image files with transparency for pre-defined slices of a face, plus one or two for the actual head and face shape, another one for the hair style.

Since you're in 2D, you'd need a separate image for every facial feature for every angle it can be viewed from (e.g. front, left, right, back ...). Then you draw them on top of each other, and maybe cache the pre-rendered head (e.g. in another image file, or as a data: URL or whatever) so you don't have to draw it over and over again.

This works similarly for the body, just that you need separate sets of slices for arms, legs and the parts of the torso, so you can rotate arms (think of how South Park looks, or how an action figure is made for inspiration on how you do the individual parts - take apart a G.I. Joe figure for instance).

For the various body types, you might be able to get away with just stretching the image sideways. Or rather, what you really want to do is draw your character wider and then horizontally compress the image for the narrower body types, because stretching an image means the computer will double pixels (where it *should* add detail), whereas if you compress it, it will remove pixels (and thus some of the "wider body type" detail, giving the appearance of adding detail to the wider ones if you do it right). If that doesn't look right, you can probably at least draw fewer body types and then make intermediate steps by compressing horizontally.

Of course, you can add shading layers that you'll only draw at certain levels of compression, e.g. a "sagging cheeks" layer at 1.0...0.9, nothing at 0.91...0.5, and "sunken cheeks" shading layer at anything below 0.5 or so, to improve the illusion. Just make sure to apply all of this to the slice when seen straight, *before* you rotate it, or it'll end up stretched/compressed in the wrong direction.

If you have a simple drawing style, you could also just draw the faces as vectors and then multiply the coordinates (or transform the coordinate system with a horizontal scale, I forget if Canvas supports that). This would also make it easier for clothes, because those might have to stretch with the character's body, and you might need special versions that show off a character's muscles (could probably be approximated with optional shading layers again). If you draw these in vectors, you could just straighten out the curves you draw for muscles for skinnier characters, or fill the character shape with a different color/texture.
> 1 votes

# Answer
This is a very good question! Unfortunately I can't suggest anything more than what probably you already know:

1. Prepare 10 faces in Photoshop or Flash or other drawing tool with layers.
2. Put every face element like nose, eyes, eyebrows etc. on a separate layer.
3. Design the faces the way all elements are on same place.
4. Hide all elements except one (or set as a guide layer in Flash)
5. Save as .PNG file and repeat for other elements
6. Put these .PNG files in groups, and generate faces by overlapping random PNGs, one of every type on top of each other.
> 0 votes

---
Tags: graphics, html5, browser-based-games, content-generation, visualization
---


# Question
Title: What is a cheap (better free) way to make multiplayer in a shooter?
I'm a newbie indie, so I don't have a budget for a game. But I'm making a 3rd person shooter and I need multiplayer for it.
It's a mech shooter, so it won't have very fast movements, meaning I don't need fast sync between participants.

I've thought about **peer-to-peer**, it seems good, but what if the host's PC crashes or they just kill the game? It would be the end of the whole match! So it seems like I need to have some sort of centralised server, but do I really need a dedicated server, and even a number of servers to be able to host thousands of matches? Or can I sync it through database services like playfab somehow?

# Answer
You could make the dedicated server software an executable and distribute it with the game, probably have a host&play option in the game itself which would launch this server in the background and connect to it.

Some games that do this are minecraft and terraria.
> 4 votes

# Answer
You could make rooms where each room picks the first joined user as the host and makes him run the server, and when he logs off the server can pick a new host either randomly (if net speed doesn't count) or the user with the fastest connection.

By putting the majority of the calculations to the users you can avoid the need of buying a strong server, you will only need a weaker one to make the users able to join to the rooms.
> 1 votes

---
Tags: architecture, networking, multiplayer
---


# Question
Title: What game-mechanical purpose does an armor attribute have in RPG games?
I saw that many RPGs have some form of armor attributes. If there's no armor, we can still calculate damage taken with only 2 attributes; attack points of the attacker and health points of the receiver.

*For Example:*

**Damage taken = Attack Points of attacker**.

**Remaining HP of receiver = current HP - damage taken**.

What's the value in adding additional complexity in form of an armor stat?

# Answer
> 1 votes
Of course you don't *need* an armor value, but adding one adds an aspect to your game you might (or might not) find useful.

When you just subtract the damage from the hit points, then a level 1 peasant (1 attack) can wear down a level 100 dragon (1000 hp) when they just find a clever way to land enough hits before they get roasted.

But when your damage formula is `damage = attack - defense` then it becomes impossible for a combatant to cause any harm to something which has more defense than the combatant has attack. So when you give the dragon 100 defense, the peasant needs to level up until they are able to inflict at least 101 damage with a single hit before they even have a theoretical chance to kill the dragon.

This kind of progression mechanic (kill stuff -\> level up -\> become stronger -\> become able to kill stronger stuff) is very typical to RPGs.

Another aspect is damage vs. attack speed. Let's say your hero got two methods of attack: A single strike which does one hit with 10 damage and a combo attack which does 4 hits with 5 damage each. Which one should they use against which enemy? Without defense, it's a no-brainer. The combo attack simply does twice as much total damage, so there is no reason to ever prefer the single-strike attack. But what if they face an enemy with 4 defense? Then the first does 6 damage, but the second only 4 damage (`4 * (5 - 4)`). Now the decision which attack to use has become less trivial. The player needs to look at (or guess) the defense stat of their enemy and make a decision which attack to use. The defense mechanic adds depth to the game and gives the player more meaningful choices to make.

# Answer
> 0 votes
Edit: changed answer to make it suit to question as it is formulated for now.

In most RPG games I had experience with, armor is used for three purposes (sometimes combined):

1) It is effective way to make character gear/equipment to affect character somehow. Same to weapon increasing damage character deals, armor decreases damage character takes.

2) Equipment may grant different stat bonuses/penalties, having different pros and cons. Player may have to choose, what to prioritize - armor for physical protection (by choosing armor with high armor stat), attack speed (by choosing light-weight armor), or stats providing.

3) Some RPGs may have more complex damage/armor system, providing different kinds of damage types, each one having corresponding protection stat. Armor in this system usually represents physical damage resistance. By varying resistance stats of enemies, developer may create different situations for player - some battles will feature monsters with high physical damage resistance/armor, but will be vulnerable to magic; player will have to focus on magic skills instead of plain attacking in such situations. It also can be combined with p.2., allowing player to focus on defense against certain damage type before next battle.

Anyway, this is mostly used ways, but developer is always free to decide, how to use armor stat.

---
Tags: game-design, rpg
---


# Question
Title: glColor is working well only in debugging mode, why?
This semester I have a class that I using OpenGL and I'm trying open a window with random colors inside rectangles.

For this, I created a class that I define RGB in constructor. If I use debugging mode and I pass step by step, OpenGL renders rectangles with the correct colors but if I run my app in Release mode, all the rectangles receive the last color set.

It is strange because I created two objects. I think that each object sould have its own properties. Am I correct?

Bellow I put two screenshots, one with the program in debugging mode and the other in Release mode.

I'm a beginner in OpenGL and have some questions in c++.

Thanks,

And bellow is my code:

Constructor of my class square GEO\_Square.cpp:

```
GEO_Square::GEO_Square()
{
    srand(time(NULL));
    red = ((rand() % 10) / 10.0);
    green = ((rand() % 10) / 10.0);
    blue = ((rand() % 10) / 10.0);
}

//Function to draw
void GEO_Square::drawSquare()
{
    fillVectorWithPosition(width, height, posX, posY); //function to calculate positions

    glBegin(GL_QUADS);
    glColor3f(red, green, blue);
        glVertex2f(positions[0], positions[1]);
        glVertex2f(positions[2], positions[3]);
        glVertex2f(positions[4], positions[5]);
        glVertex2f(positions[6], positions[7]);
    glEnd();

    drawEdge();
    changeColor();
}

```

ColorGameMain.cpp:

```
int CALLBACK WinMain(
    __in  HINSTANCE hInstance,
    __in  HINSTANCE hPrevInstance,
    __in  LPSTR lpCmdLine,
    __in  int nCmdShow
)
{
    DrawRecs dRecs;
    GLFWwindow* window;

    if (!glfwInit()) return -1;

    window = glfwCreateWindow(WIDTH, HEIGHT, "Forms", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    gluOrtho2D(0.0, WIDTH, HEIGHT, 0.0);

    GEO_Square* quad = new GEO_Square();
    GEO_Square* quad2 = new GEO_Square();

    while (!glfwWindowShouldClose(window))
    {
        quad->setWidth(40.0);
        quad->setHeight(15.0);
        quad->setPosX(0.0);
        quad->setPosY(0.0);
        quad->drawSquare();

        quad2->setWidth(40.0);
        quad2->setHeight(15.0);
        quad2->setPosX(60.0);
        quad2->setPosY(20.0);
        quad2->drawSquare();

        quad->drawSquare(40.0, 15.0, 100.0, 40.89, 0.5, 0.5, 0.0);

        glfwSwapBuffers(window);

        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

```

# Answer
> 1 votes
It's not an issue with OpenGL, it's an issue with the way you use `srand()`.

Take `srand` out of there and put it in your main.

What happens is that the code executes so fast in release that you initialize the pseudo-random-number-generator with the same seed, which results in the same sequence of generated pseudo-random numbers, thus giving you the exact same scheme of colours.

It "works" in debug because it takes some time between the first quad and the second quad so the time you use to seed the generator is not the same, thus resulting in different sequences.

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