title: Ugly fonts in Unity app on Windows 10

text:
# Question
Title: Ugly fonts in Unity app on Windows 10
I downloaded and installed Unity3D Personal edition on my Windows 10 computer and first time I launched it I couldn't help but notice that text looks really bad across all UI elements (buttons, dropdowns, preferences, etc) except system menus, as if anti-aliasing is turned off everywhere.

I couldn't find any settings related to this in Preferences. Is it GUI font customizable in Unity?

# Answer
Turn on the dark theme, it makes the ugly Editor UI font more bearable.

If you compare my screenshot below with yours, you'll see that characters such as "C", "a" and "G" looks less broken in the dark theme.

yes you can turn on dark theme for personal edition with a bit (literally) of effort, just google for it.
> 1 votes

---
Tags: unity
---


# Question
Title: Game Engine "Control Flow" Design Options?
I'm dabbling in writing my own somewhat basic game engine from scratch, and I wanted to ask about some common design configurations for connecting the various parts. I'm particularly interested in the relationship between the "engine" and the "game", and the various ways in which information and function calls cross this boundary (the "control flow", for lack of a better term).

---

Let me start by describing my *understanding of the main parts:*

* **Engine:** The engine contains various subsystems related to rendering graphics and audio, inputs, physics solving, networking, memory management and asset/resource loading/unloading, etc. Subsystems may be encapsulated into individual classes or use interfaces in order to support a variety of platforms or libraries.
* **Game:** The game contains a large and complex structure of "entities" which contain all of the data and functions that define the gameplay world and logic. Entities are also associated with visual representations, audio sources, physics bodies, and everything else that determines what the game is and how it is represented.

---

So, for example, this is my current understanding of *'control flow' when it comes to updating or 'ticking' gameplay logic* (pseudocode ahead):

1. Setup: `Main()` creates and initializes the Engine, which creates a context and initializes various subsystems. (For example, maybe setting up SDL/OpenGL/OpenAL/etc., allocated a big block of memory within the memory manager, etc.)
2. Some kind of game loop will call an `Engine::Update()`, either at a fixed or variable timestep, maybe passing in some kind of 'deltatime'.
3. The Engine contains a object/pointer/reference to a Game, and (if there is a game) will then forward its own updates to the game's `Game::Update()` function.
4. The Game will then call `Entity::Update()` on each of its own Entities, and they will perform some game-specific, per-frame, actions.

This is pretty simple to understand, as it is a straight-forward chain of `Update()` calls starting from the main loop, then the engine, then the game, and finally propagating all the way down some structure of entities (and/or components) until everything in the entire system has performed it's per-frame logic. This is a 100% linear relationship, and as such each piece only needs access (pointer/reference) to the next piece in the chain.

Is this a mostly correct understanding of how logic flows between pieces of a game? Are there other common ways of handling this (for example, Main updates Game directly and Engine is used as a service by Game for other things?)

---

Where things seem to get more complicated and where I get more confused are situations where it seems like everything isn't 'flowing in one direction', as it happens with the logic flow described above. For example, here's *my understanding of the "rendering flow".*

1. Setup/Initialization, same as before.
2. Game loop calls `Engine::Render()` at some timestep, possibly in sync with the Update() but not necessarily.
3. At this point, the Engine *could* call `Game::Render()` and this call could be passed down to individual Entities that are responsible for rendering themselves. However, then this seems to create a problem where rendering-specific code is now seeping into the "Game Space", and your game's code is getting all mixed up with D3D or OpenGL calls! I don't think that's what we want, Right? As such, my instinct here would be to have the Engine request all of the "renderable" Entities from the Game (for example, `Game::GetRenderables()` fucntion).
4. After the Engine has pulled all of the "renderable" Entities from the Game, they are then passed into the the `IRenderSystem::Render( IRenderables )`.

At least, that's my current understanding of how the control flow works when it comes to things like graphics rendering, audio rendering, physics solving, etc. In these situations it seems desirable to encapsulate these tasks within their respective engine subsystems, so that as much of the related code as possible exists in a single place. Of course the Game world and Entities determine the content of the game, including what needs to be seen, heard, collide, where it is, what it looks like, etc. But it should be the Engine that is responsible for actually taking those things from the Game and rendering/solving/processing them.

Is this a decent high-level understanding of the rendering flow between the Engine and the Game? Is this general design suitable for audio and physics systems as well (Engine collects 'primitives' from Game and delegates processing to subsystems)?

---

Finally, in my design, where the "Engine has a Game" as a "Console has a Cartridge"; updating the game's logic and collecting of all of its renderable/physics primitives each frame. I've run into a situations where the Game depends on the Engine for certain tasks. For example, *the creation and destruction of certain Entites/Components/Assets!*

It makes sense to me that the Engine should be responsible for allocation and deallocation of system resources (like memory) as well as loading assets from files. As such, in order for the Game to add a Sprite or Mesh, for example, to an Entity, it must be able to request the creation of a Mesh component (or something similar) from the Engine. The Engine will then create that object using a custom allocator, load the asset from a file, do any other preparation, and then deliver the result to the Game.

But now this seems to complicate the relationship between the Engine and the Game. It used to be that the Engine 'owns the Game', updates it, and retrieves primitives from it, while the Game had no knowledge or dependency on the Engine. But now the Game needs to be able to call functions on the Engine as well. Now there are a few ways to resolve this; making the engine a singleton, creating back-pointers to the engine, etc. But I was thinking about a solution where the Engine passes a reference to some kind of EngineUtilities object into the Game and its Entities that gives them some kind of limited interface for calling Engine functions. Kind of an attempt at dependency injection, I guess.

---

Anyway, I realize how big this question is, but the gist of it is this: **What are some common designs for connecting the various parts of a game engine and what are the pros and cons of different approaches? How does the flow of logic updates differ from the rendering flow, physics solving, object creation, etc.? Which approaches are used by popular game engines (Unreal, Unity, IdTech, CryEngine, Source, Godot, etc.), and have popular approaches changed over time?**

# Answer
I give it a try.

> What are some common designs for connecting the various parts of a game engine

The most commonn that come to my mind are

* BLOB (Bloated Object): one GameObject hold references to every systems and has in its interface methods called by every systems (DoPhysics, DoLogic, DoRendering,...) and can't change
* Component Systems: GameObjects are split into "nearly" independent components where each component (in a perfect world) would only relate to on subsystem. GameObjects use collections/arrays so you can add components and systems as you wish, even at runtime
* The third on in the middle: Aggregation (the game object holds only the references needed) but can't change during runtime

> what are the pros and cons of different approaches?

Well, this answer fills books, theses, papers, blogs,.... and depending on the person you talk to this can be somewhat religous.

They discuss factors like

* performance vs flexibility
* flexibility brings overhead
* reusability
* modularity/granularity
* more modular approaches require more coding time putting things together

> How does the flow of logic updates differ from the rendering flow, physics solving, object creation, etc.?

You mentioned you split up everything into subsystems (one for each of audio, physics, rendering,....) so I guess they share a common interface. This leads to the answer that they do not differ basically. Though all have different needs to handle their tasks. So they all share that they are called (in a speciefid order, and this is important) in the same way (Update = DoRender, DoPhysics, DoSound) and then do their tasks.

> Which approaches are used by popular game engines (Unreal, Unity, IdTech, CryEngine, Source, Godot, etc.),

Years ago (haven't checked since a time):

* Unreal: BLOB
* CryEngine: BLOB (I guess)
* Amazon Lumberyard: (once I read they bought a CryEngine license to port it to Component Based)
* IdTech: if they kept the style since Quake they have everything optimized for performance to the nightmare of every software architect. I remember everything was tied to everything, no coupling at all.
* Source: most of the older engines use BLOB so I guess this too
* Unity3D: the star amoung the component based

You can learn a lot about that stuff taking a look into open source game engines on sourceforge, github.

> and have popular approaches changed over time?

Yes.

At the beginning there was the need for massive performance tuning (ID Doom, Quake). Everything was tied together with "no clear border" between game and engine. For a new game one had to touch "the whole engine".

Then object orientation brought the BLOBs. Adding more functionality to the engine meant that GameOjbect interfaces and member lists were growing (DoRender, DoAudio, DoPhysics) and every game object holds a reference to every system.

Later on a popular way to get all the reference handling easier Dependency Injection came up.

---

> Is this a mostly correct understanding of how logic flows between pieces of a game? Are there other common ways of handling this (for example, Main updates Game directly and Engine is used as a service by Game for other things?)

Yes. One can either hardcode the gameloop and the call order or make a list/array of subsystems held by the gameloop and it will call "some kind of" update() every frame in the given order. No. Since the game loop knows the subsystems and the order it is not needed that every subsystem knows the next element in the queue.

Two interesting points I want to mention is the importance of the order in which they are called (which depends on your needs) and more important that there are two types of subsystems. In a need for a better naming I seperate them into active (do their stuff only when update is called) and passive (do their stuff immediatly).

The example I use to describe the need is as follows: Imagine a networked game with a server and a client. The server sends a message "Create GameObject X". On the client side some network logic receives this message. This message comes only once. So on reciving the logic calls something like GameObjectManager.CreateGameObject(X). The logic knows it has to do more with the game object than just creating it. E.g assign a player to it. So the logic calls something like GameObject x = GameObjectManager.GetGameObject(X). If the gameobject manager creates its objects only in update (since it is the only safe point in time where no other systems interfere with the game object list) this will not work because the GameObjectManager.CreateGameObject(X) haven't created the game object X yet and therefore GameObjectManager.GetGameObject(X) will return null in the network logic.

Hope you understand what I mean.

---

> Is this a decent high-level understanding of the rendering flow between the Engine and the Game? Is this general design suitable for audio and physics systems as well?

Yes, it is a decent high-level understanding of one approach. Nothing against doing it that way but there are other ways may are closer to what you desire.

To your game code getting mixed up with D3D or OpenGL calls: It shouldn't be. Define what stuff you have to render: Models, Animations, Textures, Texts/Fonts,... and provide in the render engine according methods like RenderModel(...), RenderTexture(...), RenderText(...) Then you can either call those methods from the GameObject.Render() or the game object holds it's Renderables which are returned in GetRenderables(). So your game object doesn't even need to know if e.g. RenderModel(...) uses D3D or OpenGL. The code is cleaner and shorter.

This is the way you can design all of your systems. Either the gameobjects holds a reference to the (render) engine as well as all required data and does its stuff like void DoRender() { renderEngine.RenderModel(\_myModel); } or the gameobject provide IRenderables.

> (Engine collects 'primitives' from Game and delegates processing to subsystems)

When it comes to stuff like render order I assume personally I would tend to an approach where the render engine holds a collection of IRenderables and the game object injects them during creation or logic state. So the render engine already knows all IRenderables when Engine.Render() is called and can sort it dependend on the it's needs. But this is only my personal preferance and I guess this is the most common approach in component based systems (I tend to use). The drawback is that each gameobject with muliptle components is in multiple growing lists. And it has to be added (on creation) and removed (on destruction) from all of the lists which can become a performance peak.

---

Ah, this was the block with the cartridge.

The first thing I am not sure if I understand is your seperation between engine and game in the sense of the engine using the game like a cartridge and who owns whom.

My personal approach of understanding the relation between those two is that the game is the master and it utilizes an/the engine. The engine is a framework, a collection of libraries, etc... or in short a tool helping your game. The game can't live without the engine but the engine can life without the game. The game controlls the engine, knows what to do and uses the engine to do it.

In your understanding of the "cartridge" you are looking for a data-driven engine design. If gameobjects aren't defined in code but in Json, XML or some self defined format the engine could load it from a predefined location (as well as the other assets like models, sounds, textures) and knows what to do. But this is only true if you also have some external scripts (Javascript, LUA) so you can controll the engine from it and implement your actual game logic. Therefore the scripting engine has to have access to your well defined engine API.... and so on

---

If you can (at least) read Java you could take a look into the Java Game Components. Some stuff I have written one.
> 1 votes

---
Tags: architecture, software-engineering, design-patterns
---


# Question
Title: Removing Hinge Joint from script doesn't work
I'm facing serious problem with handling hinge joints dynamically in Unity.

I made bunch of chains and they are all linked for make something like "sealed door".

When I remove HingeJoint component at the runtime from Inspector, chains were unlinked and everything works fine.

But when I try same thing in the script, sometimes it works and sometimes not(And most of time doesn't work). And some condition just doesn't work.

There are two chain links so I need to remove two hinge joints, one named chain1 and one named chain2.

This is the code what am I tried:

```
Destroy(chain1.GetComponent<HingeJoint>());
Destroy(chain2.GetComponent<HingeJoint>());

```

Above code is just remove hinge joints but it doesn't worked always. So I added some delays:

```
IEnumerator RemoveHingeAfterTime(float delay, Rigidbody chainRB) {
    yield return new WaitForSeconds(delay);
    Destroy(chainRB.GetComponent<HingeJoint>());
}

...

StartCoroutine(RemoveHingeAfterTime(0.1f, chain1.GetComponent<Rigidbody>()));
StartCoroutine(RemoveHingeAfterTime(0.2f, chain2.GetComponent<Rigidbody>()));

```

Above code is just quite random, sometimes work sometimes not. Especially chain2 almost not works.

I adjusted time to fix this, but nothing works. "yield return null" or "yield return new WaitForFixedUpdate" also doesn't worked.

My doesn't worked means like this:

Also I toggled isKinematics and useGravity with same logic(just hope that physics works) but doesn't worked either.

I'm using Unity 5.6.1f1. Is this glitch? Is there a way to fix this?

Any advice will very appreciate it.

# Answer
> 1 votes
I solved this by give the little force and forcely wake their rigidbody to every chain over there when it unlinked!

---
Tags: unity, rigidbody, joints
---


# Question
Title: How to set end of joint that has fixed transform?
I'm implementing chains locked the door, and used Hinge joints to linked the chains like this picture:

As you can see, last chain doesn't have connected body because it is end. And when the game starts, links were broken:

How to make last chain just hang in the position like first hinge object?

Also, chains are too way swaying, is there a way to reduce it? I increased every chain's mass to 100~1000, but seems nothing changed. Give it too much mass results broken joints.

Any advice will very appreciate it!

# Answer
I solved this by freezing the position of last chain, but not rotation. It might also work the way @Spectre suggested.
> 0 votes

---
Tags: unity, rigidbody, joints
---


title: Ray is not shooting forward

text:
# Question
Title: Ray is not shooting forward
This is the code for Raycast:

```
RaycastHit hit;
Vector3 direction = transform.forward;

Debug.DrawRay(transform.position, direction * 200f, Color.red, 0.1f);

if(Physics.Raycast(transform.position, direction * 200f, out hit, 200f)) {
    if(hit.transform.tag == "Enemy") {
        // do something with enemy
    }
}

```

I'm shooting the ray to in front of the object, but it's not quite working to me.

These are the screenshots:

As you can see above second picture, shot the ray to forward, but actual ray wasn't forwarded.

I also rotated the ray z axis 90 or -90 degree, but stil not working. (Actually I tried to rotate each axis 90 and -90, but nothing seems work)

```
Vector3 direction = Quaternion.Euler(0, 0, 90) * transform.forward;  // Doesn't work
Vector3 direction = Quaternion.Euler(0, 0, -90) * transform.forward;  // Doesn't work either

```

What am I missing?

# Answer
> 1 votes
I solved this problem by check "Experimental Apply Transform" option when export as FBX my models.

---
Tags: unity, rotation, raycasting
---


# Question
Title: Photon disconnected without any error/warning message
I'm making online game with Photon and Unity. It was working fine, but suddenly players are disconnected without any warning or errors.

It just happens sometimes fast, sometimes slow, but always happened.

Before user disconnected, it seems it's little laggy and soon player disconnected.

So I changed the log level to all, and saw this message was printed right before player disconnected.

> DisconnectByServerLogic current State: Joined

What is meaning of this? I changed Photon App to new one, but didn't worked. I spent hours to figure out why this is happening, but no progress.

There is only one part that disconnects player, it's event function that invokes user pressed exit game, but it never called and there is no more function that disconnects.

If this causes from my code, I can fix it, but there is no code for disconnect and also there is no information why user keep disconnected.

Only information that I found was just above message but I don't know what that means. Is that mean Photon forcely disconnects player?

I'm stuck here in almost day but I couldn't find any problem in my code.

I'm using Free photon plan, and result of analysis:

* 4 CCU
* 1 Rooms Max(I don't know what this means)
* 15,558 Msg/s per Room Max
* 895.0 MB Bandwidth
* 0 Rejected Players

If someone who knows this problem, it will be very appreciate it gimme some advice. Thanks.

# Answer
> 0 votes
This problem was caused by too many data transmission, so Photon forcely closed it's connection.

Reducing data transmission size solved this problem.

---
Tags: unity, photon
---


# Question
Title: How do i make turn based combat with 10+ players work?
I am currently developing a game with a turn based combat as focus.

The games battles will need to be able to handle 1 to 20 players (Multiplayer).

Each unit (Player and AI) each has an initiative (higher initiative the higher in order you are)

I am now in the stage where i will start writing the game mechanics for the turn based combat and i believe the classic turn based (individual turns) will take too long especially if someone is AFK or just slow. My initial idea was to add a timer based on the number of players min-capping at 10 seconds, but i don't want to stress out my players.

My other idea is to allow every player and AI select their actions at the same time with a higher timer at 1 minute. When all the players has selected or the time has run out the initiative order are run for each unit with their action.

I am aiming for the second one but i want to know if this is the best way to take. It will add an other dimension of strategy since each player will have to calculate what the opponent will do so they cant take action for what they have done.

Do anyone know an other way to do this? What would you chose and why?

# Answer
You should not force players to make their moves under duress by giving them a ticking down countdown timer. A *reasonable* time limit might not be a bad idea to prevent AFK players from ruining everyone's game experience, but if you make the time limit too short, the game will become very stressful. You don't want players to lose a game because they simply didn't have the time to make all the decisions they had to. If you want the game to be stressful, you should build a real-time strategy game, not a turn-based one.

If you go the simultaneous turn route (which I would really recommend with so many players) then one thing you could try is only start the timer when a fraction of players already completed their turns.

But Instead of focusing on the timer, see what you can do to reduce the time it takes to make moves. In order to do that, minimize the number of inputs players need to make during their turn. The best way to do that is by checking which inputs represent decisions which are actually relevant. Try to remove any inputs which represent obvious or irrelevant decisions and focus on those which actually matter.

A good example for this is if you compare the gameplay of the classic *X-COM: UFO Defense* with its recent remake *XCOM: Enemy Unknown*. Some examples:

* The first game had a "time unit" mechanic. Every soldier had a number of time units each turn. Every step a soldier took and every action they performed consumed time units. The player had very granular control over how exactly to spend each soldier's time units. So making a complete move with a single soldier could take 20 clicks or more.

The remake got rid of that by giving each soldier exactly two actions per turn, which could be used for either moving to any tile within range or for attacking.
* The first game had different modes of attack for each weapon (aimed shot, snap shot, burst shot...). They differed by time unit cost and accuracy. Which one to use in which situation was kind of a math problem with only one optimal answer. The successor got rid of that.
* The first game had a complex grid-based inventory system for each soldier which used a separate screen. To use an item which wasn't currently in one of the soldier's hands, the player had to go to the inventory screen, reorganize the inventory so the desired item was in the soldier's hand, and return to the actual game.

The second game also scrapped the complex inventory management. Every soldier carries one primary weapon, one handgun and 2 pieces of special equipment. All of these items are always accessible with a single click.
* The first game had up to 26 soldiers in each battle, the successor only 6.

The overall design goal which the successor pursued with these changes was to reduce the number of clicks per turn as far as possible, but also make sure that every single click is a decision which has serious impact on the game. There are very few clicks which do not represent a relevant decision.

This makes the game not just fast-paced for the player, but also fast-paced for the spectating opponent. They need to watch closely what the opponent is doing, because each of their action matters for them, too. This also makes the opponent move interesting to look at in multiplayer games.

---

However, I am a bit skeptical if you will be able to pull that off with *twenty* players. Many actions will be only relevant for a few players, but not for all of them. I am afraid that with so many players, the only option is to allow everyone to make their turns simultaneously to avoid wasting too much of the other player's time.

You should also budget some development resources for tweaking the timing for the visualization of the execution phase. You have a hard challenge to overcome here. On the one hand you need to move all units quickly so players aren't forced to watch stuff which isn't very relevant to them. But on the other hand, you need to make sure that the events which *do* matter to each player get the screentime they deserve. Keep in mind that the visualization doesn't necessarily needs to be the same for all players. You might, for example, play a detailed animation for any attacks where their own units are involved and only do a very quick one for any where they aren't.
> 4 votes

---
Tags: game-design, multiplayer, mmo, turn-based, turn-based-strategy
---


# Question
Title: How to keep the state of all games in the server?
i have a problem implementing a turn-based game server in java.

What i want is a way or a technic that let the server keep all the games state that are created in order to the client recover at the same state when an disconnection occurs.

Until now i have developed the server-client programmes and they work fine, but i didn't know that TCP can't recover over some situations of connection lose. So i get so many "connection timed out" errors, and my programmes don't have a reconnect and recover technic. Now i need to think a way the server keeps some info of all the games.

My (for now) solution is to have a class that all threads have a reference to, inside the class we have many ArrayLists to store every info we need so threads can access and handle them.

For Example:

**Game-123** has the score 100 so an ArrayList **scoreOfGame\[123\]=100**

**Game-3** PlayerB name is stored at ArrayList **PlayersB\_Names\[3\]=name**.

If there is a better way to keep track of all game states seperately on the server, i would appreciate it!!!!

# Answer
Is the name just a string or is it a unique identifier for each player.

If it is a uid you can just iterate over the player name arrays to see if the player is currently involved in a running game and then the keeps on playing that game. I can't get into more details without knowing your architecture but I bet you get the point.

---

On the other side I would recommend something like the following:

Server-side you could introduce a "session" object. Each currently running game holds it's own (and only it's own) game state within this session object. Instead global arrays holding the states (scoreOfGame\[123\]).

e.g. (since you mentioned each session lives in a thread)

```
class Session implements IRunnable() {
    private List<Player> players;
    private int score;

    //other stuff
}

```

You also would then have a session manager class handling your sessions. If a client looses a connection you can either ask the session manager if the player has a running session and then (re)join it to this session.

The benefit is that you do not need the arrays holding all the states of the other game instances.

Which may makes the code a little easier and gives it a slightly better structure/architecture.

---

If players are unique identifiable you could have a player class and the matching player manager which holds the players.

Then you could give the player class a member Session currentSession. When it logs on to your server you would have the current session already referenced and would not need to search all current session for the player.
> 1 votes

---
Tags: java, architecture, software-engineering, client-server, turn-based
---


title: How to create a hover effect on image

text:
# Question
Title: How to create a hover effect on image
I am trying to make it so that when a user hovers over an image on my JPanel, the image turns into a different image. I have 2 classes, one for the JPanel and the other is for the gameplay (snake game). How do I implement the mouseListener to make it so that the image changes on hover?

snake.java (main):

```
public class snake {

    public static int mouseX;
    public static int mouseY;

    public static void main(String[] args) {

        // JFrame
        JFrame obj = new JFrame("Snake");
        gameplay Gameplay = new gameplay();
        obj.setBounds(10, 10, 905, 700);
        obj.setBackground(Color.DARK_GRAY);
        obj.setResizable(false);
        obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        obj.add(Gameplay);
        obj.setVisible(true);

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

    }
}

```

Image I want to change:

```
    settingsImage = new ImageIcon(getClass().getResource("/assets/settings.png"));
    settingsImage.paintIcon(this, g, 700, 23);

```

If you need to see any of my other code please tell me!

# Answer
I assume the gameplay class holds the object(s) that should change the image. You don't mention if only one object should listen to the mouse or more of them.

From the given code you will have to pass the mouseX and mouseY to the towards the object that should change.

e.g.

```
obj.addMouseMotionListener(new MouseAdapter() {
        @Override
        public void mouseMoved(MouseEvent e) {
            gameplay.mouseMoved(e.getX(),  e.getY())
        }
    });

```

Within gameplay you could either pass it to every object, to only the objects that should listen to the mouse or just the one that listens.

All objects (which react to the mouse) then would have a MouseMoved(int x, int y) method. And all of theses objects need to know their bounds (position x, position y, width, height) and their current state if the mouse is currently pointing on them.

Then you have in each object these methods and members:

```
private boolean isMouseInside = false;
private int posX, posY, width, height;

public void mouseMoved(int x, int y) {
    boolean isInside =
        x > posX
      && x < posX + width
      && y > posY
      && y < posY + height;

    if (isInside && !isMouseInside) {
       //mouse just entered
       isMouseInside = true;
       OnMouseEnter();
    } else if (!isInside && isMouseInside) {
       isMouseInside = false;
       OnMouseExit();
    }
}

public void OnMouseEnter() {
     settingsImage = new ImageIcon(getClass().getResource("/assets/settings.png"));
settingsImage.paintIcon(this, g, 700, 23);
}

public void OnMouseExit() {

}

```
> 0 votes

---
Tags: java
---


# Question
Title: What audio method works across all web browsers and mobile for HTML5/JavaScript?
I have looked at a number of ways to trigger audio in HTML5/JavaScript, but each time I find something that might be workable, I find web browsers and mobile devices it doesn't work on at all.

What is considered the best method that works across all web browsers and mobile for creating a game with sound using HTML5/JavaScript?

What do experienced interactive game programmers do? Do you check the user's web browser or mobile device and serve up different code to make it work? Or do you have a single solution for this? Or do you warn the user by supplying a list of web browsers and mobile devices the software is known to work with?

Additional Information: I found out that audio in some web browsers, like Safari on the Mac, it will load the audio file each time it is triggered, which causes a problem. I saw once solution using what is called Audio Sprites: https://phaser.io/examples/v2/audio/audio-sprite This way, you load one audio containing all your sounds needed, and then you pass a pointer to where in the audio file to start playing the sound and where to stop. That sounded like a solution, but this doesn't work on the Safari web browser, it produces no sound at all.

Then I looked into Web Audio API, and this is impressive: https://forestmist.org/share/web-audio-api-demo

While this worked on the Mac for Safari, Firefox and Google Chrome, and the iPhone, it doesn't work on Windows with Internet Explorer (or Safari on Windows either).

I've not tested Web Audio API on the android phone yet, because I don't have access to one at the moment. So I was wondering what experienced interactive programmers do to provide audio to work across most or all platforms? It seems a huge step-backwards to have to alert visitors to a website that they can only use the functions on it by using a short list of web browsers.

The issues as I see it seem to have to do with being able to load the audio file and not have it re-loaded over the internet each time it is referred as play(). I realize Web Audio API might provide much more capability than most of us needs, but is that the current gold-standard for audio in a HTML5/JavaScript game?

Here is a simple example, using audio that works on Google Chrome/Mac, but it doesn't work on Safari/Mac: https://rawgit.com/mehaase/js-typewriter/master/example3-typewriter/index.html

# Answer
> 1 votes
**Disappointing Answer:**

If you decided to build something based on modern tools (HTML5/CSS3/JS6), then you should ignore browsers that don't support such features (like the Audio API), otherwise you will spend most of your time debugging and doing some dirty workarounds rather than developing. By the time you successfully made all the hacks to support these browsers, they'll probably be supporting these features.

**Additional Notes:**

caniuse.com is a good source to see what's supported and what's not as @Coburn said.

---
Tags: javascript, html5, audio
---


# Question
Title: Box2D - Constant Movement without ignoring Physics
I am developing a small game with LibGDX and Box2D.

I want to move a body at a constant speed, lets say 2 m/s (meters per sec).
The body should accelerate to that speed immediately when pressing the respective key (e.g. Arrow Up) and also be able to stop or change direction instantly.

The code to start and stop such a movement should look like this: `public void onKeyPress(key){
 if(key == ArrowUp){
 currentMovement = new Vector2(0, movementSpeed);
 body.addConstantMovement(currentMovement);
 }
 //TODO: Remaining directions
}`

`public void onKeyRelease(key){
 if(key == ArrowUp || key == ArrowLeft || key == ArrowRight || key == ArrowDown){
 body.removeConstantMovement(currentMovement);
 }
}` The given Vector2 (movementSpeed) should be remebered and I should be able to remove it at any time.

However, he should still be affected by the physics of everything around him.
So if he moves towards a magnet that pulls him 1 m/s, he will move with 3 m/s, when moving away from it the speed should be down at 1 m/s.

Is it possible to do this in Box2D without manually moving it in every step of the world?
-If yes, how?
-If no, any libraries that can do this? I only need very simple physics, no density, friction etc.

# Answer
When you want to modify a body in box2d you have 2 main choices use the physics or ignore the physics and modify things yourself.

The first option would be to use the bodie's applyForce or applyLinearImpulse methods to move the object. This will allow box 2d to perform physics on your body.

The other option is to ignore the physics from box2d and manually set the position/speed etc with setTransform, setLinearVelocity etc.

Each of these have their own pros and cons. For example, the first option will allow your body to react in a way that matches the real world but will be harder to control the speed. The second option will make it easy to control speed and position but will make it hard for you to make the body react in a natural way.

My opinion on this would be to go with option 2 as once you can move you body at your desired speed etc then you can use sensors to sense when a body is within range of said "Magnets" then have your own function to apply the physics you want, be it push or pull to a point with some simple trigonometry.

This example below shows how to control the body:

```
public void onKeyPress(key){
    if(key == ArrowUp){
        // box2d is in meters so 0,2 is 2 meters per second
        body.setLinearVelocity(new Vector2D(0, 2));
    }
    if(key == ArrowRight){
        body.setLinearVelocity(ew Vector2D(2, 0));
    }
    if(key == ArrowDown){
        body.setLinearVelocity(new Vector2D(0, -2));
    }
    if(key == ArrowLeft){
        body.setLinearVelocity(new Vector2D(-2, 0));
    }
   // this does not allow diagonals
}

```

Now to apply magnetism you will need a contact listener which listens to contacts and then checks if those came from a magnets sensor body. You woul then use something like this to apply a pull magnetism effect

```
        // get distance from moving object and magnet
        float velx = magnetBody.getPosition().x - movingBody.getPosition().x;
        float vely = magnetBody.getPosition().y - movingBody.getPosition().y;

        // get the euclidean length
        float length = (float) Math.sqrt(velx * velx + vely * vely);
        if (length != 0) {
            velx = velx / length;
            vely = vely / length;
        }

        // get current moving speed
        Vector2 current = movingBody.getLinearVelocity();

        // get speed magnet should add
        Vector2 magnets = new Vector2(velx * magnetStrength, vely
                        * magnetStrength)

        // add magnet speed to current speed to get modified speed
        Vector2 newSpeed = current.add(magnets);

        // apply it to the body
        movingBody.setLinearVelocity(newSpeed);

```

This should cover the basics of what you need to apply the speed and magnet power to a body. You will need to adjust this to match your world but this should help you get started.
> 1 votes

---
Tags: java, libgdx, physics, box2d
---


# Question
Title: Firing a particle effect toward the tapped target
I am editing this game, where i have to destroy this pyramid when user will tap, i want to show particle effect moving towards Pyramid Like this:

but sometime it is not moving towards pyramid like this but moving straight Like this:

Script for RayCast and Particle Effect Instantiation:

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

public class General : MonoBehaviour
{
    public static GameObject currentPyramid;
    RaycastHit Hit;
    public GameObject LineStart;
    public GameObject ParticleEffect;

    void Awake(){
    }
    void Start(){
    }
    void Update ()
    {
        Debug.Log (currentPyramid);
        if (Input.GetMouseButtonDown (0)) {
            RaycastHit hitInfo = new RaycastHit ();
            bool Hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),
                                       out hitInfo);
            if (Hit) {
                currentPyramid = hitInfo.transform.gameObject;
                if (currentPyramid != null) {
                    Instantiate (ParticleEffect,
                                 LineStart.transform.position,
                                 LineStart.transform.rotation);
                }
            }
        }
    }
}

```

code for Pyramids

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

public class PyramidScript : MonoBehaviour
{
    void Update () {
        if (PlayerPrefs.GetString ("Pyramid") == gameObject.name) {
            General.currentPyramid = this.gameObject;
        }
    }
}

```

# Answer
> 0 votes
You must instantiate the effect at the collision point

```
Instantiate (ParticleEffect, hitInfo.point, Quaternion.identity);

```

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


# Question
Title: Monodevelop does not show the contents of the UnityEngine namespace in the autocomplete popup, but the scripts are still working properly. Why?
This is not the first time when I use Monodevelop for script editing it shows all UnityEngine related stuff in the autocomplete popup and than it randomly decides not to do so.

Reopening it didn't help.

What should I do?

# Answer
> 1 votes
is a typical problem of Monodevelop and Unity.

Close it and double click on a Script from Unity, that opens it correctly.

Do not open it from Monodevelop access.

Or another way is, from the solution explorer in Monodevelop, right click and reload.

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


# Question
Title: How can i scale a cube on one side on x only?
I have in the Hierarchy a empty GameObject and a cube as child of it. The cube the child is at position 0,0,0 and scale 1,1,1

But when running the game the scaling is on both sides of the cube. I put the cube as child of the empty gameobject and scaling the empty gameobject but still it's scaling the cube on both sides.

The script is attached to the empty GameObject:

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

public class Walls : MonoBehaviour
{
    Vector3 originalScale;
    Vector3 destinationScale;

    void Start()
    {
        originalScale = transform.localScale;
        destinationScale = new Vector3(100.0f, 0, 0);
    }

    private void Update()
    {
        if (transform.localScale.x != 100.0f)
            transform.localScale += new Vector3(1, 0, 0);
    }
}

```

This is a working solution:

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

public class Walls : MonoBehaviour
{
    public Transform[] objectstoScale;

    private void Update()
    {
        if (objectstoScale[0].localScale.x != 100.0f)
        {
            objectstoScale[0].localScale += new Vector3(1, 0, 0);
        }
    }
}

```

But i want to make that the same cube will also scale one side on the z. So the cube will be scaled on both x and z but without filling it one be like frames. So i tried this:

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

public class Walls : MonoBehaviour
{
    public Transform[] objectstoScale;

    private void Update()
    {
        if (objectstoScale[0].localScale.x != 100.0f)
        {
            objectstoScale[0].localScale += new Vector3(1, 0, 0);
            objectstoScale[1].localScale += new Vector3(0, 0, 1);
        }
    }
}

```

And i have now two cubes childs of the empty gameobject one cube position is 0.5,0,0 the second is 0,0,0.5 but what i'm getting is:

What i want to do is to create automatic a rectangle scaling a cube on 4 sides at the same time not filled rectangle.

For example like this:

# Answer
> 0 votes
Position the child cube at (0.5, 0, 0) in its parent's coordinate space. That will put one side exactly on the origin of the parent at its default scale (the cube measures 1x1x1 by default, so it extends one half a unit in each direction)

Then scale the parent by your desired factor. Since one side is exactly at the origin/zero, and zero times any scale factor is still zero, that side will stay put and the other side will move.

Alternatively, you can reposition the cube by half its scale factor to keep your desired side at the origin.

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


# Question
Title: How do I test if an AABB and concave polygon intersect?
The player's collider is an axis-aligned bounding box in my 2D platformer, but the environment can be different shapes. I already have collision-detection that prevents the player from going through colliders, but I don't have anything for getting the player out of concave polygons if he ends up inside one by for example flipping the collider when changing direction from/to left/right.

SAT doesn't work on concave polygons, so I need an algorithm that can tell me if an AABB and any polygon intersects and give me the minimum translation vector to push the shapes apart. (The velocity of the objects will not need to be considered).

BTW the game is written in C# with the MonoGame framework if that's of any relevance.

# Answer
If your game starts with the player AABB completely outside of the concave polygon, then I would solve an easier problem:

Test the edges (line segments) of the polygon against the AABB. If you have an intersection, just push out the AABB so it is on the correct side of the linesegment.

Your polygon is probably counter-clockwise, so you know which part of the edge is "inside" and which part of the edge is "outside."

Beware this can cause "tunnelling" if your AABB moves too fast and goes from completely outside the polygon to completely inside the polygon within a single simulation step.

To do edge-versus-AABB in 2D, you can use the Cohen-Sutherland algorithm.
> 2 votes

# Answer
Intersecting a polygon *P* with a box/rectangle *R* is the essence of clipping, so you could use a clipping algorithm. There are several, e.g., the Cohen-Sutherland algorithm. A box *R* and a polygon *P* intersect if (and only if), when you clip *P* to the box *R*, the result is not empty, i.e., some parts of *P* are inside *R*.
> 0 votes

---
Tags: c#, collision-detection, geometry, aabb
---


title: How can I track two fingers?

text:
# Question
Title: How can I track two fingers?
Im trying to make make game which is intended to be played with the phone in landscape mode, and the player uses their thumbs to control the movement. The game controls look like this:

On the left there is a simple button to accelerate, and on the right a wheel to adjust the direction. Both work perfectly when used individually but they won't work both at the same time.

I would need to implement multitouch and accelerate/rotate depending on which side of the screen the finger is on, but I can't figure out how to do that detection.

Below is the onTouchEvent, how can i modify it to do what i want?

```
@Override
    public boolean onTouchEvent(MotionEvent event){

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (event.getX() < 300 && event.getY() > 250) {
                    btnPress = true;
                }
                break;
            case MotionEvent.ACTION_MOVE:
                x = (int) event.getX(); //this is used by the direction wheel
                y = (int) event.getY();
                break;
            case MotionEvent.ACTION_UP:
                btnPress = false;
                break;

        }
        return true;
    }

```

# Answer
You need to separate the two control areas not just for ACTION\_DOWN but also for ACTION\_MOVE and ACTION\_UP.

Currently, you only check the 0..320, 0..250 area in the ACTION\_DOWN.
> 0 votes

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


# Question
Title: How can I detect the player being crushed in a 2D platformer?
I'm checking collision for a platformer character as shown in #1. The red dots are the pixels that are checked and the grey lines indicate the axes they pertain to. I like the results I get from checking collision this way (versus, say, bounding box). Everything works exactly as I'd like it except for one problem: crush detection.

In the following images, the light blue box represents the ground, the orange box is an object, and the arrows indicate direction of movement.

The simple solution to detecting when the player is crushed is to see if the collision points on opposite sides are both triggering. If they are, the player is being crushed. In #2, you can see a normal crush scenario. The player is grounded and the top collision points are intersecting with the falling object. This triggers a crush.

#3, 4, and 5 present problematic scenarios. In #3, the player is moving toward the object, which is moving up. A right-side collision point is hitting the object, causing a collision and stopping the player.

Now, if the object continues to move up and the player continues to move right (as shown in #4), the object clears the players right-side collision point and the player moves to the right. But now, having done so, the object is intersecting a top collision point causing an unwanted vertical crush.

A similar scenario is shown in #5. Two objects are far enough apart for the bottom collision points to clear, allowing the player to fall, but no to so far as to allow the side collision points to clear, causing an unwanted horizontal crush.

I've been racking my brain on a solution, but nothing I've come up with has worked particularly well, so I'm wondering if anyone out there has an idea or insight into how to solve these problems.

To clear up some confusion, the red collision points would be within the sprite and the grey lines were only used to denote the relevant axis for each collision point. For example, if the character's sprite was a simple green square, the collion points would look something like this:

# Answer
> 34 votes
I think you'll have to take the **box's movement** into consideration. That is, only crush if the box is moving towards the player.

This is similar to other problems in platformers, where the movement is important. E.g. for platforms that you can jump through and onto from below, don't check collision if the player is moving upwards.

So a block can crush the player from above only if the block is moving downwards; from below only if the block is moving upwards; from the left only if the block is moving to the right, and so on.

# Answer
> 9 votes
Have the "crush test" points be *inside* the gray box shown in your image #1 - i.e. kill the player only if you detect a hit on one of the pixels there.

# Answer
> 6 votes
As someone who grew up with 80s platformers, my first comment is that the contact points *must* be exactly on the sprite, not anywhere outside it. There were few experiences more frustrating than dying when a weapon/crusher/enemy was clearly several pixels away from your character - and that kind of experience is what stops people playing.

With that in mind, the idea of having separate points for horizontal and vertical collision simply doesn't fly. So your cases 3 and 5 don't exist.

As for collision detection, as has previously been said, you need to consider movement direction, and you have two axes of movement to consider. If a crusher is down, the player should not be able to walk forwards - it should act like a wall. So with horizontal and vertical detection points in the same place, you couldn't get case 4, even before you add movement direction to the mix.

The upward-moving crusher adds extra complexity. If it's so quick that the player has no chance to escape, then OK. But if it's slower, the player will expect to be able to run over the rising platform and jump off the other side. The player sprite rises upwards on the crusher, and crush detection happens at the *ceiling*.

# Answer
> 0 votes
You could make the object "harder" than the ground, meaning that, assuming collision, the player gets pushed "into" the ground, as opposed to being pushed "into" the moving object.

This assumes the player is not able to push themselves "into" either objects or ground.

# Answer
> 0 votes
If you can detect overlap of objects without having to wait for them to display, a simple approach is to process motion for the player and other objects independently, one pixel at a time, with separate collision checks afterward. If the player is moving freely and would collide with its object as a result of such motion, back it off. If a collision occurs with an object as a result of the object's motion, check whether the player can move in the same direction as that object. If so, move the player. If not, handle the "crush" situation appropriately (damaging or killing the player and/or moving the colliding object backward, depending upon the contact).

BTW, if only a limited number of combinations of shapes can collide, it may be useful to pre-calculate "collision-detection" bitmaps such that if a pixel is set in the first sprite at offset (x1,y1) and in the second at offset (x2,y2) of the second, the pixel at offset (x1-x2,y1-y2) will be set in the collision map. Such a pre-calculated collision map will make it possible to detect collisions between the two sprites by checking the state of a single pixel in the collision map.

# Answer
> 0 votes
It takes two objects to crush a player. Your crush detection should check for the player being between two objects, the space between them being equal to the size of the player, and the distance decreasing.

# Answer
> 0 votes
I find next to be working so far. It doesn't require "external" info about the crushers movement and solves the false positives problem. When a false positive is detected it is treated as collision (and this is what it actually is):

The idea is: why to check if the crusher is moving when we actually care if the character is moving. Both can answer if the crush is false positive caused by the character's own movement or true crush by the crusher object movement.

If the character is moving and crushed (collisions on opposing sides for the incoming frame) then check again for crush on the last frame/iteration coordinates:

1. If not confirmed again then it is due to character's own movement and the character should be returned to the last frame/iteration coordinates just like a collision
2. If crush is confirmed the second time then proceed with crush.

---
Tags: 2d, collision-detection, collision-resolution, platformer
---


title: How to restart game when player lose?

text:
# Question
Title: How to restart game when player lose?
am making a simple in which you drag a player on screen and when a ball hits you you lose ,so you have to move the player away from the balls.level zero:no balls, level one:there is one ball on screen, level two: two balls on screen,the level increases when you reach certain scores. the problem here when player loses the game restart at level 2 and not at level 0.here is my code:

```
public class MyGdxGame extends ApplicationAdapter implements InputProcessor{

// variables
public int[] x={0,0};
public int[] y={0,300};
public int[] size={100,50};
public Ball ball1,ball2;
public Player player;
// Checker: Checks if Ball Hits Player
public Checker checker;
public Texture background;
public Stage stage;

// creation of application
@Override
public void create () {
    checker=new Checker();
    player =new Player();
    background=new Texture(Gdx.files.internal("background.png"));
    stage = new Stage();
    // Ball(x, y, size , speedX, speedY)
    ball1=new Ball(x[0],y[0],size[0],10,10);
    ball2=new Ball(x[1],y[1],size[1],20,10);
}

// changement of application
@Override
public void render () {
    Gdx.gl.glClearColor(1,1,1,1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    stage.getBatch().begin();
    stage.getBatch().draw(background,0,0,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
    stage.addActor(player);
    if(checker.level>0)stage.addActor(ball1);
    if(checker.level>1)stage.addActor(ball2);
    stage.getBatch().end();

    // Checks if Ball Hits Player
    if(checker.check1(player,ball1)){lost();}
    if(checker.check1(player,ball2)){lost();}

    // score increases
    checker.score();

    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();

    Gdx.input.setInputProcessor(this);
}
// Moethod Called When you lose
public void lost(){
    checker.level=0;
    checker.score=0;
}

// Drag Listener
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
    player.updatePosition(screenX,screenY);
    return true;
}

// releasing memory of the app
@Override
public void dispose () {
    stage.dispose();
}

```

# Answer
> 1 votes
You call `stage.addActor(ball1)` but never call `ball1.remove()` inside `lost()`.

Same for ball2.

```
// Method called when you lose
public void lost(){
    checker.level=0;
    checker.score=0;
    ball1.remove();
    ball2.remove();
}

```

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


# Question
Title: Poor performance with LWJGL VBO triangles
I'm new to OpenGL and LWJGL & I have a question about rendering using VBOs.

I rendering 50\*50 objects using VBOs. Each object has its own render method where binding of the position, rotation.

The problem is I have a low frame rate (~10fps) even though my objects (for now) consist of simple quads. Why is my framerate so low?

Later I want to use much more complex objects and other computations...

Code:

```
public class NGINE2 {
static int w = 640;
static int h = 480;
static float oldX = 0;
static float oldY = 0;
static float oldZ = 0;
static List<Triangle> triangles = new ArrayList<Triangle>();

public static void main(String[] args) throws Exception {
    // System.out.println("Hello world from OpenGL!");

    Random rand = new Random();
    for (int x = 0; x < 50; x++) {
        for (int z = 0; z < 50; z++) {
            float rgb[] = new float[3];
            rgb[0] = rand.nextFloat();
            rgb[1] = rand.nextFloat();
            rgb[2] = rand.nextFloat();
            triangles.add(new Triangle(new Vector3f(x, 1, z), new Vector3f(+0.5f, 1f, -0.5f),
                    new Vector3f(-0.5f, 1f, -0.5f), new Vector3f(+0.5f, 1f, +0.5f), rgb, rgb, rgb));
            triangles.add(new Triangle(new Vector3f(x, 1, z), new Vector3f(-0.5f, 1f, +0.5f),
                    new Vector3f(-0.5f, 1f, -0.5f), new Vector3f(+0.5f, 1f, +0.5f), rgb, rgb, rgb));
        }
    }

    initContext();
    renderLoop();

    int height = 500;
    int width = 500;
    double value[][] = new double[500][500];
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            double nx = x / width - 0.5, ny = y / height - 0.5;
            value[y][x] = SimplexNoise.noise(nx, ny);
        }
    }
}

static void initContext() throws Exception {
    Camera.create();

    w = 640;
    h = 480;

    Display.setDisplayMode(new DisplayMode(w, h));
    Display.setFullscreen(false);
    Display.create();
    glViewport(0, 0, w, h);
}

static void renderLoop() {
    while (!Display.isCloseRequested()) {
        preRender();
        render();

        Display.update();
        Display.sync(300 /* desired fps */);
    }

    Display.destroy();
}

static void preRender() {

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    GLU.gluPerspective(45.0f, ((float) w / (float) h), 0.1f, 100.0f); // fix na błąd z kamerą

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

static void drawVBOtriangle(float s1[], float s2[], float s3[]) {
    // create geometry buffers
    FloatBuffer cBuffer = BufferUtils.createFloatBuffer(9);
    cBuffer.put(s1[3]).put(s1[4]).put(s1[5]);
    cBuffer.put(s2[3]).put(s2[4]).put(s2[5]);
    cBuffer.put(s3[3]).put(s3[4]).put(s3[5]);
    cBuffer.flip();

    FloatBuffer vBuffer = BufferUtils.createFloatBuffer(9);
    vBuffer.put(s1[0]).put(s1[1]).put(s1[2]);
    vBuffer.put(s2[0]).put(s2[1]).put(s2[2]);
    vBuffer.put(s3[0]).put(s3[1]).put(s3[2]);
    vBuffer.flip();

    IntBuffer ib = BufferUtils.createIntBuffer(2);

    glGenBuffersARB(ib);
    int vHandle = ib.get(0);
    int cHandle = ib.get(1);

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);

    glBindBufferARB(GL_ARRAY_BUFFER_ARB, vHandle);
    glBufferDataARB(GL_ARRAY_BUFFER_ARB, vBuffer, GL_STATIC_DRAW_ARB);
    glVertexPointer(3, GL_FLOAT, /* stride */3 << 2, 0L);

    glBindBufferARB(GL_ARRAY_BUFFER_ARB, cHandle);
    glBufferDataARB(GL_ARRAY_BUFFER_ARB, cBuffer, GL_STATIC_DRAW_ARB);
    glColorPointer(3, GL_FLOAT, /* stride */3 << 2, 0L);

    glDrawArrays(GL_TRIANGLES, 0, 3 /* elements */);

    glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);

    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);

    // cleanup VBO handles
    ib.put(0, vHandle);
    ib.put(1, cHandle);
    glDeleteBuffersARB(ib);
}

static void render() {
    glClearColor(1, 1, 1, 1);

    Camera.acceptInput(0.6f);
    Camera.apply();

    for (int i = 0; i < triangles.size(); i++) {
        // rysowanie trójkąta z modów...
        float s1[] = new float[6];
        s1[0] = triangles.get(i).getFirstModPoint().getX();
        s1[1] = triangles.get(i).getFirstModPoint().getY();
        s1[2] = triangles.get(i).getFirstModPoint().getZ();
        s1[3] = triangles.get(i).getFirstColor()[0];
        s1[4] = triangles.get(i).getFirstColor()[1];
        s1[5] = triangles.get(i).getFirstColor()[2];
        float s2[] = new float[6];
        s2[0] = triangles.get(i).getSecondModPoint().getX();
        s2[1] = triangles.get(i).getSecondModPoint().getY();
        s2[2] = triangles.get(i).getSecondModPoint().getZ();
        s2[3] = triangles.get(i).getSecondColor()[0];
        s2[4] = triangles.get(i).getSecondColor()[1];
        s2[5] = triangles.get(i).getSecondColor()[2];
        float s3[] = new float[6];
        s3[0] = triangles.get(i).getThirdModPoint().getX();
        s3[1] = triangles.get(i).getThirdModPoint().getY();
        s3[2] = triangles.get(i).getThirdModPoint().getZ();
        s3[3] = triangles.get(i).getThirdColor()[0];
        s3[4] = triangles.get(i).getThirdColor()[1];
        s3[5] = triangles.get(i).getThirdColor()[2];
        drawVBOtriangle(s1, s2, s3);
        glTranslatef(triangles.get(i).getStartPoint().x - oldX, triangles.get(i).getStartPoint().y - oldY, triangles.get(i).getStartPoint().z - oldZ);
        oldX = triangles.get(i).getStartPoint().x;
        oldY = triangles.get(i).getStartPoint().y;
        oldZ = triangles.get(i).getStartPoint().z;
    }
}

public static Vector3f getDirection() {
    Vector3f vector = new Vector3f();

    float rotX = Camera.getRotationX(); // pitch
    float rotY = Camera.getRotationY(); // yaw

    vector.y = (float) -Math.sin(Math.toRadians(rotY));

    float h = (float) Math.cos(Math.toRadians(rotY));

    vector.x = (float) (h * Math.sin(Math.toRadians(rotX)));
    vector.z = (float) (-h * Math.cos(Math.toRadians(rotX)));

    return vector;
}

```

}

EDIT: I rewrited the code and now i have ~250fps in 100x100 terrain. What should i did with coide to get more fps?

New code:

```
public class NGINE2 {
public static int MAX_PICKING_DISTANCE = 20;
public static int RAY_RADIUS = 5;
static int w = 640;
static int h = 480;
static float oldX = 0;
static float oldY = 0;
static float oldZ = 0;
static List<Triangle> triangles = new ArrayList<Triangle>();
static double[][]map;

static FloatBuffer cBuffer = BufferUtils.createFloatBuffer(9*(100*100*2));
static FloatBuffer vBuffer = BufferUtils.createFloatBuffer(9*(100*100*2));

public static void main(String[] args) throws Exception {
    NoiseHeightMap nsh = new NoiseHeightMap(100, 23495876);
    nsh.HeightmapPNG(nsh.getHeightmap(), "C:\\Users\\Przemo\\Desktop\\mapka.png");
    map = nsh.getHeightmap();
    Random rand = new Random();
    for (int x = 0; x < 100; x++) {
        for (int z = 0; z < 100; z++) {
            float rgb[] = new float[3];
            rgb[0] = rand.nextFloat();
            rgb[1] = rand.nextFloat();
            rgb[2] = rand.nextFloat();
            triangles.add(new Triangle(new Vector3f(x, (float) map[x][z]*100, z), new Vector3f(+0.5f, 1f, -0.5f),
                    new Vector3f(-0.5f, 1f, -0.5f), new Vector3f(+0.5f, 1f, +0.5f), rgb, rgb, rgb));
            triangles.add(new Triangle(new Vector3f(x, (float) map[x][z]*100, z), new Vector3f(-0.5f, 1f, +0.5f),
                    new Vector3f(-0.5f, 1f, -0.5f), new Vector3f(+0.5f, 1f, +0.5f), rgb, rgb, rgb));
        }
    }

    initContext();
    renderLoop();
}

static void initContext() throws Exception {
    Camera.create();

    w = 640;
    h = 480;

    Display.setDisplayMode(new DisplayMode(w, h));
    Display.setFullscreen(false);
    Display.create();
    glViewport(0, 0, w, h);
}

static void renderLoop() {
    long time = 0;
    int frames  = 0;

    for (int i = 0; i < triangles.size(); i++) {
        cBuffer.put(triangles.get(i).firstColor[0]).put(triangles.get(i).firstColor[1]).put(triangles.get(i).firstColor[2]);
        cBuffer.put(triangles.get(i).secondColor[0]).put(triangles.get(i).secondColor[1]).put(triangles.get(i).secondColor[2]);
        cBuffer.put(triangles.get(i).thirdColor[0]).put(triangles.get(i).thirdColor[1]).put(triangles.get(i).thirdColor[2]);

        vBuffer.put(triangles.get(i).firstModPoint.x).put(triangles.get(i).firstModPoint.y).put(triangles.get(i).firstModPoint.z);
        vBuffer.put(triangles.get(i).secondModPoint.x).put(triangles.get(i).secondModPoint.y).put(triangles.get(i).secondModPoint.z);
        vBuffer.put(triangles.get(i).thirdModPoint.x).put(triangles.get(i).thirdModPoint.y).put(triangles.get(i).thirdModPoint.z);
    }
    cBuffer.flip();
    vBuffer.flip();
    IntBuffer ib = BufferUtils.createIntBuffer(2);

    glGenBuffersARB(ib);
    int vHandle = ib.get(0);
    int cHandle = ib.get(1);

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);

    glBindBufferARB(GL_ARRAY_BUFFER_ARB, vHandle);
    glBufferDataARB(GL_ARRAY_BUFFER_ARB, vBuffer, GL_STATIC_DRAW_ARB);
    glVertexPointer(3, GL_FLOAT, /* stride */3 << 2, 0L);

    glBindBufferARB(GL_ARRAY_BUFFER_ARB, cHandle);
    glBufferDataARB(GL_ARRAY_BUFFER_ARB, cBuffer, GL_STATIC_DRAW_ARB);
    glColorPointer(3, GL_FLOAT, /* stride */3 << 2, 0L);

    while (!Display.isCloseRequested()) {

        preRender();
        render();

        Display.update();
        Display.sync(6000 /* desired fps */);

        // Calc FPS
         frames++;
         if( ( System.currentTimeMillis() - time ) >= 1000 ) {
            Display.setTitle(" FPS: " + (int)((frames * 1000)/( System.currentTimeMillis() - time )) );
            time = System.currentTimeMillis();
            frames = 0;
         }
    }

    glDeleteBuffersARB(ib);
    glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);
    ib.put(0, vHandle);
    ib.put(1, cHandle);
    Display.destroy();
}

static void preRender() {

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    GLU.gluPerspective(45.0f, ((float) w / (float) h), 0.1f, 100.0f); // fix na błąd z kamerą

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

static void render() {
    glClearColor(1, 1, 1, 1);

    Camera.acceptInput(0.6f);
    Camera.apply();

    int Count = 2*100*100;
    for(int Index = 0; Index < Count; Index++) {
        glDrawArrays(GL_TRIANGLES, Index*3, 3);
        glTranslatef(triangles.get(Index).getStartPoint().x - oldX, triangles.get(Index).getStartPoint().y - oldY, triangles.get(Index).getStartPoint().z - oldZ);
        oldX = triangles.get(Index).getStartPoint().x;
        oldY = triangles.get(Index).getStartPoint().y;
        oldZ = triangles.get(Index).getStartPoint().z;
    }
}

```

}

# Answer
**This is not how you are supposed to use VBOs** and you will likely get better performance from immediate mode (glBegin/glEnd).

There are a number of things seriously wrong with your code, including:

* You have a separate VBO for each triangle.
* You update the VBOs each frame whether they need it or not.
* You create and destroy the VBOs each frame.
* You unbind and disable state after each draw.

All of this has the end result of pushing the full data set to the GPU each frame, as well as dealing with object creation/destruction, as well as dealing with a large number of state changes.

Hence the fact that it's running slow.

Unfortunately you do sometimes see VBOs advertised as a general case performance optimization without making mention of the fact that you need to design your usage of them correctly otherwise it will likely end up worse.

Fixing this is going to require something of a rewrite. I can't do that for you, so here are some pointers in the correct direction.

* Stop creating objects at run time. This includes Java objects as well as OpenGL objects. Create them one-time-only at startup time instead, then reuse them at run time.
* Instead of a separate small VBO for each triangle create a single big VBO and put all of your triangles into it. Yes, it uses more memory, but that's a good thing.
* Use the *first* and *count* parameters of glDrawArrays to select a subrange of the VBO to draw - that's what they're there for. Alternatively if drawing the entire VBO at once is what you need, then do so - fewer draw calls gives higher performance.
* Use glBufferSubData to change data in an existing VBO rather than destroying it and creating a new one.
* Stop unbinding and disabling state after drawing. You're destroying any state change filtering or batching that the driver might be able to do to help you run fast.

The general theme here is that instead of generating and drawing triangles at run time, doing a lot of work each frame, you instead shift the work to startup time and do it one-time-only. This lets you reuse previously generated data and make fewer, more lightweight OpenGL calls at run time, and this is where performance comes from.

Good luck!
> 2 votes

---
Tags: java, 3d, lwjgl, vbo
---


# Question
Title: Handling Events & User Event Limits In Pygame
I am trying to make a vertical shoot em up using Python and Pygame. In order to handle timing, such as when certain enemies come out and other stage events, I've been using `pygame.time.set_timer()`.

For example, to start spawning simple enemies, I would do the following:

First setup a `USEREVENT`:

```
SPWNGRUNT = pygame.USEREVENT + 0

```

Then in the main loop, check for events:

```
for event in pygame.event.get():
    if event.type == self.SPWNGRUNT:
        spawnGrunt()

```

Then at some point, trigger the event on a timer:

```
pygame.time.set_timer(SPWNGRUNT, 600)

```

However, I have quickly ran out of these USEREVENTS. I eventually get the below error:

```
ValueError: Event id must be between NOEVENT(0) and NUMEVENTS(32)

```

My questions are this. Is there a way around this? Also, is there maybe a better way of managing timing and events that I am not seeing?

# Answer
> 1 votes
You can also use the time (delta time `dt`) that `clock.tick(fps)` returns to increase or decrease a timer variable.

```
import random
import pygame as pg

class Block(pg.sprite.Sprite):

    def __init__(self, pos):
        super().__init__()
        self.image = pg.Surface((40, 40))
        self.image.fill(pg.Color('sienna1'))
        self.rect = self.image.get_rect(topleft=pos)

def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    font = pg.font.Font(None, 30)
    all_sprites = pg.sprite.Group()
    # Delta time is the time that has passed since clock.tick
    # was called the last time.
    dt = 0
    # We'll subtract dt (delta time) from this timer variable.
    timer = 1  # 1 means one second.

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        # Decrease timer to get a countdown.
        timer -= dt
        # When the timer is below or equal to 0, we spawn
        # a new block.
        if timer <= 0:
            all_sprites.add(Block((random.randrange(600),
                                  random.randrange(440))))
            # Reset the countdown timer to one second.
            timer = 1
        all_sprites.update()
        screen.fill(pg.Color('gray15'))
        all_sprites.draw(screen)
        timer_surface = font.render(str(round(timer, 3)), True, pg.Color('yellow'))
        screen.blit(timer_surface, (20, 20))

        pg.display.flip()
        # dt = time in seconds that passed since last tick.
        # Divide by 1000 to convert milliseconds to seconds.
        dt = clock.tick(60) / 1000

if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()

```

Another alternative would be to use `pygame.time.get_ticks()` to calculate the passed time.

---
Tags: python, pygame
---


# Question
Title: Continuously flip sprite in unity script
I'm trying to flip a sprite on the X-axis continuously at a certain delay. That is, when the game starts the enemy sprite should keep flipping until destroyed.

I first tried adding it via animator but for some weird reason FlipX via animator was not working, scale and rotation would work but FlipX would have no effect. Maybe some bug?

Then I tried adding it as a script. I did some reading here and found that it can either be done via `Invoke()` or `Coroutine()`. I wrote the script below from examples but it is not working. It flips the sprite at start and then stops. How do I make it flip continuously?

```
private bool flipState;

    // Use this for initialization
    void Start () {
        flipState = false;
        StartCoroutine("Flippy");

    }

    void Update()
    {

    }

    IEnumerator Flippy()
    {
        while (true)
        {
            GetComponent<SpriteRenderer>().flipX = !flipState;
            yield return new WaitForSeconds(1f);
            GetComponent<SpriteRenderer>().flipX = !flipState;
        }

    }

```

# Answer
You're setting flipX to true and then you wait one second then set it to true again. I don't see how it's supposed to be flipping it. Also, even if you did flip it, it would be flipped once at first and then flipped twice at every other iteration after that, because your loop goes like this:

```
flip -> wait -> flip -> flip -> wait -> flip -> flip -> ...

```

Something like this should work:

```
while (true)
    {
        GetComponent<SpriteRenderer>().flipX = flipState;
        flipstate = !flipstate;
        yield return new WaitForSeconds(1f);
    }

```
> 1 votes

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


# Question
Title: Number Guessing Game: How to ensure player cannot be dishonest about their guess
I'm building a number guessing game in Unity. The computer has 10 chances to guess the number the player is thinking of. The player interacts by pressing Higher or Lower or Correct Guess.

The basic game works fine, as long as the player is honest. I'm now trying to make the game watertight and prevent any user error or dishonesty about their number. I created some test conditions to check if the random number generator has produced a number already used before, or to check if the player is pressing Higher or Lower beyond the *max* and *min* guess range.

The problem can be demonstrated well by constantly pressing Lower to the point where the final guess is the number 1. Pressing Lower again results in the game freezing. It also happens if the number you are thinking of is displayed and you press Higher or Lower towards a range of numbers which have already been eliminated as possibilities. I am thinking this is due to the game getting stuck in my *while loop* in **MakeGuess()**.

I think the problem lies in the following test condition in **MakeGuess()** but any tweaks I make seem to have no effect:

```
// check if number has been guessed before
if (newGuess == guess && (newGuess > max || newGuess < min)) {

```

I've uploaded my current playable build to GameBucket.io here: https://gamebucket.io/game/07cc2b61-493b-46ae-a446-aeaa98ffac0e

All the game logic is handled in the NumberWizard script which is attached to the NumberWizard GameObject in the main Game scene:

```
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class NumberWizard : MonoBehaviour
{
    int max;
    int min;
    int newGuess;
    public int guess;
    public int maxGuessesAllowed = 10;

    public Text text;
    public Text guessesRemaining;

    // Use this for initialization
    void Start()
    {
        StartGame();
    }

    void StartGame()
    {
        max = 1000;
        min = 1;

        MakeGuess();
        UpdateDisplay();
    }

    public void GuessHigher()
    {
        min = guess;
        NextGuess();
    }

    public void GuessLower()
    {
        max = guess;
        NextGuess();
    }

    public void GuessCorrect()
    {
        StartGame();
        SceneManager.LoadScene("Lose");
    }

    void NextGuess()
    {
        if (maxGuessesAllowed <= 0) SceneManager.LoadScene("Win");

        MakeGuess();
        maxGuessesAllowed -= 1;
        UpdateDisplay();
    }

    void UpdateDisplay()
    {
        text.text = guess.ToString() + " ?";
        guessesRemaining.text = maxGuessesAllowed.ToString();
    }

    void MakeGuess()
    {
        //guess = (max + min) / 2; // old guessing method

        bool validGuess = false;

        while (validGuess == false)
        {
            newGuess = GenerateNumber();

            // check if number has been guessed before
            if (newGuess == guess && (newGuess > max || newGuess < min))
            {
                Debug.Log("Number has been guessed before and is already at either range limit.");
                SceneManager.LoadScene("Lose2");
            }
            else if(newGuess == guess)
            {
                newGuess = GenerateNumber();
                Debug.Log("Number has been guessed before but is not at range limit.");
            }
            else
            {
                validGuess = true;
                guess = newGuess;
                Debug.Log("Number has not been guessed before.");
            }

            Debug.Log("Min: " + min);
            Debug.Log("Max: " + max);
            Debug.Log("====================");
        }
    }

    int GenerateNumber() {
        int result = Random.Range(min, max + 1); return result;
    }
}

```

Any help with the code

# Answer
The problem isn't with the MakeGuess part of what you're doing, it's changing the value of min or max in GuessHigher or GuessLower.

This can be done by adding an if statement to each of these:

```
public void GuessHigher()
{
    if (guess > min)
    {
        min = guess;
        NextGuess();
    }
}

public void GuessLower()
{
    if (guess < max)
    {
        max = guess;
        NextGuess();
    }
}

```

This will also give you the chance to add an Else statement to give you a bit of cover to a cheating player since if the AI has guessed 1 and the player says it is lower, they are cheating / lying.
> 1 votes

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


# Question
Title: Unity mobile game generates too much cache
I have built a game I have been working on for Android (Unity). It's a simple game: air hockey. It weights 21mb with all the assets and scripts.

After playing for a bit I have noticed that cache of the game is growing very fast and probably infinitely (to use all phone memory). The game itself takes 43.20mb installed. But cache for me right now is 80mb.

I have similar games installed and they take up to a 6mb max. And definitely, the cache is growing slower for them.

Previous games that I have developed doesn't have this issue. For example, the game that takes 80mb disk space has only 532KB of cache and it's not growing.

I thought of manually clearing the cache every time player leaves the game. I haven't found any relative information on how to do that in unity, but that is probably even not the right way to do it. All I have found is how to delete GI cache... and the google search doesn't show anything relevant.

How can I track what is creating so much cache? Is there an easy way to do it within Unity? Or how can I request cache deletion from code?

# Answer
I have done some intensive testing and figured out that cache grows only before UnityAds show. It can grow earlier than ad is displayed. Then I have done some searching and unity ads do cache video ads inside internal storage. But how to prevent it from doing it? I haven't found any information on this yet, as soon as I find some I will post an edit.

You can delete cache using `Caching.ClearCache();` inside Unity - it will delete all the cache created by the application.

It's weird that UnityAds don't have auto-deletion of cached ads. But maybe it's for the better, so that developer can control the process.
> 0 votes

---
Tags: unity, android, memory-efficiency
---


# Question
Title: Camera math: How to calculate the horizontal and vertical angle from the look at vector
I'm using the **PerspectiveCamera** class in C#/WPF to implement an FPS style camera.

For that, I would need to offset the camera's horizontal and vertical angles every time the mouse is moved. The problem is that PerspectiveCamera doesn't store those angles and only provides a lookat vector.

So, is there a way to **calculate those angles from the lookat vector** ?

# Answer
If there is no roll in your FPS camera (typically, there is not in an FPS) then all you need to do to get a yaw angle (-π..π ) from the vector is the atan2() function.

As suggested by DMGregory, the arcsin of the z component of the forward vector gives the tilt angle.

```
#include <math.h>
...

// calculate yaw
const float yaw_angle = atan2f( cam_fwd.y, cam_fwd.x );

// calculate pitch
const float pitch_angle = asinf( cam_fwd.z );

```

This assumes you know where the camera is looking (cam\_fwd.)
> 1 votes

---
Tags: mathematics, camera, wpf
---


# Question
Title: Do you really have to sync Physics over the network?
Let's say you want to create a 2D game where a character can shoot a bullet. You have the same code running on the Client and Server (JavaScript so it's exactly the same code).

If the client and the server create the same bullet instance at the same tick X, with the same position, direction and velocity, is it safe to assume that the bullet will end on the same place on both the server and the client? Does the server need to send back the exact position at which the bullet collided, or can the client just predict that as it uses the same physics and same bullet initial data.

Can the bullet hit the target on a different tick, or at a different position on the server from the client? My initial thought is that this shouldn't happen, but could this happen because of a different CPU architecture or a different JavaScript engine?

# Answer
What you're describing is usually called "lockstep", it's very common in RTS multiplayer games, like Starcraft.

Lockstep Network Implementation in Unity

Usually most multiplayer games will try do to some smoothing and prediction to prevent laggy behaviour.
> 1 votes

---
Tags: physics, javascript, networking, synchronization
---


title: UnityEvent Array coding C#

text:
# Question
Title: UnityEvent Array coding C#
I am fairly new to Unity 5, as I was browsing through some prefabs, I found one for the Main menu in which UnityEvent was used in scripts to list down the menu options.

This UnityEvent was an array UnityEvent \[ \] Event, which was nowhere initialized to anything but was showing no compiler errors and also during run, it was pointing to some predefined sets which the author was mentioning in the user manual... My questions are :

* Is it possible to use UnityEvent Array without mentioning the size of the array.
* What happens to the UnityEvent if we don't mention any of the events, but the Invoke functionality is called during runtime.

Btw, the prefab i used from was :Main Menu with Parallax effects

# Answer
To complete my comment:

1. If a public variable isn't initialized it will once you create an instance of the component in the editor. So basically the array will be instantiated, but the length is zero. Unity does the same for Lists.
2. The array is most likely used in conjunction with a for loop. If your array is of length 0, the for loop exits before it even enters the loop body.

The following is completely valid:

```
public class Test : MonoBehaviour {

public int[] myArray; // On adding this component myArray gets initialized

// Update is called once per frame

void Update () {

    //myArray.Length is zero, so the Debug.Log is never run

    for(int i = 0; i < myArray.Length; i++){
        Debug.Log(myArray[i]);
    }
  }
}

```
> 1 votes

---
Tags: unity, unityscript
---


# Question
Title: How to prevent objects from colliding into each other in the Unity editor?
I am building a map for a game... I am making most of the buildings with cubes. When I move a cube next to another one they go through each other... Which creates flickering. This is making it very hard to build the map. How do I enable collisions in the editor (Make it so they don't go through each other when you try to move one)?

Here is a picture:

# Answer
Try this:

> **Surface snapping**
>
> While dragging in the center using the Move tool, hold Shift and Control (Command on Mac) to quickly snap the GameObject to the intersection of any Collider.

https://docs.unity3d.com/Manual/PositioningGameObjects.html

Vertex snapping, also mentioned in that manual page, is often useful as well.

By the way, the flickering you describe is known as "Z-fighting."
> 1 votes

---
Tags: unity, collision-detection, map-editor
---


# Question
Title: How to rotate a rectangle body around a fixed point?
How to rotate a body around a point? The body has x, y, speed and angle. Coordinates of the body relative to its center. Additional conditions: point position and distance from body to point.

# Answer
> 1 votes
First off, you have redundancy in your state.

It is enough to track:

* angle (scalar.)
* angular velocity (scalar.)
* centre of rotation (2d vector.)
* radius (scalar.)

from this you can determine:

* the body's position (2d vector.)
* the body's orientation (local frame defined by body-up-vector, a 2d unit vector.)

To rotate it with timestep dt, you would do:

```
angle += dt * angular_velocity
body.up.x = cosf( angle )
body.up.y = sinf( angle )
body.pos.x = centre.x + radius * body.up.x
body.pos.y = centre.y + radius * body.up.y

```

Note that instead of defining the body's rotation with an up-vector, you could use an x-vector, or even just an angle, which in your problem is the same as the angle with which the body is rotated around the centre. But when drawing your object on screen, you need a frame with two axes anyway: an x-axis and an y-axis (object's up vector.) As the axes are perpendicular it is easy to derive the x-axis from the y-axis by simply swapping the components.

---
Tags: mathematics, body
---


# Question
Title: How can I make the main game loop frame-rate independant?
I am trying to create a frame independent game loop.

I am currently using the following code

```
 private class MainGameThread extends Thread {
        public static final int PAUSE_SLEEP_TIME = 10;
        long previous = getCurrentTimeInMillis();
        long totalElapsed = 0;
        long gameTimeStart = 0;
        long currentTime = getCurrentTimeInMillis();
        long accumulatorTime = 0;

        @Override
        public void run() {
            gameTimeStart = getCurrentTimeInMillis();
            while (mIsRunning) {
                // Pause game
                while (mIsPaused) {
                    try {
                        Thread.sleep(PAUSE_SLEEP_TIME);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                long current = getCurrentTimeInMillis();
                long elapsed = current - previous;
                previous = current;
                processGameInput();
                updateGameState(elapsed);
                totalElapsed += elapsed;
                if (totalElapsed > MainGame.MS_PER_FRAME) {
                    drawGame();
                    totalElapsed -= MainGame.MS_PER_FRAME;
                    if (totalElapsed > MainGame.MS_PER_FRAME) {
                        Log.e("GAME", "Performance warning, rendering or update took too long");
                    }
                }
                checkIfGameShouldStop(gameTimeStart);
            }
            shutdownGracefully();
        }

        private void shutdownGracefully() {
        }
    }

```

It works, however it performs differently on different devices.

In my game models `update method` I am performing the following actions

```
  mCenterX += (mVelocityVector.x * timeElapsed);
  mCenterY += (mVelocityVector.y * timeElapsed + gameSpeed.getValue())

```

I have read this article, but I can't understand the final example:

```
double t = 0.0;
double dt = 0.01;

double currentTime = hires_time_in_seconds();
double accumulator = 0.0;

State previous;
State current;

while ( !quit )
{
    double newTime = time();
    double frameTime = newTime - currentTime;
    if ( frameTime > 0.25 )
        frameTime = 0.25;
    currentTime = newTime;

    accumulator += frameTime;

    while ( accumulator >= dt )
    {
        previousState = currentState;
        integrate( currentState, t, dt );
        t += dt;
        accumulator -= dt;
    }

    const double alpha = accumulator / dt;

    State state = currentState * alpha +
        previousState * ( 1.0 - alpha );

    render( state );
}

```

What does the State class object mean in this case?

Could someone please help to adapt this example to my case or explain the example from the article and how I could update my loop to be frame independent?

# Answer
The `State` is meant to represent all of the data your program needs to render the current scene. So `mCenterX` and `mCenterY` in your example, (plus whatever else you might be drawing.) There's not a strict need for it to all live inside one class, although I have found it useful to do so in the past.

The article is suggesting that you linearly interpolate or "lerp" the current state with the previous state, (that is, the one most recently calculated, which may not be the one that was shown last.) You'll have to define your own lerp method for the class or classes that hold your state, usually delegating to the one for the members of your class. Non-number values like booleans and enums do not need to be lerped, you can just use the newest values.

The article explains why you need to lerp, if you don't want jerky motion in some cases:

> ...consider a situation where the display framerate is 60fps and the physics is running at 50fps. There is no nice multiple so the accumulator causes the simulation to alternate between mostly taking one and occasionally two physics steps per-frame when the remainders “accumulate” above dt.

So in those cases where two physics steps happen per frame, a moving object would appear to jump farther than it should. So instead we lerp, placing the object between the two states, based on how much time has elapsed.

Hopefully now you understand enough of the idea adjust your code yourself. You'll have to decide how you want to arrange your equivalent of the `State` class.

Further reading:This book chapter also compares different game loop methods including the one mentioned above.
> 3 votes

---
Tags: java, android, game-loop, frame-rate
---