# Question
Title: How can I increase the hit range of a node?
How can I set the radius or the hit range of a node initialized with a texture? Of course I can do that with increasing the size of it, but actually I want to do this without resizing the picture itself. This node is moving around the screen with a small speed. This is my code:

```
func addMonster() {

let monster = SKSpriteNode(imageNamed: "MosquitoDrawed")

monster.name = predatorNodeName

monster.zPosition = 1

// monster.physicsBody = SKPhysicsBody(circleOfRadius: 50.0)

monster.position = CGPoint(x: random(-10.0,max: -30.0), y: random(10.0, max:130.0))

addChild(monster)

let actualDuration = 7.0

let actionMoveTo = SKAction.moveTo(CGPoint(x: random(500, max:800),y: random(1, max:800) ), duration: NSTimeInterval(actualDuration))

monster.runAction(actionMoveTo,withKey: "move")

}

```

# Answer
Have you tried to initialize your SKPhysicsBody with a rectangle of the size you want?

```
var node = SKSpriteNode(imageNamed: "node.png")
node.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 50, height: 50))

```

That way you can increase the size of the bounding box of your node without using a larger image.

More details in the docs.

Hope it helps!
> 1 votes

---
Tags: spritekit, swift
---


# Question
Title: Where is the GUI button press sound file for Minecraft?
I am making a custom modpack, and I need to change the GUI button press sound for my modpack, but I don't know where the sound file is for clicking the GUI button.

# Answer
> 3 votes
Learning to better help yourself is a wonderful thing, it helps you the most! With most things programming, doing a simple Google search first is typically the best route.

Then there's the option of reading the documentation for the thing you're working on. Often they have helpful tutorials or manuals to help you. Once you find a good source for documentation, it's typically best to look there first.

Finally, you can ask a question on a forum specific to the thing you're working on (but remember to always search the forum for an answer before asking a new one!), or if your question is more general, on a site for more general development in the field you're working in.

Specifically for your question:

> Sound directory (after 1.7.2)
>
> The sound files in version 1.7.2 (specifically 13w42a) and above are scattered and hashed into different folders, which are located in:
>
> Windows: %AppData%.minecraft\assets\objects
> Mac OS X: ~/Library/Application Support/minecraft/assets/objects
> Linux: ~/.minecraft/assets/objects

# Answer
> 2 votes
Copying my answer from Arqade.

---

### How to find a sound file

1. Open `\.minecraft\assets\indexes\<version>.json`. `<version>` can be `1.7.10`, `1.8`, `14w25b`, etc.
2. In the index file, you can find a organized list of assets and some informations(hash and size) about them. `cave9.ogg` for example,

> "minecraft/sounds/ambient/cave/cave9.ogg": {
> **"hash"**: **"b463fa47816fe9a5dfe508093150e647403e4db6"**,
> "size": 27096
> }

has a hash value of `b463fa47…`. Remember first 2 digits(in this case `b4`).
3. The actual sound file is located at `.minecraft\assets\objects\<first 2 digits>\` with a filename being a `<hash>` without any extension. For example, `cave9.ogg` is located at `.minecraft\assets\objects\b4\` with a filename `b463fa47816fe9a5dfe508093150e647403e4db6` without extension.

---

In your case the filename is `click.ogg`.

---
Tags: minecraft-modding, modding
---


# Question
Title: What is the mesh generation technique shown in Chrome Music Lab?
The Google toy of the day, https://musiclab.chromeexperiments.com/Spectrogram, features a continuously scrolling 3D render of a shape with cross sections that seem to equal the spectrograph of sound at a single instant.

Assuming the frequency information is available as input, how does that information become a mesh that updates continuously?

# Answer
At first glance, I'd implement this kind of effect much the same way I'd implement 3D terrain. Build a tessellated plane of the desired resolution with the height (`z`) values all zero. As the frequency histogram information becomes available, each timeslice of the histogram is mapped onto the rightmost column of the grid such that that the intensity becomes the `z` value of the grid vertex. As subsequent histogram samples become available, they push the existing samples to the left.

If all you're doing is producing this effect you can probably get away with a high enough tessellation factor on your grid that the motion of samples "across" the grid is smooth. You'd probably want to make sure you choose an appropriate data structure for the container of samples, something like a fixed-size ring buffer, which will let you linearly read the full set of samples starting at any arbitrary point but which would also not require you to shuffle all the samples in memory when inserting a new one (just change the read/write pointers within the buffer).
> 1 votes

---
Tags: procedural-generation, dynamic-mesh
---


# Question
Title: How can I move an object around a canvas in a random direction at random times?
I am currently trying to move an object **(circle ball)** around the canvas in a **random direction**.

I have already written the code for the wall collisions so the ball bounces back into canvas when the ball hits any of the canvas sides.

The canvas size is **600 x 500**

in order to move the object around the canvas I have used;

```
   xPosition += ySpeed;
   yPosition += ySpeed;

```

From the code above, the ball moves from one end to the other end of the canvas in the same angle and direction, then bounces back at a different angle.

How can I go about doing this, if I wanted my object to move in the same speed but in a random direction around the canvas.

Any help is appreciated, thanks!

# Answer
You want to generate a random direction vector which is normalized. Since the vector is normalized, you can then multiply that vector by your desired (scalar) speed to move in that direction with the desired speed.

One way to generate a random unit vector that avoids accidentally generating a null vector or directional bias is to randomly generate a value between 0 and 2π and using sine and cosine to give you `x` and `y` values:

```
angle = random(0, 2π)
direction = vector(cos(angle), sin(angle))

```

You can then update the ball's position by doing:

```
xPosition += (speed * direction.x)
yPosition += (speed * direction.y)

```

In your title also mention "at random times," which sounds to me like you also want the ball to change direction randomly every so often. If this is true, one way to accomplish this is to have a timer that counts down, and when it reaches zero you re-generate `direction` above. Once you re-generate `direction`, reset the timer to a random value in the desired range (say, 2 to 4 to make the ball change direction every 2 to 4 seconds, or whatever).
> 1 votes

# Answer
**Decomposition into Length and Direction:**

If you write a non-zero vector `r` as

```
r = ||r|| (r / ||r||) = ||r|| e_r

```

you have decomposed it into length `||r|| = sqrt(sum_i x_i^2)` and direction vector `e_r`, which is a unit vector with start point at the origin and whose end point for 2D lies on the unit circle, for 3D it lies on the unit sphere.

The 2D case of the direction vector can be characterized by by using polar coordinates with `r = 1` and `phi` from \[0, 2pi).

```
 erx = cos(phi)
 ery = sin(phi)

```

Choosing such `phi` randomly gives random direction vectors.

**Moving with constant speed but random direction:**

The change in position vector `dr` is roughly (for small `dt`)

```
dr = v dt

```

for some velocity vector `v` and time interval `dt`.

For a fixed velocity magnitude `S = ||v||` and random direction `e_r` this turns into

```
drx = S erx dt
dry = S ery dt

```

Note: You added `ySpeed` to `xPosition` which probably should be `xSpeed`.
> -1 votes

---
Tags: java, 2d, html-canvas
---


# Question
Title: how should a server handle client actions?
So I've just started trying to make a multiplayer pong game and I have read a lot of different ways to code the connections. However, I read somewhere that you should have the inputs sent to the server queue up and then the server just processes it at fixed intervals. However, if this is done, how does the server know, process, and send accurate data based on the time the action was sent? Because if the data is just queued up, if something happens like 100 ms after another but the server processes them at the same time, wouldn't that mess up the synchronization of the game? Should the server instead be coded to handle the client actions immediately even if it costs a lot of cpu etc in larger games?

# Answer
You don't need to process a packet immediately to know timing information. Just record the timestamp when a message is received, along with current latency measurements/estimations.

When you do eventually process the message you then know when the message originated. With the latency measurements, you can even estimate when the user initiated the action, e.g. if the server takes 50ms to process a packet and the network has 70ms of latency, you can estimate that the user pressed the key 120ms in the past.

This information can then be used by the server to alter its simulation. With pong, for instance, you can both set the paddle's velocity and teleport the paddle a little bit to account for the time difference. You can even rewind the pong ball and replay its collisions with the paddle after said adjustments, so the player is less likely to just barely miss the ball.

The client can do the same sort of time adjustment. It has an estimated latency to the server as well, and also can have estimated latency for the opponent. Using this information, the client can adjust the visual locations of the opponent or the pong ball. For instance, if the server sends an update on the ball position and direction, the client can extrapolate the ball's position using the estimated server latency.

Do be careful with doing both server and client time correction. It's hard to wrap your head around mathematically (it took me a while, anyway) and it's very easy to *think* you understand it when you really don't. Doing time correction on both server and client will exasperate any problems stemming from misunderstandings. I'd probably start with client extrapolation and build up from there, *if* you even need to.
> 1 votes

---
Tags: multiplayer, client-server
---


# Question
Title: Do game studios look at personal projects when hiring?
I am 17 and I have spent the past 5 years making games for fun. But now I am faced with college and it might be time to get serious about this hobby.

So do Game Studios want to see personal games or 3d models in resumes, or will they only care about professional level work? To a lesser extent my question is also when would a company hire a high school student and why?

As always with these sites I feel like i'm walking on eggshells, so if this is posted in the wrong place, or if i'm breaking any rules please tell me.

# Answer
> 2 votes
If the game or model you made for a personal project demonstrates your skill well, it's definitely worth including in your portfolio.

Just bear in mind that more is not necessarily better. A piece that represents a great learning experience for you on the road to the more polished work in your portfolio might stand out to an interviewer as a weak point, and raise questions about the consistency of your work. So, ruthlessly pare your portfolio down to only your very best work.

---
Tags: career
---


# Question
Title: Player shooting himself when moving - Unity UNET
**Setting** : Creating my first multiplayer game and running into an odd issue. it's a tank game where players can shoot bullets and kill each other

**Problem** : When the client shoots **while moving**, the bullet seems to spawn with a little delay which causes the the player to collide with the bullet.

> The issue seems to be that the player itself is local and the bullet is being spawned on the network ( which is causing the delay)

**Note**: The host player does not have this problem, therefore it's somehow related to networking.

How can I sync the bullet with the client player?

```
private void Fire(){
    // Set the fired flag so only Fire is only called once.
    m_Fired = true;
    CmdCreateBullets ();
    // Change the clip to the firing clip and play it.
    m_ShootingAudio.clip = m_FireClip;
    m_ShootingAudio.Play ();
    // Reset the launch force.  This is a precaution in case of missing button events.
    m_CurrentLaunchForce = m_MinLaunchForce;
}

[Command]
private void CmdCreateBullets()
{

    GameObject shellInstance = (GameObject)
        Instantiate (m_Shell, m_FireTransform.position, m_FireTransform.rotation) ;
    // Set the shell's velocity to the launch force in the fire position's forward direction.
    shellInstance.GetComponent<Rigidbody>().velocity = m_CurrentLaunchForce * m_FireTransform.forward;

    NetworkServer.Spawn (shellInstance);

}

```

# Answer
Syncing physics simulations can be complex. Where are you doing the collision test? On the server? On both clients? On only the client who shot the bullet? If the collision test is on the client, look at Collision Layers: http://docs.unity3d.com/Manual/LayerBasedCollision.html This would allow you to place the local player on a different layer to remote opponents, so it could not collide with the bullet.

Alternatively look at triggers with a custom validity check: http://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html So when a bullet hit a tank it would be able to check to see if it had hit a valid target. Note that triggers don't act like rigid bodies in the scene, so they would go right trough a tank if they did not decide they were hitting something valid.

Regarding syncing the physics itself, it is usually achieved by having a single authoritative simulation, and doing periodic (ie not every frame) updates that synchronize the local client simulations to the remote one. This can be either client to client (you decide which client is authoritative, and sync the others to that one) or sever to client (there is a single authoritative simulation on the server and all the clients sync to it.) In either case, the local simulation continues on its own between syncs. That is why you see things jumping around in laggy online games, because the local simulation has gotten too far out of sync with the authoritative simulation and the update is noticeably different.

Hope that gives you some ideas.
> 2 votes

# Answer
I solved it the following way. if someone can look over to confirm my answer, it would be nice.

```
private void Fire(){
    // Set the fired flag so only Fire is only called once.
    m_Fired = true;
    CmdCreateBullets ();
    // Change the clip to the firing clip and play it.
    m_ShootingAudio.clip = m_FireClip;
    m_ShootingAudio.Play ();
    // Reset the launch force.  This is a precaution in case of missing button events.
    m_CurrentLaunchForce = m_MinLaunchForce;
}

[Command]
private void CmdCreateBullets()
{
    RpclocalBullet ();
}

[ClientRpc]
private void RpclocalBullet(){
    GameObject shellInstance = (GameObject)
        Instantiate (m_Shell, m_FireTransform.position, m_FireTransform.rotation) ;
    // Set the shell's velocity to the launch force in the fire position's forward direction.
    shellInstance.GetComponent<Rigidbody>().velocity = 25f * m_FireTransform.forward;
}

```
> 0 votes

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


# Question
Title: How can I implement Player Prefs to Save High scores in unity?
I am new to both unity and C# and facing trouble in saving and displaying the highscore.text in the game.Til now I only successfully managed to display the scoreUI and update them whenever player hits the enemy.This is the code that I'm using.

```
{

public GameObject ScoreImage;
public Text scoreTextUI;

int score;
public int Score
{
    get
    {
        return this.score;
    }
    set
    {
        this.score = value;
        UpdateScoreTextUI();
    }
}
// Use this for initialization
void Start ()
{
    //Get the Text UI Component of this gameObject
    scoreTextUI = GetComponent<Text> ();
}

void UpdateScoreTextUI()
{
    string scoreStr = string.Format ("{0:000000}", score);
    scoreTextUI.text = scoreStr;
}
}

```

# Answer
Saving `Int` to player prefs:

```
PlayerPrefs.SetInt("Player Score", 10);

```

Retriveing `Int` from player prefs:

```
var playerScore = PlayerPrefs.GetInt("Player Score");

```
> 1 votes

# Answer
Basically `PlayerPrefs` works on `Key-Value` mechanism just like `Dictionary`. The difference is that you can set `Key` only in `string`.

Unity provides very basic data types that can save using `PlayerPrefs`, that includes `int`,`float`, and `string`.

In your case you are going to save an integer value, that `PlayerPrefs` supports. You can use it through

```
/* Replace HIGH_SCORE_KEY with your string key
and HIGH_SCORE_VALUE with your int score */
PlayerPrefs.SetInt("HIGH_SCORE_KEY",HIGH_SCORE_VALUE)

// Similarly you can get the value as
PlayerPrefs.GetInt("HIGH_SCORE_KEY");

```

Now what you have to make change in your code,

```
...
int _score = 0; // Assuming that you are updating this variable as score
string KEY_HIGH_SCORE = "keyhighscore"; // whatever you set, doesn't matter. Just store it in variable to avoid any typo

// To save highscore
int currentHighScore = PlayerPrefs(KEY_HIGH_SCORE); // If no score was saved corresponding to that key then it will return 0

if (currentHighScore < _score) // if stored score is less than the current score
    PlayerPrefs.SetInt(KEY_HIGH_SCORE, _score);

// Get and update the scoreUI whenever and wherever you want as
int currentHighScore = PlayerPrefs(KEY_HIGH_SCORE);
scoreTextUI.text = scoreStr.ToString();

```
> 1 votes

---
Tags: unity, c#, 2d, mobile
---


title: Combine Unity games in one app

text:
# Question
Title: Combine Unity games in one app
I want to combine multiple Unity games in one Unity app (or other framework if necessary). This app would have a bunch of buttons that will start the desired game. Is this possible and what would be the best way to do this? Thanks!

# Answer
The scene handling system of Unity makes each scene essentially a separate game.

So you can easily do this by importing all assets and all scenes of the games into one Unity project and then add a launcher scene which allows the player to choose the game. On click of the appropriate button the start-scene of that game is loaded.
> 2 votes

---
Tags: unity
---


# Question
Title: Box2d set sprite to body that rotates around specific point
I want to rotate kinematic body around a specific point (I already done this part using

```
shape.setAsBox(1.8f / PPM, 0.2f / PPM, new Vector2(5.2f, 0), 0);

```

What I try is this:

```
PolygonShape shape = new PolygonShape();
shape.setAsBox(1.8f / PPM, 0.2f / PPM, new Vector2(5.2f, 0), 0); // !!!!

FixtureDef fdef = new FixtureDef();
fdef.shape = shape;
fdef.filter.categoryBits = categoryBits;
fdef.filter.maskBits = Constants.PLAYER;

bDef.position.set(((V_WIDTH / 32 - 3) / 2) / PPM, y / PPM);

body = world.createBody(bDef).createFixture(fdef).getBody();
body.setAngularVelocity(1f);
body.setUserData(new BodyUserData(categoryBits, colorArray[0]));

sprite.setOrigin(sprite.getWidth() / 2, sprite.getHeight() / 2);
sprite.setPosition(
    body.getPosition().x * 32 - sprite.getWidth() / 2,
    body.getPosition().y * 32 - sprite.getHeight() / 2
);

```

and here how I draw sprite

```
public void draw(SpriteBatch sb){
    sprite.setRotation(body.getAngle() * MathUtils.radiansToDegrees);
    sprite.draw(sb);
}

```

Unfortunately my sprite position is not the same as my body. It seems that sprite is rotating around it's center, not my point. Is it possible to fix that?

# Answer
Just setting your bodys angular velocity means that it rotates around its center. You never definded the point it should rotate around.

Sadly in Box2d you can't define a rotation origin, but you could try this:

1. Define a static body for your fixed point
2. Define your rotating body
3. Use a Joint to link these 2 bodies
4. Apply a force to your rotating body
5. Update your sprites position to the bodys position each time you draw it

---

Or you could calculate the circle of rotation by yourself and set the sprites position before each draw, like @Hamza Hasan described in his answer

---

If you want your sprite to rotate around a specific point, change its origin relative to that point:

```
// This sets the sprites origin to its center, letting it rotate around its center
sprite.setOrigin(sprite.getWidth() / 2, sprite.getHeight() / 2);
// If you want it to rotate around a point (e.g. 50 pixels to the left) you could try
sprite.setOrigin(-50, sprite.getHeight() / 2);

```

You just have to calculate the distance of your sprite to the point:

```
Vector2 specificPoint = new Vector2(200, 400);
Vector2 position = sprite.getPosition();
Vector2 distance = new Vector2(position.x + sprite.getWidth() / 2 - specificPoint.x,
                              position.y + sprite.getHeight() / 2 - specificPoint.y);
sprite.setOrigin(distance);

```
> 2 votes

# Answer
I don't know `libgdx`, but I know something that might help you, in fact some trigonometry will help you at this point.

Normally I use parametric equation of *circle* for this purpose if I am unable to do it by all the other ways.

Here is the *parametric equation* of *circle*

```
x = r * Cos(theta) + displacementX
y = r * Sin(theta) + displacementY

```

where,

* r = radius
* theta = angle that will change upon time. (in gameloop)
* displacementX and displacementY would be the center point of the body in center. **( if displacementX and displacementY both are zero then this equation will rotate the body around origin )**

Lets say, you have a `box` as centre point and a `circle` as the sprite or object that will rotate around the `box`.

## pseudo-code:

```
r = 5; // radius or distance from the box
theta = 0; // could be any, up to you
rotationSpeed = 0.5; // Change in angle, also represents the rotation speed

// public void draw(SpriteBatch sb) in your case
Gameloop()
{
    displacementX = box.x
    displacementY = box.y

    circle.x = r * Cos(theta) + displacementX
    circle.y = r * Sin(theta) + displacementY

    theta += rotationSpeed // from this you can control the rotation speed

    if (theta >= 360)
        theta = 0;
}

```
> 2 votes

# Answer
You need to set sprite position to body's position each render frame, not only in initialization method.
> -3 votes

---
Tags: libgdx, sprites, box2d, rotation
---


# Question
Title: How does this math behind converting angles to vectors work?
I calculated the vectors of my yaw and pitch successfully. Even tho it works fine, I can't seem to understand how the math works exactly.

Could someone (graphically / demonstratively) explain me this with a picture so I can better derive the math?

```
Vector3d CSMath::AngleToDirection(Vector3d angle) {
// Convert angle to radians
angle.x = (angle.x) * 3.14159265 / 180;
angle.y = (angle.y) * 3.14159265 / 180;

float sinYaw = sin(angle.y);
float cosYaw = cos(angle.y);

float sinPitch = sin(angle.x);
float cosPitch = cos(angle.x);

Vector3d direction;
direction.x = cosPitch * cosYaw;
direction.y = cosPitch * sinYaw;
direction.z = -sinPitch;

return direction;
}

```

I'd be really grateful! Thanks guys.

# Answer
> 1 votes
First let's look at how to convert an angle (the yaw-angle) into a vector in two-dimensional space:

As you can see the y-value is the sine of the angle and the x-value is the cosine of the angle.

```
direction.x = 1 * cosYaw;
direction.y = 1 * sinYaw;

```

Now what happens when we add a 3rd dimension and rotate all of that around the x-axis by a new angle (the pitch-angle) while still keeping our viewpoint from straight up?

As you can see, while the appearance of the circle shifts into an ellipse, both the length of the x-value and the y-value are reduced. The amount they are reduced by is the cosine of the second angle.

```
direction.x = 1 * cosYaw * cosPitch;
direction.y = 1 * sinYaw * cosPitch;

```

# Answer
> 1 votes
It works via repeated Rotations, you begin mentally with the Vector {1,0,0} then you rotate it along the Y-Axis the length of the vector is just one so you can get the new coordinates simply by evaluating sin and cos (of the angle along the Y-Axis), as their pair represents points on a circle hence rotating but you are rotating in another direction than in the second rotation (the minus infront of sinpitch). This yields {cospitch,0,-sinpitch}.The Y entry stays constant as per Definition of a Rotation around an axis.

Now you rotate along z so z will stay constant and you rotate along x and y. The distance of the point from the rotation axis is not simply cospitch because the z component lies completely in the axis. Therefore in this Rotation you have to multiply the Rotation by cospitch and rotate the x and y components. this now gives the desired form:

{cospitch times cosjaw,cospitch times sinjaw,-sinpitch}

So this is atleast one repsentation of this rotation but there are infinetly many rotations more that express this transformation but every one of them is equally valid. But your code works with this "starting vector" of {1,0,0}.

---
Tags: vector, angles, direction
---


# Question
Title: Setting a Boolean as a field of an object from another script
I saw this question asked some times but no one correlates to mine. I see people using the GetComponent() function but this one should work too.

First I receive a Bool value from a toggle button and assign it as a field of the object 'hydro':

```
hydroControl.cs

using UnityEngine;
using System.Collections;
using Assets.Code.PowerPlants;

public class hydroProwerControlPanel : MonoBehaviour {
private HydroElectric hydro;
public bool t1;

void Start ()
{
    t1 = true;
}

public hydroProwerControlPanel (){
    hydro = new HydroElectric();
}
public void turbine1State (bool t1) {
     hydro.t1Bool = t1;
}

```

Then I have the object where this bool change should be recognized and sent as an output, but it doesn't:

```
using System;
using UnityEngine;
namespace Assets.Code.PowerPlants
{
    public class HydroElectric
    {
        public bool t1Bool;
        float turbina1;

        public float prod;

        public HydroElectric ()
        {
          t1Bool = true;
          prod = 0f;
        }

        public float ControlPanel ()
        {
            turbina1 = t1Bool ? 1.5F : 0;

            prod = turbina1 ;
            Debug.Log (prod);
            return prod;
        }
    }
}

```

As requested, this is where the function ControlPanel() is called:

```
using System;
using UnityEngine;
using UnityEngine.UI;
using Assets.Code.PowerPlants;
namespace Assets.Code.Interfaces
{

public class PlayLevel1 : MonoBehaviour
{
private HydroElectric hydro;
public Text producao;

public PlayLevel1 ()
{
    hydro = new HydroElectric();
}

public void OnGUI()
{
 producao.text = hydro.ControlPanel().ToString();
}
}
}

```

Do you have any idea why does this Bool does not get updated? Any help appreciated.

# Answer
> 0 votes
You're actually referring to 2 different instances of `HydroElectric`, which is why you're not seeing the `bool` change value.

As it stands `hydroProwerControlPanel` holds an instance of `HydroElectric` whose value changes when you call `turbineState`, but `PlayLevel1` holds a completely different instance of `HydroElectric` and that instances value is never modified.

There are a couple of ways around this. You could implement the **Singleton** pattern if there is only ever going to be one `HydroElectric` per scene, or you can pass `PlayLevel1` the instance of `HydroElectric` that you want to monitor (known as **Dependency Injection**)

More details on Singletons in Unity can be found here:
https://rockonflash.wordpress.com/2010/10/21/singletons-in-unity3d/
http://wiki.unity3d.com/index.php/Singleton

More details on Dependency Injection in Unity can be found here:
http://wiki.unity3d.com/index.php/Dependency\_injection
http://blogs.unity3d.com/2014/05/07/dependency-injection-and-abstractions/

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


title: libgdx sphere rotation after movement

text:
# Question
Title: libgdx sphere rotation after movement
I'm moving my sphere on the screen using this method:

```
Matrix4 m = myBall.body.getCenterOfMassTransform();
Vector3 translation = new Vector3();
m.getTranslation(translation);

float multiplier = delta * 4 * game.platform.accelerometerFactor();
movement = new Vector3(Gdx.input.getAccelerometerY() * multiplier, 0, Gdx.input.getAccelerometerX() * multiplier);

translation.add(movement);
m.setTranslation(translation);
myBall.body.setCenterOfMassTransform(m);

```

Then I would like to rotate my sphere during movement. So I counted angle which sphere should be rotated and then applied it before I call myBall.body.setCenterOfMassTransform(m) using:

```
float x = movement.x;
float z = movement.z;
Vector3 axis = new Vector3(z, 0, -x);
m.rotate(axis, angle);

```

But the sphere is rotating strangely. Where is the problem in my process of rotation?

# Answer
It seems to me that the axis of rotation should be a positive multiple of

```
a = v x (-e_z) = (vx, vy, vz) x (0, 0, -1) = (-vy, vx, 0)

```

where `v` is the velocity vector, `e_z` the unit vector in `z` direction and `x` the vector product.
> 1 votes

---
Tags: libgdx, rotation
---


title: Camera movement in unity engine

text:
# Question
Title: Camera movement in unity engine
I have a basic camera setup which is angled like so:

```
x: 30
y: 0
z: 0
Projection: Orthographic

```

And i attached a C# component to it and made it so the camera moves with a right click and drag movement.

The problem is its not moving at the same amount as the mouse. I had to set a value for scroll speed to 1000 and even then its still too slow.

I want the camera to move with the mouse in a more raw amount, then i wish to add some lerp effect to it so it feels a bit more slick.

I don't know why the movement is so slow, i come from a 2D background and am learning 3D so i suspect my lack of understanding of 3D positions might be the issue.

This is my current code:

```
using UnityEngine;
using System.Collections;

public class cameraMove : MonoBehaviour {

// VARIABLES
public float panSpeed = 1000.0f;

private Vector3 mouseOrigin;
private bool isPanning;

void Start ()
{
    Vector3 pos = GameObject.Find("Sun").transform.position;
    Camera.main.transform.LookAt (pos);
}

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

    if (Input.GetMouseButtonDown (1))
    {
        //right click was pressed
        mouseOrigin = Input.mousePosition;
        isPanning = true;
    }

    // cancel on button release
    if (!Input.GetMouseButton (1))
    {
        isPanning = false;
    }

    //move camera on X & Y
    if (isPanning)
    {
        Vector3 pos     = Camera.main.ScreenToViewportPoint (mouseOrigin-Input.mousePosition);

        // update x and y but not z
        Vector3 move    = new Vector3 (pos.x * panSpeed, pos.y * panSpeed, 0);

        Camera.main.transform.Translate (move, Space.World);
        mouseOrigin = Input.mousePosition;
    }
}

```

}

# Answer
> 0 votes
Input.GetAxisRaw might be what you're looking for. In the Input Manager (Edit -\> Project Settings -\> Input) setup a variable for "Mouse X" and "Mouse Y" (if not already setup \[as below\]).

Then in code;

```
public class CameraMove : MonoBehaviour
{
    private Vector2 pos;
    private bool    isPanning;

    public void Start()
    {
        pos = new Vector2();
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(1))
            isPanning = true;

        if (Input.GetMouseButtonUp(1))
            isPanning = false;

        if (isPanning)
        {
            pos.Set(Input.GetAxisRaw("Mouse X"), -Input.GetAxisRaw("Mouse Y"));
            transform.Translate(pos, Space.World);
        }
    }
}

```

For movement in the Y plane, the value from the mouse must be negated to, unless you with to use inverted controls. Hope this helped.

# Answer
> 0 votes
I think you can compare `Input.mousePosition` (in pixels) directly:

```
static Vector3 mouseDelta;
//from (-Screen.width, -Screen.height, 0) to (Screen.width, Screen.height, 0)
mouseDelta = (mouseOrigin - Input.mousePosition);
//convert pixels to world-units
mouseDelta /= panSpeed;
Camera.main.transform.Translate(mouseDelta, Space.World);
mouseOrigin = Input.mousePosition;

```

Note: you should clamp the transform's position to valid coordinates.

---
Tags: camera, unity, mouse, scrolling
---


# Question
Title: Transform texture coordinates when using shader
Assuming I define four vertices of a quad with texture coordinates that cover a whole texture or region of a texture, I can animate these coordinates by setting a transform using

```
SetTransform( D3DTS_TEXTURE0, &texTrans )

```

...scaling, translating etc.

If I render using a shader, and still want to animate the coordinates, presumably I can pass in the same transformation matrix and multiply the coordinates in the vertex shader?

Instead of in the vertex shader

```
Output.TextureUV = vTexCoord0;

```

do

```
Output.TextureUV = mul( vTexCoord0, texTrans );

```

Is this a/the correct way to render an animated sprite with shader?

# Answer
> 4 votes
I just stumbled back on this question, so I figure I should supply an answer. :)

The shader code I wrote in the question is almost right. I forgot that to convert a point with these transformations, the point needs to be in homogeneous coordinates.

See: https://stackoverflow.com/questions/5066532/how-to-multiple-a-2d-point-with-a-4d-matrix

So the correct vertex shader code would be:

```
Output.TextureUV = mul( float4( vTexCoord0, 0.0f, 1.0f ), texTrans );

```

---
Tags: shaders, directx, animation, sprites, directx9
---


# Question
Title: Efficient way to store entities in javascript
I am trying to design a game from strach with Javascript.

It's a 2D game (a kind of Zelda on old devices).

I am trying to find an efficient way to store my data because I know I will have to face some major challenges among which :

* Pathfinding
* collision

I may have more than 1 000 entities on screen and maybe even more background objects (let's shoot for the stars !)

Do you have some advices / hints / articles about an efficient way to store objects so that I can (for e.g.) retrieve only a reduced set of entities in my collision algorithm

maybe there are some design patterns to deal with those challenges ?

# Answer
> 1 votes
You could use a tileset to store your background objects. Tilesets would also allow you to have efficient pathfinding and collision detection since they are just an array of data. You could also store the location of all entities in the tileset so you know which ones are in range based on the distance between the player and the edge of the screen.

You can check out this example I made on my site of a large world 2D map using a tile engine. It runs at 60FPS with collision detection.

*Disclaimer: I wrote that article and the example.*

---
Tags: game-design, javascript, design-patterns
---


# Question
Title: How to efficiently organize different game zones with different functionality?
For now I have a list of basic data class like position in game world, dimensions, type and stuff like that, but since I am starting to implement their functionality it seems kind of a bad pattern, I need each zone to have totally different data and behaviour, use different UIs etc, is there a pattern to realize that other that just making one totally different class for each zone?

# Answer
> 1 votes
You can use something like a component based, inheritance or composition architecture. You have plenty of options here, and it really boils down to your own style and the requirements of your game.

For a quick implementation, I would probably a simple form of component based architecture. Probably making the components and systems using inheritance. This would allow me to create systems and components that share some functionality, like modifying the attributes of the unit inside their bounds, or creating new units, or whatever's needed. Then when making the zones, I can mix and match components to build whatever kind of zone I want.

Zones would then be defined with the list of components you want them to have. For example adding a "Modify health" component and an "Every X seconds" component would provide your heal-over-time functionality. Or adding a "Modify health" component (with a negative value) and a "Single use" component would create something like a landmine.

I think this will give a good mixture of the two architectures and be flexible enough to provide a lot of options for zones.

---
Tags: architecture
---


# Question
Title: Initializing Consumable product to an amount on first use
I am using Unity's In App Purchase plugin to implement an in game store. In my game every player has fuel. I'd like to use the plugin in order to keep track of the amount of fuel the player has so that just erasing the cache on the phone or something wouldn't effect the regeneration time of fuel (like it would if I use PlayerPrefs).

Right now i have it setup so the fuel amount is saved in PlayerPrefs and when fuel is used, a timestamp is saved in PlayerPrefs. Then it checks every once in a while if enough time has passed since they used it in order to regenerate it.

Instead of doingoing it this way I want to initialize the fuel amount in Unity's in app purchase plugin so that Googles servers will have the amount and then I can use the same idea for regeneration that I already have but nowe the amount will be more safe.

Is there a way to initialize the amount of a consumable product a player has on their first launch of a game?

# Answer
> 2 votes
The issue at hand here isn't a matter of the store, but your program and the way you save files.

Unity Services' built-in In-App Purchasing (IAP) is, in some sense, a complex messaging system. When you register a consumable, it just means it's a repeatable purchase such as "100 gold bars", as opposed to, for example, "New level set", which would only be purchased once.

When you purchase "100 gold bars" or, in your case, a "fuel tank" or something to that effect, your IStoreListener-implementing script will receive a message through ProcessPurchase, and the PurchaseEventArgs will contain the Product representing what the user purchased. From here, you interpret that Product and say, "This Product is X amount of fuel. Add X fuel to the fuel manager". From here, it's up to you to serialize and save that data however you see fit.

For reference, here is the official Manual section on Unity Services IAP. It's not a perfect reference and needs some work, but it should give some sense on the workings of creating an in-game store. Also consider looking up classes and interfaces in the Scripting section; I find that the Product documentation gives a thorough explanation of implementing IStoreListener.

---
Tags: unity, c#, in-app-purchase
---


title: Keep a rigidbody velocity constant

text:
# Question
Title: Keep a rigidbody velocity constant
I have a "board" with a ball (rigidbody) moving over it and colliding with obstacles.

I want its velocity **magnitude** to remain constant throughout time.

*How do I achieve this?*

---

*What I've tried/achieved so far:*

* My first guess was to use OnCollisionExit to set the velocity manually, but that lead to weird physics.
* I don't see how to use AddForce to do this since the previous movement would still be factored.
* To be clear, what i want is to set the velocity at all times to *rigidbody.velocity.normalized x magnitude*, where magnitude is a float I set previously. This would allow the physics engine to make all impact math to decide the **direction** of the ball after the collision, but my math would keep the velocity intact.
* I then decided to add UpdatedFixed and on every call set the velocity as stated above. It's working, but feels like a bad hack because I'm updating the velocity every frame and forsaking the physics engine.

# Answer
> 1 votes
I feel like you're on the write track with the 'bad hack'.

You're trying to do magical things with a component designed to approximate some real-world physics.

**Inside FixedUpdate, Update or LateUpdate:**

```
rigidbody.velocity = _constantSpeed * (rigidbody.velocity.normalized);

```

or some similar variation.

Don't need interaction with other physics objects? Then you don't need the RigidBody entirely; simulate motion with something like the above code, detect collisions and let the instigator (your ball) tell the other collider how much force should be applied. It's probably not necessary

---
Tags: unity, unityscript
---


title: Glow shader limited by the texture area

text:
# Question
Title: Glow shader limited by the texture area
I'm working on a glow shader (for 2D engine Futile relying on Unity). It works OK but the effect is limited by the texture area. Except from adding a lot of empty pixels around the textures (which would result in un-optimized/too big texture atlases), is there a better solution to cope with this problem? I'm quite new with shaders so maybe this is a classic problem with some well known solutions, maybe I'm not searching with the right keywords.

# Answer
> 1 votes
You don't outline directly on the object itself, but do the outline in a post process step.

1. Draw the scene, as if there was no outline.
2. Draw the object(s) you want outlined to a new screensized texture.
3. Apply the outline shader you already use to combine the images.

You may want to change the shader, so it draw the outline to the screen, without drawing the object itself; since you can draw the object in step 1, the outline will show up nicely anyway.

This has the benefit that if the object is obscured the outline will show the entire object. For example when the wizard is behind a tree, the tree will show but the outline shows the entire wizard. This is often used in games where hilighted objects may be hidden depending on the camera orientation.

---
Tags: unity, shaders, glow
---


title: Redefining the SDL rect struct

text:
# Question
Title: Redefining the SDL rect struct
Upon checking the docs of SDL (1.2) I saw that the SDL\_Rect struct defines the x and y as Sint16. I'm making a bitmap font text scroller and I need those specifically to be unsigned ints because the text does need to go offscreen, yet still using the same struct because the SDLBlit method needs it. I tried creating my own and typecasting it as an SDL\_Rect but that didn't work. Any ideas?

Also, to be more clear. The string of text scrolls to the left, therefore the first letter of my text does indeed go off screen but the rest doesn't. I assumed this was the problem.

```
for(int i=0;i<strlen(string);i++) {
  SDL_Blitsurface(bitmapsurface, rects[chars[i]], screen, destrect);
  destrect.x+=8;
}

```

# Answer
> 1 votes
Looking at the SDL\_Rect documentation, it's defined as:

```
typedef struct {
  Sint16 x, y;
  Uint16 w, h;
} SDL_Rect;

```

This gives you a range of −32768 to 32767 for the `x` and `y` component, and a range of 0 to 65535 for the `w` and `h` component. It doesn't make sense to have negative widths and heights (thus `w` and `h` are unsigned), and `x` and `y` are already signed, meaning that it can represent off-screen positions (up to 32k pixels to the left of the screen and up to 32k pixels above the top of the screen).

Assuming your characters are 8 pixels wide (you do `destrect.x+=8;`), you can have 4000 charaters to the left of the screen and still be within the representable range of `Sint16`.

Only render what's on the screen, as the other poster suggested. In general, there are 3 cases:

1. Character is completely off-screen, no need to render
2. Character is partially off-screen, render parts of it
3. Character is completely on-screen, render it fully

In case the blitting function handles clipping, case 2 and 3 can be combined.

Given that you have a fixed-width font, skipping off-screen characters is relatively easy and can be done up-front, with no conditionals inside the loop:

```
// The X position of where the text starts
int text_position_x = -90000;

// The text that you want to output
const char *chars = "Hello World";

// The fixed width of each character
int char_width = 8;

// Determine the first on-screen character
int first_character = 0;
int last_character = strlen(chars);

// If text starts off-screen, skip completely invisible characters
if (text_position_x < 0) {
    first_character = -text_position_x / char_width;
    text_position_x += char_width * first_character;
}

// text_position_x will be >= -char_width + 1
dstrect.x = text_position_x;
for (int i=first_character; i<last_character; i++) {
    SDL_Blitsurface(bitmapsurface, rects[chars[i]], screen, destrect);
    destrect.x+=8;
}

```

Some other remarks:

* Call `strlen()` only once at the beginning and not in every iteration
* You can do clipping on the top / right / bottom edge of the screen as well
* You could cull some strings early once you know they are fully off-screen

# Answer
> 0 votes
You will have to check (where the text is, Inside or outside the screen) before you render, and correct it.

Example:

```
if( rec.x < 0 )
{
    // Here you will set something to render the other par of the text in x=0;
}

```

---
Tags: sdl
---


title: Detecting position within a circle

text:
# Question
Title: Detecting position within a circle
I need to detect the position of a knob on a touchpad. I need to detect if it is in particular areas and if so, which one. The sections, of course, being the colored parts.

I know that the black center circle ends at 0.8f and -0.8f for both the X and Y axis.

The information I can get is the percent X and percent Y which is 0 to 1 from center or 0 to -1 from center the other way.

How would I go about doing this?

# Answer
> 2 votes
This is exactly what the arc tangent function of 2 arguments (Math.atan2) does.

```
double angle = Math.atan2(y, x);

```

Also, a common trick used to cheaply test the radius is:

```
double radius = 0.8;
if (x*x + y*y > radius*radius) {
    // outside the grey circle
}

```

# Answer
> 0 votes
You should have a look at polar coordinates.

The dark central circle is the set of points

```
C = { (r, phi) | 0 <= r <= 0.8, 0 <= phi < 2 pi }

```

The other coloured parts are the sets

`C_i = { (r, phi) | 0.8 <= r <= 1, phi_i <= phi < phi_(i+1) }`

where `i in {0,..,5}`, `phi_6 = phi_0` and you need to measure the angles `phi_i` from your diagram.

For the conversion between polar and Cartesian coordinates use the formulas from the linked Wikipedia article.

---
Tags: java, mathematics
---


# Question
Title: Grid of buttons in Unity - button bounds are stretching beyond their visuals, capturing clicks meant for other buttons
I am using unity UI for the first time and trying to create a level selection menu just like Angry Birds.

I had successfully created the dynamic level selection menu. It was all good in the inspector but when I build and run it, something strange happens: when I click on the first button of the first row, instead of that button, the last button of that row got clicked.

I searched and found that the image was not stretching (because of preserve aspect property checked) but the bounds were stretching with the resolution so the bounds were overlaping and the wrong button was getting clicked.

1. There is a panel which is child of the canvas gameObject.
2. Buttons are child of panel gameObject.
3. Panel's anchors are set to stretch the canvas.
4. Buttons' anchors are set to stretch the panel.

Here is the code to create menu dynamically.

```
public class UITest : MonoBehaviour
{

    public Button button;
    public RectTransform parent;

    void Start()
    {
        SetupButtons();
    }

    void SetupButtons()
    {
        float x = -155;
        float y = 55;

        for(int i=1; i<15; i++)
        {
            var I = i;
            var btn = Instantiate(button) as Button;
            var btnRect = btn.GetComponent<RectTransform>();

            float width = btnRect.rect.width/5;
            float height = btnRect.rect.height/5;

            btn.transform.SetParent(parent, false);
            btnRect.anchoredPosition = new Vector2(x, y);
            btn.onClick.AddListener(() => Temp(btn, I));

            if(i%5 == 0)
            {
                y += (height);
                x = -155f;
            }

            else
            {
                x += -width;
            }

            //Debug.Log(width +", " + height);
        }
    }

    void Temp(Button btn, int i)
    {
        //Debug.Log("Clicked: " + i);
        Debug.Log(btn.GetComponent<RectTransform>().anchoredPosition + " " + btn.GetComponent<RectTransform>().rect);
    }
}

```

Here are some screenshots to better understand the problem.

I hope you guys have understood the problem please help me solve the problem.

# Answer
> 1 votes
```
transform.anchorMin = new Vector2(0f, 0f);
transform.anchorMax = new Vector2(1f, 1f);
transform.pivot = new Vector2(.5f, .5f);

```

http://answers.unity3d.com/questions/1007886/how-to-set-the-new-unity-ui-rect-transform-anchor.html

# Answer
> 0 votes
Thank you everyone for the response but I had solved the problem myself. In case anyone else facing this problem, I just set the anchor points to be the middle of the panel and my problem vanished.

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


# Question
Title: What do you call the sounds that play when players place/destroy blocks?
I'm working on a game and trying to find sounds for it. I'm not sure what terminology to use when searching to find the *kinds* of sounds I need.

Specifically I'm looking for sounds that make sense for when a player places or destroys a block in my game. What are these sort of incidental environment background effects called in general, so I can better refine my searches?

# Answer
> 1 votes
I think asking for assets/asset sites is off-topic, but there's a glimmer of an on-topic question here about asset *terminology*. ("I don't know, what I can Google, or how these sounds are called.")

If I interpret your question as **"What are the terms used for sound effects like placing blocks in games?"**...

Then I think the word you're looking for may be "foley." This is used to refer to all the incidental sounds of action & movement in the game world, like footsteps or rustling & jangling of clothing/armor, or the impact sounds when an object strikes/lands against another surface.

A good foley kit will usually have a bunch of combinations like "impact, wood, soft" "impact, wood, heavy" "scrape, metal, medium" or maybe even destruction sounds like "crumbling stone"

Of course, that assumes you're looking for a sound based in physical intuition about familiar materials. Since it's a game, we can control the world however we like, and decree that "placing a block" sounds like that sound old CRT televisions made when you turned them off, and "destroying a block" sounds like opera singing. If you're going super-imaginative with your sounds though, there's probably no one term that would encompass everything you're looking for, so you'd need to specify a lot more precisely what you want these things to sound like in your game world.

---
Tags: sound, terminology
---


# Question
Title: Suggest me a degree for Game development
Which degree I pursue to become a **game developer** and from where?

I have done BCA and now i want to become a **Professional Game developer** to work in companies like `ubisoft` or `ea games`.

# Answer
Game developing is not a government job. You don't need a degree to develop games, also you don't need that **Professional** title.
> -2 votes

---
Tags: game-design
---


# Question
Title: Object has its heading stored as Euler angles. After it makes a turn, how do I calculate the new angles?
Assume said object is an aircraft. I store three angles (in degrees) that describe where it's headed: yaw, pitch and roll - in that order. Let's say the plane is flying vertically, upwards. The angles would then be: `(0, 90, 0)`. Then, I command the plane to turn left; this results in the following angles: `(0, 0, 90)`.

1. Given the plane's current angles and a command (turn left, right, up, or down), how can I calculate its new angles?
2. Would it be easier if I were using a directional vector and an extra "up" vector (i.e., the normal of the surface that cuts the plane in half, horizontally)?

# Answer
Don't use Euler angles for that, you'll get in trouble with a Gimbal lock in some situation and you'll be clueless about what the angles will be doing.

I would suggest you use a space for your object, i.e. the option 2 you suggest. To make a space you need 3 vectors: the front vector, which represent the front of your model and the heading, and the side, which is arbitrarily left or right (be consistent across all of your system), in the case of a plane, it would represent one of the wings. From these 2 you can infer the 3rd vector with a cross product.

The vectors represent the local space of the plane in world space.

* When you modify the yaw, you rotate the front and the side vectors w.r.t. the up vector.
* When you modify the pitch, you rotate the front and the up vectors w.r.t. the side vector.
* When you modify the roll, you rotate the side and the up vectors w.r.t. the front vector.

The cup-and-saucers in the following image each have their *local space*, just to give you an idea, and the 'central' gizmo shows you the *global space*:

(Image source)
> 2 votes

# Answer
Don't use Euler angles for that, you'll get in trouble with a Gimbal lock in some situation and you'll be clueless about what the angles will be doing.

Instead, use Quaternions to both represent your current rotation and any changes to it.

Quaternions are often used to describe a rotation in 3d space by encoding:

1. a rotation axis (in form of a 3-dimensional vector ê)
2. how far to turn around that axis (in form of an angle θ)

By picking the rotation axis relative to the current heading of your object, you can get meaningful turning behavior from any existing rotation.

Quaternion math is quite complex, so I would recommend you to use a library for this.
> 2 votes

---
Tags: 3d, mathematics, vector, angles
---


# Question
Title: Increasing chance of good loot after multiple tries
I'm looking for a way to make chances of getting better loot increase the more you've looted. I do not want it to be possible to get a **rare** item the first 5 times and not being able to get an **epic** item the first 10 times.

However, the more the player loots, the better chance he should have of getting better items/less chance of getting **nothing**, **normal**, ...

This is my current code, but it is, as you can see, completely static. I know this might not be of much help, but at least it shows an overview of the items and the %-chance I have in mind.

```
var rand = random(100); // Random number 0-100
if(rand < 40){
    return LOOT_NOTHING;
}else if(rand < 70){
    return LOOT_NORMAL;
}else if(rand < 90){
    return LOOT_UNCOMMON;
}else if(rand < 99){
    return LOOT_RARE;
}else{
    return LOOT_EPIC;
}

```

*The project is written in GML, but pretty much any language will suffice as an answer as it's not very language-specific.*

# Answer
It might be easier to choose items like ten by ten, then 'shuffle' the bag of items so they appear in random order.

expl :

10 first items : 4 null, 6 normal.
10 next : 4 null, 5 normal, 1 uncommon.
10 next : 4 null, 4 normal, 1 uncommon, 1 rare.
10 next : 4 null, 3 normal, 2 uncommon, 1 rare.
10 next : 3 null, 2 normal, 2 uncommon, 2 rare, 1 epic.
then you keep this last balance.

Store those coef in a convenient array so you can fine-tune the balance at any time.

Rq : If when testing it doesn't feel random enough, you can easily make it more random by storing item probability, not item count :

10 first items : 40% null, 60% normal.
10 next : 40% null, 50% normal, 10% uncommon.
...

you roll the dice when building the bag, then shuffle it afterwise. Only issue here is that, for instance after 40 items in the previous example, you might get several epic items or none...

Edit : Despite the increased complexity, i would add, for the second solution, a cap/max, so that, for instance, you don't get several epic item in a row.
The description becomes :

10 first items : 40% null, 60% normal. max 6 normal.
10 next : 40% null, 50% normal, 10% uncommon. max 1 uncommon.
10 next : 4 null, 4 normal, 1 uncommon, 1 rare. max 1 uncommon, 1 rare.
...

You might represent the data as (Javascript notation) (where -1 means no max) :

```
var lootCoeff = [
                  [ [ /* prob */ 0.4, 0.5, 0.1], [ /* max */ -1, 5, 1 ] ],
                  [ [ /* prob */ 0.4, 0.4, 0.1, 0.1], [ /* max */ -1, 5, 1, 1 ] ],
...
                    ]

```
> 4 votes

# Answer
Assume you have a list named "Rewards", which holds the "rare", "epic" etc. values. Also assume you have an integer that holds how many times user rolled.

On each roll you pick a random item from the list, and give it to player.

At certain tresholds -say, each 10 rolls- you add more "epic" items to the list.

So as user rolls, the chances he gets an "epic" item increases.
> 1 votes

# Answer
You could go for a rolling scale, give each item a minimum roll of X and each time you roll for an item roll = (random) + Y, where Y is your bonus (increasing a certain amount with each roll. Then pick the highest threshold made by your roll.

say your rng (in range 1-20) produces 12 and you have had 5 rolls so far your roll-result is 17. your threshold for normal items is 15 and your threshold for rare items is 25. so you get a normal item. next roll y increases to 6 so you'll hit a rare item on a roll of 19 or higher.

The scale and ranges can be adjusted to your preference
> 1 votes

---
Tags: mathematics, algorithm, random
---


# Question
Title: How can I make an actor fire a bullet on touch?
I created a `Jet` and a `Bullet`, and when `Jet` is touched, the `Bullet` is fired.

Now I want to know how can I make the `Jet` fire again when touched after it has fired the first shot?

```
public class MyGdxGame implements ApplicationListener{

    private Texture bulletTexture;
    private Texture jetTexture;
    private Stage stage;
    private JetActor jetActor;
    private BulletActor bulletActor;

    int counter=0;
    float jetX = 700,jetY = 150;
    float bulletX = jetX-10, bulletY = jetY +43;
    boolean started;

    public class JetActor extends Actor{

        public JetActor() {
            setBounds(jetX, jetY, jetTexture.getWidth(), jetTexture.getHeight());
            this.addListener(new InputListener(){
                public boolean touchDown(InputEvent event, float x, float y, int pointer, int buttons){
                    stage.addActor(bulletActor);
                    System.out.println(counter);
                    counter++;
                    started = true;
                    return true;
                }
            });

        }

        @Override
        public void draw(Batch batch, float parentAlpha) {
            batch.draw(jetTexture, jetX, jetY, jetTexture.getWidth(), jetTexture.getHeight());
        }
    }

    public class BulletActor extends Actor{
        @Override
        public void act(float delta) {
        }

        @Override
        public void draw(Batch batch, float parentAlpha) {
            batch.draw(bulletTexture,bulletX,bulletY,bulletTexture.getWidth(), bulletTexture.getHeight());
        }
    }

    @Override
    public void create() {
        bulletTexture = new Texture("C:\\Users\\User\\Documents\\LibGdxMainProjects\\SampleGame1\\android\\assets\\bullet.png");
        jetTexture = new Texture("C:\\Users\\User\\Documents\\LibGdxMainProjects\\SampleGame1\\android\\assets\\jet.png");
        stage = new Stage();
        jetActor = new JetActor();
        bulletActor = new BulletActor();
        stage.addActor(jetActor);
        Gdx.input.setInputProcessor(stage);
    }

    @Override
    public void dispose() {
    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        if(started){
            bulletX -=5;
        }
        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }

    @Override
    public void resize ( int width, int height){
    }

    @Override
    public void pause () {
    }

    @Override
    public void resume () {

    }
}

```

# Answer
> 1 votes
Right now you declare a `BulletActor` as a member of this game class, and whenever you get a touch input you call `addActor`, giving it that bullet. All this does is add *the same* bullet over and over. I'm not super familiar with the details of the APIs you are using, but I suspect that's basically a no-op.

What you want to do instead is create a *new* bullet every time you get a touch event:

```
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int buttons){
                BulletActor newBullet = new BulletActor;

                // Configure the new bullet; you may need to assign position
                // and velocity here, or in the bullet constructor.
                // You also may need to assign other properties appropriate
                // to your game.
                newBullet.x = x;
                newBullet.y = y;
                // ...etc...

                stage.addActor(newBullet);
                System.out.println(counter);
                counter++;
                started = true;
                return true;
            }

```

Create the new bullet, set it's initial properties so it's located where you touched or where the `JetActor` is or whatever else you need, and add *that* actor to the scene. You probably won't need to the `bulletActor` member of the game class any more.

However if you do want to be able to modify properties of the bullets after creation, or if you need to retain references to them in order to be able to correct deallocate them later, you may want to create a dynamic array (`ArrayList`) of bullets and store each newly-created bullet in there for later reference.

---
Tags: java, libgdx
---


# Question
Title: How can I avoid referring directly to the state type when transition to new states in a state machine?
I finally found a good way to implement a "stack-of-states" to manage what screen I am on. Minimal example:

```
    class gameEngine {
public:
    //Removes state at the "back" of the stack and puts the new state at the "back" of the stack
    void ChangeState(std::shared_ptr<gameState> state);

    //Adds new state to top of stack
    void PushState(std::shared_ptr<gameState> state);

    //Removes back state from stack
    void PopState();

private:
    // The stack of states
    std::vector<gameState*> stateStack;
};

```

Now how I call the (for example) PushState command from inside a state itself (using tGUI library), where "stateGame" and "stateMainMenu" are game states:

```
void stateMainMenu::Init(gameEngine* game) {

    //Creates a new button
    tgui::Button::Ptr buttonStart = std::make_shared<tgui::Button>();

    //Connects the PushState function to this button. When clicked the engine will run the
    //PushState function with the arguments 'game' and a pointer to a new StateGame.
    buttonStart->connect("clicked", &gameEngine::PushState, game, std::make_shared<stateGame>());
}

```

This works, and I can transition between screens easily. However, I had a strange feeling that I shouldn't allow gameStates to know about the internals of other game states (I am including the header file for each gameState into each cpp file where I will need to transition to that state). Is it better to re-write the ChangeState and PushState functions to take an enum which refers to each game state, and then generate the shared pointers inside those functions? I'm really scratching my head, it probably makes no difference at all but I want to know what the better practice would be.

If anyone can make any sense of my rambling and put it to rest I would be extremely grateful.

Here is the full source for anyone interested, or who wants more context.

# Answer
You can't really avoid the problem of source state knowing *something* about the target state -- at the bare minimum the source state must know some unique identifier or name related to the target state to indicate *which* target state to go to.

In that regard an enumeration isn't really any different than a type name, and in fact might be worse from a maintenance perspective. With such an enumeration, creating a new kind of state involves

* writing the state's class
* adding an entry to the enumeration
* adding an entry *somewhere* that establishes the mapping between enumeration value and state type

So you've moved the "problem" of knowing the state's type from one place (the source state code) to some other place (some random spot where you have to write the enumeration-to-type mapping), *and* you've significantly increased the parts of code you have to touch to add a new state type into the mix. Compare to your current approach, which really requires only

* writing the state's class

I'd say your *current approach* is the better one. Additionally remember that exposing the *name* of the type is not the same as exposing it's "internals." The name of a type is part of its public interface.

Further, the enumeration approach basically requires that you include all possible state types in your code. That is, if you turn your code into a library at some point, you can't easily have users of that library create new state types because C++ enumerations aren't extensible. So you'll have to jump through more hoops to create a sort of ID registration system for states.
> 0 votes

---
Tags: sfml, c++
---


title: How do I "teleport" an object in Unity?

text:
# Question
Title: How do I "teleport" an object in Unity?
I'm trying to make a script where once a player triggers a collision they are teleported to another position that is determined by a empty game object. I think it has to do something with the transform function but I haven't been able to figure it out.

There isn't a good example of this type of behavior in c#. Most examples are written in java and that confuses me even more lol.

Here's what I got so far that works

```
using UnityEngine;
using System.Collections;

public class  colision: MonoBehaviour {
    public Object WarpExit;
    void OnTriggerEnter(Collider other)
    {Debug.Log("ENTERED WARP ZONE");}

    void OnTriggerStay(Collider other)
    {
        Debug.Log("IN WARP ZONE");
        //Warp player

    }
    void OnTriggerExit(Collider other)
    {Debug.Log("EXITED WARP ZONE");}
}

```

# Answer
You need to reference the exit object, and update your player position to the position of the object.

To reference the exit object, you can either define it in the Inspector after declaring a public property:

```
//Change public Object WarpExit; to:
public GameObject WarpExit;

```

This will then show up in the Inspector as a field where you can select the exit object. This is the most ideal solution if your exit is static and predefined.

Or, you can find the exit object in your script start up, with a tag, object name or if has some kind of "exit script":

```
public void Start() {
    //Choose one method

    //With a tag
    //Requires you to add a tag to your exit object, you can add a tag in the Inspector
    WarpExit = GameObject.FindWithTag("WarpExit");

    //or by name
    //Requires you to name your object 'WarpExit', you can change the name in the Inspector
    WarpExit = GameObject.Find("WarpExit");

    //or a component (script)
    //Requires you to create a new script with a class name of 'WarpExitScript' and attaching it to your exit object
    WarpExit = GameObject.FindObjectOfType<WarpExitScript>().gameObject;
}

```

Once you have your exit object defined, you know it's location, and can use that when "teleporting" your player:

```
void OnTriggerStay(Collider other)
{
    Debug.Log("IN WARP ZONE");
    other.gameObject.transform.position = WarpExit.transform.position;
}

```

As an aside, I'd suggest renaming your script to something like `WarpEntrance` instead of `colision`, as it's a good idea to name your classes based on their functionality.
> 3 votes

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


# Question
Title: How to make a triangle move and rotate using GDI in C++
I want to make a triangle move from one place to another then rotate it 270 degrees using Polygon() function does anyone knows how to?? Just a simple one.

# Answer
> 2 votes
`Polygon` takes an array of points that define the polygon; in your case this would be three points that define a triangle:

```
POINT triangle[] { {x0, y0}, {x1, y1}, {x2, y2} };

```

Define your triangle relative to some origin point that makes sense for you. For example, a triangle with the origin (roughly) in the center:

```
POINT triangle[] { {-10, -10}, {10, -10}, {0, 15} };

```

To draw this triangle at any given `x, y` point, add `x` and `y` to the appropriate component of each point:

```
POINT triangle[] { {x + -10, y - 10}, {x + 10, y - 10}, {x, y + 15} };

```

And then pass that set of points to `Polygon`. A simple function to do all of this would look like:

void DrawTriangle (HDC dc, int x, int y) { POINT triangle\[\] { {x + -10, y - 10}, {x + 10, y - 10}, {x, y + 15} }; Polygon(dc, triangle, 3); }

Then, pick a starting point given by some `x, y`, and an ending point given by some other `x', y'`. Every frame add some value to each `x` and `y` (probably scaled by delta time in order to have framerate-independent movement) to move it towards the target point, and call `DrawTriangle` with that new x and y.

---
Tags: c++, windows
---


# Question
Title: Allowing a unit to equip only certain types of weapons
I'm making a FireEmblem style game, and I am working on items at the moment. I have a Weapon class from which Sword, Axe, etc. are derived. I also have character classes like Swordsman, Mage, etc. I would like to have a way to allow classes to only equip certain weapons (Swordsman can equip Sword but not Axe). One way I thought of was to have a global enum for WeaponType, and each weapon has a const weapon\_type value. Then, each character class has a list of allowed WeaponTypes and you would check if a weapon's weapon\_type is in the allowed list.

Is there a better way to implement this without using any casting?

# Answer
`Sword`, `Axe`, et cetera as subclasses of `Weapon` sound like inheritance abuse to me. Fundamentally these types of weapon differ only in *data* (how much damage they do, what type of damage it is, what sprites or animations or effects are associated with the weapon, and so on). Consequently I'd advocate for an approach where you flatten this hierarchy away, leaving just the `Weapon` class.

This provides more impetus for your suggested approach of giving weapons a `type` flag and giving classes a set of types they can legally equip. If you implement this type flag as an enumeration organized like a bitfield

```
enum WeaponType {
  None = 0,
  Dagger = 1,
  Sword = 2,
  Axe = 4,
  Spear = 8,
  Bow = 16,
  Boomerang = 32,
  Gun = 64,
};

```

then you can give the `CharacterClass` type a field called, for example, `equippableWeaponMask`. This can be a bitwise combination of the weapon type flags that are valid for the class to wear:

```
CharacterClass warrior;
warrior.equippableWeaponMask = Dagger | Sword | Axe | Spear;

CharacterClass mage;
mage.equippableWeaponMask = Dagger | Gun;

CharacterClass hunter;
hunter.equippableWeaponMask = Spear | Bow | Gun;

```

Then, the query to see if a character class can equip a certain weapon is:

```
bool CharacterClass::canEquip (const Weapon & weapon) {
  return (weapon.type & equippableWeaponMask) != 0;
}

```

Note that this also suggests you don't need distinct subclasses for `CharacterClass` either, but can also represent their capabilities purely in data.
> 5 votes

---
Tags: c++, architecture
---


# Question
Title: Why are my brushes see-through in Hammer/CS:GO?
I'm making a map for Counter Strike: Global Offensive, but I am having this issue with a part of the map. One of my brushes is weird and see-through in game.
I have no clue what is causing it or how I can fix it. Does anyone know what's going on, and how I could fix it?

# Answer
I think it's because those are 'dentils' (an architecture element. As such, they are spaced apart. They're supposed to go under a ledge. Google images of dentils. Oh, also, look at the file name and see if THAT is named 'dentil'. That'll tell you.

As a workaround I'd put a background behind it.
> 1 votes

---
Tags: steam, valve, binary-space-partitioning, source-engine, hammer
---


title: source development kit tutorials

text:
# Question
Title: source development kit tutorials
I'm looking to create a demo using the source development kit.
Because i want it to have a similar style to portal, but one I'm wondering can i get the portal 2 authoring tools without owning the game,
and two I'm finding it very difficult to find any form of tutorials for it, could anyone link me to some preferably PDF format or eBook i rather read them.

# Answer
You need to own at least 1 Source game before you are given access to the Source editing tools. I'm not quite sure what kind of demo you plan to make, or if that demo will require code changes or not, but I believe the Source SDK only provides you with Half-Life 2 mod tools, not Portal 2. You may be able to find more information on their website here: https://developer.valvesoftware.com/wiki/Main\_Page

You can however make very sophisticated maps using Valve's map editor called Hammer. And again, you will need to own any game you want to design maps for (otherwise how did yo plan to test them?). There are plenty of Hammer tutorials out there, although here is Valve's official level design page for Portal 2: https://developer.valvesoftware.com/wiki/Category:Portal\_2\_Level\_Design
> 3 votes

# Answer
1. YouTube's got some good videos for beginners. 'World of Level Design' has some good ones on YouTube and on his own site. Type in 'SourceSDK' in YouTube's search bar and they'll pop up. There's about 4 guys that have videos up on map making in SourceSDK/Hammer.
2. You need to buy the game to run the maps, but you don't need to buy the game to use the authoring tools. That being said, just buy the game.
3. There's a Half-Life book-book, there's a downloadable Source Book (both on Amazon).

I recommend buying Left4Dead2 from Steam's website as it comes with SourceSDK/Hammer and you can watch those videos on YouTube. It's not too hard to understand and get halfway decent at pretty quickly (1 day a week for 2 months and you'll be making some pretty spiffly looking maps). You'll eventually get to the intermediate level and that's where there's problems, cuz for the life of me I cannot find a good source on how to transition from one map to the next and upload that to Steam so everyone can play your maps.
> 0 votes

---
Tags: source-engine
---


title: Inconsistent AABB collision detection

text:
# Question
Title: Inconsistent AABB collision detection
I'm making an endless jumper as my first game and I'm running into some problems with the one-way collision detection.

Collisions are detected correctly most of the time but occasionally the player inexplicably falls through the platform.

I suspect that it is ghosting through the platforms but I can't see why and I'm too close to it to be able to identify the source of the problem.

My code:

This loop is located within the update method of the global platforms object. this.\_platforms refers to the array of Platform objects.

```
 for (i = 0, len = this._platforms.length; i < len; i++) {
            var p = this._platforms[i];

            p.proximity = Math.abs(p.x / 2 - player.x / 2) + Math.abs(p.y / 2 - player.y / 2);

            if (p.closest()) {
                if (p.collision()) {
                    player.onplatform = true;
                    player.y = p.y - player_s_right.height;
                } else {
                    player.onplatform = false;
                }
            }
 ...
}

```

It loops through the platform objects, running a collision test only if the platform is the closest one to the player.

Here are the closest() and collision() checks respectively:

```
// Return whether current platform is the closest to the player
Platform.prototype.closest = function() {

    var minprox = Math.min.apply(Math, platforms._platforms.map(function (obj) {
        return obj.proximity;
    }));

    return this.proximity === minprox;
}

// Collision detection
Platform.prototype.collision = function() {

    var px = player.direction > 0 ? player.x + 15 : player.x,
        px2 = player.direction > 0 ? player.x + player_s_right.width : player.x + player_s_right.width - 15,
        py = player.y + player_s_left.height,
        py2 = player.y + player_s_right.height + player.yvelocity,

        platx2 = this.x + platform_s.width,
        platy2 = this.y + platform_s.height;

    if (((px > this.x && px < platx2) || (px2 > this.x && px2 < platx2)) && (py2 >= this.y && py2 <= platy2) && py <= this.y) {
        return true;
    }
};

```

If anyone can shed some light on this I'd really appreciate it.

# Answer
It seems your proximity algorithm only checks proximity of the top-left (?) corner of the platform. For example if we have scenario like:

```
       P
   AAAAAABBBBB

```

where we have player P and platforms A and B. Here closest() would return B as the closest platform and then B.collision() would return false.
> 0 votes

# Answer
Your proximity calculation wasn't working correctly when two platforms were right next to one another. I'm not sure what type of proximity calculation you are trying to use, but I think using the distance between two points would give a more correct result. Changing the proximity to use that seems to make it work.

```
var px = player.direction > 0 ? player.x + 15 : player.x,
    pwidth = player_s_right.width - 15;
    a = (px + pwidth / 2) - (p.x + platform_s.width / 2);
    b = (player.y + player.sprite.height / 2) - (p.y + platform_s.height / 2)

p.proximity = Math.sqrt( a*a + b*b );

```
> 0 votes

---
Tags: 2d, collision-detection, javascript, aabb
---


# Question
Title: My Sprite class generates a EXC_BAD_ACCESS error, and is sometimes NULL? Rect has weird values?
So, lets start off with the weird `Sprite*` object sometimes being `NULL`.

I run my game, the `EXC_BAD_ACCESS` error comes and sometimes, only sometimes my `Sprite*` has a value when it crashes.

Sometimes it has a memory address and other times it is just `NULL`.

Though, even when it has a memory address the game generates the same error.

Here's how I define my Sprite class :

```
std::map<std::string, Sprite*> sprites;

```

I use this function to create a new sprite :

```
void Graphics::CreateSprite(std::string ID, std::string textureID, int x, int y, int width, int height)
{
    std::cout << imagePaths["Square"] << std::endl;
    sprites.insert(std::make_pair(ID, new Sprite(imagePaths[textureID], x, y, width, height, windowRenderer)));
}

```

And I call it like this :

```
graphicsManager->CreateSprite("Test", "Square", 32, 32, 100, 50);

```

And if I `std::cout` the sprite using this `GetSprite` function ( to get the memory address, so I can check if it's NULL) :

```
Sprite* Graphics::GetSprite(std::string spriteID)
{
    std::map<std::string,Sprite*>::iterator it;
    it = sprites.find("Square");
    return it->second;
}

```

Calling it like this :

```
std::cout << graphicsManager->GetSprite("Test") << std::end;

```

I get the output of a memory address so the Sprite is not `NULL`.

---

Now, to the weird values in my `SDL_Rect`.

The SDL\_Rec is defined like this :

```
SDL_Rect m_rect;

```

Initialised like this : (in the constructor of the Sprite class)

```
m_rect.x = x;
m_rect.y = y;

if (width == 0)
{
    m_rect.w = textureSurface->w;
}
else {
    m_rect.w = width;
}

if (height == 0)
{
    m_rect.h = textureSurface->h;
}
else {
    m_rect.h = height;
}

```

The parameters being :

```
Sprite::Sprite(std::string imgPath, int x, int y, int width, int height, SDL_Renderer* windowRenderer)

```

Which is called when you create the sprite using the function I posted above.

The values in this case should be :

> x axis : 32
>
> y axis : 32
>
> width : 100
>
> height : 50

However, when I check the values they are :

> x axis : -1869611001
>
> y axis : -1869574000
>
> width : -443987883
>
> height : 1889462621

They are like this before the game crashes as well.

---

And now onto the actual crash of my game :

The error looks like this :

> Thread 1: EXC\_BAD\_ACCESS (code=1 address=0x7)

And the error is created on this line when I try to give my `m_rect` (`SDL_Rect`) a value :

```
void Sprite::Move(int offsetX, int offsetY)
{
    m_rect.x += offsetX;  <--- error here!
    m_rect.y += offsetY;
}

```

And the Move function is called like this :

```
graphicsManager->GetSprite("Test")->Move(1, 1);

```

Right after I create the Sprite using the CreateSprite function.

---

**Edit 1**

I played around with the diagnostics tools on the scheme thing, checked malloc, NSZombies objects and such, however none of them worked so I disabled all of them and tried again.

Suddenly my application didn't crash???

However when I tried running it right after, it once again crashed?

I'm so confused...

---

**Edit 2**

So, the next day everything started working again with no modifications to the code.

Now I'm even more confused. lol

# Answer
There is a code smell here:

```
Sprite* Graphics::GetSprite(std::string spriteID)
{
    std::map<std::string,Sprite*>::iterator it;
    it = sprites.find("Square");
    return it->second;
}

```

By not making sure that the object is valid, the `it` could be `sprites.end()`. According to some documentation, it's very dangerous to dereference the `end()` iterator. You **can't** be sure that the `->second` part will be `nullptr` (in fact, you can be sure that it will **not** be `nullptr`; it will be garbage, that's c++).

Also, you're not using the parameter you pass to the function:

To fix this, modify your code:

```
Sprite* Graphics::GetSprite(std::string spriteID)
{
    std::map<std::string,Sprite*>::iterator it;
    it = sprites.find(spriteID);
    if( it != sprites.end() )
      return it->second;

    return nullptr;
}

```
> 4 votes

---
Tags: sdl2, c++
---


# Question
Title: calculating the weights for direction vectors to a target
I have an entity that is allowed to move in a fixed amount of directions. Let's call *a* the angle between two directions. *r* is the length of each direction vector. Now the entity wants to head from its current position *(x1,y1)* to a target *(x2,y2)* in one of the fixed directions. Instead of getting the direction that the entity should head into, I want to get a weight for all directions that is based on how close the entity gets to the target with that direction, so that I can combine those weights with other things like avoiding some direction for example.

I thought about calculating the distance from the new positions to the target and then use the closest distance (the one in which the entity heads in the direction directly to the target) to get a weighting from 1 to zero for the other directions.

Now I was wondering if there is some other way to get the weights without having to calculate the distance for each direction. Maybe there is some sort of relation between the angle from the ideal direction and the distance that could be used to calculate the weights instead? So far I've figured out that at least there is no no linear relation between the angle and the distance.

Here is an image to hopefully clear things up a bit:

# Answer
> 1 votes
What you want is the dot-product between each direction vector and the vector to the target. This value will be maximised by the direction which will take you closest to the target.

If you are not familiar with the dot product:

```
u . v = sum(u_i * v_i)

```

where the sum is over the components of the vectors.

Edit: Please do ensure that the vectors are normalised (i.e. have magnitude = 1) before conducting the dot product. You can normalise a vactor by dividing by its magnitude.

# Answer
> 0 votes
The distance between the centre of the circle `(x1,y1)` and the target `(x2,y2)` is:

```
D = sqrt((x1-x2)² + (y1-y2)²)

```

So the distance between the target and any point on the circle varies between `D - r` and `D + r`.

For a given angle `a` with the horizontal axis, the position of a point on the circle is:

```
x = x1 + r·cos(a)
y = y1 + r·sin(a)

```

And so the distance between `(x,y)` and `(x2,y2)` is:

```
d = sqrt((x1 + r·cos(a) - x2)² + (y1 + r·sin(a) - y2)²)

```

All these values can be combined together to compute a weight that only depends on the value of `a` and goes from 0 (worst choice for `a`) to 1 (best choice for `a`):

```
W = (D + r - d) / 2r

```

I hope this can be helpful.

---
Tags: mathematics, steering-behaviors
---


# Question
Title: How to start encouraging team collaboration?
I am working on converting a single player game to multiplayer, but I am concerned that if I simply do a 1-1 conversion, even in modes with "multiple players" there won't be any incentive for team work. And since I have more experience with single player mechanics than multiplayer ones, I could use some advice on this. Here is what I have implemented so far:

* points that reward team based achievements higher than single player achievements eg. single kill vs team kill
* a "spotting" mechanic which allows players to show their team the enemy's position on the minimap
* health & ammo items which can be shared to resupply the team
* team based game modes such as capture the flag, TDM etc

My main concern with the above, is that there is a heavy reliance on individual players to ***want*** to play in a team based way. If they don't want to, they can still lone wolf it in most cases which can have a negative effect on the rest of the team who is trying to play collaboratively. It only takes one person in a team to spoil the fun!

For example, the COD series has had a number of perks, achievements and streaks designed to encourage team collaboration; but I have rarely seen these used in multiplayer since a lone wolf strategy seems to be more common. Another example, the Battlefield series has had an entire class devoted to supporting team members with health packs, repairs, ammo resupplies etc and in multiplayer it is common to see this being used to fully effect. So why do such features/mechanics work in one game of the same genre but not in another? I assume the type of player is relevant here, but there must be more to it than that.

What are some tried and true ways to encourage team-based play or collaboration? This does not necessarily mean players talking to each other, but rather working together to achieve the same goal or different parts of the same goal.

# Answer
> 1 votes
I am assuming that you are talking in terms of a first-person shooter game.

In this case, I have a suggestion that may be a little bold: Show the player's teammates his/her location and orientation.

In a first person-shooter game, when someone encounters an enemy, they try to move into places that are covered from that enemy, an most certainly will be looking in the direction of the discovered enemy. This means that they are also vulnerable to attack from other direction.

A two person team can easily ambush on lone players by having one person distract the target and the other sneak from behind the target. This is partially demonstrated in Counter Strike. Counter Strike in particular is a game whose objective depends on success as a team, this may not work well in all games and should not be forced onto a game that excels in some other way. By showing teamed people the position and orientation of their allies, players can easily execute ambush or attack by circling their enemy, and if damage or action of the teammates is displayed, players can also acquire more information about the battle.

If your game do not feature multiple opposing parties, (for example, your game is about fighting a bunch of AI-controlled enemies), then one way to encourage team play as said above is to make your AI resemble human player in that they get distracted or knows how to take cover from one direction. Otherwise, you can set in time-based objectives such as set-pieces that must be triggered in quick successions in order to obtain a reward. This mean single player needs to run from one location to the next while multiple players can just split-up for a while.

Also, you can feature a limited inventory space that can be expended by having multiple players.

---
Tags: game-design, game-mechanics, teamwork
---


# Question
Title: Unity sidescroller with 3D objects/environment. Should I create a 2D or 3D project?
I'm looking to make a side-scroller in which the camera and all objects can only move in the x and y directions. However, I'm going to have all objects and environments as actual 3D models.

Is it better to create a 2D project and just use 3D models, or should I create a 3D project and mess with the scripts to only allow x/y movement of objects and the camera?

Or does it not really matter?

# Answer
> 3 votes
You should create your project in 3D, although it's only a minor convenience.

The two modes don't change any aspects of what your game can do or the fundamental workflow, they just configure certain defaults you can easily change as needed.

In 2D mode, images are imported as UI/Sprites by default, but if you're using 3D objects you'll typically want them imported as Textures instead, so having that as the default will save you a little settings fiddling.

The other difference is a 2D project will default to a 2D scene viewport, but you'll probably be switching this back and forth with the button on the scene window fairly frequently no matter which default you choose.

The directions of movement are determined by the script components you attach (like Rigidbody or Rigidbody2D) and you can access both 2D & 3D movement scripts no matter how you initially configured your project. Just be cautious you don't inadvertently mix them, as the 2D & 3D physics don't interact with one another.

---
Tags: 2d, 3d, unity, side-scroller
---


# Question
Title: Require maths help calculating deflection angles of quadrants
For each quadrant, I need to find a neat way of calculating the deflection angle for a small circular object striking a circle, as shown in the diagram.

* Angles a and b are already known.
* Angle a is always relative to 0 degrees position.
* Angle b is relative to the quadrant.
* The initial angle can also be greater than 180, when coming from the other direction, as shown in the diagram the right.

For quadrant 2, in the following snippet from my code, dy and dx represent the x and y coordinates of a point on the circle:

```
intersectAngle = atan(dy/dx);

```

Initial angle is calculated from velocity vectors:

```
pAngle = PI - (atan2(pVel.x, pVel.y));

```

For quadrant 0, I came up with this for the rebound angle:

```
pAngle = pAngle - 2 *(pAngle - tangentAngle);

```

Where tangentAngel is just the intersect angle with half PI added. Thsi worked for a ball from any direction.

Moving onto quadrant 1, this works for pAngles of less than 90 deg, but not for pAngles from the other direction:

```
pAngle = pAngle + 0.5 * PI - intersectAngle;

```

Feels like I shouldn't be writing all this code and that there is a more efficient way. I realise this is an elementary question but I'm studying this so it's all new to me. Please be gentle.

# Answer
> 0 votes
It seems like you are just reflecting the vector and it would be easier to do so, as such, than manually fiddle with quadrant math. I think you have access to vectors but, if it's a project constraint, I can modify this to use only basic scientific calculator functions. `V1` relates to angle `a` and `V2` relates to angle `b`. All vectors should be normalized.

This works for any vector, in any quadrant:

1. I believe `V1` is `pVel`, normalized.
2. I believe `V2` is `{dx, dy}`, normalized.
3. `V3.Dot(V2) == -V1.Dot(V2)`
4. The angle between `V3` and `V2` is `acos(-V1.Dot(V2))`
5. The angle between `V3` and '0' is `acos(-V1.Dot(V2)) + b`
6. Post-collision velocity is `V3` * the original magnitude of `V1`

This could happen if you detect the wrong collision first (very little implementation detail included):

Leave a comment if you need help with it.

---
Tags: trigonometry
---


# Question
Title: What causes SFML pollEvent to segfault here?
I'm writing an SFML application in C. Currently `sfRenderWindow_pollEvent()` and `sfRenderWindow_waitEvent()` always segfault.

Here's the cleaned code that shows the issue.

```
sfRenderWindow* window;
sfVideoMode mode = {SCREEN_WIDTH, SCREEN_HEIGHT, 32};
window = sfRenderWindow_create(mode, "SFML window", sfResize | sfClose, NULL);

sfEvent* InputEvent;

while(1)
{
    while (sfRenderWindow_pollEvent(window, InputEvent) == sfTrue)
    {
        ...
    }
}

```

# Answer
> 1 votes
You forgot to initialize your `InputEvent` pointer. Currently you only declare the pointer with `sfEvent* InputEvent;`, so there is actually no memory allocated for the event.

You need to either change the line to `sfEvent InputEvent;` and change the while-loop to `while (sfRenderWindow_pollEvent(window, &InputEvent) == sfTrue)`, or you can manually allocate space for the event by calling `InputEvent = malloc(sizeof(sfEvent));`

---
Tags: sfml, c
---


# Question
Title: What technique should I use to implement the following type of "diggable" terrain?
I'm trying to replicate a certain game mechanic from the game Diggles. This game takes place in a vertical cross-section of the earth and allows the player to dig tunnels and caves into the environment. You can see this bevhaviour in action in the following Let's Play on Youtube.

https://www.youtube.com/watch?v=3lIN37JyNTU&t=7m40s

My question is: How can I implement such a modifiable terrain?

My first idea would be to keep a copy of the vertex and index buffer in memory, modify it accordingly and send it to the gpu each time it is modified. However, this seems very inefficient considering the size of the map and how often it would need to be updated.

# Answer
**Data / Model vs. View / Rendering**

First let's clear up one thing: data model vs. view, in the sense described by MVC.

One moment you're talking about one:

> How can I implement such a modifiable terrain?

And the next youre talking about the other:

> ...keep a copy of the vertex and index buffer in memory, modify it...

...You've also tagged your question with both these concepts: `game-mechanics` and `graphics-programming`. You should keep them discrete from one another. Implementing the state system on which terrain destruction occurs is *completely separate* from rendering the current state of the terrain. Remember that data is singular, but that data can be represented in many different ways via multiple views, so you should never conflate rendering with state. e.g. In games, we can represent the world state via first person view *and* minimap view - two renderings relying on one set of data.

**Data / Model**

So in the first place - for a 2D game like this, the data model is a 2D array (say of bytes/chars) in which a given location is modified to 0 (air) when the player destroys a tile / chunk of earth at that location. The other 255 values that the byte/char supports is used to identify different tile sprites. This is just a suggestion; you can use many data structures to represent the terrain data model.

**View / Rendering**

Yes, if you want it to be pseudo-3D like that game, then you'll need to modify vertex / index buffers. It is not particularly inefficient given the infrequency with which you do it. Also, you can use things like `glBufferSubData` or buffer orphaning to ensure you make the process as efficient as possible.

If you don't need it to be pseudo-3D, and can settle for plain 2D, then I'd settle for just modifying a screen-sized texture with the changed tiles.
> 4 votes

---
Tags: game-mechanics, models, geometry, graphics-programming, 3d-meshes
---


title: Unable to move GameObject?

text:
# Question
Title: Unable to move GameObject?
This simulates a GameObject swinging between two positions.

I am unable to manually move a GameObject on the Y axis using the Unity editor (in scene view) when the following script is attached and running, it's like a solid animation:

```
Vector3 min, max;

void Update()
{
    min = wall1.position + new Vector3(4,0,0);
    max = wall2.position - new Vector3(4,0,0);

    transform.position = Vector3.Lerp (min, max, (Mathf.Sin(2 * Time.time) + 1.0f) / 2.0f);
}

```

# Answer
When you assign a `Vector3` to `transform.position`, you assign all three axises. To assign only X axis, you need to do this:

```
var oldPos = transform.position;
var newPos = new Vector3(__newXValue__, oldPos.y, oldPos.z);
transform.position = newPos;

```

Change `__newXValue__` with what you want, and this code will only change x axis and other axises will not get effected by this code.

**Note:** Do not split these lines to different methods that will run on different frames, the integrity must remain intact. The reason for this is, if transform gets updated from any other source in between you get the old position and assign new position, your GameObject will teleport.
> 2 votes

# Answer
When your game is running, the Update() function update the GameObject's position every frame so you can't move it (actually you can move it but the update position it so fast that the move do not work).

You can try this: make this GameObject another GameObject's child in hierachy, and move the parent GameObject, it will work the way you want it.
> 1 votes

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