title: How to compile shader files in UWP

text:
# Question
Title: How to compile shader files in UWP
I wish to use this method

```
byte[] vertexShaderByteCode = ShaderBytecode.CompileFromFile(".......Transf_VS.hlsl", "VS", "vs_5_0");
                this.vertexShader = new D3D11.VertexShader(
                    device,
                    vertexShaderByteCode
                    );

```

But it throws exception of either file not found or file cannot be open.

Is there any solution to this? I saw HelixToolkit using shader files that has already been compiled, how is it done then? https://github.com/helix-toolkit/helix-toolkit/blob/master/Source/HelixToolkit.UWP/Model/ExampleCube3D.cs

```
// Loads vertex shader bytecode
            var vertexShaderByteCode = NativeFile.ReadAllBytes(path + "\\MiniCube_VS.fxo");
            this.vertexShader = new VertexShader(d3dDevice, vertexShaderByteCode);

```

Thank you

# Answer
> 0 votes
Here's a solution without explanation, it should apply for UWP apps:

**I manually put the shader files in a directory** like this

```
System.IO.Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "ProjectName")

```

which in my case would be

```
F:\*****\SolutionFolder\StartupProjectFolder\bin\x64\Debug\AppX\FolderWithCurrentProjectName

```

Then the compiler can read the shader files, it works for either fx. files(hlsl source code) and fxo. files(compiled before the whole solution with another program the fxc.exe). The second method can use the guidance fromhttp://stackoverflow.com/questions/23293760/creating-fxo-shader-file-using-fxc-exe

**There are other complications that one might want to notice**

1. the visual studio create txt. files with UTF-8 coding, you may want to check out in ASCII coding to remove the chars at the beginning of a file, which may cause problem.
2. fxc.exe can be found for example in this directory

C:\Program Files (x86)\Windows Kits\10\bin\x64
3. You'd better copy the fxc.exe into another folder to run it, the directory of the exe. file and source file would better not contain blanks in any of its folder names in the path.

The idea comes from the example made by HelixToolkit. You see there are lot of bumps in route and since few are doing sharpdx + uwp right now we have to sweep them ourselves. I hope this can help others who face the same problem, and of course I hope there are pros who can explain why this works and otherwise it doesn't.

Thank you.

# Answer
> 0 votes
I was under the impression you had to have precompiled shader files under UWP. There is a tool, and info in the MSDN site for compiling files.

Apologies if this is not completely correct, more here say on my front.

https://msdn.microsoft.com/en-us/library/windows/desktop/bb509633(v=vs.85).aspx#compiling\_at\_build\_time\_to\_object\_files

# Answer
> 0 votes
If you look at my answer to another question I show the steps of setting Visual Studio to compile shaders with a separate C++ project, you could use it the same way but just have the output option in the HLSL compiler tab set to your folder, that way you can build your shaders in VS and if you read my full answer I have a link to a nice tool as well.

First up make a new C++ project and call it shader builder, add a filter called shaders and then follow these steps

---
Tags: shaders, hlsl, windows, sharpdx
---


# Question
Title: DirectX 11 Predication(Occlusion culling)
Right now I'm using Predication to cull my BV tree after I first cull it with a few different view frustums, to get different ranges of objects to pass on to other parts of the engine. Life is good it works and has been a big save for me!

What I basically do is cull all the extracted BV trees nodes against the current depth buffer and it takes a few frames but I then do this:

```
 If g_pPredicate IsNot Nothing Then
        Dim tester As Boolean = _context.IsDataAvailable(g_pPredicate)
        If tester Then
            Dim ds As DataStream = _context.ImmediateContext.GetData(g_pPredicate)
            Predication = ds.Read(Of Boolean)
            ds.Dispose()
            ds = Nothing
        End If
    End If

```

to check the current occlusion of the BV tree node when I next update on the cpu, like I said it happens a few frames late but I can live with that for now.

The way I hide the lag is by only using the Predication result on tree nodes that are far from the camera and I also only update the visible tree nodes every 6 frames.

I also know after read the MSDN docs that I can use a different flag to just do the actual drawing of the object with the Predication hint and not return a value to the cpu but I don't think it will work with my instance drawing and I imagine that testing BV nodes would be faster than testing all the objects because BV nodes hold objects so if I cant see a node then I know that the objects want bee seen.

My question is, should I be down sampling the depth buffer and doing the Predication query's in a smaller resolution because that would allow me the get the returned value faster? Would it still take the same amount of time or am I doing it wrong?

# Answer
> 0 votes
Turns out after much testing that I should be using a standard occlusion query because I can read it back on the CPU, I found out by reading the MSDN doc that if I use the pred query with the hint flag then I cant read it back on the CPU and without the hint flag I had no point to use the pred query.

So the next part was the popping and query lag, I fixed this by reordering my update and occ querys, so now I fire off an occ query then once it returns I then fire off a new occ query and update update my mesh data with the old occ.

Because I only update mesh data every few frames I can have the query and update synced up and don't see any popping\query lag that's also because I cant move far enough in the time it takes to fire off and return querys so I end up sending out less and less occ querys, of course if I make really large jumps or fly up\run really fast then I de-sync a bit and spike occ querys but the player should never move that fast anyway and even with the testing spike because I check for the return in a none blocking way I don't really see any perf hit, just some popping until I slow to sain speeds.

---
Tags: directx11, sharpdx, culling
---


# Question
Title: Unity UI Image Prevent Camera To Render All Object In Front Of It
i confused why is this happen , i know there's already available post that discuss this but i cannot find it at google. My problem is that my UI image with sprite hide rendering all object in front of it ( so the camera view only show the image ) .

Screenshot In 3D Mode :

I Put A Square Object Right In Front Of The Image

And This Is The Camera Position With Camera Preview

Sorry i only can put 2 screenshot because below reputation 10 i can't put more than 2 picture .

As you see , the camera should render the " StartBox " either " MenuBox " but none are rendered even it's in front of camera view

# Answer
> 1 votes
Your Canvas is set to *Screen Space Overlay* which means it renders on top of everything in the scene. If you want to have a stretched background image behind objects in the scene you will need to use either a *World Space* Canvas or *Screen Space Camera*. Tutorial on the canvas system here: https://unity3d.com/learn/tutorials/topics/user-interface-ui/ui-canvas

---
Tags: unity, 2d
---


# Question
Title: How do I edit runtime variables within a custom C++ game engine?
I want to add a feature to my game engine where I can change different variables that control in-game things while the engine is still running from a console window.

I have designed the engine in C++, and because of its compile-time nature, I don't think it's possible to change inner-working variables during run-time. I have looked at python extensions for C++, but I do not know if that will be sufficient to change values while the program is running.

How do I edit runtime variables within a custom C++ game engine?

# Answer
> 4 votes
Of course you can change variables during run time, your engine is doing in constantly, otherwise it wouldn't be an interactive! It'll be a lot of work to dynamically list variables, since you'd have to create some kind of preprocessor to parse the code (essentially recreating C#s reflection).

* Create callbacks for each variable you want to be able to modify
* Add them to a dictionary with their name as the key.
* Your terminal just looks for the key and parses the input to convert it to the correct type, then sets the variable.
* You'll also need events for when variables change, to reload the systems that use those variables

---
Tags: c++
---


# Question
Title: Need help in making buttons for MenuScreen in Java
I'm making a Menu for my game and I made the MenuState(class) and made a MouseManager(class, implemented MouseListener and MouseMotionListener) and they are different class in different folder. Here is my problem, usually people make their buttons my drawing rectangles and adds font and makes that their button. But I didn't do that. I made a button using Photoshop and I put it in my sprite sheet, cropped it and made it my button. now I want to make it that if I click on my 'play' button picture it sends to my GameState and if I click on my 'exit' button picture it closes my window

**MyMenuState(class)**

```
 package com.vescorspel.game.MyFirstGame.states;

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

import com.vescorspel.game.MyFirstGame.Handler;
import com.vescorspel.game.MyFirstGame.gfx.Assets;

public class MenuState extends State{
// Resizing my button from 64 pixels to 256 pixels
public static final int ButtonWidth = 256;
public static final int ButtonHeight = 256;

// coordinates where my buttons are placed in pixels ;)
public static final int PlayButtonX = 500;
public static final int PlayButtonY = 100;
public static final int ExitButtonX = 500;
public static final int ExitButtonY = 400;

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

// My tick method
@Override
public void tick() {
 //This If statement tells my game if I LeftClicked anywhere in the MenuScreen, then it send me to my GameState(GameScreen)
 if(handler.getMouseManager().isLeftPressed())
  State.setState(handler.getGame().gameState);;
}

//My render where i render the button pictures in my MenuScreen
@Override
public void render(Graphics g) {
 //PlayButton from my Assets class(this is an image)
    g.drawImage(Assets.PlayButton, PlayButtonX, PlayButtonY, ButtonWidth, ButtonHeight, null );
    //ExitButton from my Assets class(this is an image)
    g.drawImage(Assets.ExitButton, ExitButtonX, ExitButtonY, ButtonWidth, ButtonHeight, null);
    //these 2 commands tells my game to make a red cube and follow my mouse in the MenuScreen
    g.setColor(Color.RED);
    g.fillRect(handler.getMouseManager().getMouseX(), handler.getMouseManager().getMouseY(), 8, 8);
}
}
```

**MouseManager(class)**

```
package com.vescorspel.game.MyFirstGame.input;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

public class MouseManager implements MouseListener, MouseMotionListener{
 private boolean leftPressed;
 private int mouseX, mouseY;

 public MouseManager(){
 }

 //Getters

 public boolean isLeftPressed(){
     return leftPressed;
 }

 public int getMouseX(){
     return mouseX;
 }

 public int getMouseY(){
     return mouseY;
 }

 // Implemented methods

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

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

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

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

 }

 @Override
 public void mouseClicked(MouseEvent e) {
 }

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

 }

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

}
```

# Answer
> 1 votes
All you need to do is verify that the mouse is inside the image, if you want to do this properly you should have an array of your own button classes which have methods to check collisions. Checking the actual collision of these buttons is trivial, just verify that the mouse coords are within the range of coordinates covered by the sprite, do this by validating that the mouse coordinates are greater that the x and y positions, but not greater than the x and y positions plus the width and height respectively, like this:

```
if ((mouseX > PlayButtonX && mouseX < (PlayButtonX + ButtonWidth)) && (mouseY > PlayButtonY && mouseY < (PlayButtonY + ButtonHeight)) {
     //play button has been clicked

```

---
Tags: java, game-mechanics, eclipse, menu
---


# Question
Title: What is the point of update independent rendering in a game loop?
There are dozens of articles, books and discussions out there on game loops. However, I pretty often come across something like this:

```
while(running)
{
    processInput();
    while(isTimeForUpdate)
    {
        update();
    }
    render();
}

```

What basically is bothering me about this approach is the "update-independent" rendering e.g. render a frame when there is no change at all. So my question is why this approach is often taught?

# Answer
There's a long history of how we arrived at this common convention, with lots of fascinating challenges along the way, so I'll try to motivate it in stages:

## 1. Problem: Devices run at different speeds

Ever try to play an old DOS game on a modern PC, and it runs unplayably fast - just a blur?

A lot of old games had a very naive update loop - they'd collect input, update game state, and render as fast as the hardware would allow, without accounting for how much time had elapsed. Which means as soon as the hardware changes, the gameplay changes.

We generally want our players to have a consistent experience and game feel on a range of devices, (as long as they meet some minimum spec) whether they're using last year's phone or the newest model, a top-end gaming desktop or a mid-tier laptop.

In particular, for games that are competitive (either multiplayer or via leaderboards) we don't want players running on a particular device to have an advantage over others because they can run faster or have more time to react.

The surefire solution here is to lock the rate at which we do gameplay state updates. That way we can guarantee the results will always be the same.

## 2. So, why not just lock the framerate (eg. using VSync) and still run the gameplay state updates & rendering in lockstep?

This can work, but is not always palatable to the audience. There was a long time when running at a solid 30 fps was considered the gold standard for games. Now, players routinely expect 60 fps as the minimum bar, especially in multiplayer action games, and some older titles now look noticeably choppy as our expectations have changed. There's also a vocal group of PC players in particular who object to framerate locks at all. They paid a lot for their bleeding-edge hardware, and want to be able to use that computing muscle for the smoothest, highest-fidelity rendering it's capable of.

In VR in particular, framerate is king, and the standard keeps creeping up. Early in the recent resurgence of VR, games often ran around 60 fps. Now 90 is more standard, and harware like the PSVR is beginning to support 120. This may continue to rise yet. So, if a VR game limits its framerate to what's doable & accepted today, it's liable to be left behind as hardware and expectations develop further.

(As a rule, be wary when told "players can't perceive anything faster than XXX" as it's usually based on a particular type of "perception," like recognizing a frame in sequence. Perception of continuity of motion is generally far far more sensitive. )

The last issue here is that a game using a locked framerate also needs to be conservative - if you ever hit a moment in the game where you're updating & displaying an unusually high number of objects, you don't want to miss your frame deadline and cause a noticeable stutter or hitch. So you either need to set your content budgets low enough to leave headroom, or invest in more complicated dynamic quality adjustment features to avoid pegging the whole play experience to the worst-case performance on min-spec hardware.

This can be especially problematic if the performance problems show up late in development, when all your existing systems are built & tuned assuming a lockstep rendering framerate that now you can't always hit. Decoupling update & rendering rates gives more flexibility for dealing with performance variability.

## 3. Doesn't updating at a fixed timestep have the same problems as (2)?

I think this is the meat of the original question: if we decouple our updates and sometimes render two frames with no game state updates in between, then isn't it the same as lockstep rendering at a lower framerate, since there's no visible change on the screen?

There's actually several different ways games use the decoupling of these updates to good effect:

**a) The update rate can be *faster* than the rendered framerate**

As tyjkenn notes in another answer, physics in particular is often stepped at a higher frequency than the rendering, which helps minimize integration errors and give more accurate collisions. So, rather than having 0 or 1 updates between rendered frames you might have 5 or 10 or 50.

Now the player rendering at 120 fps can get 2 updates per frame, while the player on lower spec hardware rendering at 30 fps gets 8 updates per frame, and both their games run at the same gameplay-ticks-per-realtime-second speed. The better hardware makes it look smoother, but doesn't radically alter how the gameplay works.

There's a risk here that, if the update rate is mismatched to the framerate, you can get a "beat frequency" between the two. Eg. most frames we have enough time for 4 game state updates and a little leftover, then every so often we have enough saved up to do 5 updates in a frame, making a little jump or stutter in the movement. This can be addressed by...

**b) Interpolating (or extrapolating) the game state between updates**

Here we'll often let the game state live one fixed timestep in the future, and store enough information from the 2 most recent states that we can render an arbitrary point between them. Then when we're ready to show a new frame on-screen, we blend to the appropriate moment for display purposes only (ie. we don't modify the underlying gameplay state here)

When done right this makes the movement feel buttery smooth, and even helps to mask some fluctuation in framerate, as long as we don't drop *too* low.

**c) Adding smoothness to non-gameplay-state changes**

Even without interpolating gameplay state, we can still get some smoothness wins.

Purely visual changes like character animation, particle systems or VFX, and user interface elements like HUD, often update separately from the gameplay state's fixed timestep. This means if we're ticking our gameplay state multiple times per frame, we're not paying their cost with every tick - only on the final render pass. Instead, we scale the playback speed of these effects to match the length of the frame, so they play as smoothly as the rendering framerate allows, without impacting game speed or fairness as discussed in (1).

Camera movement can do this too - especially in VR, we'll sometimes show the same frame more than once but reproject it to take into account the player's head movement in between, so we can improve the perceived latency and comfort, even if we can't natively render everything that fast. Some game streaming systems (where the game is running on a server and the player runs only a thin client) use a version of this too.

## 4. Why not just use that (c) style for everything? If it works for animation and UI, can't we simply scale our gameplay state updates to match the current framerate?

Yes\* this is possible, but no it's not simple.

This answer is already a bit long so I won't go into all the gory details, just a quick summary:

* Multiplying by `deltaTime` works to adjust to variable-length updates for *linear* change (eg. movement with constant velocity, countdown of a timer, or progress along an animation timeline)
* Unfortunately, many aspects of games are *non-linear*. Even something as simple as gravity demands more sophisticated integration techniques or higher-resolution substeps to avoid diverging results under varying framerates. Player input and control is itself a huge source of non-linearity.
* In particular, the results of discrete collision detection and resolution depend on update rate, leading to tunneling and jittering errors if frames get too long. So a variable framerate forces us to use more complex/expensive continuous collision detection methods on more of our content, or tolerate variability in our physics. Even continuous collision detection runs into challenges when objects move in arcs, requiring shorter timesteps...

So, in the general case for a game of medium complexity, maintaining consistent behaviour & fairness entirely through `deltaTime` scaling is somewhere between very difficult & maintenance intensive to outright infeasible.

**Standardizing an update rate** lets us guarantee more **consistent behaviour across a range of conditions**, often with simpler code.

Keeping that update rate **decoupled from rendering** gives us **flexibility** to control the smoothness and performance of the experience **without altering the gameplay logic**.

Even then we never get truly "perfect" framerate independence but like so many approaches in games it gives us a controllable method to dial in toward "good enough" for the needs of a given game. That's why it's commonly taught as a useful starting point.
> 124 votes

# Answer
The other answers are good and talk about why the game loop exists and should be seperate from the render loop. However, as for the specific example of "Why render a frame when there hasn't been any changes?" It really just comes down to hardware and complexity.

Video cards are state machines and they're really good at doing the same thing over and over again. If you only render things that have changed, it's actually more expensive, not less. In most scenarios, there's not much of anything that's static, if you move to the left slightly in an FPS game, you've changed the pixel data of 98% of stuff on the screen, you might as well render the whole frame.

But mainly, complexity. Keeping track of everything that's changed while doing an update is a lot more expensive because you have to either rework everything or keep track of the old result of some algorithm, compare it to the new result and only render that pixel if the change is different. It depends on the system.

The design of hardware etc. is largely optimised for current conventions, and a state machine has been a good model to start from.
> 8 votes

# Answer
Rendering is usually the slowest process in the game loop. Humans don't easily notice a difference in a frame rate faster than 60, so it often less important to waste time on rendering faster than that. However, there are other processes that would benefit more from a faster rate. Physics is one. Too big of a change in one loop can cause objects to glitch right past walls. There may be ways to get around simple collision errors on larger increments, but for lots of complex physics interactions, you just aren't going to get the same accuracy. If the physics loop is run more frequently though, there is less of a chance of glitches, since objects can be moved in smaller increments without being rendered every time. More resources go toward the sensitive physics engine and less are wasted on drawing more frames the user can't see.

This is especially important in more graphics-intensive games. If there was one render for every game loop, and a player did not have the most powerful machine, there may be points in the game where the fps drops to 30 or 40. While this would still be a not entirely horrible frame rate, the game would start to get fairly slow if we tried keeping each physics change reasonably small to avoid glitching. The player would be annoyed that his character walks only half the normal speed. If the rendering rate was independent from the rest of the loop, however, the player would be able to stay at a fixed walk speed despite the drop in frame rate.
> 6 votes

# Answer
A construction like the one in your question can make sense if the rendering subsystem has some notion of *"elapsed time since last render"*.

Consider, for instance, an approach in which the position of an object in the game world is represented through fixed `(x,y,z)` coordinates with an approach that additionally stores the current movement vector `(dx,dy,dz)`. Now, you could write your game loop so that the change of the *position* has to occur in the `update` method, but you could also design it so that the change of the *movement* has to occur during `update`. With the latter approach, even though your game state actually won't change until the next `update`, a `render`-function that is called at a higher frequency could already draw the object at a slightly updated position. While this technically leads to a discrepancy between what you see and what is represented internally, the difference is small enough to not matter for most practical aspects, yet allows animations to look much smoother.

Predicting "the future" of your game state (despite the risk of being wrong) can be a good idea when you take for instance the latencies of network input into account.
> 4 votes

# Answer
In addition to other answers...

Checking for change of state requires significant processing. If it takes similar (or more!) processing time to check for changes, compared to actually doing the processing, you really haven't made the situation better. In the case of rendering an image, as @Waddles says, a video card is *really* good at doing the same dumb thing over and over again, and it's more costly to check each chunk of data for changes than it is to simply transfer it across to the video card for processing. Also if the rendering is gameplay then it's really unlikely for the screen *not* to have changed in the last tick.

You're also assuming that rendering takes significant processor time. This very much depends on your processor and graphics card. For many years now, the focus has been on offloading progressively more sophisticated rendering work to the graphics card and reducing the rendering input needed from the processor. Ideally the processor's `render()` call should simply set up a DMA transfer and that's it. Getting data to the graphics card is then delegated to the memory controller, and producing the image is delegated to the graphics card. They can be doing that in their own time, while the processor *in parallel* carries on with the physics, gameplay engine and all the other stuff which a processor does better. Obviously the reality is a lot more complicated than that, but being able to offload work to other parts of the system is also a significant factor.
> 4 votes

---
Tags: game-loop, fixed-timestep
---


title: Trapping Asserts in Visual Studio

text:
# Question
Title: Trapping Asserts in Visual Studio
I'm writing a 2D game with some fairly complex off-screen logic, with plenty of room for bugs. My usual habit is to write code with a lot of Asserts in it. When an Assert gets hit I drop into the debugger, have a look around, find and fix the bug. Works for me.

Problem is: how to get Unity Asserts to call into the Visual Studio debugger. So far they just seem to get generate a log message in the Editor Console, and then Unity carries right on as if they didn't matter. What use is that?

There is an 'experimental' option in the Unity VS settings, but it doesn't seem to do anything (good or bad). Any suggestions? I can think of a couple of really hackish things to try, but surely there must be a right way?

---

After further experimentation:

1. Enabling Assert.raiseExceptions (only) makes Unity grind to a halt (instead of carrying on regardless) but otherwise no change. No trap into VS.
2. Enabling the experimental Exceptions mode (only) causes Unity to crash with a bug check on the first assert failure.
3. Doing 1+2 is the same as 1 only.

This is VS 2015 in case it matters.

# Answer
Do you have `Assert.raiseExceptions` set? If not it won't stop the execution according to the docs. Relevant info copied here:

> A failure of an assertion method does not break the control flow of the execution. On a failure, an assertion message is logged (LogType.Assert) and the execution continues. If Assert.raiseExceptions is set to true, an AssertionException is thrown instead of logging a message.
> 1 votes

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


title: How to apply Jump and gravity in java

text:
# Question
Title: How to apply Jump and gravity in java
Hey guys I'm working in a game where I want a jump function and gravity function instead of my player just flying around in the air. I added the function of able to press 'Space Bar' but haven't assigned any values to it and I don't know how.

Basically all I want is a simple jump function and gravity function.

This code below is my Key Manager(my keyboard inputs)

```
package com.vescorspel.game.MyFirstGame.input;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class KeyManager implements KeyListener{

 private boolean[] keys;
 public boolean up, down, left, right, jump;

 public KeyManager(){
  keys = new boolean[256];
 }

 public void tick(){
  up = keys[KeyEvent.VK_W];
  down = keys[KeyEvent.VK_S];
  left = keys[KeyEvent.VK_A];
  right = keys[KeyEvent.VK_D];
  jump = keys[KeyEvent.VK_SPACE];
 }

 @Override
 public void keyPressed(KeyEvent e) {
  keys[e.getKeyCode()] = true;
  System.out.println("Pressed!");
 }

 @Override
 public void keyReleased(KeyEvent e) {
  keys[e.getKeyCode()] = false;
 }

 @Override
 public void keyTyped(KeyEvent arg0) {

 }

}
```

My Player code for my player.

```
package com.vescorspel.game.MyFirstGame.entities.creatures;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

import com.vescorspel.game.MyFirstGame.Handler;
import com.vescorspel.game.MyFirstGame.gfx.Animation;
import com.vescorspel.game.MyFirstGame.gfx.Assets;

public class Player extends Creatures{

 //Animations
 private Animation animDino;

 public Player(Handler handler, float x, float y) {
  super(handler, x, y, Creatures.DEFAULT_CREATURE_WIDTH, Creatures.DEFAULT_CREATURE_HEIGHT);

  bounds.x = 32;
  bounds.y = 32;
  bounds.width = 92;
  bounds.height = 96;

  //Animations
  animDino = new Animation(100, Assets.DerpDino);
 }

 @Override
 public void tick() {
  //Animations
  animDino.tick();
  //Movement
  getInput();
  move();
  handler.getGameCamera().centerOnEntity(this);
 }

 private void getInput(){
  xMove = 0;
  yMove = 0;

  if(handler.getKeyManager().up)
   yMove = -speed;
  if(handler.getKeyManager().down)
   yMove = speed;
  if(handler.getKeyManager().left)
   xMove = -speed;
  if(handler.getKeyManager().right)
   xMove = speed;
//  if(handler.getKeyManager().jump)
   //what to type here???
 }

 @Override
 public void render(Graphics g) {
  g.drawImage(getCurrentAnimationFrame(), (int) (x - handler.getGameCamera().getxOffset()), (int) (y - handler.getGameCamera().getyOffset()), width, height, null);

//  g.setColor(Color.red);
//  g.fillRect((int) (x + bounds.x - handler.getGameCamera().getxOffset()),
//    (int) (y + bounds.y - handler.getGameCamera().getyOffset()),
//    bounds.width, bounds.height);
 }

 private BufferedImage getCurrentAnimationFrame(){
  return animDino.getCurrentFrame();
 }

}
```

# Answer
> 0 votes
Integrating physics in your game (not only gravity) is a topic that Glenn Fiedler covered in a great manner on his website : Game Physics in Games

Reading this will give you all the answers you are looking for.

---
Tags: java
---


# Question
Title: How can I create JSON sprite sheet data from a regular sprite sheet?
I want to use some art from OpenGameArt for my game. The piece I want to use is a sprite sheet containing a bunch of sprite tiles compiled into a single PNG:

I want to create a JSON file with the names and coordinates for each tile. Doing this manually would probably take took long.

I've tried TexturePacker but it seems that it only accepts separate image files which it compiles into a single image. It doesn't have an option to load precompiled sprite sheets; then select and name each tile inside of it.

How could I accomplish this?

# Answer
> 4 votes
There are tools out there that can help you, such as Shoebox. But tools-recommendation questions aren't appropriate here, so instead I'll describe a basic process you could use to do this yourself.

Since the sprites in the sheet are regular (that is, they're all the same size) you can pretty easily write a program that produce a set of rectangle data in JSON based on the size of the image. You only need to give this program the image file name, the desired tile size, and the output file name. It would then:

* Load the image file, get the width and height.
* Generate a set of tiled rectangles, starting with `(0, 0, tileWidth, tileHeight)`, by dividing the width and height accordingly.
* Generate a placeholder name for each tile, such as `tile00` through `tile24` or whatever.
* Write all that information to the output JSON file.

You can then open the file up and alter the placeholder names to match what you actually see on the sprite sheet for that section. No matter you're going to be naming the tiles yourself. You could aid yourself in this process by adding the following features to your program:

* Perform a simple check on the contents of the sprite sheet in every rectangle to see if the rectangle is empty. If so, that space can be considered empty and you can avoid generating the name or bounds information in the output.
* Write out a separate copy of the image where you've rendered a grid (in some easily visible color, like hot pink) over each tile and annotated each tile with the number used in the placeholder name. This will help you more easily match up the placeholder name with the image and help you produce better names quicker.
* In the case where you want to consider some sprites to be larger than the otherwise-mostly-regular ones (for example, the two larger trees in your example), you can manually adjust the output file to combine the bounds of the individual tiles into a larger tile, deleting the extra entries.

You can write this tool in any language, although one with built-in support for all the appropriate operations (opening PNGs, annotating them, simple math primitives like rectangles) would be ideal. C#, for example, would make a good choice and you could probably write such a thing very easily if you didn't want to just use an existing tool, if you needed to build thing into a customized asset pipeline, or if you wanted to provide extra options or UI for interaction (for example, your tool could present the sheet with the grid overlayed and allow you to drag-select rectangular regions of the base tile size that constitute "larger" sprites, like the aforementioned trees, saving you the manual fix-up step).

It's impossible to get away from having to do at least some manual work on the data (in the most general case), but simple tools like the above can help you alleviate the majority of the repetitive grunt work inherent to the process.

# Answer
> 1 votes
In case anyone is looking for alternative answer/solution:

You can actually use paint.net to generate spritesheets from individual images or vise versa with all the file(s) automatically named incrementally, although you have to install a plugin. Don't worry it's all free, and you can also benefit from other great plugins to help manage your work.

http://www.getpaint.net/index.html \- get Paint.net here http://forums.getpaint.net/index.php?/topic/15260-plugin-index/ \- dl the plugins here

\[Specific links\]

(P.S. Just remove the spaces, it's my first time posting here so I don't have enough privilege to post more than 2 links I think)

(Sprite Matrix) -\> http:// forums . getpaint . net/index . php?/topic/31670-png-sprite-sheet-matrix-march-31-2015/

(Spritesheet Animation Test) -\> http:// forums . getpaint . net/index .php?/topic/14848-spritesheet-animation-plugin/

(Alternative spritesheet exporter) -\> http:// forums . getpaint . net/index.php?/topic/26202-spritesheet-export-plugin/

---
Tags: sprites, spritesheet
---


title: OpenGL Cubemap skybox edge issue

text:
# Question
Title: OpenGL Cubemap skybox edge issue
I implemented a skybox into my program using a tutorial, and using the provided 6 textures from that tutorial to make a cube map texture, my skybox looked fine. However, ever since then every other skybox texture set I have tried to add has had issues with the edges not blending together. Here is generally how they always end up looking:

here is my code for for loading the textures and the parameters:

```
glActiveTexture(GL_TEXTURE0);
textureID = SOIL_load_OGL_cubemap(textures[0], textures[1], textures[2], textures[3], textures[4], textures[5], 0, 0, SOIL_LOAD_RGB);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
if (textureID == 0)
{
    glGenTextures(1, &textureID);

    int width, height;
    unsigned char* image;

    glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
    for (GLuint i = 0; i < 6; i++)
    {
        GLuint sID = SOIL_load_OGL_texture(textures[i], 0, 0, 0);
        image = SOIL_load_image(textures[i], &width, &height, 0, SOIL_LOAD_RGB);
        glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
        SOIL_free_image_data(image);
    }
}

glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);

```

And code for rendering the skybox:

```
glDepthMask(GL_FALSE);
shader->bind();
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
viewMatrix.r4.x = 0;
viewMatrix.r4.y = 0;
viewMatrix.r4.z = 0;
shader->loadMatrix("viewMatrix", &viewMatrix.m11);
glBindVertexArray(vao);
glEnableVertexAttribArray(0);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
shader->unbind();
glDepthMask(GL_TRUE);

```

And the shader code

```
const char vertexShader[] =
    "#version 330\r\n"
    "in vec3 position;\r\n;"
    "out vec3 texCoord;\r\n"
    "uniform mat4 projectionMatrix;\r\n"
    "uniform mat4 viewMatrix;\r\n"
    "void main()\r\n"
    "{\r\n"
    "gl_Position = projectionMatrix * viewMatrix * vec4(position, 1);\r\n"
    "texCoord = position;\r\n"
    "}";

const char fragmentShader[] =
    "#version 330\r\n"
    "in vec3 texCoord;\r\n"
    "out vec4 color;\r\n"
    "uniform samplerCube sampler;\r\n"
    "void main()\r\n"
    "{\r\n"
    "color = texture(sampler, texCoord);\r\n"
    "}";

```

Does anyone see something that I might be missing that's causing my skybox to not render properly for most cube maps?

# Answer
The solution for me was to re-order the right/left/front/back from the images I was getting online to different combinations in order to get it to look properly when rendering.
> 1 votes

---
Tags: opengl, c++, textures, cubemap, skybox
---


# Question
Title: Error loading "SpriteFont1". File not found
I have an issue while trying to load a font file with the extension ".xnb" and I am receiving following error:

```
Error loading "SpriteFont1". File not found.

```

For following code:

```
public static Dictionary<string, T> LoadListContent<T>(this ContentManager contentManager, string contentFolder)
        {
            DirectoryInfo dir = new DirectoryInfo(contentManager.RootDirectory + "/" + contentFolder);
            if (!dir.Exists)
                throw new DirectoryNotFoundException();
            Dictionary<String, T> result = new Dictionary<String, T>();

            FileInfo[] files = dir.GetFiles("*.*");
            foreach (FileInfo file in files)
            {
                string key = Path.GetFileNameWithoutExtension(file.Name);

                result[key] = contentManager.Load<T>(key);
            }
            return result;
        }

```

The file is actually there and I am getting here `FileInfo[] files = dir.GetFiles("*.*");` one file which is present in the folder.

I am using the function like this:

```
fontList = ContentLoader.LoadListContent<SpriteFont>(Content, "Fonts");

```

Is there something which I have overlooked?

# Answer
> 1 votes
Reflecting the ContentManager.Load(assetName) method, it gives this note:

assetName:

Asset name, **relative to the loader root directory**, and not including the .xnb extension.

---

Even though `files` has the needed copy of "SpriteFont1" in it, the ContentManager isn't looking for the file in `files`. It's looking for "SpriteFont1" in the ContentManager's root directory `/Content` . Try changing the ContentManager's root directory to `/Content/contentFolder`.

```
Content.RootDirectory = "Content/contentFolder";//amend the line in the Game1 constructor

```

or change `key` to:

```
string key = "/contentFolder/" + Path.GetFileNameWithoutExtension(file.Name);

```

---
Tags: xna, xna-content-pipeline, spritefont
---


# Question
Title: Player object glitching around when there is a low framerate Unity C#
I just started to make this game, it runs fine on my computer. 60fps, but when I tested it on another computer, with lower fps, the player just started to jitter and glitch around a lot. The game is basically unplayable like that, and I want to make sure that everyone who plays my game will be able to enjoy the full experience. I have pasted the specific part of the code for the movement below.

```
void Update () {

    rb.AddForce (Vector3.forward * ForwardSpeed);

    if (Input.GetKeyDown (KeyCode.A) && side > maxSideLeft) {
        rb.AddForce (-Vector3.right * Speed);
        side -= 1;
    } else if (Input.GetKeyDown (KeyCode.D) && side < maxSideRight) {
        rb.AddForce (Vector3.right * Speed);
        side += 1;
    }

    if (Input.GetKeyDown (KeyCode.W) && level < maxLevelHeight) {
        rb.AddForce (Vector3.up * Speed);
        level += 1;
    } else if (Input.GetKeyDown (KeyCode.S) && level > minLevelHeight) {
        rb.AddForce (-Vector3.up * Speed);
        level -= 1;
    }

    if (Input.GetKeyDown (KeyCode.R) || Input.GetKeyDown(KeyCode.Space)) {
        SceneManager.LoadScene ("Scene1");
        Time.timeScale = 1;
    }
}

```

# Answer
> 1 votes
You appear to be moving the player in the `Update()` method, applying direction and speed. For smooth movement, ***you also need to accommodate for the time in between updates***.

Consider this: your telling your player to move by a set distance every time you perform an `Update()`. We will say your hardware is fast enough to perform `Update()` 60 times per second. If you play your game using hardware that is only fast enough to perform `Update()` 30 times per second, you will only get to tell the player to move *half as many times* as before. Using *only* speed, your player would only be able to move *half the distance* in the same amount of time.

The solution is quite simple. You use the time since the *last* `Update()` as a multiplier, to ensure smooth movement, regardless of hardware. Unity provides this value as `Time.deltaTime`. Simply replacing `Speed` with `Speed * Time.deltaTime` should ensure smooth movement.

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


# Question
Title: How should I manage meshes for the streets of a 3D city map in Unity?
I was recreating a small city in Unity3D and was going to place streets and pathways according to a sketch. I'm building for Android and the city is quite small; I'm planning to have the entire road mesh(es) loaded during play, without a load/unload algorithm. I made a few road meshes in Sketchup and imported them into Unity, but was unsure on how to manage them. I thought of two strategies but was unable to identify the pros and cons of either:

1. Place all the separate road meshes in Unity and position them, recreating the sketch and make them children of an empty GameObject to order them in the Editor window.
2. Create the entire city roadmap in Sketchup, making it a single and complete mesh. Then, import it into Unity and that's it.

The city is quite small and I'm planning to have the entire road mesh(es) loaded during play, without a load/unload algorithm. I'm building for Android.

Which strategy should I prefer in this situation? Or are both basically the same?

# Answer
> 1 votes
Using many small meshes (option 1) will likely be favorable in this scenario for the following reasons:

* **You can make heavy use of instancing.**
    + Loading the map will likely be faster since you only need to allocate and transfer data for a few small meshes.
    + Takes up less VRAM.
* **Each tile that is not in view or is far away can be hidden or can have an LOD object.**
    + Instancing will make LOD switching difficult (but you could instance LOD levels as well if you need to), but you can find clever ways to deal with this.
    + Frustum culling, occlusion culling, and distance thresholds can all be used to take out road pieces. You said you were making a city, so I suppose it's likely building may be blocking parts of the streets.
* **The application will take up less space on your phone.**
* **It may be easy to make modifications when designing your city.**
    + This isn't a technical reason, but when doing level design, I find it easier to work many small, modular meshes than a large mesh, especially when I need to make modifications.

Batching may help performance as well, but dynamic batching can cause lag. Either way, you'll want to profile the any combination of optimizations to see what works for you.

# Answer
> -1 votes
A complete mesh would reduce the amount of draw calls so I recommend you do that but it can be strange to get the measurements right so if you have trouble with that then you should put it together piece by piece in Unity **With Loading/Unloading** so it doesn't take up too much time with the draw calls. It really depends on how big the city really is, if it is that small then it is ok to do it in small pieces without loading/unloading but keep in mind that you are building for Mobile which isn't very powerful.

---
Tags: unity, 3d-meshes, mesh, resource-management
---


# Question
Title: Smoothly moving an object sideways by a certain amount when a key is pressed Unity C#
I basically want to have the user press A once without holding it down, to **smoothly** move the player to the left. I would like to make the player move to the left by -12. So he would end up going from 0 to -12 or from -12 to -24.

# Answer
> 2 votes
What you have to do is you have to Lerp between 2 values from the current position. And you have to StartCoroutine only when Input.GetKeyDown() - the keyword is Down, so it will start only when you press, but not hold or release it, so it will start only 1 coroutine, it's important when you move something with coroutines you don't want the object to be moved by 2 different forces that don't depend one on another unless it's planned.

Here is the code to do it.

```
using UnityEngine;
using System.Collections;

public class MoveObjectWithCoroutines : MonoBehaviour {

public float movementSpeed = 5f;

// Update is called once per frame
void Update () {

    if (Input.GetKeyDown(KeyCode.A))
    {
        MoveObjectTo(this.transform, new Vector3(this.transform.position.x - 12, this.transform.position.y, this.transform.position.z), movementSpeed);
        /*
         * If you want to move it every time by -12 (new Vector3(this.transform.position.x -12, this.transform.position.y, this.transform.position.z)),
         * or by some other value and axis - just change
         * the targetPosition Vector3 passed in the argument of MoveObjectTo();
         */
    }

}

private void MoveObjectTo(Transform objectToMove, Vector3 targetPosition, float moveSpeed)
{
    StopCoroutine(MoveObject(objectToMove, targetPosition, moveSpeed));
    StartCoroutine(MoveObject(objectToMove, targetPosition, moveSpeed));
}

public static IEnumerator MoveObject(Transform objectToMove, Vector3 targetPosition, float moveSpeed)
{
    float currentProgress = 0;
    Vector3 cashedObjectPosition = objectToMove.transform.position;

    while (currentProgress <= 1)
    {
        currentProgress += moveSpeed * Time.deltaTime;

        objectToMove.position = Vector3.Lerp(cashedObjectPosition, targetPosition, currentProgress);

        yield return null;
    }
}

}

```

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


title: How to detect if game is hidden?

text:
# Question
Title: How to detect if game is hidden?
I'd like to pause my game when my app is hidden (user pressed home button or changed app). How can I detect that ?

# Answer
> 1 votes
The `ApplicationListener` interface has a `pause` method that gets called when your app is losing focus, that's where you need to hook in logic to stop doing any game logic.

---
Tags: java, libgdx
---


# Question
Title: Rotate a Crosshair around a sprite - 2d worms style game?? (LibGDX)
I'm currently learning to code 2d games in Libgdx. Right now I'm making a kind of worms clone. I am using Box2d and have just my main sprite and a flat ground object so far.

What im stuck on is making the crosshair for the main character which I would like to rotate around him at a distance of say 90px when the player presses UP or DOWN key.

Here is the code I have so far but I havent even been able to attempt the rotation code at all:

```
package com.supermegabrobro.apoca.Sprites;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.supermegabrobro.apoca.Screens.PlayScreen;

    public class ArmyDude extends Sprite {
PlayScreen playScreen;
BodyDef bodyDef;
Body body;
FixtureDef fixtureDef;

boolean crossHairShowing = false;

Texture crossHairTexture;
float crossHairDistance = 30f;
float crossHairAngle = 45f;
Vector2 crossHairPosition;

public ArmyDude(PlayScreen playScreen){
    super(new Texture("armydude.png"));
    this.playScreen = playScreen;
    bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.DynamicBody;
    bodyDef.position.set(0,0);   // TODO: Make this random

    body = playScreen.world.createBody(bodyDef);
    CircleShape circleShape = new CircleShape();
    circleShape.setRadius(getWidth() / 2);
    fixtureDef = new FixtureDef();
    fixtureDef.shape = circleShape;
    body.createFixture(fixtureDef);

    crossHairTexture = new Texture("crosshair.png");
    crossHairPosition = new Vector2(0,0);

}

public void update(float dt){
    setPosition(body.getPosition().x - getWidth() / 2, body.getPosition().y - getHeight() / 2);

    if(Gdx.input.isKeyPressed(Input.Keys.UP)){
        crossHairShowing = true;
    }
}

@Override
public void draw(Batch batch) {
    super.draw(batch);
    if (crossHairShowing){

    }
}
}

```

Any help is massively appreciated thanks. (nb. I have read up on, and implemented in previous projects, normal rotation of sprites. But I beleive this is very different since I am trying to not rotate the actual sprite but instead draw a texture (of a crosshair) that rotates around this sprite.

I'm really stuck though my poor brain can't figure it out alone :(

# Answer
Usually problems like this can be solved by using vector geometry. With the basic ideas of vectors, problems relating to the coordinate system can be much easier solved.

For your game the steps would be:

1. Create `angle` and `crosshairVector` at the constructor

```
float angle = 45f;
Vector2 crosshairVector = new Vector2;

```
2. In your method to get the crosshair position get the vector position of the player.

```
Vector2 playerVector = new Vector2(getX(), getY());

```
3. Create a vector with a length of the desired distance between player and crosshair.

```
Vector2 distanceVector = new Vector2(90, 0);

```
4. Rotate the vector by the value of the angle variable.

```
distanceVector.setAngle(angle);

```
5. Add both vectors together to get the position vector of the crosshair.

```
crosshairVector = playerVector.add(distanceVector);

```

Now you have the position of the crosshair in the Vector `crosshairVector`. With `crosshairVector.x` and `crosshairVector.y` you get the x and y values. To rotate the crosshair simply change the angle variable.

If you want to know more about the basics of vectors you can have a look on: https://www.mathsisfun.com/algebra/vectors.html
> 1 votes

---
Tags: java, 2d, libgdx, rotation
---


# Question
Title: Calculate line intersecting most points, based on random points in a grid
I have been struggling with a math issue for a game I've been developing. I am in need to find the best starting and ending point for a straight line so that it intersects most of the circles (the blue one always needs to be intersected).

As you can see in the image below I want to be able to calculate that green line based on the given points, where the blue one is required to be intersected. *The rule is that the line has to intersect as many circles as possible and should always intersect the blue circle.*

I've tried to apply the best fit algorithm but that doesn't really takes intersection into consideration. Would appreciate if someone could help me out solving the math for this.

There will only ba a maximum of 5 circles while calculating the line.

**Note: I am not deeply involved into math, only know the basic symbols for it.**

# Answer
If there are at most 5 circles to be considered the problem can be solved easily.

Given a subset of circles, you just have to check if you can find a line that intersects all of them. we can safely assume, if such a long exists, it's going to be the one best fitting the center of circles (in case circles all have same radius which seems to be the case in your picture).

Iterating over the subsets of all the circles is an easy task too, you just have to count from 0-\>2^n - 1 (like 0 to 31 in case of just 5 circles). Each bit of the number determines if a certain circle is present in subset or not.

So here is an algorithm in a whole:

```
counting from 0 to 31
    determine a subset of circles that you are going to check
    find the best fitting line for those set of circles
    check if the best fitting line intersects with all of the circles
    if all of the circles are on the line, update the chosen line.

```
> 1 votes

# Answer
It's not very pretty, but assuming there is only one blue circle, you could:

Create a line that goes through the blue's center, incrementally rotate it around the center, at each angle check how many circles coincide with the line, and finally pick the best one.

If you have to do this once, or at least not very often, this will work out fine.
> 0 votes

---
Tags: mathematics, algorithm
---


# Question
Title: Replicating Flight Mechanics of Star Wars Battlefront (2015)
I'm trying to replicate the flight mechanics from Star Wars Battlefront (2015) in Unity and I can't get my head around what exactly is going on.

Specifically, how do I get the camera to behave like this using Unity and C#:

https://youtu.be/gxZdOUiEiyY?t=1m1s

I don't mind if you don't give code, I'm just struggling to understand what happens and when in terms of camera movements and rotation.

# Answer
1. Decide the *desired* camera location. In this case a distance `x` behind the fighter plus an offset `y` in the up direction relative to the fighter. `x` and `y` can depend on the current velocity, but for starters use constant numbers.
2. Decide the desired camera "up" rotation. I guess it's just the rotation of the fighter.
3. Write a simple function that takes the current camera location and the *desired* camera location, then move the camera from the current location towards the desired one. Make the speed of that move dependent on the distance between current and desired location.
4. Same as 3 for rotation.
5. Take the flight direction of the fighter, add a certain distance to get a point in front of the fighter. Make the camera look at that point. Or use the inverse, make the fighter fly where the camera looks.
> 5 votes

# Answer
The camera tries to follow the fighter, but not in the same speed the fighter moves, a bit slower, with a specific cap. With cap I mean, that the camera seems to have a specific limit for the "deviation angle". "Deviation angle" means the angle between the direction vector of the camera and the direction vector of the fighter. Imagine the camera is bound to the fighter by a kind of "leash". You can see this at 1:40-2:00 or 2:17-2:29.

To reproduce this I would adjust the orientation of the camera with a delay (slower velocity), maybe interpolated by a simple function (via e.g. animation curves). But with specific bounds, so that the fighter is not able to move out of the camera view. To achieve this you should determine a maximum "deviation angle". The closer the "deviation angle" comes to maximum, the faster the camera is adjusted up to the maximum speed the figther can move or maybe even faster. You could use an animation curve again, to make it look smoother.
> 3 votes

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


title: glUniformBlockBinding doesn't work

text:
# Question
Title: glUniformBlockBinding doesn't work
I try use uniform blocks in OpenGL, but doesn't work. First, see my vertex shader:

```
#version 400
uniform Buffer0
{
    mat4 worldMatrix;
    mat4 viewMatrix;
    mat4 projectionMatrix;
};

in vec3 POSITION;
in vec4 COLOR;
out vec4 color;

void main(void)
{
    gl_Position = worldMatrix * vec4(POSITION, 1.0f);
    gl_Position = viewMatrix * gl_Position;
    gl_Position = projectionMatrix * gl_Position;

    color = vec4(1.f, 0.f, 0.f, 1.f);
}

```

My fragment shader output color only.

Creating and drawing vertex buffer correctly.

If use

```
gl_Position = vec4(POSITION, 1.0f);

```

drawing works, but using matrices draw doesn't work.

C++ code:

```
// Create GL_UNIFORM_BUFFER matrices

struct Matrix4f
{
float m11,m12,m13,m14;
float m21,m22,m23,m24;
float m31,m32,m33,m34;
float m41,m42,m43,m44;
};
struct MatrixBuffer
{
Matrix4f world, view, proj;
};
//The values bellow are correct
Matrix4f world =
{
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    0, 0, 0, 1
};
Matrix4f view =
{
    1, 0, 0 , 0,
    0, 1, 0 , 0,
    0, 0, 1 , 0,
    0, 0, 10, 1
};
Matrix4f projection =
{
    1.81066012f, 0         , 0           , 0,
    0         , 2.41421342f, 0           , 0,
    0         , 0         , 1.00010002f  , 1,
    0         , 0         , -0.100010000f, 0
};
MatrixBuffer data = { world, view, proj };

GLuint matrixbuffer;
glGenBuffers(1, &matrixbuffer);

if (glGetError())
// "No error here."

glBindBuffer(GL_UNIFORM_BUFFER, matrixbuffer);

if (glGetError())
// "No error here."

// GL_STATIC_DRAW for example, but I have tested many other flags
glBufferData(GL_UNIFORM_BUFFER , sizeof(MatrixBuffer), &data, GL_STATIC_DRAW);

if (glGetError())
// "No error here."

// Render function
// This code works
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
double winWidth = glutGet(GLUT_WINDOW_WIDTH);
double winHeight = glutGet(GLUT_WINDOW_HEIGHT);
double ar = winWidth / winHeight;
glOrtho(-1 * ar, 1 * ar, -1, 1, -1, 1);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

glUseProgramStages(pipeline, GL_VERTEX_SHADER_BIT, vertProgId);
glUseProgramStages(pipeline, GL_FRAGMENT_SHADER_BIT, fragProgId);
glBindProgramPipeline(pipeline);

// this code work without erros, but not draw triangle
GLuint location = glGetUniformBlockIndex(vertProgId, "Buffer0");

if (location == GL_INVALID_INDEX)
// "No error here."

// My question here.
glUniformBlockBinding(vertProgId, location, matrixbuffer);
// "No error here, but doesn't work, show a black screen."
// "If set directly matrices in vertex shader, triangles show corretly

// this code works
drawVBO();
glutSwapBuffers();

```

I tried tranpose matrices, but doesn't work too.

Something is missing? Some error?

# Answer
> 0 votes
You do not have to call glMatrixMode and related functions if you are supplying the shader the used matrices yourself.

The second problem is that glUniformBlockBinding does not want the matrix buffer name, but a binding point. You need to define the binding point yourself and assing the buffer to that binding point. Like this:

```
int bindingPoint = 2; // Just some value I came up with by throwing a dice.
glBindBufferBase(GL_UNIFORM_BUFFER, bindingPoint, matrixbuffer);
glUniformBlockBinding(vertProgId, location, bindingPoint);

```

Check the OpenGL wiki entry for Uniform Buffer Objects and glBindBufferBase

Also as noted in the comments, this is a OpenGL4 feature, which is not necessarily supported by older GPUs. You seem to be mixing the old API with the very recent functions.

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


# Question
Title: Rotated canvas sprite not drawing properly
First, sorry for my english. Said that: Recently I began to study JavaScript and like a way to consolidate what I learned I decided to make a simple video game with canvas and javascript: kind of Mortal Kombat demo, without library or game engine, just what I had learned until the moment. The problem with my little project is that when and move it or throw a punch with player2 (which is basically player1 rotated) the sprite becomes a mess, even when the code is exactly the same that for player1. I guess is related with rotating the context, but I can't figure it out. Here is the code mortal kombat demo, along with basic instructions.

# Answer
Looking at your code I found this

```
that.context.translate(xPosition + frameWidth, yPosition + frameHeight);
that.context.rotate(180 * Math.PI / 180);
that.context.scale(1, -1);
that.context.translate( - (xPosition + frameWidth),  - (yPosition + frameHeight));

```

Then you clear the previous rendering in the new coordinates system which i am guessing is resulting in bits of the previous sprite not being cleared

To fix I would rewrite the function as (sorry forgot you had where using the object `that`)

```
// Clear the old image out (you should just be clearing the whole canvas every frame
// with a background so you dont need to do this.
var oldYCoord = floor - previousHeight;
this.context.clearRect(xPosition, oldYCoord, previousWidth, previousHeight);
// Saving context only because I do not know what the current state is
this.context.save();
// Set the top left or right corner of the image
if (fliped) {
    this.setTransform(-1,0,0,1,xPosition + frameWidth,yPosition); // flip x axis and
                                                                  // set origin to top right of image
}else{
    this.setTransform(1,0,0,1,xPosition,yPosition); // set origin to top right of image
}
// draw the image at the new origins
this.context.drawImage(that.image,
    frameOriginX, frameOriginY, frameWidth, frameHeight,
    0,0, frameWidth, frameHeight  // @ 0,0
);
// restore
this.context.restore();
// if you don't do any other transforms elsewhere then remove the save and restore and add the following lineHeight
// this.context.setTransform(1,0,0,1,0,0); // restores default transform is quicker than save restore

```

I am guessing that will solve the problem.

BTW `180 * Math.PI / 180` when you multiply then divide by the same value they cancel each other out, `180/180 = 1` so the result is `Math.PI`

But you don't need to rotate just mirror along the x axis as is done in `context.setTranform(-1,0,0,1,x,y)` the first two values are the vector pointing in the direction of the x axis, the second two are the vector pointing along the y axis and the last two are the location of the origin. The values are always in canvas pixel coordinates when using setTransform, unlike `translate`,`rotate`,`scale`, and `transform` which are in the current transformed coordinate system
> 1 votes

---
Tags: javascript, html-canvas, transformation
---


title: Unity Failed to Repackage Resources

text:
# Question
Title: Unity Failed to Repackage Resources
I was trying to integrate Admob into my unity game. I imported the Google Play Games plugin and the Admob Plugin , but I have been getting this error for the past couple days.

```
CommandInvokationFailure: Failed to re-package resources.
C:\Users\Tau\AppData\Local\Android\android-sdk\build-tools\25.0.0\aapt.exe package --auto-add-overlay -v -f -m -J gen -M AndroidManifest.xml -S "res" -I "C:/Users/Tau/AppData/Local/Android/android-sdk\platforms\android-25\android.jar" -F bin/resources.ap_ --extra-packages android.support.v7.appcompat:com.google.android.gms.ads.impl:com.google.android.gms.ads.impl:com.google.android.gms.ads:com.google.android.gms.ads:com.google.android.gms.auth.api:com.google.android.gms.auth:com.google.android.gms.base:com.google.android.gms.base:com.google.android.gms:com.google.android.gms:com.google.android.gms.clearcut:com.google.android.gms.drive:com.google.android.gms.games:com.google.android.gms.gass:com.google.android.gms.nearby:com.google.android.gms.tasks:android.support.v4:android.support.v4 -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res" -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-ads-9.4.0\res" -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-ads-9.8.0\res" -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-ads-lite-9.4.0\res" -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-ads-lite-9.8.0\res" -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-auth-9.8.0\res" -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-auth-base-9.8.0\res" -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-base-9.4.0\res" -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-base-9.8.0\res" -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-basement-9.4.0\res" -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-basement-9.8.0\res" -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-clearcut-9.8.0\res" -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-drive-9.8.0\res" -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-games-9.8.0\res" -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-gass-9.8.0\res" -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-nearby-9.8.0\res" -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-tasks-9.8.0\res" -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\support-v4-23.0.0\res" -S "C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\support-v4-24.0.0\res"

stderr[
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\abc_alert_dialog_material.xml:111: note: removing attribute http://schemas.android.com/apk/res/android:layoutDirection from <LinearLayout>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\abc_alert_dialog_material.xml:48: note: removing attribute http://schemas.android.com/apk/res/android:textAlignment from <android.support.v7.internal.widget.DialogTitle>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\abc_alert_dialog_material.xml: note: using v17 attributes; synthesizing resource com.CasualGames.CoinDrop:layout/abc_alert_dialog_material for configuration v17.
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\abc_dialog_title_material.xml:29: note: removing attribute http://schemas.android.com/apk/res/android:textAlignment from <TextView>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\abc_dialog_title_material.xml: note: using v17 attributes; synthesizing resource com.CasualGames.CoinDrop:layout/abc_dialog_title_material for configuration v17.
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\abc_screen_toolbar.xml:27: note: removing attribute http://schemas.android.com/apk/res/android:touchscreenBlocksFocus from <android.support.v7.internal.widget.ActionBarContainer>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\abc_screen_toolbar.xml: note: using v21 attributes; synthesizing resource com.CasualGames.CoinDrop:layout/abc_screen_toolbar for configuration v21.
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\abc_search_view.xml:47: note: removing attribute http://schemas.android.com/apk/res/android:layoutDirection from <LinearLayout>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\abc_search_view.xml: note: using v17 attributes; synthesizing resource com.CasualGames.CoinDrop:layout/abc_search_view for configuration v17.
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_big_media.xml:42: note: removing attribute http://schemas.android.com/apk/res/android:layoutDirection from <LinearLayout>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_big_media.xml:34: note: removing attribute http://schemas.android.com/apk/res/android:layout_marginStart from <include>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_big_media.xml:34: note: removing attribute http://schemas.android.com/apk/res/android:layout_toStartOf from <include>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_big_media.xml: note: using v17 attributes; synthesizing resource com.CasualGames.CoinDrop:layout/notification_template_big_media for configuration v17.
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_big_media_narrow.xml:60: note: removing attribute http://schemas.android.com/apk/res/android:layout_toEndOf from <ImageView>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_big_media_narrow.xml:46: note: removing attribute http://schemas.android.com/apk/res/android:layout_toEndOf from <LinearLayout>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_big_media_narrow.xml:46: note: removing attribute http://schemas.android.com/apk/res/android:layoutDirection from <LinearLayout>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_big_media_narrow.xml:38: note: removing attribute http://schemas.android.com/apk/res/android:layout_marginStart from <include>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_big_media_narrow.xml:38: note: removing attribute http://schemas.android.com/apk/res/android:layout_toStartOf from <include>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_big_media_narrow.xml:30: note: removing attribute http://schemas.android.com/apk/res/android:layout_alignParentEnd from <include>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_big_media_narrow.xml: note: using v17 attributes; synthesizing resource com.CasualGames.CoinDrop:layout/notification_template_big_media_narrow for configuration v17.
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_lines.xml:18: note: removing attribute http://schemas.android.com/apk/res/android:paddingEnd from <LinearLayout>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_lines.xml:77: note: removing attribute http://schemas.android.com/apk/res/android:layout_marginStart from <LinearLayout>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_lines.xml:96: note: removing attribute http://schemas.android.com/apk/res/android:paddingStart from <TextView>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_lines.xml:64: note: removing attribute http://schemas.android.com/apk/res/android:layout_marginStart from <TextView>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_lines.xml:27: note: removing attribute http://schemas.android.com/apk/res/android:layout_marginStart from <LinearLayout>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_lines.xml: note: using v17 attributes; synthesizing resource com.CasualGames.CoinDrop:layout/notification_template_lines for configuration v17.
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_media.xml:43: note: removing attribute http://schemas.android.com/apk/res/android:layout_marginEnd from <include>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_media.xml:33: note: removing attribute http://schemas.android.com/apk/res/android:layoutDirection from <LinearLayout>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_media.xml: note: using v17 attributes; synthesizing resource com.CasualGames.CoinDrop:layout/notification_template_media for configuration v17.
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_part_chronometer.xml:18: note: removing attribute http://schemas.android.com/apk/res/android:paddingStart from <Chronometer>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_part_chronometer.xml: note: using v17 attributes; synthesizing resource com.CasualGames.CoinDrop:layout/notification_template_part_chronometer for configuration v17.
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_part_time.xml:18: note: removing attribute http://schemas.android.com/apk/res/android:paddingStart from <DateTimeView>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\layout\notification_template_part_time.xml: note: using v17 attributes; synthesizing resource com.CasualGames.CoinDrop:layout/notification_template_part_time for configuration v17.
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\drawable\abc_textfield_search_material.xml:19: note: removing attribute http://schemas.android.com/apk/res/android:state_activated from <item>
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\appcompat-v7-23.0.0\res\drawable\abc_textfield_search_material.xml: note: using v11 attributes; synthesizing resource com.CasualGames.CoinDrop:drawable/abc_textfield_search_material for configuration v11.
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-base-9.8.0\res\values\values.xml:33: error: Attribute "imageAspectRatioAdjust" already defined with incompatible format.
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-basement-9.4.0\res\values\values.xml:3: Original attribute defined here.
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-base-9.4.0\res\values\values.xml:21: error: Attribute "buttonSize" already defined with incompatible format.
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-base-9.8.0\res\values\values.xml:47: Original attribute defined here.
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-base-9.4.0\res\values\values.xml:21: error: Attribute "colorScheme" already defined with incompatible format.
C:\Users\Tau\Documents\Coin Drop\Temp\StagingArea\android-libraries\play-services-base-9.8.0\res\values\values.xml:55: Original attribute defined here.
]
stdout[
Configurations:
 (default)

Files:
  AndroidManifest.xml
    Src: () AndroidManifest.xml
```

How do I fix this?

# Answer
I paid to solve this issue , but the solution is simple. Delete the google play services folder , delete the play -services 9.4.0 files and support v23. in Unity.
> 0 votes

# Answer
Looks like you are missing **Google Play Services**, which is a separate package from the two you are using and it is a dependency. You will need to download it either through Android Studio or some other location and add it into your project folders. See this question here: http://answers.unity3d.com/questions/1190674/missing-libraries-in-google-play-services-revision.html
> 0 votes

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


# Question
Title: GL how to look at the center of the viewport
I'm using GLFW3 and OpenGL to visualize measurements from an IMU that I have. I've gotten the simple cube example working and I can rotate it successfully with quaternions that I've input.

However since I'm visualizing an IMU, it is important that I know which way I am looking at it. I would prefer to look at it from a top down view.

Hence I want to keep the cube at the center of the world (0, 0, 0) and look down at it from a corresponding height (0, 0, z) which is where I want my camera to be at. I've the following code, can someone please guide me on how to set up my glLookAt function? All the values that I input make my cube disappear.

```
void display( GLFWwindow* window )
{
  while(!glfwWindowShouldClose(window))
  {
    // Scale to window size
    GLint windowWidth, windowHeight;
    glfwGetWindowSize(window, &windowWidth, &windowHeight);
    glViewport(0, 0, windowWidth, windowHeight);

    // Draw stuff
    glClearColor(0.2, 0.2, 0.2, 1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION_MATRIX);
    glLoadIdentity();
    gluPerspective( 60, (double)windowWidth / (double)windowHeight, 0.1, 100 );

    glMatrixMode(GL_MODELVIEW_MATRIX);
    glTranslatef(0,0,-5);

    drawCube();

    // Update Screen
    glfwSwapBuffers(window);

    // Check for any input, or window movement
    glfwPollEvents();
  }

```

# Answer
Let's look at the declaration of `gluLookAt`:

```
void gluLookAt(GLdouble eyeX,
               GLdouble eyeY,
               GLdouble eyeZ,
               GLdouble centerX,
               GLdouble centerY,
               GLdouble centerZ,
               GLdouble upX,
               GLdouble upY,
               GLdouble upZ);

```

`eyeX`, `eyeY` and `eyeZ` are (obviously) the camera position (which you should have already).

`center` X, Y and Z are the positions of the object you want to focus on.

`upX`, `upY` and `upZ` are the up vector's coordinates (I seriously have no idea why OpenGL needs this, but I won't argue). This should be 0, 1 and 0 respectively.

Although, you mentioned that you wanted to visualize some data without messing with vbos or even vaos, but this is one of the reasons engines are implemented.
> 1 votes

---
Tags: opengl, camera, glut, glfw
---


# Question
Title: Is it possible to find the child body involved in a collision of a compound shape?
I am noob at using bullet physics. I am using it for collison detection and I want to create a compound body to represent a ship. However, in my game I need to know which part of the ship was hit.

The contact manifolds only have the collision objects in other words the compound body. The contact manifold does not have the child body that collided.

Thank you

# Answer
I decided to give each part a different rigid body / collision shape. They were then connected using constrains, and collisions between constrained bodies were disabled. I disabled the collisions using btDynamicsWorld::addConstraint(btTypedConstraint\* constraint, bool disableCollisionsBetweenLinkedBodies)
> 0 votes

---
Tags: c++, collision-detection, bullet-physics
---


# Question
Title: pygame scrolling: target moves faster than the camera
I know many questions have already been asked on this same topic, but I can't figure out from those how to solve my problem (possibly due to a different approach to achieve the same goal: scrolling my camera keeping the main character of my game centered in the screen).

I am developing my first 2D platform game with python and pygame.

I am having difficulties in making a camera which follows the player each times he moves, keeping him in the center of the screen.

What is happening is that the camera keeps following the main character as he passes over the center of the screen, but, as he keeps moving in one direction (say leftward), he suddenly keeps closer to the border towards he is moving (i.e. the camera "is too slow" in following him...). I know it has probably to do with the camera shift not taking the hero horizontal and vertical speed, but I don't know how to solve this problem at the moment.

I have two separate classes for the main character and the camera. I am about to attach a bit of my code (it seems a lot but it's "only" the relevant part of code to understand the problem, and there's plenty of spaces and comments...). I hope someone could give a good hint!

The `Hero` class is actually a child of `Character` class, so here are both:

```
class Character(pygame.sprite.Sprite):
    """class with generic character's attrs and methods
    (intended to be inherited from players and enemies in the game)"""

    def __init__(self, x, y, life, img):
        super().__init__() # Call the parent class (Sprite) constructor

        self.img = img

        self.image = pygame.image.load(os.path.join(SPRITE_FOLDER, img)).convert_alpha()
        self.rect = self.image.get_rect()

        self.x = x
        self.y = y
        self.rect.x, self.rect.y = self.x, self.y

        self.hspeed = 5
        self.vspeed = 0

        self.life = life

    def gravity_force(self, gravity = .35):
        if self.vspeed == 0:
            self.vspeed = 1
        else:
            self.vspeed += gravity

    def collision(self, block_list = pygame.sprite.Group()):
        """hanlde collisions between hero and environment.
        'collision_list' should contain a list of sprite against
        which collision is detected for the main character"""

        self.gravity_force()
        self.rect.top += self.vspeed # let the hero falling

        # See if the character Sprite has collided with anything in the Group block_list
        # (returns a Sprite_list)
        collision_list = pygame.sprite.spritecollide(self, block_list, False)
        ()
        # check for collisions in each direction
        for colliding in collision_list:
            if self.vspeed > 0: # if is falling...
                self.rect.bottom = colliding.rect.top # ... if hits a block, place it on it...
                self.vspeed = 0 # ... and stop vertical speed

class Hero(Character):
    """main Hero class"""

    # If you want to extend the parent's __init__() method, you should do:
    # def __init__(self, x, y, life, img, *args):
    #     super().__init__(x, y, life, img)
    #     REDEFINE super() methods and add additional attributes

    def movement(self, event = None):
        """handle character's interaction with the level and keyboard inputs"""

        if event:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    self.rect.left += self.hspeed # move topleft rectangle 'hspeed' pixels left
                if event.key == pygame.K_LEFT:
                    self.rect.left -= self.hspeed # move topleft rectangle 'hspeed' pixels right
                # if event.key == pygame.K_UP:
                #     self.rect.top += 5

```

And here is the `Camera` class (a rectangle with size equal to the screen, whose center coordinates are moved to match the Hero's ones each frame):

```
class Camera():
    """Surface containing the Hero at its center and all objects nearby it"""

    def __init__(self, screen):
        """create a camera Rect whose size is equal to screen size"""
        self.rect = screen.get_rect()
        self.x = self.rect.x
        self.y = self.rect.y
        self.dx = 0 # initialize camera x shift
        self.dy = 0 # initialize camera y shift

    def follow_target(self, target):
        """move the camera so that target Rect is always centered"""
        self.rect.clamp_ip(target.rect) # center camera to target

        # do not accept negative coords
        if self.rect.x < 0: self.rect.x = 0
        if self.rect.y < 0: self.rect.y = 0

        # calculate dx, dy based on previous and current camera position
        self.dx = self.x - self.rect.x
        self.dy = self.y - self.rect.y

        # set current camera pos permanently
        self.x = self.rect.x
        self.y = self.rect.y

    def apply_shift(self, target):
        """move target Rect according to camera pos"""
        target.rect.move_ip(self.dx, self.dy) # move target position of a given offset

```

And finally the parts in the parts of my `main()` function of the game relevant to my issue:

```
screen.blit(level.background, (0, 0)) # draw background
camera = Camera(screen) # creates camera
while True: # main game loop
....
    # draw blackground on moving objects (hero, platforms, enemies)
    # (to delete just them on each frame instead of redrawing the entire screen,
    # as this will increase game performance)
    screen.blit(level.background, hero.rect, hero.rect) # delete hero
    for block in level.block_group:
        screen.blit(level.background, block.rect, block.rect) # delete other objects

    # check for hero moves nad collision
    hero.movement(event)
    hero.collision(level.block_group)

    camera.follow_target(hero) # centers the hero to the camera Rect

    # update blocks pos according to hero pos
    for block in  level.block_group:
        camera.apply_shift(block)
        screen.blit(block.image, block.rect)

    # draw hero
    screen.blit(hero.image, hero.rect)

    pygame.display.update()

```

# Answer
> 0 votes
Ok so the solution was pretty simple, but finding it out was a pain!.... It appears that the line of code in the `follow_target` method within the `Camera` class had a bug: the attributes `self.dx` and `self.dy`, indicating the shift of the camera according to the movements oh the hero, only accounted for hero's `hspeed` at each frame, and not the actual total shift. This led the hero to surpass the screen center as he kept moving.

Also, the position of the hero himself had to shift together with the blocks (and with all level objects in general) for the game to work properly.

The change in the `Camera` class was (note the `+=` operand instead of `=`):

```
# calculate dx, dy based on previous and current camera position
self.dx += self.x - self.rect.x
self.dy += self.y - self.rect.y

```

Only working for right movements for now, but I'll keep this answer up to date as I update the code.

The change in the main function was to add a new Sprite Group (`objects`), adding to it both the hero and the blocks sprites, and update everything at each frame like:

```
objects = pygame.sprite.Group() # initialize sprite Group
objects.add(hero) # add hero to sprite Group (because he also has to shift together with other levels' objects)
objects.add(level.block_group) # add blocks to sprite Group

    while True: # main game loop
        ...
        # update every objects (including hero) pos according to hero pos
        for obj in  objects:
            camera.apply_shift(obj)
            screen.blit(obj.image, obj.rect)

```

---
Tags: python, pygame, scrolling
---


# Question
Title: Script for non-stop enabling/disabling "Is trigger" on collliders2d in Unity3D?
I had asked before that I have a problem with too many colliders in one spot and that some upgrades of towers I have are buggy due to that.

It has come to my notice, that whenever I *enable* the "Is trigger" on a colliders in the upgrading spots, it fixes, but if I start the scene again it is broken **sometimes** untill I *disable* it again.

So what script should it be to atatch to those spots to activate/deactivate the is trigger toggle non-stop?

This is a video of me trying to explain my problem from previous threads I've made elsewhere.

https://www.youtube.com/watch?v=lPFAxoPrHzs&feature=youtu.be

# Answer
Doesn't matter how many colliders there are. Just use a RaycastAll when you click the mouse, then iterate through the colliders looking for the game object you're interested in. A simple way to find the object you're looking for is to see if it has whatever your tower script is. Something like:

```
if(collider.gameObject.GetComponent<TowerScript>() != null)
     //activate the upgrade for that specific tower

```

Alternatively, you can put the tower in a different collision layer. Then use a mask on your raycast to only get objects in that layer.
> 0 votes

# Answer
Stack Exchange is asking to avoid this type of answers based on opinion, but as this question is about "how to fix a bug because of my implementation" and not the "how to do a particular thing", I could not answer it another way.

But avoid …

Asking for help, clarification, or responding to other answers. Making statements based on opinion; back them up with references or personal experience.

By monster I mean - tower(turret).

Well you have a problem because of your game design actually - why would you upgrade the monster if you would like to drag him? When you start dragging you click on the monster, thus it upgrades.

The solution would be to make that monsters that have to be upgraded cannot be dragged before they actually are upgraded, so player would have to click twice in order to upgrade and then again in order to drag the monster. Simple implementation is for your monsters to have XP and make them glowing when they can be upgraded. Otherwise if you have gold - it is not clever solution to make your player use his gold in order to drag the monster - so you would have ask with the UI for the action he wants to do or you would have to bind another key for dragging the tower.

As for the solution to actually get the script if you have multiple scripts for different kind of turrets. You can ray-cast from the camera to that monster onto turret layer and use `hit.GetComponent<Turret>().UpgradeTurret();` \- it is possible to do for any script that will be upgraded using Inheritance and Polymorphism. For example if you have PoisonTurret and IceTurret they both will Inherit from Turret class, thus they both will have implementation of UpgradeTurret();. Also I guess every turret has it's own way of upgrading itself, thus it would be good to make Turret class `abstract`, add UpgradeTurret as abstract method, then override it in every child class. Or you could make an Interface and make your super class Turret implement it and make UpgradeTurret() method virtual there.
> 0 votes

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


# Question
Title: Identify whether object is off screen or not
I have placed three game object in the scene.How to know whether the object is visible on the screen.Print a message if the object is not visible on the screen.

# Answer
> 2 votes
Take in mind, I'm not a big Unity user, however I can give you an answer, that works pretty much everywhere.

Prerequisits: you need to know the x and y FOV angle of the camera (you can calculate the x by taking the y FOV and multiplying it with the aspect ratio of the device), and the euler angles of the camera.

Create a vector, which points from the camera to the object you want to check against, then you can get the absolute angle of this vector with the following formula:

```
r := sqrt(x² + y² + z²)
yAngle := arctan(y / x)
xAngle := arccos(z / r)

```

Now, you know the absolute angles of the vector.

You need to divide the x and y angles of the camera from the x and y angles of the vector, this way you get the angles relative to the camera.

Here comes the trick: if the relative x and y angles are between the negative xFov and yFov and positove xFov and yFov (add some falloff to it of course), then it's inside the view of the camera.

However, this has some cons. The biggest and most obvious is that if your object is very big or is very close to the camera, then you can get false results. This can be solved by giving it a bigger falloff, but that won't work if you object likes to get close to the camera and then get far again, then this won't work either.

In cases like that, you should simply render it to a texture, and check if it is on it.

# Answer
> 1 votes
Unity has built-in methods to detect it. It's called the same way as OnTriggerEnter.

```
public class Invisibility : MonoBehaviour {
    void OnBecameInvisible() {
        Debug.Log("I`m gone :(");
    }
    void OnBecameVisible() {
        Debug.Log("Hi, I`m back!");
    }
}

```

Note: that if the object is visible on the Scene view OnBecameInvisible won't be called. Same way with OnBecameVisible - if it becomes visible on the Scene view. After building your game it shouldn't bother you, this only exists in the editor.

1) Renderer.OnBecameInvisible 2) MonoBehaviour.OnBecameInvisible

If you want to check if the gameobject is currently visible you can get his `Renderer.isVisible` (it returns true if the shadow is rendered).

If you want to detect via bounding box falls within a frustum of a camera, later you have to check if it's not blocked by any object via Raycasting.

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