title: Impulsioned jumping

text:
# Question
Title: Impulsioned jumping
There's one thing that has been puzzling me, and that is how to implement a 'faux-impulsed' jump in a platformer. If you don't know what I'm talking about, then think of the jumps of Mario, Kirby, and Quote from Cave Story. What do they have in common? Well, the height of your jump is determined by how long you keep the jump button pressed.

Knowing that these character's 'impulses' are built not before their jump, as in actual physics, but rather *while in mid-air* \- that is, you can very well lift your finger midway of the max height and it will stop, even if with desacceleration between it and the full stop; which is why you can simply tap for a hop and hold it for a long jump -, I am mesmerized by how they keep their trajetories as arcs.

My current implementation works as following:

While the jump button is pressed, gravity is turned off and the avatar's Y coordenate is decremented by the constant value of the gravity. For example, if things fall at Z units per tick, it will rise Z units per tick.

Once the button is released or the limit is reached, the avatar desaccelerates in an amount that would make it cover X units until its speed reaches 0; once it does, it accelerates up until its speed matches gravity - sticking to the example, I could say it accelerates from 0 to Z units/tick while still covering X units.

This implementation, however, makes jumps too diagonal, and unless the avatar's speed is faster than the gravity, which would make it way too fast in my current project (it moves at about 4 pixels per tick and gravity is 10 pixels per tick, at a framerate of 40FPS), it also makes it more vertical than horizontal. Those familiar with platformers would notice that the character's arc'd jump almost always allows them to jump further even if they aren't as fast as the game's gravity, and when it doesn't, if not played right, would prove itself to be very counter-intuitive. I know this because I could attest that my implementation is very annoying.

Has anyone ever attempted at similar mechanics, and maybe even succeeded? I'd like to know what's behind this kind of platformer jumping. If you haven't ever had any experience with this beforehand and want to give it a go, then please, don't try to correct or enhance my explained implementation, unless I was on the right way - try to make up your solution from scratch. I don't care if you use gravity, physics or whatnot, as long as it shows how these pseudo-impulses work, it does the job.

Also, I'd like its presentation to avoid a language-specific coding; like, sharing us a C++ example, or Delphi... As much as I'm using the XNA framework for my project and wouldn't mind C# stuff, I don't have much patience to read other's code, and I'm certain game developers of other languages would be interested in what we achieve here, so don't mind sticking to pseudo-code.

Thank you beforehand.

# Answer
I think your main problem lies here:

> While the jump button is pressed, gravity is turned off and the avatar's Y coordenate is decremented by the constant value of the gravity. For example, if things fall at Z units per tick, it will rise Z units per tick.

Gravity doesn't work like that. Google "uniformly accelerated motion" for the details, but in simple terms, as another fellow member said, gravity is an acceleration, not a velocity.

To put it simply, while velocity is the constant rate of change of *position* over time, acceleration is the constant rate of change of *velocity* over time.

So your first order of business would be to change your falling algorithm to include acceleration, not just velocity. Instead of:

```
pos_y = pos_y + (velocity_y * time_difference)

```

you would have to do something like

```
pos_y = pos_y + (velocity_y * time_difference) + (gravity_y * (time_difference ^ 2) / 2)
velocity_y = velocity_y + (acceleration_y * time_difference)

```

That way everything will fall in a parabola, which is the physically correct motion.

Now, to implement simple jumping (we'll get to your exact question right after this), you simply set `velocity_y` to a desired value. As long as the sign for `acceleration_y` and your desired `velocity_y` are different, your object will jump correctly (In other terms, you don't "turn off gravity". You keep it on, and simply set the object's velocity to some predefined value).

You will notice that the greater `velocity_y` is when you start jumping, the higher the jump will be. So to implement your desired effect, you add some kind of acceleration to the jump (in physical terms, this means adding a force. Think of adding a small rocket to the object).

To do this, you do the same thing as before, but now the acceleration and velocity should have the same sign. You do this while the button is pressed:

```
pos_y = pos_y + (velocity_y * time_difference) + (force_y * (time_difference ^ 2) / 2)
velocity_y = velocity_y + (force_y * time_difference)

```
> 8 votes

# Answer
The solution is not to delay deceleration. When you throw a ball up in the air, it isn't moving at a constant speed until it reaches its maximum height, but decelerates from the moment of impulse.

Gravity is not a velocity, but an acceleration. So if a player has a speed upwards of 20 units, and gravity is -10 units, on the next tick, the speed upward would be 10 units, on the next, 0 units, etc.

The reason why your jumps are seeming so diagonal is because your player's speed up and down is constant. So if you literally draw a line following the path of the player, you will see a line with the slope, positive or negative, of your gravity value over the change in the x position.

For your player to control the height of your jump, your player should be given some initial velocity on impulse, gravity should be turned off, and a special gravity value (less than regular gravity) should be applied to the player's velocity. Once the jump button is released or the player velocity reaches 0, normal gravity should be applied.

This way, the player will see a nice curve during their jump, whether they are decelerating by regular gravity or not.
> 4 votes

# Answer
Short story is: you're going to have a non-parabolic section in your jump arc somewhere.

I tried a few approaches when implementing jumping:

* Constant climb: This appears to be, in effect, what you were trying: having the positive vertical velocity fixed until the button is released, at which point normal gravity kicks in. The arc is diagonal on the ascent, but normal on the fall - this actually normally looks OK, and (more importantly) feels OK, as it's quite easy to judge the height of the jump well.
* Arrested climb: This is where you start the character off ascending at the parabola of maximum height, applying an initial impulse. Then, when the button is released, you set the vertical velocity to zero (or a small upwards velocity). This means your biggest jumps are a guaranteed parabola, and smaller jumps feel more like you're doing a big jump then slowing down.
* Variable initial impulse: This is the one I ended up opting for: pressing jump would apply an initial upward impulse sufficient for a hop, and then continue applying upward acceleration (much greater than gravity) over a short period - the jump window - until the button was released. Once the jump window closed, the motion would then be parabolic, and the period of variable initial impulse was short enough that it didn't look odd, but was long enough to give an experienced player enough scope to control jump height. The downside was it wasn't as easy to judge jump height, as the window was much smaller and didn't have the correspondence of release moment to height. As it happened most of the time you either wanted a tap or a full jump anyway, so that wasn't such an issue.

Try these and see which feels best.
> 2 votes

---
Tags: physics, platformer, jumping
---


# Question
Title: Good way of handling class instances in game development?
I'm a new indie game developer, and I've made a few games, but often times when coding I wonder "Is this the way most people do it? Am I doing it wrong?" because I'd like to become a game developer some day, and I really want to get rid of bad practices in time.

The way I'm doing it right now is like this:

```
#include <some libraries>
#include "Some classes"

    int main()
    {
      Class1 a;
      Class2 b;
      Class3 c;

      a.init();
      b.init();
      c.init();

      // game logic;
    }

```

Now as I see the game grow, I have more and more classes to initialize and create instances of. This is clean but I'm not sure if this is standard practice. Is this a regular way of creating instances of your game classes or is there a cleaner and more efficient way to do it?

# Answer
> 5 votes
Correct me if I'm wrong, but what I'm getting from the question is that you're declaring each object within the game world as a new variable. Generally when a game grows it will move away from the code and towards outside files for level creation etc. Once this happens you can't continue creating new instances of classes within the game itself.

The best way (that I've found) to manage a lot of this stuff is to use Lists. Abstract classes (as mentioned in Mihai's answer) also tend to come in handy when doing this. If you're going to have 50 enemies in a level it's a lot more viable to say "Update all enemies" or "For each enemy..." than to write exhaustive lines in that way.

In your example you could have Class1, Class2, Class3 be subclasses of GameObject, then have something like this:

```
List<GameObject> objects = new List<GameObject>();
objects.add(new Class1());
objects.add(new Class2());
objects.add(new Class3());

for(GameObject o in objects){
  o.init();
}

// game logic;

```

I don't often use C/C++ so you may have to look into how lists work in the language you're using.

# Answer
> 1 votes
The Best practice is to keep things as SIMPLE as possible . so if this is enough for you it's ok .

But when will make a bigger game with hundreds or thounds of objects this will no longer be manageable.

So what you will do is create a GameObject class and then derive other classes from it with different functionality . You will put all these instances in an array of GameObjects like this

```
std::vector<GameObjects*> m_objects;

```

Then you will have a GameLevel class which will manage your objects

In a GameLevel::Init methods you will iterate over your objects and init them then you will do the same with your Update and Render methods

Then after many years and many games ship your hierachy will become very deep You will have derived many objects from from many other objects everything will be tightly coupled and all your code will be Spaghetti Code

And then you will look into Component Systems and you will check out this https://stackoverflow.com/questions/1901251/component-based-game-engine-design and this Component-based game object systems in practice

# Answer
> 0 votes
I'm not 100% sure what your asking, is it the having to call the init method or something else? Your class constructor should do most of your init logic, unless you need to the object constructed before calling init, though this only happens in a few situations. So if you just left it as

```
Class1 a;

```

That would call the default constructor for your class. So place all the logic for your init function in there.

**EDIT**

Generally your main will have maybe an instance of GameWorld class which lets say manages all the entities in the world. It may also have an instance of level and inside level we have instances of blocks that make up the level or something like that.

The main point there, is that we tend to have composite classes which are made of smaller classes to make up more complex classes.

# Answer
> 0 votes
It really boils down to what these classes represent.

If these classes represent systems of your game such as Rendering or Sound, you can easily get by with this type of initialization structure. Even as you start adding systems to your game like networking, it's acceptable to simply leave these as member variables of a framework-like class because you often need to refer to these systems directly to use their exposed interface API and placing them into a list only adds unnecessary complexity. Nothing would stop you from having them derive from a common ISystem class though and keeping them in a list, but having specific references would minimize that list's lookup time when they were needed at the cost of a few bytes of memory.

If these classes represent game objects, or what I call entities, then generally there is a core system that is responsible for managing these instances. You simply ask this system to create you an instance, it wires it up and manages the memory and simply hands you back a reference to work with. For example:

```
// Game Object System Interface
struct IGameObjectSystem {
  // Create game object with a specified name
  GameObject* Create(const std::string& name="");
  // Create game object based on a template type with a given name
  GameObject* Create(unsigned int templateTypeId, const std::string& name="");
  // Create game object with given parameter list
  GameObject* Create(ParameterList& params);
  // Deallocates a game object
  void Destroy(GameObject* object);
};

class GameObjectSystem : public IGameObjectSystem {
public:
  /* implement the IGameObjectSystem here */
private:
  std::vector<GameObject*> mObjects; // list of objects in use
  static unsigned int mNextObjectId; // next object id to assign
};

```

The benefit is that now you can create as many game objects as you want. You could go as far as creating Factory classes for all the various types of game objects in your game and then this object system can use those factories to create a specific type of game object. You've centralized the creation/destruction of game objects and abstracted away storing them in a list too.

But keep in mind this is only one way to manage Game Objects.

As Mihai points out, Component-based design often has varying designs around game objects. Some prefer to have a GameObject class like the above examples which has a collection of components that make up it's feature-set while other implementations prefer to treat game objects as simple unsigned int values that reference specific indexes in a well designed system of arrays to quick, constant time lookups and retrieval.

The great part of all this is there is no real "right" way that works. There are some best practices but even those are going to vary from implementation to implementation all depending upon the framework being used - is it built in-house or licensed, etc. But don't be afraid to go with what works for now and improve upon it later as you get a better idea of how things all come together.

---
Tags: software-engineering
---


# Question
Title: Using XNA for a 2D isometric game, but wanna move on
I've been building a 2D isometric game (with learning purposes) in C# using XNA.

I found it's really easy to manage sprite sheets loading, collision, basic physics and such with the XNA api.

The thing is, I want to move on.

My real goal is to learn C++ and develop a game using that language.

What engine/library would you guys recommend for me to keep going on that same 2D isometric game direction using pretty much sprite sheets for the graphical part of the game?

# Answer
> 3 votes
SDL, It´s realy realy efficent! i mean, unbelivable efficent. You get to concentrate at c++ if thats what you want, or to build up a nice 2d framework without having to spend lots of time with the most advance aspects of c++ programming. instead of going with directX or OGL and having to bother with all of their optmization stuff and general knowledge SDL is a perfect way to go in my opinion.

You can from there move on to rather more "advaced" topics without so much headache.

---
Tags: xna, c++, c#
---


# Question
Title: 2D engine for both Android & iOS engine?
I want to make a simple 2d game that would run on both Android and iPhone. Since coding it separately for each platform would take some time, I thought of using an engine, that would be able to port to both platforms.

I wanted to ask, what engine would you recommend, as there are lots of them, like Corona, Marmalade, etc.

Thanks )

# Answer
> 1 votes
My suggestion is Game Maker Studio, depending on your 'simple' keyword.

# Answer
> 1 votes
http://impactjs.com/ would be a nice choice since HTML5 works for both platforms and it's pretty easy to develop there. A free option would be http://www.limejs.com/

# Answer
> 1 votes
Cocos2d can be a good choice !

It recently add HTML5 feature !

It's open-source and free and have a good community and wiki and many tutorial !

Check here for more info.

---
Tags: android, ios, html5
---


title: Writing to XML issue Unity3D C#

text:
# Question
Title: Writing to XML issue Unity3D C#
I'm trying to create a tool using Unity to generate an XML file for use in another project. Now, please, before someone suggests I do it in something, the reason I am using Unity is that it allows me to easily port this to an iPad or other device with next to no extra development. So please. Don't suggest to use something else.

At the moment, I am using the following code to write to my XML file.

```
   public void WriteXMLFile()
    {
        string _filePath = Application.dataPath + @"/Data/HV_DarkRideSettings.xml";
        XmlDocument _xmlDoc = new XmlDocument();

        if (File.Exists(_filePath))
        {
            _xmlDoc.Load(_filePath);

            XmlNode rootNode = _xmlDoc.CreateElement("Settings");
           // _xmlDoc.AppendChild(rootNode);
            rootNode.RemoveAll();

            XmlElement _cornerNode = _xmlDoc.CreateElement("Screen_Corners");
            _xmlDoc.DocumentElement.PrependChild(_cornerNode);

            #region Top Left Corners XYZ Values

            // indent top left corner value to screen corners
            XmlElement _topLeftNode = _xmlDoc.CreateElement("Top_Left");
            _cornerNode.AppendChild(_topLeftNode);

            // set the XYZ of the top left values
            XmlElement _topLeftXNode = _xmlDoc.CreateElement("TopLeftX");
            XmlElement _topLeftYNode = _xmlDoc.CreateElement("TopLeftY");
            XmlElement _topLeftZNode = _xmlDoc.CreateElement("TopLeftZ");

            // indent these values to the top_left value in XML
            _topLeftNode.AppendChild(_topLeftXNode);
            _topLeftNode.AppendChild(_topLeftYNode);
            _topLeftNode.AppendChild(_topLeftZNode);

            #endregion

            #region Bottom Left Corners XYZ Values

            // indent top left corner value to screen corners
            XmlElement _bottomLeftNode = _xmlDoc.CreateElement("Bottom_Left");
            _cornerNode.AppendChild(_bottomLeftNode);

            // set the XYZ of the top left values
            XmlElement _bottomLeftXNode = _xmlDoc.CreateElement("BottomLeftX");
            XmlElement _bottomLeftYNode = _xmlDoc.CreateElement("BottomLeftY");
            XmlElement _bottomLeftZNode = _xmlDoc.CreateElement("BottomLeftZ");

            // indent these values to the top_left value in XML
            _bottomLeftNode.AppendChild(_bottomLeftXNode);
            _bottomLeftNode.AppendChild(_bottomLeftYNode);
            _bottomLeftNode.AppendChild(_bottomLeftZNode);

            #endregion

            #region Bottom Left Corners XYZ Values

            // indent top left corner value to screen corners
            XmlElement _bottomRightNode = _xmlDoc.CreateElement("Bottom_Right");
            _cornerNode.AppendChild(_bottomRightNode);

            // set the XYZ of the top left values
            XmlElement _bottomRightXNode = _xmlDoc.CreateElement("BottomRightX");
            XmlElement _bottomRightYNode = _xmlDoc.CreateElement("BottomRightY");
            XmlElement _bottomRightZNode = _xmlDoc.CreateElement("BottomRightZ");

            // indent these values to the top_left value in XML
            _bottomRightNode.AppendChild(_bottomRightXNode);
            _bottomRightNode.AppendChild(_bottomRightYNode);
            _bottomRightNode.AppendChild(_bottomRightZNode);

            #endregion

            _xmlDoc.Save(_filePath);

        }
    }

```

This generates the following XML file:

```
    <Settings>
  <Screen_Corners>
    <Top_Left>
      <TopLeftX />
      <TopLeftY />
      <TopLeftZ />
    </Top_Left>
    <Bottom_Left>
      <BottomLeftX />
      <BottomLeftY />
      <BottomLeftZ />
    </Bottom_Left>
    <Bottom_Right>
      <BottomRightX />
      <BottomRightY />
      <BottomRightZ />
    </Bottom_Right>
  </Screen_Corners>
</Settings>

```

Which is exactly what I want. However, each time I press the button that has the WriteXMLFile() method attached to it, it's write the entire lot again. Like so:

```
<Settings>
  <Screen_Corners>
    <Top_Left>
      <TopLeftX />
      <TopLeftY />
      <TopLeftZ />
    </Top_Left>
    <Bottom_Left>
      <BottomLeftX />
      <BottomLeftY />
      <BottomLeftZ />
    </Bottom_Left>
    <Bottom_Right>
      <BottomRightX />
      <BottomRightY />
      <BottomRightZ />
    </Bottom_Right>
  </Screen_Corners>
  <Screen_Corners>
    <Top_Left>
      <TopLeftX />
      <TopLeftY />
      <TopLeftZ />
    </Top_Left>
    <Bottom_Left>
      <BottomLeftX />
      <BottomLeftY />
      <BottomLeftZ />
    </Bottom_Left>
    <Bottom_Right>
      <BottomRightX />
      <BottomRightY />
      <BottomRightZ />
    </Bottom_Right>
  </Screen_Corners>
  <Screen_Corners>
    <Top_Left>
      <TopLeftX />
      <TopLeftY />
      <TopLeftZ />
    </Top_Left>
    <Bottom_Left>
      <BottomLeftX />
      <BottomLeftY />
      <BottomLeftZ />
    </Bottom_Left>
    <Bottom_Right>
      <BottomRightX />
      <BottomRightY />
      <BottomRightZ />
    </Bottom_Right>
  </Screen_Corners>
</Settings>

```

Now, I've written XML files before using winforms, and the WriteXMLFile function is exactly the same. However, in my winform, no matter how much I press the WriteXMLFile button, it doesn't write the whole lot again.

Is there something that I'm doing wrong or should change to stop this from happening?

# Answer
> 0 votes
Guessing that what you want to do is remove the old XML and add the new one I think the reason this does not works is because you're creating a new element and erasing it from the root, i haven't used C# for a while but can you try this?

```
   public void WriteXMLFile()
{
    string _filePath = Application.dataPath + @"/Data/HV_DarkRideSettings.xml";
    XmlDocument _xmlDoc = new XmlDocument();

    if (File.Exists(_filePath))
    {
        _xmlDoc.Load(_filePath);
        _xmlDoc.RemoveAll();

        XmlNode rootNode = _xmlDoc.CreateElement("Settings");

        XmlElement _cornerNode = _xmlDoc.CreateElement("Screen_Corners");
        _xmlDoc.DocumentElement.PrependChild(_cornerNode);

        #region Top Left Corners XYZ Values

        // indent top left corner value to screen corners
        XmlElement _topLeftNode = _xmlDoc.CreateElement("Top_Left");
        _cornerNode.AppendChild(_topLeftNode);

        // set the XYZ of the top left values
        XmlElement _topLeftXNode = _xmlDoc.CreateElement("TopLeftX");
        XmlElement _topLeftYNode = _xmlDoc.CreateElement("TopLeftY");
        XmlElement _topLeftZNode = _xmlDoc.CreateElement("TopLeftZ");

        // indent these values to the top_left value in XML
        _topLeftNode.AppendChild(_topLeftXNode);
        _topLeftNode.AppendChild(_topLeftYNode);
        _topLeftNode.AppendChild(_topLeftZNode);

        #endregion

        #region Bottom Left Corners XYZ Values

        // indent top left corner value to screen corners
        XmlElement _bottomLeftNode = _xmlDoc.CreateElement("Bottom_Left");
        _cornerNode.AppendChild(_bottomLeftNode);

        // set the XYZ of the top left values
        XmlElement _bottomLeftXNode = _xmlDoc.CreateElement("BottomLeftX");
        XmlElement _bottomLeftYNode = _xmlDoc.CreateElement("BottomLeftY");
        XmlElement _bottomLeftZNode = _xmlDoc.CreateElement("BottomLeftZ");

        // indent these values to the top_left value in XML
        _bottomLeftNode.AppendChild(_bottomLeftXNode);
        _bottomLeftNode.AppendChild(_bottomLeftYNode);
        _bottomLeftNode.AppendChild(_bottomLeftZNode);

        #endregion

        #region Bottom Left Corners XYZ Values

        // indent top left corner value to screen corners
        XmlElement _bottomRightNode = _xmlDoc.CreateElement("Bottom_Right");
        _cornerNode.AppendChild(_bottomRightNode);

        // set the XYZ of the top left values
        XmlElement _bottomRightXNode = _xmlDoc.CreateElement("BottomRightX");
        XmlElement _bottomRightYNode = _xmlDoc.CreateElement("BottomRightY");
        XmlElement _bottomRightZNode = _xmlDoc.CreateElement("BottomRightZ");

        // indent these values to the top_left value in XML
        _bottomRightNode.AppendChild(_bottomRightXNode);
        _bottomRightNode.AppendChild(_bottomRightYNode);
        _bottomRightNode.AppendChild(_bottomRightZNode);

        #endregion

        _xmlDoc.Save(_filePath);

    }
}

```

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


# Question
Title: Animating DOM elements vs refreshing a single Canvas
A few years ago, when the HTML Canvas element was still kinda fresh, I wrote a small game in a rather "unusual" way: each game element had its own canvas, and frequently animated elements even had multiple canvases, one for each animation sprite. This way, the translation would be done by manipulating the DOM position of the canvases, while the sprite animation would consist of altering the visibility of the already drawn canvases. (z-indexes, of course, were the tricky part)

It worked like a charm: even in IE6 with excanvas it showed a decent performance, and everything was rather consistent between browsers, including some smartphones. Now I'm thinking in writing a larger game engine in the same fashion, so I'm wondering whether it would be a good idea to do so in the current context (with all the advances in browsers and so on).

I know I'm trading memory for time, so this needs to be customizable (even at runtime) for each machine the game will be running. But I believe using separate canvases would also help to avoid the game "freezing" on CPU spikes, since the translation would still happen even if the redraws lag for a while. Besides, the browsers' rendering engines are already optimized in may ways, so I'm guessing this scheme would also reduce the load on the CPU (in contrast to doing everything in JavaScript - specially the less optimized ones).

It looks good in my head, but I'd like to hear the opinion of more experienced people before proceeding further. Is there any known drawback of doing this? I'm particulartly unexperienced in dealing with the GPU, so I wonder whether this "trick" would nullify any benefit of using a single, big canvas. Or maybe on modern devices it's overkill (though I'm skeptic about the claims that canvas+js - especially WebGL - will ever be a good alternative to native code). Any thoughts?

# Answer
One canvas should allow for much more generalized, easy to read code. Even if multiple canvases do make for better performance, one should easily have enough performance for any user to be satisfied. Also, should you drop your code on someone to maintain, or someone would like to learn off of it, it will probably be easier to use the widely accepted method.
> 2 votes

---
Tags: animation, html5, html-canvas
---


title: Pygame surfaces and their Rects

text:
# Question
Title: Pygame surfaces and their Rects
I am trying to understand how pygame surfaces work. I am confused about Rect position of Surface object. If I try blit surface on screen at some position then Surface is drawn at right position, but Rect of the surface is still at position (0, 0)... I tried write my own surface class with new rect, but i am not sure if is that right solution. My goal is that i could move surface like image with rect.move() or something like that. If there is any solution to do that i would be happy to read it.

Thanks for answer and time for reading this awful English

If helps i write some code for better understanding my problem. (run it first, and then uncomment two lines of code and run again to see the diference):

```
import pygame
from pygame.locals import *

class SurfaceR(pygame.Surface):
    def __init__(self, size, position):
        pygame.Surface.__init__(self, size)
        self.rect = pygame.Rect(position, size)
        self.position = position
        self.size = size

    def get_rect(self):
        return self.rect

def main():
    pygame.init()
    screen = pygame.display.set_mode((640, 480))
    pygame.display.set_caption("Screen!?")
    clock = pygame.time.Clock()
    fps = 30

    white = (255, 255, 255)
    red = (255, 0, 0)
    green = (0, 255, 0)
    blue = (0, 0, 255)

    surface = pygame.Surface((70,200))
    surface.fill(red)

    surface_re = SurfaceR((300, 50), (100, 300))
    surface_re.fill(blue)

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                return 0

        screen.blit(surface, (100,50))
        screen.blit(surface_re, surface_re.position)

        #pygame.draw.rect(screen, white, surface.get_rect())
        #pygame.draw.rect(screen, white, surface_re.get_rect())

        pygame.display.update()
        clock.tick(fps)

if __name__ == "__main__":
    main()

```

# Answer
Per the documentation:

Surface.get\_rect(\**kwargs): return Rect Returns a new rectangle covering the entire surface. This rectangle will always start at 0, 0 with a width. and height the same size as the image.

You can pass keyword argument values to this function. These named values will be applied to the attributes of the Rect before it is returned. An example would be 'mysurf.get\_rect(center=(100,100))' to create a rectangle for the Surface centered at a given position.

The rectangle is used to calculate collisions, if what you're looking for is movement try using blit:

Surface.blit draw one image onto another Surface.blit(source, dest, area=None, special\_flags = 0): return Rect Draws a source Surface onto this Surface. The draw can be positioned with the dest argument. Dest can either be pair of coordinates representing the upper left corner of the source. A Rect can also be passed as the destination and the topleft corner of the rectangle will be used as the position for the blit. The size of the destination rectangle does not effect the blit.

Here's a nice Tutorial of movement in pygame: http://www.pygame.org/docs/tut/MoveIt.html
> 1 votes

# Answer
Surfaces don't have a position on the screen they're only an image, the get\_rect() method is just to get its dimensions.

Your approach extending the Surface class it's ok but it's not pretty standard. In Pygame you have a `Sprite` class which is used to keep track of surfaces on the screen. In fact you should extend Sprite class to create your own objects (player, enemies, etc).

You can read more in the tutorial or in the reference.
> 1 votes

---
Tags: pygame
---


title: Should I redraw every pixel?

text:
# Question
Title: Should I redraw every pixel?
For my first game I implemented a tetris clone in javascript. My "canvas" and an HTML `<table>` with every `<td>` representing a single block. Instead of having a gameloop redraw every single pixel, I only update pixels that have changed, like a piece being rotated and moved down. Is that a bad practice?

# Answer
No, it isn't a bad idea.

In fact, this kind of technique -- determining which (usually rectangular) regions of the screen were "dirty" and only redrawing those -- used to be standard practice for rendering to the screen before the modern era of 3D graphics, hardware acceleration via powerful dedicated GPUs, and so on. There isn't any need to waste computational power re-drawing parts of the frame that have not changed.

Now, in modern times this technique is of less obvious utility. Many games have *so much* changing from frame-to-frame (especially in 3D) that it might be worth redrawing everything all the time, even if the modern render pipeline was not specifically designed to function that way.

If you are using a technology that doesn't or can't take advantage of hardware acceleration, then it's probably a good idea, especially for a 2D game without much changing between frames.

In short, it's unlikely to be a *bad* thing, at worst it will not likely have any noticeable impact on your performance. At best it will help quite a bit, especially if your rendering involves *literally* setting individual pixels each frame (it's a bit beyond the scope of your question, but if possible you should use whatever higher-level rendering primitives are available in your toolchain, such as "DrawRect" or "DrawImage" if they exist rather than manually flipping each pixel in turn).
> 10 votes

# Answer
From what I've heard it's a great practice. The only problem is that practice is mostly troublesome. When you redraw every single pixel you might need to use buffering so you won't notice flickering between the drawing of the second image and the flush of the first.
> 2 votes

---
Tags: game-loop
---


title: Supporting Controllers on Mac

text:
# Question
Title: Supporting Controllers on Mac
I'm currently developing a small, cross-platform game for Windows/OSX. I have XInput support working correctly on the Windows version. I've left off Mac controller support until now and I'm struggling to find an analogous library on OS X.

Does something similar to the XInput API exist for OS X or am I on my own for that?

# Answer
I've been looking into this as well and I have yet to find something as clean and simple as XInput on the Mac. A library that's commonly recommended is OIS but it seems like it's not being maintained anymore.

You can also take a look at the game pad implementation in SFML. It has game pad support for Windows, Mac and Linux. I haven't gotten a chance to take the SFML game pad stuff for a test drive yet but I've been impressed with SFML in general.
> 0 votes

# Answer
I've been using Dave Dribin's DDHidLib library for all of my controller support lately. It's an Objective-C wrapper around IOHIDLib. I also comes with a few sample projects to get you started.

"Included is DDHidDevice, a class for generic HID devices, as well as four subclasses for common device types: joysticks (and gamepads), mice, keyboards, and the Apple IR remote. DDHidDevice provides easy access to HID elements and queues. The subclasses provide easier access to device specific elements (i.e. you don't have to dig through recursive dictionaries to find the mouse buttons), and provide delegates for asynchronous notifications of these elements."
> 0 votes

---
Tags: c++, macos, controllers
---


title: Drawing polygons in 3D

text:
# Question
Title: Drawing polygons in 3D
I have recently been working on a 3D engine from scratch, using JavaScript and HTML5. I've successfully created lines (although slightly buggy) and points, but I can't figure out faces. My current code: http://jsfiddle.net/13dylank/crXUC/163/

How do I add filled faces to form the surface of my figure? I don't even know where to start.

# Answer
> 3 votes
If you want to render 3D I suggest that you take a look at WebGL.

### Non-WebGL answer:

If you really want to go without you start by fixing your current bugs before moving on to faces. If you can place a point correctly it shouldn't be hard to make uni-coloured faces. You simply make a path between 3 points, and fill it.

Tip: You only need to do translation from 3D to screen coordinates in a single piece of code which you can reuse for points, lines and faces.

### Problems a bit further down the road:

Polygons that are partly in view, especially those that have a point behind or at the view plane can be tricky to deal with, but it's still reasonably possible if you know what you are doing.

Z-order, that is figuring which surfaces should be on the top, is hell, maybe you can for your specific scenes figure a way to do it reasonably.

Texture is also going to be pretty hard to do well.

---
Tags: 3d, javascript, html5, html-canvas, 3d-meshes
---


# Question
Title: Can't detect collision properly using Rectangle.Intersects()
I'm using a single sprite sheet image as the main texture for my breakout game. The image is this:

My code is a little confusing, since I'm creating two elements from the same Texture using a `Point`, to represent the element size and its position on the sheet, a `Vector`, to represent its position on the viewport and a `Rectangle` that represents the element itself.

```
Texture2D sheet;

Point paddleSize = new Point(112, 24);
Point paddleSheetPosition = new Point(0, 240);
Vector2 paddleViewportPosition;
Rectangle paddleRectangle;

Point ballSize = new Point(24, 24);
Point ballSheetPosition = new Point(160, 240);
Vector2 ballViewportPosition;
Rectangle ballRectangle;
Vector2 ballVelocity;

```

My initialization is a little confusing as well, but it works as expected:

```
paddleViewportPosition = new Vector2((GraphicsDevice.Viewport.Bounds.Width - paddleSize.X) / 2, GraphicsDevice.Viewport.Bounds.Height - (paddleSize.Y * 2));
            paddleRectangle = new Rectangle(paddleSheetPosition.X, paddleSheetPosition.Y, paddleSize.X, paddleSize.Y);

Random random = new Random();
ballViewportPosition = new Vector2(random.Next(GraphicsDevice.Viewport.Bounds.Width), random.Next(GraphicsDevice.Viewport.Bounds.Top, GraphicsDevice.Viewport.Bounds.Height / 2));
ballRectangle = new Rectangle(ballSheetPosition.X, ballSheetPosition.Y, ballSize.X, ballSize.Y);
ballVelocity = new Vector2(3f, 3f);

```

The problem is I can't detect the collision properly, using this code:

```
if(ballRectangle.Intersects(paddleRectangle))
{
    ballVelocity.Y = -ballVelocity.Y;
}

```

What am I doing wrong?

# Answer
You don't include any code to indicate that you're moving the rectangles with your objects. Additionally, you're creating the rectangles at the position they are in the sprite sheet. You should be creating them at the position their parent objects are. In your case you should be creating them like:

```
ballRectangle =
  new Rectangle(ballViewportPosition.X + ballSize.x/2f, ballViewportPosition.Y+ ballSize.y/2f, ballSize.X, ballSize.Y);

```

Then when moving the ball around, you should also be moving the rectangle around:

```
public void setBallPosition(int x, int y) {
    ballViewPortPosition.x = x;
    ballViewPortPosition.y = y;
    ballRectangle.x = ballViewportPosition.X + ballSize.x/2f;
    ballRectangle.y = ballViewportPosition.y + ballSize.y/2f;
}

```

The `ballRectangle` is used for collision. You should use something else for drawing the ball.
> 3 votes

---
Tags: xna, c#, collision-detection
---


title: Tessellation Texture Coordinates

text:
# Question
Title: Tessellation Texture Coordinates
Firstly some info - I'm using DirectX 11 , C++ and I'm a fairly good programmer but new to tessellation and not a master graphics programmer.

I'm currently implementing a tessellation system for a terrain model, but i have reached a snag. My current system produces a terrain model from a height map complete with multiple texture coordinates, normals, binormals and tangents for rendering. Now when i was using a simple vertex and pixel shader combination everything worked perfectly but since moving to include a hull and domain shader I'm slightly confused and getting strange results. My terrain is a high detail model but the textured results are very large patches of solid colour.

My current setup passes the model data into the vertex shader then through the hull into the domain and then finally into the pixel shader for use in rendering. My only thought is that in my hull shader i pass the information into the domain shader per patch and this is producing the large areas of solid colour because each patch has identical information. Lighting and normal data are also slightly off but not as visibly as texturing.

Below is a copy of my hull shader that does not work correctly because i think the way that i am passing the data through is incorrect. If anyone can help me out but suggesting an alternative way to get the required data into the pixel shader? or by showing me the correct way to handle the data in the hull shader id be very thankful!

```
cbuffer TessellationBuffer
{
    float tessellationAmount;
    float3 padding;
};

struct HullInputType
{
    float3 position : POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
    float3 tangent : TANGENT;
    float3 binormal : BINORMAL;
    float2 tex2 : TEXCOORD1;
};

struct ConstantOutputType
{
    float edges[3] : SV_TessFactor;
    float inside : SV_InsideTessFactor;
};

struct HullOutputType
{
    float3 position : POSITION;
    float2 tex : TEXCOORD0;
float3 normal : NORMAL;
float3 tangent : TANGENT;
float3 binormal : BINORMAL;
    float2 tex2 : TEXCOORD1;
    float4 depthPosition : TEXCOORD2;
};

ConstantOutputType ColorPatchConstantFunction(InputPatch<HullInputType, 3>        inputPatch, uint patchId : SV_PrimitiveID)
{
    ConstantOutputType output;

output.edges[0] = tessellationAmount;
output.edges[1] = tessellationAmount;
output.edges[2] = tessellationAmount;
output.inside = tessellationAmount;

return output;
}

[domain("tri")]
[partitioning("integer")]
[outputtopology("triangle_cw")]
[outputcontrolpoints(3)]
[patchconstantfunc("ColorPatchConstantFunction")]

HullOutputType ColorHullShader(InputPatch<HullInputType, 3> patch, uint pointId : SV_OutputControlPointID, uint patchId : SV_PrimitiveID)
{
   HullOutputType output;

output.position = patch[pointId].position;
output.tex = patch[pointId].tex;
output.tex2 = patch[pointId].tex2;
output.normal = patch[pointId].normal;
output.tangent = patch[pointId].tangent;
    output.binormal = patch[pointId].binormal;

    return output;
}

```

Edited to include the domain shader:-

```
[domain("tri")]

PixelInputType ColorDomainShader(ConstantOutputType input, float3 uvwCoord :    SV_DomainLocation, const OutputPatch<HullOutputType, 3> patch)
{
    float3 vertexPosition;
    PixelInputType output;

// Determine the position of the new vertex.
    vertexPosition = uvwCoord.x * patch[0].position + uvwCoord.y * patch[1].position + uvwCoord.z * patch[2].position;

    output.position = mul(float4(vertexPosition, 1.0f), worldMatrix);
    output.position = mul(output.position, viewMatrix);
    output.position = mul(output.position, projectionMatrix);

    output.depthPosition = output.position;

     output.tex = patch[0].tex;
     output.tex2 = patch[0].tex2;
     output.normal = patch[0].normal;
     output.tangent = patch[0].tangent;
     output.binormal = patch[0].binormal;

    return output;
}

```

# Answer
> 4 votes
The domain shader needs to interpolate amongst the patch control points using the `SV_DomainLocation` input. The idea is that the GPU runs the domain shader for each generated vertex of the tessellated patch, and you have complete control over where these vertices go. That's how you can implement different algorithms such as bicubic patches, PN triangles, subdivision surfaces, displacement mapping, etc.

As a simple test case you could just linearly interpolate the control points. This will just generate a flat triangle for each patch, i.e. the tessellated mesh should come out visually indistinguishable from the original triangle mesh, just with more triangles. To do this you'd so something like

```
output.tex = patch[0].tex * uvwCoord.x + patch[1].tex * uvwCoord.y + patch[2].tex * uvwCoord.z;

```

and similarly for the other components. The next step would be to replace the linear interpolation with something that actually generates a curved surface based on the normals, such as Phong tessellation (simpler, faster) or PN triangles (slower, possibly better results). Or, for terrain you presumably want to do displacement mapping, so you might skip generating the curved surface and just set the position directly from the heightmap.

---
Tags: directx11, tessellation
---


title: Optimal sprite size for rotations

text:
# Question
Title: Optimal sprite size for rotations
I am making a sprite based game, and I have a bunch of images that I get in a ridiculously large resolution and I scale them to the desired sprite size (for example 64x64 pixels) before converting them to a game resource, so when draw my sprite inside the game, I don't have to scale it.

However, if I rotate this small sprite inside the game (engine agnostically), some destination pixels will get interpolated, and the sprite will look smudged.

This is of course dependent on the rotation angle as well as the interpolation algorithm, but regardless, there is not enough data to correctly sample a specific destination pixel.

So there are two solutions I can think of. The first is to use the original huge image, rotate it to the desired angles, and then downscale all the reaulting variations, and put them in an atlas, which has the advantage of being quite simple to implement, but naively consumes twice as much sprite space for each rotation (each rotation must be inscribed in a circle whose diameter is the diagonal of the original sprite's rectangle, whose area is twice of that original rectangle, supposing square sprites).

It also has the disadvantage of only having a predefined set of rotations available, which may be okay or not depending on the game.

So the other choice would be to store a larger image, and rotate and downscale while rendering, which leads to my question.

What is the optimal size for this sprite? Optimal meaning that a larger image will have no effect in the resulting image.

This is definitely dependent on the image size, the amount of desired rotations without data loss down to 1/256, which is the minimum representable color difference.

I am looking for a theoretical general answer to this problem, because trying a bunch of sizes may be okay, but is far from optimal.

# Answer
I think what you are trying to do is the 2D image space equivalent to double rounding. I can construct a loose proof that it is **impossible** to find such an intermediate size, at least in the case of simple downscaling algorithms such as linear interpolation.

Suppose we found `N` such that the intermediate image has size `N×N`, greater than `64×64`. Suppose we aren't even applying rotation yet (angle is zero).

Now let’s build a picture that doesn’t work.

### Building the intermediate image

Consider a fully black intermediate image. Obviously, the final image will be fully black, too. Then, add one gray pixel of minimum intensity (R¸G,B = 1,1,1). The final image should still be fully black. Add another gray pixel touching the first one. Proceed building a circle until the final image is no longer fully black.

**Image 1**

Now one pixel in the final image is gray (if we continued forever, the resulting image would be fully gray, so obviously at some point one pixel becomes gray), and if we remove that last pixel, it’s fully black again.

### Building the original image

Consider the hypothetical original image that led to our intermediate image. I cannot prove it exists, but I have a strong feeling that it does. For instance, if the original image has size `2N×2N`, this could be it:

**Image 2**

When downscaling Image 2 to the intermediate size, we get Image 1.

And by hypothesis, when downscaling to `64×64`, we get one grey dot in the final image.

Now let's **break apart the last pixel we added** and scatter it around the original cluster:

**Image 3**

This is our counter-example.

When downscaled to the final size, this image should give us a grey pixel, because the pixels we scattered are even closer to the cluster, so the global intensity is at least as high.

When downscaled to the intermediate size, this image should miss the special pixel because they have been scattered around, so we get a fully black image when doing the two-step resize.

### Conclusion and future thoughts

I hope this convinces you that what you are trying to achieve will not work in the general case.

My approach to your problem would be to compute the best size **per image**: start with the original image and *eg.* `N = 128`, then try all possible angles and compute the maximum error. If the maximum error is not satisfying, try `N = 256` *etc.* until you get the correct size.
> 7 votes

---
Tags: 2d, sprites
---


# Question
Title: How can I implement collision detection for these tiles?
I am wondering how this would be possible, if at all.

In the image below:

The light brows tiles are ground, while the dark brown is background, so the player can pass over those tiles.

Here's the for loops that draws the level:

```
        float scale = 1f;

        for (row = 0; row < currentLevel.Rows; row++)
        {
            for (column = 0; column < currentLevel.Columns; column++)
            {
                Tile tile = (Tile)currentLevel.GetTile(row, column);
                if (tile == null) { continue; }

                Texture2D texture = tile.Texture;

                spriteBatch.Draw(texture, new Microsoft.Xna.Framework.Rectangle(
                    (int)(column * currentLevel.CellSize.X * scale),
                    (int)(row * currentLevel.CellSize.Y * scale),
                    (int)(currentLevel.CellSize.X * scale),
                    (int)(currentLevel.CellSize.Y * scale)), Microsoft.Xna.Framework.Color.White);
            }
        }

```

Here's what I have so far to determine where to create a Rectangle:

```
    Microsoft.Xna.Framework.Rectangle[,,,] groundBounds = new Microsoft.Xna.Framework.Rectangle[?, ?, ?, ?];

        int tileSize = 20;
        int screenSizeInTiles = 30;

        var tilePositions = new System.Drawing.Point[screenSizeInTiles, screenSizeInTiles];

        for (int x = 0; x < screenSizeInTiles; x++)
        {
            for (int y = 0; y < screenSizeInTiles; y++)
            {
                tilePositions[x, y] = new System.Drawing.Point(x * tileSize, y * tileSize);
                groundBounds[x, y, tileSize, tileSize] = new Microsoft.Xna.Framework.Rectangle(x, y, 20, 20);
            }
        }

```

First off, I'm not sure how to initialize the array groundBounds (I don't know how big to make it). Also, I'm not entirely sure how to go about adding information to groundBounds.

I want to add a Rectangle for each tile in the level. Preferably I'd only make a Rectangle for those tiles accessible by the player, and not background tiles, but that's for a different day.

FYI, the map was made with a freeware program called Realm Factory.

# Answer
> 2 votes
Working with tile size should be enough. You can calculate where your character is by

```
Math.floor(playerPos.x/tileSize.width); // tilesize is usually equal in width and height
Math.floor(playerPos.y/tileSize.height);

```

Let's say our map is 800 pixels wide. And our Tiles are 100 pixels wide. Let's assume there goes 8 tiles in a row.

if our players x position is 350 we get Math.floor(350/100) = 3;

Here is an image sized on actual scale for proof (note that your array starts at 0, so 3 is still position 4):

This will give you an integer which can be used as an index for your grid. Check what tiletype it is and handle the appropriate action.

```
int indexX = Math.floor(playerPos.x/tileSize);
int indexY = Math.floor(playerPos.y/tileSize);

Tile tile = currentLevel[indexY][indexX]; // [Row][Column] < [y][x]
//or in your case:
Tile tile = (Tile)currentLevel.GetTile(indexY,indexX);

//Check tile do your thang. Make stuff happen.

```

It looks like you're not keeping the position in the Tile object. ( might wanna check the properties it could be that there is a "point" or x and y property you can store its location in.

If you want to retrieve the position manually just multiply with your indices:

```
int posX = indexX*tileSize;
int posY = indexY*tileSize;
//And if you need your rectangle
Microsoft.Xna.Framework.Rectangle tileRect = new Microsoft.Xna.Framework.Rectangle(posX,posY,tileSize,tileSize);

```

---
Tags: xna, c#, tilemap
---


title: Game Patching Mac/PC

text:
# Question
Title: Game Patching Mac/PC
Just wondering what types of solutions are available to handle patching of PC/Mac games that don't have any sort of auto updater built into them.

In windows do you just spin off some sort of new install shield for the game that includes the updated files, hope you can read a valid registry key to point to the right directory, and overwrite files?

If so how does that translate over to Mac where the game is normally just distributed as straight up .app file?

Is there a better approach than the above for an already released product? (Assuming direct sells, and not through a marketplace that features auto-updating like Steam.)

Are there any off the shelf auto-updater type libraries that could also be easily integrated with a C/C++ code base even after a game has been shipped to make this a lot simpler, and that are cross platform?

Also how do auto-updaters work with new OS's that want applications and files digitally signed?

# Answer
Assuming that you're not going through the Mac App Store, on OS X the most common way for programs to self-update is using Sparkle.

It's simple, user-friendly, in-place (ie: no separate "installation" process; the new version just replaces the old version), extremely widely used, and it's free.
> 1 votes

# Answer
Unless you're embedding your resource files inside the executable file, patching a game can simply consist of changing some files. These can either be executable files, script files, media files, or any other type of files.

My games usually have resource files packed into zip files, so when I release standalone patches for my games, I send a batch file that does the following:

1. Make a backup of the data files
2. Check the currently installed files are of the correct (patchable) version. This can be done by checking an SHA1 sum.
3. Decompress the patcheable files into a temp folder.
4. Replace, add and delete the files as the patch requires.
5. Recompress the folder.
6. If you're using a good predictable compressor, the resulting file should be identical regardless of the machine in which it is running. Therefore you can now check the patch worked correctly by checking the file with an SHA1 sum.
7. Repeat for all data files. If something goes wrong, recover from backup.

This should work regardless of the platform, and it is very easy to implement.

Also, if you're only targeting Windows, MSI has a patching feature which pretty much does the same thing, but registers the patch as installed. Pretty much every install generator tool can do this.
> 1 votes

# Answer
On PC the sales boost you are going to get from Steam will always surpass the cut they take so you are going to be using `Steamworks`.

If you have been rejected by Steam, I would recommend that you use the `NSIS installer` over install shield. I found it easy to use and a far superior product. (It is also free.) There may be a third option that is even better, but I am not familiar with it.

http://www.steampowered.com/steamworks/

http://nsis.sourceforge.net/Features

The NSIS installer feature set claims to now also support patching and "an optional silent automated installation" mode. I haven't used these features personally, but given my excellent experience with that software in the past I have no reason to believe they wouldn't work.

Someone else will need to answer your Mac questions.
> 0 votes

---
Tags: deployment, patching
---


title: Scripted Motion Paths (?) (XNA)

text:
# Question
Title: Scripted Motion Paths (?) (XNA)
Ok, so the title isn't the greatest because this is a lot more general. Say I want to have the player be able to hit A and have their ship model roll to the right, and shift to the right of the screen, while the camera stays centered. Would I do that through programming (ie. set waypoints for the model and keep the camera focus still) or do it through animation ( so the ship model actually rolls and moves right, and just play those frames)(I actually don't know how to do this kind of 3D animation yet, haven't looked into it. Adding it to my To Do List)

This is a really vague question I know, I'll try and answer any questions.

Thanks, Peter

# Answer
> 2 votes
As always, it depends.

It depends mostly, on the scope of your project. I'm all for doing things clearly over correctly (if there is such a thing), so if this is a learning project, and you're not specifically interested in learning how to implement animations in your pipeline (which is an extremely complex thing by itself), then I'd say you should do this programmatically, and focus your efforts on solving a whole lot of problems that ensue in undertaking the development of a game.

Now, if this is a large project with budget, people and time, you will most likely need to implement this with animation, so your 3D designer can tweak it as she likes, regardless of what the code says. In more enterprisey terms, this is "separating logic from data".

More practically, you have the advantage that it is a ship model, which is most likely a rigid object without joints, so you can get away with modifying the ship transforms directly.

Remember, you want to *remove*, not *add* obstacles so you can get closer to completing your game every day.

---
Tags: xna-4.0
---


# Question
Title: Should pathfinder in A* hold closedSet and openedSet or each object should hold its sets?
I am about to implement A\* pathfinding algorithm and I wonder how should I implement this - from the point of view of architecture.

I have the pathfinder as a class - I think I will instantiate only one object of this class (or maybe make it a Singleton - this is not so important).

The hardest part for me is whether the `closedSet` and `openedSet` should be attached to objects that can find the path for them or should be stored in `pathfinder` class ?

I am opened to any hints and critique whatsoever.

What is the best practice considering pathfinding in terms of design ?

# Answer
> 8 votes
The open and closed sets are only relevant to the algorithm itself (unless you are interested in more than the shortest path, e.g., maybe you want to make an animation of the algorithm in progress) and they depend on the algorithm's parameters (the closed set, for example, is initialized as containing the path's starting node). This means **the sets should only be accessible by the algorithm's code**. A concrete example can be seen in the pseudocode on Wikipedia's A\*-article.

Since you've tagged your post and are open to any critique whatsoever: Don't use a singleton. (Good explanation by munificent.) Instead, implement your A\* as a static function or as a method on a graph(-like) object, which could be the object representing your game world. Nevertheless, the open and closed sets should be local variables of this function or method.

---
Tags: ai, path-finding
---


title: Breathing for game/movie characters

text:
# Question
Title: Breathing for game/movie characters
Breathing (the movement of chest and face features): I'd like to ask if it is hard to model and whether it is computationaly expensive. I recently noticed the great effect it has in Madagascar 3 movie, but (please, correct me if I am wrong) don't remember seeing it in any games (except maybe steam cloud in cold/winter setting) and very few animated movies does that to noticable degree (e.g. when it is necessary by the plot or situation).

I'd greatly appreciate answers from both movie graphics and game graphics perspective.

# Answer
There's nothing computationally expensive about it. The Total War series of games run thousands of discrete animations at once. This is just another animation: a bog-standard application of matrix mathematics, which is equally doable on CPU or GPU.

Probably the only reason you don't *often* see it is simply because most people's breathing is not that noticeable at the distances you tend to see characters from in games, i.e. several metres. In other words, it hasn't been added to many games quite simply because it doesn't add a whole lot. Chest displacement of a centimetre or two is not that noticeable, and slow breathing (which happens most of the time) is even less noticeable.

Movies are high-fidelity, especially the stuff seen in Pixar movies, so it's quite probable that they'd give us much attention to fine detail as possible. Production processes in games tend to have other goals, and keep visual detail as reasonably simple as possible to reduce the cost of rework wherever necessary, while still looking pretty good. Merging different animations / transforms can cause issues, so it's better to keep things simple, by and large. (But I doubt this applies much, here.)

**Conclusion**

Quit worrying about small factors and just write the code. If most of us were to sit around worrying about tiny issues like this, we'd never get anything done. It's a merged animation, and not a particularly complex one as these things go. It's not a big deal and has been done many, many times before. If it fits your style, great, do it. Just because others haven't included it in their games, doesn't mean there is any overarching technical limitation involved.
> 14 votes

---
Tags: 3d, graphics, animation, graphic-effects
---


# Question
Title: What name (if any) applies to this particular 3D rendering technique?
Is there a name for this technique where when instead of rendering certain polygons, you just calculate a few key points and do the drawings in 2d? For instance, instead of rendering a sphere, you just calculate its central vector and draw a 2d circle? And what are the situations one can benefit from it?

# Answer
> 4 votes
> For instance, instead of rendering a sphere, you just calculate its central vector and draw a 2d circle?

But that would just be drawing a circle. A sphere is not a circle. A sphere is *never* a circle. Lighting affects how the interior of a sphere is rendered. Even if you're just talking about the 2D silhouette of a sphere, that's not guaranteed to be a circle either, due to perspective projection effects.

I think what you're talking about are math-based impostors (as opposed to impostors based on other things, like images in a texture).

Impostors are generally a performance optimization. The reason to use a sphere impostor over a sphere mesh is if rendering the sphere mesh will take longer. The same goes for most impostors; they replace more complicated graphical effects.

# Answer
> 1 votes
I guess the closest thing to what you want is "outline rendering" which is another form of cel-shading. But that's not exactly what you describe, as it doesn't simplify calculations by just drawing some primitives (or 2d approximations).

The problem with your approach is that you'll only be able to render some primitive shapes. Sphere is going to be easy, but for every other shape you'll have to implement some other drawing technique to make that "simplification" possible. The renderer would also have to know about the type of primitive it's going to render. Cone is probably going to be quite hard... just imagine all positions a cone can take in 3d space and now imagine to simplify that with 2 lines and one curve.. isn't going to work, as the cone can be rendered as a circle too (when looked from top or bottom).

Do you need this to create vector-graphics from a 3D scene? Or is it related to your other questions (browser based games?).

If it's the first, I'd look into cell-shading and use a raster to vector converter like potrace. If it's for a web based game, I'd encourage you to use WebGL rendering instead or make a pure 2d game. If you really need the 3D, then WebGL is going to be much better as the perception of the 3D scene will be much better as with the approach you're having in mind.

# Answer
> 1 votes
I think you want Imposters technique. There is an article on GPU gems 3 that describe true imposters.

> In this chapter we present the true impostors method, an efficient technique for adding a large number of simple models to any scene without rendering a large number of polygons. The technique utilizes modern shading hardware to perform ray casting into texture-defined volumes. With this method, multiple depth layers representing non-height-field surface data are associated with quads.

Read the article online

---
Tags: 2d, 3d, graphics, rendering, 3d-meshes
---


title: Presenting game center leaderboard

text:
# Question
Title: Presenting game center leaderboard
I have the following code:

```
-(void)showLeaderboard {

GKLeaderboardViewController *leaderboardController = [[GKLeaderboardViewController alloc] init];
if (leaderboardController != NULL)
{
    leaderboardController.timeScope = GKLeaderboardTimeScopeAllTime;
    leaderboardController.leaderboardDelegate = self;
    [self presentModalViewController: leaderboardController animated: YES];
}

[leaderboardController release];

}

```

Which I am trying to use to make my leader-board pop up. The issue is cocos2d will not allow me to use the line:

```
        [self presentModalViewController: leaderboardController animated: YES];

```

How do I fix this?

Thanks

PS I am using cocos2d

# Answer
> 5 votes
You can only call \[self presentModalViewController...\] from a UIViewController (or one of its subclasses). In Cocos2d 2.0, the CCDirector is a subclass of UIViewController, so you can do something like:

```
[[CCDirector sharedDirector] presentModalViewController...]

```

(In previous versions of Cocos2d, I think you need to latch back to the RootViewController, but I could be wrong)

BTW, presentModalViewController is now deprecated; you may want to look at the replacement method "presentViewController..." instead.

For earlier versions of Cocos2d, you can either latch onto the OpenGL view:

```
[CCDirector sharedDirector] openGLView]...

```

or hook back into the main application delegate:

```
AppDelegate *app = (AppDelegate *) [[UIApplication sharedApplication] delegate];
[app methodThatDoesWhatIWantItToDo];

```

# Answer
> 2 votes
You have to implement GKAchievementViewControllerDelegate protocol in your layer or scene.

Declare your layer like this:

```
@interface MyLayer : CCLayer <GKAchievementViewControllerDelegate>

```

This will show the game center:

```
- (void)showAchievements{

     NSLog(@"Show achievements!");
     AppDelegate *delegate = [UIApplication sharedApplication].delegate;

     GKAchievementViewController *achievements = [[GKAchievementViewController alloc] init];
     if (achievements != NULL) {
        achievements.achievementDelegate = self;
        [delegate.viewController presentModalViewController: achievements animated: YES];
    }
 }

```

And to get back the control when user has finished with GameCenter:

```
- (void)achievementViewControllerDidFinish: (GKAchievementViewController *)viewController{

     AppDelegate *delegate = [UIApplication sharedApplication].delegate;
     [delegate.viewController dismissModalViewControllerAnimated: YES];
     [viewController release];
}

```

This code works on cocos2d 1.0.1 in iOS 4,5 & 6.

---
Tags: cocos2d-iphone, cocos2d, game-center
---


# Question
Title: Importance of scripting engine at Cocos2d Game Engine
Each Game Engine is different and solves different problems in different ways, so the engine design does vary greatly from engine to engine (even though a lot of principles are shared from engine to engine).

Cocos2D is a great product on it’s own, but it doesn’t expose engine functionality to a scripting Language like Lua, JavaScript etc.

My Question: How much important to integrate a Scripting Engine at Cocos2d?

# Answer
> 2 votes
Since version 2.1 cocos2d-iphone integrates JavaScript bindings.

More details: https://github.com/cocos2d/cocos2d-iphone/wiki/cocos2d-and-JavaScript

You can find a game done with JS here: https://github.com/vlidholt/CocosDragonJS

# Answer
> 1 votes
This is a very relative question. It simply depends on the use of the engine.

If you need or want to be able to do a lot of scripting internally for game designers and to avoid recompiling the projects then it might be very important to expose as much of the game engine to the scripting interface.

But if you want to allow players and moders to use the scripting engine as well you will be much better off writing your own bridge and select the functions exposed to the scripting engine.

Anyway having a scripting engine in a game engine can drastically improve game development.

Again, certain teams never use scripting in games while others never do without.

I believe this is open to discussion.

---

**Edit**: Having a scripting engine is a big plus though. Those who don't use it don't have to and they can simply deactivate it.

The perfect engine would have multiple levels with diferent interfaces:

* Game designers and internal scripts have access to everything
* 3rd party have access to a limited set of functions

This is how I will try to solve the problem of critical functions (file access, leader boards, authentication process...) being exposed to the scripting interface.

---
Tags: cocos2d-iphone, cocos2d, scripting
---


# Question
Title: SceneManagers as systems in entity system or as a core class used by a system?
It seems entity systems are really popular here. Links posted by other users convinced me of the power of such system and I decided to try it. (Well, that and my original code getting messy)

In my project, I originally had a SceneManager class that maintained needed logic and structures to organize the scene (QuadTree, 2D game). Before rendering I call selectRect() and pass the x,y of the camera and the width and height of the screen and then obtain a minimized list containing only visible entities ordered from back to front.

Now with Systems, originally in my first attempt my Render system required to get added all entities it should handle. This may sound like the correct approach but I realized this was not efficient. Trying to optimize It I reused the SceneManager class internally in the Renderer system, but then I realized I needed methods such as selectRect() in others systems too (AI principally) and make the SceneManager accessible globally again.

Currently I converted SceneManager to a system, and ended up with the following interface (only relevant methods):

```
/// Base system interface
class System
{
    public:
    virtual void tick (double delta_time) = 0;

    // (methods to add and remove entities)
};

typedef std::vector<Entity*> EntitiesVector;

/// Specialized system interface to allow query the scene
class SceneManager: public System
{
    public:
    virtual EntitiesVector& cull () = 0;

    /// Sets the entity to be used as the camera and replaces previous ones.
    virtual void setCamera (Entity* entity) = 0;
};

class SceneRenderer // Not a system
{
    vitual void render (EntitiesVector& entities) = 0;
};

```

Also I could not guess how to convert renderers to systems. My game separates logic updates from screen updates, my main class have a tick() method and a render() method that may not be called the same times. In my first attempt renderers were systems but they was saved in a separated manager, updated only in render() and not in tick() like all other systems. I realized that was silly and simply created a SceneRenderer interface and give up about converting them to systems, but that may be for another question.

Then... something does not feel right, isn't it? If I understood correctly a system should not depend on another or even count with another system exposing an specific interface. Each system should care only about its entities, or nodes (as optimization, so they have direct references to relevant components without having to constantly call the component() or getComponent() method of the entity).

Edit (answer chosen):

I've chosen the suggestion to the IsVisible component. But I added the following optimization:

First I created a IsVisibleOptimized class that descend from the original IsVisible.

The IsVisibleOptimized instances share a list where they push all the entities that are visibles and remove the ones that are not. Most systems are already designed to use the IsVisible component, they not need to change, because the IsVisibleOptimized component registers with both names and can be casted to a IsVisible. But the RenderSystem that is a critical system of the game and need to work as fast as possible, it calls the static function IsVisibleOptimized::getAllVisibles() rather than iterate through all the entities in game to see which are visible.

The CullingSystem uses the QuadTree that the SceneManagementSystem maintains updated each frame. First a call to the getAllVisibles() function and then to the quad tree selectRect(). If there are new entities they are set as visibles (causing them being added to the list too) and the ones that are not visible any more are set as not visible (this removes them from the list too). No more SceneManager with cull() function that had no sense.

The reason to have both versions of the IsVisible component is that the optimized version may not suit all type of games.

If I replace the IsVisibleOptimized for a simple IsVisible at entity build, the game still works (maybe not as efficient) and only the RenderSystem and the CullingSystem need to be replaced for implementations that don't use getAllVisibles().

IsVisibleOptimized makes sense in a game that have big maps with more hidden entities than visible ones and where the screen rect represents a small part of the game map.

I happy with this solution.

# Answer
You can make CullingSystem that updates entites every tick() and set their attributes: isVisible for rendering and isProcessable for logical updates. Though, in my opinion only rendering should care about entities being inside screen rect. Logic shouldn't know about such thing as screen, therefore its culling algorithm may differ and not depend on scene object.

Scene is only a visual representation (human view) of game world and it's only purpose to help human players interact with this world. If a game architecture is designed in such way, you can see as game world might live and update even without any views attached.
> 5 votes

# Answer
I would wager you're attempting to mix multiple concepts here.

There are multiple culling algorithms used in video games. The most notable is the one used to determine what should be drawn on the screen and to what level of detail. This culling is purely render engine driven and shouldn't live outside the render system at all.

Another is what is considered within the purview of an entity to react upon. For example, once you get close enough to a specific entity that is considered hostile, maybe it will attack you, but only if it can actually see you with it's eyes. If a corner blocks it's vision despite how close you are, maybe it cannot sense you. This type of culling happens with the AI subsystem by exploiting functionality provided by other subsystems.

For example, provide a collision sphere around an entity to represent it's sensory area to detecting other entities, notably players. If an entity enters that collision area, it gets added to a list of collided players associated to that NPC. For every collided player, the NPC attempts a ray-cast to find them. But if obstacles block their view of those collided players, it cannot react. Once I move to where I'm no longer obstructed by a wall, the NPC can enter it's attack state and move toward me because all it's behavior validation succeeded.

There is nothing wrong with inter-system dependencies in a game. What you do want to minimize is the component-to-component dependencies. This way you avoid what can often be expensive lookups during the subsystem's update loop, destroying your cache coherency.
> 2 votes

# Answer
If you need to share the SceneManager due to the code architecture, then maybe you could add an isVisible component. That way you could have a SceneSystem which would require an isVisible and Position components and based on those it would add entities to the quad tree. Then in the update function it would set the isVisible component on Entities which are visible. The RenderingSystem would then just query the isVisible, Position and Renderable components when updating. The components are exemplary of course.

I know this isn't the best design when it comes to scene graphs in entity systems, but it should work well given what you already have.
> 1 votes

---
Tags: c++, architecture, component-based, entity-system
---


# Question
Title: Cannot create a neutral unit with a trigger
I've been playing around with the starcraft UMS (Use map settings) for a while and usually i figure things out pretty quickly when im stuck. Alas not this time.

I'm trying to place a neutral unit (player 12) using a trigger. It refuses to work. I'm using Scmdraft 2.0 as my editor (but i cant get it to work in other editors either) (all neutral units placed before the game starts are visible and all other triggers work fine. Also i created a text msg and it does displays it in-game so the trigger triggers )

For testing I created a trigger that looks like this:

```
Player: neutral (i tried neutral players player 1 and all players as well)
Condition:
-always
Action:
-Create *1 Terran Medic* at '*location 022*' for *Neutral* (also tried neutral players)

```

When I start the game nothing happens.

Here is what I tried:

1. I tried placing a start location for neutral player (player 12)
2. I tried changing the owner under map properties of player 12 to neutral and computer from unused which was the default.

Although it seems like it should be a common enough problem, I don't see it in any FAQ and I cant find anything about it when I Google it.

Thanks in advance.

# Answer
> 1 votes
It's been quite a while since I've messed around with the SC:BW editor, but my initial thought here is that triggers aren't run for Neutral players. Try putting the trigger under Player 1 and creating the unit for Player 12.

Then just make sure you have a start location for Player 1 and that he isn't immediately losing the game and you should be good to go.

---
Tags: modding, map-editor, starcraft
---


title: Moving sprites on a graph in libGDX

text:
# Question
Title: Moving sprites on a graph in libGDX
In my game I'd like to move sprites on a fixed path. Until this point I was trying to stick with the tools already provided by libGDX, like the Tiled map renderer classes so I'm looking for a solution nearly as convenient as that, e.g. I'd like to avoid creating the adjacency matrix by hand. Tiled has the functionality to add objects to the map but I'm not sure if I can use it for this purpose. Any idea?

# Answer
Use the tween engine. (tweening)

It is very powerful and easy to use. You can create animations for any atribute, timelines with simultaneous and/or sequencial animations, and assign callbacks for starting, ending, looping, etc.
> 4 votes

---
Tags: java, movement, libgdx, graph
---


# Question
Title: Blender Object Appearing Gray when all Lights are Off
I have an issue with Blender where, when I turn my only light off (a sun lamp) and render the image my object appears gray rather than black (and thus, not appear to the camera). I can't figure out why this is happening.

Here's what I just did in my scene:

Added a new UV Sphere mesh (to make a total of two spheres), made it visible to the camera, turned off the sun lamp (by setting energy to 0), and rendered. The result I obtained is below.

I discovered this when attempting to render the first sphere with a material/texture on it and it was too bright. The material on the spheres (which are different) are very basic, there's no emit, diffuse and specular are at default values. Could there be an issue with the way my camera is setup? Thanks in advance!

# Answer
After digging down into the material settings I found the "Ambient" setting under "Shading" was set to 1.0. I changed it to 0.0 and it seemed to fix the problem.
> 5 votes

---
Tags: rendering, camera, models, blender, lighting
---


# Question
Title: Binding C++ and V8 Javascript from Google
The examples are quite challenging to grasp if you are still getting your head around other things, so the simplest example would be great.

Is there a simpler example?

# Answer
Some links :

1) A series of tutorials i wrote : https://github.com/underscorediscovery/v8-tutorials

2) CProxyV8 extends on the point/line samples by using their binding code

3) v8Juice is also a binding system for v8, has some simpler examples

4) Find other v8 projects and have a look inside their code (if possible)

5) Ask on gamedev.stackexchange.com

6) Ask on the v8 channel on iRC, freenode server
> 3 votes

# Answer
I think this is the simplest working one I could find (github link). It teaches you how to get V8 up and running and then creates an Alert function in C++ that gets exposed to JavaScript.

Cheers.
> 3 votes

# Answer
I've been slowly working on a pygame alternative based on V8.

Although the project is stalled at the moment, the code is still up on Github.

Have a look at the bindings files and jsgame.cpp for some examples. Particularly, JSGame::initialize().
> 1 votes

---
Tags: c++, javascript, scripting
---


# Question
Title: c++ How to use angular velocity that derived from inertia and force(torque) in 3d
* I am relatively new to game development. May my terminology and description are not appropriate. Please excuse my poor phrasing and help me by giving advice on how to question better if this question seems less fitting. I really appreciate your efforts.

Hi. I am having hard time interpreting the set of values I have. I have inertia and force(torque) in terms of x y z. FYI I used x and y coordinates as my ground, flat coordinates and z as my up/down.

I am assuming that since f = ma, that angular acceleration must be a = f / m. So I divide my torque by inertia. Then I add those x y z values to my angular velocity variable's x y z.

However these x y z values confuse me. Don't I need angle/sec or radian/sec sort of values in order to apply rotation? The x y z values I have seemed to not say anything about radians or angular movement.

* Question : If I have ( 1, 2, 3 ) or any ( x, y, z ) as my angular velocity, how do I actually apply it as angular movement?

FYI Here I am pasting my code :

```
float mass = 100;
float devidedMass = 1.0/12 * mass;
Vec3 innertia(
    devidedMass* (_box._size.z*_box._size.z + _box._size.x*_box._size.x),
    devidedMass* (_box._size.y*_box._size.y + _box._size.x*_box._size.x),
    devidedMass* (_box._size.y*_box._size.y + _box._size.z*_box._size.z ));
box._angAccel += forceAng/innertia;
box._angVelo += box._angAccel;
box._angAccel.allZero();

```

source of my inertia calculation http://www.health.uottawa.ca/biomech/courses/apa4311/solids.pdf

# Answer
> 3 votes
Trying to tackle solid mechanics are we?

First let me clear up a bit of your confusion regarding various concepts of Newtonian mechanics:

> I have inertia and force(torque) in terms of x y z.

Inertia is not a tuple (x,y,z), it is in fact a 3x3 matrix but in the case of a simple box, calculating said matrix within the set of coordinates naturally associated with the box yields a diagonal matrix (i.e. whose only non-zero entries are on the diagonal,so there are 3).

The pdf you linked to gives *Ix*, *Iy* and *Iz* which are the three non-zero entries of the inertia matrix *I* (but I'm going to call it *J* because *I* is often used for the identity matrix). But if *J* had been calculated relative to a randomly chosen set of coordinates (if the axes in the pictures to the right of the table in the pdf hadn't been in these positions priviledging the geometry of the solid shapes in question) then the matrix *J* would have been much more complex and, in addition to *Ix*, *Iy* and *Iz* there would have been three other real numbers necessary to define inertia: *Ixy = Iyx*, *Ixz = Izx* and *Iyz = Izy*. Three additional numbers only and not six because *J* is symmetric.

I don't know what `Vec3 innertia(..., ..., ...));` was supposed to mean, but if inertia is going to be a vector, then you'd better make sure your solids always have nice symmetries and invariances with respect to the axes of your axis system.

Classical mechanics tells us that *J.(dω/dt) = T* where *T* is the torque, *ω* is the angular velocity and *dt* is a small amount of time (your timestep). Both are vectors. To get only , i.e. the small amount of angular velocity that you will add to your current angular velocity, you need to multiply both sides of the equation by the inverse of *J* and then by *dt*:

```
box._angVelo += dt * inverse(J) * T;

```

If you are sure that *J* will always be a diagonal matrix then you can avoid calculating a matrix inverse, store the three real numbers making up *J* in a vector instead, like you did, and use a weird component-wise "vector division" which I guess is what you originally wanted to do with `forceAng/innertia`, and it will work. But it will harm the realism of the physics of many solids that aren't shaped in a an axes-friendly way.

Next:

> Don't I need angle/sec or radian/sec sort of values in order to apply rotation? The x y z values I have seemed to not say anything about radians or angular movement.

Angular velocity is, conceptually, the first derivative of some kind of "orientation", that is to say, it is the amount by which this orientation varies with respect to time. The angular velocity's components are indeed in radians per second. Ideally, you'd like to be able to multiply the angular velocity of a solid with a timestep *dt* and get a small variation of some kind of "orientation vector" which you could then add to the current orientation vector, pretty much like you did with velocity and position. But it isn't that easy.

What we call an "orientation" is in fact a rotation operation. Asking "How is my solid orientated?" in fact amounts to asking "What rotation should I apply to my solid so that its orientation is the one I want?".

There are three ways to encode rotations:

* A rotation can be defined as a vector, or a tuple of three real numbers representing axis and angle, but only at the price of relatively heavy computation can we use this formalism to compute a rotated vector.
* Another formalism used to encode rotations is that of quaternions, but while still better than the axis/angle representation complexity-wise, they're not the best at computing rotated vectors. In fact, they're the best solution when you must chain rotations, apply several in sequence.
* Finally, the solution we're going to use here: good ol' matrices. Multiplying a rotation matrix with the vector you want to rotate is the fastest way to rotate said vector (although chaining matrix products is less efficient than chaining quaternion products, and a 3x3 matrix is 9 real numbers as opposed to 4 for a quaternion and 3 in the angle/axis representation).

That being said, let's answer your

> Question : If I have ( 1, 2, 3 ) or any ( x, y, z ) as my angular velocity, how do I actually apply it as angular movement?

We want to change the matrix encoding our solid's orientation based on the angular velocity we got from the equations above.

1. But how do we even use that matrix to get our solid in position anyway? Well, let's imagine that the solid is at the center of the 3D space, and in its original orientation. If *G* is its center of mass, then *G* is exactly at the origin of 3D space. The solid has not ever been rotated. Let's call the solid, when it is in this position, the "base version" of the solid.
2. Now, suppose that our solid has moved since the time it was in its base version. Let's call the rotation matrix that will give us its position *R*. Since this matrix depends on time, *R(t)*. *G* has a position vector *OG* which we have already computed with little effort at this point of the computation (*G* is now away from the origin *O*). With all this, **at any time *t*, for any given point *P* belonging to our solid in its new position,**
***OP(t) = OG(t) + R(t).OP'***
**where *P'* is the point of the base version of the solid corresponding to *P*.** Like, it's the same point, but in the base version. If I have a pointy hat and I move it upside down and onto that shelf over there, if the tip of the hat is *P*, then *P'* is the tip of the hat *when upright and centered*. Making this distinction between the base version of the solid and the real, displaced solid allows us to compute the position of the solid by storing only one known, clean, easy to manipulate version of the solid as well as the transformation that allows us to move it to where we want it to be. **You don't store the current position of the solid and apply a small transformation to it. You store a base version of the solid and refresh *the transformation* that takes it from its base version to its actual version.**
This has a ton of other advantages. But i'm not going to cover them, because that's not the question.
3. Now let's modify *R(t)* to get *R(t+dt)*. *R* maps the vectors (1,0,0), (0,1,0) and (0,0,1) onto the vectors contained in *R*'s first, second and third column respectively, per the definition of a matrix. Knowing these three column vectors is necessary and sufficient to know *R*. In fact, from any two of them you can deduce the third. That's a property of rotation matrices. **If we can compute the new values of *R.(1,0,0)* and *R.(0,1,0)*, we'll be set.**
4. Let's take the first derivative of the important equation above. From the "positions" equation we deduce the "velocities" equation: the velocity of any point *P* belonging to our moving solid is given by
*Vp = Vg + R'(t).OP'*
where *R'(t)* is the first derivative of *R(t)*. But the laws of kinematics also tell us that
*Vp = Vg + ω×GP*
where × denotes the cross product. So there you go:
***R'(t).OP' = ω×GP***
So if *OP'* is to be (1,0,0) then what is *P*? It's the point you get by applying the equation of positions to *OP' = (1,0,0)*. Let's now define
*R1 = R.(1,0,0)*,
*R2 = R.(0,1,0)*
and *R3 = R.(0,0,1)*
as well as
*R'1 = R'.(1,0,0)*,
*R'2 = R'.(0,1,0)*
and *R'3 = R'.(0,0,1)*.
We have
*OP = OG + R(t).OP'<br>= OG + R1*
and also *OP = OG + GP* so that
*GP = R1.*
Therefore,
*ω×GP = ω×R1* and since, as we said, *OP' = (1,0,0)* and *R'(t).OP' = ω×GP = R'1*, we finally have
***R'1 = ω×R1***.
The same applies to *(0,1,0)* so that *R'2 = ω×R2*. *R'3* is obtained from *R'1* and *R'2* with the relation *R'3 = R'1×R'2* but we could also get it using *ω*. At any rate, we now fully know *R'(t)*.
5. Finally, ***R(t+dt) = R(t) + R'(t).dt***. That's your new "orientation". With the positions equation, you now have the position of the solid at time *t+dt*.

I have a bit of work to do so I'll come back later and add pseudocode that translates this, with a few necessary remarks regarding the loss of precision due to floating-point operations, etc. In the end, the code is very short.

**Edit :** I forgot to mention that *R* is also required to compute *ω(t+dt)*. That is because of the very definition of *J*. To quote Wikipedia on the moment of inertia,

> The use of the inertia matrix in Newton's second law assumes its components are computed relative to axes parallel to the inertial frame and not relative to a body-fixed reference frame. This means that as the body moves the components of the inertia matrix change with time. In contrast, the components of the inertia matrix measured in a body-fixed frame are constant.

To use Newton's second law and compute the angular velocity of our solid, we must either bring our problem back to the solid's own frame (base version of the solid, centered at the origin, using the usual axes of space) and use the one *J* we know, or we can re-compute *J* every time the solid rotates. Bringing the problem back within the solid's frame is much easier as it requires only linear transformations (understand rotations) of the variables of the problem (*ω*, *T*, etc) whereas computing *J* again would mean integral calculus over the rotated solid, etc, it would be a mess.

The linear transformations in question are simple: since what separates our inertial frame (relative to the inertial frame, the solid has moved) from the solid's own frame (in the solid's own frame, the center of mass is at the origin, etc) is a rotation (+ a translation but it does not interest us as we are looking at torque and rotation stuff), all you have to do is undo this rotation (apply the inverse of the orientation matrix) to the torque *T* and to *ω(t)*, do your computations in the solid's frame where *J* is the constant matrix you know and then rotate everything back:

*J.inverse(R).(dω)/(dt) = inverse(R).T*

therefore

*dω = dt.R.inverse(J).inverse(R).T*

i.e.

*ω(t+dt) = ω(t) + dt.R.inverse(J).inverse(R).T*

but *R* is an orthogonal matrix because it is a rotation matrix so we have *transpose(R) = inverse(R)*, and a matrix transpose is much easier to compute than an inverse, so finally,

*ω(t+dt) = ω(t) + dt.R.inverse(J).transpose(R).T*

Notice that the formula for the inverse of the inertia matrix in the inertial frame has appeared: we do have

*R.inverse(J).transpose(R) = inverse( R.J.transpose(R) )*

**Finally, here's the** (unbelievably simple) **code:**

```
// Notice that you NEVER use J itself, only its inverse, in calculations,
// so you should have a stored copy of inverse(J) as an object attribute
// for your solid for instance. Here I call it "invJ".
newOmega = omega.add(R.mul(invJ).mul(R.transpose()).vecMul(T).times(dt));

// We can use either omega(t) for the next step or omega(t+dt), it's practically
// the same thing. We now want to compute the new R(t+dt).
// We get the three columns of R as an array of Vec3 objects
Vec3[] rColumns = R.getColumns();
// We will store the columns of R(t+dt) in another array
Vec3[] nextrColumns;
// We apply our formulas
for (int i=0; i<3; i++) {
    nextrColumns[i] = rColumns[i].add((omega.crossProduct(rColumns[i])).times(dt));
}
// we use a static function getMatrixFromVecArray to get a matrix
Mat3x3 nextR = Mat3x3.getMatrixFromVecArray(nextrColumns);

```

# Answer
> 1 votes
You do have a measurement that is in `r/s`.

This is because `torque = moment of inertia * (delta angular velocity / delta time)`.

So we can derive `delta angular velocity = delta time * (torque / moment of inertia)`. Since you're probably working with time steps, you can throw out the delta components. The resulting vector is equal to the angular velocity in radians over seconds. Or, in other words, a quaternion.

If you were to write out the vector in terms of variables it would be `(change in x angle, change in y angle, change in z angle)`. They are also unit vectors in this case, so all you need to do is add the quaternion to the object's angle, component-wise.

---
Tags: c++, 3d, torque
---


# Question
Title: How do I find actors in an area on a poly-precise basis?
Ok, I've been asking various questions and getting some good answers, but I think I need to rethink my method, so I'll describe the problem.

I have a player who has a big blue box in front of him. This box shows which KActors will be pushed when he pulls the trigger:

Currently, the blue box spawns a descendant of Actor which checks collision to see which KActors are touching it:

```
foreach Owner.TouchingActors(class'DynamicSMActor', DynamicActorItt)
{
      // do stuff
}

```

The problem is, if you check for touching between Actors and KActors, it looks like it does a plain axis-aligned bounding-box collision. The power will push the box on the lower right, when it's clear it's not touching the blue box.

How should I do this properly? I just need a way to find out which KActors are touching that area, on a poly-by-poly level. These collisions are only done with rectangular boxes and simple sphere collision; we are aware of the potential for performance issues with complex objects and poly-collision.

I've tried making the collision checker a KActor, but it doesn't report any TouchingActors.

This issue is causing us trouble in a lot of other places as well. So solving this problem is a core issue in our game.

# Answer
> 3 votes
Current solution:

```
local Vector ImpulseToApply, PointA, PointB;
local GJKResult theResult;
local DynamicSMActor TempActor;

foreach Owner.TouchingActors(class'DynamicSMActor', TempActor)
{
    theResult =
    QuadForceImpulseActor(Owner).CollisionComponent.ClosestPointOnComponentToComponent(
        TempActor.CollisionComponent,
        PointA,
        PointB);
    if(theResult != GJK_Fail && VSizeSq(PointA - PointB) < 0.01)
    // if(theResult == GJK_Intersect) // TODO: GJK_Intersect is never returned, for some reason
    {
        // handle collision
    }
}

```

The `ClosestPointOnComponentToComponent` function returns `GJK_NonIntersecting` regardless of whether or not the components intersect. However, the two closest points returned overlap when they intersect. I think this is a bug in the function. Have reported it to Epic; we'll see what they about that.

This works very well for rectangular solids, spheres and cylinders (the three types of PrimitiveComponents).

# Answer
> 1 votes
When you spawn the Actor for collision checks, what is that actor's CollisionComponent set to? I *think* if you set its CollisionComponent to a copy of that blue box mesh, it will do its collision (and thus "Touching") checks based off of that component. (the component will probably need to have `CollideActor=true`)

---
Tags: collision-detection, udk
---