# Question
Title: Why is the ownership fixed when synching objects?
I'm creating a billiard game where one white ball will be controlled by two online players.

I have set my object photonview to ownership takeover.

1. When a player shoots the ball in one client, it is synced on other client.
2. Now when I update the ball on the other client, the other client is not updated.

Why is the ownership fixed?

Only one client is sending the updates to the other client, and not vice versa.

What should I do here?

# Answer
I can't say why the ownership is fixed.

But that being the case I'd suggest making two cue balls, one owned by each client.

Only make one visible at a time based on whose turn it is. Then after their turn, update the other ball with the exact resulting properties of the first. Swap their visibility, rinse, repeat.

Also, make sure to turn off all the physics of the invisible ball.
> 1 votes

---
Tags: unity, multiplayer, unity-networking
---


title: Create ROI tools for analysis

text:
# Question
Title: Create ROI tools for analysis
I want to create some ROI tools on my game for personal analysis.

Let's say that I have 3 different level of special powers with a recursive cost and certain bonus. So, I want to see when certain level will start have income.

1st example: 1000 coins for 10 uses. Bonus: +10% on farming speed. 2000 coins for 10 uses. Bonus: +20% on farming speed. Etc

In this example, I know exactly what the bonus will do. I have the price of the farming per unit and I can calculate the income per use for each power level. So, I can tweak the numbers using the ROI tool to make the effect better.

2nd example: 1000 coins for 3 power ups on a weapon. Bonus: +1 attack power, +5% chance to destroy the weapon. 2000 coins for 3 power ups on a weapon. Bonus: +2 attacking power, 10% chance to destroy the weapon.

3rd example: 1000 coins per use. Bonus: 30% heal, 5% chance to get injured. 2000 coins per use. Bonus: 50% heal, 10% chance to get injured.

As you can see, the first example is simple to calculate the income vs cost. However, the second and third example don't have an exact effect and both of them have a probability to either good or bad effect. How do you work on this type of ROI? How do you calculate the pros of each level?

# Answer
There are two ways to approach a problem like this, empirically and anecdotally.

**Empirically**, you could use tools like Excel or Machinations to model each. What you are looking at are essentially feedback loops. The more you use an item the more likely it is to have a negative effect, but also the more cumulative effect it will have. If you can model the total beneficial output against the detrimental output over time/uses, and adjust for cost, you should see some point where a higher level is more effective.

For example, in an RTS like StarCraft you could graph the number of gatherers (or resources spent on gathers) against the amount of resources gathered per period of time. You then also model that against how many resources you'll have a certain period, if you build only a specific number of gatherers.

Believe it or not, you're already using some empirical analysis. The fact that you are doubling both the reward and the penalty for each level, as well as the cost, is an example of simple empirical balancing. If you just continue with this and actually look at how it changes per each hit. There's a lot of possible outcomes, it's about modeling them all and seeing what's there.

**Anecdotally**, you could place the bonuses in the game as they are and track what players use. As players aim to maximize their effectiveness in a game, they'll naturally tend to a certain set of behavior. If more are skipping on the higher levels, maybe they bonus is too little or the negative too harsh. Then you can adjust, and continue watching results as players play.

---

It can be daunting, but I'd say start simple and if you find some specific concept you want to model, search for or ask another question about that specific concept.

**Side note**, those current numbers seem like they'd lead to an uninteresting choice for the player. Level 2 is literally 2 times the effects. If you introduce some sort of scaling or easing. Consider maybe the base benefit of the next level is 3 times as strong, but the chance of the weapon breaking increases at a faster rate. When you get your basics modeled, maybe consider something like that as a next step.
> 1 votes

---
Tags: game-design, tools, analytics
---


# Question
Title: Why isn't my Unity rotation angle comparision not working?
I'm trying to make a game with movement. I'm trying to write an if-statement that checks if `transform.rotation.x` is greater than a value. However, currently there is no effect. I've tried changing the comparision operator to `>`, but it had no effect. This is the code that I am using:

```
using UnityEngine;
using System.Collections;

public class movement : MonoBehaviour
{

    public float moveSpeed;

    public Transform REVOLVR;

    // Update is called once per frame
    void Update ()
    {
        if(REVOLVR.rotation.x > -60)
        {
            this.transform.Translate (Vector3.forward * moveSpeed);
        }
    }
}

```

# Answer
> 1 votes
You probably want to use `Transform.eulerAngles` instead accessing the rotation quaternion's X-component individually. You also probably want to change the check to the domain \[0, 360\] as I believe that the euler angles are clamped to that domain.

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


# Question
Title: SDL2 application occasionally refuses to close
I've been working on a sliding puzzle/game of fifteen clone in SDL recently. A problem I've had is that when I close the game the app isn't always removed from the dock and I can't force quit it. It shows up in task manager, but doesn't show up in Activity Monitor so I can't quit the game from there and end up having to hard reboot.

I can't find any pattern as to why it happens some times and not others. I thought there might be something wrong with my cleanup of SDL but I can't find any problems, although I'm honestly not sure what to look for. The full source code for this project can be found here. Thank you

# Answer
> 2 votes
In your Graphics.cpp file you have the following destructor implemented:

```
void Graphics::destroy() {
    window     = NULL;
    renderer   = NULL;
    tilenumber = NULL;
    clicks     = NULL;
    wintext    = NULL;
    menutext   = NULL;
    menuinstr  = NULL;
    cat        = NULL;
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    TTF_Quit();
    SDL_Quit();
}

```

The issue here is that you null out `renderer` and `window` before destroying them. You are essentially trying to destory two null-pointers here, which likely results in nothing getting destroyed.

So, instead move the destroy calls to the top of the destructor. In any case, nulling out pointers isn't in any way required and seems a little redurant to me.

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


# Question
Title: Data Driven Design and Game Screen Resolution
So I have just begun studying Data Driven Design and implementing it into a project. I just encountered an issue and I have not be able to locate any material that suggests an elegant if not practical design to address it.

In my case I am using an XML file to assign game objects' member variables such as x/y coordinates, etc. My issue is that the values are still in a sense 'hard-coded', i.e. x="300" y="blah blah", but what if I want to offer different window resolutions? Beyond making X number of XML files for each individual resolution, I am unsure of how to couple DDD and a feature that effects the data in manner such as this.

Could someone please provide any good ideas on how to satisfy the issue? Documented or personal experience are welcomed.

# Answer
> 1 votes
I think you want to put them in world coordinate position instead of screen coordinates; instead of the values relating to a position on the screen and thus changing; make, it say the position x=30 y=50 for example, the same on any screen so that the world coordinates are the same (a specific area in the game world) in it's own coordinate system separate from the screen

---
Tags: c++, xml, data-driven
---


title: Formula for range based attenuation

text:
# Question
Title: Formula for range based attenuation
I am trying to implement a simple shader for point lights, but I am struggling with the attenuation function. I know that normally you would use three coefficients (constant, linear, and quadratic), however in my framework point lights only have position, intensity (color) and range.

Is there any formula that only requires the light's range to work?

# Answer
> 0 votes
The three-coefficient attenuation is just a crutch used for tuning lights in the fixed pipeline; you definitely shouldn't worry about it when implementing a shader.

In physics light attenuates according to the inverse-square law, for which only distance is required. In computer graphics *sometimes* a simpler linear attenuation is preferable. Again, only distance is required.

---
Tags: opengl, c++, rendering, glsl
---


# Question
Title: Google Play Services somehow authenticates without internet connection
*This question is asked in the context of the Google Play Services plugin for Unity.*

Following the documentation for the Google Play Services plugin for Unity, I called the `Social.localuser.Authenticate()` function in my game to check if the player is authenticated (ie: logged in to google play services).

Here is the authentication code that I am currently calling:

```
void Awake ()
{
    PlayGamesPlatform.Activate();

    Social.localUser.Authenticate((bool success) => {
        if (success)
        {
            GetLeaderboardData("FirstLoad");
        }
        else
        {
            loadingText.text = "Failed to connect to Google Play Services.";
            StartCoroutine("WaitAndStart");
        }

        authenticated = success; //success returns true even without an active internet connection
    });
}

```

This works fine with an active internet connection. However, if the player has logged in before, and then launch the game without an internet connection, this function somehow returns `true`. It doesn't make sense (at least not to me) that the player can authenticate without an active internet connection. Does anyone know if this was intended? (Or if I made a mistake of some sort somewhere?)

Should it have been indeed intended (and the method is checking against a cache of some sort), is there no method to check if the player has an active connection to google's servers? Something along the lines of `PlayGamesPlatform.CheckConnection()`?

# Answer
If the user already logged in with the account, the login will be silent and it's possible without internet connection. So, yes, it's intended.

If you want to force the user to have an internet connection, you can check the `NetworkReachability`
> 1 votes

---
Tags: unity, google-play-services
---


# Question
Title: My player died and if i clicked play in the main it will go to the last scene and say gameover
I am trying to make a gameover scene where in if the player is game over The game will go back to the main or start up then when I press play it will start new game however if i am game over and go back to main and pressed play it will only show me Game over and wont continue my code is..... Gameover code..

```
#pragma strict
import UnityEngine.UI;
private var StopGame: boolean=false;
private var showGUI: boolean=false;
var GUIstop: GameObject;
var StopMenu;
var respawn : Transform;

private var canvas : Canvas;

function Start()
{
canvas = GetComponent.<Canvas>();
canvas.enabled = false;
}

function Update () {

if(HealthControl.LOVES==0){
Pause();

  Application.LoadLevel (0);

}

}
public function Pause()
{
canvas.enabled = !canvas.enabled;
Time.timeScale = Time.timeScale == 0 ? 1 : 0;
}

public function Quit()
{
#if UNITY_EDITOR
EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}

```

# Answer
Try to call your scene in script, for instance: instead of 0 put the scene name.
> -1 votes

# Answer
ok, so what does the StopGame do, beacuse if it have any function you have set it to false.
> -1 votes

---
Tags: unityscript
---


# Question
Title: How to adapt to using a graphics library in a game coded using Java's native graphics methods?
I've spent months coding a game that uses Java's native graphics methods to create a polygon-based 3D engine, and at this point it's about 12,000 lines long. However, the graphics performance is starting to get bogged down and is wildly inconsistent (e.g. running it on my very nice windows laptop gets me only around 10 FPS, and running it on my Macbook Air gets me around 30-40). From what I've read, Java's graphics are not optimized for speed as much as they would be had I used a library created to aid in drawing efficiency. Given how much work I've put into the project without knowing I probably should be using a graphics library to speed my game up, how easy would it be to implement LWJGL to my game? And if that were difficult, are there any libraries I could use instead that would make transitioning easier and would boost performance and/or at least make the frame rate more consistent across different systems?

Thanks.

# Answer
There is only little useful information in your question. The reason, you are getting low fps is that you aren't actually using your graphics card. LWJGL uses OpenGL which is a graphics pipeline/interface that runs on GPUs. In such limited space, I cannot explain, how to make a rendering engine in OpenGL since there are a lot of different ways you can do it and it is far too compex. But basicly it looks like this: almost everything is static, which means OpenGL itself provides hardly any Objects to use. Little is stored on your CPUs RAM, things are rather stored on the GPUs memory and accessed via handles, which you can think of as pointers (in c/c++ you'd use GLuint, in java just int) pointing to memory in the graphics card. GPUs are faster in terms of rendering, because they have a lot of cores, that by themselves aren't that fast, however since there are so many of them (my card has 640). They execute code in parallel, that's why you can't just port your Java or even C programs directly to the GPU, you would have to basicly start your rendering engine all over. LWJGL isn't that hard, especially if you already wrote a 3D-Engine in pure Java (not bad!). It is well documented and there are hundrets of tutorials with examples on it. Any OpenGL code looks more or less the same in any programming language, so even examples written in C++ will be helpful in Java.
> 2 votes

---
Tags: java, lwjgl, optimization
---


# Question
Title: How do you get audio clips to play on all clients?
I am new to networking with so this is probably a noob question. For context I am trying to get a gunshot sound effect to play and be heard by all players.

# Answer
The specifics of Unity networking kind of fly right over my brain, but here's a rough conceptual model to how a game would conventionally handle this.

**1.** Client 1 tells the server "I'm shooting my gun now". Client 1 plays the gun noise even if the server says later they **didn't** shoot their gun and they've been a very naughty cheaty boy. (Damage deductions should be checked by the server though)

**2.** The Server confirms that Client 1 can shoot their gun and they are where they say they are. (Server should always be authoritative over actions that can cause damage to other players or lead to potential exploits)

**3.** If Client 1 could shoot their gun then the Server multicasts this information to the other Clients ("Hey fellas, Client 1 just shot a thing!"). They then update their local representation of Client 1 to play the gun audio sting.

**Rejection Path:** Server does not agree with Client 1 over this violent shooty interruption, and does not propagate the change to the other Clients.

The server shouldn't know anything about the audio assets. It's multicasting the concept that the player has shot, not the sound itself. Let the client code play the sound when they get the message.
> 1 votes

# Answer
The client will already have the sound ready to be played, it just needs to know when to play it.

All you need to do, is ensure you are playing the sounds at the right time. In most cases the sound will play due to another action or event happening.

Did the server send out a notification telling you that someone died? Play the death sound. Did you get a notification from the server that a coin was picked up? Play the coin was picked up sound.
> 0 votes

# Answer
If you want server controlled sound on the clients, the clients would either have to have them already or download them while connecting (you could also stream them, but I don't see a point in that + playback will delay a bit). To know, when to play what sound add sound-sources the server can send to the client, which contain information about things like what sound to play (of course), when to play it, from where to play it, how loud and so on. You could for example store all sounds in a hashmap (client) to map sound names to actual sounds.
> 0 votes

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


title: What is more performance friendly?

text:
# Question
Title: What is more performance friendly?
I'm wondering what is more performance friendly:

1) Rendering a texture (in a seperate RenderTarget2D) and reuse it. (That will use multiple `spriteBatch.End()` / `spriteBatch.End()` calls, every drawing cycle)

---

2) Rerendering the texture multiple times (directly on the default rendertarget), but using only a single spriteBtach Begin/End call.

I think it is pending on how many times I'm going to redraw that texture, but calling `spriteBatch.End()` / `spriteBatch.End()` is taking really much performance...

So what should I use, when the redrawing count is pending on the user?

# Answer
> 0 votes
The spriteBatch tries to be as efficient as possible. A spriteBatch is most efficient rendering the same (source)texture over and over. Since this means the GPU doesn't need to receive new texture information (which is the most expensive part of the sprite drawing operation. This is the reason most games pack textures into a texture or sprite *atlas*.

So in your game, if you *can* use 1 texture and 1 spriteBatch, that will be the most efficient way of drawing things to the default rendertarget.

```
//Draw 100 sprites very fast.
spriteBatch.Begin();
for(int i=0;i<100;i++)
{
   spriteBatch.Draw(myTexture, new Vector2(i*10,i*2), Color.White);
}
spriteBatch.End();

```

A 2D sprite is secretly a 3D plane- as today's GPUs draw 3D triangles. Thus a spriteBatch has a lot of parameters that simply convert your 2D coordinates to the 3D system. The spriteBatch.Draw() method has a lot of parameters to set the position, scale and rotation of the sprite. See this answer about spriteBatch.Draw overloads.

```
//Draw 100 sprites very fast, each one rotated and scaled.
spriteBatch.Begin();
for(int i=0;i<100;i++)
{
    spriteBatch.Draw (myTexture, new Vector2(i*10,i*2), null, Color.White, (float)Math.PI/(float)i, new Vector2(myTexture.Width/2,myTexture.Height/2), (float)i/100f, SpriteEffects.None, 0);
}
spriteBatch.End();

```

---
Tags: xna, performance, spritebatch
---


# Question
Title: Is JavaScript viable for serious multiplatform 2D game development?
Ever since I was a little kid, my dream has been to develop games. Well, now that I am older, more mature, and have some programming experience, I would like to start. However, I would like to turn this into a career.

I would like to develop strategy games like *"Stronghold"* and *"Age of Empires"*.

The problem is that my language of choice is JavaScript.

# Answer
> 1 votes
The comment is correct, language doesn't matter too much. If you are fluent, and know your limitations, nothing can stop you. Javascript is a pretty common language, you'll find tons of examples easily, and will have plenty of people who can answer questions for you. Whether you build your own framework, or use an existing Engine, there are plenty of options open to you. You might enjoy Unity3d, which supports "UnityScript"--essentially Javascript with a more classical semantic structure. See this for a quick rundown.

---
Tags: c++, game-design, javascript
---


title: How to implement buttons in Java?

text:
# Question
Title: How to implement buttons in Java?
I'm new to java and I want to know how to implement buttons for my menustate. Right now all I did is I made pictures of the buttons (play and exit) and just used `g.drawImage` to draw my Image to the game. Now I want to make those buttons useful. I also added mouse Input.

My code

**MenuState**

```
private static final int ButtonWidth = 256, ButtonHeight = 256;

  public MenuState(Handler handler){
    super(handler);
  }

  @Override
  public void tick() {
    if(handler.getMouseManager().isLeftPressed())
      State.setState(handler.getGame().gameState);
  }

  @Override
  public void render(Graphics g) {
    g.setColor(Color.RED);
    g.fillRect(handler.getMouseManager().getMouseX(), handler.getMouseManager().getMouseY(), 8, 8);
    g.drawImage(Assets.PlayButton, 500, 100, ButtonWidth, ButtonHeight, null );
    g.drawImage(Assets.ExitButton, 500, 400, ButtonWidth, ButtonHeight, null);
  }
}

```

**MouseManager**

```
  private boolean leftPressed;
  private int mouseX, mouseY;

  public MouseManager(){

  }

  //Getters

  public boolean isLeftPressed(){
    return leftPressed;
  }

  public int getMouseX(){
    return mouseX;
  }

  public int getMouseY(){
    return mouseY;
  }

  // Implemented methods

  @Override
  public void mousePressed(MouseEvent e) {
    if(e.getButton() == MouseEvent.BUTTON1)
      leftPressed = true;

  }

  @Override
  public void mouseReleased(MouseEvent e) {
    if(e.getButton() == MouseEvent.BUTTON1)
      leftPressed = false;
  }

  @Override
  public void mouseMoved(MouseEvent e) {
    mouseX = e.getX();
    mouseY = e.getY();
  }

  @Override
  public void mouseDragged(MouseEvent e) {
    // TODO Auto-generated method stub

  }

  @Override
  public void mouseClicked(MouseEvent e) {
    // TODO Auto-generated method stub

  }

  @Override
  public void mouseEntered(MouseEvent e) {
    // TODO Auto-generated method stub

  }

  @Override
  public void mouseExited(MouseEvent e) {
    // TODO Auto-generated method stub

  }
}

```

**Handle(if needed)**

```
public class Handler {

  private Game game;
  private World world;

  public Handler(Game game){
    this.game = game;
  }

  public GameCamera getGameCamera(){
    return game.getGameCamera();
  }

  public KeyManager getKeyManager(){
    return game.getKeyManager();
  }

  public MouseManager getMouseManager(){
    return game.getMouseManager();
  }

  public int getWidth(){
    return game.getWidth();
  }

  public int getHeight(){
    return game.getHeight();
  }

  public Game getGame() {
    return game;
  }

  public void setGame(Game game) {
    this.game = game;
  }

  public World getWorld() {
    return world;
  }

  public void setWorld(World world) {
    this.world = world;
  }
}

```

**Game**

```
  private Display display;
  private int width, height;
  public String title;

  private boolean running = false;
  private Thread thread;

  private BufferStrategy bs;
  private Graphics g;

  //States
  public State gameState;
  public MenuState menuState;

  //Input
  private KeyManager keyManager;
  private MouseManager mouseManager;

  //Camera
  private GameCamera gameCamera;

  //Handler
  private Handler handler;

  public Game(String title, int width, int height){
    this.width = width;
    this.height = height;
    this.title = title;
    keyManager = new KeyManager();
    mouseManager = new MouseManager();
  }

  private void init(){
    display = new Display(title, width, height);
    display.getFrame().addKeyListener(keyManager);
    display.getFrame().addMouseListener(mouseManager);
    display.getFrame().addMouseMotionListener(mouseManager);
    display.getCanvas().addMouseListener(mouseManager);
    display.getCanvas().addMouseMotionListener(mouseManager);
    Assets.init();

    handler = new Handler(this);
    gameCamera = new GameCamera(handler, 0, 0);

    gameState = new GameState(handler);
    menuState = new MenuState(handler);
    State.setState(menuState);
  }

  private void tick(){
    keyManager.tick();

    if(State.getState() != null);
        State.getState().tick();
  }

  private void render(){
    bs = display.getCanvas().getBufferStrategy();
    if(bs == null){
      display.getCanvas().createBufferStrategy(3);
      return;
    }
    g = bs.getDrawGraphics();
    //Clear Screen
    g.clearRect(0, 0, width, height);
    //Draw Here!

    if(State.getState() != null);
          State.getState().render(g);

    //End Drawing!
    bs.show();
    g.dispose();
  }

  public void run(){

    init();

    int fps = 1000;
    double timePerTick = 1000000000 / fps;
    double delta = 0;
    long now;
    long lastTime = System.nanoTime();
    long timer = 0;
    int ticks = 0;

    while(running){
      now = System.nanoTime();
      delta += (now - lastTime) / timePerTick;
      timer += now - lastTime;
      lastTime = now;

      if(delta >=1){
        tick();
          render();
          ticks++;
          delta--;
      }
      if(timer >= 1000000000){
        System.out.println("Tick and Frames:" + ticks);
        ticks = 0;
        timer = 0;
      }
    }

    stop();

  }

  public KeyManager getKeyManager(){
    return keyManager;
  }

  public MouseManager getMouseManager(){
    return mouseManager;
  }

  public GameCamera getGameCamera(){
    return gameCamera;
  }

  public int getWidth(){
    return width;
  }

  public int getHeight(){
    return height;
  }

  public synchronized void start(){
    if(running)
      return;
    running = true;
    thread = new Thread(this);
    thread.start();
  }

  public synchronized void stop(){
    if(!running)
      return;
    running = false;
    try {
      thread.join();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

```

# Answer
> 2 votes
You can use the mouseClicked function and then check if the clicked coordinates are within the bounds of the button:

```
public void mouseClicked(MouseEvent e){
   if(button.x < e.getX() && buttonWidth + button.x > e.getX() && button.y < e.getY() && button.y + buttonHeight > e.getY(){
        //Button has been clicked
    }
}

```

In your case for the play button button.x would be 500 and button.y would be 100. Also please don't post all of the code, we only need relevant code...

This is how I did it (Don't change your code that does work for you as I made this in 5 minutes and what I made is probably not very optimized):

```
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class Game implements MouseListener{

    public static void main(String[] args){
            new Game();
    }

    private JFrame frame;
    private Game(){
        init();
        loop();
    }

    private void init(){
        frame = new JFrame("TEST");
        frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        frame.setSize(600, 400);
        frame.addMouseListener(this);
        running = true;
        frame.setVisible(true);
    }

    private boolean shouldClose = false;
    private boolean running;
    private final int buttonWidth = 100;
    private final int buttonHeight = 50;
    private void loop(){
        while(running){
            Graphics g = frame.getGraphics();
            g.drawRect(500, 100, buttonWidth, buttonHeight);
        }
        frame.setVisible(false);
    }

@Override
public void mouseClicked(MouseEvent e) {
    if(500 < e.getX() && buttonWidth + 500 > e.getX() && 100 < e.getY() && 100 + buttonHeight > e.getY()){
        System.out.println("BUTTON WAS PRESSED!");
        running = false;
    }
}

@Override
public void mousePressed(MouseEvent e) {

}

@Override
public void mouseReleased(MouseEvent e) {

}

@Override
public void mouseEntered(MouseEvent e) {

}

@Override
public void mouseExited(MouseEvent e) {

}
}

```

---
Tags: java, gui
---


# Question
Title: How do I fix this access violation when I exit my custom OpenGL game engine?
I'm writing an game engine, where the engine is written in a project and exports a .dll file. In another project, in the same solution as the engine, there is a sandbox project which uses the engine. However, there is a bug.

I run the sandbox project in debug mode with the engine dll. When I spam my mouse and keyboard for a few seconds, and close the program via the exit button, the program crashes with an error:

> Exception thrown at 0x00000043 in phantom-sandbox.exe: 0xC0000005: Access violation executing location 0x00000043.
> If there is a handler for this exception, the program may be safely continued.

---

I found the source of the bug. Since I'm currently writing the engine for OpenGL, I have to initialize GLEW, and I need to create a `HGLRC`. If I don't initialize this `HGLRC`, everything works.

This is not the ideal solution, since I need to use OpenGL for my engine. I went forth without exporting the .dll from the engine, making the engine an application, instead. I made a `main.cpp`, and wrote it to use the engine, enabling OpenGL rendering. I tried to recreate the bug, but everything works!

I thought it might OpenGL, but then now I'm thinking it might be my engine. How do I fix this?

---

Here is my code, where it errors:

```
    int const main_result = invoke_main()

    __telemetry_main_return_trigger(nullptr);

    if(!__scrt_is_managed_app())
        exit(main_result)l

    if(!has_actor) // < this is the line being sent to the call stack
        _cexit();

    __scrt_unititialize_crt(true, false);
    return main_result;
}

__except (_seh_filter_exe(GetExceptionCode(), GetExceptionInformation()))
{
    int const main_result = GetExceptionCode();

    if(!__scrt_is_managed_app())
        _exit(main_result);

```

Here is the call stack:

# Answer
What's happening is that the app is dereferencing a pointer that points to protected memory. I don't know a lot about Windows, but it looks to me like your application (or the support code that runs your application) is trying to clean up after running, and is hitting this problem. There are 2 possible causes that I can think of off the top of my head:

1. You've deallocated an object that the runtime is still using, and now that it's gone when the runtime attempts to use it, the crash occurs.
2. Something in your app has overwritten some memory that is used by the runtime, and what was once a valid pointer has been overwritten with a garbage address (0x0043).

There are other possibilities, but those seem like the most likely. Usually there are tools for finding memory overwrites. On the Mac we have guard\_malloc which will add guard pages around every allocation, and when something is deallocated, it checks to make sure the correct values are contained in the guard region. If not, then it knows that someone overwrote that memory. Perhaps there's something like that on Windows?
> 1 votes

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


# Question
Title: XNA / MonoGame - render transparent background using stencil buffer problem (3d)
I'm trying to render 3d texture quads with the following properties:

1. With lighting (rule out "AlphaTestEffect").
2. Transparent background (no opacity levels, just binary opaque or transparent).
3. No ordering, eg, I don't want to sort objects by camera distance.

If I just try to render the quads regularly with their transparent background, the result is that even the transparent pixels are written to the depth buffer, which cause a background bug see picture:

So I try to do it with a different way, using the stencil buffer. What I do is the following:

1. Render just the transparent pixels on the stencil buffer, to create a mask.
2. Render the texture itself, again, using the stencil buffer I created before.

Now it works with the background renderings, but the problem is that different quads with transparent background hide each other in transparent pixels, as seen here:

I'm not sure if it's because the stencil buffer is not cleared between renders or maybe in one of my steps I mistakenly write to depth?

Anyway here's my code (at least the relevant parts of it):

```
// set effect and settings for the stencil mask phase
_alphaMaskEffect = new AlphaTestEffect(device);
_alphaMaskEffect.World = Matrix.Identity;
_alphaMaskEffect.AlphaFunction = CompareFunction.Equal;
_alphaMaskEffect.ReferenceAlpha = 0;
_alphaMaskEffect.VertexColorEnabled = true;
_alphaMaskEffect.DiffuseColor = Color.White.ToVector3();
_alphaRenderStencilMaskSettings = new DepthStencilState
{
    StencilEnable = true,
    StencilFunction = CompareFunction.Always,
    StencilPass = StencilOperation.Replace,
    ReferenceStencil = 1,
    DepthBufferEnable = true,
    DepthBufferWriteEnable = false,
};

// set settings for the regular rendering phase
_alphaRenderTextureWithStencilSettings = new DepthStencilState
{
    StencilEnable = true,
    StencilFunction = CompareFunction.Equal,
    StencilPass = StencilOperation.Keep,
    ReferenceStencil = 0,
    DepthBufferEnable = true,
    DepthBufferWriteEnable = true,
};

```

And here's the draw function itself:

```
// set settings for the stencil buffer rendering
device.DepthStencilState = _alphaRenderStencilMaskSettings;

// render stencil buffer
foreach (EffectPass pass in _alphaMaskEffect.CurrentTechnique.Passes)
{
    // draw current pass
    pass.Apply();
    device.DrawUserIndexedPrimitives
        <VertexPositionNormalTexture>(
        PrimitiveType.TriangleList,
        Vertices, 0, 4,
        Indexes, 0, 2);
}

// now render the quad with the stencil buffer
device.DepthStencilState = _alphaRenderTextureWithStencilSettings;

// render effect itself
foreach (EffectPass pass in _effect.CurrentTechnique.Passes)
{
    // draw current pass
    pass.Apply();
    device.DrawUserIndexedPrimitives
        <VertexPositionNormalTexture>(
        PrimitiveType.TriangleList,
        Vertices, 0, 4,
        Indexes, 0, 2);
}

```

**tl;dr** what's the right way to render 3d quads with transparent background, lighting and without sorting objects by distance from camera? And if it's the code I tried - how do I make the renderings stop hiding each other?

# Answer
Hey mate the best way to do it is with alpha test, that way no sorting but it still helps to sort and u can do lighting, render with opaque blend state, cull mode to none.

I do my grass like that, its just a quad with alpha test and then I build all the normal data in the shade. I also do use the vface semantic to flip the normal because its double sided.

alpha test in the pixel shader:

```
 diffuseLayer = DiffuseMaps.Sample(samANISOTROPICClamp, float3(input.TexCoord, input.TextureID));

clip(diffuseLayer.a - 0.18); // 0.18 is the alpha cut off, play with this

```

flipping the normal based on vface:

```
   float3 normalViewSpace = NormalMapToSpaceNormal(NormalLayer.rgb, TBN[2], TBN[1], TBN[0]);
normalViewSpace = input.vFace ? normalViewSpace : -normalViewSpace; // ignore the viewsapce stuff that is for my deferred render

```

Tangents and binormals in the shader based on a normal(N should be float3(0,1,0), UV should be the clip space xy, P should be world space positon:

```
float3x3 cotangent_frame(float3 N, float3 p, float2 uv)
{
// get edge vectors of the pixel triangle
float3 dp1 = ddx_fine(p);
float3 dp2 = ddy_fine(p);
float2 duv1 = ddx_fine(uv);
float2 duv2 = ddy_fine(uv);

// solve the linear system
float3 dp2perp = cross(dp2, N);
float3 dp1perp = cross(N, dp1);
float3 T = dp2perp * duv1.x + dp1perp * duv2.x;
float3 B = dp2perp * duv1.y + dp1perp * duv2.y;

// construct a scale-invariant frame
float invmax =   -sqrt(max(dot(T, T), dot(B, B)));
return float3x3(T * invmax, B * invmax, N);
}

```

here is what the grass can look like:

CPU draw code(with dx 11 I don't have to set vertex buffers(runtime gens the points):

```
            _Context.InputAssembler.SetVertexBuffers(0, Nothing, Nothing)
        _Context.InputAssembler.InputLayout = Nothing

        _Context.OutputMerger.DepthStencilState = _device.RenderStates.Default
        _Context.Rasterizer.State = _device.RenderStates.CullNone
        _Context.SetBlendState(_device.RenderStates.Opaque)

        GrassEffectVars.Set("View", _camera.EyeTransform)
        GrassEffectVars.Set("Projection", _camera.ProjectionTransform)
        GrassEffectVars.Set("GrassNodes", GrassNodesView)
        GrassEffectVars.Set("DiffuseMaps", GrassTextureArraySRV)
        GrassEffectVars.Set("NormalMaps", GrassNormalTextureArraySRV)
        GrassEffectVars.Set("CameraTransform", _camera.Transform)

        GrassEffectVars.Set("gEyePosW", _camera.CameraBounds.Center)
        GrassEffectVars.Set("FarClip", _camera.FarClip)

        _Context.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0)
        _Context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList

        GrassEffectVars.Set("InvView", _camera.Transform)
        GrassEffectVars.Set("WorldViewProj", _camera.EyeProjectionTransform)

        _Context.ApplyShader(GrassEffectPass2)
        _Context.DrawIndexedInstanced(6, GrassCount, 0, 0, 0)

```

Full grass shader as asked(builds quads from points):

```
struct PS_INPUT3
{
float4 Position : SV_POSITION;
float2 TexCoord : TEXCOORD0;
uint TextureID : TextureID;
float4 Depth : VS_DEPTH;
bool vFace : SV_IsFrontFace;
};

PS_INPUT2 VS_Main2(uint id : SV_VertexID, uint instid : SV_InstanceId)
{
PS_INPUT2 output = (PS_INPUT2) 0;

uint particleIndex = id / 4;
uint vertexInQuad = id % 4;

GrassNode Grass = GrassNodes[instid];
float3 WS_Position = Grass.Pos.xyz;
float4 Data = Grass.Data;

float3 position;
position.x = (vertexInQuad % 2) ? 1.0 : -1.0;
position.y = (vertexInQuad & 2) ? -1.0 : 1.0;
position.z = 0.0;
position.xy *= Data.y;

WS_Position.y += Data.y;
WS_Position.x += Data.z;
WS_Position.z += Data.w;

position = mul(position, (float3x3) InvView) ;

WS_Position = WS_Position.xyz + position;

output.Depth.xyz = WS_Position;

output.Depth.w = mul(float4(WS_Position, 1), View).z;
output.Position = mul(float4(WS_Position.xyz, 1.0), WorldViewProj);
output.TexCoord.x = (vertexInQuad % 2) ? 1.0 : 0.0;
output.TexCoord.y = (vertexInQuad & 2) ? 1.0 : 0.0;
output.TextureID = Data.x;
return output;
}

GBufferPixelShaderOutput PS_Main2(PS_INPUT3 input)
{

GBufferPixelShaderOutput output;
float4 diffuseLayer = 0;
float4 NormalLayer = 0;

diffuseLayer += DiffuseMaps.Sample(samANISOTROPICClamp, float3(input.TexCoord, input.TextureID));

clip(diffuseLayer.a - 0.18);

NormalLayer += NormalMaps.Sample( samANISOTROPICClamp, float3(input.TexCoord, input.TextureID)) ;

float3x3 TBN = cotangent_frame(float3(0, 0.957, 0), input.Depth.xyz, input.Position.xy);

TBN[2] = normalize(mul(TBN[2], (float3x3) View));
TBN[0] = normalize(mul(TBN[0], (float3x3) View));
TBN[1] = normalize(mul(TBN[1], (float3x3) View));

float3 normalViewSpace = NormalMapToSpaceNormal(NormalLayer.rgb, TBN[2], TBN[1], TBN[0]);
normalViewSpace = input.vFace ? normalViewSpace : -normalViewSpace;
output.Color = float4(diffuseLayer.rgb,  diffuseLayer.r);

output.RenderMaterialID = matID;

output.Depth = float4(-input.Depth.w / FarClip, 0, EncodeNormal(normalViewSpace.xyz));

return output;

}

```
> 1 votes

---
Tags: xna, xna-4.0, monogame, transparency
---


title: SDL_RenderCopy to set location

text:
# Question
Title: SDL_RenderCopy to set location
I'm coding a game's GUI in SDL2 and c++, I'm using SDL\_RenderCopy to load the buttons on to the screen, but don't know how to get buttons in specific spots eg. bottom left corner, slightly below center. How do I achieve this?

# Answer
You need to manually calculate the positions.

Positioning itself in SDL happens using destination rects. `SDL_RenderCopy` takes in a destination rectangle that you can use to scale and translate what you render.

Finding out the correct position is just a matter of math. For centering, you want to render at `(windowWidth / 2.0f - buttonWidth / 2.0f, windowHeight / 2.0f - buttonHeight / 2.0f)`. Simply offset the Y coordinate if you need to render a button just below. For bottom-left, set the X coordinate to 0, and don't divide the window height.
> 1 votes

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


# Question
Title: Character doesn't move anymore after gameover and clicked play
When my character died it displays gameover and goes back to main menu, then if I clicked play I can see my character however I can't make it move anymore. Any suggestions?

For game over:

```
#pragma strict
import UnityEngine.UI;
private var StopGame: boolean=false;
private var showGUI: boolean=false;
var GUIstop: GameObject;
var StopMenu;

private var canvas : Canvas;

function Awake()
{
    canvas = GetComponent.<Canvas>();
    canvas.enabled = false;
}

function Update ()
{
    // If the player has run out of health...
    if(HealthControl.LOVES==0)
        Pause();
    //  }
}

public function Pause()
{
    canvas.enabled = !canvas.enabled;
    Time.timeScale = Time.timeScale == 0 ? 1 : 0;
    StopGame=true;
}

public function Quit()
{
    #if UNITY_EDITOR
    EditorApplication.isPlaying = false;
    #else
    Application.Quit();
    #endif
}

```

For character movement:

```
   function Update () {

       transform.rotation.z=0;

       if(Input.GetKey(KeyCode.UpArrow)){
           transform.position.y+=moveSpeed*Time.deltaTime;
       }
       else if(Input.GetKey(KeyCode.RightArrow)){
           transform.position.x+=moveSpeed*Time.deltaTime;
       }

```

# Answer
> 1 votes
It's hard to tell exactly what the problem could be, since there must be more scripts than just those two, but Time.timeScale has probably been set to 0. Time.deltaTime is affected by the Time Scale, so you'll need to ensure that you set it back to 1 when you resume the game. If you need a deltaTime unaffected by Time Scale, you can use Time.unscaledDeltaTime

# Answer
> 0 votes
It seems like you are stopping the character when he runs out of health on the update, maybe try increasing his health at the start method?

---
Tags: unity, unityscript
---


title: Why isn't this glsl program working?

text:
# Question
Title: Why isn't this glsl program working?
Why isn't this glsl program working ?

```
#shader vertex
#version 430

layout (location = 0) in vec4 position;
layout (location = 1) in vec3 normal;
layout (location = 2) in vec2 texture_coordinate;
layout (location = 3) in vec4 color;

uniform mat4 phantom_projection_matrix;
uniform mat4 phantom_view_matrix;
uniform mat4 phantom_model_matrix;

out OUT_DATA
{
    vec4 position;
    vec3 normal;
    vec2 texture_coordinate;
    vec4 color;
} vertex_out;

void main()
{
    gl_Position = phantom_projection_matrix * phantom_view_matrix * phantom_model_matrix * position;

    vertex_out.position             = position;
    vertex_out.normal               = normal;
    vertex_out.texture_coordinate   = texture_coordinate;
    vertex_out.color                = color;
};

#shader geometry
#version 430

layout (points) in;
layout (points, max_vertices = 1) out;

in IN_DATA
{
    vec4 position;
    vec3 normal;
    vec2 texture_coordinate;
    vec4 color;
} geometry_in[];

out OUT_DATA
{
    vec4 position;
    vec3 normal;
    vec2 texture_coordinate;
    vec4 color;
} geometry_out;

void main()
{
    gl_Position = gl_in[i].gl_Position;
    EmitVertex();
    EndPrimitive();

    geometry_out.position               = geometry_in[0].position;
    geometry_out.normal                 = geometry_in[0].normal;
    geometry_out.texture_coordinate     = geometry_in[0].texture_coordinate;
    geometry_out.color                  = geometry_in[0].color;
}

#shader fragment
#version 430

layout (location = 0) out vec4 color;

in IN_DATA
{
    vec4 position;
    vec3 normal;
    vec2 texture_coordinate;
    vec4 color;
} geometry_in;

void main()
{
    color = vec4(1.0f, 0.0f, 0.0f, 1.0f);
}

#shader tesselation_control
#shader tesselation_evaluation

```

# Answer
```
gl_Position = gl_in[i].glPosition;

```

The variable i is not specified anywhere, as you're using points as input it has to be of value 0 or you can just use 0 instead (as the Input array is of size 1).
> 1 votes

---
Tags: opengl, c++, architecture, glsl
---


# Question
Title: DirectX 12 using Visual studio 2015 on Windows 7 SP1
I'm trying to work with a directx 12 sample using windows 10 sdk, visual studio 2015, on windows 7 SP1. I get the following error

The procedure entry point CreateFile2 could not be located in the dynamic link library Kernel32.dll

# Answer
According to Microsoft itself the latest DirectX version supported on Windows 7 SP1 is "DX11.1". Even on Windows 8 you don't have access to DX12. I guess that's what causing the problem. No matter what, you won't be able to develop a DX12 app on any version of windows beside Win10.
> 5 votes

---
Tags: c++, directx, directx12
---


title: Deferred shadow mapping

text:
# Question
Title: Deferred shadow mapping
Question:

**What am i doing wrong in the CalcShadowFactor method?** It looks like the depth check is not working correctly.

Body:

I'm using deferred rendering in my engine and i have generated the following shadow map:

Which is draw by the following fragment:

```
void main()
{
    gl_FragColor = vec4(texture(gColorMap, TexCoord0).x);

}

```

The position texture is generated like this:

```
WorldPos0      = (gWorld * vec4(Position, 1.0)).xyz;

```

Where gWorld is the transformation of the object being draw(translation * rotation\* scale)

Finally, in the light pass, i want to generate the shadow produced from this spotlight with the following code:

```
float CalcShadowFactor(vec3 WorldPos)
{
    vec4 ShadowCoord = gLightWVP  * vec4(WorldPos,1);
    ShadowCoord /= ShadowCoord.w;
    vec2 UVCoords;
    UVCoords.x = 0.5 * ShadowCoord.x + 0.5;
    UVCoords.y = 0.5 * ShadowCoord.y + 0.5;
    float z = 0.5 * ShadowCoord.z + 0.5;
    float Depth = texture(gShadowMap, UVCoords).x;
    if (Depth < z + 0.00001)
        return 0;
    else
        return 1.0;
}

```

It returns a float which multiplicates the color output. I know, im just returning 0 to set the color to complete transparent, it is intensional. The variables used were:

* gLightWVP: It is the ProjectionView of the camare set at the light:

Projection * LightCameraRotation * LightCameraTranslation
* WorldPos: It is the position got from the Position Texture:

vec3 WorldPos = texture2D( gPositionMap, TextCoord0 ).xyz;
* gShadowMap: It is the shadow map texture sampler.

This is what is displayed(notice how the spotlight looks at the first image):

The engine passes are:

* Shadow pass: Render the scene for every light using a alternative camera which is placed in their position with their orientation. It generates the shadow maps for every light. Currently i just have one shadow map for that spot light.
* Render pass: It renders all the scene using the main camera. It generates the position map, normal map, diffuse map and a specular map.
* Light pass: It uses all the textures generated to place the illumination. Here is where the shadow map is being checked for generate the shadows.

EDIT: I'll also leave here the shadow map texture definition.

```
glGenTextures(1, &m_shadowMap);
glBindTexture(GL_TEXTURE_2D, m_shadowMap);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, WindowWidth, WindowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

glBindFramebuffer(GL_FRAMEBUFFER, m_fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_shadowMap, 0);

```

# Answer
Normally the 0.5 bias should have been included in the matrix (so I don't think it should be after the division by w) so this shouldn't appear:

```
UVCoords.x = 0.5 * ShadowCoord.x + 0.5;
UVCoords.y = 0.5 * ShadowCoord.y + 0.5;
float z = 0.5 * ShadowCoord.z + 0.5;

```

So instead you should do something like

```
gLightMWPBiased = gLightMWP *
(
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.5, 0.5, 0.5, 1.0
);

```

And use glLightMWPBiased.

Shadow mapping is tricky so there might be other problems, but that's all I saw.
> 2 votes

---
Tags: opengl, c++, shadow-mapping, deferred-rendering
---


# Question
Title: 3D model gets partially invisible when large, Vuforia and Unity
I'd appreciate if someone could advise on my problem.

I use one on-device image target and a single 3D model. I use Unity extension and then export the scene to Android project. I also use Extended tracking.

My 3D model is looking fine when it's small, see Screenshot1.png.

But if I try to make my 3D model larger by increasing the scale, and when I move camera far from the target, the model gets partially invisible, see Screenshot2.png.

I tried to reposition my ARCamera but no luck.

# Answer
I am guessing you are working within Unity? If I am guessing right then please check your Main Camera's Distance option on where it does cut off, this is one of the main reasons of this problem.

Also can you give more information on your model? Are the texture maps baked? Is the lighting dynamic?
> 1 votes

# Answer
So, the solution was quite simple, I needed to change Clipping Planes of Camera (child of ARCamera) by increasing `Far` property.
> -1 votes

---
Tags: unity, android, 3d, augmented-reality, vuforia
---


# Question
Title: 3DS Max MassFX -- Animation to XNA without bones/skins?
I made a model in which a number of cobble stones fall into a hole using the rigid bodies in 3DS Max 2012 MassFX. They are just editable polys, no skin, no bone. I want this to play (Take 001, 0-100 frames) when the game loads the mesh. I haven't found a way to get to the animation though.

Does anyone have suggestions? All the tutorials for animated skinned models don't seem to work with a model set up like this? Do I really need to give each of 145 rocks a bone? If so, does anyone have a suggestion how to streamline that, or if there is an alternate solution to achieving this effect? The animation only needs to play once when the game starts, and that's it.

Thanks.

# Answer
XNA does not support animations out of the box, to get animations in you need to write your own code, such as the skinned sample they provide. Changing that sample to instead load a number of FBX files and changing between them with morphing is quite possible, its used in some games and demos to do facial animations since it provides the artist with more finegrained controls.

There are drawbacks of course, the animation will take more memory since it needs to store the entire model 100 times (for your 100frame example above) instead of just the changes in terms of bone animations. But as long as you use it sparingly it shouldn't be too bad.

The first step is to export the scene into a suitable format (FBX), you need to do this once per frame (or once per keyframe, the further apart they are the higher the chance that the morphing will look bad). I don't know how to do this in 3DS Max but hopefully it has a batch mode for exporting or some scripting API you could use for this.

Secondly you need to write a processor that loads and combines all the FBX files, a quick search gave this post as a possible example, in this case it has a flaw about multiple different textures but its a starting point.

Thirdly you need to animate the result, I would recomend looking at this CPU Gem chapter which is about facial morphing.

As you can see, it isn't entirely straightforward to do, in the end it might be simpler to simply rig your animation, but morph targets can be a very nice technique for good looking facial animations (in particular) so the time spent researching this won't be wasted.
> 1 votes

# Answer
If I recall this is what you are looking for.

I haven't used it in a long time but it does rigid animation, test scene is of a box that falls and opens and does not use bones just plays the track back for you.

You will have to play with you model but it should work once u get it setup(30mins-1hr)
> -1 votes

---
Tags: xna, 3dsmax
---


# Question
Title: Game Design: Colour units per team or per unit type?
In an RTS game where the units are viewed from the top so that they appear relatively small on the screen:

What would be the best game design?

1. Colour the units per team, for example: enemy is always red, player's units is always blue
2. Colour the units per ability, for example: the "destroyer" is always red, the "collector" is always green, the "interceptor" is always blue, etc. This will only work with the assumption that the teams would never have the same units and that there are only a small number of different types of units per game.
3. A combination of 1 & 2 so that the enemy is always represented by warm colours and the friendly units with cold colours. Different unit types are represented by different shades of a colour.

If I choose (1) I am concerned that the player might get confused which unit is which and for example try to attack with the wrong unit type.

If I choose (2) I am concerned that the player might be overwhelmed with too many colours and will not be able to easily tell the enemy from the friendly units.

If I choose (3) I am concerned that it might confuse the players: e.g. say the "destroyer" was light red (enemy) in one game and the next game the player switches sides so that the "destroyer" turns light blue (friendly), the player might not recognize the unit as a "destroyer".

# Answer
> 3 votes
Use colours for team identification and shapes and sizes for individual unit type differentiation. This means enemies and friendlies are instantly distinguishable, and unit types look distinct whilst having a degree of consistency from team to team.

*e.g red triangle is an angry enemy beserker, blue square is a happy allied collector.*

# Answer
> 3 votes
Humans are usually far better at spotting something of a different color than something of a different shape. Here is an example of an image with some blue pentagons:  Among them is a red pentagon and a blue square. Which one do you spot first?

In most RTS games it is usually far more important to be able to tell what faction something belongs to than what type it is. Therefor you should use colors to mark factions and shape for unit type.

However, keep in mind that about 8% of all men and 0.5% of all women have some form of color blindness and might have difficulty to tell colors apart which look completely different for you. There are different forms of color blindness which appear in different severities, so there is no general guideline what color combinations to avoid. As a workaround you can offer an options menu which allows the player to customize the colors used by the game. This will allow most colorblind players to configure a set of colors which works for them.

---
Tags: game-design, color, rts, ui-design
---


# Question
Title: Placing sprites properly to form an object
I'm working with XNA in Visual Studio, and I'm trying to draw this sprite: https://i.stack.imgur.com/nHvN6.png

Only using this sprite: https://i.stack.imgur.com/xub5q.png

My current attempt relies on a matrix boolean, which then gets drawn in a foreach loop:

```
//Variable
 bool[,] centerPiece = new bool[,] { { false, true, false }, { true, true, true }, { false, true, false } };

//Loop
 foreach (bool b in centerPiece)
            {
                if (b == true)
                {
                    spriteBatch.Draw(squareTex, screenView(), null, Color.White, 0f, IMGCenter(), 1f, SpriteEffects.None, 0f);
                }
            }

```

While this draws all 5 squares, it doesn't place them as desired (because of they're all being drawn in the screenView() method placement(The center of the screen):

```
public Vector2 screenView()
        {
            Viewport viewport = GraphicsDevice.Viewport;
            Vector2 screenCenter = new Vector2(viewport.Width / 2f, viewport.Height / 2f);
            return screenCenter;
        }

```

How do I modify my loop to place the squares correctly, and/or do I need to change my implementation completely to achieve my desired goal?

Note: I need to both be able to access the object as a whole, and also access each individual square, in each individual object.

# Answer
This data representation of your game is fine:

```
//Variable
 bool[,] centerPiece = new bool[,] { { false, true, false }, { true, true, true }, { false, true, false } };

```

The next bit of code you supplied is being run during your Draw phase of your update loop. Here you are using a foreach loop. This is bad as it will generate a lot of garbage. You are going to want to use a for loop instead.

This will also provides you with the x,y coordinate of the data you are attempting to draw. You can then use this to provide the offset when drawing your square:

```
float Spacing = 1f;     //Do you need to adjust the spacing?

//Loop through your data
for (int x = 0; x < centerPiece.GetLength(0); x++) {
    for (int y = 0; y < centerPiece.GetLength(1); y++) {

        if (centerPiece[x,y] == true) {

            //Determine the position you will be drawing this square
            Vector2 offset = new Vector2(x,y) * Spacing;
            Vector2 position = IMGCenter() + offset;

            spriteBatch.Draw(squareTex, screenView(), null, Color.White, 0f, position, 1f, SpriteEffects.None, 0f);
        }
    }
}

```

You could take it a step further, and create a Tile class that you initialize. You could then specify its position, size, color, etc.. Then instead of a boolean array, you would create a Tile object array, which would already have everything pre-calculated and ready to go.

You would then create a Draw() and Update() method for this Tile class.
> 0 votes

---
Tags: c#, xna, visual-studio
---


# Question
Title: Creating a static background when using camera transforms in Allegro 5
How can I draw a static bitmap for the background of an Allegro 5 graphics window, if I'm using camera transformations to apply perspective to bitmaps in front of the background so it appears that they're otherwise in a 3D space?

If I try simply drawing a bitmap to the backbuffer without any transforms applied, and then call al\_use\_transform on a perspective transform when drawing the other objects, the "background" moves along with the transform.

# Answer
What you describe should work. One common mistake is forgetting to reset the transform each time you draw the background.

You probably want something like this in your draw loop:

```
void draw() {
    ALLEGRO_TRANSFORM trans;
    al_identity_transform(&trans);
    al_use_transform(&trans);
    al_draw_bitmap(background, 0, 0, 0)

    al_translate_transform(&trans, 20, 20);
    al_use_transform(&trans);
    al_draw_bitmap(foreground, 0, 0, 0)
}

```

If you forget to apply the identity transformation before drawing the background, it will continue using whatever you set with the previous call to `al_use_transform`.
> 2 votes

---
Tags: allegro
---


# Question
Title: What are some legal concerns I should have before consulting a web developer on an idea of mine
I have an idea for a web application but I am a little bit hesitant to consult a company due to fears of having my idea stolen.

What are some preliminary tasks I should set myself before actually consulting a company representative?

My main concerns are strictly legal-related. What measures should I take to make sure that the company does not steal any of my ideas with regards to the application's features, design, name, etc.

# Answer
You don't need to be afraid that your game idea gets stolen, because game ideas just by themselves are worthless.

1. Nobody can tell if an idea is good without seeing it implemented in a game. There are lots of ideas which sound really great in your head. Some of them might even still sound great to someone else when you describe them. But when someone tries to implement them, it turns out they aren't actually fun or are infeasible to implement (*cough*). People in the game industry know that, so before you have a playable prototype which demonstrates your idea is worth stealing, nobody will steal it.
2. Sharing your idea helps you refine it. People will tell you their opinion, what they think won't work, and what would be cool to add to it. The earlier you can get feedback the better.
3. Everyone in the game industry has their head full of ideas and would rather work on their own ideas than those of someone else. So they aren't even interested in stealing your ideas.
4. Even if someone steals your idea and beats you to market, that's actually good for you. No game idea goes to market fully developed. You can look at that game and observe how your idea works out in practice. You can see what works and what doesn't, what mistakes they made and what useful additions they added. You can learn from them and use that experience to create an even better implementation of your idea. When you are finished, the players of the first game will be bored by it and will be looking for a new game to play which is similar but better: Yours!

But if you want to protect your idea nevertheless, you can have your prospective business partners sign a non-disclosure agreement. How to write legal texts is out of the scope of this website, so you might want to ask on Law.SE for details. Keep in mind that forcing people to sign a paper which might get them sued one day will drive some people away.
> 1 votes

---
Tags: legal
---


# Question
Title: How do I create a closed beta on Google Play?
As per suggestion I'm splitting How do I create a closed beta on the App Store? up.

Can I upload the game I'm developing to Google Play as a closed beta, so I could generate a couple of keys/tokens for my testers? I'm hoping to only publish the game for the public after I'm happy with the game as it's offered on Google Play, as a complete user experience which includes the installation process.

If this is not the usual workflow, how should I do it?

# Answer
> 6 votes
1. Sign in to your Google Play Developer Console.
2. Select an app.
3. On the left menu, select APK \> Beta testing.
4. If you see *Choose a testing method*, select the drop-down arrow.
5. Select *Set up Closed Beta Testing* \> *Create list*.
6. Type a name to identify your list of testers

... ?. PROFIT

This way only invited people will be able to install and test your game :3

link: https://support.google.com/googleplay/android-developer/answer/3131213?hl=en

---
Tags: google-play, playtesting, beta
---


title: How to Draw 2D Shapes in DirectX

text:
# Question
Title: How to Draw 2D Shapes in DirectX
I am currently trying to **draw a simple 2D circle and an arc in DirectX** but there are no resources online with info on how I can do this. Lines & Points are built into DirectX anyway so that has never been a problem.

Can somebody explain how I can do this? I'm not talking about a sphere or any other 3D geometry. **Just a simple 2D Circle and Arc.**

# Answer
You need to approximate these shapes with triangles. Assembling a circle from triangles can be done like the following pseudo-code:

```
list<Vector2> vertices;
float radius = 10;
vertices.Add(Vector2(0,0)) // center point
for (float i = 0; i <= 100; i += 1.0f)
{
    float t = PI * 2 * i / 100;
    vertices.Add(Vector2(radius * cos(t), radius * -sin(t)));
}

```

Then you can draw these vertices with a triangle fan primitive topology.
> 1 votes

# Answer
You could draw a quad and use a pixel shader to fill the circle/arc.
> 0 votes

---
Tags: 2d, directx
---


# Question
Title: Camera not working in a Game Maker mod I am creating
I wrote an object, in Game Maker. My problem is that the camera appears to be nonexistent. It does not follow the player, and from the perspective it displays on the screen, I believe I simply do not have a camera.

---

### This is my Step event:

```
right = keyboard_check(vk_right);
left = keyboard_check(vk_left);
forward = keyboard_check(vk_up);
back = keyboard_check(vk_down);

if (jump==0 && keyboard_check(vk_space))
{
    sound_play(snd_jump);
    x += 3 * unitZ_x;
    y += 3 * unitZ_y;
    z += 3 * unitZ_z;
    jump = 1;
    canjump = 4;
}

canjump -= 0.5;
x += unitZ_x * canjump;
y += unitZ_y * canjump;
z += unitZ_z * canjump;

if (canjump < -8)
{
    canjump = -8;
    falling = 1;
}

currentRadius = sqrt((x - centerX) * (x - centerX)
        + (y - centerY) * (y - centerY) + (z - centerZ) * (z - centerZ));

if (currentRadius < radius)
{
    x -= (currentRadius - radius) * unitZ_x;
    y -= (currentRadius - radius) * unitZ_y;
    z -= (currentRadius - radius) * unitZ_z;
    currentRadius = sqrt((x - centerX) * (x - centerX)
            + (y - centerY) * (y - centerY) + (z - centerZ) * (z - centerZ));
    jump = 0;
    falling = 0;
    canjump = 0;
}

if ((right==1) || (left==1))
{
    x += (right - left) * 4 * unitX_x;
    y += (right - left) * 4 * unitX_y;
    z += (right - left) * 4 * unitX_z;

    distance = sqrt((x - centerX) * (x - centerX)
            + (y - centerY) * (y - centerY) + (z - centerZ) * (z - centerZ));

    unitZ_x = (x-centerX) / distance;
    unitZ_y = (y-centerY) / distance;
    unitZ_z = (z-centerZ) / distance;

    x -= (distance - currentRadius) * unitZ_x;
    y -= (distance - currentRadius) * unitZ_y;
    z -= (distance - currentRadius) * unitZ_z;

    unitX_x = unitY_y * unitZ_z - unitY_z * unitZ_y;
    unitX_y = unitY_z * unitZ_x - unitY_x * unitZ_z;
    unitX_z = unitY_x * unitZ_y - unitY_y * unitZ_x;
}

currentRadius = sqrt((x - centerX) * (x - centerX)
        + (y - centerY) * (y - centerY) + (z - centerZ) * (z - centerZ));

if ((forward==1) || (back==1))
{
    x += (forward - back)*4*unitY_x;
    y += (forward - back)*4*unitY_y;
    z += (forward - back)*4*unitY_z;

    distance = sqrt((x - centerX) * (x - centerX)
            + (y - centerY) * (y - centerY) + (z - centerZ) * (z - centerZ));

    unitZ_x = (x - centerX) / distance;
    unitZ_y = (y - centerY) / distance;
    unitZ_z = (z - centerZ) / distance;

    x -= (distance - currentRadius) * unitZ_x;
    y -= (distance - currentRadius) * unitZ_y;
    z -= (distance - currentRadius) * unitZ_z;

    unitY_x = unitZ_y * unitX_z - unitZ_z * unitX_y;
    unitY_y = unitZ_z * unitX_x - unitZ_x * unitX_z;
    unitY_z = unitZ_x * unitX_y - unitZ_y * unitX_x;
}

```

---

### This is my Draw event:

```
  d3d_draw_ellipsoid(x - 1, y - 1, z - 1, x + 1, y + 1, z + 1, 0, 1, 1, 60);
  d3d_set_projection_perspective(0, 0, 640, 480, 0);
  d3d_set_projection(x - 4 * unitY_x, y - 4 * unitY_y, z - 4 * unitY_z, unitY_x,
          unitY_y, unitY_z, unitZ_x, unitZ_y, unitZ_z);

```

---

Does anyone know what I have done wrong? I think it is a simple 3D camera glitch, but I have never made a camera before (in anything for that matter) so chances are it is something really basic.

# Answer
> 1 votes
Your problem is that 3D objects in game maker are drawn by order of their depth, with highest depth taking priority. Each step, any view transformations (including the camera) are reset. Try making the depth a really large number (say 1000000000) and see what happens.

Also, the only other issue I see is that the second vector in d3d\_set\_projection() is supposed to be a position vector of where you are looking, not a direction vector, but I'm sure you can figure that out.

---
Tags: 3d, camera, game-maker
---


title: Spell and Terrain Interaction in Game

text:
# Question
Title: Spell and Terrain Interaction in Game
I am currently thinking about working on a small game where the player has to get rid of mob waves in an arena. The game is going to be 2D top-down.

What I want from this game is the player to be able to use the terrain and combine spells to his advantage.

Example of spell/spell interaction: if the player casts an ice wall and then the player fires a fire ball I want the fireball to disappear and the ice wall to melt into a water puddle. Then if the player sends a lightning bolt on the puddle, I want the water puddle to become electrified and affect all the mobs currently on it with some damage.

Example of spell/terrain interaction: If a player sends a fireball on a tree, I want the tree start burning (i.e dealing dmg to nearby mobs) and eventually die (i.e unable to burn anymore). If the player then sends a water jet on the tree I want the tree to be able to grow back again (and potentially be able to burn down again).

Now that you have an idea of what I want, I'll tell you what I've done so far.

I've created a Cast class which represent my spells. This class has three key attributes to govern the interactions with other spells:

1 - `attributes`: a list of which contains the properties relevant for the Cast (eg: `'flammable'` or `'conductive'`) 2 - `states`: a dictionary which contains keys which are: `'ablaze'`, `'frozen'`, `'conductive'`, `'blooming'` 3 - `col-lvl`: the collision level, to prevent things on the ground interacting with things mid-air.

for the moment I call the following function at every frame of my game, in order to update the states of each cast in the game:

```
def update_states(casts_group):

    '''make cast attribute lists'''
    flammables = []
    freezables = []
    fertiles =[]
    conductives = []
    for c in casts_group:
        if 'flammable' in c.attributes: flammables.append(c)
        if 'freezable' in c.attributes: freezables.append(c)
        if 'fetile' in c.attributes: fertiles.append(c)
        if 'conductive' in c.attributes: conductives.append(c)

    '''resolve cast states'''
    '''for flammables'''

    for f in flammables:
        for c in flammables:
            if c.col_lvl == f.col_lvl:
                if c is not f and f.states['ablaze']:
                    c.states['ablaze'] = True

        for c in freezables:
            if c.col_lvl == f.col_lvl:
                if f.states['ablaze']:
                    if c.states['frozen']:
                        c.states['frozen'] = False
                    f.states['ablaze'] = False

        for c in fertiles:
            if c.col_lvl == f.col_lvl:
                if f.states['ablaze'] and c.states['fertile']:
                    c.states['fertile'] = False

    '''for freezables'''

    for w in freezables:
        for c in freezables:
            if c.col_lvl == w.col_lvl:
                if c is not w and w.states['frozen']:
                    c.states['frozen'] = True

        for c in fertiles:
            if c.col_lvl == w.col_lvl:
                if w.states['frozen']:
                    c.states['blooming'] =  False
                elif not w.states['frozen']:
                    c.states['blooming'] = True

        for c in conductives:
            if c.col_lvl == w.col_lvl:
                if not w.states['frozen'] and c.states['conductive']:
                    w.states['conductive'] = True
                elif w.states['frozen']:
                    w.states['conductive'] = False

    '''for fertiles'''

    for f in fertiles:
        for c in fertiles:
            if f is not c and c.col_lvl == f.col_lvl:
                if f.states['blooming']:
                    c.states['blooming'] =  True

        for c in conductives:
            if c.col_lvl == f.col_lvl:
                if f.states['blooming'] and c.states['conductive']:
                    f.states['blooming'] = False

    '''for conductives'''

    for e in conductives:
        for c in conductives:
            if c.col_lvl == e.col_lvl:
                if e is not c and e.states['conductive']:
                    c.states['conductive'] =  True

```

Each cast will then have a series of method which will dictate what should happen based on which states are currently active.

**My question to you is : How can I improve this ??**

When I run the following test my computer takes 0.8 seconds to solve for about 2000 Cast. That will never hold if I want a decent FPS. I am worried because this is just one function of the game and it already uses up a lot of time. Although I don't expect to have that many casts at any one time in the game, I will have to add a similar step to deal with Terrain/Spell interactions ... and the whole remainder of the game.

Thank you for your help,

BTW if you think this is a question best suited for the CodeReview community let me know, I wasn't quite sure.

TEST:

```
setup = """
class Cast():
    def __init__(self, attr, states):
        self.attributes = attr
        self.states = states
        self.col_lvl = 0

def update_states(casts_group):
    #for c in casts_group: print c.states

    '''make cast attribute lists'''
    flammables = []
    freezables = []
    fertiles =[]
    conductives = []
    for c in casts_group:
        if 'flammable' in c.attributes: flammables.append(c)
        if 'freezable' in c.attributes: freezables.append(c)
        if 'fetile' in c.attributes: fertiles.append(c)
        if 'conductive' in c.attributes: conductives.append(c)

    '''resolve cast states'''
    '''for flammables'''

    for f in flammables:
        for c in flammables:
            if c.col_lvl == f.col_lvl:
                if c is not f and f.states['ablaze']:
                    c.states['ablaze'] = True

        for c in freezables:
            if c.col_lvl == f.col_lvl:
                if f.states['ablaze']:
                    if c.states['frozen']:
                        c.states['frozen'] = False
                    f.states['ablaze'] = False

        for c in fertiles:
            if c.col_lvl == f.col_lvl:
                if f.states['ablaze'] and c.states['fertile']:
                    c.states['fertile'] = False

    '''for freezables'''

    for w in freezables:
        for c in freezables:
            if c.col_lvl == w.col_lvl:
                if c is not w and w.states['frozen']:
                    c.states['frozen'] = True

        for c in fertiles:
            if c.col_lvl == w.col_lvl:
                if w.states['frozen']:
                    c.states['blooming'] =  False
                elif not w.states['frozen']:
                    c.states['blooming'] = True

        for c in conductives:
            if c.col_lvl == w.col_lvl:
                if not w.states['frozen'] and c.states['conductive']:
                    w.states['conductive'] = True
                elif w.states['frozen']:
                    w.states['conductive'] = False

    '''for fertiles'''

    for f in fertiles:
        for c in fertiles:
            if f is not c and c.col_lvl == f.col_lvl:
                if f.states['blooming']:
                    c.states['blooming'] =  True

        for c in conductives:
            if c.col_lvl == f.col_lvl:
                if f.states['blooming'] and c.states['conductive']:
                    f.states['blooming'] = False

    '''for conductives'''

    for e in conductives:
        for c in conductives:
            if c.col_lvl == e.col_lvl:
                if e is not c and e.states['conductive']:
                    c.states['conductive'] =  True

    #for c in casts_group: print c.states

c_group = [
Cast(['flammable'],
{'ablaze' : True,
 'frozen' :  False,
 'blooming' :  False,
 'conductive': False}),
Cast(['freezable','conductive'],
{'ablaze' : False,
 'frozen' :  True,
 'blooming' :  False,
 'conductive': False}),
Cast(['conductive'],
{'ablaze' : False,
 'frozen' :  False,
 'blooming' :  False,
 'conductive': True})]

d_group = []
for x in range(667):
    d_group += c_group

"""

test = """update_states(d_group)"""

from timeit import timeit

n = 1

print timeit(stmt = test, setup = setup, number = n)

```

# Answer
Well, this is going to depend on some definitions. So first, let me say that by my definition you have not described terrain in the classic sense of game programming. Terrain is typically the ground and other immutable objects (a lake or ocean). Things such as trees or puddles would often be props, decorations, or some other descriptor for things that are added into a scene.

Going with that definition, it's easy to consider any two objects interacting with one another. Typically, if you have a tree and a fireball is cast at it, you might set a flag on the tree to "burning", and generate a fire particle effect or something similar at the location of the tree. This also allows the tree to be extinguished in the opposite direction with a water spell or something similar, stopping the particle effect and removing the flag.

The same could go for puddles if they are spawned in as objects sitting *on* the terrain. In this way, they can be electrified in the same manner as a tree could be set ablaze, or even evaporated with a fire spell, or created with a water spell (use water to create puddles, then use chain lightning to electrify them all).

As for improving, there are a few ways to do this. Ideally, the effect of casting would be part of the spell itself, and the spell would then interact with the objects it crosses. If you cast a fireball or flame spell, and it collides with another object, if that object is flammable it sets it ablaze. Maybe this could be done with a listener on the objects, with a message sent by the fireball when it collides. Something like:

```
when (collide)
   send.message("fire") to collided

```

The spell sends a "fire" message (or "water", or "electric", or whatever) to each object it touches, and the listener on the object says "oh, I'm flammable and that was fire... poof!", or "oh, that was an electric message and I'm made of dirt... no poof!".

The benefit of this is that you aren't constantly polling all possible combinations for objects that don't match the element being presented. Plus, some objects could have multiple listeners if multiple elements can effect it. Obviously some trial and error with this would be needed, but I'd imagine you'd cut down quite a bit of processing. It might lag a frame or two being if things get hectic, but it probably wouldn't even be noticeable on draw.
> 1 votes

---
Tags: 2d, optimization, pygame
---


# Question
Title: Multiple Texture Coordinates Per Vertex (DirectX11)
The models my artists are making in maya have multiple different texture coordinates per vertex depending on what face the vertex happens to be a part of.

Originally, to fix this problem, I duplicated each vert every time it appears in a face so each vert can have its own texture coordinates / face normals. This worked out well for a while until I started working on skinned skeletal animation.

I could not seem to get skinned skeletal animation working with this duplicate vertex method. There would be serious gaps in the mesh as it animated. In order to try and fix this, I switched back to indexed drawing, where faces share verts instead of each face having its own unique copy of a vert.

This fixed my skinned animation but now I'm at a loss as how to encode the multiple texture coordinates / face normals that are associated with verts. I was hoping there might be a way to use the index buffer and an array of face normals / uvs to fix this issue. Basically, I figure I can easily add an array of normals/tex coords to each vert but I have no idea how to instruct the gpu to properly index into it.

# Answer
> 2 votes
Duplicating vertices is probably the wrong way to go for this particular use case.

If all you have is an extra set of UVs, just send in an extra set of UVs. D3D has attributes named TEXCOORD0, TEXCOORD1, ... for a reason. :)

Accessing them is just part of the shader. Bind your attributes in your shader and use different sets of UVs for your sample calls. In shader pseudo code:

```
// vertex shader
main(vert_input in) {
  out.pos = transform(in.pos);
  out.texcoord0 = in.texcoord0;
  out.texcoord1 = in.texcoord1; // pass second set of UVs through to pixel shader
}

// pixel shader
main (pixel_input in) {
  diffuse0 = sample(tex0, in.texcoord0);
  diffuse1 = sample(tex1, in.texcoord1); // sample second texture using second set of UVs
  return diffuse0 * diffuse1;
}

```

Duplicate the vertices only when core attributes need to vary. For example, if you need different normals. You mentioned different normals in your post, but odds are you *really* don't need those; it makes little sense to have different normals for different textures in the vast majority of cases. You'd only really duplicate verts with different normals on hard edges, which has nothing to do with multi-texturing.

You can require that the art uses textures which share a UV space. Needing multiple UVs is something that should be *relatively* rare outside of particular techniques. If your artists are making content that requires multiple UVs for most content, the problem *might* be that your artists are doing something questionable that you should not try to support; instead you should educate them how to achieve the same visual effect using a more efficient and less hacky method. (A joke that applies: a man walks into a doctor's office and says, "every time I bend my finger backwards it hurts!" and the doctor replies, "then stop bending your finger backwards.")

The skinning bugs you mention is unrelated to your primary question. It's just a bug. If that's your primary problem, fix your skinning code.

---
Tags: c++, textures, directx11, skeletal-animation, uv-mapping
---


title: OpenTK crashes with Mono

text:
# Question
Title: OpenTK crashes with Mono
I've implemented OpenTK as a secondary renderer which would let me support Mac/Linux only to realize that for some reason, even without any modifications (new MonoGame project), the application would make mono crash, but it runs perfectly fine on .NET.

I've been looking for some templates and demos to start with OpenTK for Mono/Mac/Linux but all I can find is Xamarin Studio guides for iOS and Android.

# Answer
> 1 votes
Although you haven't provided many specific details about the crash, **I would highly recommend using the Mono Migration Analyzer to find any problems.**

The Mono Migration Analyzer (MoMA) is a tool designed by the Mono team to test whether your program makes any unsafe calls in its source code, or calls any unimplemented functions. **The tool should list any problematic calls or lines of code which you could try replacing with a Mono-friendly equivalent.**

You can download MoMA here. It's recently become unsupported, but works well for the recent releases of Mono.

Sorry I couldn't provide a concrete answer to your question, but this is impossible to do without more details about your setup. If using MoMA does not help you, the rest of the Game Development Community and I would be happy to help you if you provided more details.

---
Tags: opengl, monogame, opentk, mono
---


title: How should I handle MMO Enemies

text:
# Question
Title: How should I handle MMO Enemies
I have some NPCS protecting a treasure room in a friendly building. But if the player comes close they turn hostile. I don't know if the NPCS should attack everyone when triggered or only attack the player that triggered them. The latter seems good but if another player could sneak behind the guards whilst they attack someone else and succeed in an easy victory. How should I tackle this issue. If I use the former a random person who didn't do anything but is peacefully looking at the situation could get attacked which isn't RP-Friendly.

By adding more NPCS it kills a main attacker faster however doesn't solve the latter.

By adding more NPCS in the room would cause problems as it is smaller than a cubicle because of the design of the room being centred on the middle but making it larger it loses it's attention.

By simply removing the guards but adding another room before the treasure room, where the guards are. This is ok to stop the first issue because not many players will enter but it will lose the curiosity of guards guarding a door but rather another door.

# Answer
In many MMOs the target selection of mobs is governed by a mechanic nicknamed *aggro management* by the players.

Each mob keeps an *aggro* score for each player. Doing damage to the mob increases that mob's *aggro* for the attacking player. The mob will always target the player with the highest *aggro*. When you implement that mechanic, you could add an aggro-bonus to each player based on their current proximity to the location the mob is supposed to protect. That means a mob which is currently fighting player A might switch to player B when B moves much closer to the protected location than A.
> 1 votes

# Answer
You could create a specific zone, where if a player goes past that zone they become priority one for the guards to attack, so if one player gets attacked and starts running away the guards will chase and attack (for a certain distance) but if another player enters that priority zone the guards immediately change course and attack him. You could make the chasing distance low and the damage the guards do high so that they don't ever go to far from the door but are still a very menacing opponent to try to get by.

Hope this helps :)
> 2 votes

---
Tags: game-design, ai, multiplayer
---


# Question
Title: How to instantiate a prefab only when something is hit, and for some seconds?
How do I instantiate a prefab only when something is hit for a few seconds? I mean, I just need to activate the particle system when something is hit. Now it always runs, even before I hit something. I need it to activate the particle system when something is hit and for 2-3 seconds.

This is what I do now:

```
public void Shot()
{
    Destroy(gameObject);
    Instantiate(effect, transform.position, transform.rotation);
}

```

# Answer
Heya :) this is pretty simple, the two ways I like to delay something is either using a coroutine or invoking a method. As for on hit if you want the particles to hit on the body where a bullet hits a person, Raycasting a shot and getting its hit.point will help you with achieving the position of the hit, if it is that u just want the particles to Emmitt at a transform, what u have is fine. As for code: Bare with me im on my phone :p

```
GameObject yourParticleSystem;

void OnCollisionEnter(Collision col)
{
    //this is for if a bullet hits the player
    if(col.gameObject.tag == "Bullet")
    {
        StartCoroutine(waitTime(3f));
    }
}

IEnumerator waitTime (float time)
{
    yield return new waitForSeconds (time);
    Instantiate(yourParticleSystem, transform.position, Quaternio.identity);
    // this instantiates your prefab at your transform and its rotation
    //if u dont have play on awake ticked in particles a simple
    yourParticleSystem.Play(); //will make it play
}

```

Because you aren't pooling your particles, you don't want to have multiple particle GameObject within the scene, if suggest either pooling ur particles or simple adding a destroy script on your particleSystem Eg:

```
void Start ()
{
    Destroy(gameObject, 4f) // 4f is just a guess to how long the particles play for
}

```

Sorry if there are some syntax errors I tried my best on the phone hehe ^.^ hope u understand and it works :)))))
> 1 votes

# Answer
As far as only triggering something when it's "hit", this is usually done via a Collider which triggers a callback when it hits something else, such as OnCollisionEnter https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter.html

For destroying after a 2-3 second delay I would add a new script to the "effect" prefab that destroys itself after waiting some time:

```
public class DestroyAfterDelay : MonoBehaviour {
    public float delay;

    IEnumerator Start() {
        yield return new WaitForSeconds( delay );
        GameObject.Destroy( gameObject );
    }
}

```
> 1 votes

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


title: Make simple hit effect

text:
# Question
Title: Make simple hit effect
I've made a game where you can shoot some cans, but I want to add an effect when a can is shot. You know, a kind of explosion or something like that. The way the game works now is: when the can is shot it disappears `destroy(gameobject)`, but I want to add an effect before it disappears. Any suggestions? I want to keep it simple. The effect has to be in within the same method where I destroy the cans.

```
   public void Shot()
{
    //Effect should be here
    Destroy(gameObject);
}

```

# Answer
For a 3D game, a simple particle effect spawned at the location of the can would be easy enough to do. For a 2D game, you could use a particle effect or a sprite animation at the point of impact. Heck, add a sound effect. Doing any of those could happen inside your Shot() function, ideally by calling a Subroutine. Just don't make the effect a child of the can, or it won't finish before the object is destroyed.
> 2 votes

# Answer
I recommend you create a prefab with a particle system(or set of them) that also has a despawn timer script attached to it. The particles can be used for an explosion. The despawn script will wait a certain amount of time or until particle systems finish and will be attached to the top-level of the prefab. If you don't know about Prefabs, I suggest you research them because they are uber useful. You can use the `Instantiate(Object theObject)` function to spawn that prefab. You can make a public GameObject field in the `MonoBehaviour` of that `Shot()` method. This would allow you to simply drag the prefab from the Asset Explorer into the properties window for that object.

I hope this helped, if unclear, ask me to fix it.
> 0 votes

# Answer
Create a particle on top of your script

```
public GameObject effect;

```

then in your function

```
public void Shot()
{
    //Effect should be here
    Instanciate(effect, transform.position, transform.rotation);
    Destroy(gameObject);
}

```

Then in the editor, create an empty gameobject containing you effect and drag it on your script.
> 0 votes

# Answer
You should have a look at this SpaceShooter Tutorial from the Unity Website. Especially the Explosions Section https://unity3d.com/de/learn/tutorials/projects/space-shooter-tutorial/explosions?playlist=17147

You might want to tweak this particle Effect to your liking

Now all you need to do is to spawn this particle Effect before your bullet gets destroyed.

Beware to make sure that you destroy your Particle Effect after it has stopped.

You could do this like so:

```
using UnityEngine;
using System.Collections;

public class DestroyAfterStopped : MonoBehaviour {

    private ParticleSystem myParticleSystem;

    // Use this for initialization
    void Start () {
        myParticleSystem = GetComponent<ParticleSystem>();
    }

    // Update is called once per frame
    void Update () {
        if(myParticleSystem.isStopped)
        {
            if (gameObject != null)
            {
                Destroy(gameObject);
            }
        }
    }
}

```

Just assign this Script to your ParticleSystem.
> 0 votes

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


# Question
Title: Clamp point to triangle for sphere collision
I'm having some issues clamping a 3d to barycentric triangle. I've searched for some time now and keep seeing the same results, that (u,v,w) should be clamped between 0 and 1. But when I clamp those values, I'm getting very weird results as it saying it's always intersecting. Maybe I'm just clamping the wrong values or what I'm doing wrong.

The issue is that I'm projecting a point on a normal from a given triangle, then testing if the point is inside the triangle, if it is, test if it's inside the sphere. Everything works great except when the sphere center is no longer above/in front of the triangle, so the spheres edge can pass through the edge of the triangle beings that the spheres center is no longer above it. Any help with how I'm supposed to clamp the position inside of the triangle would be much appreciated.

Here is a snippet of the triangle/sphere intersect method:

```
public boolean CollidesWithMesh(MeshCollider other)
{
    float sphereRadius = gameObject.scale * (bounds.Scale().Max()) / 2f;
    boolean collided = false;
    RawMesh mesh = other.gameObject.meshRenderer.mesh.rawMesh;

    for(int i = 0; i < mesh.triangles.length; i++)
    {
        //Store the verts used in the triangle
        int first = i++;
        Vector3 vert1 = mesh.vertices[(int) mesh.triangles[first]].Add(other.gameObject.position);
        Vector3 vert2 = mesh.vertices[(int) mesh.triangles[i++]].Add(other.gameObject.position);
        Vector3 vert3 = mesh.vertices[(int) mesh.triangles[i]].Add(other.gameObject.position);

        //Project a point along the normal closest to the spheres center
        Vector3 normal = mesh.normals[(int) mesh.triangles[first]];
        float dot = Vector3.Dot(normal, gameObject.position.Subtract(vert1));
        Vector3 d = normal.Multiply(dot);
        Vector3 point = gameObject.position.Subtract(d);

        //If the point is not inside the triangle, continue
        Vector3 v0 = vert3.Subtract(vert1);
        Vector3 v1 = vert2.Subtract(vert1);
        Vector3 v2 = point.Subtract(vert1);
        float dot00 = Vector3.Dot(v0, v0);
        float dot01 = Vector3.Dot(v0, v1);
        float dot02 = Vector3.Dot(v0, v2);
        float dot11 = Vector3.Dot(v1, v1);
        float dot12 = Vector3.Dot(v1, v2);
        float invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
        float u = (dot11 * dot02 - dot01 * dot12) * invDenom;
        float v = (dot00 * dot12 - dot01 * dot02) * invDenom;
        if(!((u >= 0.0) && (v >= 0.0) && (u + v <= 1))) continue;

        //If the sphere does not encapsulates the point, continue
        if(!Contains(point)) continue;

        //Respond to the collision
        Vector3 responseNormal = point.Subtract(gameObject.position).Normalized().Multiply(sphereRadius - (point.Subtract(gameObject.position)).Length());
        Vector3.Subtract(gameObject.position, responseNormal);
        if(normal.y > 0.75) isGrounded = true;
        if(normal.y < -0.75) hitCeiling = true;
        collided = true;
    }
    return collided;
}

```

# Answer
> 1 votes
Had a few things backwards. After a couple days of research and toying with the code I finally got it working. Here is the finished method:

```
public boolean CollidesWithMesh(MeshCollider other)
{
    float sphereRadius = gameObject.scale * (bounds.Scale().Max()) / 2f;
    boolean collided = false;
    RawMesh mesh = other.gameObject.meshRenderer.mesh.rawMesh;

    for(int i = 0; i < mesh.triangles.length; i++)
    {

        //Store the verts used in the triangle
        int first = i++;
        Vector3 normal = mesh.normals[(int) mesh.triangles[first]];
        Vector3 vert1 = mesh.vertices[(int) mesh.triangles[first]].Add(other.gameObject.position);
        Vector3 vert2 = mesh.vertices[(int) mesh.triangles[i++]].Add(other.gameObject.position);
        Vector3 vert3 = mesh.vertices[(int) mesh.triangles[i]].Add(other.gameObject.position);

        //Calculate and clamp the barycentric coordinates
        Vector3 v21 = vert2.Subtract(vert1);
        Vector3 v31 = vert3.Subtract(vert1);
        Vector3 v1 = gameObject.position.Subtract(vert1);
        float dot00 = Vector3.Dot(v21, v21);
        float dot01 = Vector3.Dot(v21, v31);
        float dot11 = Vector3.Dot(v31, v31);
        float dot20 = Vector3.Dot(v1, v21);
        float dot21 = Vector3.Dot(v1, v31);
        float denom = dot00 * dot11 - dot01 * dot01;
        float v = (dot11 * dot20 - dot01 * dot21) / denom;
        float w = (dot00 * dot21 - dot01 * dot20) / denom;
        float u = 1.0f - v - w;
        if(u < 0)
        {
            Vector3 v32 = vert3.Subtract(vert2);
            float t = Vector3.Dot(gameObject.position.Subtract(vert2), v32) / (Vector3.Dot(v32, v32));
            t = Mathf.Clamp(t, 0, 1);
            u = 0.0f; v = 1.0f - t; w = t;
        }
        else if(v < 0)
        {
            Vector3 v13 = vert1.Subtract(vert3);
            float t = Vector3.Dot(gameObject.position.Subtract(vert3), v13) / (Vector3.Dot(v13, v13));
            t = Mathf.Clamp(t, 0, 1);
            u = t; v = 0.0f; w = 1.0f - t;
        }
        else if(w < 0)
        {
            float t = dot20 / dot00;
            t = Mathf.Clamp(t, 0, 1);
            u = 1.0f - t; v = t; w = 0.0f;
        }

        //Convert the barycentric coordinates to world space
        Vector3 point = new Vector3((u * vert1.x) + (v * vert2.x) + (w * vert3.x), (u * vert1.y) + (v * vert2.y) + (w * vert3.y), (u * vert1.z) + (v * vert2.z) + (w * vert3.z));

        //If the sphere does not encapsulates the point, continue
        if(!Contains(point)) continue;

        //Respond to the collision
        Vector3 responseNormal = point.Subtract(gameObject.position).Normalized().Multiply(sphereRadius - (point.Subtract(gameObject.position)).Length());
        Vector3.Subtract(gameObject.position, responseNormal);
        if(normal.y > 0.75) isGrounded = true;
        if(normal.y < -0.75) hitCeiling = true;
        collided = true;

    }
    return collided;
}

```

---
Tags: vector, intersection, bounding-spheres, barycentric-coordinates
---