# Question
Title: How can I extract sprites from a SNES games?
Planning to use some sprites for a fan project but the sprites I want haven't been ripped yet; how can I extract them in a usable form?

# Answer
The easiest way is probably with an emulator, the pront screeb button, and an eraser tool.

You could also open the game files with an editor, and copy them.
> -1 votes

---
Tags: 2d
---


# Question
Title: How can I communicate a Joystick with a SurfaceView?
I have two classes:

* JoystickView (Extends View).
* GameView (Extends SurfaceView): It will be updated by a Thread that call the onDraw Method.

Now, if I retrieve a direction by OnTouchEvent inside the JoystickView, how can send this information to the GameView? Can I use another thread for JoystickView and allow a communication between the thread of Joystick and the thread of the GameView? otherwise how can I do this?

# Answer
Create a callback interface that the `JoystickView` fires when it sees an event, then make the `GameView` implement that interface and register itself as a listener to the `JoystickView`.

A simple approach could look something like this;

```
public interface JoystickListener {
  boolean onJoystickEvent(MotionEvent e);
}

public class JoystickView extends View {

  private JoystickListener listener;

  public void setListener(JoystickListener listener) {
    this.listener = listener;
  }

  @Override
  public boolean onTouchEvent(MotionEvent e) {
    if (listener != null)
      listener.onJoystickEvent(e);
  }
}

public class GameView extends SurfaceView implements JoystickListener {
  public boolean onJoystickEvent(MotionEvent e) {
    // Handle the joytstick event here
  }
}

public class YourGameActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    JoystickView jv = (JoystickView)findViewById(id_of_joystick_view);
    GameView gv = (GameView)findViewById(id_of_game_view);

    jv.setListener(gv);
  }
}

```

Note that the data passed to the listener does not have to be a `MotionEvent`, it would probably be better if it was something that had already figured out the relevant information from the `MotionEvent`.
> 0 votes

---
Tags: android, view
---


# Question
Title: How to make rigid body move smoothly on uneven platform?
Right now I'm using Rigidbody2d for the game character along with polygon collider 2D(2d platform game).

I'm beginner hope I'm using correct components.

And transform to move character from left to right.

```
Character.transform.Translate(Vector2.right * speed * Time.deltaTime);

```

And upward(jump).

```
Character.transform.Translate(Vector2.up * speed * Time.deltaTime);

```

When the game character moves on slopes there's lot of friction and bounciness and rotation and its worse when jumping from slopes.

# Answer
It is recommended to move through `Rigidbody` so that you can achieve natural behavior.

To do so, you can follow the following simple steps and write the following code in the script attached to your character.

```
// Class level variable
Rigidbody2D _rb;

void Start()
{
    // Assigning rigidbody2d component to variable
    _rb = GetComponent<Rigidbody2D>();
}

void Update()
{
    // Setting speed along x-axis
    _rb.velocity = new Vector2(speed,_rb.velocity.y);

    // For now it will jump on strike of space key. Please change it according to your input mehtod
    if (Input.GetKey(KeyCode.Space)){
        Jump();
    }
}

void Jump()
{
    // 300 is the jump force. Do change it accordingly.
    _rb.AddForce(0,300);
}

```
> 1 votes

# Answer
Dont use transform.Translate. it completely ignores collision. Try using rigidbody instead. It will make the movement smoother too
> 1 votes

---
Tags: unity, physics, rigidbody
---


# Question
Title: How to give the player the feeling of being chased by enemies and force him/her to rush
I have already asked a question about the difficulty progression in my endless runner game: How to make difficulty progression in my endless-runner game?

Now I have to decided that it is a good approach to make the following:

1. Camera is always drifting up, slowly, but preventing the player from idling.
2. If squirrels jump, the camera follows them and the spiders also update their position to be slightly below visible area. Their speed is a little bit faster than the camera's drifting speed, so the player will panic out of the fear of the spiders catching them.
3. Something else?

I want to make feel of constant chase by spiders and force player to run, make quick decisions and make mistakes. Player need to know exactly how close the spiders to squirrels are.

P.S: You can see earlier version of this game here: http://ludumdare.com/compo/ludum-dare-34/?action=preview&uid=66055

**EDIT**: The problem is that spiders are always relatively close to player and distance between them and the spiders matters. Once spiders have left the visible area, player feels safe. Firstly, spiders run with constant speed and if the player runs a little bit faster, he is always in the safe area and doesn't see any spiders.

The idea is to have player under pressure all time. The difficulty is that the visible area between the spiders and squirrels is small

**FINAL DECISION**: The final decision was made because of majority votes, and I suppose this answer suits for many games. But there is more than one good answer, and most of the answers are worth reading and implementing. That is what I am going to do.

Thanks everyone for your great answers!

FINAL NOTE: you can check final implementation finding released game on market - https://play.google.com/store/apps/details?id=by.Ludum.Vaverki

# Answer
3. Music.

Music is probably the most effective way to express feelings.

If you manage to use the appropiate song that tells "Danger, run!", that is better than any camera movement (If you combine music with those kind of effects, it gets even better, of course).

Imagine playing Silent Hill with david guetta music, that would make Silent Hill a joke, you would laugh at every monster you see.

**Edit:** As some other users have mentioned, a lot of people play mobile games without sound, music is still my favourite option, but the second one would be:

4. Color

Color is easy to understand and easy to implement as visual feedback, you can make the environment get different color tones depending on the distance from the spiders to the player. Usually, Red/Orange toned colors symbolize "Danger" and Blue/Green toned colors symbolize "Peace/Calm".

(Color blind people might have problems with this if not implemented correctly (It is not easy though, be careful)).
> 58 votes

# Answer
In order to keep player engaged, my advises are:

1) moving camera up: slowly is good, but you can choose to change camera's speed in more challenging levels,

2) camera position: you have a lot of options here, I suggest you to read carefully this great article about scrolling techniques and camera positioning

3) music (see Mayuso answer): a dynamic music system that change music from relaxing to more rhythm with some sort of "sine" or "cosine" with higher frequency for more advanced levels

4) background: engage player and force action using background animations. I don't remember right now the game of an endless runner that show alien ships on background and following attack on the city. The point is that player could be engaged and forced to play just to see "how story in background" continues.

5) bonus: players loves bonuses and make clear that collect bonuses is a good thing (with indicators, levels, challenges, etc..) can help. I think a good example of bonuses are those change also player graphical representations, so player can "feel" more advancements. For example think about a warrior in Diablo series with basic armor and then with plate armor

6) combos: if players know that make more and more in game resolve into combos and more points (I assume you have some sort of list of best points)

7) gamification: sounds funny, but a lot of game can be "gamificated" in order to force player to play more. For and example of such concepts see here

8) precision: many games today have simple rules but force player to plan moves and make it perfectly. "Simple to rule, hard to master", few ideas:

1. Spelunky, in this game there is also a ghost enemy that chase player after some times. So if you stay still as player, you simply lose after some minutes
2. Super Meat boy
3. VVVVVV

9) challenge player verbally: make clear with audio or text that game itself challenge player. For example "You can do better, right?" "Only first level?" "NOOB!" and create a "fake enemy" behind the game itself

10) difficulty: more you play, more becomes difficult. Like in Risk of rain where with a nice mix of different enemies behaviors and increasing difficulty keep player engaged
> 19 votes

# Answer
You mention that the user feels "safe" if the spiders are all offscreen. This is probably the most important thing to address. Fortunately, you want the right kind of thing: a gut feeling that the user has that nothing is ever safe.

The "gut feeling" people get is an amalgamation of many small cues that the brain processes together to try to guestimate an unknown (in this case, the position of the spiders). Your goal should be to provide many small clues in many different ways, visual and auditory, rather than trying to come up with one big clue which tells you where the spider is.

Many have mentioned music. Sound is always good for gut feeling effects because we humans use it for wide awareness of our surroundings. It's the thing which tells us to stop focusing on trying to fix our radio because there's a zombie behind us. However, visual effects can also be used. You just need to make the spiders have a *presence*. A few ideas:

* Have lots of small animals in the background which start to flee as the spiders get closer.
* Play games with color saturation when the spiders are near. Maybe when they are far away, everything is fully saturated, but when they are getting near, the non-essential parts of the background start to lose saturation, like the color draining from someone's cheeks.
* Cues from the squirrel. The player controls their movement, but they don't control any animated twitches the squirrel has. Perhaps the squirrel could show panic as the spiders get close.
* Music cues, obviously
* Sounds associated with the spider, getting louder.

**How you present these effects as the spiders close in is more important than anything else**. The gut feeling parts of the brain work almost entirely on logarithmic scales. Thus we get the same amount of relief from the spider moving from 1 to 2 units away as we get from the spider moving from 2 to 4 or from 10 to 20. Cues which work to this scale will be more well received than anything else.

Take the spider sounds, for instance. Instead of just having one spider sound which gets louder as they get closer, consider having multiple, which all come in at different rates. Perhaps have the music start to change when the spiders are 8 feet away. Around 4 feet away, you start fading in the sound of their scratching legs against the trees. When you get to 2 feet away (which may be right off screen), you could start hearing the noises from them mashing their mouth parts hungrily (why not... they're evil spiders!).

You don't always have to use powers of 2, though they are obviously natural for game developers. Maybe the small animals flee when the spider is at 30 feet away, and the squirrel starts looking visibly nervous when they get 10 feet away. Then, at 3.3 feet, color drains from the background.

Of course, for all of these, its best to fade the effects in gradually. That way, for any spider distance, the player's gut has many smoothly varying signals with which to develop its gut feeling for where the spiders are. The more small signals the player is paying attention to, the more they will be drawn into the moment. This is the real key. A small number of obvious cues will have less effect than a large multitude of small cues which all operate on different scales, and ideally you want to let the user construct a reasonably logarithmic worldview using those cues.
> 9 votes

# Answer
A solid case study would be the game "Prince of Persia : Warrior Within"

It has many chase scenes and it is by far the best chase sequence of any game till date unless you go into the horror genera where chases are generic and sort of name of the game.

The game combines two of the most influential senses of humans which react to fear.

* Sight : When the character "Dhahaka" (which acts as the Antagonist and chases the prince) appears on the screen , the closer he is to you the colour starts to fade and the screen becomes a grey tone.This creates a sense of urgency.
* Sound : as mentioned by many already, a good soundtrack especially for the chase sequence would be monumentally critical. the game in our study uses a popular metal song and uses it exclusively when the Dahaka starts the chase sequence and not anywhere in the game.

So as you hear the music and screen goes black & white you basically shit your pants.

To add additional obstacles to the path which will slow down the linearity of the run.

You can add , one hit kill to create even more urgency.
> 6 votes

# Answer
1. Create something that the player wouldn't want to happen.
2. Show it happening in a harmless setting (cutscene is allowed, can happen to other characters).
3. Create a situation where it is obvious that the player will experience the undesirable outcome unless he acts soon.

Everything else (action music and funky camera effects) is just superficial fluff that will fade away rather soon. Player's knowledge is everything.

(Source: developer commentary of some HL2 game, independent design research).
> 3 votes

# Answer
The spiders are coming after you, but cooperatively.

One gets ahead, then it sends silk back to the other ones. Which are pulled up.

They advance exponentially.

How close the horde is then becomes a measure of how *many* spiders are close, instead of how close the front-edge of the spiders are.

The handful of spiders that get close also send webs *at* the player. At below the critical threshold, these just annoy the player in some way. Above the threshold, they are fatal.

If there is one lone spider pulling a buddy up, they are far behind.

If there are 7 spiders all pulling buddies, they are closer.

If there are 20 spiders, they are almost ready to overtake you.

If there are 50 spiders, they catch you in their web.

These spiders also advance in leaps and bounds. So even if you outrun the spiders, one will sometimes "catch up". But then you'll outrun that one for a short bit. The length of the "gap" grows (logarithmicly), and the chance that a second spider "pulled" by first one before it leaves the screen also shows up goes down.

Now, even when the spiders are far away, sometimes a huge clump will catch up and attempt to attack with webs. The frequency of this also goes down as you get further and further ahead (again, logarithmicly; so it never never happens).
> 3 votes

# Answer
Since you seem to want a precise visual representation of just how close the spiders are...

These are all valid visual representations of timers/progress bars/distance

* Numbers. Such as a timer in seconds or the specific value the spiders are at such as \[7/10\] (*where 10 means player is dead*), or the distance between spiders and squirrel.
* Fancier numbers. The timer or progress bar gains a more visual representation, while the numbers themselves may still be visible (*but probably not*). This could be a progress bar filling with spiders with a squirrel at the top, an image of a spider reaching towards a squirrel in the corner representing distance, a big spider at the top of the screen whose eyes start to glow red and mouth starts to ooze green... Whatever little thing you want to represent the player getting caught by the spiders you want. The image should catch the squirrel when the player dies or it may seem a little anti-climatic.
* Not too obtrusive visual hinting. Like another answer mentions, this could be a transition into gray-scale colors, or spiders slowly closing in from the edges of the screen. The progress bar in this case is the degree of gray-scale or the amount of screen space the spiders are taking over. By blocking the screen you may also be causing even further mistakes. (But hopefully not in a *cheap* way)
* Lunging spiders lurking below the screen. This is similar to your idea for spiders to slowly catch up to the squirrel. The idea is that, instead of getting (*extremely slowly and uneventfully*) closer and closer, the spiders occasionally *lunge* for the squirrel. How often they lunge and how close they get depends on how close to getting the squirrel they are. This should create a moment of panic while the spider is going for the squirrel.

---

Note that a more solid visual representation such as the first two can be used in conjunction with the more subtle hints like the second two. Also, keep in mind that when you are trying to test for the overall *experience*, you should include every part of the experience when you test - which is why other answers mention music.
> 1 votes

# Answer
* Ambience music. As Mayuso stated, the worst and scariest thing in every Silent Hill game was music.
* Since mobile games are mostly played without sound, you should add any visual indicator of how close the spiders "can" be. Maybe web cobs flying randomly, flying leafs, dust,.. etc,. some kind of environment destruction, but not sctrictly attached to the spiders speed. That makes the player to know something wrong its going to happen soon, but not exactly when.
* Add some leaping spiders, with random jump length. If the player knows exactly where is the point when the spiders kill you,that makes some kind of safety feeling. But if the spiders can kill you sooner by leaping randomly, that makes it harder to know when are you going to die if you're not fast enough. Also, that brings you another choice to increase difficulty.
> 1 votes

# Answer
As some have already pointed out, you can cause the feeling of rush based on sound, color and graphics .

To make things clear, I'll leave the following examples:

* Resident Evil 3:Nemesis: During the game theres tension caused by a quiet sound that hints that nemesis is around somewhere, sudently it appears and the music changes to a stressful tone.
* Sonic: Any sonic water levels, you have to catch bubbles to bread, if you stay too long under water a theme with increasing tempo will play and a visual indicator of the time left to catch a bubble will blink on screen. Example:https://youtu.be/vdRBVdOAnf0

After playing your game I think that you do an approach similar to Sonic:
Flash the screen or bottom part of the screen the following way:

* Yellow: Spiders are barely visible.
* Orange: Spiders are half way to get you.
* Red: You're almost dead.

Playing a fast paced theme with increasing tempo would also help, or at least a theme that warns the user to the incoming danger.
> 0 votes

# Answer
sound of enemy(ies) approaching fused with music that hints danger to give the player a "rush" and visual effects that can dusturb the player into making a mistake.
> -3 votes

---
Tags: game-design, balance, casual-games
---


# Question
Title: LibGDX - Best way of scrolling background
I'm new to `LibGDX` and i'm trying to implement a screen where i have a guy running and the ground under him scrolling to give impression he is really running in a sidewalk for example.

The ground should be interactive meaning it will not only change his colors or `Texture` but there will also be holes in it and so on. As you can see from the picture below each brick is a `Block` Object and i'd like to keep it this way.

Do you think in this case the best thing is to move the camera so i can show the screen ahead or try to scroll the background elements editing their position?

**Update**

So to be more clear, each block is separated from the others so it is impossible to "scroll the background" since there is no a real background, also each block will have different properties, it means it can be a block or a hole or whatever, basically i see the possibility of the scrolling camera as only solution.

# Answer
Moving background has slightly better performance than moving camera. On the other hand, moving camera is more intuitive and that's what we see in real life. It's all up to you.
> 1 votes

# Answer
You could move the background or make a new orthographic camera. Then do some thing like

```
camera.setPosition(player.x, player.y);

```
> 1 votes

# Answer
I had made a game similar to yours with almost similar logic ,I had moved camera,instead of moving each element individually as moving camera is easier and saves lot of logic's. I had a class cameraHelper that gets and sets all necessary details about camera

```
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Vector3;

public class CameraHelper {

    Vector3 position;

    OrthographicCamera camera;

    public Vector3 getPosition()
    {
        return position;
    }
    public void setPosition()
    {
    camera.position.set(position);
    }
    public void update(float deltaTime,int velocity)
    {
        position.y=position.y+deltaTime*velocity*60;
        setPosition();

    }
}

```

The below is the render loop to scroll the background and draws the background based on the position of the camera

```
@Override
    public void render(SpriteBatch batch)//draw background on screen
    {
        if(cameraHelp.getPosition().y-height/2>=j*height)
        {

            k=j;
            j=j+2;
        }
        for ( i = k; i < j+1; i++)
            batch.draw(backgroundTexture, 0, i * height, width, height);

    }

```
> 0 votes

---
Tags: java, libgdx, side-scroller
---


# Question
Title: Changing the central point for transform
I'm trying to rotate all sprites in the view port around a central character. I have made some progress, using the following I can get my ship to rotate around the coordinates 0,0, with the radius being the initial placement of the ship. How do I move the point that my ship will revolve around? If I try adding NewPoint to any meaningful screen position the ship buggers off!

```
    Dim NewPoint As New Vector2
    NewPoint = Vector2.Transform(Ship.Position, Matrix.CreateRotationZ(Ship.ShipAngle))
    Ship.Position = NewPoint
    Ship.RotationValue = Ship.ShipAngle

```

Thanks for all your help with this folks, I do appreciate it.

# Answer
> 2 votes
You need to:

1. "Move" the origin - translate the ship by `-CenterPos` (the position of central character)
2. Do the desired rotating
3. Move back translating by `CenterPos`

tip: automate the process by creating a function like `RotateAround(Point)`
see any "transformation composition" tutorial for detailed explanation.

# Answer
> 0 votes
With Many thanks.

```
        Ship.TransformValue = -0.1
        Ship.ShipAngle = Ship.TransformValue

        Dim LocalPosition As New Vector2(Ship.Position.X - cPosition.X, Ship.Position.Y - cPosition.Y)
        Dim TransormPosition As Vector2 = Vector2.Transform(LocalPosition, Matrix.CreateRotationZ(Ship.ShipAngle))

        Ship.Position = cPosition + TransormPosition

        Ship.RotationValue = Ship.ShipAngle
        Ship.Rotation += Ship.RotationValue

```

# Answer
> -1 votes
translate your object with the same amount as the difference between the original rotating ankle and the new one, then rotate it.

Let's assume, your object is in 2d space, is 50 pixels wide and high, and you want your new ankle to be in the top left corner, inszead kf in the middle, then you would wanto to translate the object wirh 25 pixels on the x, and 25 pixels om the y axis, then rotate it.

---
Tags: rotation
---


title: Doom-style 2.5D Movement Animations

text:
# Question
Title: Doom-style 2.5D Movement Animations
I've started working on a demo for my 2.5D game. For a basic scene I figured I would just use the good old fashioned doom sprites textured to a double sided plane. Simple enough. But I've been scratching my head as to how to display the proper sprite animation relative to the player viewing the sprite...if that makes since.

For example suppose I have three players in the scene Players A, B, and C as such:

Player C should see player A as: Here's an example of what I think player A should look like from C's perspective:

While player B would see player A as follows:

My current idea is that for any given player, I will need to know the current direction of each other player, and where they are located/moving to relativly. From this, I could calculate which sprite image is required.

Is this correct? What improvements/optimizations could be made?

\** **EDIT** \** Total number of directions will be 8 as depicted below:

For each direction there are two sprites (to show walking movement, sprites for the right hand directions are mirrors of the left):

\** **EDIT 2** \** Got this working and have a simple javascript/threejs example for anyone interested: https://github.com/commanderZiltoid/threejs-2.5d-fps

# Answer
> 2 votes
You would need to know the angle to the element from the spectator, so, if you have

```
A    |
| \aº|
|bº\ |
|   \|
|    B

```

where the lines marked with pipes "|" are the "facing" directions, the diagonal is the "attack line", aº is the angle between B sight and A (-30deg) and bº is the angle between A sight and B (-30deg).

You had to add the angles to see the angle of vision (-60deg). that's the rotation of the element, you only have to set the sprite tile that's closer to that rotation angle.

---
Tags: animation, sprites, movement, 2.5d
---


# Question
Title: How to do placeable electricity cables that work like the ones in "Prison Architect"
I would like to know one (of the probably many) ways to code a (sort of) `Prison-Architect`-ish electricity cable building system.

Here's a picture of what I mean:

1. How can I detect that cables are connected?
2. How can I detect if the block it's connected to is a power source?

And these 2 (above) will all be placed inside a dictionary when they are placed.

That dictionary does not yet have a key type, but the second type is a `sprite`.

How should I do this?

# Answer
> 8 votes
The easiest way is giving a variable "conected = false" to every electric item and then, starting from a energy source, do the following:

```
function adjacents(tile){
    return [
        getTile(tile.x-1,tile.y-1), getTile(tile.x,tile.y-1), getTile(tile.x+1,tile.y-1),
        getTile(tile.x-1,tile.y), tile, getTile(tile.x+1,tile.y),
        getTile(tile.x-1,tile.y+1), getTile(tile.x,tile.y+1), getTile(tile.x+1,tile.y+1),
    ]
}

// DO FOR EVERY TILE DIRECTLY CONECTED TO THE ELECTRICITY SOURCE
tile.checkAdjacents = function(){
    var adjacents = adjacents(this);

    for(var a in adjacents)
    if(adjacents[a].type == "cable" || adjacents[a].type == "electricItem"){
       adjacents[a].connected = true;
       adjacents[a].checkAdjacents();
       return true;
   }
}

return false;

```

So it'll be setting all conected cables to "connected=true"

# Answer
> 3 votes
Prison Architect uses "pieces" of cables, it is not all one long cable, it is a sum of lots of "pieces" (or squares, not sure how to define it):

Image here (The bright green conected pieces are cables)

I don´t know how they do it, and I bet they are not going to tell us, but I can tell you how I would do it.

1. Assign each "piece" of cable an state (an integer, for example).

You assign each of this states to two sides (Up and down, Up and left(For turns, for example), Left and Right...., all the combinations).

(**Edit:** You can also do this with four booleans, `up`, `down`, `left`, `right`, **This might be a lot easier**)

You then can run a loop checking this state in each piece of cable and determine if they are connected to the left, right, up or down. (They will be conected if there is cable in this position).
2. Assuming (1) is implemented, you only need to check if one of those conected cables is a power source. (For example adding each piece of cable a boolean `isPowerSource`)

I hope I explained that well, my english is not really good.

---
Tags: algorithm
---


# Question
Title: How do I remove specfic OptionData from Dropdown?
How would I remove one of the elements from the dropdown? For example, how would I remove Sprites? Here is my code:

```
public Dropdown researchFeatureDropDown;
researchFeatureDropDown.options.Add(new Dropdown.OptionData("Sprites"));
researchFeatureDropDown.options.Add(new Dropdown.OptionData("Scrolling - 2000"));

```

# Answer
The `options` property is a `List<OptionData>`, and there are no other obvious methods for removing items on the `Dropdown` type itself (other than `ClearOptions`, which empties the entire list).

Based on the principle of good API design that says one should make an API easy to use correctly and hard to misuse, it's reasonable to then conclude that you just manipulate the `options` list directly (especially since that's how you put items in the list in the first place\`).

Thus, you can use `RemoveAt` to remove an item by index, or `Remove` to remove it if you have the actual item object itself.
> 1 votes

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


# Question
Title: Creating a Melee Weapon in Box2D (libGDX)
I am struggling with how to implement a melee weapon that can swing when a key is pressed.

I am imagining two different attacks (stab and swing)

I have tried creating two fixtures (character + weapon), two different bodies, two different bodies + revolute joint, but I can not code it to behave the way I imagine it to look like.

STAB:

So with the press of a button, a body/fixture (sensor) would come out for ~1 second and then disappear (alternatively, the body/fixture could always be on the hero and just rotate 90 degrees around the vertices when pressed, and then rotate back to normal)

SWING:

Same thing, but now the weapon will start from the top and swing downwards. Weapon will also be a sensor.

What I have tried:

I created two dynamic bodies.

The weapon has to follow the hero, so I used a revolute joint to hold them together. When a key is pressed, I set the angular velocity of the weapon to a number. However, the weapon will continue to spin after I let go of the key. I tried implementing an if check (if angle is greater than \___, set angular velocity to zero). However, that just means the weapon will stop spinning when I press the key a second time.

# Answer
> 2 votes
Incidentally, I have done exactly what you are trying to do. The only catch is I was using Jbox2d so the code is in Java, but you should still be able to figure it out if you are using C++

You basically need to use joints/motors and all that fun stuff if you want to do swinging action. Here's a snippet of what my code looks like based on the key input:

```
    if (myinput.mouse0) {

        agents.get(0).rightForeJoint.enableMotor(true);
        agents.get(0).rightArmJoint.enableMotor(false);

        if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)){
            agents.get(0).rightForeJoint.enableMotor(false);
        }

        mouseY = Mouse.getY();
        mouseX = Mouse.getX();
        float temp = mouseY - prevPos[1];

        float temp2 = -mouseX + prevPos[0];

        temp2 *= modifier; temp2 *= 0.000026;
        temp  *= modifier; temp  *= 0.000030;

        agents.get(0).armR.applyAngularImpulse(-temp);
        agents.get(0).foreR.applyAngularImpulse(temp2);

        prevPos[1] = mouseY;
        prevPos[0] = mouseX;

        if(temp2 < 0){
            temp2 *=-1;
        }
        if(temp < 0){
            temp *=-1;
        }
        fatigueDrain += temp2;
        fatigueDrain += temp;

    }

```

And then as far as actually building the arms and whatnot, the snippet looks like this.

```
    // RIGHTARM //
    this.rightArmDef = new RevoluteJointDef();
        this.rightArmDef.bodyA = this.torso ; this.rightArmDef.bodyB = this.armR;
        this.rightArmDef.collideConnected = false;

        torso_armL_pin = new Vec2(0.50f, +0.05f);
        local_armL_pin = new Vec2(0.14f, 0.14f);

        this.rightArmDef.localAnchorA.set(this.torso.getLocalCenter().add(torso_armL_pin));
        this.rightArmDef.localAnchorB.set(this.armR.getLocalCenter().add(local_armL_pin));

        this.rightArmDef.enableMotor = true;
        this.rightArmDef.motorSpeed = 0f;
        this.rightArmDef.maxMotorTorque =10f;

        this.rightArmDef.enableLimit = true;
        this.rightArmDef.lowerAngle = 1.2f;// * DEGTORAD;
        this.rightArmDef.upperAngle = 5;
    this.rightArmJoint = (RevoluteJoint)world.createJoint(this.rightArmDef);

```

I realize there is a lot going on here, but its probably easier if you just ask me what you need clarity on and I explain it. If you have never used any of these things though, you will probably need to do a fair bit of reading.

EDIT\>\>

Realize, Box2d has all of the collision detection and physics built clean into its libraries. Take it on faith when I say, it is easier to figure out their system than try and do things from scratch. If you want collision, you use fixtures bodydefs, if you want them to rotate or move, you use joints. It may seem a little more complicated at first, but in the end it saves you infinitely more time to use their methods.

In fact, I would suggest that you probably will never finish if you try and do things from scratch, assuming you are creating a physics game. Because computing things like friction, buoyancy and not to mention, /efficient/ collision detection, is going to take you a lifetime.

# Answer
> 1 votes
I have found some sort of a workaround this, but I am not sure if this is a good way to code.

When a key is pressed, I set the angular velocity to 10 and then at every update, I ask it to check

```
    if(weapon.getAngle() >= Math.PI / 2) {
        weapon.setAngularVelocity(-10);
    }
    if(weapon.getAngle() <= 0) {
        weapon.setAngularVelocity(0);
    }

```

# Answer
> 1 votes
From what you are saying, it seems like you could also have to simply move the code that resets the angular velocity after a certain angle is reached. I suspect that this code is only used when the button is pressed, since you say pressing the button a second time makes the movement stop (and thus makes the testing code work).

If this is the case, you could move it to an 'else' statement after the code that tests if the key is pressed.

# Answer
> 1 votes
One thing that you could do is on command, run a method that would create a body relative to the position of the main body using body.getPosition.set(); set the filter bits to not collide, then set the linear velocity or apply force, whatever you want to move it forward after starting a timer to destroy after x amount of game loops

Or you could do the same thing but instead creating a distance joint combined with a prismatic joint only along the x axis to make a sudden shove out motion with collide connected to be false so that it doesn't collide with the main body this option would probably work better,

for a swing attack create a similar body rotated half of pi with only the tip of the sword connected to the main body with collide connected to equal false of course, then you could apply motor force on the joint an angular impulse on to the sword body destroying it after a set rotation of the body is achieved or a certain time has occurred,

if any extra assistance is needed, just comment below

---
Tags: java, libgdx, box2d
---


# Question
Title: Circle inside ellipse collision/intersection (preventing circle from leaving the ellipse)
I am working on a 2D RPG with a turned based battle system.

Characters move inside the confines of an ellipse movement area and when they leave the boundaries will be pushed back inside. (i.e they should be able to walk around the inner part of the ellipse). Previously we were using circles for the movement area and I wrote the code to do circle inside circle collision (not too difficult because the radius is always the same) but since we will change to using an ellipse, I am trying to update the code.

I have looked at a few solutions for actual ellipse collision/intersection and the math looks..daunting. My questions are:

1. Are there any clean solutions to doing circle inside ellipse collision/intersection?
2. Should I be approximating the ellipse collision in another way? Like using an n-sided polygon?

I am a bit lost on how to approach this and could really use some advice.

# Answer
> 1 votes
My initial answer to this is: Do not use an ellipse, unless you have a really good reason. My second answer would be: If you want to detect collision with complex shapes, use a library and/or engine. My third answer would be: If you want to see real progress on a game project: Use a set of good libraries, minimum.

And lastly, If you want to actually finish a game project: Take the time to learn a nice engine inside out, and stick to that. It is just my opinion ultimately, but I would say programming and game building are barely related. Even a small game is a vastly complex application that will take years to complete even if you use libraries.

In school, you will likely learn programming logic and theory, when it comes to actually producing software, in business especially, you will most likely just learn how to use /other/, production level software. You can do years of training on just one development suite, and some of the most employable tech skills are software certifications.

That's my honest advice after a few years of hobby game design.

---
Tags: collision-detection
---


# Question
Title: Letting the user draw a Polygon Body and Image
In my game, I want to provide the user with a drawing feature.

By free hand drawing, the user creates a polygon shape. Then, in my game implementation, I have to create a body for the found vertices and generate an image based on that polygon shape.

My problem is how to create an image that matches the user-provided vertices. I've heard that cocos2d has something called *Image Masking*. I don't understand how I could implement it in AndEngine. Could someone help?

# Answer
> 1 votes
This is a really interesting question.

I think the way you could do this, using strictly box2d, would be store all the points in some kind of array, and then pop them into the polygon function.

I've never used a poly myself, but judging from this:

https://stackoverflow.com/questions/4360084/creating-complex-shapes-with-box2d

You may be able to use the function createShape()

What I do remember, is there is definitely a way to read vectors into a fixture, the most logical way for that to work would be in some kind of stack.

If you've already grabbed the points based on user input, you simply need to feed them into the box2d poly function, create a fixture/body or whatnot and then add it to your world.

As far as the image, I'm pretty sure you can do this using opengl, but I'm not sure what exactly you mean. If you just want them to be able to draw an amoeba shape and then fill it with a solid color, that should be easy.

If however you want to take an existing image and skew it to fit into the fixture shape, that will be hard. I'm sure you can do it though, here's an example of what blitting looks like using opengl (note, this is in Java)

```
                glPushMatrix();
                glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
                glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
                dirPosd = i.shield.getPosition().mul(30);
                glTranslatef(dirPosd.x, dirPosd.y, 0);
                glRotated(Math.toDegrees(i.shield.getAngle()+52.9), 0, 0, 1);
                glColor3f(1,1,1);
                animationY.bind();
                sizer = 40;
                glBegin(GL_QUADS);
                glTexCoord2f(0f, 0f);

                glVertex2f( i.shield.getPosition().x - sizer-4, i.shield.getPosition().y - sizer-2);     //NW
                glTexCoord2f(1, 0);
                glVertex2f( i.shield.getPosition().x + sizer-4, i.shield.getPosition().y - sizer-2);   //NE
                glTexCoord2f(1, 1);
                glVertex2f( i.shield.getPosition().x + sizer-4, i.shield.getPosition().y + sizer-2); //SE
                glTexCoord2f(0, 1);
                glVertex2f( i.shield.getPosition().x - sizer-4, i.shield.getPosition().y + sizer-2);   //SW
                glEnd();
                glPopMatrix();

```

Your solution will be somewhere between the glBegin() and glEnd(), and will involve manipulating the glTexCoord2f() and glVertex2f(). I've played around with these a bit and achieved bizarre skews, and I'm sure you can use that to achieve what you trying to do.

The fact is, I have no clue how to actually do it, you'll probably have to take an in depth look into opengl, focusing on some of those functions I mentioned.

EDIT\>\>\>

Note: Yes, that code I posted is obviously a mess, but the purpose is to provide a rough example (but it does work). For the functionality you require, you will need a competent understanding of the opengl library.

---
Tags: sprites, box2d, game-mechanics, andengine
---


# Question
Title: How to compare different states of my game? (rpg)
I'm working on a rpg, the battle system. I want to compare different scenario with each other.

For example, what if I play move A then move B ? or two times move A ? or ...?

I'm using a tree-structure to generate all possible scenario that can happen during the battle. There is no movement involved, I'm using a battle-system as in FF7, only skill choice matters. 4vs4 units

Trick is, the battle is turn based but not static. There is an Action Point bar for each unit (filling at different speed based on the unit's stats) and the unit with the most Ap (only if \> 100) can play. If no unit is \> 100, a "turn" will happend and all unit will gain some AP based on their speed. If no unit can play, a new turn will happen...until a unit is \> 100 ap.

Each skills takes a different amount a AP to use. At turns 0 for example, we may have a unit with 140 AP that will play two times in a row for 2 actions of 20 AP each. Then other units at 100 AP may play.

It means that when I'm running a simulation of all possible outcome of a battle for my AI, I will have states (node in the tree), that will have a number a turns very different from other and from nodes at the same depth.

I dont know how to compare these nodes at all.

I was using Hp at first, but it is not enought. To prove it, consider the example: 1 vs 1 match. Unit A (opponent of AI) has only 1 move, a small attack that requieres 20 ap. Unit B (AI) has two moves : a small attack that takes 40 ap (and overall hit for very low damage compared to the opponent attack) and a second move that does nothing but consume 20 ap and that move can only be used during the 1st turn.

I will then have to compare two states :

•State 1 : AI use its attack . Opponent his attack. Units are at 60/80 ap respectively. 20 game turns passes and they are now at 80/100 ap. Opponent use his attack. 20 game turs passes and they are at 100/100 again and we are at turn 40.

•State 2 : AI use his move that does nothing. Opponent his attack. Units are at 80/80 ap. 20 games turns passes, they are now at 100/100 and we are at turns 20.

If I compare only HP, In state 1, AI will have an overall score a lower than in state 2 since it got attacked twice in state 1 and 1 times only in state 2.

If I only compare by Hp difference between AI & its opponenent, I would choose state 2 since AI lost less Hp than in state 1.

Running the simulation after state 1 and 2 will continue to show the same difference since after that point, both unit can only use one attack.

In the end, it makes my AI choose a stupid move because she thinks she is less likely to loose selecting it. Granted both move will eventually result in the defeat of the AI since its main attack is weak but I'd like my AI to nonetheless select as its first move, her attack skill and not a skill that does nothing.

I've tried weithing the overall gradient of score between the root state and the state I'm simulating by the number of turns but it does not work in all cases (it greatly depends on the number of turns and the difference between the root).

I was thinking of adding Ap ratio to my evaluation of states but in that example, we can see that in State 1 & 2, units are at the same AP anyway so it doesnt provide extra informations.

Anyone got ideas on how to compares my states from different turns ?

# Answer
> 1 votes
First, don't look at the absoulte damage numbers, look at the percent of HP. When a combatant lost half of their HP, they are halfway defeated. It doesn't matter if those 50% are 10 HP or 10,000 HP.

Let's take your examples again but look at how much damage is inflicted as percentage of HP. Let's assume that after accounting for all game mechanics, the two attack options by the AI are expected to do 0% and 20% damage to the opponent respectively, and the opponent attack does 30% damage.

In the first example, the opponent lost 20% and the AI lost 60%.

In the second example, the opponent lost 0% and the AI lost 30%.

So how could we rate these?

## Approach A: cost-benefit analysis.

A good approach would be to do a cost-benefit analysis where we treat the damage% inflicted as benefit and the damage% received as cost. To turn this into a profitability score, we simply divide benefit by cost.

20 benefit for 60 cost is a score of `0.33`. 0 benefit for 30 cost is a score of `0`. The AI should take the first course of action.

## Approach B: extrapolation

Another approach is to extrapolate: *"If this combat goes on like this: how will it end?"*. Even without simulating the details, we can estimate how many repetitions of this course of action we will survive by dividing our own HP loss by our initial HP. When we multiply this with the damage% inflicted, we know how much HP we inflicted when this is over. In the first case, we take `100% / 60%` to find out that we can repeat this course of action 1.67 times before we die. We multiply this with the amount of damage we dealt (20%), and find that the enemy will have lost `33%` HP when the combat is over. In the second example we have `(100% / 30%) * 0%)` and find out that the enemy will have lost `0%` HP. Again, the first course of action is better.

**By the way:** When you look at the math, you will see that both approaches are actually equivalent.

# Answer
> 0 votes
**tl:dr; Read the first and very last paragraph**

With this approach, your AI will likely attempt to *always use the optimal strategy*, but the way you code it *can easily lead to abuse*. So, when considering how to evaluate "the best state for the AI" keep these examples in mind:

**Example 1:** (*the problem you currently see*)

Player team is full of extremely high DPS classes. The AI evaluates that it is impossible to kill the player team so it only uses defensive skills in order to stay alive as long as possible.

**Solution:** Either take into account future encounters if you already know what they will be (*that will be harsh on the player btw*), or change your evaluation of the game states. *(Covered in the bottom section)*

**Example 2:** (*The scapegoat*)

Healers tend to be the weakest member of a traditional RPG. If enemies always select the target who they can do the most damage too, the healer may always be targeted. To counter this, one other character in particular is kept soft and vulnerable in comparison to the others, and only provides utility to the rest of the team. The AI always targets this character because it does *the most damage* to it. The player can plan on this and since he can just heal the soft character after the fight, the player doesn't really care about that character getting hurt because they serve no vital function to the team.

**Solution:** Use some randomness, or evaluate the "threat" of given members of the party. Threat is hard to evaluate - but MMO's such as WoW can serve as at least one example - where damage and healing amount can cause a lot of threat, and tanks have to spend skills raising their threat or taunting in addition to their (*lower*) damage. Many combat systems similar to yours use a weighted randomness depending on the person's position in the party (front vs. back)

**Example 3:** (*The Boss who always uses the "Ultimate Move"*)

Bosses, and even some lower minions, tend to have one move that outshines the others for the AP cost. If the AI is always using the most optimal move - it may seem as if all the monsters in the game only have one skill!

**Solution:** Allow for some deviance from the "optimal strategy", or put some kind of restraints on the AI not to use certain moves more than x-times out of y-times.

**Example 4:** (*Toying with the player*)

The reverse situation than you are seeing now, might be if the AI has essentially defeated the player, but stalls the battle in order to fully heal itself. In both end cases, the player is dead, but in one the AI has full health, that makes it clearly the better choice, right?

**Solution**: Make time the secondary factor when evaluating two end states where the player is dead, and ignore factors such as the AI's health in that circumstance.

---

As just these 4 examples show, always choosing the optimal strategy for the AI is difficult, time-consuming(CPU-wise), and generally results in either unintentional player behavior or unfun/frustrating AI behavior. This is why many times RPG games simply use weighted-randomness or specific skill patterns to decide the AI behavior.

But... **To finally get to your actual issue at hand**,

Do not compare the state of the game at different game turns. You could solve it in either direction: either compare at turn 20, in which case your AI sees that it was attacked once and did damage with his skill vs. did no damage, or compare at turn 40, where it sees that it could accomplish more than one thing (in this case two worthless attacks) vs. one major attack (*where the major attack does more damage*) - but the fact it was attacked twice shouldn't matter because it's the same in either case. The second is more difficult but is more flexible and can lead to better AI strategy.

---
Tags: game-design, algorithm, ai, rpg, logic
---


title: Checking spare time

text:
# Question
Title: Checking spare time
What's the best way to check how much free time I have between the end of my Update procedure and the next Draw event?

I want to keep a careful track of how much time my code is taking up.

# Answer
Use a timer with a decent resolution (such as `QueryPerformanceCounter` on Windows).

At the end of your update routine, query the timer and store the result somewhere. At the start of your draw routine, query the timer again and compare the result to the value from the end of the update routine.

That will tell you how much time elapsed between the two.

This seems like an unusual interval to measure, though; normally I'd think you'd want to measure the time taken from the start of update to the end of update, or the start of a draw to the end of a draw, and not the time between update and draw, during which (generally) not very much happens.
> 1 votes

---
Tags: timer
---


# Question
Title: Create a new Surface type with SDL_Texture
So I started using Awesomium, and I'm experiencing some difficulties.

I want to create a new type of `Awesomium::Surface` and implement it in my custom `Awesomium::SurfaceFactory` to render `Awesomium::WebView->surface` as `SDL_Texture`.

I'm currently stuck at the Paint function which is supposed to update some pixels, so I have this (in the project it's separated in header and definitions):

```
class AwsSurface {

    public:
    AwsSurface(int w, int h) : public Awesomium::Surface {
        // _renderer is my global renderer, on Awesomium DOCs it says that pixels are
        // "in 32-bit BGRA format" so I guess the format is right...
        texture = SDL_CreateTexture(
            _renderer,
            SDL_PIXELFORMAT_BGRA8888,
            SDL_TEXTUREACCESS_STREAMING,
            w,
            h
        );
        dst_rect = {0, 0, w, h};
    }

    void Paint(unsigned char* src_buffer,
             int src_row_span,
             const Awesomium::Rect &src_rect,
             const Awesomium::Rect &dest_rect) {
    }

    protected:
    SDL_Texture* texture;
    SDL_Rect dst_rect;
};

```

I'm not sure if I get it right, but fromwhat the DOCs say if I'm given a `src_rect={2, 1, 2, 3}` and `src_row_span=20` I am in this situation, right?

Now, I understood how the buffer works (more or less), but I don't know how to copy the pixels from it onto my texture (in the given position).

**Edit:** I came up with this paint function:

```
void AwsSurface::Paint(unsigned char* src_buffer,
                       int src_row_span,
                       const aws::Rect &src_rect,
                       const aws::Rect &dest_rect) {
    Uint32* src_buffer_i = (Uint32*)src_buffer;
    src_row_span /= 4;
    int dest_row_span;
    Uint32* dest_buffer;
    SDL_Rect r = AwsRectToSDL(dest_rect); // Custom function to convert the rect
    SDL_LockTexture(
        texture,
        &r,
        (void**)&dest_buffer,
        &dest_row_span
    );
    dest_row_span /= 4;
    for (int x = 0; x < src_rect.width; x++) {
        for (int y = 0; y < src_rect.height; y++) {
            Uint32* s = src_buffer_i + (src_rect.y + y) * src_row_span + src_rect.x + x;
            Uint32* d = dest_buffer + (dest_rect.y + y) * dest_row_span + dest_rect.x + x;
            *d = *s; // Here happens the exception
        }
    }
    SDL_UnlockTexture(texture);
}

```

But I get an **"access violation on writing"** exception on the line above, this happens after some successful executions *(usually 6/7)* and every time on the same rectangle `{0, 0, 466, 26}`.

# Answer
> 0 votes
SDL Wiki SDL\_LockTexture function:

> **pixels:** this is filled in with a pointer to the locked pixels, **appropriately offset by the locked area**

So based on this I imagined that I was given a block of pixels padded by the rect's X and Y coordinates so to get to the first pixel I needed to manually get to it, like I tried to do:

```
Uint32* d = dest_buffer + dest_rect.y*dest_row_span + dest_rect.x;

```

And I was getting **access violation on writing**, on **the only rect** where the sum of *X coordinate* and *WIDTH* was lower than the *pitch*, so I started realizing that for some reason I was going out of bounds in that specific rect.
Then I tried to use SDL\_UpdateTexture and everything worked flawlessly! So I started inspecting SDL's source code and came near the `SDL_LockTexture` function, particularly when the pixels parameter is set as follows:

```
*pixels =
        (void *) ((Uint8 *) surface->pixels + rect->y * surface->pitch +
                  rect->x * surface->format->BytesPerPixel);

```

So, indeed `pixels` points already to the **beginning of the locked pixels**!!!
And my function becomes this:

```
void XGE_AwsSurface::Paint(unsigned char* src_buffer, int src_row_span, const aws::Rect &src_rect, const aws::Rect &dest_rect){
    Uint32* src_buffer_i = (Uint32*)src_buffer;
    src_row_span /= 4;
    int dest_row_span;
    Uint32* dest_buffer;
    SDL_Rect dst_rect = XGE_AwsRectToSDL(dest_rect);
    SDL_LockTexture(texture, &dst_rect, (void**)&dest_buffer, &dest_row_span);
    dest_row_span /= 4;
    Uint32* s = src_buffer_i + src_rect.y*src_row_span + src_rect.x;
    Uint32* d = dest_buffer;
    for(int y = 0; y < dst_rect.h; y++){
        for(int x = 0; x < dst_rect.w; x++){
            *d = *s;
            d++;
            s++;
        }
        d += dest_row_span - dst_rect.w;
        s += src_row_span - src_rect.width;
    }
    SDL_UnlockTexture(texture);
}

```

I hope this helps someone in trouble...

# Answer
> 2 votes
I didn't go with the way of implementing a custom Awesomium class for this. Instead I just updated data of a single texture by querying the surface from Awesomium.

```
// Gets the surface of the web view.
Awesomium::BitmapSurface* surface = static_cast<Awesomium::BitmapSurface*>(webView->surface());
if (surface != NULL)
{
    unsigned char* pixels = nullptr;
    int pitch = 0;

    // "pixels" now point to the pixels of the texture.
    if (SDL_LockTexture(texture, nullptr, (void**)&pixels, &pitch) != 0)
    {
        std::cout << SDL_GetError() << std::endl;
    }
    // Copies the pixels to the texture.
    surface->CopyTo(pixels, pitch, 4, true, false);
    SDL_UnlockTexture(texture);
}

```

This assumes that you already have created an `SDL_Texture` called `texture`with the correct viewport size. Awesomium then offers an utility method `CopyTo` that you can use to put the pixel data to the texture.

You're right on the fact that the texture needs to be created with the `SDL_PIXELFORMAT_ABGR8888` flag. I also used the `SDL_TEXTUREACCESS_STREAMING` flag on the texture.

Anyways I find that this approach is somewhat cleaner atleast for someone who's not familiar with Awesomium's class design, as it's mostly using SDL calls and then just a simple call to an Awesomium method.

After that you're just free to render your texture to the screen.

Oh, and if you would like to use the Awesomium custom class structure, I'm sure you can figure out how to adapt this example code to put into use there.

---
Tags: sdl2, pixel, awesomium
---


# Question
Title: OpenGL App not setting cursor position appropriately
I have written a small application using OpenGL, and have implemented some rudimentary camera controls. Unfortunately, I cannot get the application to set my cursor position correctly. The cursor is never set to where I tell it to go, so my application just reacts to where the cursor is on my entire screen.

I first attempted to use GLFW, and when I saw that I couldn't set the cursor appropriately, I decided to try SFML. Neither one works.

I'm on an Arch Linux install with a Gnome desktop. I've been trying to figure this out for a few days now to no avail.

The relevant code is as follows:

```
sf::Vector2i cursor_pos = sf::Mouse::getPosition(*window);
sf::Mouse::setPosition(sf::Vector2i(1280/2, 720/2), *window);

```

This gets called every frame inside a function that messes with some matrices.

I also set the cursor position at initialization.

Any hints or advice would be greatly appreciated.

# Answer
> 0 votes
The issue turned out to be a problem with the way Wayland works. My install of Gnome was defaulting to Wayland, instead of x, and Wayland doesn't do a good job of capturing the cursor within a window.

---
Tags: opengl, c++, sfml, glfw
---


# Question
Title: calculating torque from angular momentum considering inertia moment
so I am trying to determine exactly how much torque to apply to a 3d model to make it rotate at a particular rate. I apply force from the location of each engine on the craft so if one breaks the craft should start to spiral out of control. Unity provides the inertia tensor which as far as I can figure out is the distribution of mass simplified to a vector? I am assuming Unity's own physics system relies on the same vector.. If I had a target rotation speed and for the sake of simplicity wanted to accelerate to it over one frame I'd like to be able to do something like:

```
AddForce(targetAngularVelocity * rigidbody.mass * rigidbody.inertiaTensor.magnitude);

```

assuming the inertiaTensor has a magnitude of the average distribution of mass is that how it works? hopefully you get the point because im making some assumptions here I can't really seem to find a clear answer - that I understand anyway :)

A better explanation: I can get the angular velocity of a rigidbody from unity, but how do I convert that into torque using the inertia tensor. For example if you have two rotating spheres both with the same mass and angular velocity but one is larger, the larger one will take more torque to stop it because of its mass distribution. How do I utilise the inertia tensor to determine the torque required?

Thank you

Update:

Been messing around with the tensor, created a 3D object -\> Cube in Unity, added a rigidbody, then added a second cube as a child of the first. By moving the child cube the inertia tensor changes.. I set Unity to draw a vector of the inertia tensor.. it did appear at first to remain constantly perpendicular to the mass distribution.. but it seems to only be directed along a positive diagonal along the plane closest to that perpendicular of the mass distribution..

I really need someone with knowledge on the topic to shed some light on this. What does Unity use to determine how a mass will react to a force offset from the centre of mass? I just need to know how to predict how Unity will react by applying a throttle to a single engine on, for example the wing of the plane.

The tensor appears strangely simple? can only span along 3 directions, each a positive only diagonal along a plane perpendicular to the distribution of mass.. an estimate almost? with a degree of error of 90 degrees?

Please tell me I'm missing something

Update 2:

2 upvotes, must be a record for me, so I've put some more time in haha, I hope this helps someone.

so theres another Vector3 I should have looked at long ago.. Unity also supplies Rigidbody.inertiaTensorRotation which is the euler angles for the rotation of the inertia tensor. After drawing a vector along the inertia tensor rotated by the cubes local rotation and also the inertia tensor rotation it works. The line still flickers at 90 degree rotations but it doesn't matter as it is representing the distribution of mass out from the axis that is running through the transforms position and it's centre of mass. In other words rotating the inertia tensor around the imaginary vector connecting the 2 cubes won't change it's meaning, hence why I draw the 4, it stopped the change.

The picture here shows the inertia tensor, in white. That was confusing me before as it is in global co-ordinates. The way it changes to match (to a degree) the rotation of the cubes distribution of mass made me think it was local co-ords. The green lines indicate the inertia tensor. I have drawn it 4 times, each rotated 90 degrees around the axis going through the transforms position and its centre of mass. The inertia tensor randomly changes between one of these 4, but the way it changes doesn't change how it represents the inertia moment.. just look at the pic ;)

So the inertia tensor after rotating is like a plane around the axis that mass is distributed along. Because the mass is only the 2 cubes, the distribution is by a majority along the axis going through the transforms location and its centre of mass. the inertia tensor is also slightly tipping towards one of the cubes if you look closely. That is representing the slight distribution out perpendicular to the vector I keep mentioning running through the transforms position and its centre of mass (or draw a line between the 2 cubes).

Oh yeah, so how do I use this magical vector to determine the torque required to rotate it to a specific angular momentum?

---

Update, again.. Sorry to keep coming back to this, it is driving me insane. All I need to know is how the inertia tensor affects the resulting angular momentum after a torque is applied.

---

# Answer
In Unity, the inertia tensor is represented by a vector of the diagonal of the actual inertia tensor. That is to say, there are no off-diagonal elements in the inertia tensor. As Pieter mentioned, you need to think of the inertia tensor as the mass of the object. Once you do that, you can draw results from correspondence to linear equations. We all know that `F = m * a`, so in rotational terms, `T = I * alpha`, where `I` is your inertia tensor and `alpha` is your angular acceleration. There is one GIANT difference, though. `I` is a tensor and *not* a scalar. That means you need to do matrix math to get it right. Luckily, the simplification in Unity is that `I` is diagonal, so you can just treat it like a "magnitude", ie, `T_x = I_x * alpha_x` and so forth for each of the three components.

Now, in your problem statement, you are trying to figure out how `T` affects `L`, where `L` is your angular momentum vector. Well, going back to our linear correspondence, we know that `L = I * omega`, where `omega` is the angular velocity since `p = m * v`. We also know that `alpha = omega / dt` since `a = v / dt`. Let's put that together:

```
T = I * alpha = I * omega / dt = L / dt

```

So

```
T * dt = L

```

Which means that the change in angular momentum is simply torque multiplied by the amount of time you apply the torque! So the answer you seek is that the inertia tensor *doesn't* affect the angular momentum change due to a torque. It *will* however affect the angular **velocity** since

```
T * dt = L = I * omega

```

So if you want your angular velocity components and not the momenta, then simply divide the components of your torque by the corresponding components of the inertia tensor, ie,

```
T_x * dt / I_x = omega_x

```
> 3 votes

# Answer
Let's correlate linear and angular terms, since most people have more intuition for linear kinematics and dynamics than angular, and for the moment assume a single axis of rotation:

```
Linear Term                        Angular Term
-------------------------------    --------------------------------------------------------
Mass                               Moment of Inertia
Velocity                           Angular Velocity
Force                              Torque
Momentum = Mass * Velocity         Angular Momentum = Moment of Inertia * Angular Velocity
Impulse = Change in Momentum       Angular Impulse = Change in Angular Momentum
Acceleration = rate of change of   Angular Acceleration = rate of change of
               velocity                                   angular velocity

```

Your question asks how to calculate the torque necessary to induce a specified change in angular velocity. Undoubtedly you have an unknown *t* floating around in your equations that you don't know how to solve for.

You need to look at this first from a kinematics standpoint.

* Calculate the Angular Impulse necessary to induce the required change in Angular Momentum;
* Decide the time behaviour of this Angular Impulse:
    + As a point change, like billiard balls on a pool table;
    + Constant application over a finite time, like rocket thrusters; or
    + something more esoteric.

In the first case, you simply apply the Angular Impulse at a moment in time, and the angular velocity changes to the new value instantaneously.

In the second you either pre-determine the length of time in which you wish the change to occur, or calculate the length of time from a maximum available torque. Both of these case involve solving a quadratic equation. You then apply the calculated/specified torque for the specified/calculated time.
> 1 votes

---
Tags: unity, c#, physics, rotation, vector
---


# Question
Title: Unity 5 - Time Remaining displaying in scene but not in Game
I'm currently learning game development in Unity from this course on Lynda.com. Currently I'm trying to displaying the time remaining in the game after it has been set to 5 minutes initially. When I look at the scene, I can see the text for the timer displayed in the top left corner of the canvas, but when I run the game, I'm not seeing it at all.

I made a script for a game manager which is derived from a Singleton class. The game manager contains a private variable (and an accessor method) for the time remaining. I have another script that accesses the value for the time remaining and displays it on screen. In the Unity editor, I added a UI game object for the text box and then added the text box to the GUI representation of the timer label attribute. It seems like everything should be working but since I'm still very new to this, I'm probably missing something simple. Here is the code for both scripts:

**GameManager.cs**

```
public class GameManager : Singleton<GameManager> {
    private float _timeRemaining;

    public float TimeRemaining
    {
        get { return _timeRemaining; }
        set { _timeRemaining = value; }
    }

    private float maxTime = 5 * 60; // In seconds.

    // Use this for initialization
    void Start () {
        TimeRemaining = maxTime;
    }
    // Update is called once per frame
    void Update () {
        TimeRemaining -= Time.deltaTime;
        if(TimeRemaining <= 0)
        {
            //Now Deprecated
            //Application.LoadLevel(Application.loadedLevel);
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
            TimeRemaining = maxTime;
        }
    }
}

```

**UpdateUI.cs**

```
public class UpdateUI : MonoBehaviour {

    [SerializeField]
    private Text timerLabel;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        timerLabel.text = FormatTime(GameManager.Instance.TimeRemaining);
    }

    private string FormatTime(float timeInSeconds)
    {
        return string.Format("{0}:{1:00}", Mathf.FloorToInt(timeInSeconds / 60), Mathf.FloorToInt(timeInSeconds % 60));
    }
}

```

## EDIT:

**Canvas Settings in the inspector**

**Image of the Time Remaining displayed in the scene**

# Answer
> 2 votes
Well, there is nothing obvious problem I can find in your settings but here is my recommended settings, so you can match it, may be your problems lies in between these.

* Text Object should be like,

* Canvas settings

* Game resolution should not be set to Free Aspect. Assign some resolution.

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


title: closing GUI in Unity

text:
# Question
Title: closing GUI in Unity
How do I close the GUI after the user enters a value? ~~Is there any way to stop execution of the entire app (from inside this script) until a value is entered?~~

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

public class Popup : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    string record="";

    void OnGUI() {
        //Participant Number/Record:
        GUILayout.Label ("enter participant id:");
        record = GUILayout.TextField(record);
        //GUILayout.TextField()

        if (GUILayout.Button("Submit")) {
            OnClickSavePrefab();
            GUIUtility.ExitGUI();
        }
    }

    void OnClickSavePrefab() {
        record = record.Trim();

        if (string.IsNullOrEmpty(record)) {
            EditorUtility.DisplayDialog("Unable to save record", "Please specify a valid participant record.", "Close");
            return;
        }
        // Save your prefab
        Debug.Log ("record:" + record);
    }
}

```

# Answer
Well, you can use simple flag to do so, as

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

public class Popup : MonoBehaviour {

    bool _shouldDisplayGUI = true; // Make it false when you want to turn off GUI elements.

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    string record="";

    void OnGUI() {
        if (!_shouldDisplayGUI)
            return;

        //Participant Number/Record:
        GUILayout.Label ("enter participant id:");
        record = GUILayout.TextField(record);
        //GUILayout.TextField()

        if (GUILayout.Button("Submit")) {
            OnClickSavePrefab();
            GUIUtility.ExitGUI();
        }
    }

    void OnClickSavePrefab() {
        record = record.Trim();

        if (string.IsNullOrEmpty(record)) {
            EditorUtility.DisplayDialog("Unable to save record", "Please specify a valid participant record.", "Close");
            return;
        }
        // Save your prefab
        Debug.Log ("record:" + record);
    }
}

```
> 1 votes

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


title: Rotation and Velocity vectors

text:
# Question
Title: Rotation and Velocity vectors
I've looked through the suggested, but I can't see exactly what I need. I want to calculate the vector needed for forward motion of a rotated sprite. At the moment I have:

```
        sprite.Rotation = 0
        sprite.Velocity = New Vector2(0, -1)

```

This is perfect, my sprite moves up my arena. But what I need is:

```
        sprite.Rotation = RN.Next(0, 360)
        sprite.Velocity = New Vector2(??,??)

```

I know it's going to be a PI thing but that's where my brain runs out! Could someone with a better brain please post the equation I need?

Many thank yous.

# Answer
> 1 votes
All you need is basic trigonometry. Unfortunately I don't have time to explain, but here is the formulas.

```
x = speed *  sin(rotation)
y = speed * -cos(rotation)

```

This is if positive y is down and positive x is to the left, or

```
x = speed * -sin(rotation)
y = speed * -cos(rotation)

```

If positive y is down and positive x is to the right.

Please note whether your trigonometric functions take rotation to be in radians or degrees and convert acordingly.

---
Tags: rotation
---


# Question
Title: 2D deferred lighting calculations not working
I have the following code for my HLSL pixel shader. Modified from another post here on GameDev (Link), but I have a few problems with it:

```
// calculate UV and get texture and normal.
float2 UV = Input.position.xy / Input.ScreenSize.xy;
float4 DiffuseColor = ColorTexture.Sample( SampleType, UV );
float4 NormalColor = NormalTexture.Sample( SampleType, UV );
float4 normal = 2.0f * NormalColor - 1.0f;

// calculate distance.
float3 LightDir = LightPos - Input.position.xyz;
float distance = 1 - length( LightDir ) / LightRadius;

// calculate dot of normal and light direction.
float NdL = max( 0, dot( normal.xyz, LightDir ) );

// get final color.
float4 finalColor = ( DiffuseColor * ambientIntensity ) + DiffuseColor * distance * LightIntensity * LightColor * NdL;

return float4( finalColor.rgb, DiffuseColor.a );

```

`ambientIntensity` and `LightIntensity` are currently 1.0f to simplify things. `LightRadius` depends on the size of the geometry, but is in pixels. ~80 for testing. `DiffuseColor` is a texture resulting from applying self-illumination and darkening the base image. `NormalColor` is the normal map for the image.

This shader needs to run for every light on the screen, which isn't that many.

For my tests I use the images from the blog post here. It's a little old, but it is pretty much what I need to do, which I can't.

Now; I did enough testing to know that all input and cbuffer parameters are valid but the results I get are not what I hoped for.

Here are my problems:

* Problem 1: My knowledge of math is limited and I don't understand exactly what the dot product does, why it is needed in the light calculation or why the distance is calculated as it is. Is there a resource online that would explain lighting in term of HLSL or at least in a way meant for a programmer and not using big equations meant for a mathematician? If I don't understand the basics, I'm afraid I wont be able to improve and I'll be stuck every time I need to add new features (ie: shadows), but I need to get this things running asap.
* Problem 2: The results I have are not good. When I move the light around, I can actually see where the geometry cuts off, and it is as if the light does not trail off properly near the edges of the geometry. Are the calculations wrong?
* Problem 3: I built a 2D shape editor that I use to design the shape of the lighting geometry, but I don't know how to edit the shaders or the geometry's UV to have the custom shapes (fans, circles, etc) shaded properly. The light I render is always shaded as if it was a circle.

I spent the last two weeks working on this and whenever I search on Google, I keep getting pages I have already visited, so I'm quite lost right now. **Any** suggestions would be highly appreciated.

My game is a tile-based 2D game, thought I would mention that.

# Answer
First Question: The dot product basically tells you how much two vectors are pointing in the same direction. So if a light points directly against the normal of a surface the surface will be brighter than if it points at it in an angled way or away from it.
If you are struggling with getting this to work, I would advise very heavily against trying to implement shadows because that is orders of magnitude more complicated.

Second: In deferred shading you are drawing the lights into a light map. The Light shader takes the information it needs to figure out how each pixel is lit out of the GBuffer and then draws it. So you probably want to use additive blending for them, which you may or may not already do. Your code doesn't show it.
The crucial bit of information here is, that you are drawing the light as a thing and that thing has dimensions. Your light is probably drawn as a quad so it has geometry. None of the pixels outside of that quad will be affected by your light. So you are probably drawing a quad that is too small for the area your light should be affecting.

Third: If you want to shape your light you will have to UV map the quad you are drawing as the light so that the shader can know where in the shape you are.
You can then either map a texture mask to it to shape the light or do some math to make the fade out dependent on the distance from the shapes edge or something.

As a last addition I would recommend that you read up on what deferred shading does and why it is used. You seem to lack some understanding of the rendering pipeline, so reading up on that would probably be a good idea.

Hope you get your rendering subsystem working.
> 4 votes

---
Tags: 2d, shaders, hlsl, lighting, deferred-shading
---


title: Möller-Trumbore intersection point

text:
# Question
Title: Möller-Trumbore intersection point
I am using the Möller-Trumbore method as part of my (still very basic) collision detection system.

The information I'm craving about is the distance from the ray origin and intersection point. The intersection point would be fine too obviously.

I probably wrongly assumed `t` in the code below is actually the distance from the ray origin to the intersection point. If it actually is, then I don't know what's wrong with my code.

I have got a simulation with a mesh and "bullets", sometimes firing a collision acurately, and sometimes not (bullets passing thru mesh, or firing a colision before it actually should hit).

```
bool rayTriangleIntersect(const XMFLOAT3 &orig, const XMFLOAT3 &dir, const XMFLOAT3 &v0, const XMFLOAT3 &v1, const XMFLOAT3 &v2, float &t, float &u, float &v) {
// http://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/moller-trumbore-ray-triangle-intersection

    float kEpsilon = 0.000001f;
    XMFLOAT3 v0v1 = v1 - v0;
    XMFLOAT3 v0v2 = v2 - v0;
    XMFLOAT3 pvec = XMFLOAT3Cross(dir, v0v2);

    float det = XMFLOAT3Dot(v0v1, pvec);

    if (det < kEpsilon) return false;

    float invDet = 1.0f / det;

    XMFLOAT3 tvec = orig - v0;
    u = XMFLOAT3Dot(tvec, pvec) * invDet;
    if (u < 0 || u > 1) return false;

    XMFLOAT3 qvec = XMFLOAT3Cross(tvec, v0v1);
    v = XMFLOAT3Dot(dir, qvec) * invDet;
    if (v < 0 || u + v > 1) return false;

    t = XMFLOAT3Dot(v0v2, qvec) * invDet;

    return true;
}

```

Is `t` really the distance im looking for ? If not how do I get it, or the intersection point. I've heard of baricentric coordinates in a triangle related to `u` and `v` \- is it the way to go ? If yes I'd be thankful for an example or link related to the Möller-Trumbore method.

Thanks!

# Answer
> 2 votes
One issue with your implementation is that you only check if det is smaller kEpsilon, but there is no guarantee that det is positive. You want to check

```
if(det<kEpsilon && det>-kEpsilon)

```

So that might explain the false positives. The way this algorithm works is by basically figuring out "when" the ray will hit the triangles plane and then checking if the position of the ray at that time is inside the triangle by transforming into barycentric coordinates.

You should be able to calculate the intersection point as:

```
intersection = v0+u*v0v2+v*v0v1;

```

That being said t should be the distance you are looking for anyway, so you might have an implementation problem.

There seems to be an excellent explanation here: http://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/moller-trumbore-ray-triangle-intersection

# Answer
> 1 votes
A standard parametric ray equation is `r(t) = p + td`. The origin point is `p` and `d` is the ray direction. So, that algorithm gives you `t` and you know `p` and `d` already. Therefore you can compute ray (or vector) `r(t)`, and then take its magnitude `|r(t)|` to obtain the distance to triangle (intersection).

PS. You may need to normalize your direction vector `d` first. That is, ensure its of unit length. (The link you provided isn't clear if that's necessary though.)

---
Tags: c++, collision-detection
---


# Question
Title: How to blur entire scene but a specific spot in Unity?
What I want is basically: A way to blur every object/sprite on the scene, but have a "blur-free" circular zone, that can move. And everything that's behind that circular zone won't have the blur effect applied to it.

In a 2D mobile game, how would I do that, especially in a way that's not too heavy, performance-wise(if possible).

And if it's not possible to do that in a way that won't completely destroy my performance, I also have those sprites already "pre-blurred" so maybe there's a way to have both blurred and "unblurred" objects at the same position, and only draw the right parts of them as they go through the scene and reach the blur-free zone. If there's a way to do that, that'd also help immensely.

Thanks for your time.

# Answer
I managed to solve my problem. I used the shaders from this post: http://forum.unity3d.com/threads/sprite-renderer-mask-on-specific-sorting-layer.356824/#post-2310992

And a simple grey circle for the "blur-free" circular zone. The pre-blurred sprites used the "Stencil Draw In Mask" one, the regular sprites used a shader that was the same as the above, but with Ref set to 1, and the grey circle used the Stencil Mask. While my draw calls doubled, as there was 2 times the amount of objects on scene, the performance impact wasn't as great as if I used a shader to blur the entire scene.

Thanks for your attention.
> 1 votes

---
Tags: unity, 2d, shaders, mobile, blur
---


title: DirectX11 Using Multiple Shaders

text:
# Question
Title: DirectX11 Using Multiple Shaders
I currently have a scenario where I am rendering terrain with a shadow map. I have two passes, one for the depth buffer to create the shadow map (which is rendered to a texture) and a second that takes the shadow map texture as input and actually shadows the terrain, the terrain gets drawn once for each pass. Within the second shader I also texture the terrain.

I now want to split the second shader so that shadows and texturing are separate shaders. How do I go about getting the output from the shadow shader to the texture shader (or vice versa), or do I simply do it in the same way as I have with the shadows (rendering to a texture, passing it as an input).

# Answer
I have solved this same problem (need to render the same geometry with simpler shaders for shadow mapping) in 2 ways:

1. Wrap shader code sections into #IFDEF directives, so that on compile time I could enable or disable them, thus constructing 2 shaders from single source. (I mostly use it to enable-disable effects on-the-fly)
2. Copy-paste the shader code and manually rip off everything for "light" version. In my case that was viable cos I have just a couple of shaders that got simplified to `gl_Position = M*V*P*Position;` and `gl_FragColor = vec4(0,0,0,0);`

In both cases, do not forget to also instrument your shader preparation code to assign only existing uniforms and attributes.
> 1 votes

# Answer
HLSL in Direc3D 11 has a feature called Class Instances, in which you can dynamically plug in what functionality should be used in a particular draw call. You keep the implementation in the shader file and query out the location via reflection. The instances are specified as an array to your SetShader call.

The MSDN page that outlines this is Instances and Classes and seems to rely on reflection to find the implementation and the binding points to attach the references to the code.
> 1 votes

---
Tags: shaders, directx, directx11
---


title: Coordinate system for a strategy game

text:
# Question
Title: Coordinate system for a strategy game
I am working on a personal project of developing a simple 3D strategy game. I am working on my own game engine (let's assume that I have to have my own) and I have one theoretical question. How to develop a suitable coordinate system, which would be scalable and provide the best versability?

I am deciding between a X,Y coordinate system (different units cover different space - simply rectangle shaped) and a hexagonal system (bigger units take more hexagons).

I am working here with a simple concept of three different units of three different sizes for every player (maybe even buildings) and collision detection with conflict resolution. Thanks.

# Answer
Amit Patel wrote a great entry all about hexagonal coordinate systems at http://www.redblobgames.com/grids/hexagons/ and I strongly encourage you to read through the whole thing for a deeper understanding.

A system he mentions in there that happens to be my personal choice for such systems is the Cube Coordinate system; In this system, three numbers are given to determine location of the hexagon (to match the 3 axes of a hexagon):

There are a couple of advantages to this system with the biggest one being that the three values of a hexagon's location when added will all equal zero. That is to say, X + Y + Z = 0. This is also what allows you to further simplify the system into Axial Coordinates; Because X + Y + Z always equal 0, then you can remove one of the axes and still have enough information to determine a position. If X = -1 and Y = 1, and Z is left undefined, it's easy to determine that Z = 0.
> 2 votes

---
Tags: coordinates, hexagonal-grid
---


# Question
Title: How can I evoke a sense of dislike/hate for a character through game mechanics?
In my game there is a villain who I would like the player really *despise* from the moment the character is first encountered. I want the player to hate the character so much that it affects (and drives) the player's decisions during the game, to the extent that the player may choose a course of action that harms him or herself if it would also set the villain back.

I'd like to accomplish this through game mechanics, not just writing, not just through the fact that the character is "the bad guy." What strategies and types of mechanics can I use to ensure that no matter who may play my game, this character will be completely despised?

# Answer
> 4 votes
You need not create explicit game mechanics for this. Indeed, doing so can lead to the player hating *your game* rather than your *character*.

A safer course is this one: simply design your game as normal. But every time you throw a new curve at the player, assign the *blame* for it to the badguy. Portal provides many examples:

> Due to mandatory scheduled maintenance, the appropriate test chamber for your testing sequence is currently unavailable. It has been replaced by a *live fire* course, designed for military androids. The Enrichment Center apologizes for the inconvenience and wishes you the best of luck.
>
> The Weighted Companion Cube certainly brought you good luck. However, it cannot accompany you through the testing sequence and, sadly, must be euthanized.
>
> Congratulations. The test is now over. All Aperture technologies remain safely operational up to 4000 degrees Kelvin. Rest assured that there is absolutely no chance of a dangerous equipment malfunction prior to your victory candescence.

# Answer
> 1 votes
General writing tips for how to make a character unlikable are more for Writers SE (If you decide to post there, make sure your question is not too broad). But because you posted this on game development stackexchange, I will try to focus on those methods which are unique to games and do not apply to any other medium.

A good way to make a player hate a character is to make that character interfere negatively with their gameplay in ways which are perceived as unfair and annoying.

* Have them steal their powerups and their resources (directly from them or before they can pick them up) and have them destroy what the player created.
* Have them create additional obstacles and challenges for the player which don't have any reward when overcome.
* When the character is a direct opponent, have them cheat. AIs cheating is something we do very often, but usually we try to hide it as best as we can. If you want to make the player hate the character, make it very obvious they are cheating.
* Have the player do things which are tedious, boring or humiliating while making it obvious that the character is the direct reason they have to do it.
* Have the character distract the player from something far more interesting.

Do not give the player a chance to defend against any of these.

Keep in mind that each of these techniques makes the experience of the game itself worse, so it carries a high risk that the players will not just hate the character but will also hate the whole game. So do not overdo it! Make sure each of these negative experiences is rather short and sandwich them between more positive game experiences (which you should attribute to other characters which you want to be more likable).

---
Tags: game-design, character-development
---


# Question
Title: How To Update Animation in Unity After Changing the Names of Objects in Mechanim
I have an animation clip I made with Mechanim. But when I changed the hierarchy of the objects in the children, it stopped working!

The text says ( Missing! )

Why is it breaking? How can I fix it?

# Answer
In Unity, Animations are bound by name, so if you change the name of any object, or move the object to a different parent (thereby changing the path), the animation will break.

Do *not* attempt to use a 'find and replace' feature with a text editor, as this is known to cause corruption.

Luckily, Unity has a built-in (though somewhat hidden) **API for editing animations**. If you have a big project and a team, one of your developers ought to learn this API and make an editor to handle this.

If not, you can use this free tool, which I have tried and works well (saving me hours of time by not needing to redo my animations!)

https://github.com/s-m-k/Unity-Animation-Hierarchy-Editor

(Note: tool is open source)
> 5 votes

---
Tags: unity, animation
---


# Question
Title: Make game camera stay inside of tiled map boundaries [LibGDX]
I am creating a little 2D platform game, with the LibGDX framework. So far I have created a simple prototype level in Tiled, and loaded this map into my LibGDX game. I can use mouse and keyboard controls, to move the camera around my world.

The problem I am facing, is regarding the tiled map boundaries. Lets say my map is 30x15 tiles. How can I get my camera to only show my map, and not be able to 'go outside' the tiled map. When I am making my character to walk around my map, I don't want him to be able to run outside the map boundaries.

I hope someone can help me, since I am new to LibGDX.

My class is as follows.

```
package dk.martinrohwedder.libgdx.justicejoe.screens;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.viewport.FitViewport;

import dk.martinrohwedder.libgdx.justicejoe.MainGame;
import dk.martinrohwedder.libgdx.justicejoe.parallax.ParallaxBackground;
import dk.martinrohwedder.libgdx.justicejoe.parallax.TextureRegionParallaxLayer;
import dk.martinrohwedder.libgdx.justicejoe.parallax.Utils.WH;
import dk.martinrohwedder.libgdx.justicejoe.tools.MapCreator;

/**
 * PlayScreen class is responsible for draw and render the actual game objects and playable levels in the game.
 * PlayScreen extends the abstract screen class {@link #BaseScreen}
 *
 * @author Martin Rohwedder
 * @version 1.0 (11/01/2016)
 */
public class PlayScreen extends BaseScreen {

    /* The class tag */
    private static final String TAG = PlayScreen.class.getSimpleName();

    /* Camera and viewport */
    private OrthographicCamera camera;
    private FitViewport viewport;

    /* Tiled Map */
    private TiledMap tiledMap;
    private TiledMapRenderer mapRenderer;

    /* Box 2D */
    private World world;
    private Box2DDebugRenderer b2dr;

    /* Constructor of PlayScreen objects */
    public PlayScreen(MainGame game) {
        super(game);
    }

    /* Parallax Background */
    private ParallaxBackground pbg;

    @Override
    public void show() {
        /* Setup game camera */
        camera = new OrthographicCamera();
        viewport = new FitViewport(MainGame.VIRTUAL_WIDTH, MainGame.VIRTUAL_HEIGHT, camera);

        /* Change game camera position to viewport */
        camera.position.set(viewport.getWorldWidth() / 2, viewport.getWorldHeight() / 2, 0);
        camera.update();

        /* Parallax Background */
            game.getAssetsUtil().getAssetManager().load("sprites/backgrounds/background1.png", Texture.class);
        game.getAssetsUtil().getAssetManager().load("sprites/backgrounds/background2.png", Texture.class);
        game.getAssetsUtil().getAssetManager().finishLoading();

        Texture skyBG = game.getAssetsUtil().getAssetManager().get("sprites/backgrounds/background2.png");
        Texture mountainBG = game.getAssetsUtil().getAssetManager().get("sprites/backgrounds/background1.png");

        TextureRegionParallaxLayer skyLayer = new TextureRegionParallaxLayer(new TextureRegion(skyBG, 768, 768), MainGame.VIRTUAL_WIDTH, new Vector2(.1f,.1f), WH.width);
        TextureRegionParallaxLayer mountainsLayer = new TextureRegionParallaxLayer(new TextureRegion(mountainBG, 768, 768), MainGame.VIRTUAL_HEIGHT, new Vector2(.2f,.2f), WH.height);
        pbg = new ParallaxBackground();
        pbg.addLayers(skyLayer, mountainsLayer);

        /* Load Tiled Map */
        game.getAssetsUtil().loadTiledMapAsset("sprites/maps/tutorial_level.tmx");

        /* Setup Tiled Map */
        tiledMap = game.getAssetsUtil().getAssetManager().get("sprites/maps/tutorial_level.tmx");
        mapRenderer = new OrthogonalTiledMapRenderer(tiledMap);

        /* Setup Box 2D world */
        world = new World(new Vector2(0, -10), true);
        b2dr = new Box2DDebugRenderer();

        /* Create the tiled map box 2D world */
        MapCreator.createMap(this);
    }

    @Override
    public void render(float delta) {
        if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE)) {
            Gdx.app.exit();
        }
        if (Gdx.input.isButtonPressed(Input.Buttons.LEFT)) {
            camera.position.x += 100 * delta;
        }
        else if (Gdx.input.isButtonPressed(Input.Buttons.RIGHT)) {
            camera.position.x -= 100 * delta;
        }
        else if (Gdx.input.isKeyPressed(Input.Keys.W)) {
            camera.position.y += 100 * delta;
        }
        else if (Gdx.input.isKeyPressed(Input.Keys.S)) {
            camera.position.y -= 100 * delta;
        }

        /* Clear the screen and set the color */
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        game.getBatch().begin();
        //pbg.render(delta);
        pbg.draw(camera, game.getBatch());
        game.getBatch().end();

        /* Render Tiled Map */
        camera.update();
        mapRenderer.setView(camera);
        mapRenderer.render();

        b2dr.render(world, camera.combined);
    }

    @Override
    public void resize(int width, int height) {
        Gdx.app.debug(TAG, "Screen has been resized: " + width + "x" + height);
        viewport.update(width, height);
    }

    @Override
    public void dispose() {
        //TODO: Dispose variables here.
    }

    /* Retrieve the tiled map */
    public TiledMap getTiledMap() {
        return tiledMap;
    }

    /* Retrieve the box 2D world */
    public World getWorld() {
        return world;
    }
}

```

**My Solution** I have come up with a solution, which seems to work

```
MapProperties mapProperties = tiledMap.getProperties();

if (Gdx.input.isKeyPressed(Input.Keys.D)) {
    if (camera.position.x <= ((mapProperties.get("width", Integer.class) * mapProperties.get("tilewidth", Integer.class)) - viewport.getWorldWidth() / 2) - 1)
        camera.position.x += 100 * delta;
}
else if (Gdx.input.isKeyPressed(Input.Keys.A)) {
    if (camera.position.x >= (1 + viewport.getWorldWidth() / 2))
        camera.position.x -= 100 * delta;
}
else if (Gdx.input.isKeyPressed(Input.Keys.W)) {
    camera.position.y += 100 * delta;
}
else if (Gdx.input.isKeyPressed(Input.Keys.S)) {
    if (camera.position.y >= (1 + viewport.getWorldHeight() / 2))
        camera.position.y -= 100 * delta;
}

```

# Answer
One way to do this would be to clamp (limit) the x and y values of the camera to your width and height of the game. It may look something like this:

Clamp method:

```
public int clamp(int var, int max, int min) {
    if(var > min) {
        if(var < max) {
            return var;
        } else return max;
    } else return min;
/*
 * var = your variable that you want to clamp.
 * max = the maximum value of this variable.
 * min = the minimum value of this variable.
 */
}

```

then you can limit the x and y values of the camera by doing this where you update your game:

```
camera.position.x = clamp(camera.position.x, Gdx.graphics.getWidth()-camera.viewportWidth, 0);
camera.position.y = clamp(camera.position.y, Gdx.graphics.getHeight()-camera.viewportHeight, 0);
camera.update();

```

If your map does not occupy the entire game space you can just change the max and min values to fit your desired values.
> 1 votes

---
Tags: java, libgdx, camera, platformer, tiled
---