# Question
Title: In a HTML/JavaScript game, what audio should I use for Internet Explorer?
I'm planning some HTML5/Javascript games. They will be casual games for the most part, but would still benefit from music and sound effects. I would really like to use the `<canvas>` and `<audio>` features. I do **not** anticipate needing to play any movie files like .avi or .mp4.

But I run into a problem. According to this chart, Microsoft Internet Explorer does not support .wav or .ogg! And Safari doesn't support .ogg.

So now I'm making my own chart for what audio files I should use for what browsers. Here it is so far:

```
                     SFX        Music

Desktop Chrome      .wav        .ogg
Desktop Firefox     .wav        .ogg
Desktop IE          ???         ???
Desktop Safari      .wav        .m4a (alac)
Desktop Opera       .wav        .ogg

Mobile Chrome       .wav        .ogg
Mobile Firefox      .wav        .ogg
Mobile IE            ???        ???
Mobile Safari       .wav        .m4a (alac)
Mobile Opera        .wav        .ogg

```

(I could not find any info for Microsoft Edge on whether .wav or .ogg will work in the `<audio>` tag.)

As you can see, the big question lies in Internet Explorer. What audio formats should I use for sound effects and music?

It appears that HTML5 only supports 3 types: mp3, wav, and ogg. So for Safari I will need a plugin or some way to play .m4a music natively if possible. mp3 is out of the question due to absurd licensing fees. Flash/Shockwave is out of the question too.

I have read that something called `bgsound` can be used in IE, but it's "not standard". I've never used it before and don't know what it is.

So what audio formats should I use for IE? What is the "normal" way that IE plays sound and music in the first place? I really hope I don't need some plugin like Silverlight because those are a pain to users, especially casual game users.

# Answer
On Mozilla developper website you can find the following informations :

1. MP4 is **supported** by IE
2. OGG is **not supported** by IE
3. WebM is **supported** by IE with the addition of a **plugin**

Anyway, you need to know it is a real pain in the \*** to make your audio files working on all browsers. First thing to do is link the 3 formats in order to let the browser chose the one it prefers, but even then you will likely encounter many incomprehensible issues due to the high diversity of browsers, versions, etc...

***Note :***

Even though it does not answer the question, I think it is worth noting that an easy solution would be not to support Internet Explorer for your game. The majority of people still using IE are either companies or old people. Either way, these people are less likely to play your game, so you should weight out if you are not going into useless troubles trying to make IE support.
> 1 votes

# Answer
First ask yourself this question: Why am I going to use web technologies for my game project?

If the answer is similar to this: "Because I like/am more productive coding in JavaScript" or "HTML+CSS save a lot of time doing the GUI", etc. Then, today there are ways to use those technologies to develop desktop/mobile apps.

For the desktop you have Electron and NW.js. Of all the advantages they offer, for your specific problem, you have to worry only for the audio/video formats they support. All users will be running the same runtime (the same "browser") when playing your game, no risk of your game page being loaded by an incompatible browser.

Development is handled in nearly the same way of any browser game. Compliant html/css/JavaScript will just work, you can even use js libraries like JQuery and they will just work. As a bonus, you can use the filesystem using apis not available in browsers.

---

Now, if it has to be a browser game, for whatever reason, then you will have to handle different browsers in the usual way, that is to provide multiple versions of each media file. This article comes to mind: http://diveintohtml5.info/video.html

The article is about video, but the strategy for audio is the same.

```
<audio id="electric_discharge_audio">
    <source src="snd/electric_discharge.ogg" type="audio/ogg" />
    <source src="snd/electric_discharge.aac" type="audio/mp4" /> <!--MSIE-->
</audio>

```

Or with JavaScript:

```
var audio = document.createElement("audio");
var source = document.createElement("source");
source.type = "audio/ogg";
source.src = "snd/electric_discharge.ogg";
audio.appendChild(source);
source = document.createElement("source");
source.type = "audio/mp4";
source.src = "snd/electric_discharge.aac";
audio.appendChild(source);

Game.Resources.Audio.ElectricDischarge = audio;

```

About "wav" files. Reasons to use that format for short sound effects in native games go from see no gain in storage save when encoding them to mp3/ogg/your\_favorite\_format, fear of audio artifacts in important game audio effects (bullet, magic, etc), prevent laggy decoding in slower machines (somehow more tolerable for the background music).

> "It would be a shame if nobody played your game because instead of downloading in 10 seconds, it took 2 minutes, of which 1 minute 50 seconds was downloading WAV files. It's like having all the images on your website in BMP format. Nobody does that! So we really need a compressed format." (from: https://www.scirra.com/blog/44/on-html5-audio-formats-aac-and-ogg)

The trick to prevent the quick sound effects to play with the wrong timing when using web technologies is not in using the WAV format. You can use ogg (or its replacement for each browser) for everything as long as you don't detect encoding artifacts (and if you do, then encode with a higher bitrate/quality setting).

The trick is in having the audio resource to preload during the game/level/area/map loading screen, and having it ready to play when the sound effect is needed.

This problem will be present either in true browsers as in platforms like Electron and NW.js. By design, when you set the src attribute of an audio element, controlling when the "browser" will start buffering it is tricky. Maybe one of the JavaScript game engines / media libraries that exists today may help here.

By my own experience, don't trust that the local storage will be faster than the network. This is not a local storage read speed problem, the browser will need to buffer certain amount of data before start playing, you probably don't need to care about this for the background music, but fast audio effects will probably make your game feel awkward and non professional, at least the first time each audio element is played. And having it already cached won't save you from this, you need to have, for all audio effects that will be used in the current scene, enough buffered data so the browser can start play immediately when you call audio\_element.play(). For short audio resources, the expected is that they will be buffered in their entirety, but when using web technologies our control over this is limited.

Here a person is using a technique that consist in playing the audio for the first time with volume set to 0.00000001 (maybe just 0 works too). https://stackoverflow.com/questions/8375903/problems-preloading-audio-in-javascript

I think that is only acceptable for small sound effects. As I said, just let the background music start at any time. In cases where you want to change background music quickly without weird timings, but at the same time prevent a very large audio file to silently play to the end in the background, then you can use the canplaythrough event to stop it as soon as it has enough data buffered.

---

About very old IE versions (prior to 11): do as most game developers do with non NVidia/AMD/\[Intel\] GPUs (at least for the desktop). Pretend they don't exist.

So, if going for the multi browser support, you need to care only for Microsoft Edge and Microsoft Internet Explorer 11 and I'm not very sure about IE 11.

I think Edge won't give us troubles here: https://blogs.windows.com/msedgedev/2016/04/18/webm-vp9-and-opus-support-in-microsoft-edge/#0SgrdYfAKrdXOpaY.97

---

Web Audio API: If you decide to ignore IE completely, you can safely use it. I still have to test in Edge (feel free to edit this answer if you have done it already), but I guess it won't give us troubles with this.
> 0 votes

---
Tags: javascript, audio
---


# Question
Title: Pathfinding with multiple actors moving in sync
I am trying to implement a path-finding routine involving the following:

* Multiple agents
* Multiple Goals
* Obstacles
* Both agents move in sync, i.e. they both move in the same direction unless one is stopped by an Obstacle. *See explanation below in the edit section.*

See the following image for illustration:

A1 and A2 represent the starting position of two agents. The dark squares marked with "X" represent obstacles. "G1" and "G2" represent the final goal.

I played around with A\* path finding algorithm, and it works great with 1 actor with one goal. However, I couldn't get it to work with more than one actor and goal.

Any suggestions and pointers about how to go about it would be very helpful.

**Edit:** Synchronized movement explained

If for instance, A1 is stopped by the obstacle but A2 can move, it is a valid option. A1 would stay in place but A2 will move.

Example:

1. Move Right: A1 moves to (2,1) and A2 moves to (2,7)
2. Move Right: A1 stays in place but A2 moves to (3,7)
3. Move Up: A1 moves to (2,0) and A2 moves to (3,6)
4. Move Up: A1 stays at (2,0) and A2 moves to (3,5)

# Answer
> 2 votes
This problem can be easily solved by A\* without any modifications. The implementation, however, is not trivial. You want your A\* run not in the actual world, but rather in C-space of your world (or even state space given you have extra constraint).
Most interesting for you is the paragraph mentioning that while for 1 particle in 3D the C-space has 3 dimentions, for *n* particles the space has 3 *n* dimensions.
Applied to you problem, you want to construct a 4D graph where obstacles in each 2D slice(the first two dimensions) are generated by overlaying current obstacles translated by the actor displacement vector(the second two dimensions), with connection between 2D slices made only near obstacles, e.g. as you identified in your example, at \[(2,0),(0,6)\] you can move to the \[(2,0),(0,5)\] slice of world.
For example (=one slice), finding path for two points in scene on left is equivalent to finding path for one point in scene on the right (light gray obstacle is due to the world boundary).
As you can see, if you build you A\* graph as described above, A\* will no longer have any problems with second actor and as expected, will find the correct path given one exists.

---
Tags: path-finding
---


# Question
Title: SDL2 taskbar icon notification (blinking / flashing orange)?
In steam when you get a message, or in CS:GO when you find a match the taskbar icon flashes orange and your taskbar becomes unhidden if that's how you have it setup.

In SDL2 you can set a window icon fairly easily, but is there a way to notify the user such as bringing "up" the taskbar?

# Answer
**UPDATE (2021):**

SDL 2.0.16 has added `SDL_FlashWindow`, which handles this in a cross-platform way.

**OLD ANSWER:**

No, sadly SDL doesn't have built-in functionality for this.

However, implementing this doesn't seem to be too difficult, at least for Windows. Something like the following should work:

```
SDL_SysWMinfo systemInfo; SDL_VERSION(&systemInfo.version);
SDL_GetWindowWMInfo(m_Window, &systemInfo);

FLASHWINFO flash;
flash.cbSize = sizeof(FLASHWINFO);
flash.hwnd = systemInfo.info.win.window;
flash.dwFlags = FLASHW_TIMERNOFG;  // Flashes until the window is focused.
flash.uCount = 1;
flash.dwTimeout = 100;  // The flash interval in milliseconds.
FlashWindowEx(&flash);

```

I'm sure resources can be found for doing this on other platforms from the internet.
> 4 votes

---
Tags: sdl2
---


title: What are "affordances" in game design?

text:
# Question
Title: What are "affordances" in game design?
I keep hearing the word "affordance" in terms of game design, most recently in the movie *Indie Game: Life After*. I also vaguely remember it from a UX class in undergrad. But I have no idea what it means.

What is an affordance in the context of game design?

# Answer
An Affordance in general is an action a person perceives as possible. Adding a handle to a desk drawer generates an affordance to open it. Without the handle it just looks like a panel and someone would not get the idea that opening it is even possible.

Or notice the link I posted as the second word of the answer. It is displayed in a different color and your cursor changes into a hand when you move to it. This implies that something will happen when you click on it. That's an affordance. It would be possible for Stackexchange to use some CSS to make the link the same color as the rest of the text and even suppress the cursor change when hovering on it. This would *technically* not prevent you from clicking on it, but it would remove the affordance to do so, so you likely won't do it.

In the context of game design, this means that when you want the player to do something, just making it *possible* to do it is not enough. The player must be made aware that they can interact with something in some way. So you need to give them a cue that interaction is possible. For example:

* When you want the player to realize they can push an object, make it look pushable.
* When there is a button the player needs to press to progress in the game, place it in a prominent location, make it large and visible and make it look like a button.
* When it is important that the player collects powerups, make sure they stand out from the environment so they are noticed as important.
* When the player needs to use a menu to levelup their character, make sure it is opened with a very large and obvious button which is always visible on the screen and becomes even more visible when there are skill points to distribute. Even better, open the levelup menu automatically so the player is forced to interact with it.

A common beginner mistake in game design is to add a really interesting feature to a game, but then neglect to also add an affordance which enables players to even find that feature or when they find it pay as much attention to it as it deserves.

But professionals are not immune to it either. Anyone who played Sonic 3 on the Sega Mega Drive might remember this frustrating moment:

For those who don't remember it or didn't play it: The player got locked in that room. The affordance to progress was obvious: get that drum out of the way. But what wasn't obvious was *how* to do that. The player could jump on it, and it started to bounce up and down. This created an affordance: Jump on it to make it move further. But that was a **misleading affordance**. Jumping did move it, but it didn't move it enough to allow progress.

What the player *actually* had to do was press up and down while on it. This made the drum bounce much more than through jumping. With that knowledge, that room was no challenge at all. But there was no affordance whatsoever that pressing up or down would do anything. During the whole Sonic series, pressing up and down never did *anything* to the environment. So most players got stuck in that room for ages.

How would it have been possible to improve this?

1. remove the false affordance. Don't have the barrel bounce that much on jumping to remove the implication that this would be the way to progress.
2. add a visual cue that pressing up and down would do something, for example by placing up-and-down arrows on the drum and have them light up when the player pressed up or down on their joypad.
> 165 votes

# Answer
**Teaching without words.** Essentially, allowing common sense and simple reasoning to do the teach the player how to use the mechanics of the game.

Allow me to give you a real world example. When approaching this door, do you push or do you pull?

Without words, it's not really clear. You either need to try and get lucky or they need to put up a sign, with words. Now, how about this door?

Only one option right? It's pretty clear you can only push, so that's what you do.

The second design shows people how to open the door, in the moment it takes to walk toward it.

This can be applied to games too.

* Levers are used to open doors. Early in the game, the player is trapped in a room with a door and a lever which are very close together. The next level moves the lever farther away. Quickly, players learn that if they find a door that's locked, they should be looking for a lever. This uses limited choice and proximity to teach the player that these two things are connected.
* There's a really hard enemy, every bullet you shoot at them just bounces off. Sometimes, that enemy will turn around, and you spot a small tank on their back that's a completely different color than anything else on their body. Shooting that tank makes them explode. This uses limited choice and object highlighting to teach the player that the highlighted object is important.

Games that do this well are fantastic. They don't need tutorials or wikis. Utilizing incremental introduction of new features and mechanics allows you to teach the player how to play the game, without saying a word.
> 41 votes

# Answer
"Affordance, to put it simply, is the quality of an object that communicates a way to use it."

Good affordances in game design will mean that the players know how to interact with items without significant instruction. An example of a good affordance is seeing a lock after you've already found a key.

Here's an example from Activision's Mindshadow of one of the most horrible misleading affordances I've ever seen:

This is a text adventure, so you have to type something. At this point, you know you need to drop the anchor to stop the ship. In the picture you see a spool with a rope attached to a chain. You have a cleaver. I tried "CUT ROPE" and "CUT ROPE WITH CLEAVER" etc, it just said "I can't see any rope here." The answer to this puzzle is "CUT CHAIN WITH CLEAVER".

*WHAT CLEAVER CAN CUT A GIGANTIC THICK STEEL CHAIN*

See this article for more discussion: http://www.gamasutra.com/blogs/MichelMcBrideCharpentier/20110102/88710/Affordance\_Design\_in\_HalfLife\_2.php
> 36 votes

# Answer
Just as a reminder/inspiration, let me mention that a common affordance is also the set of ridges for gripping something that you find on real-world objects:

There are three aspects to this affordance:

1. The ridges provide grip for your finger, but since they are horizontal bars, they only do so vertically. As such, it is obvious to most people you wouldn't have more grip if you slid horizontally.
2. The thinning of the ridges towards the bottom produces an arrow shape, indicating that the expected movement is down (to open ... once it is open, you've usually opened it, and you can look inside to see the arresting mechanism, so you don't really need the affordance for that, you'll remember/be able to tell how to re-assemble it).
3. The affordance is about the size of a finger, so you will naturally tend towards placing one finger and sliding/pushing a little, which will release the little hook behind the affordance that keeps the lid in place.

You will see many such affordances in the world, some even dotted. They are so common, they even made it into some computer user interfaces to e.g. indicate draggable surfaces or separators.
> 12 votes

---
Tags: game-design, terminology
---


# Question
Title: Circular lighting mask stretches to ellipse in Monogame using Pixel Shader
I am trying to implement a very simple pixel shader for some basic lighting using this tutorial http://www.xnahub.com/simple-2d-lighting-system-in-c-and-monogame/

My problem is that when the effect is applied the circular gradient ends up looking like an ellipse(left) instead of its circular shape(right).

The technique I use is to have two render targets in monogame and blend them together. The first one is all of the light masks textures, and the second is the render target I want to add the lighting effect to.

I believe the problem is related to the shader itself because when I use this code I get the ellipse(left picture)

```
//Blend both render targets together onto the backbuffer
GraphicsDevice.SetRenderTarget(null);
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
effect1.Parameters["lightMask"].SetValue(lightsTarget);
effect1.CurrentTechnique.Passes[0].Apply();
spriteBatch.Draw(mainTarget, Vector2.Zero, Color.White);
//spriteBatch.Draw(lightsTarget, Vector2.Zero, Color.White);
spriteBatch.End();

```

However, when I comment out the effect and just draw the light render target. I get a nice circle(right picture)

```
//Blend both render targets together onto the backbuffer
GraphicsDevice.SetRenderTarget(null);
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
//effect1.Parameters["lightMask"].SetValue(lightsTarget);
//effect1.CurrentTechnique.Passes[0].Apply();
//spriteBatch.Draw(mainTarget, Vector2.Zero, Color.White);
spriteBatch.Draw(lightsTarget, Vector2.Zero, Color.White);
spriteBatch.End();

```

This is my effect file

```
sampler s0;

texture lightMask;
sampler lightSampler : register(s1) = sampler_state {Texture = <lightMask>;};

float4 PixelShaderFunction(float4 pos : SV_Position, float4 color1 : COLOR0, float2 coords: TEXCOORD0) : COLOR0
{
    float4 color = tex2D(s0, coords);
    float4 lightColor = tex2D(lightSampler, coords);
    return color * lightColor;
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_4_0_level_9_1 PixelShaderFunction();
    }
}

```

Thanks.

# Answer
> 2 votes
This was a pretty simple error made in my initialization code for the two render targets.

The render target mainTarget had a height twice the length of the lightsTarget. When the shader was processing them it had to stretch the lightsTarget texture to get it to work.

---
Tags: c#, shaders, monogame, pixel, effect
---


# Question
Title: FPS controller initializing at bizarre location
I have got the hang of basic construction, terrain modification, applying materials, placing trees, etc. I have created a water plane, positioned my terrain above it, and am able to sink lakes and pools, and raise hills and mountains. Built a couple of primitive structures too.

Initially (before mucking about with the Y position of the terrain) I was also able to invoke Gameplay mode and walk around my game using FPS Character Controller. I could walk into and out of my structures and hike over the hills and valleys of my terrain.

However, since changing the Terrain Heightmap to make the "sinkhole" (negative altitudes) work, I am having the strangest trouble with my FPS Character Controller. I position it at a reasonable height above the terrain, and everything looks fine in Editor mode; but when I start Play mode my FPS character starts out miles below the world, looking up at the underside of the terrain.

So far nothing I have tried will make the FPS Controller start in the location where I have dragged it in Editor mode. I have tried Saving Scene and exiting and reloading. I have deleted and recreated the FPS controller. No matter what I do, it persists in initializing itself in this oddball "way below the world in outer space" location.

I have googled diligently but have not found any mention of this problem. Presumably I'm skipping some important step, but tutorial videos don't offer any advice beyond "drag the fps controller into the scene and it should work."

# Answer
> 1 votes
I believe I have figured this out by hit and miss. The answer was that there was an (accidental) camera attached to my Terrain. I have no idea how that camera became a child of Terrain (almost certainly n00bie operator error), but that's where it was hiding. With 2 cameras in the scene, the behaviour of FPS was inconsistent and bizarre; I found that checking and unchecking the Camera box in the Inspector pane for the FPS Character switched between the orphan (miles away in space) camera and the FPS camera!

After finding and deleting the unwanted camera, the FPS movement behaviour was still bizarre -- mouse-look movement caused an orbiting motion. I found that this was because the camera had become displaced from the controller game object. I could not find a simple Blender-like way of snapping two objects together at their centroids, so I patiently co-located them manually. Once they were co-located again, the parent relationship worked properly and the camera followed the FPS controller, mouse look worked normally and I could once again walk around my mini-world.

---
Tags: unity, camera, terrain, first-person-shooter, spawning
---


# Question
Title: What should I consider when selecting a field-of-view (FOV) for a space game?
I am making a space game (like the game Freelancer). You control a space ship in third person.

What are some gameplay considerations that I should weigh when selecting a field-of-view (FOV) for such a game?

# Answer
Space games have some additional aesthetic considerations surrounding FoV.

With a wide FoV, objects we expect to be round (like planets!) can appear elongated and elliptical toward the edges of the screen. Compare the 90- and 45-degree vertical FoV below:

A tighter FoV can also help enhance the sense of massive scale & distances in space, by diminishing parallax as the player moves around, so things like planets seem almost fixed in the starfield.

So if you want that classic sci-fi movie shot of a ship against a perfectly circular arc of a planet along the edge of the screen, amost unmoving as the vessel sails along... a narrow field of view can help accomplish that.

As the other answers note, you'll need to balance these aesthetics against gameplay usability concerns. If a narrow field of view takes away too much situational awareness, making your shooting gameplay difficult, or flattens depth too much for precise flying around local obstacles, then you'll probably need to widen it back out. If a playable FoV is making your planets look wonky, then you might need some visual trickery to compensate.
> 3 votes

# Answer
> I am making a space game (like the game Freelancer). You control a space ship in third person.
>
> What are some gameplay considerations that I should weigh when selecting a field-of-view (FOV) for such a game?

If its a single player game just let the player set the FOV themselves. Its possible to use it as a way to ballance ships (EX big ships has smaler FOVs while small have larger) but probably not worth the hassle and wont deter people who are sensitive to low FOVs.

Now if its multiplayer then thats a different issue. Being able to adjust the FOV makes it so that better hardware can become very advantagous. A large FOV with a huge monitor (2560 x 1440) in a game where spotting the other player first is an advantage can become very unballanced just because of the hardware.
> 2 votes

# Answer
There is definitely not a "best". It's more about several aspects of design, including:

1) Gameplay- Does your game benefit from a view similar to a RTS game or Isometric RPG? The world is easy to manipulate in this view. Does your game become more immersive in FPS view? Should the view be of the player inside a spaceship, viewing through a screen or window infront of them? It all depends.

2) If you are speaking of strictly FOV in a FPS view, then try a game like Battlefield or Planetside2 which lets you change the FOV. Look at the maximum before you get sick, and the minimum before you lose usability. Find a middle ground which you prefer.

3) Alternatively, allow the player to decide their FOV. Have a default value, but ultimately leave the decision to the player.
> 1 votes

# Answer
If it's a single player only game, there's no problem allowing the user to adjust the field of view as they see fit. In some cases, you may want to calculate the field of view based on the user's setup. Check out how the wide screen gaming forum does it.

You should know that scaling the field of view based on screen size can result in a very tiny view. That is why most modern games use either 45o or 90o by default, and only scale if the screen size is big enough to be a television. That is because the focal length from you to the screen is usually larger if you're using a television. They scale it smaller, and it looks more like how you would see it in real life.

Also, check out the Wikipedia article on "Field of view in video games".
> -2 votes

---
Tags: game-design, camera
---


# Question
Title: Simple Java 2D Game : Player Doesn't Move
I'm a beginner at java and I'm trying to make a simple 2D game as a practice, and i have a problem here with the player, I've tried a lot to make it move but it didn't work. These are the classes that contain the player.

Game Class :

```
package game;

import game.input.Controller;
import game.input.KeyInput;
import game.objects.Player;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Game extends JPanel implements ActionListener{

  Timer loopTimer;
  //Objects
  Player p;
  Controller c;

  public Game(){
    addKeyListener(new KeyInput(p));
    setFocusable(true);

    loopTimer = new Timer(10, this);
    loopTimer.start();

    p = new Player(300,200);
    c = new Controller();
  }

  public void paint(Graphics g){
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(Color.white);
    g2d.fillRect(0, 0, 640, 480);
    p.draw(g2d);
    c.draw(g2d);
  }

  public void actionPerformed(ActionEvent ee){
    p.update();
    c.update();
    repaint();
  }
}

```

Player Class :

```
package game.objects;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;

public class Player extends GlobalPosition {

  private String playerimage = "/images/marioR.png";

  int velX = 0;
  int velY = 0;

  public Player(int x, int y) {
    super(x, y);
  }

  public void draw(Graphics2D g2d){
    g2d.drawImage(getPlayerImage(), x, y, null);
  }

  public Image getPlayerImage(){
    ImageIcon i = new ImageIcon(getClass().getResource(playerimage));
    return i.getImage();
  }

  public void update(){
    x += velX;
    y += velY;

    // Collision with outside
    if(x < 0){
      x = 0;
    }
    if(y < 0){
      y = 0;
    }
    if(x > 640){
      x = 640;
    }
    if(y > 480){
      y = 480;
    }
  }

  public void keyPressed(KeyEvent e){
    int c = e.getKeyCode();
    if(c == KeyEvent.VK_LEFT){
      velX = -10;
    }
    if(c == KeyEvent.VK_RIGHT){
      velX = 10;
    }
    if(c == KeyEvent.VK_UP){
      velY = -10;
    }
    if(c == KeyEvent.VK_DOWN){
      velY = 10;
    }
  }

  public void keyReleased(KeyEvent e){
    int c = e.getKeyCode();
    if(c == KeyEvent.VK_LEFT){
      velX = 0;
    }
    if(c == KeyEvent.VK_RIGHT){
      velX = 0;
    }
    if(c == KeyEvent.VK_UP){
      velY = 0;
    }
    if(c == KeyEvent.VK_DOWN){
      velY = 0;
    }
  }

  public void keyTyped(KeyEvent e){
  }
}

```

KeyInput Class :

```
package game.input;

import game.objects.Player;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class KeyInput extends KeyAdapter{

  private final Player p;

  public KeyInput(Player p){
    this.p = p;
  }

  public void keyPressed(KeyEvent e){
    p.keyPressed(e);
  }

  public void keyReleased(KeyEvent e){
    p.keyReleased(e);
  }
}

```

.

# Answer
> 2 votes
`actionPerformed()` is never called, so nothing is updated or repainted. You need to register it. To check that it's registered, simple add `System.out.println("I Work!!!!")` to the body of the method.

Also, a tip for a new Java programmer: place the `@override` annotation before methods you override. In your case, add it on the lines before `keyPressed()` and `keyReleased` in the `KeyInput` class.

Please take this the right way. Don't just jump into creating a game until you fully understand the language you're working with. There are tons of resources online (articles, texts, videos, etc...) that will teach you Java quickly. It's not a hard language to learn. Master it first, then developing a game will be no problem!

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


title: Unity C# Input Buffering

text:
# Question
Title: Unity C# Input Buffering
So, I've got a fighting game with some pretty tight input windows, and I'd like to buffer the inputs for a few frames.

Basically, if the fighter is in the neutral state, pressing attack should lead into an attack. It uses Input.GetButtonDown("attack") to get the button, and if it detects a press, transitions into attacking state. Now, let's suppose the fighter has just landed, and ends up hitting "attack" a few frames before the land animation ends and he transitions back into neutral. As of right now, nothing would happen, since he's not in the neutral state where the check is, and when he enters the state, the button press is no longer happening.

Is there a way to store inputs for a few frames, so that I can read a button press a few frames back? So, instead of using Input.GetButtonDown("attack"), it'd be something like InputBuffer.KeyBuffered("attack",12) to see if the button was pressed within 12 frames?

The example above is just a bit of a simplification, I know for the above situation I could just use GetButton instead of GetButtonDown, but for a fighting game, you can imagine that the necessary inputs to buffer would get significantly more complicated.

# Answer
> 2 votes
As suggested in the comments, you can buffer frame inputs for when you're ready to process them. In your update method:

```
if (attacking && Input.GetButtonDown("attack"))
{
    queue.Enqueue(InputEnum.Attack);
}

```

When the time comes for you to act on the input, you can simply pop from the queue and proceed according to what you find. This assumes that you care about every input (and the order in which they arrived). If you only need to consider the first input made during the attack, you don't even need a queue/buffer.

---
Tags: unity, c#, input, fighting-game
---


# Question
Title: How to optimize a cubes made world game?
I'm making a cube-world-game like Minecraft. And to render it I've splitted it in 16x16x16 blocks regions (also known as chunks in mc) and then, on rendering, I take all the chunks in the rendering distance area and foreach of them I iterate all blocks and draw them.

It's so slow.

Then I tryed to remove hidden blocks and draw only visible faces of blocks. I made a VBO that store a face and then using model matrix I rotate it to make the other sides of the block. Finally I added a camera frustum test that checks if the block is visible from the camera.

I didn't code yet all these things, that's just a reasoning.

Are these optimization good or could I add something else?

P.S: I've seen that minecraft use a "display list" foreach chunk and not use a VBO for a face (I've didn't understand the code well since part of it is obfuscated) and each loop get just the rendering distance chunks and draw them using the display list stored. How's possible making a display list with all the shape of the chunk? There's another thing that does the same thing of the display list but it's not deprecated (I though VBO but I'm not sure)?

# Answer
> 3 votes
Basically what you said above answers your question...

Split the world into "chunks," and only load these when the player is within a certain distance. Minecraft has that useful "Render Distance" setting. Yes, use VBOs. They can be optimized. Make sure to use shaders, rather than inline quads and alike. Make sure to cull faces than aren't visible. Assuming you're using OpenGL as you're renderer, I'd suggest building your project with version 3.0 minimum, 3.2 or 3.3 preferred, with compatibility profile or core profile. If you use the compatibility profile, you may notice a performance drop, as noted by Quentin.

Check out https://www.khronos.org/opengl/wiki/Core\_And\_Compatibility\_in\_Contexts for more information on that.

---
Tags: opengl, lwjgl, optimization, minecraft-modding, block-world
---


# Question
Title: How can one add a level to an already published ios/android unity3D game on a daily basis?
How can one add a level to an already published iOS/Android Unity3D game on a daily/weekly basis?

I know this probably isn't feasible but it won't harm if I just made sure of it. Our game requires to allow access to just one level a day/week. You may access levels that were released on previous days and play to your heart's content but all players will get access to a new level every day/week. I know this may sound crazy but the concept requires it so just roll with me.

Is there anyway to achieve this for iOS/Android games built with Unity? Of course, we could package a whole game with 10 levels and allow access to each level after a set time, but the game will need to talk to a back-end CMS all the time to allow login and verification of users, make sure they aren't cheating, etc, etc, over proper security and https (proper anti-cheat solutions are a must and that's why maybe HTML5 route is better).

We are now moving towards doing all this in HTML5 and completely bypass Unity, but was hoping to find a solution with Unity because 3D is better than 2D depending on the situation, and some levels could be 3D while others 2D. Patching/updating everyday to upload new levels won't go down well with anyone, the app stores or the users.

# Answer
> 2 votes
Laszlo Fuleki's answer is fine. The problem is that, if you are asking this, you probably are not using a suited level structure.

So if there's an internet connection, check for a new level avaliable and if it proceeds, show it to the user (you can use a system notification or an inbox icon inside the game). Then there are 2 options:

1. The level is already there, pre-packaged, and the access is automatically allowed once the server notification.
2. The level data is sent by user request to the server.

The user can't cheat because the server controls the schedule. Pre-packaging a level and granting access to it in an schedule manner, without internet connection, seems ackward to me (candy crush lives is a similar concept). And it can be cheated. So internet connection is required.

# Answer
> 2 votes
Unity's Asset Bundles were designed specifically for this purpose, to allow you to add/download new Unity content and prefabs without the user having to update their game client at all.

http://docs.unity3d.com/Manual/AssetBundlesIntro.html

# Answer
> 1 votes
Since you use security checks on the server, in your place I would use the existing backend to provide the daily new level as well. You could transmit a JSON, XML, whatever really to the client, and based on that the client would construct the level. This way you would have full control over what is available and what is not (e.g. sending level data when the user requests to play it, or decide to cache them on the client machine once they had access to it).

# Answer
> 0 votes
Maybe look into saving your levels as txt then when the person connects it pulls that file and rebuilds the level reading from the txt.

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


# Question
Title: How to create realistic rainfall animation in modern OpenGL using shaders?
I see many examples of particle system in old style OpenGL with falling raindrops. Examples of rainfall that can interact with environment lighting and look realistic are hard to find. How to create realistic rainfall animation in modern OpenGL using shaders?

# Answer
No one is going to give you a detailed solution because it's too much work but I can give an overview.

You would probably want to use a geometry shader to create a sort of elongated teardrop shape. You will have to create quite a lot of them obviously for a big scene and to be realistic, and to keep them in a particle system that moves and updates them.

Here is a tutorial that goes over the basic ideas: http://mbsoftworks.sk/index.php?page=tutorials&series=1&tutorial=26

It will also be important to apply specular mapping, environmental mapping and refraction on top of that.

You can also detect collisions and then create splatter in a similar manner to how you created the original drops.
> 1 votes

# Answer
There are multiple ways to go about this. At different distances you will probably want to use different solutions.

At a very close distance you might want to add an animated overlay with refraction. This simulates raindrops hitting the camera lens, so its a cinematic style effect, not fit for all games.

For the medium distance you might want particle effects, but single drop particles are really costly, so you might want to consider handling multiple droplets as a single particle.

For making things look wet you could probably apply an overlay to the surfaces themselves. First making the colors darker, increasing specular, and adding a smoother bump map, that could be animated, which would simulate water flowing over the surface.(Take a look at Dungeon Defenders dragon level as an example of this)

Finally making the lighting more smooth and darker can add a lot to the atmosphere, making it feel as if it was really raining. A good HDR cubemap can do a lot for this.
> 1 votes

---
Tags: opengl, glsl
---


# Question
Title: Tile Based A* Pathfinding, but with a bomb
I've written a simple A\* path finding algorithm to quickly find a way through a tile based dungeon in which the tiles contain the information of walls.

An example of a dungeon (only 1 path for simplicity):

However now I'd like to add a variable amount of "Bombs" to the algorithm which would allow the path-finding to ignore 1 wall. However now it doesn't find the best paths anymore,

for example with use of only 1 bomb it generates paths like these:

While the correct shortest path would be this one:

The problem is that "Closed Nodes" now interfere with possible paths. Any ideas of how to tackle this problem would be greatly appreciated!

# Answer
> 9 votes
The typical approach here would be to treat your remaining bomb count as an additional dimension in the pathfinding space.

So given this situation

```
2      ↑
   ──────┐
1   ←  o │ →
         │
0      ↓

    0  1   2

```

Our tile at the `o` (1, 1, 4 bombs) has the following reachable neighbours in the cardinal directions:

| move | x | y | bombs | cost |
| --- | --- | --- | --- | --- |
|  | 0 | 1 | 4 | 1 step |
|  | 1 | 0 | 4 | 1 step |
|  | 2 | 1 | 3 | 1 step + 1 bomb |
|  | 1 | 2 | 3 | 1 step + 1 bomb |

This solves the problem of "closed nodes" interfering with possible paths, because the node you reach by blasting through the wall to the right (2, 1, 3 bombs) is different from the node you reach by walking down past the end of the wall, then right, then up (2, 1, 4 bombs). So marking one as closed doesn't prevent exploration of the other.

To make sure you can still terminate the algorithm, you count every node on the exit tile as a goal node, regardless of the number of bombs left - so a path can be considered complete whether it used no bombs or all 4. A\*'s cost minimization will choose the best one according to the parameters you give it.

You can adjust your cost function to decide whether the algorithm should always find the shortest number of steps even if it has to use all the bombs (bomb cost = 0), or give it some trade-off like "use a bomb if it saves more than 3 steps" (bomb cost = 2 x step cost, since a bomb use always comes with one step too)

When your maps or number of dimensions are large, you'd probably want to construct these tiles only as-needed, rather than reserving an array for every conceivable configuration (of which many will never be used). For the case you describe though, an exhaustive collection wouldn't be a problem.

---
Tags: path-finding
---


# Question
Title: Problem with Rotating Third Person Radar UE4
I am doodling on the Flying game template on UE4. I am making a 2D radar on top left. Radar's north direction is the pawn's forward direction. So when it approaches to an object with the dotProduct value of 1, dot representing the enemy object on the map has to approach from direction (0, -1) on the coordinate system. Just like any shooter game.

My problem:

As I know, to calculate the x,y positions on the coordinate system with given angle and distance, the formula is as follows;

x = Cos() * dist, y = sin() * dist

As Unreal Engine's UI classes use top left as the pivot point, if an object is on absolute north of the origin on the screen, it has to come from (0,-1) as I wrote above.

Cos(270), sin(270) has to give 0,-1 and when I multiply with the distance, the dot has to be shown on absolute north of the origin point of the radar.

I declared two UProperties to play with the angles on the editor on runtime. When I enter 270, 270 for cos and sin values, it shows the dot as on the image below;

the closest to the top left is when I enter -90, 90 and it shows like in the image below;

Even if I am entering the incorrect values, I think at least an angle such as 90, 90 has to be perpendicular. Does anyone have any idea?

# Answer
> 1 votes
Are you sure cos and sine take degree and not radians? Try to convert your argument into radians and see what happens:

radians = degrees * PI / 180

---
Tags: geometry, coordinates, unreal-4
---


# Question
Title: Change color, or material of specific line segments on Line Renderer
We're making a game that plays with a LineRenderer, and we want to give it a different visual feedback relative to the side of the screen that it's on.

We want to change the feedback of the specific line segments that are on the other side (when they past the middle point).

The API lets you map the segments positions, but isn't there a way that you can change the material/color of that specific segment? I just see that you can do it, but only for the whole Line Renderer, not segment-by-segment.

# Answer
Here's an example of what you can do with a single material and a shader that changes behaviour based on world position:

This shader looks something like this:

```
Shader "Unlit/WorldspaceSwitch"
{
    Properties
    {
        _Color ("Surface Color", Color) = (1, 1, 1, 1)
        _UnderColor ("Underground Color", Color) = (0, 0, 0, 0)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float3 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            // Declare the variables to hold the colours
            // we want to show above & below the line.
            fixed4 _Color;
            fixed4 _UnderColor;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv.xy = TRANSFORM_TEX(v.uv, _MainTex);

                // I added a third texture coordinate,
                // and populated it with the worldspace y position.
                o.uv.z = mul(unity_ObjectToWorld, v.vertex).y;

                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // This turns the worldspace y position
                // into a tight blending ramp from 0 to 1.
                float blend = saturate(i.uv.z * 10.0f);

                // This blends between the two colours.
                fixed4 col = lerp(_UnderColor, _Color, blend);

                return col;
            }
            ENDCG
        }
    }
}

```

You can use the same principle to make arbitrary changes to the LineRenderer's appearance, without resorting to multiple materials. If you want help creating shaders to achieve a specific effect, please feel free to ask a new question with details of what you want to create and what you have so far.
> 4 votes

---
Tags: unity, c#, 2d, materials
---


# Question
Title: Surface shader with VertexLit causes black object
I wrote the simplest possible surface shader:

```
Shader "SimpleSurf" {
    Properties {
        _MainTex ("Base (RGB)", 2D) = "white" {}
    }
    SubShader {
        Tags {"RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        #pragma surface surf Lambert

        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
        };

        void surf (Input IN, inout SurfaceOutput o) {
            half4 c = tex2D (_MainTex, IN.uv_MainTex);
            o.Albedo = c.rgb;
            o.Alpha = c.a;
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

When the "Forward" rendering path is enabled the object looks fine!

But when the "Vertex lit" rendering path is enabled, it looks became black:

Why it happened? How can I use surface shaders (or maybe write a Vertex/Fragment shader which will consider spot lights) which do some effects in VertexLit path?

# Answer
> 2 votes
```
Shader "SimpleSurf"
{
Properties
{
    _MainTex ("Base (RGB)", 2D) = "white" {}
}
SubShader
{
    Pass
    {
        CGPROGRAM
        #pragma vertex vert_img
        #pragma fragment frag

        #include "UnityCG.cginc"

        uniform sampler2D _MainTex;

        float4 frag(v2f_img i) : COLOR
        {
            return tex2D(_MainTex, i.uv);
        }
        ENDCG
    }
}}

```

Edit: I misunderstood the question. I've replaced the previous shader with the simplest possible vertex and fragment shader that works in the VertexLit render path. If you want objects to receive per pixel lighting you will need to use Forward or Deferred rendering as per http://docs.unity3d.com/Documentation/Manual/RenderingPaths.html

# Answer
> -1 votes
Try setting the fallback to the vertexlit shader. Fallback "VertexLit" I haven't tested it out my self but from my knowledge of the rendering pipeline, I can assume that it will work. Basically, if (and in this situation it will) pixel based diffuse lighting fails, it will look black as there won't be any lighting to compute, it needs something to fallback to, vertex lit.

This edit allows you to preserve the attributes of surface shading without having to stay in deffered or forward rendering paths.

---
Tags: unity, shaders, graphics, lighting, effect
---


# Question
Title: Multiple buffers and calling glBufferSubData
Originally asked this on *Computer Graphics*, but it might fit in better here.

In my project, for convenience I would like to use many buffers. Many buffers in my case means 50-100 terrain patches represented by buffers with vertex coordinates, normals, indices and maybe color. The magnitude of data would be, let's say **10^4 floats** per buffer. Some of this data can be shared between each terrain patch, f.ex. xz-coordinates and indices.

During the rendering loop, some terrain patches will be updated. Which means that for certain buffers I call `glBufferSubData()` for the whole buffer.

My question is; are there any pros/cons, performance wise between these two methods:

**1)** Controlling my data in many buffers (50-100), thus letting me call `glBufferSubData` on a complete buffer when needed.

**2)** Controlling my data in fewer (5-20) buffers, with more data in each. But then having to set up a system where I need to call *glBufferSubData* on smaller portion of a buffer. (Which leads to a more complex design in my case).

# Answer
Having fewer buffers is usually better performance-wise, because it avoids overhead from the driver. The approaching-zero-driver-overhead technique makes use of very large buffers that the program manages itself.

The system to manage the small portions of a buffer shouldn't be too complex. Fo each portion, you just need an offset and a size.
> 1 votes

---
Tags: opengl, terrain-rendering, vertex-buffer
---


# Question
Title: Isometric coordinate maths not quite right
I have written two functions, screenToCoords and coordsToScreen.

Screen being the coordinates on screen.

Coords being isometric coordinates.

So here are my functions:

Screen to isometric:

```
Vector2 TileMap::screenToCoords(Vector2 coords){
    coords.x -= offset.x;
    coords.y -= offset.y;
    Vector2 newCoords;
    newCoords.x = (coords.x / (TILE_WIDTH/2) + coords.y / (TILE_HEIGHT/2)) /2;
    newCoords.y = (coords.y / (TILE_HEIGHT/2) - (coords.x / (TILE_WIDTH/2))) /2;
    return newCoords;
}

```

Isometric to screen:

```
Vector2 TileMap::coordsToScreen(Vector2 coords){
    Vector2 newCoords;
    newCoords.x = (coords.x - coords.y) * (TILE_WIDTH/2) + offset.x;
    newCoords.y = (coords.x + coords.y) * (TILE_HEIGHT/2) + offset.y;
    return newCoords;
}

```

And these seem to work totally fine, except when dealing with mouse coordinates, as you can see here:  I can't figure out what the issue is.

Basically what's happening in this image is that I'm converting mouse coordinates into isometric coordinates, then back into screen coordinates so that I can render that highlight box.

# Answer
Like I stated in my comment to your question, double-check your offset, everything else you're doing seems fine.

I faced a similar problem with my isometric game. It turned out I needed to account for the tileset (ie source image) drawing offset, and a logical/game-space offset.

---

My isometric game operates in a standard 2D top-down mode. That is, I handle all collision, path-finding, and other mechanics in the 2D top-down space. **It is only at render-time that anything needs to be converted to look isometric.**

---

I hard-coded a solution to the *not quite right isometric math* during game startup that also caches the offset world-coordinates of all tiles. The top-left corner of the logical tile position in world-space is converted to isometric and saved in my 2D tile array:

```
// row and column are just the indexes of the 2D array where eTiles are stored
// logical cell width == logical cell height == 32 in my case,
// although the actual source image has tiles 64w x 64h in pixels (including alpha space)
// and the actual tile being rendered is visually 64w x 32h pixels
eTile & tile = cells[row][column];
eVec2 tileOrigin = eVec2((float)(row * tileMap.CellWidth()), (float)(column * tileMap.CellHeight()));
eMath::CartesianToIsometric(tileOrigin.x, tileOrigin.y);
tileOrigin.y -= 16; // tileset specific offset, not all tileset images are created equal
tileOrigin.x -= 32; // logical-to-screen isometric coordinate offset to account for the 64w x 64h tile images used
tile = eTile(tileOrigin, type, layer);

```

These two isometric tiles from Clint Bellanger are visually 64 pixels wide x 32 pixels tall, but the rectangle used to clip them from the tileset is 64 x 64. Moreover, my game operates on 32 x 32 sized cells whose dimensions become 64w x 32h when converted to isometric. Overall confusing, but it amounts to adjusting the offset for each tileset used. (side-note: They are centered differently in their 64 x 64 clip rectangles to give the further illusion of a deeper pool of water relative to "ground level".)

---

**As an example of how I use this:**

Similar to your tile-highlighting, I have a function executed each frame which allows me to change the properties of a tile under the mouse position:

```
if (input->MousePressed(SDL_BUTTON_RIGHT)) {
    // get mouse position in the window/screen (0,0 at top-left),
    // and top-left corner of 2D camera in world-space and convert to cartesian
    // (ie coordinates consumable by my 2D tile array as seen in ToggleTile function)
    eVec2 tilePoint = eVec2((float)input->GetMouseX() + game.GetCamera().GetAbsBounds().x, (float)input->GetMouseY() + game.GetCamera().GetAbsBounds().y);
    eMath::IsometricToCartesian(tilePoint.x, tilePoint.y);
    ToggleTile(tilePoint);
}

```

Its important to note here that the method I use assumes the gathered coordinates are *already* isometric and need to be converted to Cartesian.

`ToggleTile(tilePoint)` then gets the tile-array index of the tile currently under the mouse so it can set that tile's display properties (from grass to water for example):

```
void eMap::ToggleTile(const eVec2 & point) {
// ...
    row = (int)(point.x / cellWidth);       // cellWidth == 32
    column = (int)(point.y / cellHeight);   // cellHeight == 32
    eTile & tile = cells[row][column];
// ...
}

```

---

Regardless of whether I cache my tile coordinates, **my methods for converting from isometric to Cartesian are as follows:**

```
//************
// eMath::IsometricToCartesian
// rotates input coordinates 45 degrees counter-clockwise
// DEBUG: assumes the input coordinates are isometric
//************
inline void eMath::IsometricToCartesian(float & x, float & y) {
    float isoX = x;
    float isoY = y;
    x = (2.0f * isoY + isoX) * 0.5f;
    y = (2.0f * isoY - isoX) * 0.5f;
}

//************
// eMath::CartesianToIsometric
// rotates input coordinates 45 degrees clockwise
// DEBUG: assumes the input coordinates are cartesian
//************
inline void eMath::CartesianToIsometric(float & x, float & y) {
    float cartX = x;
    float cartY = y;
    x = cartX - cartY;
    y = (cartX + cartY) * 0.5f;
}

```

I hope this points you in the right direction to fixing your issue.

---

As a side-note: I cache all the tile coordinates at startup so I don't need to constantly divide by tile dimensions to get the screen position at render time. All I have to do is grab the *already isometric* tile origin and offset it by the camera world-coordinates:

```
            eVec2 screenPoint = eVec2(
                eMath::NearestFloat(tile.Origin().x - game.GetCamera().GetAbsBounds().x),
                eMath::NearestFloat(tile.Origin().y - game.GetCamera().GetAbsBounds().y)
                );

```
> 2 votes

# Answer
Is the problem in the image that its not smooth? If thats the case then you're getting integer values when you want floats. Make sure Vector2 contains floats or doubles, and make sure you cast correctly when multiplying and dividing.
> 0 votes

# Answer
It looks like your mouse pointer's origin is in its **top right** corner instead of **top left**, where the finger is. Make sure it's positioned correctly.
> 0 votes

---
Tags: c++, isometric
---


# Question
Title: Values at the start of the string are not being sent while sending json data in Unity
I have been trying to solve this issue on my own but couldn't find the cause of the issue.
Before I start, I am using unity 5.4 and for creating json data I used JSONObject, https://github.com/mtschoen/JSONObject.

The code i used to send data to server, is below

```
Debug.Log (jsonObject.ToString ());
byte[] bytes = Encoding.UTF8.GetBytes (jsonObject.ToString());
Debug.Log (Encoding.Default.GetString (bytes));
WWW www = new WWW (url, bytes, headers);
yield return www;
Debug.Log ("Sending Data " + www.text);

```

I used jsonObject.ToString() just to test sending it as a string. The data is something like

`{"Image_name":1,"Links":[{"HotspotName":"User_arch0","Location":"(-1.2, -0.2, 1.6)","Scale":"(0.1, 0.1, 0.1)","LinkedImageID":0,"HotspotName":"User_arch1","Location":"(0.5, 0.5, 1.9)","Scale":"(0.1, 0.1, 0.1)","LinkedImageID":3}]}`

The first two log statements give this data correctly into the log in the console. But the last one logging `www.text` gives this Sending Data

`{"Image_name":1,"Links":[{"HotspotName":"User_arch1","Location":"(0.5, 0.5, 1.9)","Scale":"(0.1, 0.1, 0.1)","LinkedImageID":3}]}`

As you can see, the values for Hotspot "User\_arch0" is just not there in the final output. Even if i send a string directly instead of jsonObject.ToString(), it doesn't work.

What is causing this? If you need anymore of the code let me know

# Answer
Your JSON is not correct.

If you have 2 links, they should be separated as 2 distinct objects. In your JSON, I see no brackets between the 2 links.

That means it is considered as only 1 object. This object has a `HotspotName`, which is first assigned to `user_arch0` but then overriden to `user_arch1`, and same goes for all the other attributes, so in your `www` object in the end you only get second link.

I am not a JSON expert but I guess just adding brackets like this should do it

`{"Image_name":1,"Links":[{"HotspotName":"User_arch0","Location":"(-1.2, -0.2, 1.6)","Scale":"(0.1, 0.1, 0.1)","LinkedImageID":0}, {"HotspotName":"User_arch1","Location":"(0.5, 0.5, 1.9)","Scale":"(0.1, 0.1, 0.1)","LinkedImageID":3}]}`
> 2 votes

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


# Question
Title: Implementing a lego-like system that doesn't hog computer resources?
I've heard of the term "voxel" used with modern block-builder games such as minecraft. Other games implement what appears to be a voxel system -- yet they incorporate complex 3d objects such as guns, spinning wheels, etc.

In unity3d, how does one implement a builder system that does not compromise performance?

Robocraft is an example of this, though games like *Rust* and *Unturned* do feats like this as well.

One obvious thing is to combine meshes to reduce draw calls, but then I wonder how to include individual blocks for consideration in damage, etc.

# Answer
> 1 votes
The term *Voxel* is very broad. Due to the popularity of Minecraft, many people think a voxel game can only consist of blocks (like Minecraft, Cube World and Seven Days to Die). However, this isn't true.

*Voxel* worlds usually use a three-dimensional data set to represent the terrain. In cases like Minecraft, the data set contains what block there is at certain places. In some other games, however, it tells you how much material there is at that specific point. The latter version usually uses some sort of iso-surface algorithm (like marching cubes or dual contouring) to display the terrain. Many games like Space Engineers (which is a mix of the two), the recent Astroneer or Mediavel Engineers are in this category.

It's not necessary to use perfect squares if you implement Voxel terrain the "Minecraft way", you can use irregular shapes, slopes or block sized models for it too. It has nothing to do with the complexity of the graphics.

Implementing a game like this can be achieved in multiple ways. One method of optimization is to separate the terrain into chunks, then only render the visible ones and the ones that are close to the player.

# Answer
> 1 votes
> One obvious thing is to combine meshes to reduce draw calls, but then I wonder how to include individual blocks for consideration in damage, etc.

The unity-way would be to add sub game-objects with box-colliders to represent all the blocks which are on the surface. Those blocks which are obscured don't need colliders, because they won't ever collide with anything. Also, you can mark the game objects of most of these colliders as static, because even if adding and removing blocks is a main feature of your game, the vast majority of blocks won't move ever. The Unity engine can make lots of optimizations when it is told that an object is stationary.

When this turns out to be too slow, you can try to implement collisions yourself. Instead of having colliders on everything which can collide and having `OnCollision*` methods, have the Update functions of your objects check for intersections with the voxel grid.

But keep in mind that general-purpose game engines like Unity are not optimized for games with such unusual technical requirements like Minecraft.

---
Tags: unity, c#, voxels, block-world
---


# Question
Title: How can I "smoothen" my path-finding on a map with big tiles?
I've just implemented A\* in my "game", but as I finished it this came to my mind:

* This is fine for a turn based game, but it would be really annoying for a real-time one.

**For example look at the picture below.**

In an action rpg the character would move to its goal in a **straight line**, but this is impossible here because the **tiles are too big** to make a that straight line.

**So my question is:**

* How do they solve this in action games?
* *(I don't think that they have miniature tiles because that's too inefficient. But maybe I'm wrong.)*

**Edit:**

* Or should I remove those tiles from path, which aren't necessary?

+ So there will be a only a few points left, which are connected by straight lines?
* Like this: go through the path from the Start.

+ When I find a `X. tile` which can't be accessed with a straight line from start:
    + Remove every tile from the path between `Start` and `(X - 1). tile`.
    + Repeat this from the `X. tile`, till I find the `End`.
    + Interpolate through straight lines between the remaining points.

# Answer
> 1 votes
Since your question is quite broad (you don't seem to have an actual issue to solve), I'll write a broad answer.

The tiles will be used for graphics and for obstacles, but not for navigation.

For navigation, i.e. moving from point A to point B, you'll use something like a *navmesh*, or a *navigation mesh*.

Basically, all of the points of interest of the surface where the agent will be able to travel will be used to create a graph, graph nodes will be composed of the points of interest, and graph edges will be composed of *direct paths* between points of interest. This means that the graph will 'surround' obstacles.

With that graph, an agent can find the closest point of interest from its current location, and *then* use A\* to find the shortest path to where they like.

That's the big picture. You can browse this site for more questions tagged , and if you're interested in navmeshes in Unity, you can browse this site for questions about it. From what I understand, there is a built-in feature about navmeshes in Unity, but I don't know anything about it.

# Answer
> 1 votes
In an action game they would not be using tiles, as it's likely there are not restrictions to the directions characters can move, so although they may be in a diagonal like yours they would rotate towards it and move straight at the goal. They would not necessarily use an A\* style algorithm but rather just target seeking. Path finding would be implemented if there were obstacles in the way however. A\* could be used for that since it is good at finding the best path.

For a turn based game it is totally okay to do something like this with tiles. If you are concerned with the fact that your cube character would have to go up and then right instead of up-right diagonally then try implementing diagonal movement in. While it may not look like a straight line the character would still be heading in that path straight to the goal.

Check this article out. It was my primary reading for a course where the final project was about flocking, target seeking, autonomous agents etc.

# Answer
> 1 votes
I think what you're looking for is Bezier Curves. I'm not exactly sure about how your game does what it needs to do (or what you intend to do with the tiles), but if you have points (tile coordinates) and you want a smooth transition between them, Bezier Curves will give that to you as a path. The rest is just animation and moving the character model along the path.

If you implement it right, you would get something like this:

More info on the math involved and also some code.

Most likely path to be generated in this particular case:

# Answer
> -2 votes
In the image given, it looks like you can move in a straight line: just find the line between the two points and move along that. That would mean that the position couldn't just be 0,1,2..., but it would have to be interpolated in between.

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


# Question
Title: Marching cubes with destructible environment
I've been spending a lot of time over the past few days finding out information about the marching cubes algorithm and I'm pretty sure I understand it.

My game would be using chunks of land with the voxels stored in an octree in the chunk and unless it won't run with this many voxels I was going to try with .25m blocks at first.

to make the mesh I would loop through all of the blocks I would consider to be solid(above 0.5 density from 3d Perlin noise) and call the Perlin noise function for each of the blocks vertices. Depending on the combination of vertices that are within the visible density range the mesh would be one of the 256 combinations. then move the vertices of the mesh based on interpolating the density values of the corners to make a smooth surface.

Now I want to make it possible to place blocks and dig them. All placed blocks wouldn't have a smooth flag so wouldn't have the marching cubes mesh built from them so they would retain their crisp edges. How could I make it so that if you dig blocks they would look smooth? I couldn't just use perlin noise could I, because all of the dug blocks would be considered completely solid as they are in the solid area above the isovalue. However there are plenty of videos with deformable marching cubes terrain. could somebody explain how I could do this or suggest another algorithm?

# Answer
You could add a user-defined function to the underlying perlin function.

For example, if the user adds a meta-ball function at a point x0, y0 z0 and with density d, then you add that function to your evaluation function.

It becomes (I use Java):

```
List<UserBallFunctions> userDefinedFunctions; // Init somewhere, let the user add members etc.
int evalFunction(x, y , z) {
    double terrainValue = perlin(x, y, z);
    double userModification = 0;
    for(UserBallFunctions func: userDefinedFunctions) {
         userModification  += func.valueAt(x, y, z);
    }
    return selectAppropriateMaterial(isovalue + userModification );
}

```

Where userFunction is a "ball" function added (or substracted, if value is negative) by the user:

```
public class UserBallFunctions{
    int x0, y0, z0;
    double ballDensity;
    // <-- Add initialisation, getters and setters)
    double valueAt(int x, int y, int z){
        return ballDensity / ( (x-x0)*(x-x0) + (y-y0)*(y-y0) + (z-z0*(z-z0) );
    }
}

```

When you update your topology, the world should have changed. Those changes will smoothly integrate with the existing world because we used additive mixing between `terrainValue` and `userModification`. You can force abrupt change if you instead use a `max` function, etc.

To make those changes persistant, you must save the metaball definitions in the same way you saved the world seeds etc. They may be saved per-chunk to speedup user function computation (fewer metaballs per-chunk), but careful with side-effects where a ball influences beyond its chunk. You may want a ball function with a bounded support to help with this.
> 1 votes

---
Tags: voxels, perlin-noise, marching-cubes
---


# Question
Title: Should the Sprites in my Boids implementation be backed by model objects?
This question is about the proper way to architect an implementation of Craig Reynolds Boids algorithm.

I have an `Agent` object like this:

```
struct Agent: Equatable
{
    let identifier = NSProcessInfo.processInfo().globallyUniqueString

    var position: CGPoint
    var velocity: CGVector

    init(position: CGPoint = .zero, velocity: CGVector = .zero)
    {
        self.position = position
        self.velocity = velocity
    }
}

```

And a `Simulation` object that holds an array of agents. Each iteration of the simulation the `Simulation` object updates the `position` and `velocity` of each `Agent` in its array of `Agent`s. Something like this:

```
class Simulation
{
    private var agents: [Agent] = []

    init(agents: [Agent])
    {
        self.agents = agents
    }

    func update()
    {
        for agent in self.agents
        {
            // Update agent's position and velocity
        }
    }

```

This is ok. I can run the simulation and update the `Agent` models appropriately. However, I also want to draw the models on screen.

The question is whether I should create a new `AgentView` class as the view representation of an `Agent` model object. Or whether (1) maintaining a relationship between each `Agent` model and a corresponding `AgentView` is too cumbersome and (2) I should just replace the `Agent` model with `AgentView` entirely and let `AgentView` be the sole representation of an agent (sort of blending model and view state).

Thanks in advance for your help. If you would like additional clarification just let me know.

# Answer
Coming from a game dev perspective, I'd suggest you pursue a entity component based system (ECS) to build up your simulation.

An entity is a container for components. Components represent state (and/or) behaviour of an entity.

In pseudocode, it translates to something like:

```
class Component { }

class Entity {
    var components: [Component]
    // ... code to add / get components
}

class PositionComponent : Component {
    var position: CGPoint
}

class VelocityComponent : Component {
    var velocity: CGPoint
}

class SpriteComponent : Component {
    var node: SKSpriteNode
}

```

Using this notion of components, you can build up an agent as follows:

```
let agent = Entity()
agent.add(PositionComponent(x: 0, y: 0))
agent.add(VeolcityComponent(x: 0, y: 0))
agent.add(SpriteComponent(texture: "boid.png"))

```

Given a set of agents, we need to perform actions on them. We can split this functionality across what is usually termed a "System". We could have a system that updates all agents that have a position and velocity component. This would be the core boids algorithm. We could have a display system that syncs the position component of an entity with it's sprite component.

```
class BoidSimulation {

    func update(dt, entities) {
        for agent in entities {

            // update position
            let p: PositionComponent = agent.get()
            let v: VelocityComponent = agent.get()
            p.position = p.position + v.velocity * dt

        }
    }
}

class BoidDisplay {
    func update(dt, entities) {
        for agent in entities {

            // update position
            let p: PositionComponent = agent.get()
            let sprite: SpriteComponent = agent.get()

            sprite.node.position = p.position

        }
    }
}

```

With a setup in place like that, the core update loop would composed of calling updates on these systems.

```
func update(dt) {
    simulation.update(dt, agents)
    dislay.update(dt, agents)
}

```

By splitting up an object into components, and having systems work on components rather than an entity directly, you have will have much more flexibility over your architecture - GameplayKit in iOS has an ECS model built in. You can refer to the starting guide here for more information about why an ECS pattern is better suited here.
> 1 votes

---
Tags: ios, ai, simulations, spritekit, swift
---


title: Pool game ball path line

text:
# Question
Title: Pool game ball path line
I'm using Unity C#. How would I create the effect in my pool game, a line showing the direction of the second (not white) ball after collision. Example:

I need to make the line coming from the ball (second/leftmost)

P.S. I made the other line by using Raycast to find the hit point and set that point last position of line renderer (white ball is a start position for line renderer and it casts the ray)

# Answer
> 1 votes
The direction (d) in which the target ball should move is `AB.normalized`, where `A` is the center of the imaginary circle (where cue ball reaches next to target ball) and `B` is the center of target ball.

Obviously d will not be equal to `AB.normalized` if shot has an angle. i.e. if shot is done in a way that cue ball receives a clockwise rotation, then the target ball will receive a counter-clockwise rotation less than the rotation of cue ball as well as an additional force resulting from the torque of the cue ball.

The amount of rotation reduction and the additional force depend on physical attributes of the elements of the game. e.g. ball friction, pool friction, bounciness, etc..

If your game mechanics depend on Unity's Physics Engine then you probably will have a hard time estimating the exact value for these vectors. However if you go on writing your own physics engine (which is better in the end) you have to first write all your physics equations and integrate them into the visual representations shown in the picture to have the same visual and physical behavior.

***Note***

*I'm not a physics scientist so I don't know the equations you need. But you will certainly find them here.*

# Answer
> 0 votes
What you're looking for is Elastic Collision because you have billiard balls and this will be the closest approximation. To make it absolutely realistic you'll need a mix of Inelastic Collision and Elastic Collision but that's another topic altogether.

The balls in this case will act like a Two-dimensional Gas and you can find the math here. I'm not going to detail how to do this, simply because it's a lot of groundwork. If you're unsure about the implementation (of the math and physics not the game engine part) I'd suggest asking on the Physics site of StackExchange.

---
Tags: unity, c#, raycasting, effect, path
---


title: Simple screen aligned renderer

text:
# Question
Title: Simple screen aligned renderer
I'm trying to create a super simple no frills off-screen process... I have the device, I can export the texture to Image... etc... I'm having one heck of a time just getting a simple Triangle Strip to display an image so I can run pixel shaders on it... I have found examples and even have the Direct3D cookbook.. However, I don't need all the camera functions and so on... I can't seem strip out the unnecessary bits and still have it work... please help...

I just need a super simple quad renderer that aligns to the renderer target...

# Answer
> 1 votes
This is a vertex shader which will draw a full screen triangle without a vertex buffer:

```
// This function will create the triangle
inline void FullScreenTriangle(in uint vertexID, out float4 pos, out float2 tex)
{
    FullScreenTriangle(vertexID, pos);

    tex.x = (float)(vertexID / 2)*2.0f;
    tex.y = 1.0f - (float)(vertexID % 2)*2.0f;
}

// This is the vertex structure that the vertex shader will emit and the pixel shader will receive:
struct VertexToPixelPostProcess
{
    float4 pos              : SV_POSITION;
    float2 tex              : TEXCOORD0;
};

// This is the vertex shader itself:
VertexToPixelPostProcess main(uint vI : SV_VERTEXID)
{
    VertexToPixelPostProcess Out;

    FullScreenTriangle(vI, Out.pos, Out.tex);

    return Out;
}

```

This will cover the entire screen and your pixel shader will receive texture coordinates which will map (0,0) to the upper left corner of the screen and (1,1) to the bottom right corner.

You need to call `Draw(3,0)` from your API to draw this to the screen.

This also requires a few graphics state setups. You should set a null input layout, set a null vertex buffer, set the primitive topology to trianglelist, set an appropriate blend state, disable depth/stencil tests and keep the backface culling in mind (you could disable backface culling to render at all times).

You should have a rendertarget bound when drawing.

**UPDATE:** If you specifically need a quad, then it is still achievable in a very similar way without vertex buffers. This simple vertex shader will create a quad for you:

```
struct VertextoPixel
{
    float4 pos              : SV_POSITION;
    float2 tex              : TEXCOORD0;
};

VertextoPixel main(uint vI : SV_VERTEXID)
{
    VertextoPixel Out = (VertextoPixel)0;

    // This vertex shader generates a trianglestrip like this:
    //  1--2
    //    /
    //   /
    //  3--4
    Out.tex = float2(vI % 2, vI % 4 / 2);

    Out.pos = float4(Out.tex * 2 - 1, 0, 1);

    return Out;
}

```

Call it with Draw(4,0) and a trianglestrip primitive topology.

**UPDATE2:** Your texture sampling pixel shader then could look something like this:

```
// Also bind the texture from the API side:
Texture2D myTexture:register(t0);
// If you don't bind a sampler from the API side, a default sampler will be used
SamplerState mySampler:register(s0);

float4 main(VertextoPixel input) : SV_Target
{
  return myTexture.Sample(mySampler, input.tex); // outputs the textured quad
}

```

If you still can not render it, then enable the debug layer when creating your graphics device, or use a graphics debugger like Nvidia Nsight, AMD GPU Perfstudio, PIX for Windows or Intel's Graphics Performance Analizer.

Good luck!

---
Tags: c#, sharpdx
---


# Question
Title: Kinect for Xbox One (+ adapter) and Windows 10
Can I use Kinect Xbox One (with adapter like Kinect for Windows V2 device), SDK 2.0, to build applications on Windows 10? I've read the requirements for Kinect and it lists only Win 8.0 and Win 8.1.

I'd like to use Kinect Xbox One device with Unity 3D and Hololens. Before I buy the device I'd appreciate if anyone can share some experiance or at least to confirm that would be possible to develop apps with Kinect for Xbox One on Win10?

Many thanks.

# Answer
Yes, I can confirm that the second generation Kinect works with Unity on Windows 10. I've worked on two game projects that use this setup: Glimpse and Pixelate (both were originally developed on Windows 8 / 8.1, and upgrading to Windows 10 or copying them to a Windows 10 machine has not resulted in any problems I've experienced)

One heads-up: the Kinect is *very* picky about what USB ports it will work with. It needs a USB 3.0 port with unusually high bandwidth - so if your controller is weak or daisy-chained through a HUB it will likely refuse to cooperate or suffer low framerate. So far my best experience has been with USB 3 controllers embedded in the PC's motherboard - I've yet to find an extension card the Kinect will work with reliably & without complaint.

Also, anecdotally, I've had better luck with the Xbox One Kinect plus the separate USB adapter, than with the integrated "Kinect for Windows" model that has this built-in. Might just be that we had a bad unit, but we experienced periodic crashes with the latter.
> 2 votes

---
Tags: unity, windows, kinect, hololens
---


# Question
Title: How can I make my LibGDX game persist on android even if it's not the active activity
I want my android game using LibGDX to continue keeping track of events in the game, even while it's not the active window.

For example, I have a stat that reduces over time even, if the game is not the active activity. When the stat gets to a certain percentage, I want to push a notification to the android platform.

I found some information to push android notifications. However, I could not find one on how to make a stat persist in the game when a different app or activity is on the main screen.

# Answer
The way that other games do it is by frequently saving the current time to disk then loading it on startup and subtracting it from the saved time. That way you know the duration that the app was off.

When the app is closed or minimised android will call OnPause, OnStop or/and OnDestroy. At which point you quickly grab the system time and save it. You can read more about Android application lifecycles Here. Then when OnStart or OnResume is called you simply read that value from file and work out what timers need to be changed or if they are done.

Hope this helps :)
> 2 votes

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


# Question
Title: Can I use copyrighted music in my video game, even though it's free to play?
I'm making a video game, and thought of making a boss theme, where I use an 8bit remix and the original instrumentals of the song *Chop Suey*. I'm already in contact with the 8bit versions creator, but I'm not sure if I can use the original instrumental, without my game being taken down.

# Answer
You need permission to use the work in your game. Just because a work (like a song) is freely available for you to play/use does *not* mean that also have the right to re-distribute the work yourself. You need to specifically seceure the right to use the work in your game from the person or entity that holds the intellectual property rights.

Music in particular is interesting, as both the composition and the performance are subject to intellectual property laws. You generally need to secure the rights from *both parties* (if they differ), in order to use an existing recording of the song.
> 5 votes

---
Tags: copyright, music
---


# Question
Title: Off-Screen Image processing with SharpDX
I need help with a image processing task... I'm using SharpDX which I am very new to. I have a device3D, device3DContext... I have a Texture2D for off-screen rendering... I have a RenderTargetView...

Here is what I cannot figure out... I need to create a Quad aligned to the target dimensions... based on a TriangleStrip... I need to load an image onto said Quad... I need to be able to apply a Pixel Shader to it...

Here is my prototype so far...

public event Action OnInitialized;

```
    public ImageProcessor()
    {

    }

    public void Initialize(System.Drawing.Size size)
    {
        try
        {

            var bestAdapter = DisplayAdapters.GetBestAdapter(SharpDX.Direct3D.FeatureLevel.Level_10_0);

            using (
                var device = new SharpDX.Direct3D11.Device(bestAdapter,
                    SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport, bestAdapter.FeatureLevel()))
            {
                Device = device.QueryInterface<SharpDX.Direct3D11.Device1>();
            }

            using (var dxgiDevice = Device.QueryInterface<SharpDX.DXGI.Device>())
            {
                GPUDescription = dxgiDevice.Adapter.Description.Description;
            }

            DeviceContext = AddDisposable(Device.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>());

            var colorFormat = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            var bufferDescription = new SharpDX.Direct3D11.Texture2DDescription()
            {
                ArraySize = 1,
                BindFlags = SharpDX.Direct3D11.BindFlags.RenderTarget | SharpDX.Direct3D11.BindFlags.ShaderResource,
                CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None,
                Format = colorFormat,
                Height = size.Height,
                Width = size.Width,
                MipLevels = 1,
                OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage = SharpDX.Direct3D11.ResourceUsage.Default
            };

            Target = new SharpDX.Direct3D11.Texture2D(Device, bufferDescription);

            RenderTargetView = new SharpDX.Direct3D11.RenderTargetView(Device, Target);

            OnInitialized?.Invoke(this);

        }
        catch (SharpDX.SharpDXException ex)
        {

            var desc = ex.ResultCode;
        }
    }

    public System.Drawing.Image ProcessImage(string filename)
    {

        Device.ImmediateContext.ClearRenderTargetView(RenderTargetView, SharpDX.Color.Gray);

        Target = TextureLoader.CreateTexture2DFromFile(Device, filename);

        Device.ImmediateContext.Flush();

        var memoryStream = new MemoryStream();

        CopyTexture.ToImage(DeviceContext, Target, memoryStream);
        memoryStream?.Flush();

        var processedImage = System.Drawing.Image.FromStream(memoryStream);
        memoryStream?.Dispose();

        return processedImage;
    }

    private SharpDX.Direct3D11.Device1 Device;
    private SharpDX.Direct3D11.DeviceContext1 DeviceContext;

    private SharpDX.Direct3D11.Texture2D Target;
    private SharpDX.Direct3D11.RenderTargetView RenderTargetView;

    public string GPUDescription = string.Empty;

```

Please explain code in detail...

I've asked a similar question and someone provided a HLSL file which didn't require vertices however, I have no idea how to apply it... So I figured I'd provide the code and ask for more detailed help.

# Answer
Hey mate so there are a few ways to draw on screen, you can draw a full screen triangle and do some fancy shader math or you can render a full quad.

Ill show you how to do both.

Full Screen Quad Render:

This is the full quad renderer class, its a bit of setup but it works well, I pulled it out of my code base so you will have to remove all my stuff.

```
Public Class QuadRenderer
Private _vertexBuffer As VertexPositionTexture() = Nothing
Private _indexBuffer As Integer() = Nothing
Private instdata As DataStream
Private vertexBuffer As Buffer
Private indexBuffer As Buffer
Private QuadInputlayout As InputLayout
Private QuadVertexBinding As VertexBufferBinding()

Public Sub New(_device As LowLevelDevice, ShaderInput As ShaderBytecode)
  'setting up the indexbuffer
    _indexBuffer = New Integer() {0, 3, 2, 0, 1, 3}
    instdata = New DataStream(_indexBuffer.Count * 4, True, True)
    instdata.WriteRange(_indexBuffer, 0, _indexBuffer.Count)
    instdata.Position = 0
    indexBuffer = _device.CreateBuffer(instdata, _indexBuffer.Count * 4, ResourceUsage.Immutable, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0)

'setting up the quad verts
    _vertexBuffer = New VertexPositionTexture(3) {}
    _vertexBuffer(0) = New VertexPositionTexture(New Vector3(-1.0!, 1.0!, 0!), New Vector2(0!, 0!))
    _vertexBuffer(1) = New VertexPositionTexture(New Vector3(1.0!, 1.0!, 0!), New Vector2(1.0!, 0!))
    _vertexBuffer(2) = New VertexPositionTexture(New Vector3(-1.0!, -1.0!, 0!), New Vector2(0!, 1.0!))
    _vertexBuffer(3) = New VertexPositionTexture(New Vector3(1.0!, -1.0!, 0!), New Vector2(1.0!, 1.0!))

  'setting up the vertexbuffer
    instdata = New DataStream(_vertexBuffer.Count * VertexPositionTexture.Stride, True, True)
    instdata.WriteRange(_vertexBuffer, 0, _vertexBuffer.Count)
    instdata.Position = 0

    vertexBuffer = _device.CreateBuffer(instdata, New BufferDescription(_vertexBuffer.Count * VertexPositionTexture.Stride, ResourceUsage.Immutable, BindFlags.VertexBuffer, 0, 0, 0))
    QuadVertexBinding = New VertexBufferBinding() {New VertexBufferBinding(vertexBuffer, VertexPositionTexture.Stride, 0)}

  'setting up the inputlayout
    Dim PosColor As InputElement() = {New InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData,
    0), New InputElement("TEXCOORD", 0, Format.R32G32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0)}

    QuadInputlayout = _device.CreateInputLayout(ShaderInput, PosColor)
End Sub

Public Sub RenderQuad(ByRef _Context As DeviceContext,srv as shaderresourceview)
  'setting renderstate
    _Context.PixelShader.SetShaderResource(0, srv)' srv= the texture you want to draw
    _Context.InputAssembler.InputLayout = QuadInputlayout
    _Context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList
    _Context.InputAssembler.SetVertexBuffers(0, QuadVertexBinding)
    _Context.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0)
    _Context.DrawIndexed(6, 0, 0)
End Sub

End Class

```

\_device.CreateInputLayout is a custom inputlayout builder so you just pass it a vertex shader and it gives you the correct inputlay but you will have to start a new question for that.

HLSL: This is the shader for the full screen quad.

```
Texture2D colorMap; //DeviceContext.PixelShader.SetShaderResource(0, srv) sets this on the cpu
sampler colorSampler = sampler_state
{

AddressU = Clamp;
AddressV = Clamp;
Filter = MIN_MAG_MIP_POINT;
};
struct VertexInput
{
float3 Position : POSITION0;
float2 TexCoord : TEXCOORD0;
};
VertexShaderOutput VSQuad2(VertexInput input)
{
VertexShaderOutput result;

result.Position = float4(input.Position,1); //reading vertex data from the stream
result.TexCoord = input.TexCoord;

return result;
}
PixelShaderOutput PShader(VertexShaderOutput input)
{
 PixelShaderOutput output = (PixelShaderOutput)0;

 float4 Color= colorMap.Sample(colorSampler , input.TexCoord);//the texture you want to draw

 return output;
}

```

Full Screen Triangle:

The cool thing about this one is that there is no CPU side set up, the DX runtime will generate the vertex data for you.

Use this bit of code to draw the full screen triangle.

```
    DeviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList
    DeviceContext.PixelShader.SetShaderResource(0, srv)' srv= the texture you want to draw
    DeviceContext.InputAssembler.SetVertexBuffers(Nothing)
    DeviceContext.InputAssembler.SetIndexBuffer(Nothing, Nothing, Nothing)
    DeviceContext.Rasterizer.State = Nothing
    DeviceContext.Draw(3, 0)

```

HLSL:

This is where the magic happens, you take your 3 verts and then position them in a way that covers the whole view port.

```
Texture2D colorMap; //DeviceContext.PixelShader.SetShaderResource(0, srv) sets this on the cpu
sampler colorSampler = sampler_state
{

AddressU = Clamp;
AddressV = Clamp;
Filter = MIN_MAG_MIP_POINT;
};

struct VertexShaderOutput
{
float4 Position : SV_Position;
float2 TexCoord : TEXCOORD0;

};
struct PixelShaderOutput
{
float4 Color : SV_Target0;

};

// outputs a full screen triangle with screen-space coordinates
// input: three empty vertices
VertexShaderOutput VSQuad( uint vertexID : SV_VertexID )
{
VertexShaderOutput result;
result.TexCoord = float2((vertexID << 1) & 2, vertexID & 2);
result.Position  = float4(result.TexCoord  * float2(2.0f, -2.0f) + float2(-1.0f, 1.0f), 0.0f, 1.0f); // compute the position data
return result;
}

PixelShaderOutput PShader(VertexShaderOutput input)
{
 PixelShaderOutput output = (PixelShaderOutput)1;
float4 Color = colorMap.Sample(colorSampler, input.TexCoord); //the texture you want to draw
output.Color =Color;
 return output;
}

technique11 Render
{
pass P0
{

    SetVertexShader( CompileShader( vs_5_0, VSQuad() ) );
    SetPixelShader( CompileShader( ps_5_0, PShader() ) );
}
}

```

I just had a look at the other question you asked and I need to say that the guy who wrote the answer there explains of the full screen triangle stuff works much better.
> 1 votes

---
Tags: c#, hlsl, sharpdx
---


# Question
Title: Can I make a multiplayer Android Game using Android Studio?
I want to create a multiplayer android game, where the clients connect together via a web server.

My question is: Is it possible to make this kind of games using Android Studio with other libraries like LibGDX and Java sockets?

# Answer
> 3 votes
Of course! You can make multiplayer game with Android Studio, you can utilize Firebase too if you don't have any online server to manage peer connection.
If you prefer using Java Socket Library, you will need to manage the server too or just play it locally like how ShareIt works..
Here are some reference for making a game with Android Studio:
1. LibGDX wiki
2. LibGDX Text Tutorial
3. LibGDX Video Tutorial
4. Example game built with Android Studio

Library for managing peer connection:
1. Firebase Setup
2. Socket.io (Socket Library)
If you want to connect with other peer via internet with Socket.io, you will need to implement NodeJS Server or PHP Socket Server..

---
Tags: java, android, android-studio
---