title: Unity map size limit?

text:
# Question
Title: Unity map size limit?
Does Unity have a map size limit and if there is what is the limit? Is there a way to work around it? I am making a open world zombie survival world and I want to make a really big map. Thanks!

# Answer
The limit for a single map is 2000, you can merge them until your pc allows you. I have copied a fully painted terrain around 4048~ times and everything was working properly. The rendering view ends at 2km. The terrains area does't affect performance, the LOD does, grass etc.

Somebody has actually made a map which was the size of Alaska, was funny to watch videos of people who tried running across the map. The only problem in creating a persistant world is the fact that when there are two terrains next to each other. They can not be edited at once, this creates many places for the holes in the ground where players could fall. In order to avoid this, you'd need to get a seamless terain plugin that allows you to merge terrains so that their lelevation level is the same.

To work around the limit you should use 4 terrains that are 2km/2km instead of a 4km/4km.

Search the terrain plugin directory on the unity asset store.

FYI. Don't make the world too big. A standard game human character will need over 10 minutes of running to cross 2 kilometres.
> 1 votes

# Answer
For such a big map, specially if you're planning on some kind of vehicles, take into account floating point errors.

What I mean is, if you get too away from x:0,y:0,z:0, the floating point errors will be enough to make physics shake, and many other bad things. This can be fixed by simply moving the entire world. Basically moving the whole map, making sure your position is at 0,0,0.

A rule of thumb is that for anything bigger than 5km for safety you should do corrections. This is probably way under the "game-killing physics" distance, but it's better to be safe.
> 2 votes

# Answer
According to most of the threads on Unity Answers there is no effective limit. You're limited only by computer accuracy of floating points, memory and the amount of objects you can have. That being said - you should consider cunking your scenes up for the sake of organization. Maintaining one big scene might get really monstrous, really quickly.
> 1 votes

---
Tags: unity, terrain
---


# Question
Title: How to apply logarithmic type formula for speed?
I want my character's speed to ramp up using somewhat of a logarithmic formula. I am confused about how specifically I would implement this. I want the character to move fast with a little movement as as the movement gets larger the added contribution to speed is less and less. I said logarithmic function because this kind of mimics the shape of what I am after. Does anyone have an example of how this is done?

# Answer
As much as I can tell you want something like this:

```
Target_Speed = some value;
Time = -log(Initial_Speed);

while(runnning) {
    Time += delta_time;
    Current_Speed = Target_Speed - exp(-Time);

    do some other stuff
}

```

And here is why this algorithm works:

We know logarithmic function `exp(x)` tend to approach 0 when `x` goes to negative infinity. So in order to make that logarithmic function become zero we should reduce Time to a very low value, or we can increase Time, and compute `exp(-Time)` instead. based on the current argument, it's easy to see when `Time` gets very large, `-Time` becomes real large negative and so `exp(-Time)` becomes almost zero.

And for the initial values: `Target_Speed` is your desired speed, and you can set it as you want. in the first cycle we want the `Current_Speed` to be zero, so `Target_Speed - exp(-Time)` should evaluate to zero.

```
        Target_Speed  = exp(-Time)
=>  log(Target_Speed) = log(exp(-Time)) = -Time
=> -log(Target_Speed) = Time

```

So simply by setting the initial value of Time to `-log(Target_Speed)` we will get what we wanted.

All that said I think my answer is exactly the same as Arne's except with little more information about how it's working!
> 1 votes

# Answer
You can add a curve and manually adjust the acceleration graph.

```
public AnimationCurve curve;

```

Then simply select it in the inspector and use a preset. To change speed, use:

```
currentSpeed = curve.Evaluate(t);

```

where "t" can be `Time.time/5f` or other value from 0 to 1.

If you want a more physical way then use rigidbody and `rigidbody.AddRelativeForce(Vector3.forward);`
> 0 votes

# Answer
each frame do this:

```
speed += 0.05;
pos += speed;
speed *= 0.99;

```

adjust parameters at will.
> -2 votes

---
Tags: mathematics, physics
---


title: How to move rigidbodies

text:
# Question
Title: How to move rigidbodies
Have i understood this correct: If i want to use a rigidbody for physics then

1. i should not move an object through its transform.position.
2. I should never move it by riigidbody.velocity since i then affect the physics.
3. So what is left is moving it using addForce. I guess its like mimicking how in the real world everything that moves has something that drives it.

# Answer
You seem to be answering your own question in your "question", and it seems to me like you are asking for clarification. Please note that my answer is Unity specific.

## Why use Rigidbodies?

When you use a rigidbody, then you should *use* a rigidbody. Allow me to explain what I mean. Often times, when I see developers using rigidbodies; they are neglecting its use. They are:

1. Directly modifying the transforms position and attempting to *use* the rigidbody correctly
2. Using it for collision response only and doing No.1
3. Have an incorrect understanding of transforms and rigidbodies.

**Golden Rule**: Use a rigidbody when you want all aspects of your entity to act under the laws of physics (gravity,forces,torque, etc.)

## Moving your body

Keeping the golden rule in mind(see above) and the three no-no's, we can talk about how to move your rigid-body. In Unity, you have `AddForce()` and you have `AddTorque()`.

Pretty straightforward. The AddForce function, of course, adds a force to your rigidbody. AddTorque adds torque, which is a twisting force, causing your object to spin around a specified axis.

You might ask the question, "Well, why can't I directly modify the position when using a rigidbody?" in regards to movement, per say.

You can, but you'd essentially be emulating the behavior of a transform, that of which is not able to be acted on by force or torque. Transforms, hence the name, can be "translated", but it's not the same as moving it with physics. Rigid-bodies, however, are able to be acted on by force and torque for movement related purposes. Please note that directly modifying the rigidbody's position is acceptable for certain cases.

Le Documentation
> 8 votes

# Answer
Transform.position on a rigidbody won't do any collision checks and just costs more performance.

Applying force to a rigidbody will move it while checking for collisions and such in a realistic sense. Things like moving up and down a ramp will be faster and slower (because of the direction of force) you could get around this by changing the direction the force is applied to the rigidbody to help sustain a constant movement.

If a rigidbody has a collider on it that is marked as a trigger, no matter how its moved there will be no collisions, but you will be notified when the collider enters another collider. You could make your own collisions this way.

A simple and easy way to do collisions that also takes into consideration angled ramps, is to use a character controller physics component. Don't use one of the preset ones. You just want the component not the default unity prefab. This way you can create your own movement and then call the Move(); method of the character controller component. Unity will then take care of the collisions and ramps. Check the docs for more info on the subject.
> 2 votes

---
Tags: unity, rigid-body-dynamics
---


# Question
Title: How does creating 2d game assets differ from regular 2d art?
I've done some digital paintings and concept sketches in the past, and I was thinking about employing those skills in my game making efforts.

From an artists standpoint, what does he have to do differently/additionally to make his artwork "game ready" or "game friendly"?

Mostly I'm interested in using 2D in Unity, perhaps with an isometric view (so called 2.5D)

# Answer
> 4 votes
Game sprites move over all kinds of different background together with other sprites. For that reason it is important to work cleanly regarding transparent and non-transparent parts of an image.

When you create digital paintings or concept scetches, it is usually not that noticeable when you draw a bit over the outlines, don't fill the outlines completely, have slight transparency on layers which shouldn't, or have some almost unnoticeable smears outside of the object.

But when the sprite is moving over a background, such artefacts become clearly visible.

For that reason it is important that each pixel has an opacity of exactly 0,00% or 100,00%, unless you want an intentional(!) transparency effect.

With game sprites you also have the problem that you often have little control over which context they appear in. Sprites need to stand out on any background, no matter if it's dark or bright or if it's noisy or plain. Using thick, dark outlines often helps to make a sprite more background-agnostic, but the resulting comic-look might not fit any aesthetic direction.

When your graphic engine doesn't make lots of use of scaling, you should try to create all 2d assets in the same resolution you want them to have in the final game. For performance reasons most 2d engines don't use image scaling algorithms which are as advanced as those available to graphic editors, so any rescaling will blur your artwork and should thus be avoided, especially when some images are scaled more heavily than others.

It's hardly possible to give you any advise about your workflow, because it's highly dependent on the project and its technical details. But I made the experience that it pays off to set it up in a way that testing your graphics in the actual game while you make them is as painless as possible. Most non-obvious problems don't appear before you see the graphic in the game.

In the ideal case, the game engine should be able to load graphics directly from image files in a format your graphic editor can export with one click. In one project I added a hotkey to reload all assets from hard drive while the game was running. It proved to be a real time-safer.

# Answer
> 1 votes
I would say that when it comes to creation, there are advantages and disadvantages to each method of art creation. So let us cover these first.

Let's start with standard art. One benefit that standard art has, is that you can usually get away with making black and white pictures that still look good, using only a pencil. I believe that controlling the shade of objects is a whole lot easier than having to pick colors.

Even when you do create color images, it is still usually easier to find colors. I think this is because you generally have a fixed pallet of colors, so you don't have to mess with RGB trying to find the right color (more on that later). If you need to control saturation of a color, all you need to do is control how light you are when applying the color.

Another reason that standard art is easier, is that you have the most intuitive image editor ever! Wherever you put then pencil, is where it draws. It is much easier to control a pencil than a mouse.

Now that I have discussed standard art, I will cover the advantages to digital art and how you can best use your skills for game creation.

One benefit that you get with digital art, is that it is very forgiving. Erasing doesn't leave behind traces of what was once there. This means that you don't have to worry about making a line perfect on the first try, which can make you spend less time on practice draws, and make you more productive.

Another benefit to digital art, is that you have the benefit of layers. This allows you to easily duplicate a part of your image before editing it in case you mess it up. This can also be used to keep parts of an image separate.

But one of the biggest advantages is the fact that your image editor usually provides you with tools that do the work for you. For example, instead of spending a bunch of time looking for reference photos, you can simply click a button, and you have a lens flare, for example.

The final and biggest difference, is that in regular art, digital or not, you are drawing an entire image, containing shading, a subject, and in some cases, scenery. Basically a final image. Where as in game art, you are only drawing individual components. Such as a player (or in some cases, you are only drawing individual body parts), a grass tile, or a weapon.

## Adapting

Based on what I have discussed, I will now discuss how you can adapt. And remember, use the advantages of digital art to your advatage.

First off is color. To make the job of color picking easier, you can create a pallet of colors to use in your image. If you need variation, you can simply adjust the hue and saturation. For this, I recommend switching to HSV.

I also discussed the issue of a mouse being harder to control than a mouse. To alleviate this issue, you may consider using a graphics tablet. A very popular company in the realm of tablets is Wacom. The only problem with Wacom is that they are a bit expensive, which is why I haven't bought my tablet yet. The advantage with graphics tablets, is that they usually have pressure detection. This makes the experience a lot closer to using a pencil. This can be useful for shading.

Philipp's answer (which is very helpful) discussed scale. "You should try to create all 2D assets in the same resolution you want them to have in the final game". And though you want your assets to be the same resolution when exported, doesn't mean you can't create you assets in a different resolution. One trick I learned (I don't remember where I read this) is to start with a large image that can be scaled down to the proper size (I recommend doubling the size a few times. This is also why I like to use image sizes that are powers of two, as 8x8, 16x16, 32x32, 64x64, etc.). Draw the sprite at the large size being mindful that you are going to scale the image down, and then when you are done, scale it down to the proper size. Once you do this, you will usually need to repair edges, and fix small details. Make any additional edits, and save the image at the corrected size. Remember, you may want to keep the large version of the image too.

The final piece of advice I have for switching to game art is making sure you use your editor to your advantage. If you need to make dirt, all your really need to do, is fill a brown area, and then apply noise to the image. And **BAM!** You have dirt. This is just one example of using your editor to your advantage.

The truth is, that it is hard to understand what you meant by game-ready, but I have tried my best to help answer the question.

# Answer
> 0 votes
1. With general art, you can use any size, any style and any colors. In games it's important to plan so the sizes, colors and styles of sprites make sense and are compatible when they are together on any of the games backgrounds.
2. Often times game-play mechanics and needs dictates small sprites. It is often good to keep the art clean (instead of trying to scale down a big detailed sprite) so it will look not look too distracting.
3. Animation may require planning. Too much detail means you need to redraw that detail for every frame of animation. Keep it clean and simple, at least until 99% of the work is done.

# Answer
> -1 votes
Philipp's answer is great but he missed one key part in the design of sprites and 2d game art and that is repetition. Sprites, tiles, everything that the user sees should have the ability to be reused somewhere else (even if they are not). For example, the bushes in Mario NES are the same sprite as the clouds, just with a different color code applied to them. Some of the enemies in the NES Zelda are the same sprites as other just flipped 180. Also, the trains and boats in the Pokemon games are the same sprites but with the ability to be elongated by repeating or omitting the use of the internal sprites. Thus a speed boat and a luxury liner are the same sprite base. I hope this makes sense.

---
Tags: 2d, unity, art, assets, pipeline
---


# Question
Title: Is it possible to develop a game using only 3DS Max?
My team is going to get involved in a project and we are researching to decide on whether to reject one particular project. It is a car simulation like a 3D driving simulator. I know we should use game engines like Unity, UDK and so on.

Our modeling group is using 3dsmax to model objects and they have no scripting knowledge. However when moving models to game engine it needs so much effort, almost again modeling. Is it possible to develop a car simulation by only using 3DS Max scripts?

# Answer
> 7 votes
No. 3DSMax is not a game engine. You'll have far more difficulty creating a game in 3DSMax than you would moving the models into a proper engine. If it takes so much effort to move the models from 3DSMax to your engine of choice, you're using the wrong engine, or you're doing it wrong.

If you're really in charge of these types of decisions for a team, you really need to learn more about the technology involved.

# Answer
> 1 votes
> when moving models to game engine it needs so much effort...

What engine are you referring to? The reason it requires a lot of effort (assuming it's a reasonable engine to use like the two pointed above) is lack of experience. I suggest you decide which engine to use by figuring out the goals and requirements of your project. Then learn about the relevant modeling workflow for your game. You could sometimes use Max script to simplify tasks done in 3dsm, sometimes it can be used to simplify the process of exporting game models.

# Answer
> 0 votes
Short answer: No. Long answer: 3DS Max is not a game engine, but rather more of a 3D Modelling program. The scripting language that 3DS Max uses is not used in Unity3D, the best you could possibly try (if your team has a due date, or is pressed for time) Unity's "Javascript"; but I would suggest that your team start to learn C# as it is more powerful than that of the "Javascript" that Unity uses.

Now moving models into Unity isn't too hard

Importing Objects into Unity

> To manually export to FBX from 3DS Max Download the latest fbx exporter from Autodesk website and install it. Export your scene or selected objects (File-\>Export or File-\>Export Selected) in .fbx format. Using default export options should be okay. Copy the exported fbx file into your Unity project folder. When you switch back into Unity, the .fbx file is imported automatically. Drag the file from the Project View into the Scene View.

---
Tags: unity, 3dsmax
---


# Question
Title: How can I incorporate the path of a jump into my A* implementation?
I need to calculate the path of a jump via A\* for a simple platformer game. Calculating the direction is simple, but translating the jump physics into pre-calcuted voxel paths is a bit difficult. Especially when you factor things in like obstacles. Based on the image below, what is the best way to calculate jump in A\*?

To give better context, here is a video of the game I'm working on. Will be implemented here to get companions following the player

http://www.youtube.com/watch?v=yMrbCtb2Buk

# Answer
After heavily contemplating and consulting with many devs on how to solve this problem, I eventually came to the conclusion that A\* on a pre-processed map is the best solution. Here's why:

* Practically instant run time since A\* traverses the map with everything it needs to calculate the jumps
* Pre-processing can be performed at level load, fast enough to run again later after tile destruction
* Clearance support is extremely achievable
* Maps can be easily broken up into quadrants for extremely large tile amounts (1000 x 1000 voxels plus)

The process to use pre-processing with A\* for gravity can be broken down into a few simple steps. If you already have A\* this shouldn't take too long to implement.

1. Calculate clearance values from collision tiles
2. Discover all ledges by looking for missing tiles on the top, left, and/or right or a tile. Also get all walkable tiles
3. Connect all ledges within the maximum jumping distance and that pass a simulated parabola line test (or physics but this will probably kill your runtime)
4. Perform a runoff test on all ledges that draws a curved 135 degree angle in the direction of the ledge. Anywhere the test lands create another jump connection
5. Run a drop test to see if fall locations are present on the sides of ledges
6. A pre-existing A\* implementation should be able to swallow this information with minimal tweaking since it can traverse through flat walkways and ledge connections now

Additionally here is an interactive demo I built based upon the above theory (source code available).

http://ashblue.github.io/pathfinding-platformer/
> 0 votes

# Answer
First of all understand that A\* only works well for a limited set of problems. If you can't make a heuristic that gets close enough to the actually required time then Dijkstra's algorithm is often faster. On top of that it works with teleporters, speed boosters and anything else that breaks the standard assumptions of Euclidean geometry. And it is easier to implement.

The theoretical perfect solution to the problem is to use a search space that include velocity, and any other variable that is relevant to movement, so for a typical 2D platformer you would have a 4D search space consisting of position and velocity. Whether or not this is computationally feasible depend very much on the nature of the game.

If you use float precision it is pretty much impossible to make perfect pathfinding in any case, but if your physics system binds all values to a limited integer space it may be perfectly doable.

If the complete search for any reason is too much you may want to artificially limit the search space, this could for instance be through any combination of the following:

* Do not allow slowing down while running. (Though you must provide some means for the character to turn around before and after jumps.)
* Do only allow jumping at specific points. (Edge of platform and X distance before the end of other reachable platforms seems suitable.)
* Limit the air control to only change simulated input every X physics frames.
* Implement "buggy A\*", that is favour branches that are physically closer to the target even though you cannot guarantee that they will be faster if they are chosen.
* Converge paths that are almost at the same spot in search space, if two routes lead to running in the same direction on the same platform you should terminate the slowest of the two search branches.

Depending on the context the result of these implementations may be satisfactory.

This whole answer assumes a fixed physics rate, combining variable physics rate and predictive AI is a world of trouble.
> 3 votes

---
Tags: movement, path-finding, jumping
---


# Question
Title: How to get and supply IP address for winsock client server program
I'm trying to write a c++ winsock client/server pair. Everything I've read online has the client supply the IP to connect to via command line argument. Nothing says how to get THE (singular) IP address of the server. I know how to get a list of them, but cant find anything about finding the right one. **THE IMPORTANT PART** I need the IP address the client needs to connect to the server from a different computer on a different network.

Also, nothing seems too keen on explaining how to supply one to getaddrinfo ie. what data type do I use?

Any help/links to resources are welcome, Thanks, Peter

**EDIT** (in response to comments about clarity): I have a datagram/UDP server class. Its all set up to recv from a socket. I know which socket. The problem is that I dont know what the IP is to provide the client so it can connect to the server. (Once the client is connected I know how to obtain the IP of the host but not before then which is a real problem as it precludes the client from connecting at all.)

Problem 2: Once I have this IP address, how do I supply it to getaddrinfo? I dont want to use command line arguments. Do I have the user std::cin the IP to a char array? How long do I need that array to be and are there any special termination characters I need to add to the end?

Hope this is more clear.

And just for kicks here's my code. Its all in one file so everything I have is here:

```
#include <stdio.h>
#include <iostream>
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <cstring>

#pragma comment(lib, "ws2_32.lib")

#define PORT "4590"
#define MAXBUFLEN 100

void startup(){
    WSADATA wsaData;
    int iResult;

    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != 0){
        fprintf(stderr, "WSAStartup failed\n");
        exit(1);
    }
}

void cleanup(){
    WSACleanup();
}

bool getIsHost(){
    int hosting;

    printf("Are you the host or the client? (1=host, 0=client)  ");
    std::cin >> hosting;

    if (hosting != 0){
        return true;
    }
    return false;
}

void *get_in_addr(struct sockaddr *sa){
    if (sa->sa_family == AF_INET){
        return &(((struct sockaddr_in*)sa)->sin_addr);
    }
    return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

void printNetworkAddress(){
    std::cout << "Getting Host Name" << std::endl;
    char ac[80];
    if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR){
        std::cerr << "Error " << WSAGetLastError() << " when getting local host name." << std::endl;
        exit(1);
    }
    std::cout << "Host name is " << ac << "." << std::endl;

    struct hostent *phe = gethostbyname(ac);
    if (phe == 0){
        std::cerr << "Bad host lookup." << std::endl;
        exit(1);
    }

    for (int i = 0; phe->h_addr_list[i] != 0; ++i){
        struct in_addr addr;
        memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));
        std::cout << "Address " << i << ": " << inet_ntoa(addr) << std::endl;
    }
}

void serverFunction();
void clientFunction();

int main(){

    bool isHost;

    // Header
    printf("Client/Server Program\n");

    isHost = getIsHost();

    startup();

    if (isHost){
        serverFunction();
    }
    else{
        clientFunction();
    }

    cleanup();

    printf("\n");
    std::cin >> isHost;

    return 0;
}

void serverFunction(){
    printf("Setting up Server\n");

    int sockfd;
    struct addrinfo hints, *servinfo, *p;
    int rv; // Error checking on getaddrinfo
    int numbytes;
    struct sockaddr_storage their_addr;
    char buf[MAXBUFLEN];
    socklen_t addr_len;
    char s[INET6_ADDRSTRLEN];

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_DGRAM;
    hints.ai_flags = AI_PASSIVE;

    if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        cleanup();
        exit(1);
    }

    for (p = servinfo; p != NULL; p = p->ai_next){
        if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
            perror("listener: socket");
            continue;
        }

        if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1){
            closesocket(sockfd);
            perror("listener: bind");
        }

        break;
    }

    if (p == NULL){
        fprintf(stderr, "listener: failed to bind socket\n");
        exit(2);
    }

    printNetworkAddress();

    freeaddrinfo(servinfo);

    printf("listener: waiting to recvfrom ... \n");

    addr_len = sizeof their_addr;
    if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN - 1, 0, (struct sockaddr *)&their_addr, &addr_len)) == -1){
        perror("recvfrom");
        cleanup();
        exit(1);
    }

    printf("listener: got packet from %s\n", inet_ntop(their_addr.ss_family,
        get_in_addr((struct sockaddr *)&their_addr),
        s, sizeof s));
    printf("listener: packet is %d bytes long\n", numbytes);
    buf[numbytes] = '\0';
    printf("listener: packet contains\"%s\"\n", buf);

    closesocket(sockfd);
}

void clientFunction(){
    printf("Setting up Client\n");

    int sockfd;
    struct addrinfo hints, *servinfo, *p;
    int rv;
    int numbytes;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_DGRAM;

    char connectaddr[16];
    memset(connectaddr, 0, sizeof connectaddr);
    printf("connectaddr len: %u\n", strlen(connectaddr));

    std::cout << "Enter the host IP Address: ";

    std::cin >> connectaddr;
    printf("connectaddr len: %u\n", strlen(connectaddr));
    //connectaddr[strlen(connectaddr)] = '\0';

    if ((rv = getaddrinfo(connectaddr, PORT, &hints, &servinfo)) != 0){
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        exit(1);
    }

    for (p = servinfo; p != NULL; p = p->ai_next){
        if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
            perror("talker: socket");
            continue;
        }
        break;
    }

    if (p == NULL){
        fprintf(stderr, "talker: failed to bind socket\n");
        exit(2);
    }

    char message[256];

    std::cout << "Enter your message: ";
    std::cin >> message;

    if ((numbytes = sendto(sockfd, message, strlen(message), 0, p->ai_addr, p->ai_addrlen)) == -1) {
        perror("talker: sendto");
        exit(1);
    }

    freeaddrinfo(servinfo);

    printf("talker: sent %d bytes to %s\n", numbytes, connectaddr);
    closesocket(sockfd);
}

```

# Answer
If you have multiple addresses configured on several interfaces and want to find out which address that you appear as to a foreign host, the simple way is to make a connection to the host or a known host on the external network.

Have that host echo back the address of the peer (you), much like the "what is my IP" websites do. This is also similar to the workings of STUN servers or other service catalogs, master servers and rendezvous services.

You cannot reliably determine much about what an address configured to one of interfaces is good for even if you are able to enumerate them all. The sure-fire way is to attempt to make a connection somewhere and empirically see what happens. Things like NAT/PAT and VPN gateways imply that it's possible that all the local addresses are on private networks.
> 1 votes

# Answer
If I understand yo correctly, there are three possible answers:

1. Assuming there is a list of possible IP addreses:store this list of all possible server IP's on the client and write a loop that iterates and tries them one by one. Afterwards wait and check if you got a response. If not then try again. You can check without blocking with the flag `MSG_DONTWAIT` (if not you can use other non blocking methods).
2. You can buy a domain name and use that instead of an IP address.

I would like to add that you probably should use an existing server implementation. Writing a robust game server is very challenging and time consuming. I personally think SmartFox may be a good place to start looking.
> 0 votes

# Answer
You want to look at 2 possible addresses:

Local IP Address: This is the address that your PC uses. This will typically be assigned by a router or switch, but can be from virtually any DHCP source. You can check your network adapter for this (No code provided as this is not typically what you would use).

Remote IP Address: Any computer that wants to connect to your host must use the IP address on the same common network, and you need something on that network to report the address back to you. This is the IP address as seen by that external source.

Now for your application, you're likely looking for the Remote IP Address. This is what other people will be connecting to since it's the address that exists on the internet.

The reason your PC cannot simply get the remote IP address is because it has no way to know how that information is being routed.
> 0 votes

---
Tags: c++
---


# Question
Title: Bilinear filtering: Selecting pixels to interpolate between
When looking for implementations of bilinear filtering online, all the ones I can find seem to just pick the current pixel, and the three pixels to the bottom and right side of the current pixel.

However, is this even correct, or do you actually have to get the nearest neighbors to the current pixel (from the 8 surrounding pixels) depending on the texture coordinate?

Also, how would I select between the 8 options as efficiently as possible in shaders?

# Answer
> 2 votes
For bilinear filtering, you have to pick the four pixels whose centers are closest to the sample point. (The term "current pixel" is imprecise. Pixels are discrete points, and when you do a texture lookup you provide a point in continuous UV coordinates.)

Since the pixels are arranged on a grid, finding the four whose centers are nearest is easy. First you convert from UV space to pixel coordinates by multiplying by (width, height). In that space, the pixel centers are at coordinates like 0.5, 1.5, 2.5, etc. So, if you subtract 0.5 from the pixel coordinates and then split the integer and fractional components, you have the four nearest pixels (from the integer part, plus offsets by (1,0), (0,1) and (1,1)) plus the coefficients for the bilinear interpolation (from the fractional part).

You do not have to consider 8 neighbors because you can always figure out the 4 nearest pixels directly this way.

# Answer
> 1 votes
You know the factorial component of the UV values. It is represented by the black square's center in the second image; Based on its corners' positions (each 0.5 pixels away in both axises) you pick the four closest four pixels.

This is the texture up close (4x4 pixels)

Now see how an uneven portion of each pixel is overlapped by the black square. Using the relative percentage of the surface it covers of each of the nearest four pixels you"ll mix the colors of these pixels (For instance in this example we get a lot of orange, only a little bit of dark blue and so forth).

---
Tags: shaders, rendering, interpolation
---


# Question
Title: Can GMod/SFM models be converted to Unity GameObjects?
Someone made a suite of GMod/SFM models available for free for people making games and videos in GMod and SFM. These are of type `.dmx`, `.dx80.vtx`, `.dx90.vtx`, `.mdl`, `.phy`, `.sw.vtx`, `.vvd`, `.vmt`, and `.vtf`. I don't use GMod or SFM, so I don't know what these are, thus making it hard for me to manually convert them. **Is there any way to change these into files Unity can recognize and use?**

I'd like to have an easy step from converting them, but I would also accept instructions on how to export them to generic mesh/skeleton/texture files, and then how to import and combine these in Unity.

# Answer
You can use Nem's tool called Crafty to export to .OBJ, then just throw it into your pipeline like any other model.
> 1 votes

# Answer
Studiocompiler can decompile models to \*.smd so you can import them into your fav 3d app with smd plugin. The textures are saved in \*.vtf format, you can open them with paint.net/gimp/photoshop + vtf-import/export plugin.
> 0 votes

---
Tags: unity, file-format, steam, compatibility
---


# Question
Title: Which for basic RTS prototype: Unity or Torque?
I'm wanting to test my hand at writing an RTS (something I've never gotten very far with), and so I'm looking for an indie engine that would give me the most success with a quick setup that I can then tweak and start to get the ins and outs of RTS design/development.

I've had a bit of familiarity with both Torque and Unity both, but never from that perspective.

Which would get me closer to base prototype faster?

# Answer
Personally, I would recommend Unity. In comparison to Torque I've been able to get basic proofs-of-concepts running far faster than before. (Of course, there is a bit of bias as I was far younger when experimenting with Torque)

But in general, it's been a far more pleasing experience to work with. Also in comparison to what I remember from the community at Garage Games, the Unity community is far more available to help with issues that my arise.
> 8 votes

# Answer
You might want to take a look at this tread on the Unity forums. There's also someone working on an RTS "starter kit" but I can't remember who.
> 5 votes

# Answer
My Digital Media friends are currently using Unity for their game development. They seem to like it because it makes it relatively simple to add and use custom 3D objects and the script is rather easy to handle( none of them like programming, but they seem to be doing an OK job at learning the scripting in a semester's time ).

I don't have first-hand experience of the engine itself, but it definitely sounds like it's worth some experimentation.
> 2 votes

# Answer
I haven't used Torque, and in general Unity is great for quickly getting something together.

I would add one disclaimer before you rush in though. Unity has an awful GUI system. Everyone I know who is using Unity in a professional capacity has had to buy a GUI system (I believe NGUI is a popular choice). RTS games often have a lot of UI elements and precious little of the stuff that Unity make easy (things like Physics, particles etc.).
> 0 votes

---
Tags: unity, prototyping, rts, torque
---


# Question
Title: How to load geometry/object/scene created in Clara.io with Three.js
Does anybody know how to load anything created in Clara.io into your Three.js scene?

Clara.io allows export of ThreeJS geometry, object or scene. I tried all those in combination with all THREE loaders (JSONLoader, SceneLoader, GeometryLoader, etc.) without any success (Parse function inside of three.js fails to process json structure).

Structure of exported file from Clara.io looks to be completely different from what Three.js loaders expect. Can this be achieved in any way or is Clara export simply useless at this point?

I am talking three.js v.65 in combination with current version of Clara.io

# Answer
Clara.io exports `Scene` and `Object` data using the `THREE.ObjectExporter`. The resulting exported files are intended to then be loaded by the `THREE.ObjectLoader`. The start of these exported files will look like this:

```
{"metadata":{"version":4.3,"type":"Object","generator":"ObjectExporter"},...

```

Code to load files via the `THREE.ObjectLoader` is here on Github.

You can load the data from an URL using the `ObjectLoader.load()` function or from an already in-memory JSON object using \`ObjectLoader.parse().

I hope this helps. If you would like us to modify how we do things, we can.

EDIT: We have added a documentation page that describes how to load ThreeJS scenes exported from Clara.io. It can be found here:

https://clara.io/learn/user-guide/data\_exchange/threejs\_export
> 2 votes

# Answer
All I needed was to make sure that I have exactly one mesh selected (merge them first if needed) and then use **File-\>Export-\>ThreeJS Object** from menu.

in my app, load it like this:

```
var loader = new THREE.ObjectLoader();
loader.load("dragon.json",
    function ( obj ) {
        scene.add( obj );
    }
);

```
> 2 votes

---
Tags: three.js
---


title: Integer linear program solver based AI

text:
# Question
Title: Integer linear program solver based AI
Is Integer Linear Programming a viable solution for a turn based game AI?

My current AI solution uses an ILP solver. If you are unfamiliar with ILP, it uses a collection of Booleans to find most optimal solution to a linear problem.

I'm concerned about fluctuations in performance and I"m also thinking of portability. I am using C++ to prototype. I have access to an ILP solver that works well with it. I don't know if I"ll find one that I can use on portable devices. I'm unsure if can rely on the computation time being reasonable with an N large enough to get the results I"m planning for.

I am wondering if anyone used this technique (ILP based AI) and would advice against it or in favor of it. Also are there any other (portable and effective) optimization tools that could be used for a similar result? I read about NegaScout but I did not find a book or tutorial that could provide me with a deep understanding of it.

I also read this question which did not help: Implement Negascout Algorithm with stack

# Answer
You can build a skeleton system that can technically make all moves (even if all it can do is lose stupidly), and use an artificial neural network (like FANN...) as the decision making backend.

Letting the bot in its weakest form battle against a clone of itself, you can trivially synthesize a training dataset of unlimited size by logging each game and computing statistics relevant to each move.

It can be somewhat artistic choosing the right *size* network but with a good dataset, it should be easy to tell when you've got it right. Be careful not to overshoot the size, or else it will tend to "memorize" the dataset instead of finding the appropriate algorithm.

I hope AI by neural networks is not too cliche ;)
> 1 votes

---
Tags: c++, ai, optimization
---


# Question
Title: Why does my SDL code crash when I move the mouse over the window?
Whenever I move my mouse below where the image renders in my game, the SDL window crashes and closes down.

I have narrowed the crash down to the bit of code where I check to see if the Escape key was pressed and quit my game; the relevant part of my event loop is:

```
while (SDL_PollEvent(&e))
{
  if (e.type == SDL_QUIT)
  {
    quit = true;
  }
  if (e.key.keysym.sym == SDLK_ESCAPE)
  {
    quit = true;
  }
}

```

I found that if I remove the `if(e.key.keysym.sym`... check, the crashing stops. What is wrong with my code?

# Answer
The `SDL_Event` type is a union. Only a single member of the union can be active at any point in time. Your crash is likely because you are accessing the `key` member when it isn't the active member.

The proper way to do this is to check the event's `type` field before accessing the rest of it: `if (e.type == SDL_KEYDOWN && e.key.keysym.sym...)`

In practice you'll probably want a switch statement in there as the number of events you have grows.
> 1 votes

---
Tags: software-engineering, sdl, c++
---


# Question
Title: How do I use the dot product to get an angle between two vectors?
I am learning to use normalized vectors in my games.

I've learned that in order to know the angle between two vectors, I can use the dot product. This gives me a value between -1 and 1, where

* 1 means the vectors are parallel and facing the same direction (the angle is 180 degrees).
* -1 means they are parallel and facing opposite directions (still 180 degrees).
* `0` means the angle between them is 90 degrees.

I want to know how to convert the dot product of two vectors, to an actual angle in degrees. For example, if the dot product of two vectors is `0.28`, what is the corresponding angle, between 0 and 360 degrees?

# Answer
`dot(A,B) = |A| * |B| * cos(angle)`
which can be rearranged to
`angle = arccos(dot(A,B) / (|A|* |B|))`.

With this formula, you can find the smallest angle between the two vectors, which will be between 0 and 180 degrees. If you need it between 0 and 360 degrees this question may help you.

---

By the way, the angle between two parallel vectors pointing in the same direction should be 0 degrees, not 180.
> 28 votes

# Answer
I'll expand a bit on TravisG's comment and give another answer, making use of the fact that your question had the "2D" tag.

You can get the angle between two vectors using the dot product, but you can't get the *signed* angle between two vectors using it. Put another way, if you want to turn a character over time towards a point, the dot product will get you how much to turn but not which direction. There is another simple formula, however, which is very useful when combined with the dot product. Not only do you have

`dot(A,B) = |A| * |B| * cos(angle)`

You can also have another formula (whose name I made up for political correctness):

`pseudoCross(A,B) = |A| * |B| * sin(angle)`

where if A=(a,b), B=(x,y), then pseudoCross(A,B) is defined to be the third component of the cross product (a,b,0)x(x,y,0). In other words:

`a*x+b*y = |A| * |B| * cos(angle)`

`-b*x+a*y = |A| * |B| * sin(angle)`

The full signed angle is then `angle=atanfull(-b*x+a*y,a*x+b*y)` (atanfull or atan2 functions forgive you if you pass in non-normalized values). If A and B are normalized, that is, if `|A|=|B|=1`, these are simply:

`a*x+b*y = cos(angle)`

`-b*x+a*y = sin(angle)`

---

For a deeper explanation, note that the equations above can be expressed by the matrix equation:

```
[ a,b]   [x]   [cos(angle)]
[-b,a] * [y] = [sin(angle)]

```

But a and b can be expressed as `a=cos(ang1)`, `b=sin(ang1)`, for some value `ang1` (not `angle`). Therefore, the matrix on the left is a rotation matrix which rotates the vector (x,y) by the amount -ang1. This is equivalent to switching into a frame of reference where the unit vector "A" is treated as the vector/axis (1,0)! So then just by drawing the unit circle/right triangle in this frame, you can see why the resulting vector of that product is (cos(angle),sin(angle)).

If you write (a,b) and (x,y) in polar form, and apply the angle difference formulas `cos(l)*cos(m)+sin(l)*sin(m)=cos(l-m)` and `sin(l)*cos(m)-cos(l)*sin(m)=sin(l-m)`, you re-express that the sines/cosines are given by this product, since (l-m)=angle. Alternatively, those identities could be used to see why the linear product given above rotates a vector.

All these identities mean that you rarely need angles. Because angles can be weird - radian/degrees, conventions for inverse sine/cosine, the fact that they repeat every 2\*pi - this can actually be more useful and save you a bunch of "if(ang\<180)" etc logic.
> 10 votes

---
Tags: 2d, mathematics, vector, geometry
---


# Question
Title: Communication between Box2D and libGDX Stage (Scene2D) running in separate threads
I'm making a physics based 2D game using libGDX and Box2D. I want to move the execution of the simulation out of render thread. I use immutable messages and the BlockingQueue to pass the information about player actions. The Box2D applies forces and runs a frame of simulation. In the next step I would like to sync back the changes and update Scene2D Actors accordingly. Making an immutable copy of the state of the game world and sending it back using Gdx.app.postRunnable() is one option but it seems inefficient.

Is there any other option?

# Answer
You can use an `AsyncTask` to run your Box2D logic. Its `call` method returns a result of the type you indicate when parameterizing your `AsyncTask`. It looks like this:

```
public class MyAsyncTask extends AsyncTask<Type> {

    @Override
    public Type call() throws Exception {
        /* your Box2D processing goes here */
        return <new instance of Type>;
    }
}

```

Then, you submit your task with an `AsyncExecutor`, like this:

```
final AsyncResult<Type> result = executor.submit(new MyAsyncTask());

```

Then, in your scene2d update method, you keep polling the task execution state, and then, when it's finished, get the result data and do something with it, in your case, update the scene2d actors:

```
public void update() {
    if (result.isDone()) {
        final Type data = result.get();
        /* do something with the data, eg update actors. */
    }
    /* some other update code */
}

```

I hope this helps you.
> 1 votes

---
Tags: libgdx, box2d, multithreading
---


# Question
Title: Box2D Libgdx removing bodies in case of simultaneous collisions
I am making a clone for the BreakOut game. I'm using Box2D and Libgdx for it. In the game, one scenario is that there could be 2-3 balls at one time. Now the problem occurs when 2 or more balls collide with the same object at the same instant. I'm simulating this by creating 2 balls overlapping each other and having velocities in both directions same, so they move like one body. When they collide I get this error : `AL lib: alc_cleanup: 1 device not closed`. I searched a little and modified my code by putting the condition `if (!world.isLocked())`. Now it just gets stuck and I have to end the process using task manager. Here is my code inside collision listener :

```
if (contact.getFixtureA().getUserData() instanceof Ball) {

        Ball ballTemp = (Ball) contact.getFixtureA().getUserData();

        if (contact.getFixtureB().getUserData() instanceof Brick) {
            brickTemp = (Brick) contact.getFixtureB().getUserData();

            if (brickTemp.getPower() != null)
                brickTemp.getPower().update();

            if (ballTemp.getX() > brickTemp.getPosition().x
                    + brickTemp.getWidth()) { // collision on the right
                ballTemp.goRight();
            }
            if (ballTemp.getX() < brickTemp.getPosition().x
                    - brickTemp.getWidth()) { // collision on the left
                ballTemp.goLeft();
            }
            if (ballTemp.getY() > brickTemp.getPosition().y
                    + brickTemp.getHeight()) { // collision on the top
                ballTemp.goUp();
            }
            if (ballTemp.getY() < brickTemp.getPosition().y
                    + brickTemp.getHeight()) { // collision on the
                                                // bottom
                ballTemp.goDown();
            }
            bodiesToDestroy.add(contact.getFixtureB());
        }
    }

```

I have another if statement where fixtureB is Ball and fixtureA is Brick with similar code. And the part in MainScreen.java where I'm doing the cleaning up job is :

```
world.step(TIMESTEP, VELOCITYITERATIONS, POSITIONITERATIONS);

    if (!world.isLocked()) {
        destroy(MyContactListener.bodiesToDestroy);

        if (MyContactListener.removeBall != null) {
            balls.removeValue(MyContactListener.removeBall, true);
        }

        if (MyContactListener.power) {
            MyContactListener.powerBrick.applyPower(delta);
            powerStartTime = System.nanoTime();
        }

    }
    public void destroy(Array<Fixture> bodiesToDestroy) {
    Array<Fixture> temp = new Array<Fixture>();
    for (Fixture bodyToDestroy : bodiesToDestroy) {
        if (bodyToDestroy.getBody() != null) {
            world.destroyBody(bodyToDestroy.getBody());
            temp.add(bodyToDestroy);
        }
    }
    MyContactListener.bodiesToDestroy.removeAll(temp, true);
    temp = null;
}

```

`applyPower` method just creates two new instances to Ball class with the same co-ordinates and velocities. `bodiesToDestroy` is defined as `public static Array<Fixture> bodiesToDestroy = new Array<Fixture>();`

It's unlikely that two balls collide with the same object just at the same instant, but nonetheless I have to take care of such an occurrence. Please suggest how this should be handled.

# Answer
Ok, I found what was the problem. I was adding things to `bodiestoDestroy` without checking if they were already added. So they were being added twice since two collisions were taking place at once. When deleting from the Array, it removes the first instance while the second instance is still there pointing to something that is destroyed. Hence the problem.
> 2 votes

# Answer
Are you getting a `ConcurrentModificationException`? The Javadoc for LibGDX Array does not say it uses fail-fast iterators (then again it doesn't say it doesn't).

You are removing items from your array, while iterating over it. With regular Java collections this will cause an error.

Deleting the items once you've iterated over all of them might help:

```
for (Fixture bodyToDestroy : MyContactListener.bodiesToDestroy) {
    destroy(bodyToDestroy);
}
MyContactListener.clear();

...

public void destroy(Fixture fixtureToBeDestroyed) {
    if (fixtureToBeDestroyed != null
            && fixtureToBeDestroyed.getBody() != null) {
        world.destroyBody(fixtureToBeDestroyed.getBody());
    }
}

```
> 1 votes

---
Tags: collision-detection, libgdx, box2d
---


# Question
Title: How to take into consideration gravity when moving AI
I'm making a 2D game. There is currently a helicopter flying around, controlled by the player. It's controlled using the arrow keys: UP, LEFT and RIGHT.

It's speed along the y axis is `dy`, and speed along the x axis is `dx`.

It's physics is as follows:

Whenever **UP isn't pressed**, `dy` accelerates in constant acceleration, **indefinitely** towards down. (Gravity). `dx` stays in it's current value.

When **UP is pressed**, `dy` accelerates in constant acceleration from whatever it currently is, **up to 4** (upward, until it reaches speed 4). `dx` stays in it's current value.

When **LEFT is pressed**, `dx` accelerates in constant acceleration, from whatever it currently is, **up to -4**.

When **RIGHT is pressed**, dx accelerates in constant acceleration, from whatever it currently is, **up to 4**.

*(When LEFT or RIGHT are pressed and UP is **not** pressed simultaneously, as I said: `dy` increasingly becomes smaller and smaller, because gravity is affecting the helicopter)*

All of this makes the helicopter often follow arches in the air, rather than straight lines.

This creates physics that seem quite realistic.

**My question is:**

The opponent helicopter, an AI, should move using the same physics system.

Lets say the AI wants to get from where it currently is, to point B.

If there was no gravity and no gradual acceleration in the game, it would be easy. I would simply draw a vector from the AI's position to point B, and make the AI follow it.

But since *there is* gravity and gradual acceleration, **the AI can never move in a straight line** (almost). what would be the best way to make the AI go to point B, as time-efficiently as possible?

**How can I take the gravity into consideration when moving the AI toward a specific destination?**

(If it's easier to explain, please consider point B to be on the same level on the y-axis as the AI, and not in diagonal to it.)

Thanks

# Answer
tl;dr:

```
TimeToStop.x = CurrentSpeed.x / Accelaration.x;

if (TimeToStop.x * CurrentSpeed.x >= 1.99 * DistanceFromTarget.x)
    slow_down_x(); // CurrentSpeed += Acc.x * direction;
else
    speed_up_towards_target_x(); // CurrentSpeed += Acc.x * direction;

```

Same with y. Remember to bound speed so it's between zero and the max speed. If the enemy has a very slow speed at some point and it"s trying to stop, it may begin to move in the opposite direction. Do not allow it. Stop it if it's slowing down and its speed is under 1 * Acc.

Long version: If there are no obstacles, movement on y-axis is completely irrelevant to (and does not affect) movement on x-axis. So the question you describe can be broken into two separate questions.

1. Moving there on x-Axis
2. And moving there on y-Axis.

`CS.x` & `CS.y` are our current speed on the x and y axises.

`TS.x` & `TS.y` Is the time it would take you stop only vertically or horizontally considering your current speed in the relevant axis.

`D.x` & `D.y` are the distance on each axis.

tl;dr:you continue to accelerate (if possible \[unless you reached top speed\]) on x-axis until you reach a spot where the following condition is true:

```
if (TS.x * CS.x >= 1.99 * D.x) hit_the_breaks_on_x();

```

The same with y.
> 4 votes

# Answer
One approach I've used for a similar problem was to first draw a vector to the target, then compare that to the current velocity direction.

So, take the signed angle between the velocity vector and the target vector and apply a thrust relative to the size of the vector.

So if the angle **a** between the red velocity vector and the green target vector is negative then apply positive thrust, otherwise apply no thrust and let gravity sort it out.

Note that you'll have to treat the four quadrants where the target may be differently (as if the target had been in the upper left corner a positive angle would have required applying thrust).

Also, make sure to apply the amount of thrust relative to the deviation from the target velocity.

Technically this isn't taking gravity into account, it's compensating for the current state and it means the AI helicopter may not fly in a straight line to the target but will wobble a bit. This may or may not work for your game.
> 2 votes

# Answer
You could simply recalculate the movement each X frames. Assuming you don't put too many frames between, but enough so it doesn't affect performance, the gravity on a helicopter shouldn't be strong enough to really see the trajectory changing. Plus, I think a player could possibly move the same way, adapting to the gravity while moving and not having it planned.
> 1 votes

---
Tags: 2d, physics, ai
---


# Question
Title: implementing different users in XNA - XML
So I am making a simple 2D game in XNA, and I want to implement different users (players), so each person playing can have their own high score, can only play levels they've already played, can only edit levels they've made, etc.

The levels are currently stored in XML, in the format:

> `<level>
> <name>Level Name</name>
>  <number>14</number>
>  <authorTime>12.45</authorTime>
>  <map>...</map>
>  </level>`

I was wondering what would be the most efficient way, and the best practise approach, to implementing this?

I am currently torn between two options: 1. each level having a `<users>` tag, containing a user ID and a time if they have completed the level. 2. Having a separate XML file, containing users and a list of their levels and times.

Are these good ways to do this? Are there other ways to do this better?

Thanks,

Simon

# Answer
> 1 votes
I'd not mix users with level database. Second variant (separated user base) is easier to expand and support. If you'd ever want to implement mid-stage save, rewriting the whole levels.xml for the save would be..sub-optimal.

If you want to store all the levels (including user-made) in a single file, then user id tag would be enough to distinct them. Otherwise you can create additional xmls for every level created, with creator id attached.

---
Tags: xna, xml, levels, user-experience, scoring
---


# Question
Title: 3D vector graphics - maintaining correct Z 'length'
So I'm trying to build myself a 3D display 'engine', or whatever it ought to be called. I've been experimenting with PyGame, as it's familiar to me.

In a way this has almost been more an excuse to learn the math than to actually build a 'game engine' or anything like that, though ultimately that's why we're all programmers right? To code the next Super Mario Brothers. :) Anyway, this isn't that, it's a learning project, but unfortunately I seem to have hit a wall and I'm not entirely sure how to proceed or what to look for.

I'm unsure of how to move items smoothly on the Z-axis. 0 is the 'closest' a point gets to the screen, whereas *N* is the 'furthest' it could go. In the interest of (hopefully) keeping my math similar across calculations, I've set HEIGHT, WIDTH, and DEPTH all to an arbitrary value of 600.

It would appear that moving objects along the Z-axis is not quite the same as moving them along X and Y. Whereas X and Y are just addition and subtraction, Z is apparently only really effective as a percentage. Unfortunately I can't seem to find a method of incrementing Z in any way that doesn't stretch the shapes as if they're going into Warp when I move them closer to the horizon point. Likewise they squash nearly flat as they move closer to the screen.

I believe that the two most likely code candidates for weirdness are the following two snippets; one is the model's "move all the points" method, the other is a view method. Hopefully the code I'm not sharing is self-evident; Zpt is a class that contains x, y, z coordinates, and so on.

```
def move_pts_to_pt(self, newX=None, newY=None, newZ=None):
##This is how the model moves its points
    oldCtr = self.center
    if newX is not None:
        deltaX = newX - oldCtr.x
    else: deltaX = 0
    if newY is not None:
        deltaY = newY - oldCtr.y
    else: deltaY = 0
    if newZ is not None:
        deltaZ = newZ
    else: deltaZ = 1
    for zpt in self.zpts + [self.center]:
        zpt.x += deltaX
        zpt.y += deltaY
        zpt.z *= deltaZ

def zshape_draw(shapelist, objcolor=(255, 0, 0), objwidth=2):
##This is the view's drawing method for points with a z coordinate
    for shape in shapelist:
        drawnpoints = []
        for zpt in shape:
            z = zpt.z
            horzoff = z / DEPTH
            invhorz = 1.0 - horzoff

            newX = (zpt.x * invhorz) + (WIDTH * HOR_X * horzoff)
            newY = (zpt.y * invhorz) + (HEIGHT * HOR_Y * horzoff)
            drawnpoints.append((newX, newY))

        pygame.draw.polygon(SCREEN, objcolor, drawnpoints, objwidth)

```

I apologize if I've left any code out; I'm happy to re-edit my post. In any event, I cannot suss out what it is I need to do to prevent the z-values that are closest to the 'back' of the screen from increasing much faster than those closer to the screen, while still maintaining their intended 'shape' -- that is, generally looking like they aren't changing in depth as they move from z=0 to z=600 (or, whatever ends up being 100% 'away' from the screen).

# Answer
The way to figure out where a dot in 3d space should be positioned on the screen is by imagining the monitor is a window and the dot is behind that window. To know where that dot is displayed on the monitor, you need to imagine you have one eye and the draw an imaginary line from that eye to that dot beyond the window and see where that line intersects with the window. This is where it should be drawn. If you have a line between two points, calculate the position of each of them on the monitor and proceed to draw the line.

The math in this simple case is deciding on some arbitary `z'` as the distance between the eye and the display output device. Then multiplying each dot's x & y values by that `z'` divided by their z value.

So if we have `d.x, d.y, d.z`, we"ll draw it on the monitor at `d.x/d.z*z', d.y/d.z*z'`

Hope that helps
> 3 votes

---
Tags: vector, pygame
---


# Question
Title: Using atan2 to calculate angle between two vectors
I understand that:

`atan2(vector.y, vector.x)` = the angle between the **vector and the X axis**.

But I wanted to know how to get the angle between **two vectors** using atan2. So I came across this solution:

```
atan2(vector1.y - vector2.y, vector1.x - vector2.x)

```

My question is very simple:

Will the two following formulas produce the same number?

* `atan2(vector1.y - vector2.y, vector1.x - vector2.x)`
* `atan2(vector2.y - vector1.y, vector2.x - vector1.x)`

If not: **How do I know what vector comes first in the subtractions?**

Thanks

# Answer
> 5 votes
The Red is:

`atan2(vectorA.y - vectorB.y, vectorA.x - vectorB.x)`

The Green is:

`atan2(vectorB.y - vectorA.y, vectorB.x - vectorA.x)`

The Blue which I think is what you are looking for:

`atan2(vectorA.y, vectorA.x) - atan2(vectorB.y, vectorB.x)`

You can use `abs()` if you want the absolute value like I think you do. Sometimes you will get a value that is nearly `2 * PI` `(greater than 1 * PI)`, in this case subtract `2 * PI` and use `abs()` again.

---
Tags: mathematics, vector, geometry, angles
---


# Question
Title: Applying a torque to a different centre of mass
In Unity I have an object with a circle collider attached to it and when I apply a torque to this object's rigidbody2D, it rotates as expected. However, I have now attached a sub-object to this object with a polygon (trigger) collider which I am using to detect when something is in a cone in front of the ship. There is no rigid body (2D or 3D) attached to the child object. The only rigid body on the object is the one I am applying torque to.

However, when I do this, the centre of mass of the ship is moved to the centre of this collider, which produces totally the wrong effect. This happens even if I move this collider to the root node (so both it and the circle collider are attached).

I either need a way of getting the rigid body to ignore the child collider/allow me to set the centre of gravity, or else some other way of detecting objects inside a region.

# Answer
As Slasher pointer out in his answer, the problem is that the trigger colliders are being included in the computation of the compound collider when in 2D. In 3D (i.e. with 3D colliders) this does not happen and only non-trigger colliders are used.

I have logged this as a bug with Unity, which they have confirmed and apparently fixed locally. They did not provide a date as to when a fix would go live. You can follow the bug report here.

In the mean time, there are two work arounds:

**Manual childing**

Here you create your trigger collider in a seperate gameobject and "attach" it by setting its `transform.position` and `transform.rotation` to be the same each frame.

This is kind of ugly if you have lots of items in your scene as you can't select the object and see the trigger volume. But it does work.

**3D colliders**

Depending on what you are trying to achieve, you may be able to use 3D colliders as well. For me, I just wanted to know when another object was in a cone in front of the ship. So by attaching sphere colliders and mesh colliders to each object, I could get the result I needed.

Remember, 2D colliders will not register in 3D colliders (and vice versa) so you will need to use both. Also, you can't have 2D/3D colliders on the same object, so the 3D set will need to be a child. Further, they need to have their rigid body set to kinematic so as to not interfere.

This is a good solution as it'll keep everything the same and when the fix arrives you should just be able to swap the colliders out. However, I don't know if there is a large overhead to running both 2D and 3D physics or whether they are essentially simulating 2D as 3D with infinite z-length on each object.
> 0 votes

# Answer
It's called "compound colliders" and it distributes weight across all colliders. You can fix it in 3D version by simply marking collider as "Trigger".

Unfortunately, changing center of mass in 2D physics is not yet supported.
> 1 votes

# Answer
Just attach the lightweight rigid body with a collider you need via a hinge joint. That should not affect center of mass as you still have separate rigid bodies.

Then wait until Unity implements com change.
> -1 votes

---
Tags: unity, physics
---


# Question
Title: How can I support different resolutions with Monogame?
I want to support the following 4 resolutions in my Windows Phone 8 game: 480 × 800, 768 × 1280, 720 × 1280, 1080 x 1920. How can I do that with Monogame? If I draw a sprite with Monogame, the sprite is not drawn on the right place in every resolution. For example, with a resolution of 768 × 1280, the sprite is drawn in the center of the screen, but if I use another resolution, the sprite is no more drawn in the center of the screen.

What should I do so that the sprite is in every resolution on the same place?

# Answer
> -1 votes
You must resize all your image, and use some maths for positions.

I don't know XNA, but I will give you a code that you will adapt with this lib.

**Images**

**1.** You will do everything based on 1 screen resolution, and scale your images, relative to this.

```
float Reference_Screen_X = 1280;
float Reference_Screen_Y = 720;

```

**2.** You will get your current screen resolution

```
float Screen_X = GetScreenWidth(); //your function to get the screen width
float Screen_Y = GetScreenHeight();

```

**3.** You will resize all your image this way

```
float size_x = image.getwidth() * ( Screen_X / Reference_Screen_X );
float size_y = image.getheight() * ( Screen_Y / Reference_Screen_Y );
image.setSize(size_x, size_y);

```

**OR** with scale methods

```
float scale_x = 1 * ( Screen_X / Reference_Screen_X );
float scale_y = 1 * ( Screen_Y / Reference_Screen_Y );
image.setScale(scale, scale);

```

**Positions**

**4.** You have to keep in mind that every value you will set, will be in a Reference\_Screen coordinate.

For exemple if you want go to the middle of the screen :

```
image.x = 640 * ( Screen_X / Reference_Screen_X );

```

**Shortcuts**

You should use global variables like :

```
  float refToScreen_x = ( Screen_X / Reference_Screen_X );
  float refToScreen_y = ( Screen_Y / Reference_Screen_Y );

```

Then you just multiply them to the number you want :

```
 x = 500 * refToScreen_x;

```

I hope this will help you.

---
Tags: xna, c#, monogame
---


# Question
Title: Why does everything appear backwards when using orthographic projection?
I may not be calculating my orthographic projection matrix properly. What can I do to ensure that my scene renders correctly when using orthographic projection?

The rendering order appears to be backwards too (note the grid and how it appears half ontop, as if the z-buffer from the correct direction was being used). Disabling culling fixes things, but the view is still backwards.

Perspective:

Orthographic:

Matrix code for reference:

```
    Matrix4.createFrustum = function(left, right, bottom, top, near, far, result) {
        if (typeof result === 'undefined') {
            result = new Matrix4();
        }

        var re = result.elements;
        var x = 2 * near / (right - left);
        var y = 2 * near / (top - bottom);

        var a = (right + left) / (right - left);
        var b = (top + bottom) / (top - bottom);
        var c = - (far + near) / (far - near);
        var d = - 2 * far * near / (far - near);

        re[0] = x; re[4] = 0; re[8]  = a; re[12] = 0;
        re[1] = 0; re[5] = y; re[9]  = b; re[13] = 0;
        re[2] = 0; re[6] = 0; re[10] = c; re[14] = d;
        re[3] = 0; re[7] = 0; re[11] =-1; re[15] = 0;

        return result;
    };

    Matrix4.createPerspective = function(fov, aspect, near, far, result) {
        if (typeof result === 'undefined') {
            result = new Matrix4();
        }

        var ymax = near * Math.tan(fov * Math.PI / 360);
        var ymin = - ymax;
        var xmin = ymin * aspect;
        var xmax = ymax * aspect;

        Matrix4.createFrustum(xmin, xmax, ymin, ymax, near, far, /*out*/ result);

        return result;
    };

    Matrix4.createOrthographic = function(left, right, top, bottom, near, far, result) {
        if (typeof result === 'undefined') {
            result = new Matrix4();
        }

        var re = result.elements;
        var w = right - left;
        var h = top - bottom;
        var p = far - near;

        var x = ( right + left ) / w;
        var y = ( top + bottom ) / h;
        var z = ( far + near ) / p;

        re[0] =2/w;  re[4] = 0;   re[8]  = 0;   re[12] =-x;
        re[1] = 0;   re[5] =2/h;  re[9]  = 0;   re[13] =-y;
        re[2] = 0;   re[6] = 0;   re[10] =-2/p; re[14] =-z;
        re[3] = 0;   re[7] = 0;   re[11] = 0;   re[15] = 1;

        return result;
    };

```

# Answer
Just a guess but if looks like you are using a Left-handed coordinate system and a Right-Handed Coordinate system together.... If you have an option to `Matrix4.createOrthographicLH` or `Matrix4.createOrthographicRH` or something like that try it and see what happens.

You could also try flipping the values in `Matrix4.createOrthographic` for `top` & `bottom`.

Those are all guesses, to do more I would need to see how you are calculating the values for `left`, `right`, `top` & `bottom` as well as how you are generating the `Perspective View matrix`?

-------- Edit -----------

Looking at it I think you need to do this: `var h = bottom - top;`

top - bottom is going to give you a negative number.
> 2 votes

---
Tags: camera, projection, webgl
---


# Question
Title: How to adjust a font to fit inside a speech bubble?
I'm creating a game that contains a speech bubble for dialog. The idea of this function is to allow one call to set new text in a speech bubble. The speech bubble will adjust in size of the new font texture.

The difficulty is getting the math to work. I get the font texture's size, the balloon sprite size, and then get the difference. If the difference is negative, I would think this means the font size is smaller so I need to readjust the speech bubble to fit the font (cell padding is excluded for now). If the difference is larger (font is greater than speech bubble), I would need to increase the speech bubble's size to fit it.

Part of my trouble too is SFML (API) has no SetSize function for the sprite, so I'm relying on setting the scale instead - which is a bit more confusing to me. SFML did have a SetSize function in a earlier version, but it's not in v2.1.

SFML SetScale() Reference: http://www.sfml-dev.org/documentation/2.1/classsf\_1\_1Transformable.php#a4c48a87f1626047e448f9c1a68ff167e

Within this code, I'm asking how to calculate this correctly.

```
/* Perform black magic here on scaling the correct size.

    I need to adjust the floating point #
        based on the new speech balloon's width and height. This portion is not working correctly.
    I get vScale.x = 3.6718750, vScale.y = 2.4765625, so it blows the image high.
    */
    vScale.x = (float)bal_w_prev / (float)bal_w;
    vScale.y = (float)bal_h_prev / (float)bal_h;

```

I took the advice to switch the values (bal\_w\_prev and bal\_w) to its opposite (bal\_w to bal\_w\_prev), and it does seem to work, but the speech bubble's width is half way to where it needs to be. The font size is implicitly included because SFML uses fonts as textures. Does the font's texture size need to be in this algorithm above as well?

Full code (if needed):

```
/*****************************************************************
 * Sets text for an existing speech bubble.
 *
 * @param sb - The speech balloon object.
 * @param strText - The text to insert into the speech balloon.
 * @param x - The x position.
 * @param y - The y position.
 * @param scale - Not used for now - originally to scale by 0.0-2.0.
 ****************************************************************/
void sb_set(struct X2D_SPEECH_BALLOON *sb, const char *strText,
    const float x, const float y, const float scale)
{
    float balloon_x_center, balloon_y_center;
    sfVector2f vScale;
    unsigned int font_w, font_h,
        bal_w, bal_h, bal_w_prev, bal_h_prev, diff_w, diff_h;

    /* Set font */
    fnt_setText(&sb->font, strText);

    /* Set position */
    sb_setPos(sb, x, y);

    /* Get font's size */
    font_w = sfTexture_getSize(sfFont_getTexture(sb->font.font, sb->font.size)).x;
    font_h = sfTexture_getSize(sfFont_getTexture(sb->font.font, sb->font.size)).y;

    /* Get the balloon size */
    bal_w = sfTexture_getSize(sb->sprBalloon.texture).x;
    bal_h = sfTexture_getSize(sb->sprBalloon.texture).y;
    bal_w_prev = bal_w;  /* Save original width */
    bal_h_prev = bal_h;  /* Save original height */

    /* Get the difference */
    diff_w = bal_w - font_w;
    diff_h = bal_h - font_h;

    /* Check if font size is greater than the balloon sprite size */

    /* Speech bubble's width is less than the font's width. */
    if (diff_w < 0)
    {
        bal_w += diff_w;
    }

    /* Speech bubble's height is less than the font's height. */
    if (diff_h < 0)
    {
        bal_h += diff_h;
    }

    /* The speech balloon's width is greater than the font's size. */
    if (diff_w >= 0)
    {
        bal_w -= diff_w;
    }

    /* The speech ballon's height is greater than the font's size. */
    if (diff_h >= 0)
    {
        bal_h -= diff_h;
    }

    /* Perform black magic here on scaling the correct size.

    I need to adjust the floating point # (0.0 - 2.0)
        based on the new speech balloon's width and height. This portion is not working correctly.
    I get vScale.x = 3.6718750, vScale.y = 2.4765625, so it blows the image high.
    */
    vScale.x = (float)bal_w_prev / (float)bal_w;
    vScale.y = (float)bal_h_prev / (float)bal_h;

    /* Set the scale */
    sfSprite_setScale(sb->sprBalloon.sprite, vScale);

    sb->sprBalloon.width = sfTexture_getSize(sb->sprBalloon.texture).x;
    sb->sprBalloon.height = sfTexture_getSize(sb->sprBalloon.texture).y;
}

```

# Answer
> 2 votes
Im not going to check your code but i will give you a basic idea of how i would do this. To calculate the size of the balloon, u first need to calculate the required size to fit the text. To do this u also need to know how many chars u want to fit into the bubble.

From here, u can calculate the size of the rectangle u need for the text.

* Rectangle heigth = (amount\_of\_lines * font\_heigth ) + ((amount\_of\_lines-1) * height\_line\_spacing)
* Rectangle width = (number\_of\_chars / amount\_of\_lines ) * font\_width

From the original speech bubble u need to know the textarea size to calcualte the required scaling \- scale = required\_size / original\_size

### Example:

* text\_length = 100 chars
* lines = 5
* font\_width = 10px
* font\_height = 20px
* spacing\_height = 10px (space between 2 lines)

Original bubble image size (red rectangle)

* height = 300px
* width = 500px

Original bubble image textarea size (green rectangle)

* height = 200px
* width = 400px

### Step 1: calculate required text space

* height = (5 * 20px) + ((5-1) * 10px) = 100px + 40px = 140px
* width = 100 / 5 * 10px = 200px

### Step 2 : calculate scaling

* Height scale = required\_height / original\_height = 140 / 200 = 0.7 = 70%
* Width scale = required\_width / original\_width = 200 / 400 = 0.5 = 50%

Dont Forget: using 2 different scaling will change the width/height ratio of the original size, resulting in a stretched image. to prevent this u should scale both dimension use the smallest scale.

---
Tags: mathematics, sprites, c, sfml
---


# Question
Title: Is it more efficient to encode rotation in a spritesheet or rotate at runtime?
I'm developing a game with JavaScript and HTML5 and I'm wondering about the performance implications of sprite rotations. There are two ways that I know to rotate a sprite:

1. Rotate the actual sprite based on its rotational speed and velocity, as it travels along it's trajectory.
2. Pre-compute the rotations and store them as frames within the sprite sheet to give the illusion that it's spinning when it isn't.

On one hand, I can see how rotating some sprites in a spritesheet would be efficient because it's one image that is loaded, split into frames, and re-used. But on the other hand, I'm not sure the calculations involved for rotating the sprite based on its velocity and rotational speed are really anything for current browsers (on computers and mobile devices) to worry about.

In my game, the canvas area is 800 x 600, and the game is using 32 x 32 sprites for everything. The "map" isn't tile-based. Of the two options above, which would be more efficient for runtime performance?

# Answer
From a pure quality standpoint, it would be better to serve a spritesheet with all the rotation angles. This allows you to make some adjustments for perspective and light direction for all angles which you can hardly do automatically (unless you have a 3d model). But even when you choose not to invest this additional work into the graphics and do the rotation automatic, graphic editors usually use filter algorithms with a much higher quality than those provided by implementations of the HTML5 canvas, resulting in less loss of quality.

But in case of web-based games, there is also another important consideration: **Bandwidth**. When you create an installable game, filesize usually doesn't matter that much. But when all assets are loaded from the web when the game starts, it pays off to keep filesizes small, because it results in much faster loading times. And loading times on web applications do matter a lot. Web users are impatient, and every second of additional loading time causes some percent of people to click the close-button of their browser tab. Also, most webhosting plans bill you by the amount of traffic you generate, so saving filesize saves you money.

When you have only one frame for each sprite which you automatically rotate in 8 directions on the client, you reduce filesize and thus loading time to one eight. This can mean that the loss of visual quality can be an acceptable trade-off.

But that does not mean that the performance of the game itself has to suffer. Instead of re-rotating the sprites whenever you draw them, you can precalculate the spritesheet with all the directions to an invisible background canvas at startup. This approach is a trade-off of memory for processing power. But unless you have a really hight number of rotation angles, it should be worth it.
> 0 votes

# Answer
If your sprites are high-fidelity (for example, 3D models rendered into a 2D sprite sheet), than you probably want to encode the rotations into the spritesheet. Not for reasons of performance, but because the sprite probably will not look as good if you rotate it at runtime.

If your sprites are such than they can survive such a runtime rotation acceptably, then that is going to be the more efficient solution in most cases. This is because:

* The math involved to rotate an image is not complex (basic trigonometry, possibly some matrix operations depending on the underlying frameworks involved).
* The math is *probably* being done anyway (especially if you are using a framework that supports it, or supports hardware acceleration), so there's no effective cost to change the rotation value from 0 to whatever you need.
* You will consume less memory in your spritesheets. At some level this may impact performance positively (less time spent paging, or better cache locality, et cetera), but mostly it is its own benefit.
* It's much easier for the developer to implement and iterate on than baking the rotations, which requires the time-consuming (relative to the alternative) re-rendering process. You can trivially adjust rotation speed and amount, which is much harder if you pre-render all rotation frames.

You probably should only consider pre-baking the rotation frames if profiling has shown this to be advantageous (this may be true in a non-hardware accelerated situation, for example) or if your sprites need it to have acceptable visual quality.
> 2 votes

# Answer
Pre-rendering rotated sprites is probably not helping a lot in this case since most modern browsers use hardware acceleration for things as simple as 2D transformations.

It may be worthy in some very specific cases, like the one described in Josh Petrie's answer, or when you want to have a specific visual style, like "8 bits pixel art graphics", but unless you have a very good reason, I wouldn't recommend it.

Also pre-rendering rotated sprites have some downsides:

* Bigger memory footprint (using too much memory is more likely to slow down your browser game than using GPU for rotating small images)
* While most gaming framework handle rotations natively, you will have to add some code to find the right sprite for a given angle, which means more complexity, more potential bugs and more expensive code maintenance (You will also have to re-implement basic things like angular speed or angular acceleration if your game need them)
* Cutting angles: if your sprites use the "corner pixels" (ie the ones near the top left corner) and you rotate the sprite by 45 degrees, those pixels will be out of the resulting 32x32 sprite; This will prevent you to use the full 32x32 area of your sprites for drawing, which may be annoying... On the other hand, if you draw your square 32x32 sprite with a 45 degrees rotation in your canvas, it will be complete.

Bottom line: I would say it really depends if you want to develop a game, or a gaming framework. As long as your framework offer things like rotation for free, and you don't have any specific issue with their implementation, just use it.

Also, unless you choose a framework which has been discontinued for years, it's likely that a group of motivated and talented peoples have spent a lot of time optimizing things as trivial as sprites rotations.
> 0 votes

---
Tags: javascript, sprites, html5, html-canvas, spritesheet
---


title: Instancing with the SharpDX toolkit

text:
# Question
Title: Instancing with the SharpDX toolkit
I am starting on the graphical portion of my project and before I begin I need to get Instancing working. I can do instancing with SharpDX, but not with the Toolkit Models. The main reason I want to use the Tookkit is for loading models, textures, fonts, etc...

The most helpful thing for me would be a link to an example that instances a `SharpDX.Toolkit.Graphics.Model` -- but anything the shows the Model working with a custom effect should be fine... I can make instancing work from there right?

I have searched and searched for that though so I am not too hopeful - so if this is not something easily done alternative solutions would be great. As I said, I can use SharpDX without the toolkit just fine - but I want the benefits that come with loading models and fonts mostly.

# Answer
Instancing requires to change the InputLayout of vertex buffers and pass an instancing buffer along the mesh vertices. Unfortunately, there is nothing automatic to do this with Toolkit models, though possible but would require to dig into the internals to do this yourself. Before even trying to do some instancing with models, you should start with a basic instancing sample with your own raw vertex buffers/index buffer and effect. You will see exactly what needs to be changed and how to setup/use instancing. With this proof of concept working and with the source code of the Toolkit available, you should be able to figure out how to use existing toolkit Model data to turn it into instancing friendly.
> 2 votes

---
Tags: hlsl, sharpdx, instancing
---


# Question
Title: Convert atan2 value to standard 360-degree-system value
Lets say I'm using `atan2` to get the angle between two vectors.

`atan2` gives a value in radians. I convert it to degrees using a built in function in Java. This gives me a value between `0` and `180` degrees or between `0` and `-180` (the nature of atan2).

Is there a way to convert the value received with this function (after it's been converted to degrees), to the standard 360-degree-system, without changing the angle - only the way it's written? It would make it easier for me to work with.

Thanks

# Answer
You can multiply the result by (180/pi) to convert the magnitude to degrees. If it's negative then you would have to add 360 to it afterwards (assuming you want a range of 0 to 360.)

For example, -pi/2 becomes -90 after the multiplication, and adding that to 360 results in 270, which gives you the amount of degrees to rotate counter-clockwise from the positive x-direction to reach the point (which is what you're looking for I think.)
> 3 votes

# Answer
You can add 180 to your converted result to give a range of 0 to 360.
> 0 votes

---
Tags: 2d, mathematics, vector, geometry
---


# Question
Title: At same positioned game objects collision detection
In my game, I am creating two game objects at same position using Instantiate statement. Each generated object has box collider attached.

So I want to detect collision between them so I write following code.

```
void OnCollisionStay(Collision collisionInfo){
   print("on collision stay");
}

```

But this statement not called. I generate two object using following code.

```
BallUtility.AddNormalCommonBall (normalBallPref, Vector3.zero);
BallUtility.AddNormalCommonBall (normalBallPref, Vector3.zero);

```

I need help in collision detection. I already post question in unity forum but I didn't get any reply from there.

# Answer
> 2 votes
Collision events will only be detected under specific circumstances.

Each collider can be considered to have these relevant properties:

1. Is a **RigidBody** (or RigidBody2D) attached to it's GameObject, if not it is considered **Static**.
2. If it has a RigidBody, is it marked **Kinematic**?
3. Is the Collider marked **Trigger**?

The circumstances under which collisions are detected are summarized in this table:

Source

---
Tags: collision-detection, unity, gameobject
---


# Question
Title: Rotating object around moving object/player in 2D
I am trying to implement a camera which rotates around the world around the player. I have found many solutions online to the task of rotating an object about the origin, or about an arbitrary point. The procedure seems to be to translate the point to be rotated about to the origin, perform the rotation, translate back, then draw. I have gotten this working for rotation around the origin as well as for a fixed point. Rotation of objects around the player works as well, provided the player does not move. However, if the objects are rotated around the player by some non-zero degree, if the player moves after the rotation it causes the rotated objects to move as well. I probably have done a poor job explaining this so here's an image:

And here's the code for the behavior:

`renderx = (Ox - Px)*cos(camAngle) - (Oy - Py)*sin(camAngle) + Px;`

`rendery = (Ox - Px)*sin(camAngle) + (Oy - Py)*cos(camAngle) + Py;`

Where (Ox,Oy) is the actual position of the object to be rotated and (Px,Py) is the actual position of the player. Any ideas? I am using C++ with SDL2.0.

# Answer
You've already basically got the answer, your problem is the positioning of all objects is based off of the player, and when the player moves so do the objects in the world.

Instead, you need to change everything to be based off of a camera position. And when rotating the world, figure out how much the character was moved, and move the camera to compensate; this way the character doesn't look like it's moving, and the world is rotating around it.

I've whipped up a sample for you, and here it is: sketchpad.cc. Just hit play. :) In one editor I was experiencing issues in Chrome (Firefox works fine), though in this editor it seems to work okay; was having issues properly tracking the mouse with Processing.js.

---

Just like your function, I have a GetProjPos method, or Get Camera Space Position.
```
class GameCamera
{
    float   Rot;// Camera rotation
    PVector Pos;// Camera position

    void GetProjPos(PVector objectPosition)
    {
        return new PVector(
            objectPosition.x * cos(Rot) - objectPosition.y * sin(Rot) + Pos.x,
            objectPosition.x * sin(Rot) + objectPosition.y * cos(Rot) + Pos.y);
    }

```

All objects are drawn using this function. To handle rotation around the camera we need the player position before and after the rotation happens.

```
oldMouse = new PVector(pmouseX, pmouseY, 0);
newMouse = new PVector(mouseX, mouseY, 0);

oldMouseFromCenter = PVector.sub(oldMouse, cam.GetProjPos(P));
newMouseFromCenter = PVector.sub(newMouse, cam.GetProjPos(P));

if (newMouseFromCenter != oldMouseFromCenter)
{

```

Cross product helps us determine which side a vector is to another vector. This is used for determining which way to rotate the world, since angleBetween (which uses acos) returns a positive angle.

```
    sign = oldMouseFromCenter.cross(newMouseFromCenter).z >= 0 ? 1 : -1;

    oldPlayerPosition = cam.GetProjPos(P);

```

angleBetween uses the dot product to determine the amount of radians needed to rotate a vector to match another vector. The typical formula is like this: `angle = acos(v1.dot(v2)) / (v1.length() * v2.length())`

```
    cam.Rot += sign * PVector.angleBetween(oldMouseFromCenter, newMouseFromCenter);
    newPlayerPosition = cam.GetProjPos(P);

    deltaPlayerPosition = PVector.sub(newPlayerPosition, oldPlayerPosition);

```

And the amount the player moved in world position, just move the camera back by that amount so it doesn't look like the player moved.

```
    cam.Pos.sub(deltaPlayerPosition);
}

```

I'm sorry you didn't get this answer sooner, but I hope you find it useful. I know my example isn't in C++ and SDL, but you should be able to apply this easily enough.
> 1 votes

# Answer
I know you are using in SDL, but this will help you much, it is how it would be done in opengl.

ok let's start with the basics we have 4 coordinate systems and 3 matrices to translate between those coordinate systems. Coordinate system lower case, matrices upper case.

normalized device coordinates (ndc) Projection (P) camere space (cs) View(V) world space (ws) Model(M) object space (os)

ndc are the coordinates that opengl wants from you. Everythin beween (-1,-1) and (1,1) is visible, everything eles will be cropped out. cs are all coordinates relative to the camera (camera origin is (0,0) here). ws are coordinates in absolute world positions, so (0,0) is the origin of you world that never changes. and os are the vertices of your object, relative to the object origin (as we only use the object itself and do not process meshes, we only use (0,0) as input here). The matrices P,V,M are there to translate between those coordinate systems. They are all invertable.

eg lets take p=\[0;0\] or for opengl it would be \[0;0;0;1\] (extended coordinate system) and multiply it with P\*V\*M\*p. What comes out is the position of your player, in screen coordinates \[-1;-1;...\] is bottom left, \[1;1;...\] is top right corner. With (P\*V\*M)^-1 you can invert this process and take screen coordinates and make them relative to your object (if you know the dapth). So each object has it's own M, but V and P are constant for the entire frame

M encodes the position and orientation of your object

V encodes the position and orientation of your camera

P encodes the field of view and wheather you want orthogonal projection or not

if you understand this method, it will much easier for you to find out, that all you have to do is to apply a translation-around-an-axis matrix to your camera coordinates, and then extract V from this new rotated camera, and everything should work as expected.

To use Matrices in C++, you can use either Eigen, or glm, both do their job well.
> 0 votes

---
Tags: c++, 2d, camera, rotation, sdl
---


# Question
Title: How do I animate pieces between puzzle states?
I'm developing a simple C# puzzle game as a learning exercise, using OpenTK. It's similar to Puzzles and Dragons' puzzle part: The aim is to match 3 pieces to remove them. Removed pieces are replaced.

I have the puzzle part done such that matches are deleted and more pieces are added from the top. How can I animate tiles dropping from the top after rows/columns have been deleted? (You can see this happening about 4~5 seconds into the video on the website linked above.)

My idea was to create an "imaginary" board above the actual board so when tiles are deleted, I would in essence lower the imaginary board down, moving it further down on each frame. This brute force approach sounds like it could be done more easily with some APIs, but I've not had any luck with this.

Is there a better way to do these animations?

# Answer
This is a good use-case for a Model-View-Controller (MVC) architecture as often used in software engineering. Keep your *model* (board contents) and *view* (how does it look) as separate parts of your program.

# Motivating example

Say you have a board that looks like this:

You then delete the red pieces and want to animate the replacement pieces falling from above, down into their places:

Now your board is like this:

The MVC pattern suggests the *model* should only store board states () and not care how they are shown.

That's the *view*'s job. Based on the model and the current point in time, it creates images for a user to see and handles everything else about animations. It does this without changing the model at all, although it might store additional data.

# Implementation hints

In your *model*, you might store a `type` and unique `id` for each piece on a grid. Here's a 3x3 grid:

```
model = [
  [ { type : "blue",  id : 1 }, { type : "red",  id : 2 }, { type : "blue",  id : 3 }, ]
  [ { type : "red",   id : 4 }, { type : "red",  id : 5 }, { type : "blue",  id : 6 }, ]
  [ { type : "green", id : 7 }, { type : "blue", id : 8 }, { type : "green", id : 9 }, ]
]

```

The notation is pseudocode; `{...}` are objects containing `key : value` pairs and `[...]` are lists.

It's the same initial board state colours; we've just added numerical `id`s. *To my understanding, you've got this bit working, though maybe without IDs.*

The reason for the IDs becomes clear if we consider what happens when the model changes.

Here's a new board state:

```
model = [
  [ { type : "red",   id : 10 }, { type : "green", id : 11 }, { type : "blue",  id : 3 }, ]
  [ { type : "blue",  id : 1  }, { type : "green", id : 12 }, { type : "blue",  id : 6 }, ]
  [ { type : "green", id : 7  }, { type : "blue",  id : 8  }, { type : "green", id : 9 }, ]
]

```

This transition happened:

Now, a "dumb" view could ignore that anything happened at all and just continue happily drawing the new board state, without any animation.

However, a "clever" view which has been paying attention by storing a copy of the state, has enough information here to animate everything:

* The pieces with `id`s `3`, `6`, `7`, `8` and `9` have stayed where they were. There's no need to animate them.
* The piece `1` is there, but it's in a different position! We could animate it moving from its old position to the new one.
* The pieces `2`, `4` and `5` aren't there anymore. They could be animated by "shrinking out" or just disappearing.
* The pieces `10`, `11` and `12` are new. We can animate them falling in from off-screen above.

The "clever view" would then track which animations are happening and how far into each animation it is. Every tick, the view would advance all animations until they've all finished. (The details of this are all about interpolation. There are various interpolations you could use, but that's a different question's territory!)

---

I hope this is helpful. Ask about unclear parts!
> 8 votes

---
Tags: c#, animation, puzzle, opentk
---