# Question
Title: Have a method accept generic methods for a in-game console
I'm making a console, like in Half-Life so that the devs can add their commands.

I'm making this in Unity's C#.

I have a problem when dealing with the commands. When you want to add a commands, you create a class Command and add it through a method to the Console List of Commands.

The code of the class Command is the following one:

```
public class Command
    {
        /// <summary>The string by which this command will be called</summary>
        public string commandKey;
        /// <summary>The information of this command that the help option will show</summary>
        public string helpInfo;

        public delegate string stringVoid();
        public delegate string stringString(string consoleInput);
        public delegate void voidCmd();
        public delegate void voidString(string consoleInput);

        public stringVoid _stringVoid;
        public stringString _stringString;
        public voidCmd _voidCmd;
        public voidString _voidString;

        public Command(string commandInput, string helpTooltip)
        {
            commandKey = commandInput;
            helpInfo = helpTooltip;
        }

        #region Add Command Methods
        public Command addVoidCommand(voidCmd voidCommand)
        {
            _voidCmd = voidCommand;
            return this;
        }
        public Command addStringVoid(stringVoid stringVoidCmd)
        {
            _stringVoid = stringVoidCmd;
            return this;
        }

        public Command addStringString(stringString stringStringCmd)
        {
            _stringString = stringStringCmd;
            return this;
        }

        public Command addVoidString(voidString voidStringCmd)
        {
            _voidString = voidStringCmd;
            return this;
        }
        #endregion
    }

```

## As you can see users can add four types of delegates methods:

* Void methods with no parameters.
* String methods with no parameters.
* Void methods with a string parameter.
* String method with a string parameter.

This makes the class very heavy, and makes the users have to navigate through a lot of options to add a class.

I want to have some way to add methods without having to go through so many options, and, from my side, taking out the need of searching through so many options when a command is called from console.

You can find the whole script/project here.

In conclusion, I want to have a way that the user simply write

```
// way I want it to work
new Command("commandName", "this is an example" ExampleCommand);
new Command("commandString", "this is another example" ExampleString);

void ExampleCommand(){ }
string ExamplesString(string ble){ return ble + "bla"; }

// way it currently works
new Command("commandName", "this is an example").addVoidCommand(ExampleCommand);
new Command("commandString", "this is another example").addStringString(ExampleString);

```

To simplify everything. Is any way I can achieve this with delegates, Unity Actions or something else?

Thank you very much.

# Answer
> 4 votes
The way I implemented this myself might not be perfect or the most C# solution (since I use C++) but it works pretty well for me and even provides some additional features.

So, in this solution all your console command callbacks would have the same signature: `void ConsoleCommand(List<string> arguments);`. Now as you can see, all the parameters are passed into the command as a list of strings, and that is indeed the downside of this approach: the command needs to do its own argument parsing, and convert the data it gets into correct datatypes and so on. This can be quite error prone.

However, there's also a small benefit into doing this: optional parameters. Let's take a console command that spawns in an enemy for an example. The user would type in `/spawnEnemy 100 200` and the console command would spawn the enemy at the given coords. But here comes the trick: if the user types in just `/spawnEnemy` instead, the command could decide to perhaps use the mouse cursor's position for an example.

```
void SpawnEnemy(List<string> arguments)
{
    if (arguments.Size == 2)
    {
        ActualSpawnEnemy(arguments[0].ToInt(), arguments[1].ToInt());
    }
    else if (arguments.Size == 0)
    {
        ActualSpawnEnemy(Mouse.X, Mouse.Y);
    }
    else
    {
        // Display something to the user.
    }
}

void ActualSpawnEnemy(int x, int y)
{
    ...
}

```

# Answer
> 2 votes
Use a Delegate:
Change your constructor to something like this:

```
public Command(string commandInput, string helpTooltip, Delegate invoker)

```

Now the constructor callers have to look like this:

```
new Command("commandName", "this is an example", (Action)ExampleCommand);
new Command("commandString", "this is another example", (Func<string, string>)ExamplesString);

```

The invoker `Delegate` has a method named `DynamicInvoke` which takes an array of arguments (if any) and returns an object with the return value (or null if the method return type is Void).

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


# Question
Title: How OpenGL works with Windows GDI in order to produce output image on computer screen?
I am curious how GDI integrates with OpengGL in order to create image for computer screen.

I know that GDI provide Device Context which describes window properties and as far as I know it also offer 2D software based rendering.

Then based on Device Context, Rendering Context is created for OpenGL.

During rendering OpenGL maintain framebuffer objects which are stored in GPU memory and those buffers are then pushed to the screen somehow? However what is the role in GDI in this process? I know that GDI is responsible for transferring image to the graphics devices... So does it mean that framebuffer contents are transferred to CPU RAM and then again to GPU in order to transfer it to display?! It doesn't sound logic...

Why such a software based drawing component (GDI) is used with OpenGL which should be able to send image straight from framebuffer (GPU memory) to display? I can't understand that...

How Windows UI is rendered? Desktop, folders, Start Menu etc. it is software based or gpu based rendering?

# Answer
The video adapter sends to the monitor a video buffer stored somewhere in video memory. This is something the adapter does, and it is responsibility of the device driver.

*I am talking about a single monitor for simplicity. In the case of multiple monitor, each one will have a video buffer associated with it, and Windows needs to keep track of their relative position to know what parts of each Window is on each monitor.*

What Windows actually puts into the buffer that is send to the monitor needs to be composed from the images of the multiple windows that are to appear on the screen. It is responsibility of Windows to manage those windows so it will know what window will draw where (that is to handle position, size, z-order).

Now, to draw on a given window, there is the GDI API, which allows you to access a buffer dedicated to store the image of a particular window of your application, and do graphic operations on it (such as drawing bitmaps, lines, etc.). Most of these operations happen on CPU.

Windows has to take the images in the buffers of the windows to construct the image that the video adapter will send to the monitor. Modern Windows uses GPU for this process.

However, you do not want to use GDI to draw images, instead you want to use OpenGL. Well, you need a buffer that OpenGL can access, and you need to associate it to the window, so Windows knows where to put it.

How do you get the buffer for the window? You request it via GDI. However, GDI does not give you a naked pointer to the buffer; it gives you a pointer to a structure that has the relevant information for GDI - that we call the Device Context Handle (hDC). That is NOT useful for OpenGL! OpenGL need its own structure, so call a function to create an object that OpenGL understands from the hDC, that object is the Rendering Context.

Note: it is also possible to get an hDC to render directly on a monitor, bypassing the composition step, and use that.

Now that you can tell OpenGL to render to that context, the output from OpenGL will end up in the buffer associated to your window. In addition, from there Windows can take the image and compose it into the result presented to the user.
> 3 votes

---
Tags: opengl, rendering, windows, image, winapi
---


# Question
Title: What is the best approach for networking a basic HTML5 pong game?
I'm working on the design of a basic multiplayer HTML5 pong game, and I have a very basic question about architecture.

The implied physics is very basic, and the movements are not a problem. The players will be connected to the server via sockets, and the refresh rate is controlled in order to make things run smoother. My problem is with the ball movement. Where should I put the ball logic?

* If I run logic on the client sides, the balls may be desynchronized.
* If I run all the logic on one client side, acting as a host, this could work; but I don't know if this is a good practice.
* I could run the logic on the server side, but I think that I will replicate all the physics and rules for the game that I can have with a simple javascript framework for game development.

What is the best approach, here?

# Answer
> 1 votes
You should never make calculations of game mechanics on the client side. Just expect that there will be a hackers on the client side changing your code.

You should store the model data in the server and use it on the client side to draw the view.

# Answer
> 0 votes
I suggets to start with all logic on server for first. User press button - client send command "move", server moves, and send updates for both players.

Will be a bit laggy, maybe. Just a bit.

After that you can make vizualization on client immediate (before server confirm this movement). So user getting key-press feedback immediately. (But keep in mind - server always right, even with a bit late, so you need to sync pad after server response).

And after that you can tweak server a bit on ping-compensation. As your ball movements relatively predictible, your pad react immediatly (visually) and you know ping/delay value - you can dive into math and calculate ping compensation to correct objects positions on your table.

# Answer
> 0 votes
Lag the clients behind the server by x ms with the drawing of things and have the server do the movement of the ball and send the position every x ms to the clients. The clients should store a queue of the positions it's getting from the server which will be choppy if you just set those, but because you have a queue and you're lagging behind the server you can interpolate between the current position to the next position on the queue. This will give you nice smooth and accurate ball position controlled from the server.

You also want to store a rolling list on the server side of these positions that were sent so you have a small amount of history. You'll want this because the clients are lagging behind so when you get paddle movement commands at a point in time you then "rewind" the ball by looking at the history ball position list for the time you get the clients paddle movement minus the ping (the time it took you to get that movement). Then you can validate if a collision happened or not and the server ultimately controls the ball.

At the point of a collision because the ball is lagged behind on the client, on the server the ball may have went passed where the paddle is thought to be on the server. So when a collision from the rewind happens, you'll want to re-position the ball on the server at the collision point and run the physics from there which will reverse it's position. You might want to send that collision point to the users as well even if it's outside your interval of sending ball position because you'll want that specific point for them.

But this way the server controls all physics of the ball an the clients are all just lagged behind but they are none the wiser of that.

The side note of this is that how you tell if the ball actually did get passed a paddle. You'll just have to make that check happen farther away from the paddle based on how fast the ball can move and your update interval. In other words the server needs to consider the lag behind in ms the clients are doing when telling if a ball really got by a paddle.

Side note, this is how the Source engine works. When you shoot on your side that command is sent to the server and it knows how long it took to get there (ping). Let's say the server gets it at tick 500 and it took 50ms to get the command. It knows the clients are lagging behind by 150ms (this is a hardcoded value that the server decides on at the start) so it knows to look at (now - 150 - 50) in the history list of game states on the server. It'll find the closest snapshot and interpolate from there to get positions/rotations of everything in the game at that point which should have been what YOU saw at that point, and then runs the raycast on the shoot to tell if there was a hit or not. Same concept here really. The only difference is you having to snap the ball to the collision point if the server deems one took place.

# Answer
> -3 votes
What you can do is since it is a multi player games best for two player, you can create a group for two and then synchronize the movement on both the side. Ex: Since same Javascript file (Client Side) runs on both the machines, once two person joins the game, you initiate the game (movement of ball). I think no random calculations where made.

---
Tags: javascript, architecture, networking, html5
---


title: Different Activities for every level?

text:
# Question
Title: Different Activities for every level?
So I've got a simple game with different levels. For the most part the levels use the same code, with only slightly different things. Do i have to make a new Activity for every level? The app will have a 'level select' screen. Is there a way to tell one activity to run a certain set of java based on what level I selected? Any suggestions would be appreciated.

# Answer
> 0 votes
I've figured it out.

On the level picking activity, basically have an Intent that can send information to the activity that actually runs the game. Based on what level is selected, you can set it to change a string to whatever level it is. The gameplay activity will get the information from the level selection activity and use it to choose which "game" (lines of code) to run. For example:

```
if  (level.getString("level", "").equals("1")) {
                        //change aspect of game like time or the score: each of those
                        would be a Double
                    }
if  (level.getString("level", "").equals("2")) {
                        //change the time or score to be harder than the level before.

```

# Answer
> 0 votes
Perhaps activities can inherit from different "gameplay" classes using a common interface? Multiple inheritance could be useful here. Then you assign an activity to a level and get the gameplay.

---
Tags: java, android, level-design, levels
---


# Question
Title: How to import texture from Maya to unity?
I am trying to export a model from Maya with animation but when I import into unity I am getting the model but the texture is not there. From the internet I found that while importing the model I need to enable media that also does not work for me.Is there any way that I can import Material texture in fbx file

# Answer
As far as I know, you can't directly encode the texture(s) into the fbx file itself.

So, you can export the fbx normally (without enable media) and import that into Unity.

Then, import the texture(s) into Unity and for the model's material, change its Albedo texture to the texture of the model.

If the model has multiple textures for different parts of it (hands, legs, etc.) then you have to assign each part a different material with a different Albedo texture.
> 1 votes

---
Tags: unity, textures, maya, export
---


title: How to change the position of a dialog?

text:
# Question
Title: How to change the position of a dialog?
I have created a dialog in Libgdx main menu screen.

I have tried

```
dialog.setPosition(300, 300);
dialog.show(stage);

```

It doesn't do anything. Is it a camera trick? Am I missing something?

# Answer
Just in case some people encounter the same issue :

---

Libgdx javadoc says dialog is centered by default with show method.

Do :

```
dialog.setPosition(300, 300);
stage.addActor(dialog);

```

Instead of `dialog.show`to let the dialog use these positions instead of default ones computed by show method.
> 3 votes

# Answer
You could use the `show` method:

```
dialog.show(stage, sequence(Actions.alpha(0), Actions.fadeIn(0.4f, Interpolation.fade)));
dialog.setPosition(position.x, position.y);

```

According to the source code, the general `show` method just auto-sets the position to the center. By using this method, you could pass the auto-set center.
> 0 votes

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


# Question
Title: Which approach to use when simulating a button press in a cockpit?
As the picture shows, I wish to press a button when I am flying the plane. I'm writing the program in DirectX 12 and C++, without a game engine. I am new to this, so I don't know which approach to use to simulate the button press. Should I use a skeleton and make an animation binding to the bone, or just program the button position in code?

# Answer
> 1 votes
Skeletal animation is great for organic 3d models, because skeletal animation systems can simulate squeezing and stretching of parts of the 3d mesh. This means that when a joint of a living being moves, the skin and cloth doesn't retract into the body, it stretches just like it would for a real being.

But for objects which are supposed to look mechanical, skeletal animation is usually overkill and/or doesn't give you the effect you want it to have. I would recommend you to make each button/switch/knob an own 3d object and implement the animations by simply translating/rotating them.

If you later would like to add a pilot's hand which presses the buttons, it might be worth thinking about implementing a skeletal animation system for it.

# Answer
> 1 votes
The simplest solution is to make the buttons independent models.

Merging the meshes and sending the state of individual buttons to the GPU is an optimization to be left for when you need it. When you get to that point, that optimization can take many forms, only one of which is skeletal animation. Another one would be dynamic batching.

# Answer
> 0 votes
There would be unnecessary complexity involved in setting up a skeletal mesh only for this.

All you need to do is set a new position for the various vertices of the button, in code; the easiest way to do this may be to treat the button as a submesh, or a wholly separate mesh, when the flight console is being constructed in e.g. Max, Blender or Maya. You can then shift the origin in code, and all the button's vertices will shift with it.

---
Tags: 3d-meshes
---


# Question
Title: Should I sync animations from the server to the client or let the client play its own animations?
For example, if the user presses the "Fire" button which leads to the player character doing some kind of animation, should the client evaluate itself if it can play the animation or wait for a response from the server telling it that it's ok to play the animation?

# Answer
> 1 votes
If you're going with the authoritative server model (to limit player cheating), you want to simulate everything immediately on the client. Otherwise, there will be latency, so the player could press fire, and 200ms later see the animation, which would be a poor experience.

When the server sends back updates, the client must rewind to the state last processed by the server, then replay any local inputs not yet processed by the server to appear responsive.

See this tutorial series: http://www.gabrielgambetta.com/fpm1.html

---
Tags: networking, client-server, synchronization
---


# Question
Title: Java Thread.sleep() VS Get last and current time
I am creating a simple game using Java. I'm not using any game library. I just want to know if it is okay to call `Thread.sleep(40)` before calling `repaint()`.

```
public void run() {
    while(isGameRunning) {
        try {
            Thread.sleep(40);
            repaint();
        }
        catch(Exception e) {
        }
    }
}

```

or should I use:

```
private long last_time = System.nanoTime();
private double ns = 1000000000/25D;
private double delta = 0;
@Override
public void run() {
    while(Universe.IsGameRunning) {
        long time  = System.nanoTime();
        delta += (int)(time - last_time)/ns;
        last_time = time;
        System.out.println(delta);
        if(delta>=1) {
            repaint();
            delta--;
        }
    }
}

```

The code below has more CPU and RAM usage than the first one. Can you explain to me how 'Delta Timing' actually works?

# Answer
> 1 votes
Delta timing is almost always the better choice.

The idea behind it is that it gives you the exact number of milliseconds since the last frame computation cycle completed.

Let's say it only takes 10ms to compute the frame.

In your first example, you specify a 40m/s delay. This means, that 30ms for each frame will be spent doing nothing, and at *best*, you will get 25 fps (1000/40).

In your second example, you are computing the frame, then *immediately* starting again. This means that, as it only took 10ms to compute your frame, you are actually getting 100 frames per second. This will be 4 times as smooth when it comes to animation, and will ensure that no cpu time is wasted.

I will add that with smaller, more discrete timesteps between frames, collision detection becomes more accurate, and less likely to allow objects to tunnel through each other.

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


# Question
Title: Unity - How can I make my player's gun point at the cursor, not the player itself?
I'm making a 2D top-down shooter in unity. Currently, I'm using the code below to point my player towards my cursor at all times, this works but isn't exactly what I want.

```
//Find the mouse position on the camera view
Vector3 mousePoint = theCamera.ScreenToWorldPoint(Input.mousePosition);

//Find how the mouse relates to the object's position
Vector3 difference = mousePoint - transform.position;
difference.Normalize();

//Find wanted angle of rotation
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
Quaternion newRotation = Quaternion.Euler(new Vector3(0.0f, 0.0f, rotZ + adjustmentAngle));

//Apply wanted angle of rotation
transform.rotation = Quaternion.Lerp(transform.rotation, newRotation, Time.deltaTime * smoothing);

```

While this works, my player's gun isn't in the centre of my player so when the gun fires it actually skims past the cursor missing slightly.

How can I get my player to rotate so his gun is what points towards the cursor rather than himself? I have a child `GameObject` at the end of the barrel of his gun used to `Raycast` and stuff which I figure can be used?

# Answer
> 0 votes
I don't believe the answer here is to make the gun point towards the cursor, but to make the gun **fire** towards the cursor. So keep your current rotation mechanism and instead make your `GameObject` fire towards the cursor.

If this looks weird (like your character is shooting really wonky) you should probably rotate the weapon to accommodate for this change. IMO it looks better than having your character look to the side of an enemy almost like he's looking into the distance.

---
Tags: unity, c#, rotation, shooter
---


# Question
Title: Compute "up" and "right" from a direction
I have a camera class that is missing some functionality.

I need to give it the ability to, given a direction, or a point to look at, will rotate the camera left/right and up/down to look at this point or along this direction, without causing gimbal lock.

lets, say I move the camera to (10,10,10).

I want the camera to point at (0,0,0).

By normalizing the vector , I find that the direction I want to look along is (-0.577,-0.577,-0.577). We'll call this "Forward".

What I want to be able to do, is compute the local "Up" and "Right" vectors which are perpendicular to Forward.

How do I do this?

# Answer
First, keep in mind that you need some other piece of information. A direction by itself has no intrinsic "up" direction. You'll typically have some kind of global "up" defined by your game, usually `(0,+1,0)` or the like.

From this, you can use cross products to calculate the "right" vector (or "left" vector, depending on handedness in use). The cross product of your *normalized* forward/view vector and the normalized world up vector gives you the right vector.

From there, you can now calculate the view's "up" vector, by taking the cross product of the right vector and the normalized forward/view vector.
> 4 votes

---
Tags: mathematics, camera, vector
---


# Question
Title: JAVA: How do I use BufferedImage to properly render a PNG with Transparency?
I've been around the internet for about 5 hours and found no solution to my issue, so hopefully someone will help me. So' I've been trying to make a simple game. In previous oportunities I've used JLabel to render my sprites (Player, enemies, misc) but that takes a lot of single files just to make simple animations, so I decided to use spritesheets, which have served me right on C++ (SFML) before. Tried to use JLabels also to achieve this, but with no success, aparently there's no way to select a single tile on the sheet properly, BUT transparency works just fine. Searching aroud the web I found out that there's Graphics2D API, so I decided to give it a shot, using BufferedImage (as many have recommended), but this is where it all went to hell.

This is my actual sheet:

You can see it is actually transparent, I used BufferedImage and getSubimage(...) to render it on screen, but all I get is this:

This is my code:

```
public class GameScreen extends Screen
{
    private JFrame gameFrame;
    private BufferedImage background;
    private BufferedImage charSprite = null;
    private BufferedImage enemySprite;
    private BufferedImage spellSprite;
    private Character character;
    private Enemy enemy;

public GameScreen(JFrame mainFrame)
{
    initComponents();
    this.setBounds(0, 0, 500, 500);
    this.setVisible(true);
    mainFrame.getContentPane().add(this);
    gameFrame = mainFrame;
}

@Override
public void refresh()
{

}

@Override
public void paint(Graphics g)
{
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D)g;
    g2d.drawImage(background, 0, 0, null);
    g.fillRect(0, 0, 320, 320);
    g2d.drawImage(charSprite.getSubimage(0, 0, 60, 60), 60, 60, null);
}

public void initComponents()
{
    try
    {

        URL url = this.getClass().getResource("/images/char_sheet.png");
        charSprite = ImageIO.read(url);
        url = this.getClass().getResource("/images/arena.png");
        background = ImageIO.read(url);
        url = this.getClass().getResource("/images/enemy.png");
        enemySprite = ImageIO.read(url);
        url = this.getClass().getResource("/images/projectile.png");
        spellSprite = ImageIO.read(url);
    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(gameFrame, "Fatal Error\n" + e.toString() + "\n" + e.getLocalizedMessage(),
                "Warning", JOptionPane.ERROR_MESSAGE);
        System.exit(0);
    }
}

```

}

It's a simple class, that extends an interface which (for now) only has the refresh() method, I decided to have the rendering and updating in that single class, for this is just a practice. Can you spot what I'm doing wrong? Or have ane advice or tips? It would be highly appreciated, I've been freaking about about this for the last minutes. Thanks in advance.

EDIT: Forgot to mention something, the screen class implements JPanel, to work as a Canvas.

# Answer
> 0 votes
Very strangely, it appears that your picture *is not transparent*.

I copied your code, and tried it with your image, and the background was white. Then I tried it with a png I found on my computer and it *did* work. So I put your picture into photoshop, and there it was – a white background.

Here's a transparent version if you need :

# Answer
> 0 votes
You need to call the method `setOpaque(false)`, because by default a JPanel is ***not*** set transparent, it is set to opaque=true and thats the problem. I just solved mine with this method call.

```
JPanel panel = new JPanel();
//now if you want your panel to be transparent you just call this method
panel.setOpaque(false); //be sure to check if it's a png file else it won't work no matter what u do in your code

```

---
Tags: java, transparency, png
---


# Question
Title: Unity 5 - Moving canvas elements smoothly
So I am making a game menu in unity 5 for a school assignment. I am trying to smoothly move an image on the canvas using lerp. The canvas is on **world space render mode** because I also want to make a flying camera when clicking a button.

I have 5 buttons and when hovering over one of them, the image should move to that button smoothly (with a lerp). Every button has a script on it called "ButtonScript"

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

public class ButtonScript : MonoBehaviour
{
    [SerializeField]
    private AudioSource m_audioSource;
    [SerializeField]
    private Image m_buttonImage;

    private RectTransform m_rectTransform;

    private string m_buttonName;

    private Vector3[] m_buttonEffectPositions;
    private Vector3 m_currentButtonEffectPosition;

    void Start()
    {
        m_audioSource = GetComponent<AudioSource>();
        m_buttonName = gameObject.name;
        m_rectTransform = m_buttonImage.GetComponent<RectTransform>();

        m_buttonEffectPositions = new Vector3[6];

        m_buttonEffectPositions[0] = new Vector3(-741, 21, 0);
        m_buttonEffectPositions[1] = new Vector3(-741, -60, 0);
        m_buttonEffectPositions[2] = new Vector3(-741, -137, 0);
        m_buttonEffectPositions[3] = new Vector3(-741, -216, 0);
        m_buttonEffectPositions[4] = new Vector3(-741, -297, 0);
        m_buttonEffectPositions[5] = new Vector3(-1300, -252, 0);
    }

    void Update()
    {
        m_rectTransform.position = Vector3.Lerp(m_rectTransform.position, m_currentButtonEffectPosition, 0.1f);
    }

    public void SetButtonEffectPosition()
    {
        switch (m_buttonName)
        {
            case "NewGame":
                m_currentButtonEffectPosition = m_buttonEffectPositions[0];
                m_audioSource.Play();
                break;
            case "LoadGame":
                m_currentButtonEffectPosition = m_buttonEffectPositions[1];
                m_audioSource.Play();
                break;
            case "Options":
                m_currentButtonEffectPosition = m_buttonEffectPositions[2];
                m_audioSource.Play();
                break;
            case "Credits":
                m_currentButtonEffectPosition = m_buttonEffectPositions[3];
                m_audioSource.Play();
                break;
            case "Exit":
                m_currentButtonEffectPosition = m_buttonEffectPositions[4];
                m_audioSource.Play();
                break;
        }
    }

    public void RemoveButtonEffect()
    {
        m_currentButtonEffectPosition = m_buttonEffectPositions[5];
    }

    public void ChangeOptionsCamera()
    {

    }
}

```

Every button has a PointerEnter function which calls the SetButtonEffectPosition function.

The problem is that the RectTransform coördinates of the image don't match the coördinates in the code. They jump to ridiculous values like -7000.

I couldn't find much documentation on this subject as the canvas is rather new to unity.

If there is any information missing that is required to help me with my question please let me know :)

To the person that suggested this as a duplicate thread, it is not because in that thread the OP has his canvas on screen overlay render mode and I have mine on world space render mode which seems to be different to me.

Any help would be appreciated!

# Answer
The easiest way to achieve things like this is to use `Tweening` and the most popular lib is: http://dotween.demigiant.com/

Then, you do something like:

```
using DG.Tweening;

public void Start(){ // or onClick, or whatever you want
    objectToMove.transform.DoMove(target.transform.position, 2f)
        .SetEase(Ease.Linear).SetDelay(1f);
}

```

`DoMove()` parameters are: the target position and the time to move

`SetEase()` sets your desired intepolation (there are alot of them)

`SetDelay()` sets the start delay to one second.

There are hundreds of methods in the documentation: http://dotween.demigiant.com/documentation.php

Hope this helps!
> 1 votes

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


# Question
Title: Entity Component System - How to implement an object's Transform?
In designing an entity-component system for my engine, I've come across a little snag in the way of storing and retrieving a particular type of component.

First, let me set clear up a bit of terminology I'm going to use in this question:

* I call "**Component**" a data structure that stores relevant data for a particular system.
* I call "**System**" an aggregation of methods and data structures that makes use of Components to update game state/interface with the user.
* An "**Entity**" is basically just an ID used to retrieve specific components and modify their data in game logic.

Each system owns an (ID-mapped) array of its type of Component (E.g Physics-\>PhysicsComponent, AI-\>AIComponent, Rendering-\>RenderingComponent), so that it can iterate efficiently over data.

Not all components are specifically owned by a system, however. For example, a Transform component stores an object's position, rotation and scale. It's one of the most important parts of an entity (Unity makes it mandatory, even), since it is used by a lot of systems, e.g. Physics, AI, Rendering etc.

This is pretty much the problem I'm facing. Since Transform is used by a lot of other systems, how should I go about retrieving one to use for each Component? One possible solution I see is to make each Component store its own Entity ID. It would be easy to retrieve any component like this, but it wouldn't be that efficient, and it also would go against the concept of a Component as an isolated and independent bundle of data, that isn't aware of any other.

Is there a proper way to solve this problem? Should Transform even be a component?

# Answer
> 2 votes
This is quite a broad question, the answer to which, strongly depends on your architecture. However, I will attempt to give you a general answer.

Your physics and rendering systems will certainly require the transform, however, the AI system will not. Therefore, it makes sense to encapsulate the transform into it's own component class. All such interested systems would use the same data, therefore, it makes sense for the entity to have a pointer to the transform object, or an id for a transform object stored elsewhere.

If you choose the latter solution, then each system that is interested in a transform will require access to wherever the transform object is stored.

If you choose the former, then all each system needs to do is access the entity itself, and request the transform.

In the former case, the problem becomes how to grant access to the storage for transforms to each system, without breaking OOP rules, if you care about such things.

The latter case has no such issues, but requires changing your entity object design to store pointers to objects rather than ids of component objects.

My personal preference is to design the entity class to store pointers to component objects, as it simplifies many design issues. In this way, each system which requires a transform can request it from the entity, and ignore it if it doesn't. However, this does carry a computational overhead inherent to pointers, that being the cost of cache misses.

Have a look at this ECS Overview for more information on this.

At the end of the day, It's up to you to decide which is more important to you: ease of development, or performance.

I would point out, finally, that your question is an excellent example of the design questions that ECS proponents think about, and there is no definitive silver bullet solution.

---
Tags: entity-system
---


# Question
Title: How to make this Flock behaviour work in Java?
I'm having trouble implementing Flock Behaviour. What I expect is that the boids should move towards the mouse coordinate but they dont.

Thanks in advance.

```
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.JPanel;

public class MainPanel extends JPanel implements Runnable, MouseMotionListener{
    private Target mouse;
    private List<Boid> boids;
    int delay = 20;
    private int width = 900, height = 900;
    Thread thread;

    public MainPanel() {
        setPreferredSize(new Dimension(width, height));
        setBackground(Color.BLACK);
        setFocusable(true);
        addMouseMotionListener(this);
        thread = new Thread(this);
        mouse = new Target(20, 40);;

        boids = new ArrayList<>();

        boids.add(new Boid(320, 30, this));
        boids.add(new Boid(330, 80, this));
        boids.add(new Boid(360, 130, this));
        boids.add(new Boid(420, 20, this));
        boids.add(new Boid(390, 30, this));

        thread.start();
    }

    @Override
    public void run() {
        while (true) {
            mouse.update();

            for (Boid b : boids) {
                b.run();
            }

            repaint();

            try {
                thread.sleep(delay);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        mouse.paint(g2d);

        for (Boid b : boids) {
            b.paint(g2d);
        }

        g2d.setColor(Color.GREEN);
        String s1 = "MX: %8.2f         MY: %8.2f";
        String s2 = "CX: %8.2f         CY: %8.2f";
        g2d.drawString(String.format(s1, mouse.getX(), mouse.getY()), 10, 20);
    }

    public List<Boid> getBoids() {
        return boids;
    }

    public double getTargetX() {
        return mouse.getX();
    }
    public double getTargetY() {
        return mouse.getY();
    }

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

    @Override
    public void mouseMoved(MouseEvent e) {
        mouse.setPos(e.getX(), e.getY());
    }
}

-----------------------------------------------------------

import java.awt.Color;
import java.awt.Graphics;
import java.util.List;

public class Boid {
    private double x, y;
    private double accX, accY; // acceleration
    private double vx, vy; // velocity
    private MainPanel panel;
    double maxSpeed = 16;
    //double maxForce = 3;
    double mass = 2;
    double weightingFactor = 5. / 6;
    int r = 40;

    // separation
    double sepX;
    double sepY;

    // alignment
    double aliX;
    double aliY;

    // cohesion
    double cohX;
    double cohY;

    // seek
    double seeX;
    double seeY;

    public Boid(double x, double y, MainPanel panel) {
        // current coordinate
        this.x = x;
        this.y = y;

        // acceleration
        accX = 0;
        accY = 0;

        // velocity
        vx = 3;
        vy = 3;

        sepX = 0;
        sepY = 0;
        aliX = 0;
        aliY = 0;
        cohX = 0;
        cohY = 0;
        seeX = 0;
        seeY = 0;

        this.panel = panel;
    }

    public void run() {
        flock();
        update();
    }

    private void update() {
        // update velocity
        //vx = vx + accX;
        //vy = vy + accY;

        // limit speed
        //vx = Math.min(vx, maxSpeed);
        //vy = Math.min(vy, maxSpeed);

        x = x + vx;
        y = y + vy;

        // reset acceleration to 0 each cycle
        accX = 0;
        accY = 0;
    }

    private void flock() {
        seek();

        List<Boid> boids = panel.getBoids();
        // accumulate a new acceleration each time based on three rules
        separete(boids);
        align(boids);
        cohesion(boids);

        // arbitrarily weight these forces
        sepX = sepX * 1.5;
        sepY = sepY * 1.5;

        aliX = aliX * 1;
        aliY = aliY * 1;

        cohX = cohX * 1;
        cohY = cohY * 1;

        // add the force vectors to acceleration
        // We could add mass here if we want A = F / M

        accX = seeX + sepX + aliX + cohX;
        accY = seeY + sepY + aliY + cohY;
        vx = accX;
        vy = accY;
    }

    // Checks for nearby boids and steers away
    private void separete(List<Boid> boids) {
        double desiredseparation = 25.0f;
        double steeringX = 0;
        double steeringY = 0;
        int count = 0;

        // For every boid in the system, check if it's too close
        double ed = 0;
        double dx = 0;
        double dy = 0;
        for (Boid other : boids) {
            dx = other.getX() - x;
            dy = other.getY() - y;
            ed = Math.sqrt(dx * dx + dy * dy);
            if (ed > 0 && ed < desiredseparation) {
                // calculate vector pointing away from neighbour
                double diffX = other.getX() - x;
                double diffY = other.getY() - y;

                // normalise
                diffX = diffX / ed;
                diffY = diffY / ed;

                // weight by distance
                diffX = diffX / ed;
                diffY = diffY / ed;

                steeringX = steeringX + diffX;
                steeringY = steeringY + diffY;
                count++; // count how many
            }
        }

        // average -- ??
        if (count > 0) {
            steeringX = steeringX / count;
            steeringY = steeringY / count;
        }

        ed = Math.sqrt(steeringX * steeringX + steeringY * steeringY);
        if (ed > 0) {
            double desiredVX = steeringX / ed * maxSpeed;
            double desiredVY = steeringY / ed * maxSpeed;

            double steeringVX = desiredVX - vx;
            double steeringVY = desiredVY - vy;

            double tvx = ((vx * weightingFactor) + (steeringVX * (1 - weightingFactor) / mass));
            double tvy = ((vy * weightingFactor) + (steeringVY * (1 - weightingFactor) / mass));
            double tve = Math.sqrt(tvx * tvx + tvy * tvy);
            double tvlen = Math.min(tve, maxSpeed);
            vx = tvx / tve * tvlen;
            vy = tvy / tve * tvlen;

            sepX = vx;
            sepY = vy;
        }

        sepX = steeringX;
        sepY = steeringY;
    }

    //Calculate the average velocity for every nearby boid
    private void align(List<Boid> boids) {
        double neighborDistance = 50;
        double sumX = 0;
        double sumY = 0;
        int count = 0;

        double ed = 0;
        double dx = 0;
        double dy = 0;
        for (Boid other : boids) {
            dx = other.getX() - x;
            dy = other.getY() - y;
            ed = Math.sqrt(dx * dx + dy * dy);
            if (ed > 0 && ed < neighborDistance) {
                sumX = sumX + other.getVX();
                sumY = sumY + other.getVY();
                count++;
            }
        }

        if (count > 0) {
            sumX = sumX / count;
            sumY = sumY / count;
            ed = Math.sqrt(sumX * sumX + sumY * sumY);

            double desiredVX = sumX / ed * maxSpeed;
            double desiredVY = sumY / ed * maxSpeed;

            double steeringVX = desiredVX - vx;
            double steeringVY = desiredVY - vy;

            double tvx = ((vx * weightingFactor) + (steeringVX * (1 - weightingFactor) / mass));
            double tvy = ((vy * weightingFactor) + (steeringVY * (1 - weightingFactor) / mass));
            double tve = Math.sqrt(tvx * tvx + tvy * tvy);
            double tvlen = Math.min(tve, maxSpeed);
            vx = tvx / tve * tvlen;
            vy = tvy / tve * tvlen;

            aliX = vx;
            aliY = vy;
        } else {
            aliX = 0;
            aliY = 0;
        }
    }

    // Calculate steering vector towards that position for the average position (i.e. center) of all nearby boids
    private void cohesion(List<Boid> boids) {
        double neighborDistance = 50;
        double sumX = 0;
        double sumY = 0;
        int count = 0;

        double ed = 0;
        double dx = 0;
        double dy = 0;
        for (Boid other : boids) {
            dx = other.getX() - x;
            dy = other.getY() - y;
            ed = Math.sqrt(dx * dx + dy * dy);
            if (ed > 0 && ed < neighborDistance) {
                sumX = sumX + other.getVX();
                sumY = sumY + other.getVY();
                count++;
            }
        }

        if (count > 0) {
            sumX = sumX / count;
            sumY = sumY / count;
            seek(sumX, sumY);
        } else {
            cohX = 0;
            cohY = 0;
        }
    }

    private void seek(double tx, double ty) {
        double dx = tx - x;
        double dy = ty - y;
        double ed = Math.sqrt(dx * dx + dy * dy); // distance to the target
        if (ed > 0) {
            double desiredVX = dx / ed * maxSpeed;
            double desiredVY = dy / ed * maxSpeed;
            // double steeringVX = desiredVX + vx;
            // double steeringVY = desiredVY + vy;
            double steeringVX = desiredVX - vx;
            double steeringVY = desiredVY - vy;

            double v = Math.sqrt(steeringVX * steeringVX + steeringVY * steeringVY);
            if (v != 0.0) {
                // truncate with max speed
                steeringVX = steeringVX / v * Math.min(v, maxSpeed);
                steeringVY = steeringVY / v * Math.min(v, maxSpeed);
            }

            double tvx = ((vx * weightingFactor) + (steeringVX * (1 - weightingFactor) / mass));
            double tvy = ((vy * weightingFactor) + (steeringVY * (1 - weightingFactor) / mass));
            double tve = Math.sqrt(tvx * tvx + tvy * tvy);
            double tvlen = Math.min(tve, maxSpeed);
            vx = tvx / tve * tvlen;
            vy = tvy / tve * tvlen;

            cohX = vx;
            cohY = vy;
        }
    }

    private void seek() {
        double dx = panel.getTargetX() - x;
        double dy = panel.getTargetY() - y;
        double ed = Math.sqrt(dx * dx + dy * dy); // distance to the target
        if (ed > 0) {
            double desiredVX = dx / ed * maxSpeed;
            double desiredVY = dy / ed * maxSpeed;
            // double steeringVX = desiredVX + vx;
            // double steeringVY = desiredVY + vy;
            double steeringVX = desiredVX - seeX;
            double steeringVY = desiredVY - seeY;

            double v = Math.sqrt(steeringVX * steeringVX + steeringVY * steeringVY);
            if (v != 0.0) {
                // truncate with max speed
                steeringVX = steeringVX / v * Math.min(v, maxSpeed);
                steeringVY = steeringVY / v * Math.min(v, maxSpeed);
            }

            double tvx = ((seeX * weightingFactor) + (steeringVX * (1 - weightingFactor) / mass));
            double tvy = ((seeY * weightingFactor) + (steeringVY * (1 - weightingFactor) / mass));
            double tve = Math.sqrt(tvx * tvx + tvy * tvy);
            double tvlen = Math.min(tve, maxSpeed);
            seeX = tvx / tve * tvlen;
            seeY = tvy / tve * tvlen;
        }
    }

    public void paint(Graphics g) {
        g.setColor(Color.YELLOW);
        g.fillRect((int) (x + .5), (int) (y + .5), 20, 20);
        g.setColor(Color.RED);
        g.drawOval((int)x - r / 2, (int)y - r / 2, r, r);
    }

    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }

    // Get velocity
    public double getVX() {
        return vx;
    }

    public double getVY() {
        return vy;
    }
}

-----------------------------------------------------------

import java.awt.Color;
import java.awt.Graphics;

public class Target {
    private int x, y, vx, vy, r;

    public Target(int x, int y) {
        this.x = x;
        this.y = y;
        r = 100;
    }

    public void setPos(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public void update() {
    }

    public void stop() {
        vx = 0;
        vy = 0;
    }

    public void paint(Graphics g) {
        g.setColor(Color.BLUE);
        g.fillRect(x, y, 10, 10);
        g.setColor(Color.RED);
        g.drawOval(x - r / 2, y - r / 2, r, r);
    }

    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }
}

-----------------------------------------------------------

import java.awt.Container;

import javax.swing.JFrame;

public class Test extends JFrame {
    public Test() {
        Container container = getContentPane();
        container.add(new MainPanel());
        pack();
    }

    public static void main(String[] args) {
        Test gameFrame = new Test();
        gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gameFrame.setVisible(true);
    }
}

```

# Answer
I believe the problem is that the boids do not know where the mouse is. I searched your source for calls to `getTargetX` or `getTargetY` and didn't find any.

The standard boids algorithm doesn't use a target. I believe you can modify your implementation to include one by adding another influence in `Boids.run` that draws the boid toward the mouse position.

Something along these lines would make sense to me:

Add a function to find the target position. This can start out as a copy of `seek`. Instead of taking in parameters `tx` and `ty` it will read them from the panel, and instead of saving results to `cohX` and `cohY` it will save them to two new members.

Call this new function from `flock`, and then add the values of new members to `accX` and `accY`.
> 1 votes

---
Tags: java, path-finding
---


# Question
Title: GLSL "varying" interpolation: component-wise? Reference in the spec?
Probably a dumb question, but I can't find (or am not understanding) a conclusive answer in the spec or in other questions (e.g., this one).

For smoothly-interpolated varying `vec` and `mat` vertex shader outputs / fragment shader inputs, is each element of the vector or matrix interpolated individually?

GL spec sec. 13.5.1 (clipping) describes linear clip-space interpolation of the "output values associated with a vertex." It also says that those are componentwise for vectors, but doesn't mention matrices.

Similarly, sec. 14.5.1 (rasterizing lines) and sec 14.6 (rasterizing polygons) describe interpolation of an "associated datum *f* for the fragment". Is each element of a vector or matrix considered an individual "associated datum" and interpolated independently from the other elements of the vector or matrix?

Secs. 11.1.3.10 (shader outputs) and 15.1 (fragment shader variables) mention interpolation but refer elsewhere for the details.

Similarly, in the GLSL spec, sec. 4.5 (interpolation qualifiers) says that interpolation happens but does not distinguish scalars from multi-component variables.

I am looking for a definitive statement about how `vec`s and `mat`s are interpolated, if there is one. Or let me know if there isn't! Thank you!

(Note: answers can be for any OpenGL version.)

# Answer
> 4 votes
**TL;DR:** Yes, it is component-wise.

---

As you said, GLSL specifications have formulas for computing *"datum associated with a fragment"*, like this one:

**GLSL 330 spec : 3.5.1 Basic Line Segment Rasterization**

> The value of an associated datum `*f*` for the fragment, whether it be a varying shader output or the clip `*w*` coordinate, is found as
>
> ```
>      (1 ― *t**f<sub>a</sub>*/*w<sub>a</sub>* + *t·f<sub>b</sub>*/*w<sub>b</sub>*
> *f* = ――――――――――――――――――――――――                                (3.6)
>        (1 ― *t*)/*w<sub>a</sub>* + *t*/*w<sub>b</sub>*
> ```
> where `*f<sub>a</sub>*` and `*f<sub>b</sub>*` are the data associated with the starting and ending endpoints of the segment, respectively; `*w<sub>a</sub>*` and `*w<sub>b</sub>*` are the clip `*w*` coordinates of the starting and ending endpoints of the segments, respectively.

It may be not entirely clear if *"datum"* means an entire vector/matrix or separate components, but the point is that it doesn't matter, because multiplication and divison between a scalar and a vector/matrix are defined component-wise.

---
Tags: opengl, shaders, glsl, interpolation, standards
---


# Question
Title: Why is my sprite leaving copies as it moves in Monogame?
I am pretty new to Monogame, and I'm trying to draw a character sprite and move it using keyboard. Instead of moving to different positions, it leaves a track of copies along the way.

I have 2 game states; one is the menu, and the other one is the level, where the sprite is called to draw.

Why is my sprite leaving copies as it moves in Monogame?

---

**Player.cs**

```
class Player : Entity
{
    private float velocity;
    private int hp;
    public Texture2D texture;
    public Rectangle hitbox;
    public Vector2 pos;
    KeyboardState oldState;

    public void Init(ContentManager content)
    {
        texture = content.Load<Texture2D>("char");
        hitbox.Width = texture.Width;
        hitbox.Height = texture.Height;
        velocity = 150f;
        pos.X = 100;
        pos.Y = 100;
    }

    public void Update(float delta)
    {
        KeyboardState newState = Keyboard.GetState();

        if (newState.IsKeyDown(Keys.D))
            pos.X += 100 * delta;
        if (newState.IsKeyDown(Keys.A))
            pos.X -= 100 * delta;

        oldState = newState;
    }

    public void Draw(SpriteBatch sb)
    {
        sb.Begin();
        sb.Draw(texture, pos, Color.White);
        sb.End();
    }
}

```

---

**Level1.cs**

```
class Level1 : State
{
    private Texture2D background;
    public Player player;

    public void Init(ContentManager content)
    {
        //background = content.Load<Texture2D>("Level1/bg");
        player = new Player();
        player.Init(content);
    }

    public void Update(float delta)
    {
        player.Update(delta);
    }

    public void Draw(SpriteBatch sb, GraphicsDeviceManager graphics)
    {
        player.Draw(sb);
    }
}

```

---

**Game1.cs**

```
public class Game1 : Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    State CurrentState;
    KeyboardState oldState;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    void SetState(State state)
    {
        GraphicsDevice.Clear(Color.White);
        CurrentState = state;
        CurrentState.Init(Content);
    }

    protected override void Initialize()
    {
        SetState(new MenuState());
        graphics.PreferredBackBufferWidth = 1920;
        graphics.PreferredBackBufferHeight = 1080;
        graphics.IsFullScreen = true;
        graphics.ApplyChanges();
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
    }

    protected override void Update(GameTime gameTime)
    {
        KeyboardState newState = Keyboard.GetState();

        var delta = (float)gameTime.ElapsedGameTime.TotalSeconds;

        CurrentState.Update(delta);

        if (CurrentState is MenuState && (newState.IsKeyDown(Keys.F)
            && oldState.IsKeyUp(Keys.F)))
        {
            SetState(new Level1());
        }

        if (CurrentState is MenuState && (newState.IsKeyDown(Keys.Escape)
            && oldState.IsKeyUp(Keys.Escape)))
        {
            this.Exit();
        }

        if (CurrentState is Level1 && (newState.IsKeyDown(Keys.Escape)
            && oldState.IsKeyUp(Keys.Escape)))
        {
            this.Exit();
        }

        base.Update(gameTime);
        oldState = newState;
    }

    protected override void Draw(GameTime gameTime)
    {
        CurrentState.Draw(spriteBatch, graphics);
    }
}

```

# Answer
> 2 votes
You want to call `GraphicsDevice.Clear(Color.White);` before rendering the state.

---
Tags: xna, 2d, sprites, monogame
---


# Question
Title: Why would one have "waves" in each stage of a tower defense game?
For example, in Plants vs Zombies, the zombies come in waves. If I recall, there's always at least two waves. The first and easier wave and then when you get 90% through the stage there's a "final wave" which is shorter, harder, and has a bunch of zombies all come at once.

My question is, why would a game decide to announce when you change from one wave to the next? They could have just let the level progress from start to finish without this if they wanted to.

Does this make the game more fun for some reason? Where can I learn more about this technique (eg: does it have a name)?

# Answer
> 8 votes
From my experience with the game (Plants vs Zombies) I would say it's a design decision to make the game more accessible, smoother learning curve and a more engaging experience.

Each level (as far as I remember) introduces new weapons, playing techniques and unsurprisingly new zombies, my take on this:

* The designers intended to let you learn and understand how the new techniques work before introducing a harder wave of zombies. This will let you feel more in control of the game, other than splashing tons of enemies and weapons in your face and let you figure it out. The very opposite of what Dark/Demon Souls do, which is one of the reasons why they are considered "hard", they simply let you figure it out.
* This will let the player be prepared physiologically for the next wave, this is not only about learning the game. **But also about being engaged**. For example a lot of games will give you those hints about a Big enemy coming next (hints: could be music, sound effects, or level design) this will always make you want to see what is coming next, and play more!
* It gives the player a feel of progress.
* This might not be the best thing a hardcore gamer wants in a game. But given the game's success, I would say it was the right decision. At least for the intended more casual audience.

# Answer
> 3 votes
There are a few reasons I can think of. I'll answer this based on the tower defense genre and not just Plants vs Zombies (which of course copied the basic TD formula).

* Setup - Players need time to buy and place new towers. Some tower defense games stop towers from shooting while they upgrade, making the wave break indispensible for tactics. If the player's tower setup is not working for this level's enemies, the small time between waves allows for selling and building of different towers.
* Bonus - Many TD's enable the player to send upcoming waves early. There is generally a bonus for doing so, whether immediate or not. For example as money during the level or just extra points after winning. This would encourage the player to develop a strategy that allows them to send more waves early, further adding to the fun and replayability.

Also, the super wave at the end is something many (if not most) other TD's do as well. It's like any other game that has a boss at the end of the level. You'd better be prepared for it or the rest of the level was all for naught!

# Answer
> 3 votes
In Plants vs. Zombies the game spawns zombies continuously throughout the stage while also having two big waves per level: one at the half way point and one grand finale.

To me, the biggest reason for these big waves is to provide dynamic peaks and troughs in the gameplay. Peaks produce an emotional response that boosts the player's adrenaline and give them the sense they are overcoming a big challenge. "Troughs", or the lulls in between waves, give the player time to mentally relax before the next big wave. This peak/trough dynamic is a lot more exciting and engaging that just a steady, uniform, or slowly increasing spawn rate.

# Answer
> 2 votes
I think the reasons for this are of a much simpler nature: letting the player know how much longer they need to survive and allowing them to react accordingly. For example you know that the next wave is the last wave which will be harder than the previous ones so you pay extra attention towards improving your defenses.

Unless you are making a horror game it is never good to leave the player in the dark about what awaits him. Else it can be a source of frustration, and frustration is not good. The player might think the game is unfair and stop playing it.

# Answer
> 1 votes
Also bunching up enemies distributes the damage your towers are dealing differently. If the enemies are spawning at a fixed rate, there is no accumulation of enemy groups that create interesting gameplay events. If everyone moves at a fixed rate, the level is very predictable. After you've seen the first two enemies get destroyed - you already know you've won and the level will feel repetitive.

If you bunch up the enemies into groups (and with different speeds) then the zombie who takes damage from your towers keeps changing while they move - in effect moving the weaker zombies to the back when they've taken damage.

# Answer
> 1 votes
Waves and the lulls in-between provide a few advantages to the player.

1. They provide more variety of play types. In PvZ, this is embodied by elements like the peashooter vs. cherry bomb: the peashooter can beat 10 enemies separately, but if they are in a clump, you need AOE. By varying the type of challenge, they prevent a single optimal strategy, and let us have a more interesting experience. (extra credits has an episode on this here)
2. They provide time to prepare for the next challenge. In plants versus zombies this is important due to the cool-downs on different plants, you can't build them all at once even if you can afford it. The lulls also allow planning, increasing the strategic value of the game.
3. They provide more sentiments of victory per level, as you get a feeling of victory every wave, instead of only at the end of the level. They also give some adrenaline when a near miss occurs.

---
Tags: game-design, game-mechanics, psychology
---


title: Sparsely distributed locked levels?

text:
# Question
Title: Sparsely distributed locked levels?
I want to include some locked levels in my puzzle app as a lightweight reward system. The levels play relatively quickly (average 1-min/level) and there are 100-200 levels in a pack. I prefer not to enforce a strict sequential ordering of play (I'm worried that a "wall" of 200 locked levels looks somewhat daunting and does not allow any exploration).

I propose (for example) that the player must solve puzzles #1-4 (in any order) to unlock #5, #6-8 (in any order) to unlock #9, #10-13 to unlock #14, and so forth. The locked levels have no dependencies other than you must solve those puzzles immediately preceding it and after the last locked level (e.g. you can unlock level #9 without unlocking level #5).

While I don't expect to convey all the subtleties/rules of unlocking, would the following graphic be "good game design" practice for showing the locked levels? Would one reasonably assume they had to solve #1-4 to unlock #5? (I know that this a subjective question, but game design psychology can be a pretty subjective topic).

# Answer
I don't see why you couldn't give some less subtle hints. Something like this:

Seems like an obvious enough encoding. You could remove the keys from the levels that have already been completed. Of course you can tune the prominence of the keys into your desired solution. They could be the same scale as the locks behind the numbers as well. Just some food for thought, I don't think the coherence of the elements in a row alone and the left to right association from the numbering is strong enough alone to convey it without some amount of trial and error by the user.
> 6 votes

# Answer
A possible indicator is if the player clicks on a locked level, you could animate one of the levels it is dependent on. A simple red flash would do the trick. You could have a message pop up saying "you need to finish levels 1-4 to unlock this" clicking on things for more information is a common behavior. Also, most players play levels in order and like to complete them all, so this behavior would let them unlock the next levels without thinking until they notice the pattern.

You should make sure to include a level unlocked animation to draw the players attention to when they have met the criteria. This also reinforces the reward system, since players are more aware they received something.
> 0 votes

---
Tags: levels, ui-design, psychology
---


title: Scoring and purchased hints?

text:
# Question
Title: Scoring and purchased hints?
Curious about how developers approach the use of purchased hints and scoring.

Context:

I have a puzzle app that allows users to incrementally reveal an optimal solution via purchased hints. They can choose to ultimately reveal the whole solution or only pieces of the solution.

There are hundreds of puzzles in the app. The nature of each puzzle is not so memorable (many look similar). Each puzzle has multiple solutions and an optimal solution so a player can return to an already solved puzzle to improve her/his score and strive for the optimal solution. Scoring is based on the number of moves (lower is better). The app tracks the personal best score for each puzzle.

Question:

From a standpoint of user experience and better/longer gameplay...

Would it be a bad idea to somehow penalize (in scoring) the player for using hints? Is there precedence for this? I had the notion of adding a point (low score is better) for every hint used. The penalty would preclude reaching the perfect score. This way the player can use a hint when stuck but still return to try for the optimal solution without hints.

# Answer
I've got only one hint - try not to penalize your player, make gifts instead.

In your situation - don't take something that player already achieved (his points) for using hints. Instead, stimulate him with giving even more scores for not using hints.

This trick works almost in every gamedesign - inverting "punish" mechanic (negative) to "stimulate" mechanic (positive).
> 5 votes

# Answer
You should not punish players for paying you money. (Even framing it as a a reward scheme still harms your monetization) If you rely on leader-boards or any kind of score comparison, you need to tread carefully to avoid the appearance of pay-to-win. However, I am guessing you are making a game with little to no competitive sentiment, and the rest of my answer assumes that.

A more subtle way to do it than just penalizing the score would be to save two scores for each level if hints were used. The first is the score without hints, the second is with hints. If the no-hints score is equal to or greater than the score with hints hide the hints score. (a visual marker to point out which levels were done with hints should be included)Perfectionists will try to beat the level without hints, and will appreciate a pointer to which levels need beating. Other players will just speed up their progression, possibly replaying tricky levels later on.

This motivates players to play through levels perfectly by simply stating what they did. They will not interpret it as punishment, even though hints are being recorded as less-than-perfect.

There is a small problem of players cheating and memorizing the solution with hints in order to beat the level again in a no-hints game, but this does not really harm your game-play (I think). If this is an issue you could count all solutions to the puzzle in the hour after using a hint as also having used the hint.
> 0 votes

---
Tags: leaderboards, scoring, psychology
---


title: Chunk/Region Compression/Decompression

text:
# Question
Title: Chunk/Region Compression/Decompression
Reading this article here, the author writes about chunk saving and using a lookup table and then saving each chunk in a region file, each region file having 4096 chunks and each chunk having 4096 bytes of data. He structures it so that each chunk in the region file is offset by 4096 bytes - perfect. So far so good, I've created this in C# easily.

My problem is now with compression. If I compress each chunk down, that is great, nonetheless I still have a region file that is full length in size based on each chunk being 4096 offset - so the file itself still looks full size despite each chunk being compressed and save within it's 4096 byte allotment. I don't want to compress the entire region file because that is extremely inefficient to have to always decompress 4096 chunks in a region just to get 1 chunk. It is better to compress each chunk individually before adding to region file.

Can someone suggest how I might work around this without resizing the region file? I do not want to resize a region file every time it is modified, which is also what the author of this article avoids too. File resizing would be too costly in performance.

# Answer
> 1 votes
Why don't you create a smaller allocation unit size (instead of 4096 per chunk)?

From what I understand, each chunk is 4096 byte long uncompressed. I'm guessing that a lot of data in the region is the same, so compressed it's at least 20x smaller, so that's about 200 something bytes. You can compress a bunch of chunks and chose allocation unit size that would be small enough, but still fit most of the compressed chunks.

If you make a allocation unit size 256 bytes you could store most of compressed chunks into a single unit, filling it with data and then completing the unit by adding zeroes up to 256 bytes. If the chunk happens to be larger than that, you'd have to use two or more units to store it.

In that case, your offsets would get messed up and you would have to create a header that would store the offset of each chunk from the start of the file in regards of number of 256 byte blocks. Given that you have 4096 chunks, you could get away with 2 bytes per chunks.

Alternative is to choose a unit size that you'd know for certain wouldn't get too small for a compressed chunk, but that's a gamble.

I know this is a late answer, but it might help someone else who stumbles upon it.

---
Tags: voxels, file-format, compression
---


# Question
Title: sfml - graphic not showing once i change the context setting
I am trying out `sfml` and want to draw simple 2D graphic on top of 3D object.

```
sf::ContextSettings settings;
settings.depthBits = 24;
settings.majorVersion = 4;
settings.minorVersion = 1;//opengl v4.1
settings.attributeFlags =  sf::ContextSettings::Core;

sf::RenderWindow window( sf::VideoMode(1200,800),"sfml", sf::Style::Default, settings);

sf::CircleShape qs;
qs.setRadius(400);
qs.setPosition(400,400);

while(window.isOpen()){
        sf::Event evnt;
        while (window.pollEvent(evnt)) {
            switch (evnt.type) {
                case sf::Event::Closed:
                    window.close();
                    break;
            }
        }
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);

        window.draw(qs);

        window.display();
    }

```

the `sf::ContextSettings` is set so that I can use `openGL` to draw 3D graphic. but with this settings, my `qs` not showing in the window. if I comment out the `settings.majorVersion = 4;` and `settings.minorVersion = 1;`, then it appear.

I am rather new and not sure how it works.

1. Is this possible to be resolved?
2. Is it correct to think that I want to use `sfml` for interface graphic and `OpenGL` for 3D? How do people normally do it?

# Answer
> 0 votes
<sup>*I apologize if my answer in relation to this on Stack Overflow didn't properly explain the cause and effect of this.*</sup>

The problem is that the SFML graphics module relies on some legacy OpenGL functionality. This means that if you create a (\>= 3.2) core context then that functionality isn't available.

Thus you must specify that you need a backwards compatible context, which is done by setting:

```
settings.attributeFlags = sf::ContextSettings::Default;

```

Here's an excerpt from the SFML 2.4.2 documentation.

> When requesting a context with a version greater or equal to 3.2, you have the option of specifying whether the context should follow the core or compatibility profile of all newer (\>= 3.2) OpenGL specifications. For versions 3.0 and 3.1 there is only the core profile. By default a compatibility context is created. You only need to specify the core flag if you want a core profile context to use with your own OpenGL rendering. **Warning: The graphics module will not function if you request a core profile context. Make sure the attributes are set to Default if you want to use the graphics module.**

Note that when it comes to OS X there's another condition as well.

> Apple only supports choosing between either a legacy context (OpenGL 2.1) or a core context (OpenGL version depends on the operating system version but is at least 3.2). Compatibility contexts are not supported. Further information is available on the OpenGL Capabilities Tables page. OS X also currently does not support debug contexts.

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


# Question
Title: How can I change InvokeRepeating time in unity?
I have a slider in the pause menu which will have a min value of 1 and max of 5. When I change it, the `InvokeRepeating` function maintains the same speed, but Debug.Log shows current slider value.

How can I change the `InvokeRepeating` rate?

Player.m1 is a float; when I give 5f or something like that to `InvokeRepeating` it works fine.

<pre><code>    using UnityEngine;

    public class Gen1 : MonoBehaviour
    {
        public GameObject rocks;

        int scr = 0;
        public int m=0;
        float n11=Player.m1;
        float sp;

        // Use this for initialization
        void Start()
        {
            //if (Player.m1 == 5 || Player.m1==4) {
            InvokeRepeating ("CreateObstacle", Player.m1,5f);//Here speed handels
            //} else {
                //InvokeRepeating ("CreateObstacle", 4f, 5f);//Here speed handels
            //}
            Debug.Log ("current speed is afad"+Player.m1);
        }

        void Update()
        {
            //InvokeRepeating ("CreateObstacle", 4f, Player.m1); //Here speed handels
            //Debug.Log ("current speed is afad"+Player.m1);
        }

        void OnGui()
        {
            GUI.color = Color.black;
            GUILayout.Label ("Score is" + scr.ToString ());
        }

        void CreateObstacle()
        {
            Instantiate(rocks);
            Player.score += 1;
            Debug.Log ("current speed is "+sp);

        }

        void OnBecameInvisible() {
            // Destroy the bullet
            Destroy(this.rocks);
        }
    }
```
</code></pre>

# Answer
> 3 votes
Once an `InvokeRepeating` is started, you can't change the repeat rate. You have to Cancel the Invoke and start it again.... **Or**, you use the power of coroutines! `Invoke` and `InvokeRepeating` should be removed from the Unity API IMO...

```
public float sp = 5f ;

void Start()
{
    StartCoroutine( CreateObstacle(Player.m1) ) ;
}

IEnumerator CreateObstacle( float time )
{
    yield return new WaitForSeconds(time) ;
    while( true )
    {
        Instantiate(rocks);
        Player.score += 1;
        Debug.Log ("current speed is "+sp);
        yield return new WaitForSeconds(sp) ;
    }
}

```

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


title: Gif maker in libgdx

text:
# Question
Title: Gif maker in libgdx
**Hi all!**

I want to put some screen activity into gif, I achieved this, but it take a lot of time.

**How I do it:** I want to record gif 100x100 with 25 frames:

1) I take 25 screenshots: In render method I set scalingViewport 100x100, then I take screenshots:

```
    gl.glPixelStorei(GL20.GL_PACK_ALIGNMENT, 1);
    final Pixmap pixmap = new Pixmap(width, height, Pixmap.Format.RGBA8888);
    ByteBuffer pixels = pixmap.getPixels();
    byte[] bytes = new byte[pixels.remaining()];
    gl.glReadPixels(0, 0, width, height, GL20.GL_RGBA, GL20.GL_UNSIGNED_BYTE, pixels);
    pixels.get(bytes);

    int bytesSize = bytes.length;
    int[] arrayWitoutAlpha = new int[bytesSize/4];
    int arrayPos = 0;
    for(int i = 0; i < bytesSize; i+=4) {
        arrayWitoutAlpha[arrayPos] = ((bytes[i]&0x0ff) << 16) | ((bytes[i+1]&0x0ff) << 8) | (bytes[i+2]&0x0ff);
        arrayPos++;
    }
    return arrayWitoutAlpha;

```

and add this int arrays into one two-dimensional int array. Taking 25 screenshots 100x100 takes about 500ms.

2) After that I combine screenshots with different gif encoders (like this and others). But sometimes frame can be added in encoder in 50ms, or sometimes it can be added in 1000ms, and gif with that size can be generated for 1500ms, or can be generated for 30 seconds or more.

Example of code how i generate gif with gif encoder from Square:

```
        GifEncoder encoder = new GifEncoder(Gdx.files.external("testgif.gif").write(false),
                gifWidth, gifHeight, 1);
        ImageOptions options = new ImageOptions();
        for (int i = 0; i < framesArray.length; i++) { //framesArray - two-dimentional int array with frames
            encoder.addImage(framesArray[i], gifWidth, options);
        }
        encoder.finishEncoding();

```

I think even 1500ms for this little gif it is very long. I would be very grateful to that who knows how to deal with it. Thanks in advance!

# Answer
There's a few important notes I want to mention first.

OpenGL's origin is the bottom left corner. While `Pixmap`'s origin is at the top left corner. Thus after calling `glReadPixels()` you have to flip the `Pixmap` on its y-axis.

```
Pixmap pixmap = ...

int width = pixmap.getWidth(), height = pixmap.getHeight();
Pixmap flipped = new Pixmap(width, height, pixmap.getFormat());

for (int x = 0; x < width; ++x)
    for (int y = 0; y < height; ++y)
        flipped.drawPixel(x, y, pixmap.getPixel(x, height - y - 1));

pixmap.dispose();
pixmap = flipped;

```

Next it should be noted that `Pixmap`'s internal format is RGBA while `GifEncoder` expects a format of ARGB. Which can be changed by doing:

```
int pixel = pixmap.getPixel(x, y); // RGBA

int r = (pixel >> 24) & 0xFF;
int g = (pixel >> 16) & 0xFF;
int b = (pixel >> 8) & 0xFF;
int a = pixel & 0xFF;

pixel = (a << 24) + (r << 16) + (g << 8) + b; // ARGB

```

> How to record a GIF with LibGDX

So using `GifEncoder`. The change I would make to your code, is that I would keep `List<Pixmap> frames` instead. So for capturing the frame I would in total do:

```
Pixmap pixmap = new Pixmap(width, height, Pixmap.Format.RGBA8888);
ByteBuffer pixels = pixmap.getPixels();
gl.glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
frames.add(pixmap);

```

The key is to do the least amount of work while capturing the frame. While later utilizing multithreading to export the GIF.

Then when you have captured enough frames, you can go ahead and save the GIF by doing:

```
// Note that if loopCount is less than 1, then the gif will loop indefinitely
GifEncoder encoder = new GifEncoder(..., width, height, 0);

ImageOptions options = new ImageOptions();

// Frame rate / Time between each frame
options.setDelay(50, TimeUnit.MILLISECONDS);

for (Pixmap pixmap : frames) {
    int width = pixmap.getWidth(), height = pixmap.getHeight();
    int[][] pixels = new int[height][width];

    ... flip pixmap on the y-axis ...

    for (int x = 0; x < width; ++x) {
        for (int y = 0; y < height; ++y) {
            int pixel = pixmap.getPixel(x, y);

            ... change pixel format ...

            pixels[y][x] = pixel;
        }
    }

    encoder.addImage(pixels, options);
}

encoder.finishEncoding();

```

To do so that you won't stall the rest of application while saving the GIF. You could do all the saving in a separate thread.

```
new Thread(new Runnable() {
    @Override
    public void run() {
        ... save gif ...
    }
}).start();

```

Saving will still take time, as each frame will have to be encoded and written to the file. However multithreading makes so the user wouldn't be stalled and annoyed by the process.

Last but not least, remember to dispose all those `Pixmap`s.

```
for (Pixmap pixmap : frames)
    pixmap.dispose();
frames.clear();

```

If needed, you can also save a `Pixmap` to a PNG by doing:

```
PixmapIO.writePNG(fileHandle, pixmap);

```

Additionally you can get rid of all those `GL20.`, by statically importing `GL20`.

```
import static com.badlogic.gdx.graphics.GL20.*;

```
> 1 votes

# Answer
Use `options.setDelay(delay, TimeUnit.MILLISECONDS);` where `delay` is your time between frames to set how long the images should show.
> 0 votes

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


title: Display canvas in front of player

text:
# Question
Title: Display canvas in front of player
*I have stuck in this simple problem but unable to understand that why i am unable to control it.*

I have these line of code which is displaying my canvas object in front of my player(**camRotationToWatch** object name in code) at certain rotation of the player.

```
if (camRotationToWatch.transform.localEulerAngles.x >= navigationCanvasXMinmumLimit && camRotationToWatch.transform.localEulerAngles.x <= navigationCanvasXMaximumLimit)
        {
            if (!navCanvasHasDisplay)
            {

                navigationCanvas.SetActive(true);
                //Debug.Log(camRotationToWatch.transform.forward);
                Vector3 navCanvas = camRotationToWatch.transform.position + camRotationToWatch.transform.forward * navCanvasDisplayDistanceFromCam;
                navCanvas = new Vector3(navCanvas.x, 2f, navCanvas.z);
                navigationCanvas.transform.position = new Vector3(navCanvas.x, navCanvas.y, navCanvas.z);

                navigationCanvas.transform.rotation = camRotationToWatch.transform.rotation;

                navCanvasHasDisplay = true;

            }
        }

        else
        {
            //navigationCanvas.SetActive(false);
            if (locationPanel.activeSelf == false && infoPanel.activeSelf == false) {
                navigationCanvas.SetActive(false);
                navCanvasHasDisplay = false;
            }
        }

```

This code is actually work fine when **camRotationToWatch** object rotate from **down to up** and Canvas show at correct position but as I try to to rotate **camRotationToWatch** from **up to down** it display(active) Canvas at very top position. How can I restrict canvas to show at same position (*No matter player rotate from up to down or down to up*) but display on front of the player object?

# Answer
I believe the problem is that `camRotationToWatch.transform.localEulerAngles.x` may represent the angle in a way you are not expecting. For example, -30 degrees is the same as +330 degrees.

I'll take a guess that you are expecting a negative angle when looking up, while Unity is returning a positive angle. Try replacing the first line of the code you pasted with this code:

```
float xFromCamera = camRotationToWatch.transform.localEulerAngles.x;
if (xFromCamera >= 180.0f) xFromCamera -= 360.0f;
if (xFromCamera < -180.0f) xFromCamera += 360.0f;

if (xFromCamera >= navigationCanvasXMinmumLimit && xFromCamera <= navigationCanvasXMaximumLimit)

```

(Note: I wasn't confident at first, so I decided to test this out in Unity. I set the x rotation of a transform to a negative angle in code, then read the same x rotation later. The returned angle was positive, 360 + my angle.)
> 1 votes

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


# Question
Title: I have problems for export from Blender to Ogre3D
I don't speak good english, but I will try.. I need to make a game for my University. Exists lot of models in **blendswap** but, I have problem for export.

Many of these models have extra objects, such as a floor, I need to remove those extra objects and export the weapon and hand.

My idea is:

Import a weapon model with hand with 2 actions, reload and shoot. **How can I do it?**

I love this models:

http://www.blendswap.com/blends/view/85257 or 67870 or 70607 (change number in link, because I don't can put more 1 link, because I'm level noob)

# Answer
> 1 votes
I would recommend using the blender2ogre exporter: http://www.ogre3d.org/tikiwiki/tiki-index.php?page=blender2ogre

If the plugin doesn't export .mesh files, and only exports .xml files, use the XML converter tool on the XML files to produce the .mesh files: http://www.ogre3d.org/tikiwiki/OgreXmlConverter

As far as only exporting the weapon and not the floor, this is a matter of Blender editing. You will need to select only the geometry you wish to export, and check the "Export selected only" option. You may have to go into mesh editing mode, and cut out the triangles that you don't want, depending on the model.

---
Tags: blender, ogre, blender-game-engine
---


# Question
Title: How do you create an over world styled like Pokémon Black and White, with both 2D and 3D elements?
The over world of Pokémon white uses 3D models for objects like houses, and 2D sprites for characters like the player. What would I have to do to create an over world styled like this?

Here is an example:

# Answer
If I understand what you're asking for, sort of a "cardboard cutout" effect for the characters, then what you'd do is build your "Overworld" as a 3D world and draw your characters on quads (planes).
> 1 votes

---
Tags: xna, graphics
---


# Question
Title: How do I make my offline socket.io server go online?
I've made a simple multiplayer game using socket.io, and took a lot of help from YouTube and the Internet on how to do it. However, the tutorials only talk about how to run the server locally, and none of the ones that I followed ever talked about running the server online - and I looked through a lot!

I think that I only need to add my server IP to my Javascript file, and match the socket.io inspector property value with it.

How do I make my offline socket.io server go online?

# Answer
> 0 votes
in this picture is what i learned about my problem and how to fix it. hope it helps someone else too.

---
Tags: node.js, socket
---