title: Best way to do headshot decapitation?

text:
# Question
Title: Best way to do headshot decapitation?
I'm using UE4 and blender. I was wondering what the process is of preparing in the 3D software and then making a head burst animation upon headshot. I don't want to do destructible meshes because they are sharp jagged fragments... I want it to literally burst and splash blood. How can I do this? Any support is appreciated.

# Answer
> 0 votes
Add 2 blueprints, 1 for head and 1 for body. Then in construction script of the main blueprint, spawn both and add head to body. When the head drops, unattach it from the body and add a force in the desired direction.

# Answer
> 0 votes
I think for the blood splashing you could use a particles system and make it play when a headshot it done. For the head burst I would divide the mesh in blender into pieces and then just move them away from the centre.

---
Tags: blender, unreal
---


# Question
Title: How do I create a 3rd person camera in XNA?
Because other people are using too complicated code for me to understand, I decided to ask a question from an XNA noob. So, I'm using the spaceship thing that Microsoft use in their tutorials of Going Beyond: XNA Game Studio in 3D, but I decided to create Asteroids (like in lesson 4) without the tutorials. Here's the code:

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace WindowsGame2
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    /// <summary>
    /// Allows the game to perform any initialization it needs to before starting to run.
    /// This is where it can query for any required services and load any non-graphic
    /// related content.  Calling base.Initialize will enumerate through any components
    /// and initialize them as well.
    /// </summary>
    protected override void Initialize()
    {
        // TODO: Add your initialization logic here

        base.Initialize();
    }

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    Model myModel;
    SoundEffect soundEngine;
    SoundEffectInstance soundEngineInstance;
    SoundEffect soundHyperspaceActivation;

    float aspectRatio;

    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        myModel = Content.Load<Model>("Models\\p1_wedge");
        soundEngine = Content.Load<SoundEffect>("Audio\\Waves\\engine_2");
        soundEngineInstance = soundEngine.CreateInstance();
        soundHyperspaceActivation =
            Content.Load<SoundEffect>("Audio\\Waves\\hyperspace_activate");

        aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;
    }

    KeyboardState keyState;

    /// <summary>
    /// UnloadContent will be called once per game and is the place to unload
    /// all content.
    /// </summary>
    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>

    Vector3 modelVelocity = Vector3.Zero;

    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        // Get some input.
        UpdateInput();

        // Add velocity to the current position.
        modelPosition += modelVelocity;

        // Bleed off velocity over time.
        modelVelocity *= 0.95f;

        base.Update(gameTime);
    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>

    Vector3 modelPosition = Vector3.Zero;
    float modelRotation = 0.0f;

    Vector3 cameraPosition = new Vector3(0.0f, 50.0f, 5000.0f);

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        Matrix[] transforms = new Matrix[myModel.Bones.Count];
        myModel.CopyAbsoluteBoneTransformsTo(transforms);

        foreach (ModelMesh mesh in myModel.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.EnableDefaultLighting();
                effect.World = transforms[mesh.ParentBone.Index] *
                    Matrix.CreateRotationY(modelRotation)
                    * Matrix.CreateTranslation(modelPosition);
                effect.View = Matrix.CreateLookAt(cameraPosition,
                    Vector3.Zero, Vector3.Up);
                effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                    MathHelper.ToRadians(45.0f), aspectRatio,
                    1.0f, 10000.0f);
            }
                mesh.Draw();
        }

        base.Draw(gameTime);
    }

    Vector3 modelVelocityAdd = Vector3.Zero;

    protected void UpdateInput()
    {
        keyState = Keyboard.GetState();
        // Rotate the model using the left arrow button and scale it down
        if (keyState.IsKeyDown(Keys.Left))
            modelRotation += 0.10f;
        else if (keyState.IsKeyDown(Keys.Right))
            modelRotation -= 0.10f;
        else

        // Find out what direction we should be thrusting,
        // using rotation.
        modelVelocityAdd.X = -(float)Math.Sin(modelRotation);
        modelVelocityAdd.Z = -(float)Math.Cos(modelRotation);

        // Now scale our direction by how hard the trigger is down.
        if (keyState.IsKeyDown(Keys.Up))
            modelVelocityAdd *= 1;
        else

            // Finally, add this vector to our velocity.
            modelVelocity += modelVelocityAdd;

        if (keyState.IsKeyUp(Keys.Up))
        {
            if (soundEngineInstance.State == SoundState.Stopped)
            {
                soundEngineInstance.Volume = 0.75f;
                soundEngineInstance.IsLooped = true;
                soundEngineInstance.Play();
            }
            else
                soundEngineInstance.Resume();
        }
        else if (keyState.IsKeyDown(Keys.Up))
        {
            if (soundEngineInstance.State == SoundState.Playing)
            soundEngineInstance.Pause();

        }
        // In case you get lost, press A to warp back to the center.
        if (keyState.IsKeyDown(Keys.Space))
        {
            modelPosition = Vector3.Zero;
            modelVelocity = Vector3.Zero;
            modelRotation = 0.0f;
            soundHyperspaceActivation.Play();
        }
    }
}

```

}

# Answer
> 0 votes
So, there are 2 solutions, one with trigonometry and one with linear algebra. Depends on you wich one you use.

I assume you have a vector for the player position (p with p.x, p.y and p.z as coordinates) and a rotation around the y axis (yAngle). Also, declare a distance from the player (d) and the angle between the camera and the ground (hAngle)

**Trigonometry**

pseudo code:

```
let x := cos(yAngle) * d + p.x
let y := cos(hAngle) * d + p.y
let z := sin(yAngle) * d + p.z

let cameraPos := Vector3(x, y, z)

```

In C#:

```
float x = Math.Cos(yAngle) * d + p.x;
float y = Math.Cos(hAngle) * d + p.y;
float z = Math.Sin(yAngle) * d + p.z

Vector3 vec = new Vector3(x, y, z);

```

(I don't know C#, if you can't translate this to it, then I will try my hardest to do it)

Also, make sure the angles are in radians. Use cameraPos to place the camera somewhere.

If the camera looks in a weird direction, try adding/subtracting 0.5 * pi to/from the yAngle.

**Linear algebra**

With linear algebra, it's quite a bit harder, and slower, O post it here because it's possible.

First, create a rotation matrix with the same rotation around the yAngle as the player (yAngle), and the rotation around the x Axis (hAngle).

Then create a vector, with the z component of the distance between the player and the camera times -1. (Vector3(0, 0, -d)), and multiply it with the rotationMatrix.

You should receive the position for the camera.

(Seriously, this last method is slow as hell, don't use it)

# Answer
> 0 votes
Here is a quick and easy way to implement a 3rd person camera within the code base of your project. Normally, I'd recommend placing these changes in the Update method instead of the Draw method but that would require a bit of refactoring of your code base that is beyond the scope of this question.

Change this section:

```
    Matrix[] transforms = new Matrix[myModel.Bones.Count];
    myModel.CopyAbsoluteBoneTransformsTo(transforms);

    foreach (ModelMesh mesh in myModel.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.World = transforms[mesh.ParentBone.Index] *
                Matrix.CreateRotationY(modelRotation)
                * Matrix.CreateTranslation(modelPosition);
            effect.View = Matrix.CreateLookAt(cameraPosition,
                Vector3.Zero, Vector3.Up);
            effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.ToRadians(45.0f), aspectRatio,
                1.0f, 10000.0f);
        }
            mesh.Draw();
    }

```

To this:

```
        Matrix[] transforms = new Matrix[myModel.Bones.Count];
        myModel.CopyAbsoluteBoneTransformsTo(transforms);

        Matrix modelWorld = Matrix.CreateRotationY(modelRotation) * Matrix.CreateTranslation(modelPosition);

       cameraPosition = modelPosition + (modelWorld.Backward * 10f);//set the distance (the value, 10f in this case) to whatever distance you want your camera to be behind your model.
       Vector3 cameraTarget = modelPosition;//the camera is always looking at the model (and beyond)
       Vector3 cameraUp = modelWorld.Up;// whatever is up for the model is up for the camera
       Matrix view = Matrix.CreateLookAt(cameraPosition, cameraTarget,cameraUp);

      foreach (ModelMesh mesh in myModel.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.EnableDefaultLighting();
                effect.World = transforms[mesh.ParentBone.Index] *
                    modelWorld;//simplify this line.
                effect.View = view;//no need to make the thing twice...
                effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                    MathHelper.ToRadians(45.0f), aspectRatio,
                    1.0f, 10000.0f);
            }
                mesh.Draw();
        }

```

---
Tags: xna
---


# Question
Title: How to "properly" display a 2d sprites in a 3d environment?
I would like to show "the classic" missile lock viewfinder (the target symbol) of a war aircraft. So the target symbol must follow the enemy, and became red when "lock" it. So i thought simply to Show the 2d sprite centered on screen (x and y = screen.height and width /2 ) but, depending of the Z , the sprite became bigger (near camera) or smaller (far from the camera).

How to display a 2d sprite indipendent from Z axis ?

Thanks

# Answer
> 1 votes
I would recommend you to place the 2d sprite not in the game world but instead place it on a UI canvas with "Screen Space - Overlay" mode.

You can convert the game-world position of a GameObject to screen-coordinates using `Camera.WorldToScreenPoint`. Then you need to convert the screen coordinates to canvas coordinates and place your sprite there.

Code stolen from answers.unity3d.com:

```
var viewport_position = camera.WorldToViewportPoint(world_position);
var canvas_rect = canvas.GetComponent<RectTransform>();

var sprite_position = new Vector2(
    (viewport_position.x * canvas_rect.sizeDelta.x) - (canvas_rect.sizeDelta.x * 0.5f),
    (viewport_position.y * canvas_rect.sizeDelta.y) - (canvas_rect.sizeDelta.y * 0.5f));

```

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


title: Is OpenTK Dead?

text:
# Question
Title: Is OpenTK Dead?
Looking at OpenTK, I notice some disturbing signs:

Does OpenTK exist anymore, or is it abandonware now?

**Edit:** Some people have expressed concern at my use of "ambiguous" and "loaded terms" like "dead," "abandonware," and others.

What I'm asking is this: software projects comprise of many pieces:

* The actual software project (such as OpenTK)
* A group of people who maintain the software (project leads, core developers)
* Some vehicle by which users can find and consume the latest versions (such as releasing daily builds)
* A community (can I ask questions about it? Get answers?)
* Updates (are there new features? New releases? Active development? A roadmap?)

Some projects have all of these things. Most have a few. Some have nothing, other than maybe the actual software project itself.

Is OpenTK one of these? Because it seems like:

* The actual software project is stable
* The maintainers don't contribute to it anymore
* There are no more latest versions (daily builds), not since 2010 (2+ years)
* The community is very low-traffic (nobody is asking/answering questions, who is actually using this anyway?)
* There are no updates since 2010

# Answer
OpenTK 1.1 was released in February.

Changelog:

1. support for OpenGL 4.4 and OpenGL ES 3.0
2. strongly-typed enums for OpenGL ES 2.0 and 3.0
3. new, faster OpenGL bindings based on hand-optimized IL
4. a new SDL2 backend for improved platform compatibility
5. new Joystick and GamePad APIs under OpenTK.Input
6. improved startup time and reduced memory consumption
7. inline documentation for all OpenGL and OpenGL ES core functions
8. a greatly expanded math library
9. numerous bugfixes for Mac OS X, Windows 8 and Linux
10. ANGLE support for Windows systems without OpenGL drivers
11. support for Retina / high-DPI monitors
12. monolinker can now be used to reduce the size of OpenTK.dll
13. precompiled binaries for optional dependencies (OpenAL, SDL2, monolinker)
> 14 votes

# Answer
It depends on your definition of dead. I know that it is currently being used by an active project called MonoGame.

In my opinion OpenTK is a stable library with enough developers invested in it that it won't go away anytime soon.
> 10 votes

# Answer
I had the same concerns, after reading through their OpenTK webpage, didn't feel me with the greatest of confidence - most of it seemed outdated. However their GitHub Commit Statistics page shows a healthy amount of activity in the last year.

In addition to that, there are downstream Projects such as Duality, or AgateLib which *I hope* will spur on further development.
> 4 votes

# Answer
I couldn't find anything offical, but it seems to be headed that way. The project is still somewhat active as far as the user base goes, as seen on the blog page. And there's still 1000+ downloads per week from the sourceforge site.

However, the developer side of things looks much worse. The nightly builds, which were going fairly regularly (a least a few days a week an new release would be added), stopped back in March.

It's likely it's abandoned by the developer or on track to be abandoned.
> 3 votes

# Answer
As of 4/30/2016 The official OpenTK website has been suspended(a few months after the only maintainer had left the project), and the Fiddler has not been seen on Stackoverflow since May 26 '15 at 14:35. It's safe to assume now that the project is officially dead. The Fiddler had also stated that he had lost interest in OpenTK roughly a year ago, and was focusing more on his academics. I would provide sources and citations for this, but the quote is located on the primary website, which is no longer active.

The lack of OpenTK leaves a massive void in the C# programming world.
> 1 votes

---
Tags: opentk
---


# Question
Title: How do you handle loss aversion in probability-based games?
The psychological phenomenon of loss aversion refers to how players feel losses twice as powerfully as victories.

For example, *Bite Fight*'s PvP is a simulation based on probabilities related on character skills, and players voice this feeling many times per week in the community forums.

If you don't want to create a pay-to-win game, but you do want to let the worst players win often enough to feel good about it, how can you do that?

The question has two parts:

1. How do you handle it technically? Do you use some kind of math techniques or a memory based simulation to avoid many loses in the row for a certain player?
2. How do you handle it from the community point of view? What do you do about complaints like this on public forums?

# Answer
> 15 votes
I see this question has a number of close votes for being too broad or opinion-based, but I think a reasonably sourced overview can be provided within the scope of a StackExchange answer - I'll take a stab at that here.

Sid Meier talked about this problem in his 2010 GDC Talk "The Psychology of Game Design (Everything you know is wrong)" (this gave me an error in Chrome but I was able to view it in Edge - your mileage may vary) Some of the aspects he covers:

* The Winners Paradox: although failure in games is in some sense much more acceptable than failure in reality, players are accustomed to winning games if they put enough time in.
* Players tend to perceive good results as a well-deserved consequence of their actions, skills, and strategy, and bad results as vindictive punishments or glitches.
* Humans have a very distorted view of probability. If you show players 3:1 or 4:1 odds in their favour, they perceive this as *overwhelming* advantage, and so losses (even though they should occur 20-25% of the time) feel shockingly negative.
* Breaking random events into a number of smaller stages can help meet players halfway here. (This is why in many versions of Civ battles play out in multiple rounds). By rolling the dice multiple times for incremental results, probability drives the results toward the expected value, and you see fewer surprising outliers. When the player does lose, they can see it coming as a trajectory of several losses in a row, rather than a single bolt of lightning out of the blue.

## 1) Do you use some kind of math techniques or a memory based simulation to avoid many loses in the row for a certain player?

Quite often, yes. Sid Meier talks about doing just this in Civ in the talk linked above. XCOM: Enemy Within also does this on its lower difficulty levels:

> "On Normal and Easy modes, there's a bad streak breaker," says Gupta. "It's stronger on easy. On Easy, it's very hard to actually lose soldiers, and the fewer soldiers you have the stronger this effect becomes, so if you start losing it builds to compensate. Of course, the aliens themselves have weaker stats on Easy and Normal too, and on Classic or higher difficulty settings this effect doesn't exist. Believe me though, on Easy, if you miss three times in a row you're not going to miss your fourth shot. It can be a 1% chance to hit and you're not going to miss that shot."

Even Tetris (in most incarnations) uses a shuffled bag of pieces to ensure you can never go more than a certain number of rounds without getting that one piece you need.

These types of systems provide a safeguard against a player getting "dice humped". Often, what we want as designers is a little variety/unpredictability/surprise, and not 100% unforgiving randomness. ;)

## 2) How do you handle it from the community side of view?

There are two major branches to this:

**Listening to the community & maintaining open dialogue.** World of Warcraft provides an excellent long-term case study of responding to community feedback - doing things like introducing ramping probabilities on certain rare drops so that players who've missed them many times in a row are more likely to find one on the next roll (similar to the example above from XCOM, this is effectively building the Gambler's Fallacy into the game probabilities, for the cases where it improves the player experience).

Even if you don't remove every pain point (*some* friction is necessary for there to be challenge), developing a reputation for attentiveness to balance issues can improve perception of fairness.

**Cultivating a community that is accepting of failure.** Dwarf Fortress's community rallies around the mantra "losing is fun". Dark Souls is lauded for its unforgiving difficulty (even enshrining it in the marketing tag-line, "prepare to die"). They have some things in common:

* They encourage their audiences to self-select. Someone looking for a mindless reward-fest is not going to buy these games in the first place. Identifying as someone "tough enough" to handle these games is part of the player fantasy they advertise.
* Loss in these games is not capricious. Even though a dragon could wander into your undefended fortress and slaughter all your dwarves in no time flat, that dragon wasn't just a bad die roll. It had a history in the world - it came from somewhere, it's going somewhere, and the fact that you got mowed down in its way is largely your own fault for picking that site and not defending it well enough. Everything in these games' worlds follows consistent rules, and a player who wields them well can handle even the toughest challenges the games throw at them. That doesn't mean guaranteed success for skilled players, but it means their skill makes a difference. When you structure your game this way, loss becomes an honest signal "there is something you can do better" rather than "the designer thought you should lose a bit more often."

# Answer
> 8 votes
There are good points in DMGregory's answer. I especially like the one where a win/loss is split into multiple minor wins/losses, which is taken from slot machines - when in doubt copy slot machines, because they're the ultimate game where (almost) all players lose, yet so many continue to play. Let's add some more points:

**Use gamedesign to allow victories, even in defeat.**

Ideally, an overwhelming one-sided victory should be very rare. So in a hockey simulation the loser can try for a consolation goal, in a strategy game they may want to at least take out a certain unit. In Titanfall there are super weak bots in every match so the player could at least get some kills. You can also leave the definition of victory open, such as in 8 player free for all deathmatch, where first place is so unlikely to achieve people don't expect to get it. That way weaker players can set their own targets, such as not being the first to die.

**Use statistics to allow players to feel a sense of accomplishment after a loss**

At the end of the game you offer statistics, like in HotS where you can see who made the most kills, dealt the most damage, the most other kind of damage, absorbed the most damage, died the least, contributed the most xp, healed the most, assisted with the most kills, etc. That way even if the match was lost, it is rather likely that you'll be best in some statistic. In Starcraft there is even a mark next to every statistic in which you played better than your average.

**Players must stand a chance in PvP**

Matching new players against the top players in pvp isn't fun for anyone involved. The challenge needs to match the players' level of skill, so in PvP you need a system that guesses a player's strength and (a) prevents totally unfair matchups and (b) provides a minor advantage for players suffering from a loss streak. (b) is key, because losing 10 times in a row can make players quit your game permanently.

**Provide the option to train basic skills without losing**

If there is any skill involved, players need to have an opportunity to train that skill without losing all the time. For example, people who have never played an fps will not stand a chance in a pure PvP game like the recent Star Wars themed Battlefield game - they would likely die more than 100 times before making their first kill. Even in a 100% multiplayer game, there needs to be an option to train against non-human opponents, no matter how dumbed down and basic it is. In Battlefront they solved this with a simple mode where they just spawn waves of weak enemies, in other fps games they solved it by adding a single player campaign, or by allowing to play games with or against any number of bots.

# Answer
> 3 votes
A lot of great stuff covered in the other answers. Here's my take on (the perception of) win/loss probabilities. In the case of PvP, consider different ways to track & show win loss scores either directly or in some sort of cooked format (I.E. player rank). Specific examples:

Puzzle Pirates ranks player performance relative to all of the other players locally & server wide. The developer wanted to keep numeric scores out of the game, this is expressed on the standings in the form of a descriptive word (E.G. Proficient, Master, Grand-Master, Ultimate). All of the puzzles have some degree of luck involved. Some such as sword fighting can be influenced by equipment. But I would argue that in all of them, player skill is the most important factor. Since the game makes this known, losing a wager is mostly on the player. This game allows player's wagering resources on matches & allows unranked competition, reinforcing the idea that the players opt into losing ranking &/or resources.

FIBS is a backgammon server that rates players using an open formula. If you win, your rating goes up. If you lose, it goes down. If you beat someone who is better than you, you will get more points than beating someone who is worse & vice versa. Your gain/loss is dependent on: difference in rating, the match length and your experience.

Often showing the stats, especially in a raw form, may not be good enough as humans often misunderstand probability (E.G. confusion about the Monty hall problem). You might be able to adjust for that by providing some context. For instance, the roguelike Brogue provides the following sort of information about combat:

> The eel has a 63% chance to hit you, typically hits for 55% of your current health & at worst, could defeat you in 2 hits. You have a 70% chance to hit the eel, typically hit for 30% of its current health, & at best, could defeat it in 3 hits.

Notice that it bases everything on the current situation, reducing math for the player thus lowering the chances of death by math error. Also it gives both average & best case damage. It's not perfect - it doesn't account for simultaneous damage from different sources & the player has to choose to read it, but in generally, I think it does better than raw stats alone.

@DMGregory touched on filtering/tuning random numbers. Extreme runs of good & bad rolls from a vanilla RNG can & will occur given enough attempts. When you consider the number of rolls made in an MMO game, it is almost guaranteed that someone will experience such runs of luck. If you want to correct for this you need to filter the RNG output to remove these runs. My recommended reading on that topic:

---
Tags: game-design, algorithm, community-management, psychology, probability
---


# Question
Title: Reducing draw calls in a y-sorted orthogonal world
This is a hypothetical question, as I haven't yet come across the problem of making too many draw calls, but for my game I am aware that this could become a potential problem.

The style of my game is similar to an old school top down RPG, except the characters and environment are high resolution and not tile based. With moving characters and objects, different textures and geometries are flitting between layers constantly. It's all in 2D.

Currently I'm finding it very hard to batch anything. As I understand, batching requires that multiple geometries appear at the same depth with the same texture. Unfortunately, this doesn't leave me many opportunities to batch. Also consider the high resolution of the textures does not allow me put everything in a single spritesheet, and the z-order of a scene is constantly changing (characters and objects move around)

I'm now trying to add some kind of deferred lighting system and with my many draw calls this appears somewhat incompatible.

I should probably mention I'm fairly new to the concept of GPU rendering. I come from Flash.

This isn't a question really, but I'd appreciate some advice.

# Answer
> 1 votes
Primitives get rendered in the order they're found in the vertex buffer or index buffer if you're using one.

You can use the index buffer to sort your primitives to render multiple mesh at different z-orders without having to move the vertices around in a single draw call provided they all use the same render settings (shaders, textures, blending, etc).

So you don't need them to be at the same depth.

The issue then is you have to figure out how much data you can move around the index buffer to sort your batches before breaking the batches down to multiple draw calls becomes faster. There is no set rule for this you have to experiment as it depends on the hardware, engine and game requirements.

# Answer
> 0 votes
This is one of many ways out there (This is what i think and probably not the best). This way is probably a little expensive to do. But here we go.

Try to split the rendering step into 3 parts (Your spritesheet count) and for each part try to call the draw call as few as possible (batching) using the same texture/spritesheet. If you have a trouble on the sorting (probably yes, because we render it based on spritesheet), you might want to search about depth peeling. You can see it here (It's for opengl though. This might not be the best but that is what i can with the least opengl) about depth peeling. Depth peeling will take away the render order problem. Might want to see the alpha testing too if you don't have a semi-transparent texture.

Though both depth peeling and alpha testing are pretty expensive on my experience.

*By the way, i don't recall batching need objects with the same depth*

Update: You didn't say what you are using so i assume you use opengl for this one. I'm going to assume (again) you have a tile id for each tile you send to your shader and the texture is 2048x2048 with 16x16 tiles (which is 128x128 in resolution per tile). Use `glActiveTexture()` and bind your textures for example 2 of your spritesheet and send them to the shader as a uniform `sampler2D`. We know each spritesheet has tile id from 0 to 255. So, in your shader check if the id \>= 256 if yes, then minus it with 256 which will go back to 0 which mean we use the other texture with that new id too. But, this approach will obviously create a branching on the shader which is not good for performance either.

---
Tags: rendering, performance, gpu, haxe, batching
---


# Question
Title: Is there any way in open-gl to "bit crush" everything on the screen?
I am making an educational game and am looking for options for a visual effect to show when something is "incorrect". So, I am looking to see if there's an easy way in openGL to temporarily distort everything on the screen (all sprites, everything), like pixelate it or something...

Does anyone know if this is possible?

I'm using cocos2d by the way...

**Edit**: here is an example of what I am looking for:

On the left, the original, on the right the pixelated / bitcrushed version:

The thing is, I don't want to just do this to a single texture / sprite, I want to take the entire display output, and perform this pixelated effect on it and then revert back to normal after a second or something.

# Answer
I don't know cocos2d, but the general approach to use for this effect is simply to just render the scene at a lower resolution into an offscreen render buffer (VBO, in OpenGL terminology), and then copy that low-resolution image to the screen, with smoothing turned off. (in OpenGL terms, that'd be performing the copy using `GL_NEAREST` instead of `GL_LINEAR`).

The lower the resolution of the buffer you render into, the larger the 'pixels' will be in your final image.
> 1 votes

---
Tags: opengl, opengl-es, cocos2d-iphone
---


title: Doubts on player movement strategy

text:
# Question
Title: Doubts on player movement strategy
What I want to achieve is the player moving to the touched position on a 2D grid-based game, stopping at the last reachable spot if the target position is unreachable. What is the strategy usually adopted in these cases? Should I implement a specific path finding algorithm for the player?

# Answer
This question on partial path-finding presents one solution - modify your path finding algorithm to remember the node visited that had the closest estimated distance to the target. Eventually, the path-finding will fail to get a route to the target (since it was unreachable), but you will have a path to the closest point encountered while it searched.
> 2 votes

---
Tags: 2d, movement, path-finding
---


# Question
Title: Unity procedural TileMap generation without creating gameobject per tile
I've been searching internet to find an efficient way to create a procedural tilemap without creating a GameObject per tile. All the TileMap tutorials I've found are creating tiles by creating hundreds of GameObjects. Thus the hierarchy in Unity is expanding unexpectedly.

I'm pretty sure this is not the "right" way to do it. Especially after seeing the new Unity 2D tools that supports tilemaps. Unity made it so, you can create tiles in "one" gameobject, not for each tile.

So, how do I do it in the right and effiecent way?

# Answer
Here's what I'm aware of:

Option 1. GameObject per tile. It's not completely horrible in certain cases. Depending on your needs, it could work.. well enough.

Option 2. A single quad or plane referencing a texture you create at run-time. You would essentially use your tile atlas texture to "paint" your map as one new texture. Depending on the size of your map of course, you might want to have multiple quads/planes each representing portions of your map.

Option 3. Create your own mesh. This would more than likely be the method you'll like most once implemented. It'll give you tons of flexibility and probably the highest performance. You would essentially create a quad per tile and set each vertex UV to map to the tiles in your tile atlas.

For Option 2, I'd suggest watching this video series by quill18creates: 3D TileMap tutorial series by quill18creates

For Option 3, this is my code, with tweaks, so it may not be perfect:

```
//For this, your GameObject this script is attached to would have a
//Transform Component, a Mesh Filter Component, and a Mesh Renderer
//component. You will also need to assign your texture atlas / material
//to it.

void Start() {
    meshFilter = GetComponent<MeshFilter>();

    BuildMesh();
}

public void BuildMesh() {
    int numTiles = mapSizeX * mapSizeY;
    int numTriangles = numTiles * 6;
    int numVerts = numTiles * 4;

    Vector3[] vertices = new Vector3[numVerts];
    UVArray = new Vector2[numVerts];

    int x, y, iVertCount = 0;
    for (x = 0; x < mapSizeX; x++) {
        for (y = 0; y < mapSizeY; y++) {
            vertices[iVertCount + 0] = new Vector3(x, y, 0);
            vertices[iVertCount + 1] = new Vector3(x + 1, y, 0);
            vertices[iVertCount + 2] = new Vector3(x + 1, y + 1, 0);
            vertices[iVertCount + 3] = new Vector3(x, y + 1, 0);
            iVertCount += 4;
        }
    }

    int[] triangles = new int[numTriangles];

    int iIndexCount = 0; iVertCount = 0;
    for (int i = 0; i < numTiles; i++) {
        triangles[iIndexCount + 0] += (iVertCount + 0);
        triangles[iIndexCount + 1] += (iVertCount + 1);
        triangles[iIndexCount + 2] += (iVertCount + 2);
        triangles[iIndexCount + 3] += (iVertCount + 0);
        triangles[iIndexCount + 4] += (iVertCount + 2);
        triangles[iIndexCount + 5] += (iVertCount + 3);

        iVertCount += 4; iIndexCount += 6;
    }

    mesh = new Mesh();
    //mesh.MarkDynamic(); if you intend to change the vertices a lot, this will help.
    mesh.vertices = vertices;
    mesh.triangles = triangles;
    meshFilter.mesh = mesh;

    UpdateMesh(); //I put this in a separate method for my own purposes.
}

//Note, the example UV entries I have are assuming a tile atlas
//with 16 total tiles in a 4x4 grid.

public void UpdateMesh() {
    int iVertCount = 0;

    for (int x = 0; x < mapSizeX; x++) {
        for (int y = 0; y < mapSizeY; y++) {
            UVArray[iVertCount + 0] = new Vector2(0, 0); //Top left of tile in atlas
            UVArray[iVertCount + 1] = new Vector2(.25f, 0); //Top right of tile in atlas
            UVArray[iVertCount + 2] = new Vector2(.25f, .25f); //Bottom right of tile in atlas
            UVArray[iVertCount + 3] = new Vector2(0, .25f); //Bottom left of tile in atlas
            iVertCount += 4;
        }
    }

    meshFilter.mesh.uv = UVArray;
}

```
> 8 votes

# Answer
As you (I think) alluded to, Unity's roadmap has plans for a tilemap editor. I'm looking forward to it, because right now it's a little confusing how to proceed.

In the meantime, the best approach I'm seeing is to make your map in Tiled and then use X-UniTMX to import it into Unity. Obviously that's not procedural generation though; I'd imagine you would use the same technique as X-UniTMX is using to create the mesh.
> 0 votes

# Answer
You could just have the tiles created deeper in the hierarchy and close that folder and don't be bothered. What you can do as well is hide your game objects from the hierarchy \`myTile.hideFlags = HideFlags.HideInHierarchy" not sure about how much performance would be gained.

Showing 100x100 textures on the screen is never a good idea drawing textures is more heavy then drawing polygons anyway. If you need to zoom out that far you are better off with bigger textures. Same goes for being zoomed in, you should not draw the textures that do not need to be drawn.

What I usually do (I'm not a Unity guy) is creating a Class for a map and use a 2 dimensional array for holding all your tiles. This array could be simply of ints or a Tile class with a couple of ints that refer to your textures, tile type, objects, etc. Then one would draw it as follows:

```
for (int y = 0; y < mapHeight; y++)
{
    for(int x = 0; x < mapHeight; x++)
    {
        Graphics.DrawTexture(new Rect(x * tileWidth, y * tileHeight, tileWidth, tileHeigt), tileTexture);
    }
}

```

The draw method I use seems to be for drawing a GUI but might be perfectly suitable for the task. Otherwise you have to dig into the sprite manager and find a way that works with this method.

You could use a dictionary for texture reference like `int 1` in your tile class refers to some texture and `int 2` refers to another. In the line you are drawing your texture you would use your dictionary to give the right texture object. This way it should not create a GameObject and thus not create all unnecessary overhead.

You can do the same for pretty much everything that does not need the level of control of a GameObject. Mind though, this way it will draw every tile of your map it most probably does not auto cull the objects like I think unity does with game objects. But just drawing what needs to be on screen is very easy. You know the screen/viewport size, camera position and the tile size. Some simple math should draw exactly what's needed.

Still, unity is a 3D engine. It just supports 2D in a 3D way. But you can basically do the same thing for quads/meshes with textures and a Orthographic camera. Just drawing those meshes needed is pretty cheap.
> 0 votes

# Answer
As someone working on voxel/block-based project, I cannot help but think about just using the same approach, only in 2D. You can build a grid-like mesh procedurally and assign right coordinates of tile visuals in your texture atlas to UV channel. In 3D you have to do much more job than this to have high performance, but in 2D very likely it's really enough.
> 0 votes

# Answer
You could always use LeanPool. Its a free asset on the asset store. It does object pooling for you. Then you can do a simple cull system around the cameras view that spawns/de spawns tile gameobjects as they enter/exit the cameras view. Im not sure on how big your tilemap is going to be but Unity can handle quite a bit of gameobjects. LeanPool has benchmark scenes in Unity where you can spawn/ de spawn a thousand objects with box collision components and I think possibly a render component as well on each one and it does it very very quickly.

https://gamedevacademy.org/how-to-script-a-2d-tile-map-in-unity3d/

Here is a link that will show you an example of using LeanPool with a tilemap.
> 0 votes

---
Tags: unity, procedural-generation, tilemap
---


title: Scripting: to block or not to block

text:
# Question
Title: Scripting: to block or not to block
Context: I'm making a little "program your robot army" sort of game in Java in which the player writes Lua scripts (which are then run by LuaJ) to program their robots to do stuff. So far there are two objectives:

1. Keep It Simple, Stupid, and
2. React to the environment.

To take a simple example of what I currently have, the player should be able to tell their robot to go to a particular location with something like

```
robot:goTo(5, 8)

```

Like Colobot, the scripting engine effectively halts (blocks) at that instruction until the robot has reached its destination.

I like this -- it's meets the first requirement nicely, in that you can't *do* anything until `goTo` decides to return. It's also simple on the Java side -- I can basically do `while (/* condition */) yield()` and just resume the coroutine every tick (then maintaining state in local variables is trivial). But: what if that resource at (5,8) disappears, or an enemy comes near, or energy runs low? There's no opportunity to bail -- the robot *has* to reach (5,8) before it can do anything else.

The main other idea I can think of is to produce some sort of loop:

```
while not robot:near(5,8) do
    if robot:enemyNearby() then
        break -- and do some other stuff, presumably
    else
        robot:moveTo(5,8)
    end
end

```

where `moveTo` this time sets the velocity/acceleration and then immediately returns, without blocking until arrival.

I *could* have `robot:goTo` return the actual coroutine (either wrapped, so you just call it, or directly, which requires calling `coroutine.resume` and passing the coroutine), which might look something like this:

```
moveTask = robot:moveTo(5,8)
while not robot:near(5,8) do
    if robot:enemyNearby() then
        break
    else
        moveTask()
        -- or perhaps coroutine.resume(moveTask)
        -- or some other syntactic sugar
    end
end

```

These last two approaches *look* pretty similar, but reusing a coroutine as in the second example makes managing state (e.g. a path) trivial, at the cost of exposing coroutines to the player.

To reiterate, the goal is to allow for writing simple scripts, in which a set of actions are executed in series (sorta like queued actions in The Sims), while simultaneously allowing more complex scripts with actions that may be interrupted by arbitrary events (nearby enemy, target moved, stats dropping).

Any tips or ideas would be much appreciated!

# Answer
You can make the moveTo() function a blocking function in the user script, but you should definitely not make it block your script.
This way you should have moveTo() return a boolean telling weather the destination was reached or the action was interrupted.
I suppose this would be the simplest solution for the user.

You cold also have the moveTo() function just sends the destination and actionToTake to your program and return immediately.
Then your program can just move the robot towards that destination unless it gets interrupted, then when/if it reaches destination just execute the action that was assigned (action could be a function call or you could predefine a set of possible actions).
> 1 votes

# Answer
Multiple solutions:

1. Pass a callback to the `moveTo` function that can check other things from inside the loop and optionally stop it in the middle.
2. Create two new coroutines - one for movement, one for doing things while moving. Yield main thread until either of the two has finished, abort the remaining one afterwards.
3. Turn movement into state, resolve it in parallel (possibly from outside Lua). `robot.targetPos = {5,7}`, then do the additional work in the same thread.

Which one's 'best' for this case is up to you.
> 0 votes

# Answer
When something bad happens while running a Java function from a Lua script, have that function exit by throwing an exception. There are several ways to implement Lua from Java, so refer to the documentation for details about how to throw an exception from a java function back to Lua. The downside is that the player will have to put lots of error checking into their code and wrap everything in `pcall`, which might be a bit unfun.

Another option is to just do nothing when there is an error on the Java side and return silently to Lua. It's now up to the player to implement error-checking code by calling a `getLastError` Java-method . If they don't, their program will continue as if nothing had happened and might simply not do what they want to do.
> 0 votes

---
Tags: game-design, scripting, lua
---


title: Terrain not rendering like it should be

text:
# Question
Title: Terrain not rendering like it should be
i was following this tutorial here: https://www.youtube.com/watch?v=yNYwZMmgTJk, in which i was translating from Java to C++ to generate a terrain, and stumbled across this issue:

As it appears, it is rendering lines instead of triangles. i have checked, glDrawArrays() which was drawing triangles like normal. i checked the generator and the textures which was normal. But when i put in verticies manually it drew the terrain normally. This then leads to me suspecting that the error is in the terrain generator. another possibility, but least likely, is that i suspect is that i am not passing the data to the vertex and fragment shader correctly.

here is the terrain generator code:

```
const int vertex_count = 128;
const int size = 800;

GLfloat vert[(vertex_count * vertex_count) * 3]{
    0
};

GLfloat norm[(vertex_count * vertex_count) * 3]{
    0
};

GLfloat texCoord[(vertex_count * vertex_count) * 2]{
    0
};

int vertexPointer = 0;

for (int i = 0; i < vertex_count; i++) {
    for (int j= 0; j < vertex_count; j++) {
        vert[vertexPointer * 3] = -(float)j / ((float)vertex_count - 1) * size;
        vert[vertexPointer * 3 + 1] = 0;
        vert[vertexPointer * 3 + 2] = -(float)i / ((float)vertex_count - 1) * size;

        norm[vertexPointer * 3] = 0;
        norm[vertexPointer * 3 + 1] = 1;
        norm[vertexPointer * 3 + 2] = 0;

        texCoord[vertexPointer * 2] = (float)j / ((float)vertex_count - 1);
        texCoord[vertexPointer * 2 + 1] = (float)i / ((float)vertex_count - 1);

        vertexPointer++;
    }
}

```

and glDrawArrays():

```
 glDrawArrays(GL_TRIANGLES, 0, sizeof(vert));

```

and passing the data to the fragment and vertex shaders:

```
GLuint vao, vbo;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER,sizeof(vert), vert, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);

GLuint vbo2;
glGenBuffers(1, &vbo2);
glBindBuffer(GL_ARRAY_BUFFER, vbo2);
glBufferData(GL_ARRAY_BUFFER, sizeof(texCoord), texCoord, GL_STATIC_DRAW);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);

GLuint vbo3;
glGenBuffers(1, &vbo3);
glBindBuffer(GL_ARRAY_BUFFER, vbo3);
glBufferData(GL_ARRAY_BUFFER, sizeof(norm), norm, GL_STATIC_DRAW);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(2);

```

# Answer
> 0 votes
You appear to be writing your vertices in a straight line.

That is, vertex0 has position (0,0,0). vertex1 has position (-6,0,0). vertex2 has position (-12,0,0). vertex3 has position (-18,0,0), and so on. Once you've finished all 128 vertices along one strip, you move back to the start and then specify vertex128 (0,0,-6). (and then (-6,0,-6), (-12,0,-6), and so on)

`glDrawArrays()`, when called using `GL_TRIANGLES`, expects to receive vertices in triples, defining the triangles to be drawn. So it looks at vertex 0, 1, and 2, and draws a triangle between those three points. In your case, vertices 0, 1, 2 (and in fact, everything up to vertex 127) are all completely in line with each other. So trying to draw triangles between any of them will end up looking like a line.

The standard thing to do here would be to use `glDrawElements()` instead of `glDrawArrays()`, and provide another data buffer containing the vertex indices of the triangles you want to draw (that buffer might start as {0,1,128, 1,129,128, ...} and so on.

But if you want to stick with `glDrawArrays()`, then you'll need to modify how you build that vertex buffer (and the normals and texture coordinates as well) so that the vertices in the buffer, when taken in consecutive sets of three, form the triangles that you actually want `glDrawArrays()` to draw. (note that this would require multiple copies of most vertices, since most vertices in your grid will be used in multiple triangles)

---
Tags: c++, terrain, glfw, glew
---


# Question
Title: If I accidentally used a trademarked name or word in my title, can I just change it?
I'm closing in on a point in the development of my first game that it's ready for Steam Greenlight. I don't even have a name for it though. My project name is Asteroids, but obviously I can't use that. I have a bunch of other ideas, but I'm scared to death of getting sued. Let's use the Edge Vs EA example. Edge Games tried to sue Electronic Arts because they released Mirror's Edge. They were unsuccessful, but the case aside, couldn't EA have just said, "Oops, sorry mates, we'll come up with something else."? I'm developing because I want to secure a real future for my family, but I make $10 an hour busing tables, getting sued would mean financial ruin, right? I barely manage to pay my bills and feed myself, so a Lawyer isn't an option, and there's no other way I know of to be absolutely sure I'm not infringing on someone else's rights.

# Answer
> 1 votes
Changing the name of a larger game development project is often easier said than done because of all the marketing expenses and PR effort which was already invested to promote the old name. Companies like EA run a well-oiled marketing machinery for every title which starts working long before a title is even announced. The money and time they lose through a name-change might far outnumber the cost of the lawsuit. Also, when the game was already sold or the trademark owner feels like the existing marketing has already damaged their brand, the trademark owner could try to demand recourse even when the name is changed immediately.

You can check the US patent office database of registered trademarks to check if your game's name is a trademark registered in the United States. You should also check if there is a database like that specific to your own country.

There is generally no sure way to be completely save from lawsuits because everyone can sue anyone for anything, and finding out if the lawsuit is even remotely justified already takes money from both sides.

I am not a lawyer, but if I would want to protect my private finances from being ruined by a lawsuit against my game, I would consider forming a limited company and distribute my game through that company. A limited company is a separate legal entity from yourself, and when it goes bankrupt you will only lose the money you invested into the company and will not inherit any of its debt. This also means that anyone who sues your company won't see any more money than the company owns, which makes it unattractive for any trademark trolls who don't care about your game and only want money.

But in the long run you should really get proper legal advise and not just rely on what random laypeople on the internet like me tell you. When you want to run a company, legal advise is just part of the cost of doing business.

# Answer
> 0 votes
IANAL. Disclaimer: my advice is based on my experience in the gamedev field alone.

You can not use trademarked names for your actual game. Try and come up with a different name. A lawsuit is an ugly thing.

You can go with something unique-ish like... Kuiper Belt something. Do your best to not even derive your name from other games.

---
Tags: trademark
---


# Question
Title: i want to make four letter one word game. i have designed xml but getting problem in main activity java.
i want to make four letter one word game. I have designed xml using four imagebutton and randomly load from string array, but how to code entire java file. i am beginner to programming.

# Answer
Look at some free android Java tutorials on youtube or read some from places like code+tuts or mybringback. Nobody is going to hand you code.

Guru Raj is right, use lists because they are less of a pain to use and also fetch your words from an external csv file or so.

That way you can pull your word library from wikipedia. Then you can pull random words from the file, add them to a list and work with that list.

This is a link to my mediafire source as well as an app called Game of Words. Maybe it's something along the lines of what you need. Use it for whatever you want, you can even sell the app that you come up with. Try and PM me to show me your work if you do.

APK file - http://www.mediafire.com/download/bhol315o30t603j/GameOfWords.apk

and this is the eclipse source

http://www.mediafire.com/download/im47iwjb14ebniq/Game\_of\_Words\_%284%29.7z
> 1 votes

# Answer
> use lists instead of array you may use mapping also
> -2 votes

---
Tags: android
---


title: How does one structure a Player GUI

text:
# Question
Title: How does one structure a Player GUI
I am using Java and the Slick2D library.

I've been testing around with ways to develop a Player Graphical User Interface (GUI) (to show armour, items picked up, weapons equipped, etc). The one problem I am facing however is how to actually make such a system work.

I do not know if Slick2D has a system for creating a Player GUI. I have tried looking up resources on the internet with limited success.

Currently I am thinking of having a BasicGameState named StatePlayerInventory which is the Player Inventory for the player to interact with and I have another BasicGameState named GameState which is the Over-world map and whatever items the player gets from the over-world map, it will render in the Player Inventory GUI. I already have a functionable inventory class and an item class but it isn't able to be rendered because of I have no GUI for the Player currently.

My question is is what does if this kind of system I have is efficient/workable. If there are better ways of creating the Player Gui, I am open to suggestions. Also, if there are online resources on Player Inventories, it would be nice to have access to them.

# Answer
I've stumbled on an answer for creating a decent and easy GUI system from playing around with my game. Currently it draws the images of items onto the GUI screen, but more can be done in the future.

This is essentially how I have it setup:

Over-World State: EntityPlayer {picks up} --\> Item (i.e. ItemPotion) --\> {goes to} Player Inventory

The Player walks over the item, which picks the item up and then the item goes into the Player's Inventory, which is handled by a List. Here's a code snippet:

```
    private List<Item> itemList = new LinkedList<Item>();

```

This handles all the items the Player picks up and stores the items into the Player inventory.

A method that will come into play is the getItemSprite() method:

```
    public Image getItemSprite (List<Item> itemList) {
    for (int i=0;i<itemList.size();i++) {
        item = itemList.get(i);
        return item.getSprite();
    }
    return null;
}

```

PlayerInventory State: in the PlayerInvState, I have a method called drawItemsToInventory(Graphics graphics) {} which grabs all the items in the Player Inventory, specifically the sprites of the items, and displays those images onto the gui screen. Here's a code snippet:

```
public void drawItemsToInventory (Graphics graphics) {
    for (int x=0; x < StateGame.getPlayer().inventory.getItems().size(); x++) {
        if (StateGame.getPlayer().inventory.checkIfEmpty() == true) { //Checks to see if inventory has an item, if not, it won't draw an empty image which could crash the game
            return;
        }
        graphics.drawImage(StateGame.getPlayer().inventory.getItemSprite(StateGame.getPlayer().inventory.getItems()), 8 +((64) * x), 356);
    }
}

```

This way, whatever items the Player picks up goes to the inventory, and then the PlayerInvState renders those items found in the list, onto the screen. Here's an example of it in action:

In this instance, the Player picks up the item in stores it into the inventory.

And in this instance the item sprite is being read and written onto the GUI.

I've just managed to get this to work, it's far from being finished however. But, at least it can be beneficial to those who are struggling to create their own kind of GUI System.
> 1 votes

---
Tags: java, gui, graphics-programming, slick
---


title: SQLite in libGDX

text:
# Question
Title: SQLite in libGDX
Does anyone have an example of how I can use SQLite in libGDX? I have a class in my original Android code that allowed me to easily access a database but I can't seem to find anything equivalent to that in libGDX. Or maybe I am missing something? Am I able to use that in the libGDX code somehow? Sorry I am new to libGDX.

# Answer
If you have that, you can use (callbacks).

You define an interface, and implement the methods in the android classes, in that way you can retrieve data and get it in your libGdx project.

Its an easy way.

```
public interface ActionPerformed
{
public String actionPerformed();
}

public class AppActivity extends AndroidApplication implements ActionPerformed
{

       public AppActivity()
       {
             new XMLProgress(this);
       }

      public String actionPerfomed()
      {
         //Here goes your code;
      }
}

public class XMLProgress
{
      static ActionPerformed action;

      public XMLProgress(ActionPerformed a)
      {
           action = a;
      }

      public String getMethod()
      {
          return action.actionPerformed();
      }
}

```

I used my class in libgdx as a singleton, because i dont need a lot of instances, and i secure that is always live.
> 5 votes

# Answer
If you want to use sqlite with libGdx you can use opensource project gdx-sqlite .

gdx-sqlite is a cross-platform Libgdx extension for SQLite database handling. The extension abstracts database handling to provide a unified method to handle database transacitons across multiple platforms while also adding SQLite support for desktop version of Libgdx application.
> 1 votes

---
Tags: android, java, libgdx
---


# Question
Title: XNA/MonoGame Collisions between two boxes don't work as expected
I have the following problem: I have two GameObjects (one is static, the other is the player). Both of them have one BoundingBox that surrounds them, and a List that contains more BoundingBoxes for a more detailed collision detection. I use the follwing code when the player moves:

```
/// <summary>
    /// Checks if this Game Object blocks the specific boundingbox.
    /// </summary>
    /// <param name="box">Box.</param>
    public virtual bool Blocks(BoundingBox box)
    {
        if (BoundingBoxes.Count.Equals(0))
        {
            return !(this.SurroundBox.Contains(box) == ContainmentType.Disjoint);
        }

        bool blocked = false;
        BoundingBoxes.ForEach(b =>
        {
            if (b.Contains(box) != ContainmentType.Disjoint)
                blocked = true;
        });

        return blocked;
    }

    /// <summary>
    /// Checks if this Game Object blocks any of boxes in the specific list of boundingboxes.
    /// </summary>
    /// <param name="boxes">Boxes.</param>
    public virtual bool Blocks(List<BoundingBox> boxes)
    {
        bool blocked = false;
        boxes.ForEach(b =>
        {
            if (this.Blocks(b))
                blocked = true;
        });

        return blocked;
}

```

If I just use the Surroundboxes, everything works fine. If I start using the Lists, blocked never gets true. I'm pretty shure my BoundingBoxes aren't the problem (visually they clearly overlap!). Here's a screenshot, where b is the red boundingbox from the tree and the lightblue is the one from the player. Blue boundingboxes are the surroundingboxes. The right image is just there to demonstrate that the player's boundingbox is also 3D. (In this case each GameObjects List of BoundingBoxes only contains one BoundingBox that is slightly smaller than their SurroundingBox)

Shouldn't `if (b.Contains(box) != ContainmentType.Disjoint)` now return `true`? If not, wheres my mistake? Any comment/help is appreciated!

# Answer
> 0 votes
Nevermind, I found out how to solve it: I should use `BoundingBox.CreateFromPoints`instead of the standard constructor. The standard constructor gets confused if `Min`and `Max` aren't actually Min and Max. `BoundingBox.CreateFromPoints` takes care of this.

---
Tags: collision-detection, monogame, bounding-boxes
---


# Question
Title: Does a Standard Exist for Game Entity View Frustums
I was just recently adding the ability for my in-game entities to have their own Frustums, with the intentions of making them able to see enemies later down the road of my development cycle. My custom approach works great, **but I find myself left with a suprisingly staggering question. What kind of perspective should my entities have? What is the standard for modern games?** Here is a picture to show my implementation in action:

The Settings for that Frustum are as follows:

```
            // Just winging a random projection; worked pretty well, actually!
            Matrix4 entityProjectionMatrix = Matrix4.CreatePerspectiveFieldOfView(0.5f,1f, 0.1f, 50f);
            // Calculated by hand for testing purposes
            Matrix4 entityViewMatrix = new Matrix4(
                -0.02840426f, -0.1789574f, 0.9834467f, 0,
                0, 0.9838437f, 0.1790296f, 0,
                -0.9995965f, 0.005085204f, -0.02794535f, 0,
                50.50341f, 6.017713f, -46.88488f, 1);
            BoundingFrustum entityFrustum = new BoundingFrustum(entityViewMatrix * entityProjectionMatrix);

```

Now, clearly, those settings are a little lacking in the side-view peripheral department. I also don't think the entities should have a large frustum like players, who can see damn near anything(the player Frustum is absolutely massive). I feel as though something small, yet realistic would suffice, but I don't know if there is already a current standard for how much an entity should be able to see. I'm sorry if this question is broad, but it is a problem, and I am looking for some clarity/literature on the topic.

# Answer
There isn't really a standard - it's going to be dictated by the needs of your gameplay.

For Splinter Cell, determining whether the player (or suspicious evidence) is seen by an AI is the heart of the stealth gameplay. We needed a lot of nuance - consideration of peripheral vision versus direct line of sight, illumination, AI alertness level, movement state, partial occlusion, etc - but we also needed it to be predictable & intuitive enough for players to learn and plan their tactics around.

As recently as Blacklist, our AI used multiple overlapping detection volumes, and designers could fine-tune their sizes, offsets, near and far detection speeds, and tolerance for shadow/occlusion, in order to dial-in the behaviour to just the right difficulty for each case.

These volumes aren't necessarily frustums either - a perspective camera view frustum gets taller and wider in the distance, but in practice people don't really look up very often, and climbing along ceilings to get a drop on guards is one of the thrills of a Splinter Cell game. So capping the detection height (for guards who haven't been alerted to look up) can make for a better play experience.

Typically our AI had a long narrow "search beam" that would detect quite rapidly in a corridor shape directly ahead of them, peripheral volumes to the sides with shorter range/progressively less sensitive detection, and a small "bump radius" to react to threats in their immediate personal space (which would be missed by a strict frustum-based approach)

I expect you'll need to do some similar case-by-case tuning to find what's right for your project. Try exposing your detection parameters for runtime tweaking if that's supported in your engine, or hot reload them from a configuration file. That way you can play the game, get into a situation where it feels like the AI should / should not see something, then tune the parameters to get that desired result. Repeat until you're happy with their level of perception.

More details about the details of Blacklist's detection scheme can be found in this GDC talk by AI lead Martin Walsh, which is where the image above is from. They're also accessibly summarized in this Game Maker's Toolkit video.
> 3 votes

---
Tags: game-design, projection-matrix, entities
---


# Question
Title: Why create meshes instead of using Planes?
I'm working on a top down 2D game in Unity and I want to create levels dynamically. All tutorials I find tend to talk about generating meshes so I've followed some great tutorials such as this one. However, here's where I'm not understanding the point. What's the difference between doing all that work to render a plane when you can just use the Plane object with the height/width configured to match what the manual creation has?

# Answer
> 4 votes
First of all if you are interested in generating meshes I recommend to you this series of articles in gamasutra about procedural meshes

Modelling by numbers

So returning to the main question, generate planes procedurally allows you to define the distribution of the vertex, for example I use this kind of methods to generate low poly terrains

So if you want to generate surfaces dynamically and you want to create your own tools to generate your levels, I think that procedural generation its the way

cheers!

---
Tags: unity, procedural-generation, optimization, mesh
---


# Question
Title: How do I make a circular hole inside an editable poly without boolean operations?
I have created a rectangle, then converted it into an editable poly. Then I created a circle and converted it to editable poly too. How to make it so that that the circle becomes a hole in the rectangle?

# Answer
That's called a **Boolean operation**. You can find a video tutorial here for almost the exact situation you're asking about.

Essentially, it looks like you create a new object with your two objects selected. You'll likely need to make your circle a cylinder first. The new object is a Compound Object of type Boolean. Then in the operations you select A-B (where A is your rectangle and B is your cylinder).

It's still a boolean operation. It's just done with splines that share a common plane. Check the Boolean heading on this page.
> 2 votes

# Answer
If you don't want to use booleans...

1. Use INSET on the front and rear facing face. This creates a square polygon in the middle with edges going towards the corners of the cube.
2. Delete the new square polygons on each face.
3. Bridge the new gap created.

Obviously this creates a square hole. However, if you add more verts around the edges of the cube before using INSET, you could later manually shape the hole.
> 1 votes

# Answer
I know, the question was asked about 3 years ago, but never mind. I don't think the boolean operation is a good solution ant it is not required here. It is desined for other cases, to my mind.

So, you created 2 splines. You should convert one of them, for instance rectangle, to editable spline, than **Attach** the second. Than apply **Extrude** modifier. The nested object automatically becomes a hole in the parent object.

So the recipe is:

1. Create as many nested splies as you want, *wihout intersection*
2. Convert one of the to editable splie and **Attach** them all together
3. Use **Extrude** modifier

Therefore extruding a circle inside a circle (in other words a flat a ring) creates a tube.

The cap created automatically will be without any edges in it. If you are bothering about topology - you may:

* Cut it using **Cut** tool
* **Connect** vertices
* Remove cap and use **Bridge**
* Use **Quadify Mesh** modifier (doesn't give clean topology)

If you're creating game assets - that **Quadify Mesh** may be not desirable. But if you're going only to have smoothed model for one render - it's a quick way.

Your question seem to be more general than creating a cirular hole in a box but...

In case you want to create a perfectly round circle in a square (you may want to insert it into other objects) using *TurboSmooth*, you do

1. Create a plane 2\*2
2. Create diagonal lines (connect or cut)
3. Chamfer the vertext in the middle
4. Delete polygone in the center

Here we are, having low poly model.

And that is is. Other steps are necessary only for smoothing:

5. Prepare edges for smoothing (add some density near the corners)
6. Apply **TurboSmooth**
> 1 votes

# Answer
this video shows how to create a circle in your square using the 'loop tools' in the graphite editor. Works perfect, maintains quads everywhere. https://www.youtube.com/watch?v=nwzqn3K7RxE
> 0 votes

---
Tags: 3dsmax
---


# Question
Title: Object shrinks at same rate no matter what
I am using the following code to shrink a sprite:

```
public bool shrinking = false;
public float targetScale = 0.1f;
public float shrinkSpeed = 0.1f;

void Update () {
    if(shrinking) {
        mySprite.transform.localScale -= Vector3.one * Time.deltaTime * shrinkSpeed;
        if(mySprite.transform.localScale.x <= targetScale) {
            shrinking = false;
        }
    }
}

```

However, no matter what I change `shrinkSpeed` to, the object shrinks at the same rate. I know it probably has something to do with putting it in the update function but where should I move it to fix the problem?

# Answer
It turns out I should have paid more attention in CS class. I didn't realize Unity overrides any initialized values from scripts with whatever is present in the Inspector. Having made all my variables public, the Inspector was overriding them every time, even when I used `[HideInInspector]`. Simply making all the variables private (which they should have been from the beginning) solved the problem.
> 1 votes

# Answer
You may want to consider setting up your transitions based on a time period instead of a multiplier. That way, you can instead adjust the "Duration" of your transition in milliseconds instead of fiddling with multiplier values.

Consider something like this:

```
float Duration = 0.5f;
const float DURATION = 0.5f;
Vector3 StartSize = Vector3.one;
Vector3 EndSize = Vector3.zero;
bool Done;

Update(){
    if (!Done)
    {
        Duration -= Time.deltaTime;
        if (Duration <= 0) {
            Duration = 0;
            Done = true;
        }
        mySprite.transform.localScale = Vector3.Lerp (EndSize, StartSize, Duration / DURATION);
    }
}

```
> 0 votes

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


# Question
Title: Unity Android Unable to convert classes into dex format AdMob
I'm a beginner Unity programmer (school-age), so I don't know that much about the system. On its own my app compiles fine, but when I implement the AdMob SDK (Google) 2.1, I have the following error log (when converting java.class into DEX):

```
Error building Player: CommandInvokationFailure: Unable to convert classes into dex format. See the Console for details.
/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home/bin/java -Xmx1024M -Dcom.android.sdkmanager.toolsdir="/Volumes/SAMSUNG/Programming/Eclipse Java etc./android-sdk-macosx/tools" -Dfile.encoding=UTF8 -jar "/Volumes/SAMSUNG/Applications/Unity/Unity.app/Contents/BuildTargetTools/AndroidPlayer/sdktools.jar" -

stderr[

UNEXPECTED TOP-LEVEL EXCEPTION:
java.util.zip.ZipException: error in opening zip file
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.<init>(ZipFile.java:128)
    at java.util.zip.ZipFile.<init>(ZipFile.java:145)
    at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:244)
    at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:166)
    at com.android.dx.cf.direct.ClassPathOpener.processDirectory(ClassPathOpener.java:229)
    at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:158)
    at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144)
    at com.android.dx.command.dexer.Main.processOne(Main.java:596)
    at com.android.dx.command.dexer.Main.processAllFiles(Main.java:498)
    at com.android.dx.command.dexer.Main.runMonoDex(Main.java:264)
    at com.android.dx.command.dexer.Main.run(Main.java:230)
    at com.android.dx.command.dexer.Main.main(Main.java:199)
    at com.android.dx.command.Main.main(Main.java:103)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at SDKMain.main(SDKMain.java:129)
1 error; aborting
]
stdout[
processing archive bin/classes.jar...
processing com/unity3d/player/a$1.class...
processing com/unity3d/player/a$2.class...
processing com/unity3d/player/a$a.class...
processing com/unity3d/player/a.class...
processing com/unity3d/player/b.class...
processing com/unity3d/player/c$1.class...
processing com/unity3d/player/c$2.class...
processing com/unity3d/player/c.class...
processing com/unity3d/player/d.class...
processing com/unity3d/player/e$1.class...
processing com/unity3d/player/e$2.class...
processing com/unity3d/player/e.class...
processing com/unity3d/player/f.class...
processing com/unity3d/player/g.class...
processing com/unity3d/player/h.class...
processing com/unity3d/player/i.class...
processing com/unity3d/player/j.class...
processing com/unity3d/player/k$1.class...
processing com/unity3d/player/k.class...
processing com/unity3d/player/NativeLoader.class...
processing com/unity3d/player/l.class...
processing com/unity3d/player/PsmMainActivity.class...
processing com/unity3d/player/PsmUnityActivity.class...
processing com/unity3d/player/ReflectionHelper$1.class...
processing com/unity3d/player/ReflectionHelper$a.class...
processing com/unity3d/player/ReflectionHelper.class...
processing com/unity3d/player/m.class...
processing com/unity3d/player/n$1.class...
processing com/unity3d/player/n$2.class...
processing com/unity3d/player/n$3.class...
processing com/unity3d/player/n.class...
processing com/unity3d/player/o.class...
processing com/unity3d/player/p.class...
processing com/unity3d/player/UnityPlayer$1.class...
processing com/unity3d/player/UnityPlayer$2.class...
processing com/unity3d/player/UnityPlayer$4.class...
processing com/unity3d/player/UnityPlayer$5.class...
processing com/unity3d/player/UnityPlayer$6.class...
processing com/unity3d/player/UnityPlayer$7.class...
processing com/unity3d/player/UnityPlayer$8.class...
processing com/unity3d/player/UnityPlayer$9.class...
processing com/unity3d/player/UnityPlayer$10.class...
processing com/unity3d/player/UnityPlayer$11.class...
processing com/unity3d/player/UnityPlayer$12.class...
processing com/unity3d/player/UnityPlayer$13$1.class...
processing com/unity3d/player/UnityPlayer$13.class...
processing com/unity3d/player/UnityPlayer$3.class...
processing com/unity3d/player/UnityPlayer$14.class...
processing com/unity3d/player/UnityPlayer$15.class...
processing com/unity3d/player/UnityPlayer$16.class...
processing com/unity3d/player/UnityPlayer$17.class...
processing com/unity3d/player/UnityPlayer$18.class...
processing com/unity3d/player/UnityPlayer$19.class...
processing com/unity3d/player/UnityPlayer$a.class...
processing com/unity3d/player/UnityPlayer$b.class...
processing com/unity3d/player/UnityPlayer.class...
processing com/unity3d/player/UnityPlayerActivity.class...
processing com/unity3d/player/UnityPlayerNativeActivity.class...
processing com/unity3d/player/UnityPlayerProxyActivity.class...
processing com/unity3d/player/q.class...
processing com/unity3d/player/r$1.class...
processing com/unity3d/player/r.class...
processing com/unity3d/player/WWW.class...
processing org/fmod/FMODAudioDevice$a.class...
processing org/fmod/FMODAudioDevice.class...
processing org/fmod/a.class...
processing bin/classes/./com/google/android/gms/R$attr.class...
processing bin/classes/./com/google/android/gms/R$color.class...
processing bin/classes/./com/google/android/gms/R$drawable.class...
processing bin/classes/./com/google/android/gms/R$id.class...
processing bin/classes/./com/google/android/gms/R$integer.class...
processing bin/classes/./com/google/android/gms/R$string.class...
processing bin/classes/./com/google/android/gms/R$style.class...
processing bin/classes/./com/google/android/gms/R$styleable.class...
processing bin/classes/./com/google/android/gms/R.class...
processing bin/classes/./com/homegrownapps/gochickengo/R$attr.class...
processing bin/classes/./com/homegrownapps/gochickengo/R$color.class...
processing bin/classes/./com/homegrownapps/gochickengo/R$drawable.class...
processing bin/classes/./com/homegrownapps/gochickengo/R$id.class...
processing bin/classes/./com/homegrownapps/gochickengo/R$integer.class...
processing bin/classes/./com/homegrownapps/gochickengo/R$string.class...
processing bin/classes/./com/homegrownapps/gochickengo/R$style.class...
processing bin/classes/./com/homegrownapps/gochickengo/R$styleable.class...
processing bin/classes/./com/homegrownapps/gochickengo/R.class...
processing archive plugins/./unity-plugin-library.jar...
ignored resource META-INF/MANIFEST.MF
processing com/google/unity/ads/Banner$1$1.class...
processing com/google/unity/ads/Banner$1.class...
processing com/google/unity/ads/Banner$2.class...
processing com/google/unity/ads/Banner$3.class...
processing com/google/unity/ads/Banner$4.class...
processing com/google/unity/ads/Banner$5.class...
processing com/google/unity/ads/Banner.class...
processing com/google/unity/ads/Interstitial$1$1.class...
processing com/google/unity/ads/Interstitial$1.class...
processing com/google/unity/ads/Interstitial$2.class...
processing com/google/unity/ads/Interstitial$3.class...
processing com/google/unity/ads/Interstitial.class...
processing com/google/unity/ads/PluginUtils.class...
processing com/google/unity/ads/UnityAdListener.class...
processing archive /Volumes/SAMSUNG/Programming/Unity Android/Go, Chicken, Go!/Temp/StagingArea/android-libraries/google-play-services_lib/libs/./google-play-services.jar...
ignored resource .readme
processing com/google/android/gms/internal/mb.class...
processing com/google/android/gms/internal/mc.class...
processing com/google/android/gms/internal/md.class...
processing com/google/android/gms/internal/mi.class...
processing com/google/android/gms/internal/me.class...
processing com/google/android/gms/internal/mf.class...
processing com/google/android/gms/internal/mg.class...
processing com/google/android/gms/internal/mh.class...
processing com/google/android/gms/internal/ma$a.class...
processing com/google/android/gms/internal/ma.class...
processing com/google/android/gms/internal/lz.class...
processing com/google/android/gms/common/internal/safeparcel/b.class...
processing com/google/android/gms/common/internal/safeparcel/a.class...
processing com/google/android/gms/common/internal/safeparcel/a$a.class...
processing com/google/android/gms/common/internal/safeparcel/SafeParcelable.class...
processing com/google/android/gms/internal/e.class...
processing com/google/android/gms/internal/f$1.class...
processing com/google/android/gms/internal/f$a.class...
processing com/google/android/gms/internal/f$b.class...
processing com/google/android/gms/internal/f$c.class...
processing com/google/android/gms/internal/f$d.class...
processing com/google/android/gms/internal/f$e.class...
processing com/google/android/gms/internal/f$f.class...
processing com/google/android/gms/internal/f$g.class...
processing com/google/android/gms/internal/f$h.class...
processing com/google/android/gms/internal/f$i.class...
processing com/google/android/gms/internal/f$j.class...
processing com/google/android/gms/internal/f$k.class...
processing com/google/android/gms/internal/f$l.class...
processing com/google/android/gms/internal/f$m.class...
processing com/google/android/gms/internal/f.class...
processing com/google/android/gms/internal/g.class...
processing com/google/android/gms/internal/h.class...
processing com/google/android/gms/internal/i.class...
processing com/google/android/gms/internal/j$a.class...
processing com/google/android/gms/internal/j.class...
processing com/google/android/gms/internal/k$a.class...
processing com/google/android/gms/internal/k.class...
processing com/google/android/gms/internal/l.class...
processing com/google/android/gms/internal/m.class...
processing com/google/android/gms/internal/n.class...
processing com/google/android/gms/internal/o.class...
processing com/google/android/gms/internal/p$a.class...
processing com/google/android/gms/internal/p.class...
processing com/google/android/gms/internal/q.class...
processing com/google/android/gms/internal/r.class...
processing com/google/android/gms/internal/ly.class...
processing com/google/android/gms/internal/a.class...
processing com/google/android/gms/internal/b.class...
processing com/google/android/gms/internal/c$j.class...
processing com/google/android/gms/internal/c.class...
processing com/google/android/gms/internal/c$a.class...
processing com/google/android/gms/internal/c$i.class...
processing com/google/android/gms/internal/c$c.class...
processing com/google/android/gms/internal/c$f.class...
processing com/google/android/gms/internal/c$d.class...
processing com/google/android/gms/internal/c$g.class...
processing com/google/android/gms/internal/c$h.class...
processing com/google/android/gms/internal/c$b.class...
processing com/google/android/gms/internal/c$e.class...
processing com/google/android/gms/internal/d$a.class...
processing com/google/android/gms/internal/d.class...
processing com/google/android/gms/internal/s$a.class...
processing com/google/android/gms/internal/s.class...
processing com/google/android/gms/internal/s$a$a.class...
processing com/google/android/gms/location/LocationRequest.class...
processing com/google/android/gms/location/ActivityRecognition$1.class...
processing com/google/android/gms/location/LocationServices$a.class...
processing com/google/android/gms/location/DetectedActivity.class...
processing com/google/android/gms/location/b.class...
processing com/google/android/gms/location/LocationServices.class...
processing com/google/android/gms/location/GeofenceStatusCodes.class...
processing com/google/android/gms/location/FusedLocationProviderApi.class...
processing com/google/android/gms/location/a.class...
processing com/google/android/gms/location/a$a.class...
processing com/google/android/gms/location/LocationStatusCodes.class...
processing com/google/android/gms/location/ActivityRecognition$a.class...
processing com/google/android/gms/location/a$a$a.class...
processing com/google/android/gms/location/ActivityRecognition.class...
processing com/google/android/gms/location/Geofence$Builder.class...
processing com/google/android/gms/location/ActivityRecognitionResult.class...
processing com/google/android/gms/location/LocationClient$OnRemoveGeofencesResultListener.class...
processing com/google/android/gms/location/DetectedActivityCreator.class...
processing com/google/android/gms/location/GeofencingEvent.class...
processing com/google/android/gms/location/Geofence.class...
processing com/google/android/gms/location/LocationClient$OnAddGeofencesResultListener.class...
processing com/google/android/gms/location/ActivityRecognitionClient.class...
processing com/google/android/gms/location/c.class...
processing com/google/android/gms/location/LocationClient.class...
processing com/google/android/gms/location/LocationServices$1.class...
processing com/google/android/gms/location/LocationRequestCreator.class...
processing com/google/android/gms/location/ActivityRecognitionResultCreator.class...
processing com/google/android/gms/location/GeofencingApi.class...
processing com/google/android/gms/location/ActivityRecognitionApi.class...
processing com/google/android/gms/location/LocationListener.class...
processing com/google/android/gms/internal/ja.class...
processing com/google/android/gms/internal/jg$b.class...
processing com/google/android/gms/internal/jc$a.class...
processing com/google/android/gms/internal/jd$2.class...
processing com/google/android/gms/internal/jd$1$1.class...
processing com/google/android/gms/internal/jc$4.class...
processing com/google/android/gms/internal/ji.class...
processing com/google/android/gms/internal/jd$2$1.class...
processing com/google/android/gms/internal/jf$a.class...
processing com/google/android/gms/internal/jj.class...
processing com/google/android/gms/internal/jh.class...
processing com/google/android/gms/internal/jc$3.class...
processing com/google/android/gms/internal/jb.class...
processing com/google/android/gms/internal/jc$1.class...
processing com/google/android/gms/internal/je$a.class...
processing com/google/android/gms/internal/jd.class...
processing com/google/android/gms/internal/je.class...
processing com/google/android/gms/internal/jb$a.class...
processing com/google/android/gms/internal/jd$a.class...
processing com/google/android/gms/internal/jh$1.class...
processing com/google/android/gms/internal/jc$6.class...
processing com/google/android/gms/internal/jd$1.class...
processing com/google/android/gms/internal/jc$7.class...
processing com/google/android/gms/internal/jb$1.class...
processing com/google/android/gms/internal/jb$2.class...
processing com/google/android/gms/internal/jk.class...
processing com/google/android/gms/internal/jd$3.class...
processing com/google/android/gms/internal/jh$a.class...
processing com/google/android/gms/internal/jc.class...
processing com/google/android/gms/internal/jh$b.class...
processing com/google/android/gms/internal/jg.class...
processing com/google/android/gms/internal/jg$a.class...
processing com/google/android/gms/internal/je$a$a.class...
processing com/google/android/gms/internal/jh$c.class...
processing com/google/android/gms/internal/jc$5.class...
processing com/google/android/gms/internal/jd$3$1.class...
processing com/google/android/gms/internal/jh$d.class...
processing com/google/android/gms/internal/jf.class...
processing com/google/android/gms/internal/jf$a$a.class...
processing com/google/android/gms/internal/jc$2.class...
processing com/google/android/gms/internal/jq.class...
processing com/google/android/gms/internal/jm.class...
processing com/google/android/gms/internal/jp.class...
processing com/google/android/gms/internal/jx.class...
processing com/google/android/gms/internal/jl.class...
processing com/google/android/gms/internal/jr.class...
processing com/google/android/gms/internal/jv.class...
processing com/google/android/gms/internal/jy.class...
processing com/google/android/gms/internal/ju.class...
processing com/google/android/gms/internal/jt.class...
processing com/google/android/gms/internal/jo.class...
processing com/google/android/gms/internal/jn.class...
processing com/google/android/gms/internal/js.class...
processing com/google/android/gms/internal/jw.class...
processing com/google/android/gms/internal/jz$a$a.class...
processing com/google/android/gms/internal/jz$a.class...
processing com/google/android/gms/internal/kc.class...
processing com/google/android/gms/internal/ka.class...
processing com/go

```

My 'Assets' directory contains plugins, which contains android and ios, the android folder containing my own AndroidManifest.xml and google-play-services-libs (from the most recent Android SDK update).

# Answer
> 1 votes
Here are some things to try out:

1. Try doing a Reimport All.
2. Do you have any duplicate modues ? (like two modules for In-app billing plugins). Getting rid of the surplus one entirely should solve it.
3. When I ran into this recently, it seems to be caused by using a JAR which references classes.jar for android. It seems that I must reference the AndroidDevelopmentPlayer version when building my JAR if I want to build a development player the AndroidPlayer version if I'm not. I guess this kinda makes sense, but it also seems a little weird, since it's just a reference.

# Answer
> 1 votes
I think you have created many jar files.

**Combine the two or more jar files into one and give them the same package name.**

If you get the jar file from Eclipse, **create more classes in the same package**, and call this package name into your plugin. This will be a better choice.

---
Tags: unity, android, unityscript, google-play-services, advertisements
---


title: Set up a basic D3DXQUATERNION

text:
# Question
Title: Set up a basic D3DXQUATERNION
I'm trying to set up a D3DXQUATERNION to operate a rotation of 90 degrees around the Y axis.

I tried in the following way:

```
D3DXQUATERNION tempRot1(0.0f, 1.0f, 0.0f, cos(XM_PIDIV2/2));

```

because in the documentation they write that the fourth component, w, is defined as:

```
q.w = cos(theta/2)

```

But I'm afraid I didn't understand correctly, since the rotation is not what I expected.

# Answer
Ok, i didn't read carefully enough the documentations, it states that:

```
q.x = sin(theta/2) * axis.x
q.y = sin(theta/2) * axis.y
q.z = sin(theta/2) * axis.z
q.w = cos(theta/2)

```

so in my case i had to write:

```
D3DXQUATERNION tempRot1(0.0f, sin(XM_PIDIV2 / 2), 0.0f, cos(XM_PIDIV2 / 2));

```
> 1 votes

---
Tags: directx, quaternion
---


# Question
Title: How to make the wheels rotate depending on the speed of the vehicle
I want to know what the right formula is, or a way to make the wheels rotate with the speed of the vehicle? What is the standard way to make wheels look realistic and natural? Do developers use other techniques?

Thank you for helping

# Answer
When you are using the Unity physics system, the engine offers you a `WheelCollider` which handles wheel physics for you.

Usual practice is that the wheel colliders are not attached to the wheel mesh but rather to the vehicle body directly. So they are supposed to simulate "invisible" wheels. You then control the vehicle by changing the `motorTorque`, `brakeTorque` and `steerAngle` of each wheel and let the physics engine do the rest.

You can then use `wheelCollider.GetWorldPose()` to get the current position and rotation of each simulated wheel and assign these to the visible but non-physical wheel models.
> 4 votes

# Answer
The idea is that you need to have the outer part of the wheel go on the ground at the same speed that the one of the vehicle.

Assuming you have these values beforehand:

```
vehicle_speed  // in meters per second
wheel_radius   // in meters

```

You can infer this one:

```
wheel_circumference = 2 * PI * wheel_radius // still in meters

```

You can then get the rotation per second for the wheels:

```
rot_per_second = vehicle_speed / wheel_circumference

```

Now, this will not take into consideration the fact that the front wheels will turn on the vertical axis to make the vehicle steer, and that the inside wheels will roll less than the outside ones when the vehicle steer. It is, however, enough for you to simulate the wheels animation on your vehicle.
> 3 votes

---
Tags: unity, unityscript
---


title: onHold input libGDX

text:
# Question
Title: onHold input libGDX
I want to have `onHold` or `onTouch` input for my game. So as long as the user touches the screen something happens (a car moves) and when he stops touching the screen it stops. How do I do that?

**I want my input in the `handleInput` area:**

***MyInputProcessor class***

```
public class MyInputProcessor implements InputProcessor {
@Override
public boolean keyDown(int keycode) {
    return false;
}

@Override
public boolean keyUp(int keycode) {
    return false;
}

@Override
public boolean keyTyped(char character) {
    return false;
}

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    return false;
}

@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
    return false;
}

@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
    return false;
}

@Override
public boolean mouseMoved(int screenX, int screenY) {
    return false;
}

@Override
public boolean scrolled(int amount) {
    return false;
}

```

}

***My PlayState class:***

```
 public class PlayState extends State  {

MyInputProcessor inputProcessor = new MyInputProcessor();

public PlayState(GameStateManager gsm) {
super(gsm);
Gdx.input.setInputProcessor(inputProcessor);
 }

@Override
protected void handleInput() {

 if(inputProcessor.touchDown(**"asks for four ints"**)){

    }

}

@Override
public void update(float dt) {

handleInput();
 }

```

**what do I add in `HandleInput` if I want the action to occur whenever the user holds(keeps touching) the screen (anywhere on the screen).**

# Answer
The `InputProcessor` interface has `touchDown()` and `touchUp()` methods. Create a class that implements the `InputProcessor` interface and then give it to libgdx via

```
MyInputProcessor inputProcessor = new MyInputProcessor();
Gdx.input.setInputProcessor(inputProcessor);

```

I thought I should also note that if you are using scene2d and you want to react only when a specific actor is touched, then you first setup an `InputListener` on the actor

```
actor.addListener(new InputListener() {
  public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
      System.out.println("down");
      return true;
  }

  public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
      System.out.println("up");
  }
});

```

And then give the stage to libgdx as the `InputProcessor`

```
Gdx.input.setInputProcessor(myStage);

```

Should you need more information about input handling, here is the wiki page

**Edit:**

Since you updated your question, here's my updated answer.

Part of your problem is that your are using a `GestureListener` which is probably more complex than you really wanted. You don't need to know about longpress or tap or fling, just switch to a vanilla `InputProcessor` so that you have access to the `touchUp()` and `touchDown()` method.

The floats in the `touchUp()` and `touchDown()` calls are the x and y coordinates of the user's touch. If you give your `InputProcessor` to libgdx as described above, you don't need to call `touchUp()` or `touchDown()` manually. They will automatically be called when the user touches the screen.

As far as doing something like moving a car when the user touches the screen, here's a simplified example of how to do it:

On your car class, have a `boolean` that means whether or not the car is moving. On `touchDown()` set it to true and on `touchUp()` set it to false. Then in your render loop do an update step like this

```
public void render(){
    if(car.isMoving()){
       //move the car in the direction and amount that you want
       car.move();
    }
    //render the car
}

```

Now if you want to steer the car based on where the user touched, you would have to give the touchDown x and y location to the car class and let it determine which direction to go. Nevertheless, the basic principle is the same.
> 0 votes

---
Tags: java, libgdx
---


# Question
Title: Plugins for creating and styling custom Editor Windows like C#/C++ Form Designer or “Web Inspector”?
`Unity3d` allows to construct window with custom UI. Just need to use `EditorGUI/EditorGUILayout` classes and their static methods. Example of custom window:

The problem is that all the components have to be added manually via script. Then need to save, switch to Editor, wait for little compile things, and then we can see the result.

In web-development people use `Web Inspector` (for example, we can press `F12` in `chrome`, Tab `Elements` -\> `Styles`). We can add all needed properties to element and can see the result in real-time.

**EDIT.** another example (better than previous): we know `C# winFormApp`, `C++ MFC` e.t.c, which has form designer. We can choose any elements and set their properties:

It would be nice to have similar plugins for Unity

So. Does `Unity3d` have similar tools, utilities, plugins? Utilities to inspect code and editing styles (position, margin, padding, background, width, height, color e.t.c.)?

# Answer
> 1 votes
Well, I found something interesting...Editor window designer

The plugin is almost what I need

The project had been started but not completed yet. As the author says: he decided to release Editor Window Designer as an open source project, that code is here

For now plugin allows add elements and styling them (position, padding, width, height, e.t.c) Base demo window:

And here is hierarchy window and properties of concrete element

I wonder why Unity developers (or someone else) still didn't do something like that? It is very useful and necessary thing...

# Answer
> 0 votes
No, since the scripts are compiled (before run) and therefore can't be manipulated at runtime. However: you could add debug fields to your scripts to change certain fields (let's say a color or so).

---
Tags: unity, tools
---