# Question
Title: Designing PHP RPG game: Should I use multiple classes for each type of item or a single table?
I'm making a text-based role playing game written in PHP.

I have a hard time figuring out how to handle items in game - there will be a few types of objects (weapon, machine, tool, building etc) each of these types will have its own stats, attributes etc, and items itself.

My initial plan was to make a interface and abstract class called `Object`

```
interface IObject
{

   public function takeObject() {};
   public function dropObject() {};
   public function examineObject() {};
   // etc
}

abstract class WeaponObject implements IObject
{
   // Some generic properties valid for this type of objects
   public $name = "";
   public $weight = 0;
   public $damage = 0;

   // etc
}

```

and then make another class **for each item** that extends the base `Object`

e.g

```
class HuntingBow extends WeaponObject
{
   //
}

```

But there's a problem I think. There's going to be a lot of objects in the game - and that means a lot of classes, and composer need to load them all. So I think that performance may decrease significantly?

My second idea was to make a generic table called `objects`

In which I would store every item. But setting up object attributes, handling stats, etc, would be a nightmare.

Is the first idea the best way to approach the problem? Is there a better way of doing thins that I don't about?

# Answer
> 6 votes
A rule of thumb is that you use different classes when objects require different code and instances of the same class when the objects only require different values.

So when `ShortBow`, `HuntingBow`, `CompositeBow`, `ElvenBow` etc. all behave identical except for having different stats, then they would all be instances of the same class.

When bows have different mechanics for resolving attacks than other ranged weapons, that class would be `Bow`. When guns, crossbows and slingshots also use the same mechanics as bows do, they would all be class `RangedWeapon`. When you don't have any mechanical differences between ranged weapons and melee weapons, they would all be of class `Weapon`.

But in any case, when you have one really special bow with very unique mechanics, like `LordKibosMagicBowWhichAlwaysDoesCriticalDamageExceptOnThursdays` that might again justify an unique class which extends whatever class the other bows use.

---
Tags: browser-based-games, php, oop, browser
---


# Question
Title: How can I get an asset for my ObjectField?
I am trying to learn how to use ScriptableObjects. I have an `ObjectField`:

```
Foo myFoo = null;
myFoo = EditorGUILayout.ObjectField("My Foo", myFoo, typeof(Foo), true) as Foo;

```

I have a `Foo` in my Scene and in my Assets folder. In the editor, I can set `myFoo` to be the `Foo` in my Scene, but not my Assets folder. How can I get the prefab from my Assets folder?

(I have tried setting the allow scene objects to `false`, but I still can't find myFoo in the Assets folder.)

It allows me to drag and drop `myFoo` in from my Assets folder, but it doesn't stay there. If I use the Scene one, it does. But when I search for it in Assets, it is not there.

# Answer
> 1 votes
The "true" parameter that you have set is meant for allowSceneObjects, so you will be able to drag a scene object into that field, however I am unsure if passing your own type will always work.

From what I've seen it is only able to use type that Unity recognize, Transform, GameObject, TextAsset (which could be .txt, .cs, .ja), etc.

Also, your object in the Scene doesn't necessary share the same type of the one in your asset folder.

For instance, your could specify a MonoBehaviour attatched to a GameObject

```
MonoA myMonoA = null;
myMonoA = EditorGUILayout.ObjectField("My Mono A", myMonoA, typeof(MonoA), true) as MonoA;

```

and be able to drag it from the scene with a GameObject on which it is attached to.

However, if you drag and drop the same "MonoBehaviour" from your Asset folder `MonoA.cs` well, your out of luck, because in that case it is a `TextAsset`. So as you can see, the type don't match.

# Edit 1

For a prefab though, I was able to drag and drop using the `GameObject` or the `Object`. I guess you could want to drap and drop a prefab as an `Object` and later do `GameObject.Instantiate(thatObject);`

But even there, I'm not sure how you would detect the "real" type of the object dragged in with Unity. With `Object` I was able to drag a folder from the Project view, but his type seems to be DefaultAsset, so at that point it might be hard to know if what you've got is a folder or a prefab.

# Edit 2

Finding more way to do this, since I currently need something similar, there is the `AssetDatabase.GetAssetPath(myFoo)` function which returns you the full path of the Asset. I doubled checked, and it does returns the extension as well.

So if the object pass is a prefab, it would return /The/Full/Path/myFoo.prefab, if it's a folder it would return /The/Full/Path/myFoo or a script /The/Full/Path/myFoo.cs.

You could write your own file detection here to handle what you want, and set back myFoo object to null with a user message if that type isn't supported by your scriptable object.

---
Tags: unity
---


# Question
Title: Best practice/way for client to speak with server
I'm making a multiplayer game in HTML5 Canvas and Node using Express and Socket.io. It's a platformer style game and so far the players are able to see each other and move around on the screen. It works pretty well, but most of my game logic is client side which I believe might become a problem. The movement of other players at the moment isn't very smooth at all. So far, the only thing the server does is recieve the position and velocity of the players, and then broadcast it out to all the other players so they can see each other. I was wondering if there was a smarter way to go about this? Everything like collision detection, movement, key inputs etc is all used client side. Should this be server side instead? I could imagine that if I calculated things like collision detection and movement server sided, then there would be no way for the player to do things like edit their position via the browser console and change their size etc.

I hope it's not too complicated. I haven't written much code yet since I would like to make sure I do it the correct way from the start without having to change and rewrite a lot of code. Let me know if you'd like to see my code.

# Answer
Talking about online games - all logic/collision/actions should be manager on server. (because user is a cheater by default)

I understand that maybe one single unit jump with 50-100ms ping will looks weird (as websockets guarantee package delivery, but also a bit slower because works under http).

So let's imagine jump logic:

* user press space (or up) to jump
* unit immediately jump on client (just if your want super-fast feedback)
* also at the same time you sent "jump" message to server
* server-side unit also jump and broadcast it for all observers (including current user)
* each client overwrite unit info with server data.

so there is two ways:

* move all physic/logic to server
* move all physic/logic to server AND mirror it on client to get quick feedback

> moment isn't very smooth at all

For example my server tick is about 150 ms. Sometimes up to 200ms. So movements can't be smooth at all. But I solved it in render. I've made some analog of .animate() from old jquery (1.2 or something) and all changes becomes smooth.

Maybe it's a bit more complex for platformer, as it's not just a vector & speed, so here you should mirror some logic on server as on client.

But keep in mind - client vs. server - server always right, even when both doing the same.

I hope it will help :3
> 1 votes

---
Tags: html-canvas, server, node.js, client
---


title: Input before or after update/draw?

text:
# Question
Title: Input before or after update/draw?
This is how I understood the game loop, and I wanted to know if I'm correct or not:

```
1) Draw/render -> input
CPU    |    GPU
------------------
Update |
Draw   |
Input  | Rendering

2) Input -> Draw/render
CPU        |    GPU
------------------
Input      |
Update     |
Draw       |
(nothing?) | Rendering

```

By rendering I mean updating the actual frame. What happens in the second case? Is the CPU doing nothing or is it checking input for the next frame already? Are there any differences from checking input before or after the update/draw part?

# Answer
> 2 votes
Whether you input, update, render or render, input, update is irrelevant. The loop will restart, so there is no difference. Same with whether you input, update, draw or update, draw, input(which becomes input, update, draw under the same logic). Now, if your blocking at the end for a swap or frame-sync, then you may have input lag to rendering if you receive input before the waiting.

Hence, I always input, update, and then render.

# Answer
> -1 votes
If i was you, i should multithread the whole thing, having a renderthreat and a enginethreat or whatever you want to call it

---
Tags: opengl, sdl2
---


# Question
Title: How can I determine the size of my app store bundle?
I made a very simple game. It only has Facebook, and Twitter share icons but it does have Ad Networks SDKs and adapters. My entire folder that contains all the SDK's is currently 200mb. The inmobi SDK alone takes 40mb and it is pretty huge for a super simple game.

Do the files in these folders contribute to the size of my app? Will this be the final app size when submitted on the appstore?

# Answer
Just in case people have doubt regarding the difference in size of the binary before uploading to iTunes and after uploading to iTunes here is the calculation:-

Apple is encrypting the executable file. By doing so its size doesn’t change much but its contents do which usually can no longer be compressed as much as before. By putting all this together i came up with a way to calculate the maximum size of your App in the App Store (it will most likely be less than this):

```
open the .app bundle via right-click -> Show Package Contents (on Mac)
locate the executable file and remember its (uncompressed) size (Size “A”)
delete the executable from the bundle
zip the bundle and remember the bundle’s compressed size (Size “B”)

```

Size “C” are the 100 KB from the additional files added to the bundle by Apple. The final calculation for the maximum size of your App is as follows:

A + B + C = maximum size of your App after approval

The calculation put in words:

(uncompressed executable size) + (app bundle compressed but without executable) + 0,1 MB = maximum size of your App after approval
> 1 votes

---
Tags: ios, appstore
---


# Question
Title: Where should I save game object's attributes (hp, score) in Swift?
**Scenario:** I have a game with several game objects on screen. Each can have different score and hitpoints. When I use collision detection for cannonball vs. ship (example) I need to know which ship is hit and how much hitpoints it has.

**Problem:** I had several approaches from extending `SKSpriteNode` or `SKPhysicsBody` but all failed. SKSpriteNode doesn't work, because Swifts collision detection only returns physicsBody and since you can't extend physicsBody, it didn't work to save there ships attributes as well.

**Question:** What would be a good approach to save such data to my game objects? I do not need code - because I think I can write it myself - but I would be happy to read a good suggestion. But if you have already some code written and a good solution for this problem, I would not be angry to read it ;)

# Answer
Use the SKPhysicsBody instances as keys to a dictionary of game objects. When you want to process a collision, retrieve the game object associated with the physics body from the dictionary. Not as efficient as the direct link you sought, but more than sufficient for most purposes.
> 1 votes

# Answer
Try Using

**NSUserDefaults** it has the full CRUD functionality and you can save each ship type with their specific hit points and cannonball

More description about NSUserDefaults is **Here**
> -1 votes

---
Tags: collision-detection, gameobject, spritekit, swift
---


title: Game state management techniques?

text:
# Question
Title: Game state management techniques?
First off, I'm not referring to scene management; I'm defining game state loosely as any sort of state in a game which has implications about whether or not user input should be enabled, or if certain actors should be temporarily disabled, etc.

As a concrete example, let's say it's a game of the classic Battlechess. After I make a move to take another player's piece, a short battle sequence plays. During this sequence, the player shouldn't be allowed to move pieces. So how would you track this sort of state transition? A finite state machine? A simple boolean check? It seems the latter would only work well for a game with very few state changes of this sort.

I can think of a lot of straightforward ways of handling this using finite state machines, but I can also see them quickly getting out of hand. I'm just curious if there's a more elegant way to keep track of game states/transitions.

# Answer
I once came across an article that solves your problem quite elegantly. It is a basic FSM implementation, that is called in your main loop. I have outlined the basic rundown of the article in the rest of this answer.

Your basic game state looks like this:

```
class CGameState
{
    public:
        // Setup and destroy the state
        void Init();
        void Cleanup();

        // Used when temporarily transitioning to another state
        void Pause();
        void Resume();

        // The three important actions within a game loop
        void HandleEvents();
        void Update();
        void Draw();
};

```

Each game state is represented by an implementation of this interface. For your Battlechess example, this could mean these states:

* intro animation
* main menu
* chess board setup animation
* player move input
* player move animation
* opponent move animation
* pause menu
* endgame screen

States are managed in your state engine:

```
class CGameEngine
{
    public:
        // Creating and destroying the state machine
        void Init();
        void Cleanup();

        // Transit between states
        void ChangeState(CGameState* state);
        void PushState(CGameState* state);
        void PopState();

        // The three important actions within a game loop
        // (these will be handled by the top state in the stack)
        void HandleEvents();
        void Update();
        void Draw();

        // ...
};

```

Note that each state needs a pointer to the CGameEngine at some point, so the state itself can decide whether a new state should be entered. The article suggest passing in the CGameEngine as a parameter for HandleEvents, Update and Draw.

In the end, your main loop only deals with the state engine:

```
int main ( int argc, char *argv[] )
{
    CGameEngine game;

    // initialize the engine
    game.Init( "Engine Test v1.0" );

    // load the intro
    game.ChangeState( CIntroState::Instance() );

    // main loop
    while ( game.Running() )
    {
        game.HandleEvents();
        game.Update();
        game.Draw();
    }

    // cleanup the engine
    game.Cleanup();
    return 0;
}

```
> 24 votes

# Answer
I start by handling this sort of thing the simplest way possible.

```
bool isPieceMoving;

```

Then I'll add the checks against that boolean flag in the relevant places.

If I later find I need more special cases than this - and only it - I re-factor into something better. There are usually 3 approaches I'll take:

* Refactor any exclusive substate-representing flags into enums. eg. `enum { PRE_MOVE, MOVE, POST_MOVE }` and add the transitions wherever needed. Then I can check against this enum where I used to check against the boolean flag. This is a simple change but one which reduces the number of things you have to check against, allows you to use switch statements to manage behaviour effectively, etc.
* Switch off individual subsystems as you need to. If the only difference during the battle sequence is that you can't move pieces, you can call `pieceSelectionManager->disable()` or similar at the start of the sequence, and `pieceSelectionManager->enable()`. You still essentially have flags, but now they're stored closer to the object they control, and you don't need to maintain any extra state in your game code.
* The previous part implies the existence of a PieceSelectionManager: more generally, you can factor out parts of your game state and behaviour into smaller objects that handle a subset of the overall state in a coherent way. Each of these objects will have some of its own state which determines its behaviour but it's easy to manage since it's isolated from the other objects. Resist the urge to allow your gamestate object or main loop to become a dumping ground for pseudo-globals and factor that stuff out!

Generally speaking I never need to go any further than this when it comes to special-case substates, so I don't think there is a risk of it 'quickly getting out of hand'.
> 2 votes

# Answer
http://www.ai-junkie.com/architecture/state\_driven/tut\_state1.html is a lovely tutorial to game state management! You can use it either for game entities or for a menu system like above.

He starts teaching about the State Design Pattern, and then goes on to implement a `State Machine`, and successively extends it further and further. It's a very good read! Will give you a solid understanding of how the whole concept works and how to apply it to new types of problems!
> 2 votes

# Answer
I try not to use state machine and booleans for this purpose, because both are not scalable. Both turn into mess when number of states grow.

I usually design the gameplay as a sequence of actions and consequences, any game state just come naturally without a need to define it separately.

For example in your case with disabling player input: you have some user input handler and some ingame visual indication that input is disabled, you should make them a one object or component, so to disable input you just disable the whole object, no need to synchronize them in some state machine or react to some boolean indicator.
> 1 votes

---
Tags: state
---


# Question
Title: What are these odd distortions on far away textures?
I'm currently writing a simple voxel engine just to get some practice in, and I'm coming across some odd issues. In order to generate terrain, I create a mesh and then assign UV coordinates on a texture atlas to each vertex. Whenever I run the game, I get strange distortions, like these:

I've tried doing a few things so far:

* Generating mip maps for the texture atlas.
* Play around with the max size of the texture atlas.
* Play around with the format of the texture atlas.

Unfortunately, none of these have worked so far. As of right now, the import settings on the texture atlas itself look like this:

Is there any way I can get rid of these obnoxious distortions?

# Answer
> 6 votes
This distortion pattern is an aliasing artifact caused by point sampling the wrong mip level of a texture. Change the "Filter Mode" from "Point" to bilinear, and make sure to check "Generate Mip Maps". (There is rarely a good reason to disable mip-map generation.) As some have suggested in the comments, anisotropic filtering will work even better to eliminate this kind of artifact.

The problem is caused because at a distance each square in the checkerboard pattern is almost, but not quite, the width of a screen pixel. The pattern of texture samples overlaid on the texture checkerboard pattern gives rise to a new visual pattern. Mip maps and anisotropic sampling will cause the GPU to average together neighboring texels so that distant pixels blend to green instead of generating a pattern.

Here's an article with images that explain what you're seeing: https://paroj.github.io/gltut/Texturing/Tut15%20Anisotropy.html

---
Tags: graphics, unity, mesh
---


# Question
Title: How do I change a LÖVE2D game executable's icon?
I merged my `game.love` file and the `love.exe` with the command `copy /b love.exe+app.love game.exe`. But the resulting executable has the default LÖVE2D icon.

Is there a way to change that icon to another one?

# Answer
I don't know much about Love so I don't know if there is a built-in way, but you can change the icon of an executable file using a variety of icon editing software. Last time I did this in days of yore my weapon of choice was IconForge but I'm sure there are other tools available now (like these).
> 3 votes

# Answer
The steps below are also covered in a video tutorial (icon topic starts at 2:22).

1. Create an .ico file using GIMP, you can use the `game.ico` or `love.ico` included in the 32bit redistributable of LÖVE as a template.
2. Rename your `.exe` file to `nonsense.exe` (explanation below).
3. Drag the `.exe` file into Resource Hacker, unfold `Icon Group` and right-click the only item in it. Select "Replace icon ..." and select the `.ico` file you created.
4. Press Save (floppy disk icon).
5. You might not see the change yet. Rename `nonsense.exe` to `yourgamename.exe` and it should become visible.
> 2 votes

---
Tags: windows, lua, love2d
---


# Question
Title: How does "Additional Design" or "Additional Programming" differ from just "Design" or "Programming?"
In the credits of video games there are often separate headings for "Additional Programming", "Additional Design" or "Additional Art"- often containing the names of people who work in other departments. What is the need for this separation and how do "Additional" developers differ from the "regular" ones. Does this imply that people from other departments do design/programming/animation as well?

# Answer
> 4 votes
In the movie business, professionals often belong to guilds (actors, writers etc.) who collectively bargain for exactly how their members are compensated, including credits. The rules are quite comprehensive. On the other hand, there are no such fixed rules for the games industry. Instead, some companies create their own rules on how to write credits and who deserves them. Obviously, this leaves a lot of people unhappy.

There are efforts to standardize the credits; IGDA have a group working on a game crediting guide. As of writing this is still in draft form and is supposed to be a "recommendation" only, but it can give us some clues on what those credits might mean. Here's the relevant section:

> 1-3. For non-Leads, if the contribution consists of less than 40% or eight months (whichever is least) of the project’s total workdays in development, then the credit may be listed in a lower tier, e.g. “Additional Programming.”

But none of this is industry standard, so yes it could also mean whatever they want.

# Answer
> 1 votes
It means whatever the company *wants* it to mean.

There are no mandated crediting standards in this industry, and so just as the precise meanings of job titles differ from studio to the studio, the precise meanings associated with credits terminology vary as well. In fact, it can often vary from product to product, even within the same studio.

The "additional" prefix could mean a variety of things:

* As you surmise, it could mean the people in question have "official" job titles other than what they are being credited for.
* It could mean the people in question were contractors, as opposed to full-time employees.
* Similarly, it could mean that the people in question were from another division of the company (particularly in the case of large companies that actually own multiple independent studios).
* It could mean the people in question did not work full-time on the *project*, but were perhaps called in to do some fire-fighting during critical milestones or similar.
* It could mean the people in question were not full-time employees at the time the credits were finalized (typically when the game is considered "gold," or shippable), but worked sufficiently long on the project prior to their departure to still receive some form of credit.
* It could mean the people in question have names longer than 15 letters.

That last one is unlikely, of course, but I include it simply to underscore how arbitrary credits can be.

---
Tags: terminology
---


# Question
Title: Applying texture inside of an Icosphere?
I have implemented a code to generate an Icosphere procedurally in Unity 5.3.4f, which works pretty well. However, what I need to do know it tweak the code to make the sphere to receive texture only in its inside triangle-faces, not outside. Searching trough the Unity forums, many have said that it's simply the case of flipping the normals of all triangles (i.e. multiplying them by -1). I tried it and it is not the case.

What is the correct way of changing the triangles (not trough shaders) so the Icosphere mesh can only be textured inside (e.g. in a skydome)?

EDIT: After Kromster's answer, I did some research and ended up implementing the following code:

```
Mesh InvertMeshFaces(Mesh _mesh)
{

    //Flip the triangles
    int[] triangles = _mesh.triangles;

    int numtriangles = triangles.Length / 3;
    for (int t = 0; t < numtriangles; t++)
    {
        int temptriangle = triangles[t * 3];
        triangles[t * 3] = triangles[(t * 3) + 2];
        triangles[(t * 3) + 2] = temptriangle;
    }

    //reseting the UV
    Vector2[] uvs = _mesh.uv;
    for (int uvnum = 0; uvnum < uvs.Length; uvnum++)
    {
        uvs[uvnum] = new Vector2(1 - uvs[uvnum].x, uvs[uvnum].y);
    }

    //reseting normals
    Vector3[] normals = _mesh.normals;
    for (int normalsnum = 0; normalsnum < norms.Length; normalsnum++)
    {
        norms[normalsnum] = -norms[normalsnum];
    }

    //setting the new values of triangles, normals and UVs
    _mesh.triangles = triangles;
    _mesh.uv = uvs;
    _mesh.normals = normals ;

    return _mesh;
}

```

So far, it works only partially. Applying that function to my Icosphere mesh, now it is possible to see the sphere rendered when camera is inside it. However, oddly enough, it's still also possible to see the sphere from outside. It means, both inside and outside are visible - the outside is not culled as expected.

# Answer
> 1 votes
To change polygons orientation you need to change indices order, so that faces are facing in different direction. From clockwise to counter-clickwise (or vice versa, it depends on your graphics engine setup). Change every triangle indices order from being 1-2-3 to 1-3-2.

---
Tags: textures, geometry, uv-mapping, normals
---


title: How can I min-max quaternions?

text:
# Question
Title: How can I min-max quaternions?
## What I'm doing

In my engine, I'm trying to implement a camera that will follow a target object, such as a player.

I wanted to avoid just simply using the inverse of the target's transformation, because the camera may end up "jerky", so instead I interpolate between the current and target orientation over time, this way the camera's rotation eases in on the desired rotation:

```
quat targetQuat   = target->getOrientation();
quat currentQuat  = getOrientation();

quat slerpQuat    = glm::slerp(currentQuat, targetQuat, 0.05f);

setOrientation(slerpQuat);

```

---

## Where my problem begins:

Since I'm just interpolating between quaternions, it is possible that the target may spin faster than the camera can catch up, and may wind up falling behind.

I want to somehow impose a quaternion rotation cap, or somehow determine which of the two is larger so I can min/max 2 quaternions. For example:

```
quat targetQuat   = target->getOrientation();
quat currentQuat  = getOrientation();

quat slerpQuat    = glm::slerp(currentQuat, targetQuat, 0.05f);
quat maximumQuat  = targetQuat*quat(0.707, 0, -0.3535, 0);

quat desiredQuat  = min(slerpQuat, maximumQuat);

setOrientation(desiredQuat);

```

How can I determine which of two quaternions rotates/deviates the furthest? Are there any better alternatives methods? The general idea I had was just to min/max the quat such that it always falls within the bounds I need.

I know that I can calculate a delta quaternion, or rather multiply q0 by inverse q1, but even so I don't know what I would do with it or how it could inform me which of the two is the largest one.

# Answer
> 2 votes
Alright so I figured out an even more ideal solution.

The way I was trying to solve the problem was going to lead to more issues than I needed to deal with, so instead I slept on the problem and thought up a different approach.

Instead of trying to min-max my orientation, I now calculate how far from the target orientation the camera is, If it lays above a certain threshold, I lerp the camera's quat against the targets quat, by an amount that would return it to that threshold.

1. Calculate the angle between the camera and the target (between 0-1, where 1 = 180°)
2. If the angle is greater than a specified amount, go to step 3
3. Divide the desired angle by the current angle
4. We now know how far we have to lerp from the camera to the target in order to return to the maximum desired value.

The advantage of this is that the camera is given a specified "cone" of freedom to smoothly move around in, which the camera will drag along the edge of instead of falling behind (imagine a funnel with a stick in it).

---

To constrain my camera's orientation by an angle of 45° from the target, I do the following:

```
float getAngleBetween(quat q1, quat q2)
{
    float theta = acosf(q1.w*q2.w + q1.x*q2.x + q1.y*q2.y + q1.z*q2.z);
    if (theta > M_PI_2)
        theta   = M_PI - theta;
    return theta;
}

void DCamera::update()
{
    quat targetQuat      = glm::normalize(target->getOrientation());
    quat currentQuat     = glm::normalize(getOrientation());

    // Angle between the camera and the target
    float angle          = getAngleBetween(targetQuat, currentQuat);
    const float maxAngle = 0.25f;

    // If the angle is greater than 45 degrees
    // (0-1 range == 0-180, thus 0.25 = 45)
    if (angle > maxAngle) {
        // Inteprolate a quaternion between the camera and the target
        // The mixing amount is the desired angle divided by the total angle in this range
        setOrientation(glm::slerp(targetQuat, currentQuat, maxAngle / angle));
    }
}

```

So if my camera is 135 degrees away from the target, and the maximum allowed angle is 45 degrees in any direction, then we rotate the camera straight towards the target by 90 degrees.

# Answer
> 2 votes
I bit on the mathematical side, but here's a Q & A on MSE on computing quanternion distance. Using that you could do something like:

```
quat targetQuat   = target->getOrientation();
quat currentQuat  = getOrientation();

quat lerpQuat     = glm::lerp(currentQuat, targetQuat, 0.05f);
quat maximumQuat  = targetQuat*quat(0.707, 0, -0.3535, 0);

float d1 = quant_dist(currentQuat, lerpQuat);
float d2 = quant_dist(currentQuat, maximumQuat);

if(d1 < d2){
   desiredQuat = lerpQuat;
}
else{
   desiredQuat = maximumQuat;
}

setOrientation(desiredQuat);

```

# Answer
> 0 votes
If I understand your question, you want to limit the rotational velocity of a turn?

Get the delta.

From your rotation delta, you can find out how many radians of turn it represents from the S element (or sometimes called W element). The S element is `cos(rotationAmt / 2)`, so can be extracted as `rotationAmt = acos(deltaQuaternion.s) * 2`.

From there you could clamp the radians-per-tick movement amount. Like:

```
rotationAmt = acos(deltaQuaternion.s) * 2.0;
if(rotationAmt > maxRadiansPerTick)
{
    rotationAmt = maxRadiansPerTick;
    deltaQuaternion.s = rotationAmt;

    // renormalize it
    deltaQuaternion = normalizeQuat(deltaQuaternion);
}

```

(Ok, I have not run this code. Also it might need to handle negative rotationAmt, if your quaternions are flipped or anything. But that's the gist of it.)

# Answer
> 0 votes
The idea of measuring the distance between quaternions is indeed a useful similarity measure.

In essence, what you can measure the *dot product* between two quaternions `qA` and `qB` just as you compute the dot product of two vectors (see this). Moreover, since you have unit quaternions (they do represent rotations!), the dot product should be between \[-1,1\]. The more similar your quats are (i.e. closer), the larger the dot product value (i.e. closer to 1).

Refer to the image below. The `A` arc on the unit (hyper)sphere is the path taken by the slerp. The length of `A` is actually the distance between your quats and is equal to the angle between them (computable, but not directly required, from the dot product).

The slerp is also a pretty good equivalent to normal lerp, but on curved spaces (the unit hypersphere). So if you have two quantities, `qA` and `qB` and you want to produce a value `qT` such that `qT` starts from `qA` and moves towards `qB`, the slerp is going to do that. All you need to make sure is that the slerp interpolation parameter (`t` between \[0,1\]) traverses the \[0,1\] interval. If your `qB` quaternion does not remain constant over time, you must restart the slerp from by setting `qA = qT` (the current orientation becomes the start of a new slerp), while `qB` is your new target orientation. If you want to have your camera trace the target orientation in a fixed amount of time, you must restart the tracing be setting `qA` to your current camera orientation and `qB` to the new target orientation (assuming the target has rotated at all).

Summarizing this all in an algorithm:

```
OnTargetRotationSet(qNew) // called when you (re)set the target orientation
{
   qTarget = qNew;
   if (dot(qCam, qTarget) < 1 - epsilon)
   {
      camAlignInProgress = true;
      qStart = qCam;
      qEnd = qTarget;
      slerpParam = 0;
      slerpLength = ComputeAngleBetween(qCam, qTarget) / 3.141592;
      slerpSpeed = slerpLength / totalTimeToPerformAlignmentInSeconds;
   }
 }

 OnGameStep() // called/triggered somewhere in your game loop before rendering anything
 {
    if (rotationInProgress == false)
       return; // no need to align the camera with target
    if (slerpParam >= 1.0)
    {
       qCam = qTarget; // snap to target
       rotationInProgress = false;
       return; // end the alignment procedure
    }

    qCam = QuatSlerp(qStart, qEnd, slerpParam);
    // advance on the hypersphere
    slerpParam += slerpSpeed * Game.GetCurrentDeltaTime();
 }

```

---
Tags: camera, rotation, quaternion, lerp, orientation
---


title: C# XNA :Snake Game, direction problem

text:
# Question
Title: C# XNA :Snake Game, direction problem
I am trying to do a snake game in XNA but I have some little problems...

I explain :

The Snake has a direction (Enum Type : Haut(=up), Bas(=down), Droite(=right), Gauche(=left)) When the player press a direction key this funcion is used :

```
public void SetDirection(Direction newDirection) // Teste les directions impossibles => impossible de faire un demi tour
{
    if (_direction == Direction.Haut && newDirection == Direction.Bas)
    {
        return;
    }
    else if (_direction == Direction.Bas && newDirection == Direction.Haut)
    {
        return;
    }
    else if (_direction == Direction.Gauche && newDirection == Direction.Droite)
    {
        return;
    }
    else if (_direction == Direction.Droite && newDirection == Direction.Gauche)
    {
        return;
    }
    _direction = newDirection;
}

```

In theory, the snake can't make a U-turn. But it does not work properly (I will try to explain why) :

The snake moves each 100ms. while these 100ms, the snake is waiting for a direction. BUT if the snake goes up for example, and if the user presses {Droite(=right), Bas(=down)} or {Gauche(=left), Bas(=down)} while these 100ms, the snake makes a U-turn, and die because he cuts himself.

As a consequence, the user loose the game...

I can't see how to solve this problem.

If I am not clear or if you need any other information, please let me know.

Thanks in advance for your help

PS : I am sorry for the grammar faults but I don't speak perfectly english... :)

PPS : Here is the call to setDirection :

```
case GameState.Infini:
    if (newKeyboardState.IsKeyDown(Keys.Escape))
    {
        CurrentGameState = GameState.Pause;
    }
    else if (newKeyboardState.IsKeyDown(Keys.Up))
    {
        _snake.SetDirection(Direction.Haut);
    }
    else if (newKeyboardState.IsKeyDown(Keys.Down))
    {
        _snake.SetDirection(Direction.Bas);
    }
    else if (newKeyboardState.IsKeyDown(Keys.Left))
    {
        _snake.SetDirection(Direction.Gauche);
    }
    else if (newKeyboardState.IsKeyDown(Keys.Right))
    {
        _snake.SetDirection(Direction.Droite);
    }

```

# Answer
I finally succeeded to get rid of this behaviour. (Thanks @Jon !)

"Don't let the snake change its direction if it heads backward from its current heading. " It actually works :)

Example with 'Up' Direction :

```
int X = _snake._parts.Last().X;
int Y = _snake._parts.Last().Y;
if (newDirection == Direction.Haut)
{
    Rectangle test = new Rectangle(X, Y - _blocCorps.Height, _blocCorps.Width, _blocCorps.Height);
    if (test.Intersects(_snake._parts.ElementAt(_snake._parts.Count - 2)))
    {
        return;
    }
}

```

Thank to everyone who took some time to help me !
> 1 votes

# Answer
Not sure if this will work but I did a few tests and it seems to be fine. Define your enum like this :

```
enum Directions
    {
        Up = 1,
        Down = ~Up,
        Right = 2,
        Left = ~Right
    };

```

Now you can a check about the current direction and next direction like this

```
    if(currDit == ~nextDir)
    {
    //the snake will go into itself
    }else
    {
    //change the direction
    }

```

Again I'm not 100% sure that this will work. Someone correct me if I'm wrong.
> 0 votes

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


# Question
Title: Play and Stop Animation on Condition - Unity
I've applied a scale animation on Play button of my game. I want to stop animation when play button is not interactable. It stops playing animation, but animation is not playing again, even when play button gets interactable. Here is my snippet to Play and Stop Animation.

```
if (!PlayButton.GetComponent<Button> ().IsInteractable()) {
    PlayButtonAnimator.Stop ();
} else if (PlayButton.GetComponent<Button> ().IsInteractable()) {
    PlayButtonAnimator.Play ("Play_Button_Animation");
}

```

What should i do to play animation again. Thanks in advance :)

# Answer
> 1 votes
Not sure if this is the exact answer but instead of doing a `PlayButtonAnimator.Stop()`you could add a `New State` into the animator and call `PlayButtonAnimator.Play ("New State")` when the button is not insteractable.

```
if (!PlayButton.GetComponent<Button>().IsInteractable())
{
    animator.Play("New State");
}
else if (PlayButton.GetComponent<Button>().IsInteractable())
{
    animator.Play("Play_Button_Animation");
}

```

---
Tags: unity, animation
---


# Question
Title: How to combat exponential growth in sprite messaging?
In my 2D platformer game, I have a number of sprites moving around the world. When two sprites collide with each other, I calculate how deep the collision is and then call a virtual method on both sprites that lets them handle the collision (for instance, a fireball would kill the other sprite).

Each sprite is checked for collision against each other sprite "near" it. "Nearness" is determined through my lazy Quadtree which is really just a list of evenly-sized cells that objects are sorted into.

However, the number of virtual method calls (or messages) increases exponentially with the number of sprites colliding at once, leading to \<1fps with only about 120 sprites onscreen. If three sprites overlap each other, six messages need to be send. Four sprites need 12 messages, and twenty sprites need 380.

Just checking for collisions can be costly, even with the game world being divided into cells - if 30 sprites are in the same cell, 900 collision checks are required.

Now, I don't expect 120 onscreen sprites to be the norm - it'd probably be closer to 20, but I'm really concerned with how little range there is between playable and slideshow.

I strongly suspect that if I really want each sprite to message each other, there's no way to do any better than `N*(N-1)/2` messages. Is there anything I can do to reduce the costs?

**Edit:** On request, here's the relevant code:

```
foreach (var collidableSprite in Sprites.GetItemsNearItem(sprite))
{
    if (Object.ReferenceEquals(collidableSprite, sprite)) { continue; }

    BoundingRectangle hitboxA = sprite.Hitbox;
    BoundingRectangle hitboxB = collidableSprite.Hitbox;

    Vector2 intersectA = hitboxA.GetIntersectionDepth(hitboxB);
    Vector2 intersectB = hitboxB.GetIntersectionDepth(hitboxA);

    if (!intersectA.IsNaN() && !intersectB.IsNaN())
    {
        sprite.HandleSpriteCollision(collidableSprite, intersectA);
        collidableSprite.HandleSpriteCollision(sprite, intersectB);
    }
}

```

Essentially, for each sprite in the world, for each sprite near this sprite (in the same grid cell(s)), check to see if there's an intersection and how deep it is. If there is, call the collision handlers on both sprites.

```
internal IEnumerable<T> ItemsInCells(SparseCellRange range)
{
    foreach (T item in items)
    {
        if (GetCellsItemIsIn(item).Equals(range))
        {
            yield return item;
        }
    }
}

internal IEnumerable<T> GetItemsNearItem(T item)
{
    SparseCellRange range = GetCellsItemIsIn(item);

    return ItemsInCells(range);
}

```

Here's the code that checks for nearness. The `SparseCellRange` is a pair of `Vector2` instances for `TopLeft` and `BottomRight` cell numbers.

# Answer
> 1 votes
Check broad-phase collision detection. Example link

That would reduce the collision detection cost. Then figure out WHAT causes your performance drop. Virtual method calls themselves are not that expensive - 1000 of them in a frame will definitely NOT cause a slideshow. Perhaps the message system is slow? The message creation copies data by value? etc etc.

---
Tags: c#, collision-detection, monogame, performance, entity-system
---


# Question
Title: Swift - How do I detect the exact point at which two "SKPhysicsBody(edgeFromPoint:" type physics bodies intersect in sprite kit
I have two physics bodies attached to two separate sprite nodes using Sprit Kit. One is a vertical line and one is a horizontal line:

```
//sprite with horizontal physics body
spriteMatrix[i][j].physicsBody = SKPhysicsBody(edgeFromPoint: CGPointMake(0, tileSegmentHeight), toPoint: CGPointMake(tileSegmentWidth, tileSegmentHeight))
spriteMatrix[i][j].physicsBody!.categoryBitMask = self.surfaceCatagory
spriteMatrix[i][j].physicsBody!.contactTestBitMask = heroCatagory

//sprite with vertical physics body
self.hero.physicsBody = SKPhysicsBody(edgeFromPoint: CGPointMake(self.hero.frame.width / 2, self.hero.frame.height / 2), toPoint: CGPointMake(self.hero.frame.width / 2, -20))
self.hero.physicsBody!.categoryBitMask = heroCatagory
self.hero.physicsBody!.contactTestBitMask = surfaceCatagory

```

What I'm want to do is test if they are intersecting on every frame, and if they are, return the x and y position of where they are intersecting. Is this even possible?

# Answer
You are not using **collisionBitMask** The class reference can be found Here

A example of code is Here which also explains very well how collisionBitMask works
> 1 votes

# Answer
This is not possible. Apparently, only a dynamic volume physics body can make contact with an edge body. I do not like this about Sprite Kit.
> 0 votes

---
Tags: collision-detection, ios
---


# Question
Title: How can I use a data grid to make an isometric turn based game in GameMaker?
I am making a Hero Quest clone. It is a turn based adventure game with an isometric view point. So far I have been able to turn a 2D map into an isometric view but I believe I need to use a data grid to achieve turn based movement, combat etc.

There are plenty of tutorials on data grids but none that I can find on how to translate a 2D grid to a psedo-3D isometric game.

How could I do it?

# Answer
> 2 votes
Using a data structure to save level data is a good idea, as there are many games using voxel engines to deal with this kind of information.

A **voxel engine** is essentially an engine that stores level data into an appropriate data structure (a list, a grid, or even a 3D matrix as Minecraft does), and uses it to recreate levels in your game. Voxel engines are commonly used in 3D games, but you can take advantage of the idea behind it to apply into your own game.

Let's start with an easy example: chess. A chessboard is a 8x8 grid, on which pieces are moved and placed (also, it's turn-based like your game). You can have plenty of different chessboards in the world, with different sizes and colours. But they have one thing in common: *coordinates*. You can always replay a chess game on any chessboard, because they all share the same coordinate system and pieces assets.

As you can see, this is a simple example where game "logic" and game "rendering" are separated: chess rules are independent from the chessboard style and design, as long as there's a reference to a 8x8 grid on them.

That's the strategy you can follow. If your level consists of an isometric map where you can define a certain number of horizontal and vertical tiles, the only thing you need to do is mapping these tiles to an appropriate allocation in a `ds_grid` data structure.

### A simple grid

Let's say we want to create a diamond-shaped level, and we consider a grid data structure to store information about tiles: the indexes in the data structure are multiplicated times the width/height to fit our graphic resources in the room (plus any offset). Data stored in `grid[0,0]` will be placed in our room at position `(0,0)`, whereas the data `grid[0,1]` \- which is the neighbor tile on the left, will be placed at position `(0,1*tile_width)`, so `(0,tile_width)`.

To see a possible result, consider the following 6x6 grid where `0` means grass and `1` is a solid wall:

```
1 1 1 1 1 1
1 0 0 0 0 1
1 0 0 0 0 1
1 0 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1

```

Using the appropriate function to map data to 2D tiles, that's the result:

Once you fix the `(0,0)` position in your world, all other tiles are positioned relative to this one.

You can find many tutorials on Youtube to get started with isometric design.

# Answer
> 1 votes
Usually when you work with an isometric perspective all the data and logic is still done in normal 2D and then you translate it to isometric.

Especially if you do a grid based game cause the grid is actually the same. The only difference is how it's drawn. Like in most isometric games the tile in the top end has the index (0,0) and then, depending on how you sort, the tile down to the right has index (1,0) and so on which give you a normal 2d grid to have the data and logic on.

---
Tags: isometric, grid, game-maker
---


# Question
Title: Does "Object.ToString().GetHashCode()" return a truly unique character seed?
In my game I'm generating a character seed from a bunch of traits that the player chooses. The traits are all part of a Enum. In unity I've attached a script to a bunch of toggles. When the player selects a toggle I do this : `charGen.testCharHash += trait.ToString().GetHashCode();` Does this guarantee that I will have a unique number generated based on the players choice ?

# Answer
> 26 votes
Hash codes are never guaranteed to be unique. Also, you do not get a guarantee that adding hash-codes gets you an unique value which does not collide with a different combination of hash-codes.

The usual solution to identify a combination of on/off flags is to use a bitfield.

Assign manual integer values to your enum which are all powers of two:

```
[Flags] // optional attribute which tells the compiler that this is a bitfield
enum CharacterTraits {
    TRAIT_ONE = 1,
    TRAIT_TWO = 2,
    TRAIT_RED = 4,
    TRAIT_BLUE = 8,
    TRAIT_BLACK = 16,
    TRAIT_OLD = 32,
    TRAIT_NEW = 64,
    ...
}

```

When you look at these values in binary, you will notice that they all just have a single bit set. When you simply add a combination of these values together, you will always get an unique integer. Bitfields also have other useful properties when used with bitwise operators. For example:

```
 if (character.traits.HasFlag(CharacterTraits.TRAIT_TWO)) { ... }

```

will trigger when the trait combination of the character has the bit for TRAIT\_TWO set.

To set traits:

```
character.traits = CharacterTraits.TRAIT_ONE | CharacterTraits.TRAIT_BLACK;

```

To add a trait:

```
character.traits |= CharacterTraits.TRAIT_BLUE;

```

To remove traits:

```
character.traits &= ~CharacterTraits.TRAIT_BLUE;

```

An enum is backed by an `int` by default, so you get up to 31 traits that way (one bit is lost because of negative values). You can increase that to up to 64 by declaring it as `enum CharacterTraits : ulong {`. Should you need more than 64 traits, you need to look for a different solution, like an array of `bool`.

# Answer
> 4 votes
As Phillipp said, HashCodes do not guarantee uniqueness. In fact they pretty much don't guarantee anything.

What you seem to want to do is to generate a unique number from a unique string. How to do that generically is answered in this question: How can I generate a GUID for a string?

If you just want a unique identifier which is allowed to differ even for the same input, you can use `Guid.NewGuid()`.

# Answer
> 2 votes
It might be useful to note that while it is not *guaranteed* to be unique, your original approach is still going to work in practice with small amounts of traits, and a collision would not even have disastrous consequences if it happened.

The chance that some combination of hashes will match the hash some other trait is n!/2^32 (for a 32-bit hash), which is almost 0 for n=10, but becomes significant at 15-20 traits.

# Answer
> 0 votes
To generate *unique* seed from non-boolean traits (small integers in some range), for purposes of random generation or other equivalent, you can treat all the possible player choices as dimensions, giving you a multi-dimensional coordinate when you consider them together (in the state space of all possible trait combinations a player may choose)

So if you have 3 choices, treat that as a 3D point.

Second step, you linearize this multidimensional coordinate into a single dimensional. Similar to how a 3D array would be mapped in RAM.

Given integer traits (ranged 0-n) x,y,z with max values sx,sy,sz:

```
int uniqueSeed = x*sy*sz + y*sz + z;

```

It should be easy to see how this would generalize to a higher number of traits/dimensions (just throw the traits and their sizes in an array and use some loops)

Assuming your range for each trait is minimal, this will give the smallest integer presentation possible for selected traits (assuming you dont want to compress/favor some possibilities over others).

You can use this seed directly for random generation, assuming the PRNG is good enough.

If thats not what you need it for, you can hash it with a good hash function to generate a random-looking / scrambled seed.

**While a (decent) hash can potentially collide with another hash, the probability is practically 0 if it has enough bits.** (lets assume 64 bits, which has 9 223 372 036 854 775 807 possible values, youd probably win the lottery thousand times over before you experience a collision, even if hash functions cant perfectly utilize the available values)

Also note that if you use this to seed a random generator, potential collisions in generating the seed are irrelevant because you will ALSO get 'collisions' from the random generator itself, if you only generate a finite amount of random numbers (there is a probability that two different seeds will get you the same initial random numbers).

Stuffing your choices in a bit field will work if they are simple binary choices. As will simply concatenating their bit representations if theres few enough that they fit in an integer (or if they happen to all have a range that is power-of-2).

**My suggestion is use the hash**, because **stuffing them in a limited-size integer is both annoying the extend** (what if you add a trait with type float?), **and will not scale beyond a few traits** (which will limit your game design, for no real benefit). Just use a decent hash (not something made out of 1 multiplication, shift, and a xor operation!). If by some miracle there was a collision, salt the hash (throw in some extra number with the other data) and problem solved.

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


# Question
Title: 2D Collision in tilemap - ArrayOutOfBounds
im trying to do collision detection with world based on tilemaps (two dimensional array) array -

```
private int WIDTH = 10;
private int HEIGHT = 6;
String[][] simplemap = new String[][]{

    { "0","1","2","3","4","5","6","7","8","g",},
    { "11","g","","","","","g","","","g",},
    { "22","g","","","","","g","","","g",},
    { "33","g","","","","","g","","","g",},
    { "44","g","","","","","g","","","g",},
    { "g","g","g","g","g","g","g","g","g","g",},
    { "g","g","g","g","g","g","g","g","g","g",},
};

```

than i create array from blocks and trying to show it

create blocks :

```
blocks = new Enemy[HEIGHT][WIDTH];
for(int i =0;i<HEIGHT;i++){
    for(int j=0;j<WIDTH;j++){
        blocks[i][j]= new Enemy(context,0,0);
        blocks[i][j].boxWidth=blockWidth;
        blocks[i][j].boxHeight=blockHeight;
        blocks[i][j].x=blockWidth*j;
        blocks[i][j].y=blockHeight*i;
        blocks[i][j].state = simplemap[i][j];
    }
}

```

im not sure about

```
blocks[i][j].x=blockWidth*j;
blocks[i][j].y=blockHeight*i;

```

but if write blockWidth\*i (not j) than map building like rotated on 90 degree. Maybe error here in this code. Not sure Than in glDraw i draw my map

```
for (int i = 0; i < HEIGHT; i++) {
    for (int j = 0; j < WIDTH; j++) {
        if ( blocks[i][j].state == "g") {
            blocks[i][j].draw(gl);
        }
    }
}

```

For collision i do a this code (it's for Y collision detection) for X collision code similar

```
for(int i = (int)ball.y/tileSize; i<(ball.y+ball.boxWidth)/tileSize; i++) {
    for(int j = (int)ball.x/tileSize; j<(ball.x+ball.boxWidth)/tileSize;j++) {
        //System.out.print("  i = "+i+"j "+j);
        Log.e("ERROR ", " "+i+":"+j);
        Log.e("ERROR", "DY = "+dy);
        if (blocks[i][j].state=="g") {
                       //do what we need, check directions or something other
        }
    }
}

```

**Problem** Map drawing ok with this code , and my object work only in small area like i =HEIGHT, In tests its like when i start moving from left to right side - i see 10 blocks(like road) app always crashed with nullpointerexception(from array out of bounds) after 4-5 blocks on road. I think i just not correct building my map and position . With this code i see on phone correct map, if change i and j when we set position for every blocks - than its rounded on 90 degree. Also exception on code `if (blocks[i][j].state=="g")` array out of bounds . Length 6 etc. I cant understand where my error, can any good guy help me ? please.

Regards, Peter.

**Thank you all guys** Not sure if its right - but in test its show all correct; code for collision on Y

```
public void checkColisionY(){

        dy = dy + gravity * dt;
        ball.y = ball.y + dy * dt + 0.05f * gravity * dt * dt;
        for(int i = (int)ball.y/tileSize; i<(ball.y+ball.boxWidth)/tileSize; i++){
            for(int j = (int)ball.x/tileSize; j<(ball.x+ball.boxWidth)/tileSize;j++)
            {

                    if(dy>0){
                        if(ball.y+ball.boxWidth>=blocks[i+1][j].y && blocks[i+1][j].state =="g"){
                            ball.y = blocks[i+1][j].y-ball.boxWidth;
                            dy=dy*energyloss;
                            dy = dy * -1;
                        }
                    }
                }
            }
    }

```

# Answer
> 3 votes
For accessing the array i suggest you make a function like the following:

```
String getState(int x, int y) {
    if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT) return "g"; // Let's say all blocks outside the map is solid.
    return blocks[y][x].state;
}

```

This simple function can save you from array out of bounds error. Basically, the function check the x and y which you want to access, if it is outside the array then return for example "g" which i suppose is ground/solid? You may change it to whatever value you want.

---

And for this:

```
blocks[i][j].x=blockWidth*j;
blocks[i][j].y=blockHeight*i;

```

If you switch j with i, it's no wonder for me if it is rotated 90 degree. As in your for loop j is x, and i is y. Changing j/i to x/y might help you out of the confusion.

# Answer
> 1 votes
# Expanding on Greffin28's Answer

**Tile Based Collision Detection in Games**

In tile based games it's really easy and fast to detect whether an object is colliding with a tile. Some psuedo- code to accomplish this:

```
/**
* Moves our entity along the x, then y. If we do both at the same time the entity
* will not move if any of the collision detections fail (won't be able to slide)
*/
public boolean doMove(int x, int y){
    boolean cx = move(x, 0);
    boolean cy = move(0, y);
    return cx || cy; //return whether we moved (you may use this later for something else)
}

/**
* Actually perform the move and roll back the entities position if the move fails
*/
public boolean move(int x, int y){
    pos.x += x;
    pos.y += y;
    boolean overlapping = checkCollision();
    if(overlapping){
        pos.x -= x;
        pos.y -= y;
        return false;
    }else{
        return true;
    }
}

/**
* Check if our top left point is currently inside a tile, you can repeat this for all 4 corners for bounding boxes or do some
* other fancy stuff for a circle.
*/
public boolean checkCollision(){
    int tx = pos.x/TILE_SIZE; //Check which tile our entity is stood on
    int ty = pos.y/TILE_SIZE;

    if(tiles[tx][ty].equals("g")){ //Note that I use .equals() and not == this is
        return true;               //because Strings are objects and they are not equal
    }                              //in an object sense. Their contents are just
    return false;                  //the same. so .equals() returns true and == will not.
}

```

This will need to be adapted for your game of course.

---
Tags: java, opengl-es, tilemap
---


title: Bouncing Balls in angular movement

text:
# Question
Title: Bouncing Balls in angular movement
I'm trying to bounce a ball off of a wall based on angular movement. The ball comes in at angle X ( lets say 30 ). Bouncing off with the equation 360-ballangle works for the left and right walls 180-angle works for top and bottom walls.

**Edit** Sorry for the vagueness - heres whats going on When a ball hits a wall on any side, the ball bounces right back on the same angle . I'm not sure why it does this - I am trying to have the ball flip its X velocity on a horizontal collision, and flip its Y velocity on a verticle collision. Because I am using angular movement, I need to do this by modifying the ball's angle value, and I am not sure how to set it so it bounces correctly.

(wall.getDimensions returns a rectangle with the walls size and location)

```
public void moveBullet(Bullet b) {
    float xpos = (float) (speed * 2 * Math.sin(Math.toRadians(b.angle)));
    float ypos = (float) (speed * 2 * Math.cos(Math.toRadians(b.angle)));
    Rectangle bulletbounds = new Rectangle((int) (b.bulletx + xpos), (int) (b.bullety + ypos), 10, 10);
    for (Wall wall : walls) {
        if (bulletbounds.intersects(wall.getDimensions())) {
            if (b.bulletx + 10 > wall.getDimensions().x || b.bulletx < wall.getDimensions().x + wall.getDimensions().width) {
                b.angle = (360 - b.angle);
            }
            if (b.bullety - 10 < wall.getDimensions().y + wall.getDimensions().height || b.bullety > wall.getDimensions().y) {
                b.angle = (180 - b.angle);
            }
        }

    }
    xpos = (float) (speed * 2 * Math.sin(Math.toRadians(b.angle)));
    ypos = (float) (speed * 2 * Math.cos(Math.toRadians(b.angle)));
    b.bulletx += xpos;
    b.bullety += ypos;

}

```

# Answer
> 1 votes
# An Alternative Approach

As very astutely stated by Dan in the comments to your question, trigonometric functions are very expensive to calculate and for something as simple as a bouncy ball you can keep to simple and fast vector math.

It appears that you're only doing AABB collision so this method will work perfectly for you.

**What to change**

* Your `Ball` would no longer need an angle attribute.
* Create a `Vector` object with two variables `x` and `y`
* Instantiate this new `Vector` object in your `Ball` class, we'll save it in a field called `vel`
* Instead of all this trigonometry every frame to calculate your balls movement you can now simply use `pos.x += vel.x`, which is a lot faster!
* And finally for your collision you could use a code along the lines of:

```
/*
* Will reverse the bouncing direction of the ball and lower it's velocity by half
*/
public void onCollision(boolean x, boolean y){
    if(x){
        vel.x = -vel.x/2;
    }
    if(y){
        vel.y = -vel.y/2;
    }
}

```

This method will reverse the x or y velocity depending on the two booleans you pass into it. You need to check which type of collision you have.

If for whatever reason you can't implement this method then I would speculate that you `+-90` degrees and `%` the result by 360 to get crude bouncing. You would obviously look at the current angle and `+90` if it's `> 180` and `-90` if it's `< 180`.

---
Tags: java, physics
---


title: Matte reflection effect in Unity?

text:
# Question
Title: Matte reflection effect in Unity?
I'm trying to achieve that kind of scene but in real time using Unity.

It's basically composed of some primitives, a skybox, and a plane. I'm intrigued on how to do this effect in particular:

The plane acts like a mirror, but tainted and matte (and it appears to be less blurry at the bottom of the buildings... but I'm not quite sure). I have found some shaders to create mirrors in Unity but nothing about the matte effect like in this picture. Could you guide me on how to achieve this kind of effect (knowing that I'm pretty lame when it comes to write shaders but I want to learn).

Thanks.

# Answer
> 1 votes
Reflection on a rough plane are a bit difficult, as the distance between the point observed & the object reflected into it come into play.

That mean you need to render your colors of your reflection, but also its depth, to be able then to compute for each pixel of the plane it's distance to the pixel it reflect. Then you blur it using a ratio computed from distance & roughness of the plane.

Not an easy task if you don't know shaders or post processing, but I suggest taking a look at Screenspace reflection & Physically based shading for inspiration of handling roughness & blurring. It's heavy stuff though.

---
Tags: unity, shaders, reflection-rendering
---


# Question
Title: Unity 3d: Animating Offset on a Quad is causing stretching issue only with iOS devices - Using Wrap Mode: Repeat
I added a 3D Object \> Quad and added a graphic on it with the Wrap Mode set to Repeat. I'm animating the Offset to scroll the repeating image for a parallax effect. Everything is working perfectly with in Editor and Android devices. On iOS devices, the image shows fine and then stretches as the offset is changing. I'm attaching 2 screen shots of the image import settings - Quad settings, and the issue on the iPhone. Below is my code:

```
 public float scrollSpeed = 0.05f;
 private Vector2 savedOffset;
 Rigidbody2D player;

 void Start () {
     GameObject player_go = GameObject.FindGameObjectWithTag("Player");

     if (player_go == null)
     {
         //Debug.LogError("Couldn't find an object with tag 'Player'");
         return;
     }

     player = player_go.GetComponent<Rigidbody2D>();

     savedOffset = GetComponent<Renderer>().sharedMaterial.GetTextureOffset("_MainTex");
 }

 void FixedUpdate()
 {
     if(player.GetComponent<BirdMovement>().dead)
     {
         return;
     }
     float vel = Time.fixedTime * scrollSpeed;

     float y = Mathf.Repeat(vel, 1);
     Vector2 offset = new Vector2(y, savedOffset.x%1);

     offset.x = (float) System.Math.Round (offset.x, 3); //Mathf.Round (offset.x * 10) / 10;

     Debug.Log ("Offset:" + offset.x);
     if (offset.x > 1) {
         offset.x = 0;
     }
     GetComponent<Renderer>().sharedMaterial.SetTextureOffset("_MainTex", offset);
 }

 void OnDisable()
 {
     GetComponent<Renderer>().sharedMaterial.SetTextureOffset("_MainTex", savedOffset);
 }

```

# Answer
> 1 votes
Just in case you haven't fix this or anyone else comes across this question, what worked for me was to change some import settings for the texture: Non Power of 2 from None to ToNearest and Sprite Mode from Single to None. I hope this helps.

# Answer
> 0 votes
Ahh, if you have parallax of screen size then my answer would be useful for you. I have had a bad experience with this issue even in `Editor`. What I did is just change the approach for parallax. That is working fine in all circumstances.

So follow these simple steps,

* Create a Quad at origin(center of screen) of unit size with Position (0,0,0), rotation (0,0,0) and scaling (1,1,1).
* Apply material with shader *Unlit/Texture* or *Unlit/Transparent*.
* Apply the texture to that material.
* Duplicate it and make that new Quad child of the original one.
* Retain everything same except `x` position that should be 1. Means the position of the child Quad would be (1,0,0).

Now Attach the following script to the parent Quad **only**.

```
using UnityEngine;
using System.Collections;

public class Parallex : MonoBehaviour
{

    // Scrolling speed
    public float scrollSpeed;

    // Sorting layer of each parallax. Very helpful for multiple parallax in layers with different speed
    public int _sortingLayer = 0;

    // Ending X value on which parallax would repeat.
    float tileSize;
    float _worldScreenHeight;
    float _worldScreenWidth;

    private Vector3 startPosition;

    void Start ()
    {
        _worldScreenHeight = Camera.main.orthographicSize * 2.0f;
        _worldScreenWidth = _worldScreenHeight / Screen.height * Screen.width;
        transform.localScale = new Vector3 (_worldScreenWidth, _worldScreenHeight);
        tileSize = _worldScreenWidth;
        startPosition = transform.position;
    }

    void Update ()
    {
        float newPosition = Mathf.Repeat (Time.time * scrollSpeed, tileSize);
        transform.position = new Vector3 ((startPosition + Vector3.right * -newPosition).x, (startPosition + Vector3.right * -newPosition).y, -_sortingLayer);
    }
}

```

That's it. Obviously you also can modify it according to your needs.

---
Tags: textures, ios, unity
---


title: Load game data via ajax

text:
# Question
Title: Load game data via ajax
what are The Best practies To load game data that are Stored in a mysql database?

I'm using ajax request. But The async Call is a problem because i can't sync The game level with The data load. And game does Not start because the variable is not defined. If i use sync Call, The loop wait The result And all the entities are blocked on The screen.

How Can i resolve?

# Answer
I would say sockets, TCP will work great if you don't aim to a MMO-thing.

If you just want to use AJAX calls, you can use promises to trigger the callback (the game itself) once the data has been received.
> 0 votes

---
Tags: ajax, impactjs
---


# Question
Title: Categorizing Projectiles in an arcade shooter (multiple inheritance?)
I have been working on a simple arcade shooter in Java in the vein of missile command/space invaders. I've made a base Projectile class and have been extending other Projectile types from it. This has been a nice way so far for me to keep the same basic behavior of the projectile, while experimenting with new ideas, like a missile projectile, electric projectile, bursting, etc. Before I went further though, I started to realize I needed to think about this in a better organized way because of this problem: what if I wanted to make a projectile that has features of more than one type?

Like, for example, if I wanted to make a projectile that is both seeking as well as bursting, or seeking, and shocking, etc... or a projectile that is all of the types. It seems repetitive then for me to have to create a class for each combination type. If I tried to do this on my own now, I'd essentially be copying n' pasting code from one type into another to make the hybrid type.

What's the best way to organize this type of design? It seems as though I need multiple inheritance. I don't understand how that works exactly in runtime though and how to ensure that the functions that I'm required to implement will be called and perform the behaviors I want, given any projectile.

Maybe in code it looks something like this?

```
Projectile p = new Projectile(loc, vel);
p.attachBehavior('electric');
p.attachBehavior('bursting');

```

and Projectile already inherits all the types possible? (It seems like it will make the Projectile class really huge though) and so perhaps `attachBehavior()` is essentially a loop that cycles through all the interfaces that the Projectile has?

However, looking at this post on Java and multiple inheritance (https://stackoverflow.com/questions/21824402/java-multiple-inheritance?lq=1), it seems as though even the base Projectile would also be an inherited thing. So I'm a bit confused about how to design such behaviors. (Even more confused when I think that some projectiles like lazers/beams behave instantaneously compared to gun bullets)

Also, when I'm doing things like this, I'm a bit wary about how to code in such a way that I'm not running more `for` loops than I should. Like for example, the missile projectile type needs to loop through the enemies to find the closest enemy, but the electric type, which shoots out an arc to a badguy will also need to loop through the enemies to see if its close to it. Instead of having one for loop, by having these two behaviors, haven't I now made the game run potentially slower because I'm going through two for loops now as opposed to just making a distinct hybrid projectile class that checks for both conditions in the same for loop?

# Answer
I encountered a similar problem while working on a project of mine. The player was able to pick up a certain variety of weapons, which shoot different type of bullets. I'll help you to figure out a solution for you by explaining the solution I found for my game.

In order to take advantage of inheritance and polymorphism, I managed to work out all the possible bullets my weapons were supposed to shoot, and made a list of their properties:

* Travel speed
* Impact damage
* Splash damage
* Homing
* Stickyness
* Graphic appearance
* Trail appearance
* Affected by gravity

First thing I did was to create the main parent class `Bullet`, through which I could track and deal with any bullet object in my side-scrolling 2D shooter game.

### Travel speed

Does the bullet physically travel in the space (projectile), or is supposed to reach the target instantaneously (hitscan)? Here we have two different behaviors: given starting point *A* and ending point *B*, our bullet may travel and get to *B* after a certain amount of time (remember the equation of motion), or get there after a single in-game timestep, eventually stopping before *B* because of a collision with an object. Do I need two different classes `HitscanBullet` and `ProjectileBullet` who extends the parent class `Bullet`?

Answer was *no*. Reason was: even though hitscan bullets reach their final position instantaneously, the algorithm I used to compute such position was based on the idea behind the binary search on arrays. Simply, I check if there are collisions with *any* instance of, for example, objects `BipedEnemy`; if no, then I found the final position (the second point of my line); else, the middle point of trajectory is taken in account, then I verify if the first middle segment intersects any object: if yes, iterate; else, the collision occurs in the further segment, and I iterate anyway.

This algorithm requested two arguments: a starting position `(x,y)`, a direction `θ`, and a `range`, which are *fields* in my parent class, so I can edit them on need (and, we'll see I need to do so...). Because of the range being a finite number, I realized I could set this value as big as I liked to simulate `HitscanBullet`s (the bullet would eventually reach its target outside the screen, so no problem), and if target was visible by the player the effect was immediate.

On the other hand, a `ProjectileBullet` could simply use a very smaller value, taking care of iterating such algorithm every timestep in order to give the idea of non-instant motion.

So, no separated classes here, I just pass a valid value for bullet speed (the `range` argument) and get any motion effect I desire. Motion is done, and is put in the parent class `Bullet` along with fields to track position, direction, and speed.

### Impact damage

Nothing special to talk about here. Impact damage is another field (we may call `damage`) in the parent class `Bullet`, and stores a value which is subtracted to the object's health it collide with when moving. If that has health, obviously. Enemies have health, floor and walls don't.

### Splash damage

Splash damage occurs when a bullet impacts, and delivers area or volume damage to nearby objects. In my game, I decided not to let a `Bullet` deal with splash damage itself, instead it creates an object `SplashDamage`, or maybe `DamageExplosion`, which is in charge of delivering damage to objects closer than a suitable `damage_range` distance.

Anyway, if you want your `Bullet` to deliver splash damage on his own, you can consider a maximum distance for it. At this point, your `Bullet` will have a `impact_damage` (previously simply `damage`), and two more fields, `splash_damage` and `splash_damage_range`. Make sure to deliver less splash damage as distance increase from the bullet collision point.

If you implement splash damage as creation of a new object in charge of it, you can do a lot of different things: you may create explosions for missiles, minor explosions for energy-based bullets, or an electric area damage (as you mentioned). You could even burst new bullets at random directions (as you mentioned, I guess), from this point on.

### Homing

Homing is the capability of a bullet to adjust its `direction` to automatically move towards an enemy. Here I questioned what were the right criteria to move the bullet. Should it move to the closest enemy continuously? Or it should check for the closest enemy at creation and then just follow that particular one, regardless of others as it travels? I opted for the latter, as it was easier to implement.

Homing requires two operations: (1) identify the target, and (2) adjust the direction accordingly to its relative position. Can homing be implemented as a function, or is it better creating a subclass `HomingBullet` which extends parent class `Bullet`? Your choice. In my game, I extended my parent class with a subclass, because there was more than one bullet type capable of homing towards an enemy.

### Stickyness

Does the bullet need to be destroyed at the impact, or the bullet can stick into walls, so it would be nice to see it? A rifle bullet is the first type, but if you fire a nail gun you expect to see nails sticking to walls or even enemies. I found it simple to implement this feature as a timer i called `bullet_life`, being decreased every timestep, and when it reaches the `0` then I can destroy the bullet object. If you already set it at `0` the bullet is never seen once impacted a target or a wall.

### Graphic and tail appearance

You may want to store the drawing sprite or model associated to a given `Bullet` in a variable, or you can take advantage of inheritance for advanced drawing hierarchy. Anyway, drawing can be performed in many ways, so I'm not taking it in account for this answer.

### Gravity

This property can be implemented in the physics update functions, and I don't believe you need an entire class to make distinctions between bullets affected by gravity or not.

This is a possible way to realize your bullet hierarchy, but it isn't the only possible solution. Don't try to find the best solution at all, but the best one which fits your game: you don't really need a bullet capable of hitscanning, splash damage, bursting, electric... Well, it would be OP, ahah. Anyway, you can have a couple of subclasses to differentiate the unique properties, and by unique I mean that feature is not available to other bullets. If you want properties available to any projectile, then it would be a property of the parent class.
> 1 votes

---
Tags: java, game-design, design-patterns, shooter, inheritance
---


title: Gravity wells that go with finger

text:
# Question
Title: Gravity wells that go with finger
I have a simple particle game, where all the particles are arranged in a grid. This game is for touch devices so to take advantage of it I am trying to have a multitouch gravity field thing going on.

Basically I am trying to get it so that each finger is basically a well in an otherwise non existent gravity field. That way the particles are pulled towards a finger.

My problem is I don't even know where to begin with these calculations, I have tried averaging a particles distance to each finger, its direction to each finger and nothing seems to work nicely!

I have seen other games do this. What does the math for it look like?

# Answer
> 2 votes
This is in no way a complete answer.

What you could try is: for each finger touching the interface, you calculate the distance and direction of each particle from the touch point.

With the distance, you compute a force (use x as input, and have y result in something based on a logarithm or square function: the closer to the well, the stronger the force).

Add the velocity, composed of the direction and the force, to the particle.

Repeat for each finger!

---
Tags: physics, mathematics
---


title: Average height of any point in a shape

text:
# Question
Title: Average height of any point in a shape
Super quick intro. I am making a terrain generator (With a MC exporter mostly to debug). For the islands I am creating a map with points, and create a Voronoi diagram from it. Each intersection (Where lines of the shapes meet) has a different height, depending on the distance to the coast. The coast itself is elevation=0.

However, whatever I try, I keep getting weird heightmaps. (I can't link more than two images, so I will explain). You can clearly see the difference between each site, yet they are slightly sloped.

In-game this looks like this:

The red blocks that stick out is the height of the intersection. Sites are created by references to the intersections, since they have IDs.

The code I am using at the moment:

```
Point p = new Point(x, 1, z);

        double[] distances = new double[points.length];
        double[] percentages = new double[points.length];
        double[] elevations = new double[points.length];

        int max = 0;
        for(int i=0; i<points.length; i++)
            if(parent.getIntersections().fromIndex(points[i]).getElevation() > max)
                max = (int)parent.getIntersections().fromIndex(points[i]).getElevation();

        double totaldist = 0;
        for(int i=0; i<points.length; i++) {
            distances[i] = parent.getIntersections().fromIndex(points[i]).getLocation().surfaceDist(p);
            totaldist+=distances[i];
        }

        for(int i=0; i<points.length; i++){
            percentages[i] = (distances[i] / totaldist);
        }

        for(int i=0; i<points.length; i++)
            elevations[i] = (percentages[i] * (parent.getIntersections().fromIndex(points[i]).getElevation()));

        double heightTemp = 0;
        for(int i=0; i<elevations.length; i++)
            heightTemp += elevations[i];
        heightTemp = max-heightTemp+max;

        int height = (int) heightTemp - 3 + parent.getConfig().getSeaLevel() ;
        height = (height>255 ? 255 : height);

```

The code's quite weird and unorganized since I pretty much tried anything I could come up with. "points" is an array containing the reference IDs to the correct intersections "parent.getIntersections().fromIndex(int index)" is the way to retrieve an intersection from the index/reference id. "p" is the point to get the altitude/elevation from. "Intersection.getElevation()" returns the elevation (Anything above sea level).

Sorry if this is real vague, I have no clue on how to explain this properly.

# Answer
**Solved**

After thinking this through almost a complete day (I encountered the problem yesterday), I realized I had the function to determine the height of any given point using the distance to the ocean. Why would I need to take averages and complicated calculations if I could just check the distance to the nearest coast, and then use the formula?
> 1 votes

---
Tags: java, heightmap
---


# Question
Title: How to get which gameobject the mouse is over in Unity?
So I'm working on a simple drag-n-drop based trading card game for my own amusement.

There is a card inspector included.

What I want to achieve is to change values in the inspector (which has its own *Inspector.cs*, so I would change the variables in it) based on which card I hover over with my mouse.

Each card has its own *Card.cs* attached from which I want to read the values of the current card.

If I try to do this from within the *Inspector.cs* by something like this: `Name.text = gameobject.GetComponent<Card>().Name;`, then obviously it won't work, because using gameobject in the current context is not valid.

So solution No1 would be to properly reference the gameobject over which the mouse is, which I don't know how to do.

When I try to do the same from within *Card.cs*, I cannot use an event trigger *OnPointerEnter* and run the code through that, because I have to have a reference to the gameobject that contains that function. ( And I cannot do that in a prefab, only in gameobject already existing in the level.)

So could anyone tell me how I could achieve what I want, please?

# Answer
> 3 votes
Physics.Raycast will help you to get the gameobject using mousePosition and ScreenPointToRay

```
 using UnityEngine;
 using System.Collections;

 public class Example : MonoBehaviour
 {
     Ray ray;
     RaycastHit hit;

     void Update()
     {
         ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         if(Physics.Raycast(ray, out hit))
         {
             print (hit.collider.name);
         }
     }
 }

```

---
Tags: unity, gui, scripting, mouse, gameobject
---


# Question
Title: Level/Asset design for performance Unity
I am a big fan of modular assets. Currently I am designing a 3d game for mobile and I don't know how I should create my levels to get the most out of the device.

Should I...

create lots of "small" (1x1x1 meter) assets and build my level using them
or create one geometry for the entire level?

What about textures?
Should "all" objects share one highres texture and only display their part using the right UV settings (like say in minecraft)
or should I create an individual texture for each object?

# Answer
There are lots way of optimization including

1. LOD \- hig and low poly object display according to camera
2. Culling \- show only camera frustam obects
3. mesh combine \- combine meshes
4. World streamer (dividing scene into sub-scene then load/unload according to camera position)

Maybe what you are talking about is the fourth option divide your scene into multiple scene using this package and enjoy good performance.

*Remember: before purchasing any package you need to carryout some research according to your requirements*
> 0 votes

---
Tags: unity, textures, performance, levels
---


# Question
Title: Unity 3D - create autonomous moving robot in house + first person camera movement
I have very, very little knowledge about programming or Unity. I have done some basic tutorials, but I want to try something harder. The thing is, I don't know where to start. If you find the time to help out a newb like myself, I thank you greatly :)

**Scenario**

I bought this asset: https://www.assetstore.unity3d.com/en/#!/content/48976 (it's a 3D model of a house). I want a robot, a UGV (unmanned ground vehicle) to move through the house, randomly. I want a first person view in the game, where the person playing the game can move with his mouse + WASD. In the house, I will "hide" some objects that the robot should be able to recognize. For example, I will hide a guitar in the house. When the guitar is visible to the robot, I want it to report to me via some sort of message screen. I want it to be able to "communicate" with the person walking through the house.

Now, I have absolutely no idea what to do.. I have the house.. I can get my hands on a UGV + guitar model.. I know how to attach some scripts to the first person so it can move.

**My questions:**

how can I randomly move the robot asset through the house?

How can it detect certain objects? Is it done through tags?

How can the robot communicate with the person playing, walking through the game?

If someone has some leads for me, I would love to hear from you!

# Answer
I do have some answers for you:

**how can I randomly move the robot asset through the house?**
Use a navmesh agent. (this tutorial will help you)
The robot would have to set a new random target, once it reaches it's previous. This could be done by selecting a random one out of several predefined target points.

Alternatively, you could attach a standart character controller to the robot and controll it using your own script. Use a Vector3 variable as the input for the character movement and change it to a random value every 2 - 4 seconds. In order to avoid the robot running into walls, you can also have it check, if it's position changed and force it to generate a new Vector3, if it got stuck.

**How can it detect certain objects? Is it done through tags?**
You can get the tag or name of a GameObject with `myGameObject.tag` or `myGameObject.name`. "Finding" objects can be done by using ray casting.

**How can the robot communicate with the person playing, walking through the game?**
There are multiple solutions to communicating between two scripts in Unity. Since you are probably only using two (Player and UGV), I think you can use the following example:

```
public class Player : MonoBehaviour{
    public UGV ugv; //assign this variable in the inspector, or using another method

    public void CallMethodAInUGV(){
        if(ugv != null){
            ugv.MethodA();
        }
    }

    public void MethodB(){
        //do something (Player)
    }
}

```

...same for the Robot:

```
    public class UGV: MonoBehaviour{
    public Player player; //assign this variable in the inspector, or using another method

    public void CallMethodBInPlayer(){
        if(player != null){
            player.MethodB();
        }
    }

    public void MethodA(){
        //do something (Robot)
    }
}

```

As said previously, this is just one of multiple solutions.
> 0 votes

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


# Question
Title: How to make an object fly disabling gravity through C# script in unity
I want to make an object fly which has ridged body physics by disabling its gravity after pressing a key. So I just want to know how to disable gravity through C# script. I already went through google search but I didn’t get what I want. I even tried this link http://docs.unity3d.com/ScriptReference/Rigidbody-useGravity.html

# Answer
You need to do something like this. its simple

```
    public GameObject YourGameobject;//refrence of your gameobject
    void Update()
    {
    if (Input.GetKey(KeyCode.W))//on W input it will disable the gravit of your desire object
        {
            YourGameobject.GetComponent<Rigidbody>().useGravity = false;
        }
    }

```

You can change KeyCode.W into according to your requirement
> 3 votes

---
Tags: unity, physics
---


# Question
Title: Assign a ScriptableObject to MonoScript through code
Sample code:

```
public class Item : MonoBehavior
{
    public ItemObject item; //the scriptable object

    void Start(){ // do stuff}

}

```

Normally I would drag and drop the asset of the `ScriptableObject` in the inspector.

How can I find and assign the asset (from Project View) through the script during runtime and possibly add it to a `List<>` or `Array[]`?

# Answer
Acually you want to load resource from your project views there are 2 ways to do this.*(which I know if somebody know more then surely update this answer)*

1. Resource.Load
2. Asset Bundles

**1 . Resource Example**

```
void Start() {
        GameObject go = GameObject.CreatePrimitive(PrimitiveType.Plane);
        Renderer rend = go.GetComponent<Renderer>();
        rend.material.mainTexture = Resources.Load("glass") as Texture;
    }

```

while "glass" is located inside Resource Folder of your project view. You must need to make Resource folder to use this. You can also check \[LoadAssetAtPath\].

**2. Asset Bundle Loading example(for detail refer to above link).**
> 1 votes

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


# Question
Title: How can I register Mouse Events in the Scene window of the Editor?
I want to create a custom level editor for the level designers that should allow them to place predefined objects in Unity3d similar to the Terrain wizard.

How can I register Mouse Events in the Scene window of the Editor?

# Answer
> 2 votes
Perhaps this is something you are looking for. This allows you to register mouse events in the scene, when a game object with the specified type is selected in the hierarchy.

```
using UnityEngine;
using UnityEditor;
using System.Collections;

[CustomEditor(typeof(SomeScriptType))]
public class MyEditorPlayer : Editor
{
    void OnSceneGUI()
    {
        int controlID = GUIUtility.GetControlID(FocusType.Passive);

        switch (Event.current.GetTypeForControl(controlID))
        {
            case EventType.mouseDown:
                GUIUtility.hotControl = controlID;
                Debug.Log("MouseDown");
                Event.current.Use();
                break;

            case EventType.MouseUp:
                GUIUtility.hotControl = 0;
                Event.current.Use();
                break;
        }
    }
}

```

# Answer
> 1 votes
You only need to add the `[ExecuteInEditMode]` attribute to your class to run events in edit mode:

```
[ExecuteInEditMode]
public class myclass: MonoBehaviour
{
    void Update()
    {

    }
}

```

---
Tags: map-editor, unity
---


title: Level Selection libgdx

text:
# Question
Title: Level Selection libgdx
I'm following the Canyon Bunny example in making my own game and I'm at the point where I want to implement a level selection screen. The way the example code works is that there's a `Level` class whose constructor takes a string variable that contains the path of the level file to be loaded from `WorldController` class which contains the game logic. So far I have a LevelScreen with the various buttons for the various levels like so:

```
public class LevelScreen extends AbstractGameScreen {

private Stage stage;
private Skin levelSkin;
private String currLevel;

private Image imgBackground;

private Button btnForest, btnDesert;

private final float DEBUG_REBUILD_INTERVAL = 5.0f;
private boolean debugEnabled = false;
private float debugRebuildStage;

private static final String TAG = LevelScreen.class.getName();

public LevelScreen(DirectedGame game) {
    super(game);
}

private void rebuildStage() {
    levelSkin = new Skin(Gdx.files.internal(Constants.SKIN_LEVEL_UI),
            new TextureAtlas(Constants.TEXTURE_ATLAS_LEVELS));

    Table layerBackground = buildBackgroundLayer();
    Table layerLevels = buildLevelsLayer();

    stage.clear();
    Stack stack = new Stack();
    stage.addActor(stack);
    stack.setSize(Constants.VIEWPORT_GUI_WIDTH, Constants.VIEWPORT_GUI_HEIGHT);
    stack.add(layerBackground);
    stack.add(layerLevels);
}

private Table buildBackgroundLayer() {
    Table layer = new Table();
    imgBackground = new Image(levelSkin, "wallpaper");
    layer.add(imgBackground);
    return layer;
}

private Table buildLevelsLayer() {
    Table layer = new Table();

    btnDesert = new Button(levelSkin, "desert");
    layer.addActor(btnDesert);
    btnDesert.setPosition(50, 250);
    btnDesert.addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            onDesertClicked();
        }

        private void onDesertClicked() {
            setCurrLevel(Constants.LEVEL_01);
            ScreenTransition transition = ScreenTransitionSlide.init(0.75f, ScreenTransitionSlide.LEFT, false,
                    Interpolation.bounceOut);
            game.setScreen(new GameScreen(game), transition);
        }
    });

    btnForest = new Button(levelSkin, "forest");
    layer.addActor(btnForest);
    btnForest.setPosition(345, 150);
    btnForest.addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            onForestClicked();
        }

        private void onForestClicked() {
            setCurrLevel(Constants.LEVEL_02);
            ScreenTransition transition = ScreenTransitionSlide.init(0.75f, ScreenTransitionSlide.LEFT, false,
                    Interpolation.bounceOut);
            game.setScreen(new GameScreen(game), transition);
        }
    });

    btnBack = new Button(levelSkin, "back");
    layer.addActor(btnBack);
    btnBack.setPosition(640, 50);
    btnBack.addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            onBackClicked();
        }
    });

    return layer;
}

@Override
public InputProcessor getInputProcessor() {
    return stage;
}

@Override
public void render(float deltaTime) {
    Gdx.gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    if (debugEnabled) {
        debugRebuildStage -= deltaTime;
        if (debugRebuildStage <= 0) {
            debugRebuildStage = DEBUG_REBUILD_INTERVAL;
            rebuildStage();
        }
    }

    stage.act(deltaTime);
    stage.draw();
    Table.drawDebug(stage);
}

private void onBackClicked() {
    ScreenTransition transition = ScreenTransitionSlide.init(1, ScreenTransitionSlide.RIGHT, false,
            Interpolation.bounceOut);
    game.setScreen(new MenuScreen(game), transition);
}

@Override
public void resize(int width, int height) {
    stage.getViewport().update(width, height, true);
}

@Override
public void show() {
    stage = new Stage(new StretchViewport(Constants.VIEWPORT_GUI_WIDTH, Constants.VIEWPORT_GUI_HEIGHT));
    rebuildStage();
}

@Override
public void hide() {
    stage.dispose();
    levelSkin.dispose();
}

@Override
public void pause() {
}

public String getCurrLevel() {
    return currLevel;
}

public void setCurrLevel(String currLevel) {
    this.currLevel = currLevel;
}

```

}

What I'm trying to achieve is for the `initLevel()` method in `WorldController` to receive currLevel and pass it to `Level` as shown

```
public class WorldController extends InputAdapter {

private static final String TAG = WorldController.class.getName();

public Level level;
public int lives;
public int coinScore, keyScore;

public CameraHelper cameraHelper;

private DirectedGame game;
private LevelScreen levScreen;

private Rectangle r1 = new Rectangle();
private Rectangle r2 = new Rectangle();

public WorldController(DirectedGame game) {
    this.game = game;
    init();
}

private void init() {
    cameraHelper = new CameraHelper();
    lives = Constants.LIVES_START;
    initLevel();
}

private void initLevel() {
    coinScore = 0;
    level = new Level(levScreen.getCurrLevel());
    cameraHelper.setTarget(level.player);
}

// more code

}

```

I keep getting a NPE error with this. I'm still new to java and libgdx, what I'd like to know is how I can pass the String containing the path to the level file from `LevelSelect` to `WorldController` and specifically to this line `level = new Level(levScreen.getCurrLevel());` Thanks.

# Answer
> 2 votes
In Java, every variable that is an object type (that is, any thing that isn't a primative type such as an `int`, `float`, `boolean`, etc.) is initialized to `null`. That means unless you store something in that variable via

```
 SomeObjectType variable = new SomeObjectType();
 //or
 SomeObjectType variable = otherVariableThatIsNotNull;

```

Then you will get a `NullPointerException` (NPE) whenever you call `variable.anyFunction()`

There may be more than one, but it looks like you have a guaranteed NPE in your `WorldController` class. You never give a value to your `levScreen` variable and you get a NPE when you call `levScreen.getCurrLevel()`.

Either in `WorldController`'s constructor or in the `initLevel()` function you need to pass in your levelScreen so that `WorldController` can store and access it.

---
Tags: libgdx
---