# Question
Title: Raycast not working on touchscreen (Android tablet/phone)
I have a raycast that works in the unity editor but not when I build it for Android( tablet or phone, neither work). The code I'm using is as follows:

```
public class DirectionalTilePlacing : MonoBehaviour {

public LayerMask levelLayer;
private int tileType;
public int Tiletype
    {
        get { return tileType; }
    set
    {
        tileType = value;
    }
    }
RaycastHit hit;
Vector2I placePosition;
// Update is called once per frame
void Update()
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out hit, Mathf.Infinity, levelLayer))
    {
        if (hit.collider.tag == "Replaceable")
        {

            transform.position = new Vector3(Mathf.Floor(hit.point.x) + 0.5f, Mathf.Floor(hit.point.y), Mathf.Floor(hit.point.z) + 0.5f);
            GetComponent<MeshRenderer>().enabled = true;
        }
    }
    if (Input.GetMouseButtonUp(0))
    {
        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit, Mathf.Infinity, levelLayer))
            if (hit.collider.tag == "Replaceable")
            {
                placePosition = new Vector2I((int)transform.position.x, (int)transform.position.z);
                EditorManager.map.SetEmpty(placePosition);
                EditorManager.map.BrushTile(EditorManager.map.TypeToObject((Tile.tileType)tileType), placePosition, (Tile.tileType)tileType);
                GetComponent<MeshRenderer>().enabled = false;
                gameObject.SetActive(false);
            }
    }

}

```

}

Everything up until any Physics.Raycast line works. The idea is that there is a ray casted from the position your finger is at when touching the screen.

# Answer
The answer was pretty simple. I found out that none of the objects in question had a collider whatsoever. So added colliders and everything works now. Thanks anyhow.
> 0 votes

# Answer
Instead of using Input.getMouseButton try this

if you want to detect only one screen touch use this:

```
 if (Input.GetTouch(0).phase == TouchPhase.Ended)
{
    ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out hit, Mathf.Infinity, levelLayer))
        if (hit.collider.tag == "Replaceable")
        {
            placePosition = new Vector2I((int)transform.position.x, (int)transform.position.z);
            EditorManager.map.SetEmpty(placePosition);
            EditorManager.map.BrushTile(EditorManager.map.TypeToObject((Tile.tileType)tileType), placePosition, (Tile.tileType)tileType);
            GetComponent<MeshRenderer>().enabled = false;
            gameObject.SetActive(false);
        }
}

```

but if you want to detect all touches use this

```
for (int i = 0; i < Input.touchCount; ++i) {

    if (Input.GetTouch(i).phase == TouchPhase.Ended){
         ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out hit, Mathf.Infinity, levelLayer))
        if (hit.collider.tag == "Replaceable")
        {
            placePosition = new Vector2I((int)transform.position.x, (int)transform.position.z);
            EditorManager.map.SetEmpty(placePosition);
            EditorManager.map.BrushTile(EditorManager.map.TypeToObject((Tile.tileType)tileType), placePosition, (Tile.tileType)tileType);
            GetComponent<MeshRenderer>().enabled = false;
            gameObject.SetActive(false);
        }

    }
}

```
> 0 votes

---
Tags: android, unity, raycasting, touch
---


# Question
Title: How to organize messages queue in a fast-paced multiplayer game
I'm trying to develop a fast-paced multiplayer game. I decided to build my own protocol over UDP and now I'm stuck with the following question.

The idea of the protocol is very basic and it's similar to many others:

* Client does NOT do any game logic except of some predictions (like smooth walking). It just sends 'ping', 'connect', 'disconnect' and 'keypressed' / 'keyreleased' actions to the server.
* On contrary, the server does game logic based on the users inputs and sends diffs to each client every 30 ms

As I already mentioned, the client sends 'ping' messages (to notify server that we're still alive when there's no other messages in some period of time) as well as 'keypressed' / 'keyreleased' stuff.

I thought that the 'ping' messages can be unrelirable -- the client sends them at steady intervals anyway, so if one was lost, nothing bad will happen.

However, such messages like 'keypressed' and 'keyreleased' should be reliable. By this I mean that the client should resend them in case of any failure and they should appear on the server in the same order they were sent (otherwise 'keyreleased' message could arrive before 'keypressed' resulting in the incorrect game behavior).

So, the questions is -- how is it usually handled? I mean, what is the right way to implement such logic on the server? Should I queue all incoming reliable messages in some container and wait until messages with smaller sequence IDs also arrive? If so, what should I do with unrelirable messages then? Because I definitely shouldn't wait before 'ping' message arrived (and there's a chance that it won't arrive at all). Should I use a distinct sequence numbers for unrelirable messages or should I make 'ping' messages reliable as well?

# Answer
You should implement your UDP reliable as TCP.

On http://gafferongames.com/ you can read about packing packets, resending them, correcting errors. There is some pseudo-code (or this is written in C, I don't remember now) - which explains everything well.

Let's say that you have a struct (or a class) with currently pressed keys:

```
class Input{
    boolean left,right,down,up,space;
}

```

I assume that you did something like:

```
while(someCondition){
    if(30ms passed){
        client.sendPacket(new Input(player.getPressedKeys()));
    }
}

```

This is not enought, because the server won't know which packed was sent first - it won't get the order. This could make a situation like this: On your device you jumped and then went to the right (space, right) The server gets these packets in a wrong order (right,space) and send them to your opponent in a new order - which is unacceptable of course.

In this case, you should add a field which is known as a SequenceNumber (also used in TCP networking).

```
class Input{
    boolean l,r,u,d;
    long sequenceNumber;
}

```

With each sent packet your should increase the sequence number so the server knows the order too.

But this is still not enough. What about lost packets? This is UDP, some packet's wont arrive. In this case you should make a superultranitroushypersystem called a 'List' - which will be a history list of your packets.

Let's make a list (in Java):

```
ArrayList<Input> packetHistory = new ArrayList<>();

```

And now we do two tricks: \- we don't send a single packet, but the entire list \- when adding a packet to the list, when it's size it higher than 32, we cut a packet from the top (the oldest one)

We send a packet:

```
while(condition)

    if(30ms passed){
        Input input = new Input(player.getPressedKeys());
        input.sequenceNumber = sequenceNumber++;
        packetHistory.add(input);
        if(packetHistory.size() > 32) packetHistory.remove(0) // i'm lazy
        client.send(packetHistory);
    }

```

Now, the server each 30 seconds receives a list of 32 previous positions and look what happens here.

Each packet in the list has a sequence number, for example after ~1second we would have a list with sequence numbers from 32 to 64 (64 is the most fresh).

Now let's assume that this list is LOST in the universe somewhere, so the server didn't get the list with the packet '64'. But wait, we don't have to make any corrections because the next list which is already going out has the range 33-65 - which of course has the 64 in it. We don't need to send any requests to the client like 'oh dear client, please, I didn't receive the 64'th packet'. We'll get it in ~30 seconds cause it will be in the next incoming list. We've fixed the packets loss.

**Edit** If we lose more than 32 lists in a row (which is of course possible) we could change our idea a little bit. We can keep a second list of packets on the client from which we don't substract the oldest packet when sending the entire list. This is a critical list, which is substracted only when the confirmation from the server comes.

**What happens when we lose more than 32 packets?** We send a response to the server, that none of received 32 packets matched the sequence number. We could name this packet 'CorrectionPacket'. On the server we pack to it a server's sequence number so the client knows where to substract the critical list and send these lost packets.

**An example:**

Some time has passed from the start of the game. We currently have a list with packets 65-97. Server is waiting for packet 97. We also have a critical list which has the same amount of packets (65-97). Now the crucial moment - there's a storm and 40 next packets are lost in the universe.

Normal history list: packets 105 - 137 (we sent 40 packets) Critical history list: packets 65 - 137

Server still didn't confirm a packet with a number 97, and the next range that it received after the storm was 105 - 137. He sends the `CorrectionPacket()` with his local sequence number (97) to the client and the client looks in the critical list, cuts it below 97 (not needed) and send the entire tail - 97-137 to the server which corrects everything.

I hope you get the idea :) - you have to keep two lists, one for normal packets - 32 all time - which is small with integers and one with the 'older' history to solve problems like this, when you lose more than 32 packets.

Of course - it should be improved - but this is on your own.

**What about the server?**

At the start, you create a number starting at 0:

```
long serverSeqNum = 0;

```

When a list arrives, you check all of the packets in it:

```
for(Input input : receivedList)
{
    if(input.sequenceNumber.equals(serverSeqNum){ // perfect, this is the packet that we're waiting for
        player.process(input);
        serverSeqNum++; // and increment a number, we're waiting for a next packet
    }

}

// and here one more trick
// we should send the confirmation to the client with the server's sequence number - so it won't send not needed packets anymore. For example if we received a packet with number 64 and processed it, we don't need it anymore so we send a packet to the client:
server.send(new ConfirmationPacket(64));

```

And when the client receives it - cuts the historyList below this packet, so we don't waste our network and don't send packet's which are not needed.

**What about messages like PING?**

Messages like 'JoinedQueue', 'EndedMatch' should be TCP - always - they have to arrive and we don't care if it takes 100ms to show the player his stats or 300 ms.

Messages like 'Ping' should be implemented on your own. I send them via UDP (so it shows the real speed, how the game goes) and store every 3 of them. If I have 3, I add them and divide by 3 and get the average ping of 3 last packets. This is a newbie solution - but it works well. Most of the common networking libraries have their own pings to keep the connection alive - you can easly read from them their values when the arrive.

You don't have to re-send pings and ACK them. Ping is just for user's information, if he's lagging or not. Of course, you CAN re-send them, ACK etc, but it's that's not crucial. You know how the ping works in games - it only shows the average (it changes by couple of sends, it doesn't update each 30 ms and shows a new value).

Via TCP you send only crucial informations - things that HAVE TO be performed no matter what, for example inform player that his opponent was disconnected.

With UDP you send anything else (positions, spells, jumps, health changes) - but always with lists/confirmations, cause they have to arrive in order.

**Your last question - about the collection of messages**

You can do this, of course, you can send everything, but be aware that if you store everything - positions, inputs, health changes and thousands of things, when you lose some packets you would need to resend a collection with 150 or even 54323 elements which will cause a lag. And what if the entire list is lost too? :D

If you receive informations on the server on one listener and check the packet type, if it's a 'InputPacket' or a 'AbilityPacket' you can store everything in one collection but you should apply the same sequence number to all packets.

When you want to split your things and send 'InputPackets' and 'AbilityPackets' separately, you should create two lists, two sequence numbers and two threads for sending them from the client. Then, you can send Inputs for example every 20 ms, and Abilities every 5 - or even only when they're 'used' by the user.

Your solution is of course correct. Do some tests, write some things and you'll know what's the best option for you. It really depends on the game type.
> 5 votes

---
Tags: networking, multiplayer, client-server, udp
---


# Question
Title: Keeping a object(world space canvas) always in the cameras viewport
So I have the following problem: I have a world space canvas following a arrow that moves around the screen. The canvas itself is just a child of the arrow. The problem is that sometimes when the arrow is pointing to something on the edge of the screen parts of the canvas go off screen. I want to write some code that keeps the entire canvas inside the viewport at all times. I found a solution online but this keeps the pivot point of the object inside the camera bounds and not the whole object. I simply cant figure out how to keep the whole object inside the camera bounds. Here is the code I have :

```
void LateUpdate()
{
  transform.rotation = rotation;// This simply keeps the objects original rotation independant from the parent
  Vector3 pos = Camera.main.WorldToViewportPoint(transform.position);
  pos.x = Mathf.Clamp01(pos.x);
  pos.y = Mathf.Clamp01(pos.y);
  transform.position = Camera.main.ViewportToWorldPoint(pos);
}

```

Edit: this is how it looks with the first answer: The gif is too large to upload so here is a link to it.

# Answer
Something like this should solve the problem:

```
var scaleViewport = Camera.main.WorldToViewportPoint(transform.lossyScale.x, transform.lossyScale.y, transform.position.z);
var halfXScale = scaleViewport.x /2;
var halfYScale = scaleViewport.y /2;

pos.x = Mathf.Clamp(pos.x, 0 + halfXScale, 1 - halfXScale);
pos.y = Mathf.Clamp(pos.y, 0 + halfYScale, 1 - halfYScale);

```

If the parent has the scale `(1,1,1)` you can use `transform.localScale` instead of `transform.lossyScale`.

This code limits the area of possible movement by the the size of object. So when you come to limited boundaries and the object overflows from them, it will still be inside the actual viewport.
> 1 votes

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


title: How to create "broken glass" animation?

text:
# Question
Title: How to create "broken glass" animation?
I have started making a 3D game in Unity5 that consists in avoiding obstacles. It is very easy but I want to add a collision effect when I collide on the wall.

I would like to slice the screen into many parts (random pieces is better) that are falling down from screen with gravity.

**An example of what I mean:**

How can I do this?
I've tried using a lot of different images (shapes) but I'm sure that is not the best way...

Thanks for any suggestions.

# Answer
> 1 votes
Instead of randomly slicing the sprite, you can create several different animations including premade sliced sprites, and randomly play one of them.

If you have around 5-6, the repeats would be unnoticable for the most of the players.

---

There is also this asset on the Asset Store which allows you to dynamically slice sprites on runtime.

---
Tags: unity, c#, animation, random
---


# Question
Title: Is this how I use activities in android studio?
I'm a student who is just stepping into android game development.

I'd like to create a text-based RPG game for android and started to learn about Android Studio (I think Android Studio is enough because I'm not using any 2D or 3D sprites).

But then I got into some confusions about the activity.

I learned that an activity has a life cycle from onCreate to onDestroy.

In some tutorials, I heard that activities are just various scenes that can be used within an app.

With that said, my question is, **can an activity be used for a game scene?**

For instance, I'm thinking about creating game scenes like the *battle scene, exploring scene, town scene, inventory scene* etc.

But opening up another scene, or activity, would destroy the previous one in which, in some cases, I would not want that to happen. (Am I correct on this?)

Do I need something else other than activity to create those scenes?

# Answer
> 1 votes
Every activity is an *individual application screen*, so you are correct in thinking they could be used for, as you put it, individual *game scenes*.

The activity lifecycle is set up the way it is to facilitate memory management. Most Android devices have a small amount of RAM available (1 or 2 GB), which is often shared between the OS and several other applications. To put it simply, if applications were able to hold onto their activities for however long they want, the device would very quickly run out of memory. This leads to lag, hanging, and crashes.

To pass data between activities you can use intents. The "Building Your First App" section of the Android Developers website, for example, shows how to pass a message from one activity to be displayed in another activity. If you need something more robust, Android offers plenty of different storage options.

You can also use fragments to create different contexts within the same activtiy. For example, opening a stat page during battle.

Udacity has several great, free online courses on Android development. These can teach you the basics and technicalities of the Android platform, and much more if you're feeling curious. Of course, the official Android API guides are always a good reference to look into.

In summary, your question is too general to warrant a particular answer. Yes, it is possible to do what you want to do. How one would go about doing it, however, depends on a lot of factors. Hopefully you now have an idea of where and how to start experimenting. Good luck!

# Answer
> 0 votes
You could use the xml layout fIle to play out different scenes within an activity. For example you can make a text visible and invisible when certain actions have been done ( press a button/timer etc.). This way you don't need an activity for every scene. Hope I helped you on your way a bit.

---
Tags: android, rpg, android-studio
---


# Question
Title: How do I fix this weird lighting problem?
I'm making a small game in Unity, and some models are displaying very ugly shading. The shading usually looks funky along the edges between triangles. I'm pretty new to working in 3D; I bet this is an artifact of vertex lighting, but I'm not sure, and I'm not sure how to fix it.

Here you can see the worst example of this problem:

Low-quality lightmapping is visible in that shot, but I'm asking about the visible bands and weird shapes visible on the surface of the orange mesh in the foreground. The mesh was built and UV-mapped in Blender, and is using a standard bumped diffuse shader. There is a light behind and above the camera; all other lights in the scene are pretty far away. What am I doing wrong, and how can I do better?

EDIT: Below is the wireframe for this model in Blender.

# Answer
> 7 votes
It looks like your vertex normals might be messed up. Each vertex's normals should be perpendicular to its face (parallel with the face normals that your wireframe image shows), and you'll need separate vertices for the corners, one for each face that meets at a corner.

# Answer
> 2 votes
That looks like a vertex normal issue. Not having used Blender I'm not sure what options you have to see/modify the normals directly at the vertex level.

The first thing I would do to test, is break off the front surface from the rest of the object and see if it lights correctly. If that works then you could just export it as 2 parts, front & back faces as one object and then side parts as another.

# Answer
> 1 votes
I know this is an old thread, but I stumbled over it, so maybe someone else can benefit from this answer: The problem is: you are trying to interpolate (smooth shading) normals over a 90° angle which most of the time leads to problems.

There are multiple solutions for this: 1. set the shading to flat (T-Menu) 2. Select all edges with an angle \> 50 (or higher, toy around a bit), press CTRL E -\> mark sharp. Unity can read that information. It will split the vert. normals at the marked edges instead of trying to interpolate them. 3. Use an edge split modifier to actually split the mesh at the angle you specify (I would recomend the upper one in this case) 4. Use a bevel modifier with a depth of 2 or higher. I would recommend this option, it makes the mesh a bit more high poly, but also more realistic. Be sure to either mark the edges you want beveled yourself or choose angle as the limitation mode.

# Answer
> 0 votes
If you're actually using lightmapping, Unity has a modle import setting to Generate Lightmap UVs which would probably solve your problem.

---
Tags: 3d, graphics, unity, lighting, blender
---


# Question
Title: Everything is set to Bounciness 0 - Why am I still bouncing?
I am creating a platformer where rather than manipulating the character to get them from the beginning of the level to the end, you manipulate the world. Thus, when you want to make the character 'jump' over a gap, you actually use the land like a slingshot and 'fling' them.

This is all working well and good save for one thing - whenever I pull my land down and my player falls into it again, it begins to bounce - aggressively so!

I have made EVERYTHING out of a new physics material with 0 bounce, and I set my default physics to 0 bounce.

My player is a rigidbody2D that is moving itself along on top of other rigid bodies.

What gives? Why, even though EVERYTHING is set to 'no bouncing allowed' does my game turn into a bouncy-house whenever i start to play?

EDIT: Here is a video of the behavior:

FlingyJump - Bouncing Issues

EDIT: I have noticed a correlation to the bounce occurring and the spring being active. It have noticed that two things are happening:

1) The spring is for some reason transferring force through to the ground piece while being stretched out.

2) The player is bouncing *before even ever hitting the ground*. I don't know quite how that is possible but it seems like as soon as it is enters the original position of the rigidbody2D for the ground piece it bounces.

# Answer
I have found that it seems that the spring is constantly exerting force on the platform even when I'm not actually allowing the platform to move. While that was expected, what I did not expect was that apparently the force was being transferred through the platform into the player upon contact.

I've since restructured the entire way the mechanic works, but I thought that I'd add that bit of insight in case this might help someone else someday.
> 0 votes

---
Tags: unity, physics
---


# Question
Title: Accessing RigidBody2d from OnTriggerEnter2D(Collider)
I have the following script on my water object which, when the Players ship triggers it, the ships gravity is inverted to give the sense of buoyancy. I have added a 'print' statement to prove that the collision is working and that the Name condition check works, which it does. However it throws an error when trying to access the plays ship Rigidbody2D property to then access the GravityScale with the message:

*There is no 'Rigidbody2D' attached to the "Player" game object, but a script is trying to access it. You probably need to add a Rigidbody2D to the game object "Player"...*

```
void OnTriggerEnter2D(Collider2D coll)
{
    if (coll.gameObject.name == "Player")
    {
        print("Player Hit Water");
        Rigidbody2D tmp = coll.gameObject.GetComponent<Rigidbody2D>();
        tmp.gravityScale *= -1;
    }
}

```

**Update:** It turns out this code is fine it was the structure of my gameobjects that was the problem as the Rigidbody2D was in the child object, not the parent. See comments below for details.

# Answer
you should use cast

```
Rigidbody2D tmp = coll.gameObject.GetComponent<Rigidbody2D>() as Rigidbody2D;

```

or

```
Rigidbody2D tmp = (Rigidbody2D)coll.gameObject.GetComponent<Rigidbody2D>();

```

but if don't work try this:

```
void OnTriggerEnter2D(Collider2D coll)
{
    if (coll.gameObject.name == "Player")
    {
        print("Player Hit Water");
        GameObject tmp = coll.gameObject;
        tmp.GetComponent<Rigidbody2D>().gravityScale *= -1;
    }
}

```
> 0 votes

---
Tags: unity, events
---


# Question
Title: How do I save files with libgdx so that users can't read them?
Writing my game in libgdx, I arrived at the point when I need to save the player stats and the info of the levels. However, in libgdx it's not allowed to write the file inside folder of the application, only external (on the SD) is allowed. The point is that I don't want the file to be seen by anyone, or if they can see it, how can I convert it to a binary file so it's not human readable? I just want to hide the file.

# Answer
I resolved it with callbacks, with that I can use Android methods, that way I can write to the internal memory.
> -4 votes

# Answer
Libgdx has built in decoding and encoding functionality. Gustavo Steigert has written a nice article about this on his blog: http://steigert.blogspot.be/2012/03/5-libgdx-tutorial-files.html. Scroll down a bit to the section "2. Persist Profile operation".

In this blogpost, he explains that by using the class com.badlogic.gdx.utils.Base64Coder you can encode and decode files in the Base64-format. Leaving the unreadable and unmodifiable for end users.
> 9 votes

# Answer
It sounds like using a "preference" is what you need to do. It allows you to save small bits of data (like a high score, or other settings) which persist when the game is shut down.

And it's a lot easier than trying to write to a file; you don't really have to concern yourself where the file is.

See: http://code.google.com/p/libgdx/wiki/Preferences

On Windows it gets put in the user's home directory. Android uses a SharedPreference system.

If you don't want users being able to read what's in there, you can always save your values in an encoded way. Ex:

```
prefs.putInteger("HighLevel", 15);

```

or

```
prefs.putString("SecretInfo", myEncodeFunction("here's the secret text to save."));

```
> 3 votes

# Answer
The following code will create a text file where you can store basic data

```
FileHandle file= Gdx.files.local("files/myfile.txt");
file.writeString("my_first_file", false);

```

to read from it

```
FileHandle file= Gdx.files.local("files/myfile.txt");
String text = file.readString();

```

now

```
    if (text.equals("my_first_file")) {
           //your code
    }

```

if you'd like to check first whether not the file exits,

first, initialize :

```
boolean my_file_exits = Gdx.files.local("files/myfile.txt").exists();

```

then

```
  if (exists) {
        FileHandle file= Gdx.files.local("files/myfile.txt");
        String text = file.readString();

        if (text.equals("my_first_file")) {
               //your code
        }
} else {
 //create a textfile and store default value
}

```
> 1 votes

# Answer
Again, try asking here..

http://www.badlogicgames.com/forum/

Basically, you may want to read up on how Android handles directories in your app. There is a file handle class in libgdx that should work for you. If you just want it saved in a protected place, use the internal process and it should be local to your app directory and not visible. It doesn't have to be on an sd card. Read the android docs and ask on the badlogic forum if you still need help and don't get any answers here
> -1 votes

---
Tags: android, libgdx, file
---


# Question
Title: Do programmers in the industry get to participate in the game design process?
My main goal is to create games which is why I'm planning on studying IT so I can later on be a game developer/programmer.

My question is: does a game programmer get involved in the game designing process or is that only the game designer's job? Is a game designer always needed or can programmers work on game design some of the time?

Do programmers need to have game designing knowledge or do they just follow orders? Similarly, do game designers require programming knowledge?

I'm kind of confused over what I want to be which is why I'm asking here. Basically, do game programmers also get to be game designers?

# Answer
It depends on the company. Roles and titles vary widely across the industry, so at some companies roles will be very rigid and strict and at others they will be more flexible and allow for more cross-discipline work.

It also depends on the person; some developers like to explore beyond their "technical" role or job title, others don't.

You'll probably find more flexibility in a *smaller* game company, but it's certainly possible to find the role flexibility you are hoping for in a larger one. You just need to be aware that's something you want and look for it during the interview process. Or start your own company where you can be everything and do everything.
> 88 votes

# Answer
It's important to understand that the hundred coders in a company will be *implementing* high-level designs, not *making* them. In design terms, you might get given a task like "design the graphic format to be used for all art assets" but you won't be given the task "design a way to encourage users to interact in groups of five to ten people". Or indeed be asked to design a solution to prettymuch any question from my list of basic MMORPG questions.

Game designers get to decide that stuff.

HOWEVER... don't think that being a game designer is all wonderful pie-in-the-sky imagineering, either. Most of it is research, math, data-mining, crunching numbers, and grunt work, and that work will be massively under-appreciated by almost everyone in the company. The advantage of this is that it's entirely possible your bosses will not know if you suck at it, because nobody knows what game designers really do.

An example I always give of why I could *not* be a game designer is that I had the joy of working with a good one: a guy called Ben Jans. He left the company I was working with to work for Lolapps as a game designer on a game called Ravenwood Fair. Notice how at that link, you don't see Ben Jans listed there: you see John Romero, Brenda Brathwaite and Dr Cat, all those three designers deservedly being massive heavyweights in the industry.

So, the way I heard the story, about thirdhand because Ben is too humble, is that shortly after Ben applyied to LolApps for the job, the company director went to the hiring manager and said "why are you hiring game designers? Why can't you just get the coders to design it?"

The hiring manager handed Ben's application to the Director, who read it, nodded, and walked out, never to ask that question again.

Ben got his acceptance letter the next day.

What was in that application? Design notes for two questlines for the game. Not just a high-level overview, but extremely low-level: character names, lines of dialog with perfect tone for the game (including hundreds of carefully-researched references to the lore of the game, and countless gamer in-jokes), carefully balanced quest rewards (in a Farmville style game where every single action gives some level of reward), carefully balanced task costs, and far more, and summing it all up with a list of all required assets for each quest (sounds and graphics for the characters and their environments; each questline using all existing features of the engine, but requiring one small extra piece of programming just to show that he understood the cost of doing things that the engine did not already do).

In my vague memory, I think one quest was "the dragons visit the player's island", starting with vague rumors that the dragons were coming, culminating in meeting a dragon and getting to hatch dragon eggs... I completely forget what the other is.

Both were exciting, engaging, and novel, taking the game in slightly new directions without violating either the lore or tone of the games, like the very best DLCs you see for games nowadays.

Now, what made me realize that I could never be a game designer is that in order to do this job, he would have to come up with a new questline, in that level of detail, at that level of novelty, *every single week*. I'm not sure I'd run out of ideas first, or would get bored to tears by the minutiae first.

Just like everyone has one novel in them, so every programmer has one or two good game ideas they'd love to try making someday. Some do make them. Some of those ideas do actually turn out to be both good and successful. But almost all are one-shot wonders.

Most people are scared to tell others their One Idea. Scared it might get stolen. True creatives have so many ideas, they don't care - they just shout their ideas from the rooftops and hope one of them takes root. Like the rantings of the madman in Sandman's Calliope made me realize that Niel Gaiman must have an infinite supply of ideas, so working with Ben Jans made me realize what you need to be a game designer.

A game designer needs to have amazing patience and attention to detail, yes: but *infinite* ideas.
> 74 votes

# Answer
At my previous job as a backend dev at a game studio, the programmers had very little input into the gameplay/mechanics of the game. Occasionally a game designer or UI/UX designer would ask me if something they wanted to do was feasible, but that was the extent of my input into the design of the game.

That was at a mid-size studio of around 40 people, at a small indie studio you would likely have much more input as a programmer.

Something to keep in mind is that at my former studio, there were somewhere between 10-15 programmers and **1** game designer. If you want to create games, please please think about your job prospects. If you stick with programming, you can create anything you want on your own time. As a game designer, you may or may not be able to build very much without a team behind you. Programming is also a more transferable skill, which is handy if you discover that making games for a living takes the fun out of it, or if you end up working for a studio that goes under (sadly not uncommon in such a hit-driven industry), or for any reason want to relocate to an area without a strong games industry.
> 10 votes

# Answer
I have worked on a big-name game officially as the AI programmer, in truth I didn't have that much interest in other design aspects but I had to analyze the game mechanics carefully and do an awful lot of play-testing in the process of implementing the AI. As such I ended up in a good position to critique design aspects. My suggestions on design were almost always well received and sometimes even implemented verbatim.

Dev teams are usually, well, teams, and everyone ultimately works together. If you're smart enough to be on the team, you're also smart enough for your opinion to be taken seriously even in areas outside your official role.
> 9 votes

# Answer
A title is just a title so it will vary from company to company, but usually a game designer does a lot of scripting of events/quests etc. and if you are hired on as a straight up programmer it is very unlikely that you will have any input into the game design.

In short being a programmer for a game company is not much different from other places, while being a game designer means you will design games but will usually also have to know a decent amount about coding or at least scripting.
> 4 votes

# Answer
As the other answers have pointed out, this will vary from company to company, but I need to point out something about the video game industry, something that it has in common with all other branches of the entertainment industry.

In short, game design is the "fun" part, so the people in charge, and the people that have paid their dues, tend to monopolize it. People with less experience, or less seniority, tend to see their attempted contributions dismissed out of hand.

Compounding this, so many people think they want to work in the video-game industry, and the people in charge know this, so they have little motivation to treat newcomers kindly, since they are so easily replaced. So don't expect to successfully call them out on their exclusive behavior.

There are other nasty truths in the video-game industry, such as long hours, emotionally immature peers, and video-game consoles that are toys in more than one sense of the word, but they're beyond the scope of an answer to your question. The bottom line for me is, I'm glad to no longer work in the video-game industry, and never want to go back.
> 4 votes

# Answer
Firstly make sure you take a course that gives you fundamentals of Computer Science. IT generally means focus on business and information systems. I interview programmers a lot and we tend to ask a lot of questions about algorithms and data structures as well as the principles of OOP and Functional Programming. This would be in addition to making sure you can program, or can demonstrate the ability to learn quickly.

> My question is: does a game programmer get involved in the game designing process or is that only the game designer's job? Is a game designer always needed or can programmers work on game design some of the time?

As others have said it depends. If you work on gameplay (game features, animation, AI) then you will almost certainly be involved in game design. If you're not then you will be less effective in your job and have less fun. The best experiences I had were when a small group of people with multiple skills get together to implement something. For example a game designer, animator and a programmer may work on some new combat move. Each person has their own perspective on the feature. The game designer will explain how this works in other games, why it will be fun in our game as well as what the tuning parameters will be. The animator will need to know what animations are needed and how they will fit together. The programmer needs to explain how they will implement the feature and let the team know of any performance issues or technical challenges. When a team works together like this, that's when magic happens. In an environment where people are protective of their jobs and don't let anyone else give them feedback, nobody can grow and the quality of work is lower.

> Do programmers need to have game designing knowledge or do they just follow orders? Similarly, do game designers require programming knowledge?

It's important to play a lot of games. Especially the ones your company made before, and games in the same genre. Game designers spend a lot of time studying and playing other games. If you don't know what they're talking about then that makes things take longer. It's also more fun to work on a game if you know what you are making. However there is a lot of skill and domain knowledge that game designers need to do their jobs, and as a programmer you don't necessarily need that.

> I'm kind of confused over what I want to be which is why I'm asking here. Basically, do game programmers also get to be game designers?

Yes. To different extents all programmers are also game designers. Game designers do not need to know anything about programming but if they do it helps them understand when a programmer is telling them that some feature is too complex to implement in the time available, or will take up too much memory and so on.

In my experience of the years I've worked on a 200+ team at EA where I got very little input into the game design (but I was a graphics programmer anyway), and on a 60-70 person team at Activision making movie licensed games where I was very involved in the game design.

My current role is on a 30 person team and everybody is deeply involved in the game design as well as their own role.
> 3 votes

---
Tags: game-industry
---


# Question
Title: Getting an Object From a List (Unity C#)
So in Unity I'm making Snake, and to do that I've a list which houses all the tail elements from the Snake (this was implemented by the NoobTuts tutorial on snake just FYI).

I'm find with adding stuff and removing stuff from the list, HOWEVER, I do have an issue with part of the removal.

When I remove an object from the list it's still in the scene, it's just not acting with the rest of the objects still in the list. All I need to do, is just destroy that object.

I'm not sure if you can destroy an object in a list, or if that'll cause an issue, so I've been trying to set a gameobject to the value at the end of the list. However all list methods seem to just return the bloody index value, not the value in the index!

I've had a look through MSDN but can't understand parts of it.

Here's what I have:

```
else if (ateslow)
    {
        tailExcess = tail.Count - 1;

        //tail.IndexOf(tail.Count - 1);
        tail.RemoveAt(tail.Count-1);
        ateslow = false;
        if (snakeSpeed < minSnakeSpeed)
            snakeSpeed += 0.0f;
    }

```

So I play on having tailExcess equal the last element in the list, then I plan on destroying tailExcess after having it popped from the list. The rest below that doesn't matter.

What am I missing?

# Answer
> 0 votes
Lists in C# support lookup by indexing (like with arrays). In MSDN documentation on the indexing is typically under a property called Item\[\<.index type\>\].

So you can get items in a list by index like this:

```
var lastIndex = tail.Count - 1;
var tailExcess = tail[lastIndex];

```

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


title: How to play animations in Cocos2d-x?

text:
# Question
Title: How to play animations in Cocos2d-x?
I'm new to Cocos2d-x and looking for a good way/tutorial on how to play animations in Cocos2d-x.

# Answer
Sprite animation is pretty simple. You just create a `CCAnimation` node, add the images to loop, then create an action using `CCAnimate::actionWithDuration(float, CCAnimation, bool)` and make the sprite run it.

**Example:**

```
CCAnimation * anim = CCAnimation::animation();
// There are other several ways of storing + adding frames,
// this is the most basic using one image per frame.
anim->addFrameWithFileName("bear1.png");
anim->addFrameWithFileName("bear2.png");
anim->addFrameWithFileName("bear3.png");
anim->addFrameWithFileName("bear4.png");
anim->addFrameWithFileName("bear5.png");
anim->addFrameWithFileName("bear6.png");
anim->addFrameWithFileName("bear7.png");
anim->addFrameWithFileName("bear8.png");

CCAnimate *theAnim = CCAnimate::actionWithDuration(1.8f,anim,true);
// Duration, animation action and bool to return to frame 1 after finishing.

CCSprite *bear = CCSprite::spriteWithFile("bear1.png");
addChild(bear,0); //Don't forget to add any sprite you use as a child to the CCLayer!
bear->runAction(theAnim);

```
> 9 votes

# Answer
In new version of CoCos2dx (2.1.1) you can use (it's working)

```
CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
cache->addSpriteFramesWithFile("numbers.plist","numbers.png");

CCSprite* sprite = CCSprite::createWithSpriteFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("slice2_0_0.png"));
sprite->setPosition(ccp(GameScene::windowSize.width/2,GameScene::windowSize.height/3));

CCSpriteBatchNode* spriteBatchNode = CCSpriteBatchNode::create("numbers.png");
spriteBatchNode->addChild(sprite);
addChild(spriteBatchNode);

CCArray* animFrames = CCArray::createWithCapacity(10);

char str[100] = {0};
for(int i = 0; i < 10; ++i)
{
    sprintf(str, "slice2_0_%d.png", i);
    CCSpriteFrame* frame = cache->spriteFrameByName( str );
    animFrames->addObject(frame);
}
CCAnimation* animation = CCAnimation::createWithSpriteFrames(animFrames,1.f);
sprite->runAction(CCAnimate::create(animation) );

```
> 5 votes

# Answer
If you don't want to use a *.plist* file and want to continue with the Ef Es's answer with the current version of cocos2d-x, just change some lines as below:

```
    CCSprite * sprite  = CCSprite::create("bear1.png"); // NEW - create a sprite here
    CCAnimation * anim = CCAnimation::animation();
    // There are other several ways of storing + adding frames,
    // this is the most basic using one image per frame.
    anim->addSpriteFrameWithFileName("bear1.png");
    anim->addSpriteFrameWithFileName("bear2.png");
    anim->addSpriteFrameWithFileName("bear3.png");
    anim->addSpriteFrameWithFileName("bear4.png");
    anim->addSpriteFrameWithFileName("bear5.png");
    anim->addSpriteFrameWithFileName("bear6.png");
    anim->addSpriteFrameWithFileName("bear7.png");
    anim->addSpriteFrameWithFileName("bear8.png");

    anim->setLoops(-1); // for infinit loop animation
    anim->setDelayPerUnit(0.1f); //Duration per frame
    //CCAnimate *theAnim = CCAnimate::actionWithDuration(1.8f,anim,true); // this wont work in newer version..

    sprite->runAction(CCAnimate::create(anim) );
    sprite->setPosition(ccp(200,200)); //set position of sprite in some visible area

    this->addChild(sprite, 1); // cross check the Z index = 1 with your code

```

I think this can be the solution for Ben's question also.
> 2 votes

# Answer
For cocos2dx-v3, you'll need something like this:

```
auto cache = SpriteFrameCache::getInstance();
Vector<SpriteFrame*> frames = Vector<SpriteFrame*>();

frames.pushBack(cache->getSpriteFrameByName("open.png"));
frames.pushBack(cache->getSpriteFrameByName("closed.png"));
frames.pushBack(cache->getSpriteFrameByName("closed.png"));
cocos2d::Animation* anim = cocos2d::Animation::createWithSpriteFrames(frames, 0.1f, 1);

cocos2d::Animate* anim_action = cocos2d::Animate::create(anim);
//sprite is already added to scene elsewhere and ready to go
this->sprite->runAction(RepeatForever::create(anim_action));

```

Wasn't able to get any other way going. You're also able to re-add the same frames over and over again to introduce a pause, but I'm sure there's another way of doing that too.
> 0 votes

---
Tags: c++, animation, cocos2d-x
---


# Question
Title: How to tell if a fixture is being squeezed by two other fixtures in Box2D?
Let's say I had a ground fixture, a player box, and a kinematic block moving up and down. If the player stands under the block, weird things happen. I want to simply play an event where the player dies. How can I detect when the player box is crushed by the block moving down on it?

# Answer
I use this trick in libGDX:

* Add a "hidden" box, slightly smaller than your "crusher" box.
* Align the center of the "hidden" box with the center of "crusher" box (this includes movement).
* Place custom data in the "hidden" body using Body#setUserData(), indicating that is a 'destroyer box'. You can access this UserData from inside the ContactListener.
* Detect any colission between the "player" box and the "hidden" box marked as 'destroyer' in with your UserData, so you can call a 'destruction' method.

It's common for Box2D to leave a dynamic body locked and overlapping kinematic bodies when the dynamic one can't move in any other direction. In this case, the dynamic body can collide with the "inner" box, otherwise impossible to reach.

This could vary according on your restitution and friction values.
> 1 votes

---
Tags: box2d
---


# Question
Title: In a simple raycasting engine, why is the distance between player and projection plane constant?
According to this article about making a simple raycasting engine (like the one that was used in Wolfenstein3d), the distance between the player and the projection plane will be constant.

For example, suppose we are using a projection plane of dimension 320 X 200, and player's field of view (fov) is 60 degrees. Then the distance from the player to the projection plane is going to be

*160 / tan(30 degrees) = 277 units*

I can understand the trigonometry, but I can't understand why would the distance remain constant througout the game? Why wouldn't the distance change when the player moves closer or farther away from the projection plane?

# Answer
> 1 votes
It would change if the player moved closer or farther away from the projection plane (I can image you could still do that for some special effects though). However, he does not.
You can think of it this way: your eye is the player(camera) and your computer screen a window(projection plane) into the games world - naturally this distance is constant. When you walk in-game, you do not move the player but actually move the world in opposite direction.

---
Tags: game-mechanics, raycasting
---


title: Java 2D Lighting

text:
# Question
Title: Java 2D Lighting
Edit- ive noticed that the issue is caused when drawing to a bufferedimage

I've been struggling to create 2D lighting in my 2D sandbox game. I've been reading through multiple threads and have tried many things, heres a list:

* I've tried the method of creating an image of a light (instead of creating a radialgradient each time I want to make a light circle), but this gets very laggy the more I have or the bigger they get. I've tried downscaling the quality but then it just looks terrible, and I still have issues with lag. Also, it is very difficult to change color and other such things this way (since the image is already prebuilt at the start).

You can see the FPS already garbage after only a few lights placed down.

This code below is a much simplified version

```
public void makeLightMap(Graphics2D g)
{
    Graphics2D gl = light.createGraphics();
    gl.setColor(new Color(0, 0, 0, 255));
    gl.fillRect(0, 0, Handler.width,Handler.height);
    gl.setColor(new Color(0, 0, 0, 255));

       Composite oldComp = gl.getComposite();
       for(int i = 0; i < lights.size(); i++)
       {
            Point2D.Double pt = new Point2D.Double(lights.get(i).x,     lights.get(i).y);
             int radius = 500;
              gl.setComposite(AlphaComposite.DstIn);
              gl.drawImage(lightImage, (int) pt.x, (int) pt.y, radius * 1, radius * 1, null);
       }

gl.setComposite(oldComp);
gl.dispose();

}

```
* I've also tried to draw directly onto my JFrame (instead of drawing it to a bufferedimage than drawing it onto the Jframe), which would remove this lag, but I could not get this to work.
* I've also heard about doing it per pixel like in Notch's Left4KDead, but I heard this was very inefficient so I decided not to bother.

So, is there any way I could have it so I have lots of lights on the screen, some moving around, without lag and with the quality of gradient that I have now? Any help would be appreciated! PS: I would really like to avoid rough lighting, such as seen in this \[post\]\[2\]

**----edit 2----**

I've narrowed the issue to drawing on bufferedimages ( which seems to create this lag).
In this picture, you can see I'm drawing 500 images of dirt(32x32 png image) directly onto my frame (the brown line extending from the top left to the bottom left), and getting normal FPS. Code:

```
//I call super.paintComponent(g);   at the beginning
for(int i = 0; i < 500; i++)
    {
        g.drawImage(Sources.DIRT, 0 + i, 0 + i, 100, 100, null);
    }

```

---

However, if I attempt to draw the same 500 images on the bufferedimages, I start to lag (30 - 40fps) C

```
 BufferedImage bufferedimage = new BufferedImage(Screen.width, Screen.height, BufferedImage.TYPE_INT_ARGB);
    public void render(Graphics2D g)
    {
        BufferedImageLag()
        g.drawImage(bufferedimage, 0, 0, null);
    public void BufferedImageLag()
    {
        Graphics2D g = bufferedimage.createGraphics();
        for(int i = 0; i < 500; i++)
        {
            g.drawImage(Sources.DIRT, 0 + i, 0 + i, 100, 100, null);
        }
        g.dispose();
    }

```

Now of course I wouldn't being doing something like this in my game, but I beleive you should be able to copy paste this into a simple program and get the same effect (not sure how you'd get fps, but you could look at task manager and see how much cpu java is eating up).

# Answer
> 4 votes
This may not be a perfectly satisfactory answer, but: Modifying a `BufferedImage` in the main memory and uploading it to the video memory in each frame simply causes a considerable performance impact.

I created the following MCVE to reproduce the issue: It allows switching between the "direct" painting, an the painting that uses an intermediate `BufferedImage`

**Note that some parts of this test are rather crude, and should/would not be done like this in "real" application code. This is really only to reproduce the issue:**

```
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Locale;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;

public class BufferedImageLags
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI()
    {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        f.getContentPane().setLayout(new BorderLayout());

        final BufferedImageLagsPanel p = new BufferedImageLagsPanel();
        f.getContentPane().add(p, BorderLayout.CENTER);

        final JToggleButton tb = new JToggleButton("Draw direct");
        tb.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                p.setDrawDirect(tb.isSelected());
                p.drawImagesToMainImage();
            }
        });
        f.getContentPane().add(tb, BorderLayout.SOUTH);

        Thread t = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                while (true)
                {
                    // Brutally flood the system with paint events.
                    // DON'T DO THIS IN PRODUCTION CODE!!!
                    p.repaint();
                }
            }
        });
        t.setDaemon(true);
        t.start();

        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
}

class SimplePerformanceMeasure
{
    private static long startNs;
    private static long endNs;
    private static Deque<Long> durationsNs = new LinkedList<Long>();
    private static int averaging = 20;
    private static int counter = 0;

    static void startFrame()
    {
        startNs = System.nanoTime();
    }

    static void endFrame()
    {
        endNs = System.nanoTime();
        long durationNs = endNs - startNs;
        durationsNs.addLast(durationNs);
        while (durationsNs.size() > averaging)
        {
            durationsNs.removeFirst();
        }
        counter++;
        if ((counter % averaging) == 0)
        {
            long sumNs = 0;
            for (long ns : durationsNs)
            {
                sumNs += ns;
            }
            double averageMs = (double)sumNs / durationsNs.size() / 1e6;
            System.out.printf(Locale.ENGLISH,
                "Average time was %5.3fms\n", averageMs);
        }
    }
}

class BufferedImageLagsPanel extends JPanel
{
    private final int w = 800;
    private final int h = 800;
    private boolean drawDirect = false;

    private final BufferedImage mainImage =
        new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);

    private final BufferedImage tileImage =
        new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);

    public BufferedImageLagsPanel()
    {
        Graphics2D g = tileImage.createGraphics();
        g.setColor(Color.BLACK);
        g.drawLine(0, 0, 32, 32);
        g.drawLine(0, 32, 32, 0);
        g.dispose();
    }

    public void drawImagesToMainImage()
    {
        Graphics2D ig = mainImage.createGraphics();
        drawImages(ig);
        ig.dispose();
    }

    public void setDrawDirect(boolean drawDirect)
    {
        this.drawDirect = drawDirect;
    }

    @Override
    protected void paintComponent(Graphics gr)
    {
        super.paintComponent(gr);
        Graphics2D g = (Graphics2D)gr;
        render(g);
    }

    public void render(Graphics2D g)
    {
        SimplePerformanceMeasure.startFrame();

        if (drawDirect)
        {
            drawImages(g);
        }
        else
        {
            drawImagesToMainImage();
            g.drawImage(mainImage, 0, 0, null);
        }

        SimplePerformanceMeasure.endFrame();
    }

    private void drawImages(Graphics2D g)
    {
        for (int i = 0; i < 500; i++)
        {
            g.drawImage(tileImage, 0 + i, 0 + i, null);
        }
    }

    @Override
    public Dimension getPreferredSize()
    {
        return new Dimension(w, h);
    }
}

```

It can be seen that the time for painting is much higher when going through the `BufferedImage` path.

---

Side note: Notice that I used

```
g.drawImage(tileImage, 0 + i, 0 + i, null);

```

which draws the tiles in their original size of 32x32 pixels. Your call,

```
g.drawImage(tileImage, 0 + i, 0 + i, 100, 100, null);

```

caused the image to be scaled each time it was painted. **This scaling alone can decrease performance dramatically!** If possible, you should create the images in the size in which you want to paint them. In doubt, you can always create a scaled version of the original image once, in the constructor, and then use the first version of the `drawImage` call, to directly draw the scaled image.

---

Admittedly, although I already worked a bit with Swing and `BufferedImage`, I was not aware of the fact that the performance impact of updating a `BufferedImage` before painting it could be **so** significant for this particular application pattern. Until now, I only considered using such an "offscreen" image for the case where painting the image contents was expensive, but the image itself changed rarely. And then, it will of course bring a speedup. I did not yet have the case where the image had to be updated in each frame.

However, the usual recommendation in this case is to use a `VolatileImage`. It allows hardware-accelerated rendering and can achieve a higher performance. This higher performance comes at the price of being a bit more fiddly to use.

In the following example, I converted the MCVE from above so that it uses a `VolatileImage`. For convenience, I wrapped this into a `VolatileImageHandle` class that basically encapsulates the two most important functionalities:

* It receives a `Consumer<Graphics2D>` in the constructor. This is the function that will be used to fill the image with the desired content. In your case (and this example), it just draws the 500 tile images
* It offers a `draw` method, to draw the volatile image into a `Graphics2D`

The bookkeping of checking the volatile image against the graphics configuration is hidden here, which simplifies stuff a bit.

```
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.VolatileImage;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Locale;
import java.util.function.Consumer;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class VolatileImageNoLags
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI()
    {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        f.getContentPane().setLayout(new BorderLayout());

        final VolatileImageNoLagsPanel p = new VolatileImageNoLagsPanel();
        f.getContentPane().add(p, BorderLayout.CENTER);

        Thread t = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                while (true)
                {
                    // Brutally flood the system with paint events.
                    // DON'T DO THIS IN PRODUCTION CODE!!!
                    p.repaint();
                }
            }
        });
        t.setDaemon(true);
        t.start();

        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
}

class SimplePerformanceMeasure
{
    private static long startNs;
    private static long endNs;
    private static Deque<Long> durationsNs = new LinkedList<Long>();
    private static int averaging = 20;
    private static int counter = 0;

    static void startFrame()
    {
        startNs = System.nanoTime();
    }

    static void endFrame()
    {
        endNs = System.nanoTime();
        long durationNs = endNs - startNs;
        durationsNs.addLast(durationNs);
        while (durationsNs.size() > averaging)
        {
            durationsNs.removeFirst();
        }
        counter++;
        if ((counter % averaging) == 0)
        {
            long sumNs = 0;
            for (long ns : durationsNs)
            {
                sumNs += ns;
            }
            double averageMs = (double)sumNs / durationsNs.size() / 1e6;
            System.out.printf(Locale.ENGLISH,
                "Average time was %5.3fms\n", averageMs);
        }
    }
}

class VolatileImageHandle
{
    private VolatileImage image;
    private final Component component;
    private final int width;
    private final int height;
    private final boolean transparent;
    private Consumer<? super Graphics2D> painter;

    VolatileImageHandle(Component component,
        int width, int height, boolean transparent,
        Consumer<? super Graphics2D> painter)
    {
        this.component = component;
        this.width = width;
        this.height = height;
        this.transparent = transparent;
        this.painter = painter;
    }

    private void createImage()
    {
        GraphicsConfiguration graphicsConfiguration =
            component.getGraphicsConfiguration();
        int transparency = transparent ?
            Transparency.TRANSLUCENT : Transparency.OPAQUE;
        image = graphicsConfiguration.createCompatibleVolatileImage(
            width, height, transparency);
    }

    private void validateImage()
    {
        if (image == null)
        {
            createImage();
        }
        else
        {
            GraphicsConfiguration graphicsConfiguration =
                component.getGraphicsConfiguration();
            int validationResult =
                image.validate(graphicsConfiguration);
            if (validationResult == VolatileImage.IMAGE_INCOMPATIBLE)
            {
                image.flush();
                createImage();
            }
        }
    }

    private void updateImage()
    {
        do
        {
            validateImage();
            Graphics2D g = image.createGraphics();
            painter.accept(g);
            g.dispose();
        } while (image.contentsLost());
    }

    public void draw(Graphics2D g, int x, int y)
    {
        do
        {
            validateImage();
            updateImage();
            g.drawImage(image, x, y, null);
        } while (image.contentsLost());
    }
}

class VolatileImageNoLagsPanel extends JPanel
{
    private final int w = 800;
    private final int h = 800;
    private boolean drawDirect = false;

    private final VolatileImageHandle mainImage =
        new VolatileImageHandle(this, w, h, true, this::drawImages);

    private final BufferedImage tileImage =
        new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);

    public VolatileImageNoLagsPanel()
    {
        Graphics2D g = tileImage.createGraphics();
        g.setColor(Color.BLACK);
        g.drawLine(0, 0, 32, 32);
        g.drawLine(0, 32, 32, 0);
        g.dispose();
    }

    public void setDrawDirect(boolean drawDirect)
    {
        this.drawDirect = drawDirect;
    }

    @Override
    protected void paintComponent(Graphics gr)
    {
        super.paintComponent(gr);
        Graphics2D g = (Graphics2D)gr;
        render(g);
    }

    public void render(Graphics2D g)
    {
        SimplePerformanceMeasure.startFrame();

        mainImage.draw(g, 0, 0);

        SimplePerformanceMeasure.endFrame();
    }

    private void drawImages(Graphics2D g)
    {
        for (int i = 0; i < 500; i++)
        {
            g.drawImage(tileImage, 0 + i, 0 + i, null);
        }
    }

    @Override
    public Dimension getPreferredSize()
    {
        return new Dimension(w, h);
    }
}

```

The increase of performance (on my machine) is remarkable. Again, this performance test is questionable in some ways, but the *rough* time measures show that in the original version, it took ~25ms to update and paint the image, and in the version that uses the volatile image, this decreased to less than 1 millisecond. YMMV.

# Answer
> 1 votes
My solution is actual not to different from yours. First start by creating a black image the size of the screen that we will call the light map and on it you will draw all of the lights. After all the lights have been drawn on the light map you will draw the light map on top of your scene.

Each light will be just a bunch of overlapping circles that all have the same center, but each one's radius is smaller than the last one's. But instead of simply setting the color of the pixels that the light affects, you will subtract the luminosity of the pixels from their alpha value.

In that way the closer a pixel is to a light, the the more transparent it becomes. Thus since we are drawing the light map above the scene, the more transparent the pixel is, the more of the scene will be visible.

Light map:

```
private BufferedImage lightMap = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

```

Light:

```
private BufferedImage image;
private int x;
private int y;

public Light(int x, int y, int radius, float luminosity) {
    //Recommended luminosity between 1 and 2
    this.x = x;
    this.y = y;
    image = new BufferedImage(radius * 2, radius * 2, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = (Graphics2D) image.getGraphics();

    for(int i = 0; i < radius; i++) {
        double luma = 1.0D - ((i + 0.001) / radius);
        int alpha = Math.min((int)(255.0D * luma * luminosity), 255);
        g2.setColor(new Color(0, 0, 0, alpha));
        g2.setStroke(new BasicStroke(2));
        g2.drawOval(radius - i, radius - i, i * 2, i * 2);
    }
}

public void render(Graphics2D g2) {
    g2.drawImage(image, x - image.getWidth() / 2, y - image.getHeight() / 2, image.getWidth(), image.getHeight(), null);
}

```

Light Rendering:

```
private ArrayList<Light> lights = new ArrayList<Light>();

public void makeLightMap(BufferedImage lightMap) {
   Graphics2D gl = lightMap.createGraphics();
   gl.setColor(new Color(0, 0, 0, 255));
   gl.fillRect(0, 0, getWidth(), getHeight());
   Composite oldComp = gl.getComposite();
   gl.setComposite(AlphaComposite.DstOut);

   for(Light light : lights) light.render(gl);

   gl.setComposite(oldComp);
   gl.dispose();
}

```

---
Tags: java, 2d, graphics, lighting
---


# Question
Title: Why is the code in this if statement being run when the condition for it is not met?
I have a feeling I'm overlooking something stupid here...

By default all of my enemy objects start without a target assigned to them. As in - "target = noone;"

However, despite target being undefined I'm still erroring out from things being erroneously run inside of a code block that should only run if the enemy object has a target.

I have the if statement...

```
if(target != noone)

```

and have even tried...

```
if(!is_undefined(target))

```

... and in both cases there are lines being run that will cause my program to crash. Such as checking the distance between the target, turning to face the target, etc. All of these lines should never be getting run since they are within a block of code that should only run if the if statement check shows there is actually a target.

The entire code block is...

```
// If there is a target...
if(!is_undefined(target))
//if(target != noone)
    {

    // TARGET CONDITION CHECKS

    // Check the distance to target.
    var tdist = distance_to_object(target)

    // Check if it is within firing range...
    if(tdist < range_actual) then target_in_range = true else target_in_range = false;

    // Check the difference in angles between the turret and its target
    var pd = point_direction(x, y, target.x, target.y);
    var dd = angle_difference(direction, pd);

    // Check if the (absolute value of the) angle difference is within the weapons tolerance enough for the target to be considered within the firing arc of the weapon.
    if(abs(dd) < angle_tolerance) then target_in_firing_arc = true else target_in_firing_arc = false;

    //Rotate towards target using the above angle difference (dd)
    direction -= min(abs(dd), rotation_speed) * sign(dd);

    // If the target is within firing range...
    // If they are also within the firing arc, and not reloading, then tell the weapon to start firing.
    if(target_in_range = true && target_in_firing_arc && status != "reloading")
        {
            {
            status = "firing"
            }
        }

    // If the target isn't in range then start hoofing it them.
    if(!target_in_range)
        {
        speed += acceleration;
        if(speed > max_speed) then speed = max_speed;

        xPos = x + lengthdir_x(speed, direction);
        yPos = y + lengthdir_x(speed, direction);
        if(place_meeting(xPos, yPos, obj_Col_Parent) && instance_place(xPos, yPos, obj_Col_Parent) != id) then speed = 0;
        if(place_meeting(xPos, yPos, obj_player)) then speed = 0;
        }
    else    // If they are in range then start to come to a stop.
        {
        if(point_distance(x, y, target.x, target.y) < range_actual / 2)
            {
            speed -= braking;
            if(speed < 0) then speed = 0;
            }
        }
    }

```

When using "if(target != noone)" to start my if statement block it will error out on line 87 which is "var tdist = distance\_to\_object(target)" and if I instead start the if statement with "if(!is\_undefined(target))" then it will get just a bit further and error out on line 93 which is "var pd = point\_direction(x, y, target.x, target.y);"

Anyone out there see what exactly I'm doing wrong?

I can't figure out why any lines of code in that if statement would ever be getting run since there isn't a target set and as such everything in that if statement should be entirely skipped over. Its kinda driving me nuts.

UPDATE: Alright. As per request, here is the code relevant to targets being assigned.

In the Create Event the target is assigned to noone / undefined with...

```
target = noone; // The id of the enemy instance this weapon is aiming at.

```

In the Step Event a potential target, assuming one exists, is checked for with...

```
// Check if the target still exists and if not then reset target to the default 'noone'
if(target != noone && !instance_exists(target)) then target = noone;

// If there isn't currently a target being aimed at or the weapon is idle then set the target as random or nearest player piece.
if(target == noone && object_exists(obj_player))
    {
    if(targetting_method = "random")
        {
        var randtarg = irandom_range(0, ds_list_size(global.segment_list) - 1);
        target = ds_list_find_value(global.segment_list, randtarg);
        }
    if(targetting_method = "nearest")
        {
        target = instance_nearest(x, y, obj_player);
        }
    }

```

Using the debugger while running the program shows the enemy objects target variable as "undefined". So, at least according to the debugger, the target is correctly assigned to noone / undefined at the time the program crashes out by running the code inside that if statement block that should only be run in the event there actually is a target.

UPDATE 2: I had initially stated, just above actually, that the debugger correctly shows my target variable being assigned as "undefined" / noone. This was a mistake on my part and is incorrect.

Its true that with the specific obj\_soldier that the game crashed on was showing target as holding the value "undefined". However "undefined" is NOT equal to "noone".

The Gamemaker manual lists that noone is the value of -4 so when you set a variable to hold the value of noone its simply being set to hold -4. So, my obj\_soldier having a target of "undefined" means it wasn't properly set as noone.

Since "undefined" is literally not assignment when my if statement tries to check if "target != noone" it passes the if statement check because "undefined" isn't -4. Which causes my if statement to continue on and try to run its checks for when there is actually a target and the end result is that my program tries to do calculations involving "undefined", such as trying to check the obj\_soldiers distance to "undefined" which results in a rather expected crash.

Through experimenting I've found that the first obj\_soldier I create is correct and works fine. For them target is correctly noone (-4) and they don't crash the game when that if statement runs its check. This occurs whether I place them directly in the room or create them via code.

My second obj\_soldier that is created however, doesn't have target assigned correctly and it ends up showing in the debugger as "undefined". When the if statement check occurs they erroneously pass the check and then cause the program to crash doing impossible calculations. This occurs whether the second soldier is placed in the room directly or created via code.

Interestingly, all obj\_soldiers after the second work fine and have target correctly noone (-4) just like the first obj\_soldier. Place directly or created via code doesn't matter.

For example, if I place or create with code 30 soldiers (which I did several times as a test) the game crashes and in the debugger the second soldier has target with a value of "undefined" while the first and third through thirtieth soldiers have their target shown as holding "-4" which is correct for an assignment of noone.

Aside from the possibility of this issue being a problem with Gamemaker itself, which I've contacted YoYo Games about and am awaiting a response, I can't really track down a reason for it to be occurring.

All of my obj\_soldiers should be identical. They are call just instances of that one object and there should be no exceptions to setting "target = noone" for any of them.

I've even gone so far as to try forcibly reseting target to noone at the time of creation by storing obj\_soldier in a variable at the time of creation and using "with" to set "target = noone" for each one.

The only workaround I've found is to immediately before my if statement of "if(target != noone)" is run to have this line "if(is\_undefined(target)) then target = noone" to ensure that if the value of target is "undefined" it is forced to being noone just before running the check.

While that workaround avoids the crash it doesn't solve the issue of why setting to noone can sometimes result in a value of "undefined" instead of the correct -4 though.

# Answer
> 1 votes
`is_undefined()` is wrong for this case. It can be used, as example, for `ds_map` functions, but not for an undefined variable (or varibale which equal `noone`). There must be used `if target != noone and instance_exists(target) { actions with target }`.

If your `if(target != noone && !instance_exists(target)) then target = noone;` and actions with target is placed in different events then you need to add check for sure that instance still exists. Because instance can be destroyed between these events.

```
// If there is a target...
if target != noone and instance_exists(target)
{
    // TARGET CONDITION CHECKS

    // Check the distance to target.
    var tdist = distance_to_object(target);

    // Check if it is within firing range...
    var target_in_range = (tdist < range_actual);

    // Check the difference in angles between the turret and its target
    var pd = point_direction(x, y, target.x, target.y);
    var dd = angle_difference(direction, pd);

    // Check if the (absolute value of the) angle difference is within the weapons tolerance enough for the target to be considered within the firing arc of the weapon.
    var target_in_firing_arc = (abs(dd) < angle_tolerance);

    //Rotate towards target using the above angle difference (dd)
    direction -= min(abs(dd), rotation_speed) * sign(dd);

    // If the target is within firing range...
    // If they are also within the firing arc, and not reloading, then tell the weapon to start firing.
    if target_in_range and target_in_firing_arc and status != "reloading"
    {
        status = "firing";
    }

    // If the target isn't in range then start hoofing it them.
    if !target_in_range
    {
        speed += acceleration;
        speed = min(speed, max_speed);

        xPos = x + lengthdir_x(speed, direction);
        yPos = y + lengthdir_x(speed, direction);
        if (place_meeting(xPos, yPos, obj_Col_Parent) and instance_place(xPos, yPos, obj_Col_Parent) != id)
        or (place_meeting(xPos, yPos, obj_player))
            speed = 0;
    }
    else    // If they are in range then start to come to a stop.
    {
        if point_distance(x, y, target.x, target.y) < range_actual / 2
        {
            speed -= braking;
            speed = max(0, speed);
        }
    }
}
else if target != noone
    target = noone;

```

And for `targetting_method` better will be use `switch` statement:

```
// Check if the target still exists and if not then reset target to the default 'noone'
if target != noone and !instance_exists(target)) target = noone;

// If there isn't currently a target being aimed at or the weapon is idle then set the target as random or nearest player piece.
if target == noone and object_exists(obj_player)
{
    switch targetting_method
    {
        case "random":
            var randtarg = irandom_range(0, ds_list_size(global.segment_list) - 1);
            target = ds_list_find_value(global.segment_list, randtarg);
            break;
        case "nearest":
            target = instance_nearest(x, y, obj_player);
            break;
    }
}

```

Instead strings (`"firing"`, `"reloading"`, etc) use macros. For example, define macros: `STATE_FIRING` as `0`, `STATE_RELOADING` as `1` and `TARGETTING_RANDOM` as `0`, `TARGETTING_NEAREST` as `1`, then use it in code:

```
switch targetting_method
{
    case TARGETTING_RANDOM:
        var randtarg = irandom_range(0, ds_list_size(global.segment_list) - 1);
        target = ds_list_find_value(global.segment_list, randtarg);
        break;
    case TARGETTING_NEAREST:
        target = instance_nearest(x, y, obj_player);
        break;
}

```

When you use strings, you may easy get typo, etc, and code will work wrong (but it won't show any error messages in most cases). Also autocomplete will be available for all macros - you don't need remember all exact names, etc. You will write more fast and without errors.

---
Tags: game-maker, logic
---


# Question
Title: Unity Editor: Get Mouse coordinates on left click on Scene Editor
I need a simple script which does the following:

When I left-click somewhere in the Editor-Scene:

(doesnt matter if there is an object under the cursor- or not)

Do NOT deselect the current selection in the Inspector. Do not select the object under the cursor. and

## Just print the mouse X and Z interception with the Y-Plane in the Debug.Log();

i stumbled on many solutions but somehow i couldnt get this to work.

i tried:

HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));

and

Tools.current = Tool.None;

both seem to do nothing ..... X.x

EDIT:

Happens that "HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));" needs to be inside: public void OnSceneGUI() and called every frame - to "block" the mouse clicks on the editor. i thought it toggles it off.

still the problem of the mouse coordinates persists.

# Answer
> 0 votes
I solved my little problem. This is the solution I came up with:

```
Ray ray;
RaycastHit hit;

ray = Camera.current.ScreenPointToRay(new Vector3(Event.current.mousePosition.x, SceneView.currentDrawingSceneView.camera.pixelHeight - Event.current.mousePosition.y));

if (Physics.Raycast(ray, out hit))
{
    x1 = Input.mousePosition.x;
    y1 = Input.mousePosition.y;
    z1 = Input.mousePosition.z;
    x2 = hit.point.x;
    y2 = 0;
    z2 = hit.point.z;
}

```

This script gets the mouse coordinates on the y-plane if there is a collider on the y-plane.

x2,x2,z2 are the result coordinates.

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


# Question
Title: 1 Texture For Multiple Models, Or 1 Model Using Different Textures For Each
I'm creating some voxel flowers that are exactly the same, just different colours. Is it better to create 5 models and use 1 texture that has the 5 different colours, or create 1 model and use 5 different textures for each colour?

Am curious as to which is more efficient in regards to performance, as there could be quite a few flowers on screen.

I'm playing around with MagicaVoxel and Unity.

# Answer
> 3 votes
You can use one model with one texture.

Create a separate material for each flower-type. Each material uses the same texture but has a different color in its properties. This will require a shader which applies the albedo color only to specific pixels of the texture. You would have to do some shader programming for this. When you aren't into shader programming and want to use the premade Unity shader instead, you can create a model with two materials. Use one material for the recolorable polygons and one for those which are not recolorable. You can then assign the Unity standard shader to both materials and set the albedo color on the material for the recolorable parts.

---
Tags: unity
---


# Question
Title: How to Replace two object by rotating in center
I created Find Rock game but I have problem In replacing two object by rotating in center and when rotating finish stop rotating how can I do this?

```
using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    public GameObject[] obj;
    public int[] Randomize = new int[2];

    void Start(){
        StartCoroutine (Delay ());

    }

    IEnumerator Delay(){
        Randomize [0] = Random.Range (0, obj.Length);
        Randomize [1] = Random.Range (0, obj.Length);
        while (Randomize [0] == Randomize [1]) {
        Randomize [0] = Random.Range (0, obj.Length);
        }
        yield return new WaitForSeconds (2);
        obj [Randomize [0]].transform.rotation = Quaternion.Euler (new Vector3 (0, 0, 0));
        obj [Randomize [1]].transform.rotation = Quaternion.Euler (new Vector3 (0, 0, 0));

        StartCoroutine (Delay ());
        }
    void Update(){
        if (obj [Randomize [0]].transform.rotation.eulerAngles.y < 90 || obj [Randomize [1]].transform.rotation.eulerAngles.y < 90) {
            obj [Randomize [0]].transform.RotateAround (obj [Randomize [1]].transform.position, Vector3.up, Time.deltaTime * 100);
            obj [Randomize [1]].transform.RotateAround (obj [Randomize [0]].transform.position, Vector3.up, Time.deltaTime * 100);
        }
    }
}

```

I can make this game but when rotating finish they aren't Directed.

How can I use mathf clamp RotateAround for stopping rotation?

# Answer
> 1 votes
Because of the discrete nature of time, the last rotation step you do ends up being too much. You have two options: (1) detect when you are doing the very last rotation update and make sure it's not too much, or (2) when your rotation is over, set the position/rotation of the objects to where they should be. I will describe (1) below:

```
void Update(){
    if (obj [Randomize [0]].transform.rotation.eulerAngles.y < 90 || obj [Randomize [1]].transform.rotation.eulerAngles.y < 90) {
        float angleToRotate = Time.deltaTime * 100;
        float angleRemaining = 90 - obj [Randomize [0]].transform.rotation.eulerAngles.y;
        if(angleRemaining < angleToRotate) {
            angleToRotate = angleRemaining;
        }
        obj [Randomize [0]].transform.RotateAround (obj [Randomize [1]].transform.position, Vector3.up, angleToRotate);
        obj [Randomize [1]].transform.RotateAround (obj [Randomize [0]].transform.position, Vector3.up, angleToRotate);
    }
}

```

This should prevent your boxes from moving too much and they should stay on a line.

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


title: Twitter in Unity

text:
# Question
Title: Twitter in Unity
I would like to talk to twitter through my unity game.

I found an library for .NET C# that could help, but I am not sure if this is the right way.... The repository for Tweetinvi is here: https://github.com/linvi/tweetinvi

I pulled the repository into a project and am getting +999 errors, mostly related to some strange missing libraries (Windows.UI.Core / Windows.UI.Xaml/ System.Threading.Tasks ....)

***My questions:***

1. For those with more Unity experience: does tweetinvi look like something that could be implemented well with the engine for a mobile game? (I know that not all libraries work for mobile, but don't know what the criteria is...)
2. Does anyone know another, more efficient and painless way to retrieve data from twitter in Unity? (Pseudocode, libraries, experience - any comments are welcome!)

Thank you

# Answer
Twitter offers a REST API which you can access using the `WWW` class. No additional libraries are required.

However, in order to use it you need to authenticate via OAuth and then include the OAuth headers in every request, which isn't that straight-forward.

There is a free packet on the Unity Asset Store named *Let's Tweet In Unity* which claims to take care of OAuth and offer a simple wrapper for the REST API, but I haven't used it, so I can't say if and how well it works.
> 5 votes

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


# Question
Title: Any good pattern for managing user input in XNA
I'm doing some experimentation on XNA, and unlike past experiences with XNA, I wanna do stuff right.

Are there any good patterns for managing user input?

Like... how do I manage what components get the input?

Is there anything like that? I feel like doing the normal - checking for state of a button and if-ing for every thing you need... It can't be that there isn't something more clever and well designed to do that.

I feel that the wheel has already been invented here, I just can't find it.

# Answer
> 1 votes
A common way is to have a controller base class. This can be an AI controller or just an input controller that is looking at gamepad or keyboard input.

In general adding an extra layer of abstraction makes sense. So you'd have inputs specific to your game, like jump, left, right, up, down, etc. This will allow you to do keybindings easily, since your game only needs to know about what the controller outputs.

The code you are describing in your post still has to run somewhere, but you can make it more comfortable to use.

If your question is about how to handle wether a menu or the player or whatever is currently handling the input. You can just have an Active switch inside things that use the input to turn them on or off.

Your question is pretty vague, so I'm not sure if this clears it up.

---
Tags: xna, xna-4.0, input
---


title: Frame Skips in MonoGame

text:
# Question
Title: Frame Skips in MonoGame
I'm developing a 2D game using MonoGame. I've got a square on the screen I can move around. The problem is that about once a second, the square jumps a bit. Using a frame counter I found here I've concluded that my FPS drops from 59.9988 to either 59.3988 or 59.6988. It's skipping frames.

I've tried googling and searching forums for hours but can't find a solution. I've commented out everything in the Draw method of the Game class except for the frame counter and it still happens. I even tried creating an entirely new MonoGame project with nothing in it except the frame counter and still I would get the frame skips.

Setting IsFixedTimeStep = true does not fix the issue. I do get higher frame rate, but also not as high as I would expect (not higher than ~100). I've looked at the diagnostic tools and there is no garbage collection going on (no yellow triangles).

I am completely at a loss. If anyone has any insights to offer, it would be much appreciated.

# Answer
> 2 votes
I guess your monitors refresh rate is about 100Hz. If you disable IsFixedTimeStep and SynchronizeWithVerticalRetrace you will probably see the FPS shoot up.

It's almost impossible that there is no garbage collection happening. I'd say run a profiling tool and check what if anything is being allocated every frame. You might find an issue in Monogame that can be fixed even.

The frame counter will allocate memory every frame as well since it is using String.Format to generate the message to print. It's certainly not a lot of memory though, probably around 1kb per second or something depending on your framerate.

---
Tags: c#, xna, monogame, first-person-shooter
---


# Question
Title: Targeting system, Vectors and Angles Maths
I need a bit of help with the maths for a targeting system for a space simulator. The problem is working out the correct turret angle so that the bullets hit the target ship...

I have a ship at location X, Y and the ship has turrets which can turn 360 degrees. I want to aim at an asteroid at location Xa, Ya.

The maths for this which is working great is like this....

```
VectorX = X - Xa
VectorY = Y - Ya

Angle = (57.2957795 * atan2(VectorX , -VectorY ))

```

Now consider the asteroid is moving at a velocity vector of Xsa, Ysa and the bullets fired from the turret have a speed.

The maths for this which again works really well is....

```
VectorX = X - Xa
VectorY = Y - Ya

Distance = sqrt((VectorX * VectorX) + (VectorY * VectorY))

VX = VectorX - (Xsa * (Distance / BulletSpeed));
VY = VectorY - (Ysa * (Distance / BulletSpeed));

Angle = (57.2957795 * atan2( VX, -VY )

```

Ok the bit I cant get to work right is when the ship is also moving, lets call this velocity vector Xs, Ys. When the ship is moving the bullets fire maintain the movement of the ship plus the bullet firing speed at the angle vector. Think of driving a car and shooting a bullet out the window the bullet would fire out sideways from the car but would also maintain the car's forward momentum as it traveled.

```
BulletVelX = Xs + ( BulletSpeed * cos( Radians( Angle ) ) )
BulletVelY = Ys + ( BulletSpeed * sin( Radians( Angle ) ) )

```

I have found a site that says simultaneous equasions could be used to solve the problem but has anyone working knowledge of how this is done.

Thanks

# Answer
> 0 votes
Your aiming routine seems problematic to begin with. I have no clue where 57.2957795 is coming from.

I guess your atan2 routine takes y as the first parameter not the second and so you needed a correction factor.

Your aiming at a moving target routine is also just an approximation and not the correct math. In order to work this out we will describe where your bullet could be at a given time by a circle and we will describe where the ship you are targeting will be with a line.

```
//Circles radius depending on t
r(t) = bulletSpeed*t;
//Enemy ships position depending on t
s(t) = (Xa,Ya) + t*(Xsa,Xya)
//We are really just interested in our relative distance though, so
//our distance from the ship at time t is
d(t) = length(s(t)-(X,Y))
//Now we want that distance to be the same as where our bullet can be at time t. So:
   r(t)=d(t)
<->r(t)^2 = d(t)^2
<->bulletSpeed^2*t^2=(s(t).X-X)^2+(s(t).Y-Y)^2
<->bulletSpeed^2*t^2=(Xa-X+t*Xsa)^2+(Ya-Y+t*Ysa)
<->bulletSpeed^2*t^2=(Xa-X)^2+2(Xa-X)*Xsa*t+t^2*Xsa^2+(Ya-Y)^2+2(Ya-Y)*Ysa*t+t^2*Ysa^2
//Now we can take a shortcut here and differentiate this,
//since we are looking for the minimum and it is geometrically clear
//That there is only one minimum if it exists.
<->2*bulletSpeed^2*t=2(Xa-X)*Xsa+2*t*Xsa^2+2*(Ya-Y)*Ysa+2*t*Ysa^2
<->2*bulletSpeed^2*t-2*t*Xsa^2-2*t*Ysa^2 = 2(Xa-X)*Xsa+2(Ya-Y)*Ysa
<->t*(2*bulletSpeed^2-2*Xsa^2-2*Ysa^2) = 2(Xa-X)*Xsa+2(Ya-Y)*Ysa
<->t = ((Xa-X)*Xsa+(Ya-Y)*Ysa)/(bulletSpeed^2-Xsa^2-Ysa^2)
//Now this tells you at what time your bullet and the target could collide
//(Unless I made a mistake in deriving this, which should be easy to check)
//So let's call the t that solves that equation t'.

//If you are moving relative to the thing you are shooting at, consider your own ship at rest.
//And subtract your velocity from the other ships velocity, so you get the relative velocity between both ships.
Xsa = Xsa-Xs
Ysa = Ysa-Ys

//Then
Diff = s(t')-(X,Y)
Angle = atan2(Diff.Y,Diff.X)

```

---
Tags: game-mechanics, angles
---


# Question
Title: Input and output of a server side game using web sockets
I am having a look at redeveloping an old flash based top-down zombie shooter game I made in highschool so that it supports multiplayer using `socket.io`. My experience over the last 5 years has been mostly writing server-side code, so writing the game logic itself on the server isn't a huge concern. The places I am having trouble with due to my very limited experience with *sockets* specifically is:

* What the most appropriate input and output should be to and from the server in a *game* context.
* How much data is appropriate to send.

Off the top of my head, I imagine the process would look something like:

* The server runs the game (using NodeJS).
* Clients that connect send their input to the server (key presses, clicks, etc).
* Those inputs are queued against the client ID on the server and interpreted to move their character or whatever it does.
* The server sends back the updated position of the client *as well as everything else around the client in the "world"*.

The last point is where I have the most doubts. Assuming a reasonable collection of objects in the world, I am not confident that sending through the position of everything every ~30ms to every client would be sustainable (though I really don't know what is sustainable with web sockets). Then again, maybe it actually is perfectly fine to do this.

Obviously I can limit the amount of objects by only sending ones who have actually been updated (so static objects would never come through, etc) but I am not sure whether that is necessary at all or whether that is something extremely crucial. I also don't see this working if we implemented something like everyone being able to fire 100s of projectiles (or some other massive collection of constantly updating objects).

Are there any general guidelines or common knowledge around how much data you would expect to see come through a web socket and how frequently? Am I way off the mark or would this work okay for a moderate amount of clients?

I realize this all sounds very broad so to try tighten it up a bit I am specifically interested in how much data is realistic to send through web sockets and how frequently. Any auxiliary information based on the above is a great addition.

# Answer
> 1 votes
I don't think the WebSockets protocol has the speed that you'd be looking for in a real-time game.

"The technique is effective, but is not well suited for applications that have sub-500 millisecond latency or high throughput requirements."

Websockets are built on top of TCP, which ensures that every packet of information is received by the client. Do you need this sort of reliability? Maybe not.

You might build on top UDP instead, which doesn't guarantee the transmission of every packet of info. Because of this, it's a lot faster.

There's a great article that goes into a lot of depth on this answer, and which basically states that although TCP has a lot of bells and whistles and reliability, because in UDP you sacrifice these layers of protection (and is a bit of a pain in the ass) you get much faster speed.

# Answer
> 1 votes
I've worked on a very similar personal project similar to one you have mentioned. It was my first real attempt at creating a real-time multiplayer game using Node.js with Socket.io. You can check it out here.

Not saying my game is anything of a good example of a multiplayer server, however if you check the network data (chrome - f12) when playing on it you'll see what kinda data the server can send, and the client can receive.

My server does **not** send unique info to each player (by sending only relevant, nearby data), but instead sends all of the game info to every connected player every 50ms (or something close to that). this, whilst a bad practice, kind of answers your question. My inefficient game can send every single bit of game data, to every connected client, every 50ms. I've had almost 20 people playing simultaneously with no noticeable hit to server lag.

So, if you're thinking of implementing functionality that sends unique and relevant data to all connected clients, you're already one step ahead of me. (And my game works fine™).

---
Tags: multiplayer, node.js, websocket
---