title: XNA 4.0 HLSL - strange depth map

text:
# Question
Title: XNA 4.0 HLSL - strange depth map
I want to draw my pre-rendered depth map to the scene.

I get my depth value in the following way:

basically (Pixel Shader)

```
// Depth is stored as distance from camera / far plane distance, 1-d for more precision
output.Depth = float4(1-(input.Depth.x / input.Depth.y),0,0,1);

```

where (Vertex Shader)

```
output.Position = mul(input.Position, worldViewProjection);
output.Depth.xy = output.Position.zw;

```

(input = output of Vertex Shader)

and store it in a RenderTarget2D

```
depthTarg = new RenderTarget2D(GraphicsDevice, viewWidth,
                viewHeight, false, SurfaceFormat.Single, DepthFormat.Depth24, samples, RenderTargetUsage.DiscardContents);

```

But somehow, when I draw that (Single), I get this result: (displaying rgb)

channel r:

(all black)

channel g:

channel b:

channel a:

Why is there data in every color channel althrough i only defined a value on the red parameter (and 1 on a, but you can somehow see the outlines of the model, so it cant be all 1)

And surprisingly, the b channel looks almost like what I am looking for, but has strange lines in it which stay at the same distance to the camera if I move it.

# Answer
As Andon M. Coleman pointed out: The problem was that I treated the Depth Map as float4 and tried to get the r channel to retrieve my depth value.

I now simply get a float value from the map and (for presentation purposes) multiply it with a scalar of 500, creating a new Texture with its r,g,b channel holding the data calculated before.

Thanks!
> 3 votes

---
Tags: xna, xna-4.0, hlsl, depth
---


# Question
Title: How do I set up a depth buffer in SharpDX?
I draw some instanced cubes, but when i rotate the camera (or the world) some cubes that should be behind other cubes are drawn before the cubes.

I already had this issue a long time before and i remembered that is was because the depth buffer.

I don't know how to set up a depth buffer in SharpDX.

My current trial:

```
DepthStencilView depthStencilView;

```

Init

```
var zBufferTextureDescription = new Texture2DDescription
        {
            Format = Format.D16_UNorm,
            ArraySize = 1,
            MipLevels = 1,
            Width = this.RenderWindow.ClientSize.Width,
            Height = this.RenderWindow.ClientSize.Height,
            SampleDescription = new SampleDescription(1, 0),
            Usage = ResourceUsage.Default,
            BindFlags = BindFlags.DepthStencil,
            CpuAccessFlags = CpuAccessFlags.None,
            OptionFlags = ResourceOptionFlags.None
        };
using (var zBufferTexture = new Texture2D(Device, zBufferTextureDescription))
  depthStencilView = new DepthStencilView(Device, zBufferTexture);

DeviceContext.OutputMerger.SetTargets(depthStencilView, RenderTargetView);

```

Draw

```
//ClearRenderTargetView
DeviceContext.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth, 1f, 0);
//DrawInstanced(...);

```

My question: what steps do i have to do, to set up a depth buffer correctly?

(I don't use SharpDX.Toolkit)

# Answer
> 1 votes
To configure depth-stencil buffers, you need to do the following:

* Create a depth-stencil resource (a 2D texture) and an associated view, and bind the view to the output merger state; you're already doing this in the code you posted.
* Create a depth-stencil state object and assign *that* to the output merger as well. You *don't* appear to be doing this. You'll need SharpDX's `DepthStencilStateDescription` for this, and to assign it via `DeviceContext.OutputMerger.SetDepthStencilState` or something.
* Make sure to clear the buffer when appropriate, usually before rendering a frame. You're doing this too.

Basically it seems like you are only missing the step involving configuration and attaching the depth-stencil state; the state object controls whether or not the depth testing is enabled, what comparison function is used, and all that other useful stuff.

The MSDN has a good overview of the process that includes reasonable default values (for example, it's odd that you're trying to use a multi-sampled sample description in your depth-stencil texture resource). SharpDX is just a wrapper around the native API, so if you are familiar enough with the nomenclature mapping it uses to rename all the native API interfaces, you can usually just follow along with information for the native API and translate it.

---
Tags: c#, directx11, sharpdx
---


# Question
Title: What design pattern should I employ for validating character movement?
I'm developing a RPG in Java and have a Map class, which will contain all the MapObjects (the Player, Enemies, Walls, etc.):

Map.java

```
public class Map {

private int width;
private int height;

private ArrayList<MapObject> MapObjects = new ArrayList<MapObject>();

public Map(int width, int height) {
    this.width = width;
    this.height = height;
}
 }

```

Hero.java:

```
public class Hero extends MapObject implements Movable {

private Map map;

public Hero(int x, int y, int direction, Map map) {
    super(x, y, direction);
    this.map = map;
}

public boolean move(int direction) {
    //movement code
}

}

```

I will have a listener on an external class that will call the hero.move(direction) function.

What is the best approach to validate the movement (making sure that there's an empty space on the map)?

I could pass the Map as an argument, or even use the Command design pattern (the hero being the "remote" and the map being the implementation and executer), but I'm not sure if any of those are the right way to approach this problem.

# Answer
> 3 votes
Don't try to over-complicate or over-engineer your code by using design patterns as solution templates. Design patterns exist primarily as a means of communicating about a design efficiently. You should not think about problems in terms like "which design pattern do I use to solve this?" but rather "*what do I do* to solve this?" If what you do ends up aligning in some ways to a common pattern, great. But by limiting yourself only to choices considered design patterns you drastically reduce your solution search space.

In this case, you need something so simple it doesn't really have a "design pattern" associated with it. You need:

* the map object to be able to tell you if a given tile is passable
* your hero movement function to check if the tile the hero is going to move to is passable by asking the map (since it's already a member of the hero class).

That's all. Nice and simple. Keep your solutions simple and add generality as complexity increases; don't start with something more involved that it needs to be.

# Answer
> 1 votes
Design patters aren't used (mostly) to solve implementation problems. They are there to keep the code flexible and easy to maintain an change. Like others said, simply add a method that checks if that spot is empty and there is a clear path from the current spot to the destination. The question you should ask is how to implement the check in O(1). You probably should start by placing the items on the map in a grid instead of an ArrayList.

---
Tags: java, movement, tilemap, rpg
---


# Question
Title: How to save and restore Bullet Physics state?
I'm looking for information on how to save the runtime state of rigid bodies with Bullet Physics. Most of my world consists of static objects, but I have a few dynamic and kinematic objects as well. I need to take a snapshot of the game state and later restore the exact same state so that it produces the same simulation as if there wasn't any pause. I can easily (and prefer to) recreate the whole world including the rigid bodies, their configuration, collision shapes and constraints.

In addition I need to reset the objects to their initial state, but I think solving the save/restore problem also solves resetting.

I'm using JBullet, which is based on Bullet version 2.72. This means that the built-in serialization is not available for me, as it was added in version 2.76. However answers utilizing the serialization are also welcome, as Java has built-in serialization and others might find it useful. However the description on the wiki page sounds like it's meant for storing whole worlds instead of just the runtime state.

Checking the source code of RigidBody and CollisionObject reveals lots of internal non-final fields of which many are pointers instead primitives. I don't know which of the fields I should save and how to handle the non-primitive fields.

I am surprised to not having found any information on the Internet about this, as I think this is necessary for any game using Bullet physics and requiring exact save and restore functionality. I would prefer a solution that requires only the public API, but I'm open to other solutions as well including modifying the source code as a last resort. I'm also aware of the differences on floating point operations between platforms, but that is not a concern for me.

**Edit:**

I implemented the solution suggested by Byte56. I'm now saving and restoring worldTransform, linearVelocity and angularVelocity. I also tried motionState, but that did not have any effect. After restoring the state my object seems to continue the correct trajectory until first collision with a (static) wall. After the collision the object doesn't follow the same path anymore. Interestingly there seems to be only 5-7 slightly different paths that the object randomly chooses.

Without the save and restore my simulation is completely deterministic and always proceeds exactly the same results when running multiple times with the same starting values.

I was thinking that the randomness could have been because of uneven number of simulation steps. I'm using frame skipping and passing 1.0 / 60 as the delta time for stepSimulation: `dynamicsWorld.stepSimulation(deltaTime, 100, 1.0f / 200);`. I tried changing 200 to 180, but that didn't help. I wonder if there is something in the DiscreteDynamicsWorld that I should also save. I also tried to save `DiscreteDynamicsWorld.localTime` through reflection, but no luck.

**Edit2:**

After closer investigation even the initial trajectory before any collisions is slightly off. However there seems to be only a constant offset in the coordinates and after the first collision the path changes direction compared to the original.

I implemented a custom serializer using Java Reflection API, which recursively stores all primitive fields from `RigidBody` and `DiscreteDynamicsWorld`. That didn't help. I also tried changing physics updating to just `dynamicsWorld.stepSimulation(1.0f / 60.0f);`, but no luck there either. Now I'm out of ideas how to proceed.

# Answer
> 8 votes
I just write the body and shape values to a file. Then when reading them, I create a new body and shape and set the values to those read from the file. From what I've seen this works great. I haven't seen any strange behaviors or anything like that. Bodies that were flying through the air, continue to do so when the game is reloaded.

The values I read/write are: Mass, Friction, LocalInertia, LinearVelocity, AngularVelocity.

Acceleration values are stored from other components as I just apply impulses anyway. Saving takes place after a frame step, so there are no existing forces other than gravity.

I just take those values and create a new physics object just like I was adding a new one to the DyanmicsWorld.

Works well enough for me. Your results may vary if you're using the engine in a more advanced way than I am.

---

I've tested this out. I saved my game right when a physics object was falling towards a ramp on the ground. I then loaded the game and watched where the physics object ended up after hitting the ramp and rolling to a rest. Each time I loaded and watched the object, it ended up in the exact same spot, pixel for pixel (I took screen shots and compared). I performed the test five times with the same result.

So then I thought I would save it again, a little farther along its fall before it hits the ramp, then load again. The next time I loaded, it ended in a different place! However, now every time I load it, it ends up in that second spot.

Now, every time I load the game it always ends in the same spot, but that spot can change depending on the starting conditions.

---

Looking into it more, I've found that it's a common issue. See this bug report filed against bullet. And this post about serialization and determinism. The user claims to have good determinism if they save/restore when the scene is mostly settled (which doesn't seem very useful to me). This post claims contains information claiming that 3.x Bullet will be much better at this.

So, it appears to be **a failure with Bullet Physics**. There is hope that this will be solved soon with 3.x. Unfortunately, we don't really know how long it'll take once 3.x is out for that to get ported to JBullet.

If you require determinism *now*, then you'll have to implement a system independent of Bullet Physics. Otherwise you can wait to see what 3.x brings to the table.

# Answer
> 5 votes
From your latest comments, it looks like you're trying to save/restore all the internal simulation state inside Bullet (overlapping pairs, contact points, etc.). This sounds... daunting!

Another idea: Every frame, remove and re-add all your dynamic objects. Obviously, this is hugely bad for performance, but you indicated that you don't have many dynamic objects, so maybe it'll be okay. The goal here is to get Bullet to essentially clear all its internal state that's causing determinism problems.

Just to illustrate my thought process, let's take this idea to the extreme: You could destroy and re-create your Bullet world and all your Bullet objects every frame. Of course, you would re-create dynamic objects with the saved positions and velocities from the previous frame, so the simulation would still appear normal and continuous. This would almost certainly be deterministic, because you're preventing Bullet from maintaining any of its own internal state from one frame to the next.

# Answer
> 3 votes
So, if I understood your problem, you have a way to set an initial state, and a consistent function for advancing the state by one frame. You also have a way to retrieve a current state, but it is not reliable, since restoring to it gives different results than if you had not restored it in the first place.

In that case, I have three options for you to consider:

1. If you manage to reproduce the exact simulation by setting the same initial parameters, then you can save a state by saving those initial parameters, and the frame number where you want to stop. When loading the state, you reset your initial parameters and run the simulation as fast as you can, without pausing.

This is in my opinion a pragmatic solution, which will probably require the least amount of changes in your code. If the purpose of your system is to implement replays, this will work pretty well, as it supports playback and forward seeking natively. However, reverse playback, backward and random seeking are very expensive. Which leads us to:
2. If your purpose is to have a randomly seekable, but mostly for playback simulation, and your only problem with saving and restoring in the way Byte56 suggested, is that it gives *different* -but not *incorrect*\- results, then you can implement option number 1, with keyframes. This would mean that during the initial simulation (the one you're recording), every *n* frames, you save the state, **restore it**, and then continue.

When seeking, you first restore the closest saved state before the frame you wish to seek to, and then use option 1 above to seek to your specific frame. Once again, this works when seeking randomly, but is only marginally better than option 1 when playing backwards. By the way, this is how many video codecs work.

Needless to say, the closer your keyframes are, the more time it will take to save them. However, seeking will be faster. I'm pretty sure you can reach a good compromise in your case.
3. Use continuations. A continuation is an object which represents the state of a program (or part of it). Many languages, including C#, Lua and Python have mature support for continuations; also, languages where you have direct access to your memory like C, can also make it easier to implement continuations.

In the Java case, unfortunately, the closest implementation seems to be Javaflow, which apparently is not yet completed. But may be worth a look. This may require some substantial changes in your program, and you will probably be saving much more than just the relevant parameters.

To use continuations, you simply create a continuation object whenever you want to save the program state, and then resume from it whenever you want to seek to it.

# Answer
> 2 votes
I made Bullet physics deterministic by saving and restoring all bullet memory: Simply call `btAlignedAllocSetCustom` and `btAlignedAllocSetCustomAligned` for a custom allocator. This always works.

# Answer
> 0 votes
The problem has nothing to do with physics state loading or saving. The suggestion that Byte56 has given is perfectly valid; the real problem at hand here and the reason you're seeing deviating behavior however is your physics is using a variable time step. Read this question and answer and change your time step for physics to be fixed if you don't want behavior that is different on separate runs.

---
Tags: java, bullet-physics, savegame
---


# Question
Title: Why does my turn-based game loop allow the enemy to act repeatedly?
I'm trying to create a turn-based game in pyGame but hit a wall when trying to properly handle the main game loop. So I have something like this:

```
def loop(self):
    while self.stategame==1:
        for event in pygame.event.get():
            if event.type == QUIT \
            or (event.type == KEYDOWN and event.key ==    K_ESCAPE):
                self.stategame = 0

        if self.isPlayerTurn:
            self.events()
        else:
            self.enemyTurn()
        self.draw_map()

        pygame.display.flip()

```

The enemyTurn() function here is called multiple times after each player's move causing the enemies to move multiple tiles before the player does anything again. I'm a beginner in gamedev do I don't know how to overcome this and, in the first place, why does it hapen. Isn't the code supposed to be analyzed from top to bottom like in regular Python so that the enemyTurn() is called just once and then the game goes back to waiting for user input? How can I solve this problem and call the enemyTurn() just once each time the player makes a move?

# Answer
> 9 votes
> Isn't the code supposed to be analyzed from top to bottom like in regular Python so that the enemyTurn() is called just once and then the game goes back to waiting for user input?

The code is executed just like normal code; your assertion here is correct *except* that your code doesn't have anywhere that "waits for user input."

The function `pygame.event.get()` gets all messages in the event queue and removes them. The documentation does not mention that the function will block if empty (indeed, that's probably what `wait` is for.

So your loop never waits for user input, it simply gets any available input, and even if there wasn't any, goes on to either call `self.events()` or `self.enemyTurn()`, depending on the state of `self.playerTurn`.

It sounds like `self.enemyTurn()` doesn't necessarily always toggle that variable, and so you end up calling `enemyTurn` several times in a row; make sure you toggle `playerTurn` when appropriate.

# Answer
> 2 votes
Just change the turn after the enemy moves:

```
    if self.isPlayerTurn:
        self.events()
    else:
        self.enemyTurn()
        self.isPlayerTurn = True

```

Also, your main loop seems to lack a clock.Tick() to avoid using CPU all the time.

---
Tags: architecture, game-loop, pygame
---


# Question
Title: Why does Unity in 2d mode employ scaling and the default othographic size the way it does?
I previously used SFML, XNA, Monogame, etc. to create 2d games, where if I display a 100px sprite on the screen, *it will take up 100px*. If I use 128px tiles to create a background, the first tile will be at (0, 0) while the second will be at (128, 0).

Unity on the other hand, has its own odd unit system, scaling on all transforms, pixel-to-units, othographic size, etc, etc. So my question is two-fold, namely:

1. Why does Unity have this system by default for 2d? Is it for mobile dev? Is there a big benefit I'm not seeing?
2. How can I setup my environment, so that if I have a 128x128 sprite in Photoshop, it displays as a 128x128 sprite in Unity when I run my game?

Note that I am targeting desktop exclusively.

# Answer
Handling 2D coordinates and scaling in Unity is fairly simple, but non-obvious and as you've noticed it's unlike how other dev tools work. Why this happens is because Unity was a 3D engine that recently had 2D graphics grafted in.

In particular, 1 unit in Unity is not necessarily 1 pixel in the image. When you import images as 2D Sprites there's actually a Pixels-to-Units setting that could be made 1:1 but I recommend leaving it at the default 100:1 for a couple reasons (the physics engine doesn't work right at 1:1, and the default is better for compatibility with others' code).

This scaling setting means that all positions are divided by 100. It's pretty easy as long as you always remember the scaling; when you want to move a sprite 256 pixels (say) then you move it 2.56 You may also want to write a utility function to round numbers to 2 decimal places/the nearest pixel: Mathf.Round(float * 100) / 100f

---

As for setting up a pixel-perfect camera, first off set it as an orthographic camera. When you select the camera, in it's settings is a drop-down for Perspective or Orthographic projection; perspective means things will look 3D, while orthographic displays the scene flat. Right under this drop-down is Size; set the camera's orthographic size to half the pixel dimensions of the screen you want.

For example, let's say you want a pixel-perfect 1024x768 screen. Well that means the camera height should be 384 pixels. Divide that by 100 (because of the pixels-to-units scale) and you get 3.84 for the camera size. Again, that math is simply SCREEN\_SIZE / 2 / 100f

---

(I was waiting to see what other answers come first, but it's been a couple days. I've been doing 2D in Unity for a while using 2D Toolkit, but am relatively new to the built-in 2D features)
> 4 votes

# Answer
As jhocking says, it's a result of shoehorning 2D into a 3D IDE. But, there is a solution, it's just a bit arcane.

First step is to open your sprite's Import Settings from the Project pane. Once Texture Type is set to Sprite or Advanced (Advanced gives you other handy options, but Sprite is default if you created a 2D project at the beginning), there's a Pixels To Units field with a default of 100.

I'm mucking around with a tile system, so I'm using 16x16 pixel tiles and set Pixels To Units to 16. The math works like so: Size in pixels (either X or Y) / Pixels To Units = Unity Units in Transform. 16 pixel cube with PTU 16 takes up 1 unit in Unity space.

I haven't tried yet, but I expect a PTU of 1 would make things pixel perfect.

The orthographic camera setting is a bit of a headache however. Once again, it's based of that Pixels to Units setting, but also a few other things. Basically it's half the screen height from Player Settings (ie 1080, 768, whatever the iPhone 5 is, can't be bothered to look it up) divided by Pixels To Units.
> 2 votes

# Answer
Pixel units is not a good way to represent large worlds due to the way that floating point numbers work. With floating point numbers, you lose precision with very large numbers. Numbers that are near 0 have the best precision. Thus, some game engines tend to prefer the MKS system of metrics (Meters/Kilograms/Seconds). Unity defaults to meters, so game characters can easily be represented as 1.0-2.0 meters tall with very good precision.

The average weight and height of a human male is about 50kg and 1.8meters tall. If you tried to make a character that is 1200 pixels tall, its weight would be about 33,000 pixels units. If you then wanted to add a a very heavy object like a bus to a game, you'd have a huge number of pixel units. You can easily see how this could lead to very imprecise calculations for collisions.

If you are very determined to use pixel units, you can easily calculate the pixels to meters ratio.
> 1 votes

---
Tags: 2d, unity, sprites, camera
---


title: How do I make a slot car game?

text:
# Question
Title: How do I make a slot car game?
I new to game development with Unity and my first project is a slot car racer. For a realistic slot car-like-driving experience, I first build a track with a channel in the track and a pin on the car. This kind of works, but it does not look like a slot car, its more like a car with a pin and sometimes the physics just go crazy and kick me out of the channel.

I next tried making a spline with a simple game object following the track. I attached my car to my "follower" with a fixed joint. This didn't work so well: My car was tumbling and pulled sideway but I never archived that my car gets pulled down the track.

How should I be approaching this? I'd like the car to accelerate and decelerate quickly, with that acceleration and deceleration controllable by the user.

# Answer
You should consider using a large rectangular prism as the pin. Keep in mind that what you draw on the screen does not have to match the meshes that are used to determine the collisions. You could draw a normal slot car on the screen, but use a large rectangular prism mesh that is not visible to the player, which would help prevent the car from being thrown from the track on high-speed turns.

The length of the prism could run parallel to the track, and the length and width could easily be adjusted to get the precise collisions that you are happy with.
> 2 votes

---
Tags: unity, 3d, physics, car
---


# Question
Title: Which library to choose between SDL and GTK for C game Development (Begginer)
I've been programming in C it's been some time, now I want to get into game development but I'm not sure which GUI library should I use between SDL or GTK? Is it worth sticking up with C or should I switch to C++ (taking out the learning time barrier) ? What will C++ give me that C won't when developing simple 2D games. I am not willing to switch to any other language such as "Java, python, etc" for I still want to use the low level memory management capabilities that C and C++ give. I am also not willing to use a Game Engine to learn game development.

# Answer
**Answer**

**First**, I think you might be mixing up some terms. For games you want a game-engine such as SDL or unity (list on wikipedia). For graphical user interfaces (GUI) you want something like Qt, GTK, wx (list on wikipedia).

You CAN use a GUI library to make games, it depends on the game type. But if you want high performance game specific features such as realtime 3d graphics and asset management then you should definitely look for a game engine.

**Second**, the ideals in C++ are very different from the ideals in C. You CAN (and many people do) mix C++ and C. That is in my book a good feature of C++, that you can program like you are used to in C using a C++ compiler, and learn new C++ features as you go. C++ has many many features that can benefit you, especially if you want to write more high-level code. Some game engines and GUI libraries rely on C++ and are not available for pure C programs (for example Qt).
> 5 votes

# Answer
SDL and GTK are quite different in the sense that SDL just tries to provide you with a drawing surface and device inputs. GTK provides you with a user interface toolkit, that is, it provides you with user interface elements such as scrollbars, push buttons and so on. GTK is also quite complex compared to SDL. So I'd definitely go with SDL here. C or C++.. That's a can of worms I'm not going to open.
> 1 votes

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


# Question
Title: Collision between sprites in game programming?
I've since just started coding for an android game using eclipse. I've read Beginning Android Game Programming and various other e-books. Recently, I've encountered a problem with collision between sprites. I've used this code template for my program.

```
package com.project.CAI_test;

import java.util.Random;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;

public class Sprite {
       // direction = 0 up, 1 left, 2 down, 3 right,
       // animation = 3 back, 1 left, 0 front, 2 right
       int[] DIRECTION_TO_ANIMATION_MAP = { 3, 1, 0, 2 };
       private static final int BMP_ROWS = 4;
       private static final int BMP_COLUMNS = 3;
       private static final int MAX_SPEED = 5;
       private GameView gameView;
       private Bitmap bmp;
       private int x = 0;
       private int y = 0;
       private int xSpeed;
       private int ySpeed;
       private int currentFrame = 0;
       private int width;
       private int height;

       public Sprite(GameView gameView, Bitmap bmp) {
             this.width = bmp.getWidth() / BMP_COLUMNS;
             this.height = bmp.getHeight() / BMP_ROWS;
             this.gameView = gameView;
             this.bmp = bmp;

             Random rnd = new Random();
             x = rnd.nextInt(gameView.getWidth() - width);
             y = rnd.nextInt(gameView.getHeight() - height);
             xSpeed = rnd.nextInt(MAX_SPEED * 2) - MAX_SPEED;
             ySpeed = rnd.nextInt(MAX_SPEED * 2) - MAX_SPEED;
       }

       private void update() {
             if (x >= gameView.getWidth() - width - xSpeed || x + xSpeed <= 0) {
                    xSpeed = -xSpeed;
             }
             x = x + xSpeed;
             if (y >= gameView.getHeight() - height - ySpeed || y + ySpeed <= 0) {
                    ySpeed = -ySpeed;
             }
             y = y + ySpeed;
             currentFrame = ++currentFrame % BMP_COLUMNS;
       }

       public void onDraw(Canvas canvas) {
             update();
             int srcX = currentFrame * width;
             int srcY = getAnimationRow() * height;
             Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);
             Rect dst = new Rect(x, y, x + width, y + height);
             canvas.drawBitmap(bmp, src, dst, null);
       }

       private int getAnimationRow() {
             double dirDouble = (Math.atan2(xSpeed, ySpeed) / (Math.PI / 2) + 2);
             int direction = (int) Math.round(dirDouble) % BMP_ROWS;
             return DIRECTION_TO_ANIMATION_MAP[direction];
       }

       public boolean isCollition(float x2, float y2) {
             return x2 > x && x2 < x + width && y2 > y && y2 < y + height;
       }
}

```

The above code only detects collision between the generated sprites and the surface border. What I want to achieve is a collision detection that is controlled by the update function without having to change much of the coding. Probably several lines placed in the update() function. Tnx for any comment/suggestion.

# Answer
This is fairly simple. In this example the class we check for collision with is called Example, and that class has its own getBounds() method.

```
 public Rect getBounds(){
   return new Rect(x, y, x+width, y+height);
 }

 Public void checkCollision(){
    Rect mySprite = this.getBounds();
    Rect myCollisionObject = example.getBounds();
    if(mySprite.intersect(myCollisionObject)){
        //Todo code here
    }
  }

```

then you just put this method in your update-method.
> 2 votes

# Answer
I've used this template, too and I assigned my sprites to an array list. I've tried automating collision from the update () method in the sprite class itself. So far all I get is moving sprites bounding from the borders but not bounding when they collide with each other...
> 0 votes

# Answer
You will need the height and width of both Sprites. try something like this:

```
 public boolean collidesWith(Sprite obj) {
    if (obj.y <= this.y + this.height &&
               obj.y + obj.height >= this.y    &&
               obj.x + obj.width >= this.x &&
               obj.x <= this.x + this.width){
        return true;
    }
    return false;
}

```
> 0 votes

---
Tags: java, android, collision-detection, game-mechanics
---


# Question
Title: Render 2 images that uses different shaders
Based on the giawa/nehe tutorials, how can I render 2 images with different shaders. I'm pretty new to OpenGl and shaders so I'm not completely sure whats happening in my code, but I think the shaders that is called last overwrites the first one.

```
private static void OnRenderFrame()
{
    // calculate how much time has elapsed since the last frame
    watch.Stop();
    float deltaTime = (float)watch.ElapsedTicks / System.Diagnostics.Stopwatch.Frequency;
    watch.Restart();

    // use the deltaTime to adjust the angle of the cube
    angle += deltaTime;

    // set up the OpenGL viewport and clear both the color and depth bits
    Gl.Viewport(0, 0, width, height);
    Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

    // use our shader program and bind the crate texture
    Gl.UseProgram(program);

    //<<<<<<<<<<<<   TOP PYRAMID
    // set the transformation of the top_pyramid
    program["model_matrix"].SetValue(Matrix4.CreateRotationY(angle * rotate_cube));
    program["enable_lighting"].SetValue(lighting);
    // bind the vertex positions, UV coordinates and element array
    Gl.BindBufferToShaderAttribute(top_pyramid, program, "vertexPosition");
    Gl.BindBufferToShaderAttribute(top_pyramidNormals, program, "vertexNormal");
    Gl.BindBufferToShaderAttribute(top_pyramidUV, program, "vertexUV");
    Gl.BindBuffer(top_pyramidTrianlges);
    // draw the textured top_pyramid
    Gl.DrawElements(BeginMode.Triangles, top_pyramidTrianlges.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);

    //<<<<<<<<<<    CUBE
    // set the transformation of the cube
    program["model_matrix"].SetValue(Matrix4.CreateRotationY(angle * rotate_cube));
    program["enable_lighting"].SetValue(lighting);
    // bind the vertex positions, UV coordinates and element array
    Gl.BindBufferToShaderAttribute(cube, program, "vertexPosition");
    Gl.BindBufferToShaderAttribute(cubeNormals, program, "vertexNormal");
    Gl.BindBufferToShaderAttribute(cubeUV, program, "vertexUV");
    Gl.BindBuffer(cubeQuads);
    // draw the textured cube
    Gl.DrawElements(BeginMode.Quads, cubeQuads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);

    //<<<<<<<<<<<<   BOTTOM PYRAMID
    // set the transformation of the bottom_pyramid
    program["model_matrix"].SetValue(Matrix4.CreateRotationY(angle * rotate_cube));
    program["enable_lighting"].SetValue(lighting);
    // bind the vertex positions, UV coordinates and element array
    Gl.BindBufferToShaderAttribute(bottom_pyramid, program, "vertexPosition");
    Gl.BindBufferToShaderAttribute(bottom_pyramidNormals, program, "vertexNormal");
    Gl.BindBufferToShaderAttribute(bottom_pyramidUV, program, "vertexUV");
    Gl.BindBuffer(bottom_pyramidTrianlges);
    // draw the textured bottom_pyramid
    Gl.DrawElements(BeginMode.Triangles, bottom_pyramidTrianlges.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);

     //<<<<<<<<<<<<<     STAR
     Gl.Disable(EnableCap.DepthTest);
     Gl.Enable(EnableCap.Blend);
     Gl.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.One);

     Gl.BindTexture(starTexture);
     //calculate the camera position using some fancy polar co-ordinates
      Vector3 position = 20 * new Vector3(Math.Cos(phi) * Math.Sin(theta), Math.Cos(theta), Math.Sin(phi) * Math.Sin(theta));
      Vector3 upVector = ((theta % (Math.PI * 2)) > Math.PI) ? Vector3.Up : Vector3.Down;
      program_2["view_matrix"].SetValue(Matrix4.LookAt(position, Vector3.Zero, upVector));

     // make sure the shader program and texture are being used
     Gl.UseProgram(program_2);

     // loop through the stars, drawing each one
     for (int i = 0; i < stars.Count; i++)
     {
         // set the position and color of this star
         program_2["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(stars[i].dist, 0, 0)) * Matrix4.CreateRotationZ(stars[i].angle));
         program_2["color"].SetValue(stars[i].color);

         Gl.BindBufferToShaderAttribute(star, program_2, "vertexPosition");
         Gl.BindBufferToShaderAttribute(starUV, program_2, "vertexUV");
         Gl.BindBuffer(starQuads);

         Gl.DrawElements(BeginMode.Quads, starQuads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero);

         // update the position of the star
         stars[i].angle += (float)i / stars.Count * deltaTime * 2 * rotate_stars;
         stars[i].dist -= 0.2f * deltaTime * rotate_stars;

         // if we've reached the center then move this star outwards and give it a new color
         if (stars[i].dist < 0f)
         {
             stars[i].dist += 5f;
             stars[i].color = new Vector3(generator.NextDouble(), generator.NextDouble(), generator.NextDouble());
         }
     }
    Glut.glutSwapBuffers();
}

```

The same goes for the textures, whichever one I mention last gets applied to both object?

# Answer
The word you are looking for is `bind`. When you bind a texture or shader, that will be the "active" texture or shader.

For shaders it looks like this:

```
Gl.UseProgram(program);

```

And for textures it looks like this:

```
Gl.BindTexture(texture);

```
> 1 votes

---
Tags: opengl, c#, shaders
---


# Question
Title: Can I use the names or logos of real football teams in my game?
I am developing a football game and I want to know if it is legal to name teams after real football teams. What about their logos?

# Answer
The names of sports teams names are usually trademarks of their owning corporation or entity, as are the logos. You cannot use them as teams in your games without permission.

This is a legal matter; you should contact your lawyer for definitive advice.
> 3 votes

---
Tags: legal, copyright, trademark
---


# Question
Title: How do I make objects' speeds appear the same despite screen resolution?
I'm working on my HTML5 game with Intel XDK. I'm stuck on making all devices display the same number of frames per second.

The first generation iPad has a screen resolution of 1024 pixels horizontally, while the Motorola Moto G Android phone has ~2657 pixels horizontally. With my game running at 30 FPS and sprites moving at 1 pixel per frame on the Motorola, this can take up to 5 mins to get from one side to the other.

Changing the FPS to 300 makes it work normally on the Motorola but too fast on the iPad.

Is there a work-around for this?

# Answer
There is a deeper problem revealed in your question. You are experiencing this difficulty because you are conceiving of the movement in your game as being pixels/frame, when you should be thinking of units/second. This is sometimes called "frame independent movement" and you can see a good stackexchange q&a on it at Frame Independent Movement.

The basic idea of units/second is this: "Units" can be arbitrarily defined by you to whatever is convenient. 1.0 unit could be the width of the player-controlled character, and your canvas would be determined by you to be w x h of those units, perhaps chosen to match actual resolution against an ideal number of pixels wide for your stage. Once that calculation is made, it's all units, all the time.

* How fast does your character move at full speed? 3 units / second.
* How tall is this barrer? 2.25 units.
* How fast do enemy projectiles move? 0.5 units / second.

Embrace this thinking and your programming tasks will be immensely simplified, in Intel XDK and anywhere else.
> 1 votes

# Answer
Answer from stack overflow comments - https://stackoverflow.com/questions/3193277/how-do-i-make-a-canvas-drawing-to-completely-fill-the-browser

With a Canvas it's possible to set the physical/viewable size and the virtual size independently, eg. draw onto a 500x500 canvas that's been set to fill a 1280x768 screen, but the actual canvas still remains at 500x500. I think this is what Micah is trying to do, hence why this solution wouldn't really work.
> 0 votes

---
Tags: frame-rate, aspect-ratio, intel
---


# Question
Title: What's the difference between an "SDK" and an "engine?"
In delving into game programming, I have encountered both "SDKs" and "game engines". What are their relationships and differences to each other?

# Answer
To be as concise as possible, an **SDK** is **engine + tools**. It gives you all you need to make a game for that platform.

Sometimes you don't need specialised tools to make a game; in that case you only need an engine. Sometimes they are required or at least very helpful.

To give a few examples:

* UDK, in addition to the Unreal engine, includes editors to create content suited for the engine.
* Back in the cartridge console days, the console vendor would give you a kit with hardware tools, such as a doohickey (like gameshark/gamegenie) that you plug in between the cartridge and console, which gives useful diagnostic output. Sometimes they will also give you a special development version of the console that amounts to the same thing.

Of course, you can have SDKs for things that aren't engines, which adds a bit of confusion. The DirectX SDK for example doesn't include a game engine, as DirectX is a graphics/multimedia framework.
> 3 votes

# Answer
SDK applies to all of software development, whereas "engine" pretty much only applies to games. That's the only real difference between the terms (and even this description of "engine" plenty of people will disagree with); everything else is just semantics.
> -1 votes

---
Tags: terminology
---


title: glViewport like camera

text:
# Question
Title: glViewport like camera
I'm using glViewport as a camera of sorts, but I'm not quite sure how it works. For example when I change do:

```
glOrtho(0, 800, 600, 0, -1, 1);
glViewport(0, 0, 400, 200);

```

It makes the viewing area larger rather than just viewing a 400x200 area...

# Answer
> 1 votes
glViewport sets the viewport of your application. The viewport should be set to the size of your screen, window, canvas (for webgl) or texture you are rendering to.

glOrtho sets the selected matrix parallel projection matrix, which can be used as a camera. Calling it like in the following sample lets you control the position with the `x`and `y` variables while allowing you to change the size with the `width`and `height` variables.

```
float left = x - width / 2;
float right = x + width / 2;
float bottom = y + height / 2;
float top = y - width / 2;
glOrtho(left, right, bottom, top, -1, 1);

```

# Answer
> 1 votes
`glViewport` is a ***completely*** different transformation than you think it is. What `glViewport` actually does is re-map the scene *after* projection.

In OpenGL, the scene always projects to a special coordinate space where the viewing volume is defined by a cube: \[**-1**,**1**\] (following division by `W`). The location (-1,-1,-1) is the bottom-left of your viewport at the near clip plane. The location (1,1,1) is the top-right of your viewport at the far clip plane. Your projection matrix produces coordinates in a special coordinate space called *clip-space*, and the *clip-space* coordinates are divided by `W` to produce the NDC coordinates described above.

Thus, the only thing that `glViewport` actually does is define ***where within your window*** that your projected image is displayed. It will effectively stretch the scene, and I do not think that is what you want. To display a 400x200 area, you need to alter your projection matrix as well so that you do not simply compress your projected scene into a smaller area.

### Consider the following instead:

```
glOrtho    (0, 400, 200, 0,    -1, 1);
glViewport (0, 0,   400, 200);

```

---
Tags: lwjgl
---


title: Choose tile based on adjacent tiles

text:
# Question
Title: Choose tile based on adjacent tiles
I am working on a tiled map editor, and I need to choose tiles automatically, based on the adjacent tiles. For example, when placing a road tile, next to another road tile, the two need to be oriented so that they form a continuous road. If there are other roads around them, we may need to use corner or intersection tiles.

Can anyone recommend some algorithms for doing this? The game uses an 8-directional square tiled map.

# Answer
Maybe this is how it's typically done. You have your list of different tiles that represent a road tiles in all their possible orientations. Left to right, all four corners, top to bottom, whatever. Now you'll index all those tiles with a byte each. 8 bits, one for each direction. This could be in a hashmap or by file name... however you want to do this.

So you have this:

The byte code for the above tile is **00000000**. Then your tile that goes from left to right (or right to left) is like this:

The byte code for that tile is **10001000**, or 136. As another example, lets look at a three way intersection:

The byte code for that tile is **10101000**.

You probably see where I'm going. You set bit positions in the byte representing connections. This is far better than trying to do some big if/else chain that I've seen before. When you're looking to place a tile, examine the tiles around it and create a byte along the way. Set 1's for tiles that have roads (or whatever you're looking to connect) and 0's for tiles that don't. When you're done, you'll have the byte code for the exact tile you need.

Note that when creating the assets you can reuse a lot of them by simply rotating and assigning the correct byte code to it.

**EDIT**: Updated images to be less crappy. Yes those are better than before.
> 18 votes

# Answer
I would recommend you take a look at this handy page for more information, as it goes into great detail about pretty much every aspect of what you're doing, as well as a few potential optimizations: http://www.angryfishstudios.com/2011/04/adventures-in-bitmasking/

The tldr is that you query each adjacent cell and store the combination in a bitfield/byte, then pass it through a map that converts a number from 0~255 into a value from 0~47, which corresponds to a unique image.
> 3 votes

---
Tags: algorithm, tilemap
---


# Question
Title: When to get input state: multiple times or one time in a static class?
Let's say I have these classes:

* Player

Here I want to make the player jump:

```
  current_state_ = Keyboard.GetState();
  if ((current_state_.IsKeyDown(Keys.Space) || current_state_.IsKeyDown(Keys.Up))
       Jump();

```
* Intro scene
* GameOver scene

Here I just want to give the possibility to skip those scenes:

```
  current_state_ = Keyboard.GetState();
  if ((current_state_.IsKeyDown(Keys.Space) || current_state_.IsKeyDown(Keys.Up))
       SkipScene();

```

My question is what is usual done:

* "Asking" for input in every class, or make a static class that asks for input every update, and then you get that value?

```
public static class InputHandler
{
    private static KeyboardState current_state_;

    public static bool IsSpacePressed()
    {
        return current_key_.IsKeyDown(Keys.Space);
    }

    // Others

    // To be called in game's main loop
    public static void Update(GameTime gametime)
    {
        current_key_ = Keyboard.GetState();
    }
}

```

I'm worried about that because I thought (don't know if it is correct!) that maybe it is wrong to ask multiple times per update for input.

# Answer
> 0 votes
Generally speaking, static properties are a no-no in this case. They should only be used for utility functions (Vector3.Lerp), or for read only variables that will be identical for all instances of a class (Vector3.UnitX).

They introduce issues when trying to synchronize resources because of their nature (anything can access them, so several objects can attempt to update at the same time), and looking up static variables has a significant performance overhead. They also introduce a slippery slop when programming - once you start using them, the longer you go on for, the harder it is to stop.

I would suggest creating one local instance of the keyboards current state in your games main Update method as a local variable (local scope allocation and deallocation are slightly faster than accessing a global variable) and passing it to your Player, IntroScene and GameOverScene classes via a seperate paramater in their update call. This means instead of accessing some global static variable somewhere, you're accessing a local variable variable, which exists in the same scope (local scopes get searched first for variables before global scopes). Also, it means you only fetch the keyboard state once per update, further saving on performance. Given the number of update calls a second, a little bit of performance gain can go a long way

However, it does boil down to your preference in the end. If you feel statics are the best way to go, then who are we to stop you?

Some further reading, if you are interested.

http://forum.unity3d.com/threads/186915-Declaring-a-Variables-Locally-Vs-Globally-Effect-on-Performance

https://stackoverflow.com/questions/9924223/static-vs-non-static-class-members

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


# Question
Title: Seamless tilemap rendering (borderless adjacent images)
I have a 2D game engine that draws tilemaps by drawing tiles from a tileset image. Because by default OpenGL can only wrap the entire texture (`GL_REPEAT`), and not just part of it, each tile is split off in to a separate texture. Then regions of the same tile are rendered adjacent to each other. Here's what it looks like when it's working as intended:

However as soon as you introduce fractional scaling, seams appear:

Why does this happen? I thought it was due to linear filtering blending the borders of the quads, but it still happens with point filtering. The only solution I've found so far is to ensure all positioning and scaling only happens at integer values, *and* use point filtering. This can degrade the visual quality of the game (particularly that sub-pixel positioning no longer works so motion is not so smooth).

Things I have tried/considered:

* antialiasing reduces, but does not entirely eliminate, the seams
* turning off mipmapping, has no effect
* render each tile individually and extrude the edges by 1px - but this is a de-optimisation, since it can no longer render regions of tiles in one go, and creates other artefacts along the edges of areas of transparency
* add a 1px border around source images and repeat the last pixels - but then they are no longer power-of-two, causing compatibility problems with systems without NPOT support
* writing a custom shader to handle tiled images - but then what would you do differently? `GL_REPEAT` should be grabbing the pixel from the opposite side of the image at the borders, and not pick transparency.
* the geometry is exactly adjacent, there are no floating point rounding errors.
* if the fragment shader is hard coded to return the same color, *the seams disappear*.
* if the textures are set to `GL_CLAMP` instead of `GL_REPEAT`, *the seams disappear* (although the rendering is wrong).
* if the textures are set to `GL_MIRRORED_REPEAT`, *the seams disappear* (although the rendering is wrong again).
* if I make the background red, the seams are still white. This suggests it's sampling opaque white from somewhere rather than transparency.

So the seams appear only when `GL_REPEAT` is set. For some reason in this mode only, at the edges of the geometry there is some bleed/leakage/transparency. How can that be? The entire texture is opaque.

# Answer
> 1 votes
The seams are correct behaviour for sampling with GL\_REPEAT. Consider the following tile:

Sampling on the edges of the tile using fractional values mixes colors from the edge and the opposite edge, resulting in wrong colors: The left edge should be green, but is a mix from green and beige. The right edge should be beige, but is a mixed color as well. Especially the beige lines on the green background are very visible, but if you look closely you can see the green bleeding into the edge:

> antialiasing reduces, but does not entirely eliminate, the seams

MSAA works by taking more samples around polygon edges. Samples taken left- or right of the edge will be "green" (again, considering the left edge of the first picture), and only one sample will be "on" the edge, partialy sampling from the "beige" area. When the samples are mixed the effect will be reduced.

**Possible solutions:**

*In any case* you should switch to `GL_CLAMP` to prevent bleeding from the pixel at the opposite side of the texture. Then you have three options:

1. Enable anti-aliasing to smooth the transition between the tiles a bit.
2. Set the texture filtering to `GL_NEAREST`. This gives all pixels hard edges, so polygon/sprite edges become indistinguishable, but it is obviously changes the style of the game quite a bit.
3. Add the already discussed 1px border, **just make sure the border has the color of the adjacent tile** (and not the color of the opposite edge).

* This might also be a good time to switch to a texture atlas (just make it bigger if you are concerned about NPOT support).
    * This is the only "perfect" solution, enabling `GL_LINEAR`-like filtering across the edges of polygons/sprites.

# Answer
> 6 votes
> Because by default OpenGL can only wrap the entire texture (GL\_REPEAT), and not just part of it, each tile is split off in to a separate texture. Then regions of the same tile are rendered adjacent to each other.

Consider the display of an single, ordinary textured quad in OpenGL. Are there any seams, at any scale? No, never. Your goal is to get all your scene tiles packed tightly onto a single texture, *then* send that to the screen. **EDIT** To clarify this further: If you have discrete bounding vertices on each tile quad, you *will* have seemingly-unjustified seams under most circumstances. It's how GPU hardware works... floating point errors create these gaps based on the current perspective... errors which are avoided on a unified manifold, since if two faces are adjacent *within the same manifold* (submesh), the hardware will render them without seams, guaranteed. You've seen this in countless games and apps. You must have one tightly-packed texture on a single submesh without doubled vertices to avoid this once and for all. It's an issue that comes up time and again on this site and elsewhere: if you don't merge the corner vertices of your tiles (every 4 tiles share a corner vertex), expect seams.

(Consider that you may not even need vertices except at the four corners of the entire map... depends on your approach to shading.)

To solve: render (at 1:1) all of your tile textures into an FBO/RBO with no gaps, then send that FBO to the default framebuffer (the screen). Because the FBO itself is basically a single texture, you cannot end up with gaps on scaling. All texel boundaries that don't fall on a screen pixel boundary are going to be blended if you're using GL\_LINEAR.... which is exactly what you want. This is the standard approach.

This also opens up a number of different routes to scaling:

* scaling the size of the quad to which you will render the FBO
* changing the UVs on that quad
* fiddling with camera settings

# Answer
> 1 votes
If the images should appear as one surface, render these as one surface texture (scale 1x) on one 3D mesh/plane. If you render each as a separate 3D object it will always have seams due to rounding errors.

The answer by @Nick-Wiggill is correct, i think you misunderstood it.

# Answer
> 0 votes
2 possibilities that might be worth trying:

1. Use `GL_NEAREST` instead of `GL_LINEAR` for your texture filtering in. (As pointed out by Andon M. Coleman)

`GL_LINEAR` will (in effect) blur the image ever so slightly (interpolating between the nearest pixels), which allows for a smooth transition in color from one pixel to the next. This can help make textures look better in many cases, since it prevents your textures from having those blocky pixels all over it. It also makes it so that a little bit of brown from one pixel of one tile over can get blurred over to the adjacent green pixel of the adjacent tile.

`GL_NEAREST` just finds the nearest pixel and uses that color. No interpolation. As a result, it's actually a little faster to.
2. Shrink the texture coordinates for each tile a little.

Sort of like adding that extra pixel around each tile as a buffer, except instead of expanding the tile on the image, you shrink the tile in the software. 14x14px tiles while rendering instead of 16x16px tiles.

You might even be able to get away with 14.5x14.5 tiles without too much brown being mixed in.

--edit--

As shown in the image above, you can still easily use a power of two texture. So you can support hardware that doesn't support NPOT textures. What changes is your texture coordinates, instead of going from `(0.0f, 0.0f)` to `(1.0f, 1.0f)` You'd go from `(0.03125f, 0.03125f)` to `(0.96875f, 0.96875f)`.

That puts your tex-coords slightly inside the tile which reduces the effective resolution in game (though not on hardware so that you still have power-of-two textures), however should have the same rendering effect as expanding the texture.

# Answer
> 0 votes
Here is what I think that might be happening: Where two tiles collide, the x component of their edges should be equal. If that is not true, they might get rounded into the opposite direction. So make sure that they have exactly the same x value. How do you ensure that this happens? You might try to, lets say, multiply by 10, round and then divide by 10 (only do this on the CPU, before your vertices are going into the vertex shader). That should give correct results. Also, do not draw tile by tile using transformation matrices, but put them in a batch VBO to make sure that the wrong results are not coming from the lossy IEEE floating point system in combination with matrix multiplications.

Why do I suggest this? Because from my experience, if the vertices have the exact same coordinates when they come out of the vertex shader, filling the corresponding triangles will create seamless results. Keep in mind that something that is mathematically correct, might be a bit off due to IEEE. The more calculations you perform on your numbers, the less accurate the result will be. And yes, matrix multiplications require quite some operations, that might be done in only a multiplication and an addition when creating your VBO, which will give more accurate results.

What also might be the problem is that you are using a spritesheet (also called atlas) and that when sampling the texture, the pixels of the adjacent tile texture gets picked. To ensure that this doesn't happen is to create a tiny border in the UV mappings. So, if you have a 64x64 tile, your UV mapping should cover a bit less. How much? I think I used in my games 1 quarter of a pixel at each side of the rectangle. So offset your UV's by 1/(4\*widthOfTheAtlas) for x components and 1/(4\*heightOfTheAtlas) for y components.

# Answer
> 0 votes
To solve this in 3D space, I mixed texture arrays with Wolfgang Skyler's suggestion. I put a 8-pixel border around my real texture for each tile (120x120, 128x128 total) which, for each side, which I could fill with "wrapped" image or the side just being extended. The sampler reads this area when it is interpolating the image.

Now with filtering and mipmapping, the sampler can still easily read past the entire 8 pixel border. To catch that small problem (I say small because it only happens on a few pixels when geometry is really skewed or far away), I split the tiles into a texture array, so each tile has its own texture space and can use clamping on the edges.

In your case (2D/flat), I would certainly go with rendering a pixel perfect scene, and then scaling the desired portion of the result into the viewport, as suggested by Nick Wiggil.

---
Tags: opengl, 2d, rendering, tiles, tilemap
---


# Question
Title: Find the next cell in a grid from a point and direction
I'm trying to solve a very simple problem but I'm unable to come-up with an efficient solution so far. What I'm really trying to do is voxelize triangles in a three dimensional environment but I'll give a 2D example of my problem.

I have a point **P** and a direction **d**. **P** is somewhere inside a cell in the grid. I can easily calculate which cell.

My questions is. When I trace a line from **P** in direction *d* what are the coordinates of the first cell I will encounter, and at what location will I enter it? Or, in other words, at what edge and where on that edge will I exit the cell?

As a picture says a thousand words:

*I'll also place the broader context here to see if I'm going about this the right way. My idea is to voxelize the triangle with vertices t0,t1,t2 by first voxelizing the edge t0-t1 and then filling in the triangle by tracing multiple edges along the line t0-t1 towards t1-t2. This way I can create the shell of the mesh after which In can start filling it in*

# Answer
> 4 votes
lets rephrase it a bit

you have a point `p` and a direction `d`, find the smallest `t>0` such that `p+t*d` has one of its coordinates on a whole multiple of cell size in the same dimension.

then it is easy

take p.x and find how much you need to go in the x direction so that we are on a multiple of width `xstep = frac(p.x/w)*w`

then you find how many `d.x` you need to add take to get there, if d.x is negative then replace `xstep` with `w-xstep` and negate v.x then you do `tx = xstep/d.x`.

repeat for each of the axis and take the minimum of the `t`s

# Answer
> 2 votes
You can calculate the distance until the player crosses the next vertical line, and horizontal line. The smallest of the two will be the first to be crossed, so you will know the player will be in the next cell on the right, bottom, left or top.

As you can see on the following image there are two right triangle. You can know Y and X quite easily and if you have the direction you also know a.

```
Cos(a) = Y/diagonal_distance

```

The diagonal distance until the next horizontal line is `Y/cos(a)`, and until the next vertical line is `X/cos(pi/2 - a)`.

When d faces down right

```
if (Y/cos(a) > X/cos(pi/2 - a))
{
    //next cell is down
}
else
{
    //next cell is right
}

```

This is just to give you the idea. The calculus isn't exactly the same when d faces other direction. You should probably calculate the distance until the next horizontal line (if d faces up or down), the distance until the next vertical line (if d faces right or left) then compare the two values.

---
Tags: geometry, voxels
---


title: SFML fail to load image as texture

text:
# Question
Title: SFML fail to load image as texture
I have come to a problem with the code below ... Using SFML 2.0

```
#include <SFML/Graphics.hpp>

#include <iostream>
#include <list>

int main()
{
float speed = 5.0f;

// create the window
sf::RenderWindow window(sf::VideoMode(sf::VideoMode::getDesktopMode().height - 300, 800), "Bricks");

// Set game window position on the screen
window.setPosition( sf::Vector2i(sf::VideoMode::getDesktopMode().width/4 + sf::VideoMode::getDesktopMode().width/16 , 0) );

// Allow library to accept repeatitive key presses (i.e. holding key)
window.setKeyRepeatEnabled(true);

// Hide mouse cursor
//window.setMouseCursorVisible(false);

// Limit 30 frames per sec; the minimum for all games
window.setFramerateLimit(30);

sf::Texture texture;
if (!texture.loadFromFile("tile.png", sf::IntRect(0, 0, 125, 32)))
{
    std::cout<<"Could not load image\n";
    return -1;
}

// Empty list of sprites
std::list<sf::Sprite> spriteContainer;
bool gameFocus = true;

// run the program as long as the window is open
while (window.isOpen())
{
    sf::Vector2i mousePos = sf::Mouse::getPosition(window);

    // check all the window's events that were triggered since the last iteration of the loop
    sf::Event event;
    while (window.pollEvent(event))
    {
        float offsetX = 0.0f, offsetY = 0.0f;

        if(event.type == sf::Event::GainedFocus)
            gameFocus = !gameFocus;
        else if(event.type == sf::Event::LostFocus)
            gameFocus = !gameFocus;

        if(event.type == sf::Event::KeyPressed)
        {
            if (event.key.code == sf::Keyboard::Space)
            {
                if(gameFocus)
                {
                    // Create sprite and add features before putting it into container
                    sf::Sprite sprite(texture);
                    sprite.scale(.9f,.7f);
                    sf::Vector2u textSize = texture.getSize();

                    sprite.setPosition(sf::Vector2f(mousePos.x-textSize.x/2.0f, mousePos.y - textSize.y/2.0f));

                    spriteContainer.push_front(sprite);
                }
            }

            if(event.key.code == sf::Keyboard::P)
                std::cout << spriteContainer.size() << std::endl;

            if( event.key.code == sf::Keyboard::W )
                offsetY -= speed;

            if( event.key.code == sf::Keyboard::A )
                offsetX -= speed;

            if( event.key.code == sf::Keyboard::S )
                offsetY += speed;

            if( event.key.code == sf::Keyboard::D )
                offsetX += speed;
        }

        // "close requested" event: we close the window
        if (event.type == sf::Event::Closed || event.key.code == sf::Keyboard::Escape)
            window.close();

        // Move all sprites synchronously
        for (std::list<sf::Sprite>::iterator sprite = spriteContainer.begin(); sprite != spriteContainer.end(); ++sprite)
            sprite->move(offsetX, offsetY);

        //sprite.move(offsetX,offsetY);
    }

    // clear the window with black color
    window.clear(sf::Color::Black);

    // draw everything here...
    // window.draw(...);
    // Draw all sprites in the container
    for (std::list<sf::Sprite>::iterator sprite = spriteContainer.begin(); sprite != spriteContainer.end(); ++sprite)
            window.draw(*sprite);

    // end the current frame
    window.display();
}

return 0;
}

```

A couple weeks ago it worked flawlessly to my expectation, but now that I come back to it and I am having problems importing the image as a texture "tile.png". I don't understand why this is evening happening and the only message I get via the terminal is "Cannot load image ..." then a bunch of random characters. My libraries are for sure working, but now I am not sure why the image is not loading. My image is in the same directory as with my .h and .cpp files.

This is an irritating problem that keep coming up for some reason and is always a problem to fix it.

I import my libraries via my own directory "locals" which contain many APIs, but I specifically get SFML, and done appropriately as I am able to open a window and many other stuff.

# Answer
OpenGL does not like loading in textures that are not to the power of 2, some loaders add padding to make up to these numbers, but you cannot account for all libraries you use to achieve this. Try scaling the image to 512x512 as opposed to 510x510 and change 125 to 128, usually the texture will load in this instance in graphics libraries and you will experience tearing and distortion across the surface of the model, as it moves in relation to the view port.

To ensure completely that your project is finding the specified file, type the absolute path destination, instead of just the file name. This will eliminate any possibility that the project is unable to find the file.
> 1 votes

# Answer
From the documentation of sf::Texture:

"Like sf::Image, sf::Texture can handle a unique internal representation of pixels, which is RGBA 32 bits. This means that a pixel must be composed of 8 bits red, green, blue and alpha channels – just like a sf::Color."

I think SFML forces RGBA pixels, because this way, it doesn't have to care about 4 byte aligment when uploading to OpenGL, and also working with data aligned to 4 bytes is usually faster despite the memory overhead.

Your image doesn't have an alpha channel, and probably this is the source of the error.
> 0 votes

---
Tags: sfml, loading, importing
---


# Question
Title: Setting uniform value of a vertex shader for different sprites in a SpriteBatch
I'm using libGDX and currently have a simple shader that does a passthrough, except for randomly shifting the vertex positions. This shift is a vec2 uniform that I set within my code's render() loop. It's declared in my vertex shader as `uniform vec2 u_random`.

I have two different kind of Sprites -- let's called them SpriteA and SpriteB. Both are drawn within the same SpriteBatch's begin()/end() calls. Prior to drawing each sprite in my scene, I check the type of the sprite.

* If sprite instance of **SpriteA**: I set the uniform `u_random` value to `Vector2.Zero`, meaning that I don't want any vertex changes for it.
* If sprite instance of **SpriteB**, I set the uniform `u_random` to `Vector2(MathUtils.random(), MathUtils.random()`.

The expected behavior was that all the SpriteA objects in my scene won't experience any jittering, while all SpriteB objects would be jittering about their positions.

However, what I'm experiencing is that both SpriteA and SpriteB are jittering, leading me to believe that the `u_random` uniform is not actually being set per Sprite, and being applied to all sprites. What is the reason for this? And how can I fix this such that the vertex shader correctly accepts the uniform value set to affect each sprite individually?

**passthrough.vsh**

```
attribute vec4 a_color;
attribute vec3 a_position;
attribute vec2 a_texCoord0;

uniform mat4 u_projTrans;
uniform vec2 u_random;

varying vec4 v_color;
varying vec2 v_texCoord;

void main() {

    v_color = a_color;
    v_texCoord = a_texCoord0;

    vec3 temp_position = vec3( a_position.x + u_random.x, a_position.y + u_random.y, a_position.z);

    gl_Position = u_projTrans * vec4(temp_position, 1.0);

}

```

**Java Code**

```
this.batch.begin();
this.batch.setShader(shader);

for (Sprite sprite : sprites)
{
    Vector2 v = Vector2.Zero;
    if (sprite instanceof SpriteB)
    {
        v.x = MathUtils.random(-1, 1);
        v.y = MathUtils.random(-1, 1);
    }

    shader.setUniformf("u_random", v);

    sprite.draw(this.batch);
}

this.batch.end();

```

# Answer
> 2 votes
i think you first have to call it like this:

```
shader.begin();
shader.setUniformf("u_random", v);
shader.end();

```

because otherwise the uniform wont be set each time.

---
Tags: libgdx, glsl, spritebatch
---


# Question
Title: How do I make a sprite move to another position using vectors
Ok, so far I have made the sprite move to a mouse position. But I got a question, does anyone know how to make a sprite move by itself without the use of a mouseclick from Point a to point b using vectors? In which then the sprite stops after reaching point B.

```
def calcMoveVector(self):
    movetopos = self.posto
    currentpos = self.rect.center
    directtoX = movetopos[0]-currentpos[0]
    directtoY = movetopos[1]-currentpos[1]

    vect = pygame.math.Vector2(10, 10)
    if vect.length() > 0: self.vector = vect.normalize()
    return vect

    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            sys.exit()

        if event.type==pygame.MOUSEBUTTONDOWN:
            mpos = pygame.mouse.get_pos()
            r = pygame.rect.Rect(mpos[0],mpos[1],10,10)
            buttons=pygame.mouse.get_pressed()

            if buttons[0]==True:
                c = pygame.color.THECOLORS["green2"]
                pygame.draw.rect(screen,c,r)
                monster.posto = mpos
                monster.state = Monster.MOVETO
                monster.speed=3

```

# Answer
> 1 votes
You have a function which operates on `self.posto`. So the relevant code is in how you set that property. The code you included ~~should work just fine~~ is broken, but you simply give it a different destination.

And as you might expect, you have literally infinite options for how you set that destination vector.

**Edit:**

The code you posted won't work. You go through the effort of calculating the direction, but for some reason you stop using it halfway through your function. It should read:

```
vect = pygame.math.Vector2(directtoX, directtoY)

```

Or, since the docs say `pygame.math.Vector2` supports "numerical operations" (python-speak for operator overloading?), you could condense the previous two lines, as well:

```
movetopos = self.posto
currentpos = self.rect.center
vect = movetopos - currentpos  // also a vector, via subtraction

```

---
Tags: sprites, vector, python, pygame
---


title: What's it like being a game developer?

text:
# Question
Title: What's it like being a game developer?
I am a 6th grade student and I would like to be a video game designer. In class, we all had to choose a career that we would like to have and interview someone with that career. Finding a game designer locally has been difficult, so I thought I would try online. If some of you would take the time to answer these questions I would be grateful. Some of the questions I have for you are:

Why did you choose your career?

What kind of education did you have to complete for this career?

How is math related in this career?

What would a day in your normal life in this career typically look like?

How do you dress for this career?

What is your favorite part about this career?

What kind of games do you create?

You do not have to answer all of the questions but it would be much appreciated if you would answer most of them. Thanks!

# Answer
One thing to watch out for: it's common to use "game design" and "game development" interchangeably, but design is just one skill in an ensemble. Here's what I can say about being a game designer, but note that there are many more ways to take part in game development, and many more roles to fill.

**Why did you choose your career?**

I love solving problems - especially ones that demand a mix of creative thinking and more technical figuring.

**What kind of education did you have to complete for this career?**

I studied industrial design, which is about designing products for mass consumption (like toothbrushes, cars, etc.) My school focused on user-centered design, which involves thinking about how the person using the product (your player) thinks/feels/wants, and using that to guide design decisions.

Other game designers I know have studied architecture, economics, psychology, education, language, etc. Some designers I know got into games straight out of secondary school. So there's no hard requirements.

A few programs are available now specifically tailored to game design and game development — I now teach in a Bachelor of Game Design program at Sheridan College — but they're not the only way in.

**How is math related in this career?**

As a game designer, one of the main jobs is defining and tuning the rules for how the game acts. How fast can the player move, how often does this item show up, etc.

Math is a great way to specify those rules concretely, so the computer can execute them exactly as you intend. It's also helpful for predicting what those rules will do - extrapolating out to the extreme cases that are hard to test directly, like "how long will this boss battle take with 60 players fighting at once?"

Once you have a mathematical model for part of a game, you can play with the numbers to find the right balance, so that the game never becomes too easy or too hard, so players are properly rewarded and can progress at a comfortable pace, and so multiplayer remains fair.

**What would a day in your normal life in this career typically look like?**

My days are pretty weird, and I like them that way. Unlike other jobs where I might have a standard routine, in game design I'll bounce between playing & researching games to get a baseline, meeting with colleagues across the studio to get their input, making and giving presentations to the team about new feature proposals, drawing mock-ups and programming prototypes, documenting & diagramming approved features, crunching numbers in a spreadsheet to balance the scoring and store prices, playtesting to ensure features are working right and identify bugs, and a dozen other tasks.

**How do you dress for this career?**

Usually jeans and a T-shirt or dress shirt. Most game studios I've been to have fairly easygoing dress codes.

**What is your favorite part about this career?**

The variety. There are many jobs where 90% of the problems you deal with each day have been solved long before, and it's just a matter of following the steps. Game development isn't often like that. We're usually trying to do at least one thing we've never done before, maybe something that nobody has done before, so we need to come up with our own new solutions. It's terrifying and exhilarating and often fails, but I love the striving.

**What kind of games do you create?**

So far my portfolio is mostly 3rd-person action games, but like many designers I'm not tied to any one kind of game. I'd love to work on a 2D puzzler or a sprawling RPG or RTS or anything else that comes my way. :)

---

You might also like to check out Game School Prep, a blog about studying to enter game development. It's run by a producer at my studio, and it's just getting started, but it's already got some excellent info.
> 2 votes

---
Tags: game-design
---


# Question
Title: Why isn't this physics code scaling velocities separately?
I'm working my way through this book and I'm trying to work this code out:

```
var squaredVelocity = this.velocity.x*this.velocity.x
                    + this.velocity.z*this.velocity.z;

if (squaredVelocity > Player.SPEED*Player.SPEED) {
   var scalar = Player.SPEED / Math.sqrt(squaredVelocity);
   this.velocity.x *= scalar;
   this.velocity.z *= scalar;
}

```

The book doesn't explain it. I've been staring at it for an hour. I can see exactly what it does (in the technical sense), but what's its *purpose*?

I understand bits: The `scalar` variable is always a fraction, so multiplying the velocity by it scales back that velocity.

Is this code for limiting speed? Then why are the x and y velocities added together? Shouldn't the X and Y be scaled independently?

---

Do I need to know this stuff for a career in video games? I understand that all this math is educational, but will I still have to do this sort of thing in an engine like Physijs?

# Answer
> 18 votes
The reason for this is Pythagorean Theorem, and it's probably the bit of math I use most often in games. Even when working with a full-featured engine, there are times when knowing this math has helped me get the gameplay and look I wanted.

Don't worry though, it's very simple once you've used it a few times. :)

What this bit of code does is ensure that the player's velocity (`this.velocity`) doesn't exceed a defined maximum speed (`Player.SPEED`)

To do this, it's not enough to check the x and z components separately. If both x and z were equal to `Player.SPEED`, then looking at each component it would appear that we're within our speed limit. But something that's moving at `Player.SPEED` forward AND right must be going faster than `Player.SPEED` in total. We need a way to calculate the combined effect in these two axes.

If we picture the velocity as an arrow in space (pointing from where the object is now to where it will be in one unit of time), the speed per unit of time is the length of this arrow.

When you break the arrow into its x and z components, you find that they make a triangle - a right angled triangle, since the x and z axes are perpendicular to each other. That means we can use Pythagorean Theorem to find the length of the diagonal, the hypotenuse of the triangle.

\\$\begin{align} {total\\,speed}^2 &= velocity.x^2 + velocity.z^2 \\ {total\\,speed} &= \sqrt{velocity.x^2 + velocity.z^2} \end{align}\\$

That's this line:

```
var squaredVelocity = this.velocity.x*this.velocity.x + this.velocity.z*this.velocity.z;

```

Why should this math work? My favourite proof is just this image:

$$\LARGE{a^2+b^2=c^2}$$

The big squares to the left & right have the same side length \\$(a + b)\\$, so they must have equal area. The purple areas inside are all composed of the same four right triangles, with identical side lengths a & b, so the purple parts of the left & right squares must also have equal area. That means what's left must also be equal: the white area on the left \\$(a^2 + b^2)\\$ must equal the white area on the right (\\$c^2\\$, the square whose side length is the hypotenuse of the purple triangles).

That leaves one detail: why is this code written with so many squares, instead of just taking the square root in the first line?

That's because of the way computer processors work. They can add and multiply numbers with blinding speed, but division and square roots take significantly longer. On today's hardware you'd only notice the difference if you were doing many millions of computations, but in the old days it was a big deal, and it can still add up in performance-critical code like physics & rendering systems, which crunch gobs of numbers every frame.

So gamedevs have developed a bunch of tricks to avoid these costlier operations, or at least hold off on them until they're absolutely necessary. One is working with squares:

```
if (squaredVelocity > Player.SPEED*Player.SPEED)

```

Comparing the square of the velocity vector's length vs the square of the max speed will always give the same result as comparing the unsquared versions (since neither one is allowed to be negative by definition). If the velocity is below the max speed then we can safely skip ahead, never having to compute the square root.

If the velocity is too great, then we need to scale the vector down. Dividing each component by its current length would uniformly scale it down to a length of one (called a "unit vector"). Multiplying a unit vector by the `Player.SPEED` then scales it up uniformly to have a length equal to `Player.SPEED`. This code combines these two scale operations into one scale factor, and applies it to each component:

```
var scalar = Player.SPEED / Math.sqrt(squaredVelocity);
this.velocity.x *= scalar;
this.velocity.z *= scalar;

```

At the end of this code, we can be sure that this.velocity has length less than or equal to `Player.SPEED`.

One last note: Unless you're writing engine code, you can probably get away with using square roots wherever you want. Looking at other devs' code, you'll find we're often using these tricks out of habit, even if it's a script that only runs once per frame, or where we're memory- not cpu-bound - and it looks like that might be the case in this example. Pythagorean Theorem is definitely worth knowing, but the particular form of this example isn't something you need to duplicate exactly. Just write code that's clear to you.

# Answer
> 3 votes
The length of a vector **x, y** is **sqrt(x^2+y^2)**.

That's basically the gist of that whole snippet. If you properly define vector operations and a "length" method for them it would look like this:

```
// Set the velocity of the object to the maximum if it is above the maximum
if (velocity.length() > Player.SPEED)
  velocity = velocity  / velocity.length() * Player.SPEED;

```

Dividing a vector by it's length is called "normalization". Normalizing a vector gives you a so called "unit" or "direction" vector that points into the same direction but whose length is exactly 1.

So for example 17, 0 normalized is 1, 0. And 0, 5.32 normalized would be 0, 1. And 4, 4 normalized would be 1/sqrt(2), 1/sqrt(2) e.g. 0.703, 0.703. Since the length is 1 you can just multiply it with any scalar to get a vector of that length.

So even more simplified it would be:

```
if (velocity.length() > Player.SPEED)
  velocity = velocity.normalized() * Player.SPEED;

```

---
Tags: mathematics, physics, vector
---


# Question
Title: Can I use clipping with Unity Sprite in NGUI?
I used NGUI free version (2.7) with Unity 4.3. I have tried to use clipping to restrict the area of viewer by using clipping to hide some content of Unity Sprite. However, it did not work. If it's NGUI own sprite, it worked. Is there a way to use clipping with Unity Sprite? I have done some asset with animation with unity sprite (2D) but it cannot be clipped.

# Answer
> 1 votes
As far as I know, Unity sprites supports became available with new NGUI versions (3.x). Previous NGUI was developed before `Unity 4.3` with 2D features was available, and old NGUI is not under development for a quite long time.

So, you can either move to new NGUI, or go into shaders code and make use of `UIPanel` alpha values. Maybe you could have a luck and by setting some NGUI shaders for Unity2D sprites you will achieve the same without spending any time on improving your shaders? That should be a good start.

---
Tags: unity, sprites, clipping, ngui
---


title: ArrayList of Entites Random Movement

text:
# Question
Title: ArrayList of Entites Random Movement
I have an arraylist of entites that I want to move randomly. No matter what I do, they won't move. Here is my female class:

```
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.util.Random;

import javax.swing.ImageIcon;

public class Female extends Entity {
static int femaleX = 0;
static int femaleY = 0;
double walkSpeed = .1f;
Random rand = new Random();
int random;
int dir;

Player player;

public Female(int posX, int posY) {
    super(posX, posY);

}

public void update() {
    posX += femaleX;
    posY += femaleY;

}

public void draw(Graphics2D g2d) {
    g2d.drawImage(getFemaleImg(), posX, posY, null);
    if (Player.showBounds == true) {
        g2d.draw(getBounds());
    }
}

public Image getFemaleImg() {
    ImageIcon ic = new ImageIcon("res/female.png");
    return ic.getImage();
}

public Rectangle getBounds() {
    return new Rectangle(posX, posY, getFemaleImg().getHeight(null),
            getFemaleImg().getWidth(null));
}

public void moveFemale() {
    random = rand.nextInt(3);
    System.out.println(random);

    if (random == 0) {
        dir = 0;
        posX -= (int) walkSpeed;
    }
}

}

```

And here is how I update the female class in the main class:

```
public void actionPerformed(ActionEvent ae) {
    player.update();

    for(int i = 0; i < females.size(); i++){
        Female tempFemale = females.get(i);
        tempFemale.update();
    }
    repaint();
}

```

If I do something like this(in the female update method):

```
public void update() {
    posX += femaleX;
    posY += femaleY;

    posX -= walkSpeed;

}

```

The characters move with no problem. Why is this?

# Answer
Because (prior to your fix) that's exactly what you've asked it to do. Nowhere do I see `femaleX` or `femaleY` being updated; thus, they remain zero, and thus you add zero to the current position, so nothing moves.

I think you are not clear on what your code is supposed to be doing, here is how this is always meant to be approached:

```
//acceleration
float ax = 0;
float ay = 0;
//speed
float sx = 0;
float sy = 0;
//displacment AKA position
float x = 0;
float y = 0;

...

void update(...)
{
    //after all input and AI, etc. etc., finalise your physics
    //using the basic Equations of Motion a la Isaac Newton:
    //new velocity is old velocity plus current acceleration (usually derived from inputs)
    sx += ax;
    sy += ay;
    //new position is old position plus current speed
    x += sx;
    y += sy;
}

```

Whereas in your code, it almost seems as if you are saying position = position + someOtherPosition, which cannot really work. Speed (or as a vector, velocity) is the diff you apply to displacement, just as acceleration is the diff you apply to speed.

PS. Using acceleration is completely up to you -- you can just set velocities in your input handler code if you like. Many games do not need acceleration.
> 1 votes

# Answer
You cast `walkSpeed` to an int before adding it to the position in `moveFemale()`, its value will be 0 so nothing changes.
> 0 votes

# Answer
You have to call `moveFemale();` in the `update`-method.
> -2 votes

---
Tags: java
---


# Question
Title: Why are my 2D world click-positions offset after camera movement?
I'm writing a 2D game engine. I need to add a camera to my world that can zoom in and out as well as move away from its initial position at `(0,0)` at the center of the world.

The main issue can be seen in this video. When the camera hasn't yet moved (still at `0,0`), I can click anywhere in the visible world and the click is mapped to the correct world position. I can even zoom and everything including the mouse position is scaled correctly. However, the moment I move the camera, the position becomes offset by a percentage of the camera movement. (This is clearer in the video.)

I have tried calculating the draw position and world mouse position in many different ways, but I always get the same issue.

What might be wrong?

Here's the code for both *object position to screen position* and *mouse position to world position conversion*:

```
public Vector2 GetDrawCoord(Vector2 position)
{
    return new Vector2(((position.X - cameraCenter.X)) * zoom + graphics.Viewport.Width / 2,
        graphics.Viewport.Height - ((position.Y - cameraCenter.Y) * zoom + graphics.Viewport.Height / 2));
}

public Vector2 GetClickCoord(Vector2 position)
{
    return new Vector2((position.X - graphics.Viewport.Width / 2 + cameraCenter.X) / zoom,
        (graphics.Viewport.Height / 2 - position.Y + cameraCenter.Y) / zoom);
}

```

Update:

New code:

```
Vector3 vec = graphics.Viewport.Unproject(new Vector3(position.X, position.Y, 0f),
            Matrix.CreateOrthographic((float)graphics.Viewport.Width, (float)graphics.Viewport.Height, 0f, 0f),
            cameraMatrix,
            Matrix.Identity);

```

# Answer
You can use Viewport.Unproject method exactly for this.

* For the **source** which is a vector3 you should specify your screenspace position into the xy members. The z member of the vector corresponds to the view frustum near and far planes. 0 means you are on the near plane, 1 means that you are on the far plane and in between means you are between by that value.
* The **projection** matrix should be an orthographics matrix if you are doing a 2D game. You can create an ortho projection by calling Matrix.CreateOrthographic and specifying your screen dimensions and some near-far frustum values which could be irrelevant in a 2D game.
* The **view** matrix is your camera transformation matrix.
* The **world** matrix is a world transform matrix. It should be Matrix.Identity if you are not transforming you world.
> 1 votes

---
Tags: xna, c#, camera, coordinates
---


title: How to load a DDS file with mipmaps

text:
# Question
Title: How to load a DDS file with mipmaps
I believe there's a `D3DX` function that can load a `DDS` file with mipmaps but `D3DX` is deprecated. Any function/library that can load it and that's not deprecated? I need it for `DirectX` if it makes any difference.

# Answer
There is DirectXTex which has a lightweight DDS loader which can load mipmaps for you. You can integrate it very easily (just include some headers in your project and that's it) and call `CreateDDSTextureFromFile` function to load a texture from disk. There is an even more robust loader one which I haven't tried yet.
> 1 votes

---
Tags: directx, loading, mipmaps, dds
---


# Question
Title: How to launch a prefab at the mouse position
I want to use `Instantiate(item, new Vector3(...), Quaternion.identity)` to land an item at the position that was clicked. My game is using a third-person view (example).

This is the code that I think I should be using:

```
if(Input.GetKeyDown(KeyCode.Mouse0) && cur_items > 0){
    Instantiate(item, object_pos, Quaternion.identity);
    cur_items--;
}

mouse_pos = Input.mousePosition;
object_pos = Camera.main.WorldToScreenPoint(mouse_pos);

```

What am I doing wrong?

# Answer
> 3 votes
First of all you need to determine how would you determine z-axis. If you want the z to be constant, just change the position after instantiating or while instantiating. Another way would be to casting a ray from camera, and instantiating the object at ray hit position. Something like below -

```
if(Input.GetMouseDown(0)){
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RayCastHit hit;
    if (Physics.Raycast(ray, out hit, 100)) {
        Instantiate(item, hit.point, Quaternion.identity);
    }
}

```

JS Version(untested)

```
if(Input.GetMouseDown(0)){
    var ray:Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    var hit:RayCastHit;
    if (Physics.Raycast(ray, hit, 100)) {
        Instantiate(item, hit.point, Quaternion.identity);
    }
}

```

PS: LVBen got a point that using `hit.transform.position` will give weird results. It's upto you if you want to use it or not. `hit.point` will be the better option anyways.

# Answer
> 3 votes
It should be Camera.main.ScreenToWorldPoint(mouse\_pos); and it should come before instantiating the object

# Answer
> 0 votes
You could use a Ray. This is how I am doing it on my current project:

```
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit rayHit;
if (Physics.Raycast(ray, out rayHit))
{
    // ... instantiate object here
    newObject.transform.position = rayHit.point;
}

```

That will instantiate an object at the point where the ray collides with an object. All of my meshes have the origin at the bottom, so my new objects will appear exactly on top of whichever object is beneath the mouse.

---
Tags: unity, javascript
---


# Question
Title: Textures have lines between them when zoomed out
These are two screenshots from my new game, a top-down RTS with tiles. The first one is from a normal view with no zoom, the second one is a zoomed out view of the whole map:

In the first image, the tiles are rendered perfectly. However, when I zoom out, some of the tiles are rendered with lines in between them, while others clump into larger groups with their own lines. Here is the code that draws the tiles:

```
            Rectangle rect;

            if ((int)(32 * gameInfo.Game.ZoomFactor) > 0)
            { rect = new Rectangle(0, 0, (int)(32 * gameInfo.Game.ZoomFactor), (int)(32 * gameInfo.Game.ZoomFactor)); }
            else
            { rect = new Rectangle(0, 0, 1, 1); }

            Texture2D buffer = new Texture2D(this.GraphicsDevice, rect.Width, rect.Height);

            for (int x = 0; x < gameInfo.Game.TileMap.GetLength(0); x++)
            {
                for (int y = 0; y < gameInfo.Game.TileMap.GetLength(1); y++)
                {
                    rect.X = (int)(gameInfo.Game.ZoomFactor * ((x * 32) - gameInfo.Game.ViewOffset.X));
                    rect.Y = (int)(gameInfo.Game.ZoomFactor * ((y * 32) - gameInfo.Game.ViewOffset.Y));
                    buffer = EnvironmentTextures.ENTileTextures[gameInfo.Game.TileMap[x, y].TileType];
                    spriteBatch.Draw(buffer, rect, Color.White);
                }
            }

```

The `gameInfo.Game.ZoomFactor` is a `Single` which is modified when the scroll wheel is changed, in increments of `0.2f`. Has anyone had this problem before, and how can I fix it?

# Answer
> 3 votes
The gaps are caused when you are truncating the `rect` width and height. Instead of:

```
rect = new Rectangle(0, 0, (int)(32 * gameInfo.Game.ZoomFactor), (int)(32 * gameInfo.Game.ZoomFactor));

```

You should use:

```
rect = new Rectangle(0, 0, (int)((32 * gameInfo.Game.ZoomFactor) + 0.5), (int)((32 * gameInfo.Game.ZoomFactor) + 0.5));

```

This should ensure that the width and height of the tiles will be sufficient to cover the canvas and you'll eliminate the gaps.

---
Tags: xna, c#, tiles
---