title: Modify a script at runtime

text:
# Question
Title: Modify a script at runtime
I am about to make a programming game for children, hence I will use blocks (like Scratch or Stencyl). My question is: Is there a way that you can modify a script (let's say, by adding a string attached to a code block)?

Also, could there by a way to delete just some text for that script (for when I want to "reset" the script to its default state)?

# Answer
> 3 votes
Unity compiles all its scripts to bytecode at build time. While there may be relatively exotic ways to JIT arbitrary source code at runtime on some platforms, it's **very likely not the cleanest or safest route to what you're looking for**.

What you can do instead is use Unity scripting to build a virtual machine, which then interprets the scripts that the player has authored.

There are lots of ways you could do this.

A conventional approach would be to implement this as a **text parser**, which reads a string containing the program the player has authored, turns it into a syntax tree, then walks the tree executing the appropriate actions at each step.

You could also try a more **distributed/modular approach**. If you want a visual block structure like Scratch or Stencyl, then you very likely have a GameObject for each command block in the player's program, just to provide its visual representation. You could attach to each such GameObject a script that inherits from a common base class or implements an "ICommandBlock" interface, exposing:

* A `SetNextCommand()` method that you can use to link commands in a chain when the player connects them. If commands can be nested, you might need a few flavours of this, like `SetChildCommand()`
* A `Resume()` method implemented for blocks that can contain other blocks, so it can continue its work once its contained statements finish (eg. a loop block would increment its loop counter, check if the loop is complete, then re-run its contained statements)
* A `Run()` method that executes the logic of this command (which might include pushing itself onto the stack and running a child command), then runs the next command set above if there is one, or resumes the last command in the stack otherwise, signalling the end of the program if the stack is empty

In this model, you and the player are effectively working at the syntax tree level itself, rather than in raw text, although the two approaches could by hybridized. You could have a text parser whose job is to spawn & wire up GameObjects corresponding to the syntax of code as the player types, for example.

Either way, you'll likely want to set this up so the running of the program occurs in discrete stages (eg. rather than calling the `nextCommand.Run()` directly, we *schedule* it to be executed after a given delay), so that you can step through the program slowly to show it working, pause or abort execution where you want, and prevent your game from locking up if the player creates an infinite loop in their code. ;)

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


# Question
Title: IgnoreCollision while Dodging & Colliding
I'm working on a mechanic to allow the player to dodge through enemies. However I'm running into the issue where the player is only able to dodge through enemies while their *already dodging* when they collide with the enemy.

I want this to work both ways, as in, when their colliding with the enemy, they should be able to dodge through then.

Here's what I've been trying:

```
void OnCollisionEnter (Collision col) {

    //    STOP ENEMY FROM MOVING/PUSHING
    if (col.gameObject.tag == "Enemy") {
        Debug.Log("Collided with: " + col.gameObject.name);
        target = col.gameObject;
        target.GetComponent<ZombieController>().mRigidbody.isKinematic = true;

        //    IGNORE DODGING COLLISION WHEN ALREADY COLLIDED
        if (isDodging) Physics.IgnoreCollision(col.collider, GetComponent<Collider>(), true);
    }

    /*    IGNORE DODGING COLLISION
    if (isDodging && col.gameObject.tag == "Enemy") {
        Physics.IgnoreCollision(col.collider, GetComponent<Collider>(), true);
    }*/

}

```

It just doesn't seem to work when the player has already collided with the enemy. Hopefully all that made sense.

# Answer
You have to be prepared to avoid collision when the player is in dodging state even it it's not in collision / `OnCollision()`. Put a block like below on the `Update()`:

```
if (isDodging)
{
    Physics.IgnoreCollision(GameObject.FindWithTag("Enemy").GetComponent<Collider>(),
                            GetComponent<Collider>(),
                            true);
}

```
> 0 votes

---
Tags: unity, collision-detection, 3d
---


title: LibGDX - Bundling Files

text:
# Question
Title: LibGDX - Bundling Files
I have 3 files. A JSON file, a PNG file, and a TXT file. Is there any possible way I can put all three inside a common file with a custom extension? (for example "fileName.abc")

I searched the web a little, and found this which is perfect, and exactly what I need:
https://gist.github.com/MobiDevelop/5514357
Which is a zip solution. But I don't want to compress the files and if the extension is not zip, I would be happier.

**Question 1:** Can we change a file's extension ("file.png" to "file.abc") and read it as if it had the same extension?

**Question 2:** How can I put multiple files into same file, just like AAA games do?

**Question 3:** Can I just create a non-compressed zip file and change the extension? And read it using the class in the link?

**Question 4:** Is there a better way than question 3? Maybe a third party solution or something?

**EDIT:** I don't want the files to be compressed because the game will be runned on mobile devices too. And the game might be loading files during gameplay. I am just worried that there might be staggers, fps drops while loading files.

# Answer
> 0 votes
> Can we change a file's extension ("file.png" to "file.abc") and read it as if it had the same extension?

It depends on your framework. I don't know about libGDX, but some framework will open the file based on its extension, so renaming the file will not work. It's easily testable with a simple application.

> How can I put multiple files into same file, just like AAA games do?

They usually use a custom file format, or a zip file or the like (rar, 7z, whatever they decide). I see two advantages into doing this like that: it reduces the total file size (if there is compression) and increase the read speed because there are more chances that the files needed are close one to another on the disk (I think Wii games needed to be like this).

> Can I just create a non-compressed zip file and change the extension?

I know at least Quake3 did that. I'm not sure why you would like to have it *not* compressed, though (reading whole files from disk is usually slower than reading a much smaller archive into memory and decompressing from there).

> And read it using the class in the link?

I don't know. You'll have to see for yourself (technology recommendation is off topic here).

> Is there a better way than what I already suggested?

I think you have all the info now. Unless you have very specific needs, zipping the files together is usually enough for most needs.

# Answer
> 0 votes
> Question 1: Can we change a file's extension ("file.png" to "file.abc") and read it as if it had the same extension?

Yes this is possible with LibGDX.

> Question 2: How can I put multiple files into same file, just like AAA games do?

I ended up putting them inside a Zip file and changed the extension.

> Question 3: Can I just create a non-compressed zip file and change the extension? And read it using the class in the link?

The given class in the link has a problem. When the zip file is inside a jar file, you cannot use random access. You have to create a stream everytime you want to access a file. This will set you in the right direction: https://stackoverflow.com/questions/23869228/how-to-read-file-from-zip-using-inputstream

> Question 4: Is there a better way than question 3? Maybe a third party solution or something?

I wish there was. But I didn't find any.

Of course if you use zip files, anyone can open the jar and then the zip files with winrar, even if you change the .zip extension to something else.

---
Tags: java, libgdx, filesystem
---


title: Projectile Direction Unity

text:
# Question
Title: Projectile Direction Unity
I want to shoot a projectile in the direction the gun is facing.

With my current script it only shoots vertically. (I can also make it go horizontally but that's it).

This is my `GunController` class:

```
public Transform guntip;
public GameObject bullet;

float fireRate = 0.5f;
float nextFire = 0f;

void Update ()
{
    //playershooting
    if (Input.GetAxisRaw("Fire1") > 0)
    {
     fireRocket();
    }
}

void fireRocket()
{
    if(Time.time > nextFire)
    {
        nextFire = Time.time + fireRate;

        Instantiate(bullet, guntip.position, Quaternion.Euler(new Vector3(0, 0, 0)));
    }
}

```

This is my `ProjectileController` class:

```
Rigidbody2D MyRB;
public float rocketSpeed;

 void Awake()
{
    MyRB = GetComponent<Rigidbody2D>();

    MyRB.AddForce(new Vector2(0, 1) * rocketSpeed, ForceMode2D.Impulse); // explosive force, change vector 2 for horizontal shooting

}

```

# Answer
> 0 votes
```
Instantiate(bullet, guntip.position, guntip.rotation);

```

You need to inherit rotation of guntip to make bullets face that way.

---

To make bullet go towards the direction it's facing, if your 2D setup is top-down:

```
 MyRB.AddForce(transform.up * rocketSpeed, ForceMode2D.Impulse);

```

If your 2D setup is side-scroller:

```
 MyRB.AddForce(transform.right * rocketSpeed, ForceMode2D.Impulse);

```

# Answer
> 0 votes
Your `Awake()` method at `ProjectileController` class should be like:

```
void Awake()
{
    MyRB = GetComponent<Rigidbody2D>();

    Vector2 direction = GameObject.Find("Gun").GetComponenet<GunController>().guntip.position - transform.position; //Get a direction vector to fire the bullet at.

    direction.Normalized(); // direction vector normalized to magnitude 1

    MyRB.AddForce(direction * rocketSpeed, ForceMode2D.Impulse);
}

```

And Instantiation in `GunController()` should be like:

```
void fireRocket()
{
    if(Time.time > nextFire)
    {
        nextFire = Time.time + fireRate;

        Instantiate(bullet, transform.position, Quaternion.identity);
    }
}

```

You need a direction from `GunController` class's `guntip`. Name the gun object as "Gun" (or change in code) and need to get the gun tip position so that you can get a direction to shoot the projectile at. When we are subtracting `projectile`'s position vector from `guntip`'s position vector, we get a direction from projectile's current position to `guntip`'s position which is the direction to shoot projectile. But it has some magnitude in it. So we have to make the magnitude to 1 so that it doesn't effect the force you are about to apply on it. That's why `Normalized()` is used on the direction so the direction vector is now unit vector with just direction in it(magnitude 1). Then `AddForce()` on that direction.

---
Tags: unity, c#, projectile-physics
---


title: BoxCollider2D Not Working

text:
# Question
Title: BoxCollider2D Not Working
So I'm making a copy of noobtuts tutorial on Snake

I've done all their steps and am at the point of extending the game solo, however I have an issue with the basic set-up. My box colliders aren't working at all!

I have four borders each with a Box Collider 2D, nothing fancy about them, and a Snakehead with a Box Collider 2D, nothing fancy about that either. Only the food prefab I have uses the `IsTrigger`. The Snake head also has a Rigidbody 2D and I've experimented with putting a `Rigidbody2D` on the borders too but it's not solved my problem.

Basically when I have the Snakehead moves to the border, it just passes through the border! It doesn't stop, it doesn't do anything, just continues straight through the border.

I've a basic gif showing off what I mean:

The only different thing about the box colliders is that for the snake they're 0.7 in size, not 1. But even when put to 1, they don't work properly.

Why isn't it stopping the snake from moving? I've never had to tell an object that when it hits another object to not move through it from what I can remember.

# Answer
> 3 votes
In unity when collision don't work you can fix the problem by following the below steps:

1.Set Collision and Triggers based on game(If game was 2d you should use BoxCollider2D) and check BoxCollider2D trigger Boolean.

2.you should check Rigidbody Component that attached to objects because Collision need physics component(if game was 2d you should use RigidBody2D) and disable isKinematic because Collision don't work.

3.check your script:

4.If you can not fix your problem perhaps wrong settings go Edit/project Setting/Physics or Physics2D

So let's define when snake hit with wall reset game; create 4 Boxcollider2D and attach them Rigidbody2D using UnityEngine; using System.Collections;

```
public class Snake: MonoBehaviour {

    void OnCollisionEnter2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "Wall")
        {
            Application.LoadLevel(Application.loadedLevel); //RESTART
        }
    }
}

```

second way:you can use Trigger and define when snake exit from scope of the game Reset game

```
using UnityEngine;
using System.Collections;

public class Snake: MonoBehaviour {

    void OnTriggerExit2D(Collider2D coll)
    {
        if (coll.gameObject.tag == "Zone")//allowed scope of the game so walls are not included
        {
            Application.LoadLevel(Application.loadedLevel); //RESTART
        }
    }
}

```

# Answer
> 0 votes
Use `transform.Translate(dir * Time.deltaTime * snakeSpeed);` instead of `transform.Translate(dir);` on `Move()` method. Keep a float variable called `snakeSpeed`.

But you should not work with translation of a rigidbody. Use velocity instead.

Code should be like:

```
[SerializeField]
private float snakeSpeed = 10f;

private Rigidbody2D snakeHead;

void Start()
{
 snakeHead = GetComponent<Rigidbody2D>();
}

void FixedUpdate()
{
 Move();
}

void Move()
{
 snakeHead.velocity = dir * snakeSpeed;
 //Or
 //snakeHead.velocity = dir * Time.fixedDeltaTime * snakeSpeed; // In this case you have to increase snakeSpeed.
}

```

# Answer
> 0 votes
I had the same issue when i was making a breakout game it seems that Kinematic rigidbody collider don't interact with static ones you can check the table here: https://docs.unity3d.com/Manual/CollidersOverview.html.

for me i've overcame the issue by disabling isKinematic and setting the GravityScale to 0. you can either do that or use a script to limit the snake movement by comparing its coordinates with the borders' coordinates.

---
Tags: c#, 2d, collision-detection, unity
---


# Question
Title: Getting the material name or index from a Blender FBX model in MonoGame
I've imported Blender FBX models in to UE4 before, so I'm aware that some of the material information is saved in the model. How do I go about accessing this in MonoGame?

To be clear, I don't specifically mean *textures*. I mean the materials that then refer to a given set of textures (colour, normal, etc).

I'm currently parsing the same texture to the HLSL shader for the entire model, however I want to be able to change which texture is parsed based on the material information (or parse all textures to the shader and have it choose, I'm not sure)

EDIT: it would seem this information is saved in the FBX as "LayerElementMaterial"

```
LayerElementMaterial: 0 {
        Version: 101
        Name: ""
        MappingInformationType: "ByPolygon"
        ReferenceInformationType: "IndexToDirect"
        Materials: 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
                   2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,
                   3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
                   2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
                   2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2,2,2,2,
                   2,2,2,2,3,3,3,3,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
                   2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
                   2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
                   2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,1,1,1,1,

```

The question still stands, is this information accessible at runtime?

# Answer
> 0 votes
It would seem the only way to do this is to have the vertex colours correspond to a particular material (which wouldn't work as materials are set per face not per vertex) or completely re-write the FBX importer to take materials into account

As far as I can tell it's otherwise impossible

---
Tags: monogame, hlsl, blender, fbx, materials
---


# Question
Title: OpenGL 3.3 Core Compatibility with OpenGL 4.x
**Are all OpenGL calls in 3.3 Core and GLSL 330 core shaders valid and functionally equivalent in OpenGL 4.0 through 4.5 core?**

I can't seem to find a clear and definitive answer; both in specification and the real world, is code written for 3.3 core going to function in a 4.5 core context? I've currently kept all of my OpenGL renderer code strictly to 3.3 core profile, but I'd like to take advantage of some features that are only available in 4.0+ and 4.4+ if the user's environment supports those contexts. The change-logs of OpenGL seem fairly simple and it doesn't look like anything in 3.3 core has been deprecated in 4.

Are there new requirements OpenGL 4.0 or 4.4 that makes 3.3 core code used in conjunction with new features like tessellation shaders incompatible?

# Answer
> 2 votes
Code written for core 3.3 should be fully compatible with a 4.5 core profile. This can be seen from the OpenGL 4.1 and 4.5 specifications, which note features deprecated in each version (see appendices J and K in the first, and appendices E through H in the second). The only features which have been deprecated since the 3.3 specification are "the pixel pack parameters `UNPACK_LSB_FIRST` and `PACK_LSB_FIRST`" (deprecated in OpenGL 4.3). However, these calls are still available as of 4.5 and therefore compatibility is maintained.

As to whether there are quirks with switching the target GL version not obvious from the specification, I can't say. Strictly speaking though, you shouldn't encounter any issues.

For reference, all OpenGL specifications are available via the OpenGL Registry.

---
Tags: opengl
---


# Question
Title: How can I use a display as a background in unity?
I have a dancing game that I am trying to make and I have a stage where a character dances and a script to switch cameras inside that stage. What I am trying to do is set those cameras to display 2 and use that display as a background for the place where the game actually takes place. Is there a way to do that?

# Answer
> 1 votes
The way I achieved this is in a project consists of using an extended display configuration at operating system level. **Nvidia Mosaic** tool is great for this: I went up to 6 displays. You can then use a render-to-texture approach to render your camera onto a quad that corresponds to the area that is rendered to your 2nd display.

Also, it might be worth for you to have a look to how to launch a borderless window which I would recommend when using multiple displays. You do that by launching your Unity application with the popupwindow (link 1, link 2) parameter. Fullscreen mode can be good too.

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


title: Performing movement per game tick

text:
# Question
Title: Performing movement per game tick
Assume we have a player on a map, whereby the grid is represented as a floating point.

When a player is moving, they have an `x` and `y` velocity.

How to do you properly apply their movement each gametic?

By that I mean: do you keep nudging the player forward by one map unit and repeat that by the velocity? Where is that fine line where I say "we don't go any smaller movements than this like 0.5, or 0.25, etc"

Further, is there a way to optimize this to be able to make movement fast computationally? I thought of having some kind of blocks where you can quickly check if you'd intersect anything and make some optimizations, but I have no idea if this is good, bad, or how it should be done.

**Update**: Suppose you have a projectile traveling 100 map units North, and it would collide with an object 50 map units North of it. In the period of one world 'ticking', would you just halt it in a dead on collision (assuming the line is impassible), or would you detect a collision and then do something after it since that remaining 100 map unit velocity (like maybe if it's on an angle then cancel its Northward momentum and continue trying to move it to the East/West.

# Answer
> 2 votes
It s a bit unclear what you are asking, in particular what you mean by "gametic".

A computer game re-paints the screen repeatedly. Between two re-paints you have a delta time T, typically 0.01...0.03 s. Say it is 0.02 s this time - note however that it fluctuates.

Then you can calculate the physics & movement over a single calculation, to which you give 0.02 s as time.

An alternative is to do the calculation at a finer granularity, for example 0.005 s. In that case, there would be 4 re-calculations, since 4\*0.005 = 0.02. Hence, each physics re-calc uses timedelta=0.005, updates/re-positions the objects (but not visually, only in data), does the same again, again, 4 times or as many times as your pre-determined "fine granularity physics timestep" fits into frame timedelta T.

As these 4 iterations are completed, you paint the screen upon "what data you have now". If there was any unused time, eg. if frame time delta was 0.022, then you save 0.002 s for the next cycle/frame.

Ie. you check how many 0.005's fit into T, do the physics iterations that many times and pass the leftover to next frame. If that frame (or say "main game loop cycle") took 0.023 s, then you do the physics calc using 5 iterations, as 0.023 + 0.002 = 0.025 and 0.005 fits 5 times in 0.0025.

The amount of physics re-calcs per painted frame depends on the overall burden. Usually games are in a hurry.

**As a comment on your update text:** That is totally opinion-based, there is no "would" or "would not". Physics calculation at a fine granularity gives accuracy and detail, at a rough granularity gives speed. If it is essential that the physics behaviour is exact, then apparently do it at a fine granularity. This has nothing to do with frame painting. A frame paint is a "snapshot of the current situation". You can re-paint as seldom as once a day, though that would be a bad user experience. If you only do one physics re-calc during that day, well don't expect the car to have changed course from the initial. But if you do a trillion invisible physics re-calculations during the day, then the car will be at expected location when you do a screen re-paint next day. Physics calc does not have to be in sync with real world elapsed time.

# Answer
> 1 votes
In nutshell your a movement would look something like this: `speedX` `speedY` for vertical and horizontal speed. You have a `velocityX` and `velocityY` for example. Lets say its a top down game.

And you have your positions like `posX` and `posY`. Every tick you update your positions:

```
posX += speedX;
posY += speedY;

```

You assing a value to velocity like 0.2. In you code where you are listening for input:

```
if(A is pressed) speedY += velocityY;

```

Same with the others as well. To stop, you need to check if the button is released so you can decrease the speed to 0. Almost done, but this way your object will accelerate while you pressing the right button. You can define a max speed that will help you decide whether go any faster or not.

```
if(A is pressed && speedY < maxSpeed) speedY += velocityY;

```

Will solve this issue. To take care about direction you will need the absolute value of your speeds.

# Answer
> 1 votes
I havent done much on these lines.

But every object should recive (time\_elapsed) and calculate new position accordingly.

They should check for possible collision with static objects, and react (change of direction / state).

As far as other closer moving objects, you will have to do some hack (either treat the slower one as static, or get its approximate position in-between 2/3 slices of time frame and treat the slower one as static, or calculate the collision point based on their speed of movements, decide new course for both objects and mark both as done for the current time.

If there is more collision and detection, you would certainly want to use a physics library like Box2d.

# Answer
> 0 votes
@eldo's answer is good, but since you are doing this from scratch, you need to begin implementing systems for physics. There are all manner of ways to do this, from implementing a quadtree of physical space (so you're only checking sections that your moving object will pass through), to implementing colliders like Unity does (and I believe Unreal Engine has a similar system).

As to the question of what happens when the moving object hits something - that depends on what you implement. If the physics of your engine dictates a full stop of the object, then I would reduce the velocity to 0, only because continually trying to keep velocity on an object that cannot go anywhere seems like a waste of cycles.

---
Tags: physics, movement
---


title: Unity Wwise. No audio in my game build

text:
# Question
Title: Unity Wwise. No audio in my game build
I'm building a game in Unity using Wwise as the audio engine. I'm on a Mac and whenever I build the game, there is no audio. Apparently this is because the sound banks are not in the correct folder. They should be in Assets/StreamingAssets/Audio/GeneratedSoundBanks/ followed by a sub-folder with the name of whatever platform you are using. I should have a Mac folder located here however there isn't one. Instead my sound banks just sit in the GeneratedSoundBanks folder which works when i test the game in unity, however there is no audio when I build the game. Apparently this has something to do with environment variables or a python path but I have no idea how to fix or edit these as I am new to coding as well as Wwise and Unity. If I build the game for web player I get an error CS0246: The type of namespace name 'AKRESULT' could not be found. Web GL says it doesn't work for the unity wise integration package I have either (and going to an older one just messed my whole projects audio up completely). If anyone could give me any help at all, it would be very much appreciated. Thank You.

I'm using: Unity 5.3.5.1f, Wwise v2016.1 (32-bit), WwiseUnityIntergration\_v2016.1\_Mac.unitypackage.

# Answer
> 2 votes
You need to copy the `GeneratedSoundbanks` folder in your Wwise project, and paste it into the `Assets/StreamingAssets/Audio/` directory of your Unity project before running the build process in Unity.

---
Tags: unity, audio, wwise
---


# Question
Title: Why does Facebook share callback return "success" if the user cancels?
Here is the code piece I used to debug:

```
public void Share (FacebookPost post)
{
    FacebookDelegate<IShareResult> innerCallback = (result) =>
    {
        foreach (var item in result.ResultDictionary)
        {
            Debug.Log(item.Key + " " + item.Value);
        }
    }

    FB.ShareLink (post.linkURL, post.linkTitle, post.linkDescription, post.imageURL, innerCallback);
}

```

The callback is expected to return a "cancelled" key if user closes the share dialog without sharing, but instead it returns "posted" key with "true" value, which is exactly the same result as when user literally "posts".

And it returns no other data that can help me to decide if user actually shared or not.

So, how can i decide if user shared or cancelled?

# Answer
> -1 votes
I never really found a documentation for , i had to debug it. By the way, stub function in UnityEditor does not return same values (result) as those on device. Example: for success post Editor: {"did\_complete" : true} for success post Device: {"posted" : true}

Are you sure you are: 1) using latest fb plugin? 2) did you debug results on the build version? 3) are your fb app id, and all other parametres setup right, and are you using test user?

---
Tags: unity, facebook
---


title: Setting sound panning

text:
# Question
Title: Setting sound panning
I'm trying to set sound panning in my game depending on camera position, rotation and audio source position.

I was able to set sound panning depending on camera position (listener), and audio source like this:

```
Vector3 toSourceVector = Vector3::subtract(sourceTransform->position, listenerTransform->position);
float value = MathUtil::clamp(toSourceVector.x, -1.5f, 1.5f);
value = value + 1.5f;
float perc = (value / 3.0f) * 254.0f;
AudioManager::setPanning(254.0f - perc, perc);

```

Max panning value on the right/left speaker is 254. When I'm standing on the front of the audio source (without rotating my camera), panning values are: 127 and 127, for example, when the audio source is on my right side, panning values are 0 and 254.

Obviously, if I rotate my camera, sound panning is same.

I've got Vector3 with camera (listener) rotation values (x, y, z).

My question is: how to calculate panning values depending on camera rotation too?

# Answer
Sorry for answering my own question, but as the final solution, I decided to use ready API called OpenAL, that takes a care of sound panning.

Thanks for everyone's input.
> 0 votes

---
Tags: c++, sound
---


# Question
Title: given the position and velocity of an object how can I detect possible Collision?
I'm trying to detect Collision between autonomous moving objects and steer direction if collision is detected. so far I've been following a tutorial and I'm having a hard time to fully understand how it works especially the role of the dot product

```
foreach (GameObject t in targets) //get me all moving agents
{
 Vector3 relativePos;
 Agent targetAgent = t.GetComponent<Agent>(); //access properties like velocity
 relativePos = t.transform.position - transform.position;
 Vector3 relativeVel = targetAgent.velocity - agent.velocity;
 float relativeSpeed = relativeVel.magnitude;

```

//can someone explain this part of code how did we calculate the time of collision?

```
 float timeToCollision = Vector3.Dot(relativePos, relativeVel);
 timeToCollision /= relativeSpeed * relativeSpeed * -1;
 float distance = relativePos.magnitude;
 float minSeparation = distance - relativeSpeed *
 timeToCollision;

```

# Answer
The dot product has two nice properties for collision avoidance. The dot product is closely related to the cosine of the angle between two vectors.

The dot product of a unit vector A and a second vector B of any non-zero length, the result is the length of vector A projected in the direction of vector B.

So as you can see in the image; if the angle is greater than 90 degrees, the dot product will be negative. So, the dot product has to be a positive value or there will be no collision. Most likely in your code/tutorial the dot product is used to check if the objects are heading towards eachother (maybe based on a "viewcone" or something similar- for example a dot product of \>0.5 equals a cone of 45 degrees). This is the first property: check if the objects are actually heading towards eachother by evaluating the angle between them.

Once decided a collision is likely based on the directions the objects, the next property comes into play:

The relPosition and relVelocity are is used to project the velocity vector onto the position vector:

```
float timeToCollision = Vector3.Dot(relativePos, relativeVel);

```

This line basically projects the Velocity (A in the image) onto the RelativePosition (vector pointing from the first agent to the 2nd agent).

Then the result is divided by the `relativeSpeed * relativeSpeed` (since the two objects both have their velocities turned into one relative speed value), to calculate the actual `timeToCollision`.

Note that this calculation *does not mean* the objects will collide! It merely calculates the time where the two objects are *the most close* to eachother during their trajectories (the variable name may be confusing you here!)

This is where these lines comes in:

```
float distance = relativePos.magnitude;
float minSeparation = distance - relativeSpeed * timeToCollision;

```

The minimal Separation is the distance between the two objects at the time of the closest approach. Remember `relativePos` is actually a vector from object A to B; the magnitude is the current distance. Shorten the distance by the distance travelled during the calculated timeframe `relativeSpeed * timeToCollision` and the result will be the minimal distance between the objects during the trajectories.

Now if the minimal distance is smaller than the sizes of the objects *they will collide* and the agent must take an evasive action.

The image is taken from the Wikipedia page 'Dot product'.
> 1 votes

---
Tags: collision-detection, ai, linear-algebra, collision-avoidance
---


# Question
Title: Why does every texture drawn cause a new draw call?
I'm currently working on a 2d sandbox tile game in LibGDX and I noticed I had 700+ draw calls. So checked my code and I could not find anything that would cause a new draw call. All the tiles are drawn between a single batch.begin() and a batch.end(). I commented out the code for rendering the tiles and I had around 2-3 draw calls. I can't figure out whats wrong so I am posting this here.

Here is the call chain of the render method:

In my world class:

```
public void render(SpriteBatch batch, ShapeRenderer shapeBatch) {

    batch.begin();
    chunkManager.render(batch);
    if (selectedBlock != null) batch.draw(gameScreen.app.assetManager.get("misc/block_selection_texture.png",Texture.class), selectedPosition.x * 32, selectedPosition.y * 32);
    batch.end();

}

```

World is calling chunkManager.render(..):

```
public void render(SpriteBatch batch) {
    //Render all the chunks
    for (Chunk c : activeChunks) {
        if (c != currentChunk) {
            c.render(batch);
        }
    }

    //Render Current Chunk the player is in in front of every other chunk
    currentChunk.render(batch);
}

```

ChunkManager is calling c.render(..):

```
public void render(SpriteBatch batch){
    //Render all Blocks inside the Chunk
    for(Block b:blocks.values()){
        b.render(batch); // <- this is the line I commented out
    }

    //Render all Entities inside the Chunk
    for(Entity e:entities){
        e.render(batch);
    }
}

```

Chunk is calling b.render(..):

```
public void render(SpriteBatch batch){

    float hp = hardness/maxHardness;

    //tint the blocks based on their health
    batch.setColor(1*hp,1*hp,1*hp,1);
    batch.draw(texture, x*32, y*32);
    batch.setColor(Color.WHITE);

}

```

and e.render(..):

```
public void render(SpriteBatch batch){
   if(isAnimated) {
       renderAnimation(batch); // -> just batch.draw(..) for animations
   } else {
       batch.draw(texture, x, y);
   }
}

```

# Answer
> 3 votes
At the GPU API level (that is, the D3D or OpenGL level) drawing something with a different texture is generally going to involve issuing a new draw call. Draw calls only use the current state as-of the point where the call is issued; changing textures is a state change.

"Sprite batch" implementations generally use some kind of sorting to minimize draw calls; for example, if you call "spritebatch.draw" with a set of parameters (including texture) that match an *existing* set of parameters (including texture) within that batch's begin/end block, the batch will make sure to draw both sets of geometry with that set of GPU state before switching to another. But that still means if you have 100 textures, you'll get a minimum of 100 draw calls; more if the sprite batch doesn't implement this technique well or if there is other state you're changing with each draw.

A quick examination of LibGDX's sprite batch suggests that it does *not* perform the above optimization. Rather, every time you call draw it checks to see if the texture you've given it is the same as the last time. If it isn't, it calls `switchTexture`. `switchTexture` calls `flush`, which renders the actual geometry queued up.

This means you are potentially getting one GPU draw call for every sprite batch draw call (in the worst case scenario where the texture changes every time).

You can solve this by sorting or batching your own calls to the sprite batch so that keep the texture parameter the *same* for as many consecutive calls to `draw` as possible. This way the batch will only flush when it hits its vertex buffer threshold (maximum number of quads to draw at once, basically). This should give you much fewer draw calls, to the theoretical best case of one call per unique texture.

Alternatively, you can pack multiple sprites into one larger texture and reduce the need to switch textures that way as well.

---
Tags: java, libgdx
---


# Question
Title: SDL2 graphics will draw in main process but not in separate thread
I'm having an issue that I'm absolutely stuck on and my ability to debug this issue has been exhausted.

I am implementing a base for a 2D game where I am handling my keyboard input, logic, and graphics in their own thread. The input and logic work flawlessly, and as far as I know, the graphics is working too... except that the graphics is not drawn to the screen.

If I put all of my graphics logic into my main process, it works fine. For example:

```
TTextObject* text = new TTextObject("My text", 12, TPoint(0,0), {255,0,0});
SDL_SetRenderDrawColor(_R, 0, 0, 0, 0);
SDL_RenderClear(_R);
text->draw();
SDL_RenderPresent(_R);

```

The TTextObject accepts the actual text, font size, origin point, and color.

As I stated before, this works absolutely fine within the main process of the program. However, when I split up the code, and take the same exact code and use it in a separate thread, it will not work.

I have debugged to make sure that:

* The Renderer object is the same
* The text object is the same
* The window is the same (it should be at least as the renderer is created with respect to the window).

**My source code is found at: https://Zulukas@bitbucket.org/Zulukas/gamebase.git**

It should compile just fine on Ubuntu; I haven't tested it on Windows or any other Linux distro. Thanks for any help in advance!

# Answer
> 2 votes
SDL isn't built to support multithreaded rendering. It's a miracle that your code doesn't immediately crash. In most graphics APIs rendering has to be done on the thread where the renderer was created.

---
Tags: sdl2
---


# Question
Title: How would I make my position interpolation stop once the destination is reached?
I would like to implement tile-based grid movement and I've heard that linear interpolation comes handy in the implementation process. I've tried to use it but I'm not sure how to make it stop once the target position is reached. I can't find a way to check that on the interpolation. Here's the code I'm using:

```
function movePlayer(deltaTime) {
    if buttonUp then
       velocity.add(0, speed);
    if buttonRight then
       velocity.add(speed, 0);
    if buttonSouth then
       velocity.sub(0, speed);
    if buttonLeft then
       velocity.sub(speed, 0);

    velocity.scl(deltaTime);

    if (targetPosition.isZero()) {
        targetPosition.add(getNextPosition());
    }

    position.lerp(targetPosition, speed * deltaTime);

    float distance = position.dst(targetPosition);
    if (allowMovement && distance < 0.1f) {
        position = targetPosition;
        allowMovement = false;
        targetPosition.set(0, 0);
    }
}

```

# Answer
The solution can be achieved in multiple ways, but checking the remaining distance between the current and the target position is a good way to go about this.

```
distance = targetPosition.sub(position).getLength();
if (distance < some_small_constant)
{
    position = targetPosition;
}

```

The code first creates a vector from the current position to the target position, and calculates its length. The length is then compared to a small constant (you should try out different values to see which feels good enough). If the length requirement is met, the position is snapped to the target position and then you're good to go!
> 1 votes

# Answer
It seems like you are going about this the wrong way.

Linear interpolation is the process of transitioning from one value to a second value, which is exactly what you are looking for with your movement.

I'm unaware of java and libgdx syntax, but here's some example code so you get the idea.

Here's what you need:

`Vector2 CurrentPosition` : Your characters current position.

`Vector2 StartingPosition` : Your characters original position.

`Vector2 EndPosition` : Your characters desired position.

`float timeSinceStart` : The amount of time that has passed since beginning the transition.

`int time` : How long you want the transition to take in milliseconds.

To lerp, just do this every frame:

```
timeSinceStart += deltaTime; //Elapsed time since last frame
var delta = Clamp(time / timeSinceStart, 0, 1);
CurrentPosition = Lerp(StartingPosition, EndPosition, delta);
//Or possibly CurrentPosition = StartingPosition.lerp(EndPosition, delta) if that's the syntax.

```

First it adds the elapsed game time (delta time) to `timeSinceStart` to keep track of how much time has passed.

Then it creates the `delta` variable which is used to lerp between the start and end positions. The `Clamp` method is used to keep the value within 0 and 1. If delta is at 0 it means that no time has passed and the characters position should be at the starting position. If delta is at 1 it means that the amount of time that has passed is equal to how long we wanted it to take our character to move, and so our character will be at the end position.

Then it lerps between the start and end positions using the delta.

To check if your player has reached his target position, you simply check if `delta == 1`
> 0 votes

---
Tags: java, libgdx, movement
---


# Question
Title: shooting the projectile in the way it is facing
I got my projectile facing the right way thanks to @S. Tarık Çetin. But now I want it to move the direction it's facing. I think I need to use `RayCastHit2D` but I am not sure. If I need to use `RayCastHit2D` please tell me how.

I want to replace this part with `RayCastHit2D` or something else -:

```
MyRB.AddRelativeForce(new Vector2(1,1) * rocketSpeed, ForceMode2D.Impulse);

```

Another thing - my projectile requires gravity. I think if I use `RayCastHit2D` the projectile will go in a straight line and not fall down. So if that's the case please tell me a better alternative. (so it acts like a tank projectile)

here is my code -:

Aim class -

```
       void Update(){
        if (Input.GetKey(KeyCode.L))
        transform.Rotate(0, 0, -3.0f);

        if (Input.GetKey(KeyCode.J))
            transform.Rotate(0, 0, 3f);
}

```

ProjectileController class -

```
     void Awake()
    {
        MyRB = GetComponent<Rigidbody2D>();
        MyRB.AddRelativeForce(new Vector2(1,1) * rocketSpeed, ForceMode2D.Impulse);
}

```

GunController class -:

```
void Update()
{

    //playershooting
    if (Input.GetAxisRaw("Fire1") > 0)
        fireRocket();

}

void fireRocket()
{

    if (Time.time > nextFire)
    {

        nextFire = Time.time + fireRate;

        Instantiate(bullet, guntip.position, guntip.rotation);

    }

```

# Answer
please tell me what do you want?! RayCastHit uses for find hit object in scene for example define when tank see enemy shot.your code is correct if you want shooting the projectile in the way it is facing you should use transform.right

```
    void fireRocket()
    {

        if (Time.time > nextFire)
        {

            nextFire = Time.time + fireRate;

            GameObject clone = Instantiate(bullet, guntip.position, guntip.rotation) as GameObject;
            clone.GetComponent<Rigidbody2D>().AddForce(transform.right * 10, ForceMode2D.Impulse);
        }
    }
}

```
> 0 votes

---
Tags: unity, c#, projectile-physics
---


# Question
Title: Multiple keys being pressed, some being ignored SDL
I'm making a two player pong clone and my problem is that when the second player presses both of his/her buttons at once, the first player locks up and cannot move, even though this does not happen when player one does this. This is pretty much the last kink I have in this clone so I'd like to handle it so I can move on to something new. The code that takes the key strokes looks like this:

```
void Paddle::events()
{
    //press
        if (player == 1)
        {
            Uint8 *keystates = SDL_GetKeyState(NULL);
            if (keystates[SDLK_o] == 1)
            {
                yVel = -200;
                return;
            }
            if (keystates[SDLK_k] == 1)
            {
                yVel = 200;
                return;
            }
        }
        if (player == 2)
        {
            Uint8 *keystates = SDL_GetKeyState(NULL);
            if (keystates[SDLK_w] == 1)
            {
                yVel = -200;
                return;
            }
            if (keystates[SDLK_s] == 1)
            {
                yVel = 200;
                return;
            }
        }
        //release
        if (player == 1)
        {
            Uint8 *keystates = SDL_GetKeyState(NULL);
            if ((keystates[SDLK_o] == 0) && (keystates[SDLK_k] == 0))
            {
                yVel = 0;
                return;
            }
        }
        if (player == 2)
        {
            Uint8 *keystates = SDL_GetKeyState(NULL);
            if ((keystates[SDLK_w] == 0) && (keystates[SDLK_s] == 0))
            {
                yVel = 0;
                return;
            }
        }
    if (event.type == SDL_QUIT)
    {
        quit = true;
    }
}

```

I've stewed over it for quite some time, but don't see how it could be doing that. Could it be hardware related?

And as a note, event polling occurs in my main loop, which is supported by a state machine, so that's why you don't see the classic `while (SDL_EventPoll (&event))` in there.

I fail to understand how implementing Polls for each player would work withing proper game loop writing, I've been taught only to Poll in the main loop and not in classes or methods. But either way, here is the entirety of the code:

```
#include "SDL.h"
#include "SDL_image.h"
#include "SDL_ttf.h"
#include "SDL_mixer.h"
#include <iostream>
#include <string>
#include <sstream>
#include <stdlib.h>

/*CLASSES*/

class GameState
{
public:
    virtual void events() = 0;
    virtual void logic() = 0;
    virtual void render() = 0;
    virtual ~GameState(){};
};

class Button
{
public:
    SDL_Rect button_clip[2];
    SDL_Rect button;
    SDL_Surface *button_sprite = NULL;
    Button();
};

class Paddle
{
private:

public:
    int player;
    float x, y, w, h;
    float yVel;
    SDL_Surface *sprite = NULL;
    SDL_Rect clip;
    SDL_Rect *cliping;
    void events();
    void logic(Uint32 deltaticks);
    void render();
    Paddle();
    ~Paddle();
};

class Ball
{
private:
    SDL_Rect clip[1];
public:
    float temp_x;
    float temp_y;
    bool win;
    SDL_Surface *win_message;
    int score_P1;
    int score_P2;
    Paddle *paddle_pointer1;
    Paddle *paddle_pointer2;
    SDL_Rect *collision;
    float x, y, w, h;
    float xVel, yVel;
    SDL_Surface *sprite = NULL;
    SDL_Rect *cliping;
    void events();
    void logic(Uint32 deltaticks);
    void render();
    Ball();
    ~Ball();
};

class Game : public GameState
{
public:
    SDL_Surface *score_message = NULL;
    int *score_P1;
    int *score_P2;
    Paddle PlayerOne;
    Paddle PlayerTwo;
    Ball Game_Ball;
    SDL_Rect clip[1];
    void events();
    void logic();
    void render();
    Game();
    ~Game();
};

class Title : public GameState
{
private:
    SDL_Surface *Title_Message = NULL;
    SDL_Rect *clip;
    Button Title_Button;
public:
    void events();
    void logic();
    void render();
    Title();
    ~Title();
};

class Timer
{
private:
    //The clock time when the timer started
    int startTicks;

    //The ticks stored when the timer was paused
    int pausedTicks;

    //The timer status
    bool paused;
    bool started;

public:
    //Initializes variables
    Timer();

    //The various clock actions
    void start();
    void stop();
    void pause();
    void unpause();

    //Gets the timer's time
    int get_ticks();

    //Checks the status of the timer
    bool is_started();
    bool is_paused();
};

/*CONSTANTS AND GLBALS*/
const int SCREEN_WIDTH = 700;
const int SCREEN_HEIGHT = 500;
const int SCREEN_BPP = 32;
const int FPS = 100;

/*VARS*/
bool quit = false;

/*GAMESTATES*/
enum States
{
    S_NULL,
    TITLE,
    GAME,
    WIN,
    EXIT,
};

/*SURFACES*/
SDL_Surface *screen = NULL;

/*FONTS*/
SDL_Color color = { 255, 255, 255 };
TTF_Font *font = NULL;

//STATE VARS
GameState *currentState = NULL;
int stateID = NULL;
int nextState = NULL;

//SDL event
SDL_Event event;

//timer
Timer delta;

//key
Uint8 *keystates = SDL_GetKeyState(NULL);

/*FUNCTIONS*/
SDL_Surface *load_image(std::string filename)
{
    //loaded image
    SDL_Surface* loadedImage = NULL;
    //optimized surface
    SDL_Surface* optimizedImage = NULL;
    //load image
    loadedImage = IMG_Load(filename.c_str());
    //if image loaded
    if (loadedImage != NULL)
    {
        //Create optimized image
        optimizedImage = SDL_DisplayFormat(loadedImage);
        //free old image
        SDL_FreeSurface(loadedImage);
        //if optimized
        if (optimizedImage != NULL)
        {
            //map color key
            Uint32 colorkey = SDL_MapRGB(optimizedImage->format, 0, 0, 0);
            //set all pixles of color 0,0,0 to be transparent
            SDL_SetColorKey(optimizedImage, SDL_SRCCOLORKEY, colorkey);
        }
    }
    return optimizedImage;
}

//apply image
void apply_surface(int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip = NULL)
{
    //temp rect
    SDL_Rect offset;
    //offsets
    offset.x = x;
    offset.y = y;
    //blit
    SDL_BlitSurface(source, clip, destination, &offset);
}

//initiate SDL etc
bool init()
{
    //initialize all SDL subsystems
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
    {
        return false;
    }
    //set up screen
    screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE);
    if (screen == NULL)
    {
        return false;
    }
    //check screen
    if (screen == NULL)
    {
        return false;
    }
    //init TTF
    if (TTF_Init() == -1)
    {
        return false;
    }
    //set window caption
    SDL_WM_SetCaption("PONG", NULL);
    //if evetything worked
    return true;
}

//load files
bool load_files()
{
    font = TTF_OpenFont("SF Pixelate.ttf", 45);
    if (font == NULL)
    {
        return false;
    }
    return true;
}

//quit
void clean_up()
{
    //delete game state
    //free image

    //quit ttf
    TTF_CloseFont(font);
    TTF_Quit();
    //quit SDL
    SDL_Quit();
}

// STATE MACHINE FUNCTIONS //
void set_next_state(int newState)
{
    if (nextState != EXIT)
    {
        nextState = newState;
    }
}

void change_state()
{
    if (nextState != S_NULL)
    {
        //change state
        switch (nextState)
        {
        case GAME:
            currentState = new Game();
            break;
        }
        //change state
        stateID = nextState;
        //null nextState
        nextState = S_NULL;
    }
}

/*CLASS DEFINITIONS*/

Timer::Timer()
{
    //Initialize the variables
    startTicks = 0;
    pausedTicks = 0;
    paused = false;
    started = false;
}

void Timer::start()
{
    //Start the timer
    started = true;

    //Unpause the timer
    paused = false;

    //Get the current clock time
    startTicks = SDL_GetTicks();
}

void Timer::stop()
{
    //Stop the timer
    started = false;

    //Unpause the timer
    paused = false;
}

void Timer::pause()
{
    //If the timer is running and isn't already paused
    if ((started == true) && (paused == false))
    {
        //Pause the timer
        paused = true;

        //Calculate the paused ticks
        pausedTicks = SDL_GetTicks() - startTicks;
    }
}

void Timer::unpause()
{
    //If the timer is paused
    if (paused == true)
    {
        //Unpause the timer
        paused = false;

        //Reset the starting ticks
        startTicks = SDL_GetTicks() - pausedTicks;

        //Reset the paused ticks
        pausedTicks = 0;
    }
}

int Timer::get_ticks()
{
    //If the timer is running
    if (started == true)
    {
        //If the timer is paused
        if (paused == true)
        {
            //Return the number of ticks when the timer was paused
            return pausedTicks;
        }
        else
        {
            //Return the current time minus the start time
            return SDL_GetTicks() - startTicks;
        }
    }

    //If the timer isn't running
    return 0;
}

bool Timer::is_started()
{
    return started;
}

bool Timer::is_paused()
{
    return paused;
}

Button::Button()
{

}

Title::Title()
{
    //text/sprites
    Title_Message = TTF_RenderText_Solid(font, "PONG", color);
    Title_Button.button_sprite = load_image("Start.png");
    //region for button
    Title_Button.button.x = 300;
    Title_Button.button.y = 350;
    Title_Button.button.w = 100;
    Title_Button.button.h = 50;
    //clips not hover
    Title_Button.button_clip[0].x = 0;
    Title_Button.button_clip[0].y = 0;
    Title_Button.button_clip[0].w = 100;
    Title_Button.button_clip[0].h = 50;
    //clips hover
    Title_Button.button_clip[1].x = 0;
    Title_Button.button_clip[1].y = 50;
    Title_Button.button_clip[1].w = 100;
    Title_Button.button_clip[1].h = 50;
}

Title::~Title()
{
    SDL_FreeSurface(Title_Message);
    SDL_FreeSurface(Title_Button.button_sprite);
}

void Title::events()
{
    int x = 0;
    int y = 0;
        if (event.type == SDL_MOUSEMOTION)
        {
            x = event.motion.x;
            y = event.motion.y;
            if ((x > Title_Button.button.x) && (x < (Title_Button.button.x + Title_Button.button.w)) && (y > Title_Button.button.y) && (y < (Title_Button.button.y + Title_Button.button.h)))
            {
                clip = &Title_Button.button_clip[1];
            }
            else
            {
                clip = &Title_Button.button_clip[0];
            }
        }
        if (event.type == SDL_QUIT)
        {
            quit = true;
        }
        if (event.type == SDL_MOUSEBUTTONDOWN)
        {
            if (event.button.button == SDL_BUTTON_LEFT)
            {
                x = event.motion.x;
                y = event.motion.y;
                if ((x > Title_Button.button.x) && (x < (Title_Button.button.x + Title_Button.button.w)) && (y > Title_Button.button.y) && (y < (Title_Button.button.y + Title_Button.button.h)))
                {
                    set_next_state(GAME);
                }
            }
        }

}

void Title::logic()
{

}

void Title::render()
{
    apply_surface(Title_Button.button.x, Title_Button.button.y, Title_Button.button_sprite, screen, clip);
    apply_surface((SCREEN_WIDTH - Title_Message->w) / 2, 100, Title_Message, screen);
}

Paddle::Paddle()
{

}

Paddle::~Paddle()
{

}

void Paddle::events()
{
    //press
        if (player == 1)
        {
            Uint8 *keystates = SDL_GetKeyState(NULL);
            if (keystates[SDLK_o] == 1)
            {
                yVel = -200;
                return;
            }
            if (keystates[SDLK_k] == 1)
            {
                yVel = 200;
                return;
            }
        }
        if (player == 2)
        {
            Uint8 *keystates = SDL_GetKeyState(NULL);
            if (keystates[SDLK_w] == 1)
            {
                yVel = -200;
                return;
            }
            if (keystates[SDLK_s] == 1)
            {
                yVel = 200;
                return;
            }
        }
        //release
        if (player == 1)
        {
            Uint8 *keystates = SDL_GetKeyState(NULL);
            if ((keystates[SDLK_o] == 0) && (keystates[SDLK_k] == 0))
            {
                yVel = 0;
                return;
            }
        }
        if (player == 2)
        {
            Uint8 *keystates = SDL_GetKeyState(NULL);
            if ((keystates[SDLK_w] == 0) && (keystates[SDLK_s] == 0))
            {
                yVel = 0;
                return;
            }
        }
    if (event.type == SDL_QUIT)
    {
        quit = true;
    }
}

void Paddle::logic(Uint32 deltaticks)
{
    y += yVel * (deltaticks / 1000.f);
    if (y < 0)
    {
        y = 0;
    }
    else if (y > SCREEN_HEIGHT - h)
    {
        y = SCREEN_HEIGHT - h;
    }
}

void Paddle::render()
{
    apply_surface((int)x, (int)y, sprite, screen, cliping);
}

Ball::Ball()
{
    sprite = load_image("Game_sprite.png");
    clip[0].x = 0;
    clip[0].y = 0;
    clip[0].w = 20;
    clip[0].h = 20;
    cliping = &clip[0];
    win = false;
    x = 340;
    y = 240;
    w = 20;
    h = 20;
    yVel = 0;
    xVel = 200;
}

Ball::~Ball()
{

}

void Ball::events()
{
    if (event.type == SDL_QUIT)
    {
        quit = true;
    }
}

void Ball::logic(Uint32 deltaticks)
{
    temp_x = x + xVel * (deltaticks / 1000.f);
    temp_y = y + yVel * (deltaticks / 1000.f);
    if (x < 0)
    {
        score_P1 += 1;
        x = 340;
        y = 240;
        yVel = 200;
        xVel = -170;
        SDL_Delay(1000);
        return;
    }
    if (x > SCREEN_WIDTH - w)
    {
        score_P2 += 1;
        x = 340;
        y = 240;
        yVel = 200;
        xVel = 170;
        SDL_Delay(1000);
        return;
    }
    if ((temp_y < 0) || (y + w > SCREEN_HEIGHT))
    {
        yVel = -yVel;
        y += yVel * (deltaticks / 1000.f);
        return;
    }

    //standard collisions
    //P1
    if (((temp_x <= (paddle_pointer1->x + paddle_pointer1->w)) && ((temp_x + w) >= paddle_pointer1->x)) && (((temp_y + h) >= paddle_pointer1->y) && (temp_y <= (paddle_pointer1->y + paddle_pointer1->h))))
    {
        if (xVel > 0)
        {
            xVel += 30;
        }
        else
        {
            xVel -= 30;
        }
        if (yVel >= 0)
        {
            if (paddle_pointer2->yVel > 0)
            {
                yVel += 50;
                xVel = -xVel;
            }
            else
            {
                yVel += 50;
                yVel = -yVel;
                xVel = -xVel;
            }
            x -= paddle_pointer2->yVel * (deltaticks / 1000.f);
            return;
        }
        if (yVel <= 0)
        {
            if (paddle_pointer2->yVel > 0)
            {
                yVel += 50;
                yVel = -yVel;
                xVel = -xVel;
            }
            else
            {
                yVel += 50;
                xVel = -xVel;
            }
            x += paddle_pointer2->yVel * (deltaticks / 1000.f);
            return;
        }
    }
    //P2
    if (((temp_x <= (paddle_pointer2->x + paddle_pointer2->w)) && ((temp_x + w) >= paddle_pointer2->x)) && (((temp_y + h) >= paddle_pointer2->y) && (temp_y <= (paddle_pointer2->y + paddle_pointer2->h))))
    {
        if (xVel > 0)
        {
            xVel += 30;
        }
        else
        {
            xVel -= 30;
        }
        if (yVel >= 0)
        {
            if (paddle_pointer2->yVel > 0)
            {
                yVel += 50;
                xVel = -xVel;
            }
            else
            {
                yVel += 50;
                yVel = -yVel;
                xVel = -xVel;
            }
            x -= paddle_pointer2->yVel * (deltaticks / 1000.f);
            return;
        }
        if (yVel <= 0)
        {
            if (paddle_pointer2->yVel > 0)
            {
                yVel += 50;
                yVel = -yVel;
                xVel = -xVel;
            }
            else
            {
                yVel += 50;
                xVel = -xVel;
            }
            x += paddle_pointer2->yVel * (deltaticks / 1000.f);
            return;
        }
    }
    y += yVel * (deltaticks / 1000.f);
    x += xVel * (deltaticks / 1000.f);
}

void Ball::render()
{
    if (score_P1 == 11)
    {
        win_message = TTF_RenderText_Solid(font, "Player One Wins", color);
        apply_surface((SCREEN_WIDTH - win_message->w) / 2, (SCREEN_HEIGHT - win_message->h) / 2, win_message, screen);
        win = true;
    }
    else if (score_P2 == 11)
    {
        win_message = TTF_RenderText_Solid(font, "Player Two Wins", color);
        apply_surface((SCREEN_WIDTH - win_message->w) / 2, (SCREEN_HEIGHT - win_message->h) / 2, win_message, screen);
        win = true;
    }
    else
    {
        apply_surface((int)x, (int)y, sprite, screen, cliping);
    }
}

Game::Game()
{
    //clip sprite
    //paddle
    clip[0].x = 0;
    clip[0].y = 20;
    clip[0].w = 20;
    clip[0].h = 100;
    //ball
    clip[1].x = 0;
    clip[1].y = 0;
    clip[1].w = 20;
    clip[1].h = 20;
    //player one
    PlayerOne.sprite = load_image("Game_sprite.png");
    PlayerOne.clip.x = 0;
    PlayerOne.clip.y = 20;
    PlayerOne.clip.w = 20;
    PlayerOne.clip.h = 100;
    PlayerOne.x = 680;
    PlayerOne.y = 200;
    PlayerOne.w = 20;
    PlayerOne.h = 100;
    PlayerOne.cliping = &clip[0];
    PlayerOne.yVel = 0;
    PlayerOne.player = 1;
    //player two
    PlayerTwo.sprite = load_image("Game_sprite.png");
    PlayerTwo.clip.x = 0;
    PlayerTwo.clip.y = 20;
    PlayerTwo.clip.w = 20;
    PlayerTwo.clip.h = 100;
    PlayerTwo.x = 0;
    PlayerTwo.y = 200;
    PlayerTwo.w = 20;
    PlayerTwo.h = 100;
    PlayerTwo.cliping = &clip[0];
    PlayerTwo.yVel = 0;
    PlayerTwo.player = 2;
//pointers
    Game_Ball.paddle_pointer1 = &PlayerOne;
    Game_Ball.paddle_pointer2 = &PlayerTwo;
    score_P1 = &Game_Ball.score_P1;
    score_P2 = &Game_Ball.score_P2;
}

Game::~Game()
{
    SDL_FreeSurface(PlayerOne.sprite);
    SDL_FreeSurface(PlayerTwo.sprite);
}

void Game::events()
{
    Game_Ball.events();
    PlayerOne.events();
    PlayerTwo.events();
}

void Game::logic()
{
    Game_Ball.logic(delta.get_ticks());
    PlayerOne.logic(delta.get_ticks());
    PlayerTwo.logic(delta.get_ticks());
}

void Game::render()
{
    std::stringstream score_current;
    score_current << *score_P2 << " : " << *score_P1;
    score_message = TTF_RenderText_Solid(font, score_current.str().c_str(), color);
    SDL_FillRect(screen, &screen->clip_rect, SDL_MapRGB(screen->format, 0, 0, 0));
    apply_surface((SCREEN_WIDTH - score_message->w) / 2, 0, score_message, screen);
    if (Game_Ball.win == false)
    {
        Game_Ball.render();
        PlayerOne.render();
        PlayerTwo.render();
    }
    if (Game_Ball.win == true)
    {
        PlayerOne.render();
        PlayerTwo.render();
        SDL_Flip(screen);
        SDL_Delay(2000);
        set_next_state(TITLE);
    }
}

/*MAIIIIIIN*/
int main(int argc, char* args[])
{
    Timer fps;
    //init SDL
    if (init() == false)
    {
        return 1;
    }
    //load everything
    if (load_files() == false)
    {
        return 1;
    }
    delta.start();
    currentState = new Title();
    while (quit == false)
    {
        //Keystates
        Uint8 *keystates = SDL_GetKeyState(NULL);
        //handle state events
        while (SDL_PollEvent(&event))
        {
            currentState->events();
        }
        // do state logic
        currentState->logic();
        //timer reset
        delta.start();
        //change state if needed
        change_state();
        //render state
        currentState->render();
        if (SDL_Flip(screen) == -1)
        {
            return 1;
        }
        if (fps.get_ticks() < (1000 / FPS))
        {
            SDL_Delay((1000 / FPS) - fps.get_ticks());
        }
    }
    clean_up();
    return 0;
}

```

Hopefully this makes it clear the way I'm implementing the event handling.

# Answer
You may be dealing with keyboard ghosting, the phenomenon where certain keys cannot be pressed down simultaneously. This differs between different keyboards, but you can test it out in the link I've provided, which has an interactive program for testing key presses.

You may be able to fix this problem by finding different keys that can be pressed together, or using different devices or even multiple keyboards. You could also try more expensive keyboards; a lot of gaming keyboards advertise "anti-ghosting" features.
> 4 votes

# Answer
You need a keyboard with n-key rollover
> -3 votes

---
Tags: c++, sdl, keyboard
---


# Question
Title: Simulation of a two-masses connected by a rod 2D system
I'm working on a multitouch-based interface and I want to add some physical behavior to gestures (pan, zoom and rotation). I thought model the system like that:

* When a touch starts, a point mass is created.
* As the finger moves, I calculate it's velocity vector.
* When the touch ends, I suppose the mass is released and starts to move freely.

My problem comes when I have two masses (I don't need more than two masses to model this system):

The masses should act as if they were connected by a massless rod and, **optional**, they can slide along the rod with some coefficient of friction.

I attach a picture to explain the thing better.

I forgot almost all the physics I knew at college and now I'm a developer.

I know that at time t the masses have a position (x, y), a velocity and one or more forces or accelerations acting on it. And I want to know those values at time t+dt.

I would like to have some advice or approach to this problem. It's not about integrators or numerical analysis. My main doubt is about the rod constraint (keep the distance between masses) and the rotation movement.

# Answer
> 1 votes
You have only four independent co-ordinates to track:

* The location of the center-of-mass, as the vector (*x*, *y*);
* the separation of the two point masses as the scalar *d*; and
* the orientation of the masses about the center-of-mass, as the scalar *theta*.

plus their rate of change over time: (*Vx*, *Vy*), *v*, and *w*

Don't attempt to analyze any forces - just use the kinematics and apply linear impulses as you have described in your posting.

Apply all impulses applied to either mass directly to the center-of-mass as a change in its velocity; then recalculate the resultant changes in *v* and *w* by applying the each impulse to the appropriate point mass relative to the center-of-mass.

In this model the constraint of the rod is implicitly enforced by having every impulse to each mass also result in an overall rotation of the system.

---
Tags: 2d, physics, simulations
---


# Question
Title: Do I need a server to connect two players in a mobile game?
I would like to make a 2 players app game, where 2 players can compete with each other in real time.

If I want the player to be able to compete with the public (anyone who registered with my game able to compete with one another), do I need a server?

If I want the player to be only able to compete with his facebook friends, do I need a server?

Do I need a server at all in the first place, for 2 players game?

# Answer
> 3 votes
Yes, you'll need a server if you want to connect players together over the internet (Facebook friends or otherwise). Without a "meeting place" (your server) your players wouldn't have the information they need to connect with each other. In all likelihood, they won't be directly connecting with each other at all, it'll be far simpler to route the traffic through the server.

It's possible to not use a server if you're connecting players on the same wifi network.

# Answer
> 0 votes
Basically to connect one client to another at least one of them needs to know the IP address of the other one, the only way to do this is having both client connect to a server (which they know the ip address) and then the server can interchange the ip address between the two clients so they can connect directly.

If you don't want to develop your own server, unity provides some multiplayer services , including a matchmaking that I think it does exactly that, connects the two clients directly, making one of them act as the server.

---
Tags: unity, mobile
---


# Question
Title: Phaser.io with Socket.io - What should the Server calculate and what the Client?
I'm currently playing around with phaser.io and socket.io to create a really simple multiplayer.

For the beginning I created basic movement which is synched via socket.io. The clients are sending their positions to the server and the server broadcasts it to the other clients. This works fine, however I'm aware of the fact that every user could simply cheat by emitting wrong positions.

Exactly this is where I need some new ideas. I'd really like to use phaser because it is really helpful with all the animations and rotations etc. However, I kinda know I should calculate movements etc. in the backend - not in the client.

But is there a way to use phaser.io on a node server to run a game instance which then calculates the positions? Or do I need to build my "own game engine" in the backend?

An basic example would be: A player shots ( in a tank game for example ) towards another player. Using phaser only this would be very simple. But in a multiplayer i would now need to do the collision calculation on my own - right?

Any ideas ?

# Answer
What you can do is not to send to the server the game statuses(like positions), just the clients inputs.

So on client input (lets say that clientA press 'fire' button), you can send this event to the server ('fire from clientA'), then the server broadcasts the event to all clients and are the clients whom finally make the changes, with the Phaser engine (on\_client\_fire render the bullet... and the same thing for movement or whatever).

On this way you will also start dealing with latency.

**EDIT (with a practical example of what I meant):**

If, in your update loop, you have something like this in order to move the tank:

```
if (cursors.left.isDown ){
    tank.body.velocity.x = -400;
}

```

What I suggest is changing it with womething like this:

On client, first emit that the tank wants to move:

```
if (cursors.left.isDown){
    socket.emit("move_left");
}

```

Then, on server, listen for the move and broadcasts when it arrives:

```
io.sockets.on("connection", on_socket_connection);

function on_socket_connection(client) {
    client.on("move_left", function(){
        io.emit("move_left_from_server", client.id);
    });
}

```

And back on client, listen for the server event and finally change the velocity:

```
socket.on("move_left_from_server", move_left_from_server_function);

function move_left_from_server_function(id) {
    //assuming you have all tanks in an array...
    tank[id].body.velocity.x = -400;
}

```
> 1 votes

---
Tags: multiplayer, browser-based-games, phaser, websocket
---


# Question
Title: How to get a job as a game programmer/developer in AAA studios?
I have looked up and down on the internet and haven't really found the solution, or maybe I am just too confused to know the answer.

I love games and wanted to get into making them from a long time. I first started working with Unity and then realized that I could not see how this could help me in getting into AAA studios as all there job requirements had stuff that I didn't learn in the process. Then it felt like making a game engine would help me learn better what those studios want. But then that stuff was too overwhelmingly tough for me to actually get something competitive done. I did learn some things, but it was not a one man job. I then again decided to go into making games on a pre-existing engine, this time I took up Unreal Engine 4. But this time I have a better idea of what I want to do. I am interested in making game play logic, AI system, and on a side have fair bit of interest in modelling (not texturing) and animation. I may not be good at all this right now, but I have figured out what I have to do exactly, and on the side. Now again I did end up one some companies job page(Naughty Dog, Santa Monica and Sucker Punch) and I found myself in the sea of confusion and hopelessness, half of the time I couldn't figure out what the requirements.

So my question is, is learning how to get complex AI running in UE4, setting up some nice game play mechanics in UE4, and setting up a nice UI in UE4 and creating some models and animating them in Maya will be enough to get me a job at some of the AAA studios I mentioned?

I know I haven't done all the stuff I mentioned in depth, but I can't proceed without having a proper aim and path, the path can change in between but should lead me somewhere at least.

I will be thankful for any good advice.

Edit. I am not good at art, just in case.

# Answer
> 3 votes
Lower your expectations. Getting a job at a studio like Naughty Dog without having worked in the industry for quite some time is unrealistic. And don't try to become Jack of all trades unless you want to run your own one man indie studio. Try to focus on one specific area and master it. Then try to get a foot in the door by looking at smaller studios first.

# Answer
> 1 votes
Easy: working hard.

AAA Studios want people highly specialized in some specific areas, like model of environments or lighting.

# Answer
> 0 votes
Basically, every game mechanics programmer needs to know about 3D mathematics, and ability to program with engines/languages. So "get complex AI running in UE4, setting up some nice game play mechanics in UE4, and setting up a nice UI in UE4 and creating some models and animating them in Maya" can be enough to work at studios.

But in AAA studios, things can go a little bit different. They need not only those who can do above stuffs, but also the best ones - with experience and has a vital role in some released titles.

So this is my advice for you (and for me, too, since I found myself in you, even the path we experienced, the feelings we had when see an AAA studio's job requirements,...): find a job in a small studios - gain more experience. Then you will know what need to be done next.

---
Tags: jobs
---


# Question
Title: How "fake" do invented names of a football game have to be in order to avoid copyright infringement?
I know that real player names cannot be used in videogames unless the authorization (generally very expensive) has been given by the holders of the rights (players, teams etc.)

as explained here and here. There is a discussion here about possible sources that can be consulted in order to figure out whether you are infringing any copyright issue, but it does not say anything specific about my problem (at least as far as I understood it, given my poor comprehension and expertise on the matter).

*my question is very simple*: **is there any rule that determines the amount of difference (in characters, sound, length, phonological features, whatever) from a real name to a fictitious (or fake) name in order for the latter to be considered really fake?**

For example, if I created a football videogame in which there is a strong offensive midfielder that has Cristiano Ronaldo's features (with respect to characteristics, statistics etc. not physical appearance) how could I call this player to avoid copyright infringement?

Cristian Ronald? Cristo Romaldi? Christiano Ronnaldo?

there was a famous release of ISS PRO (football game) employing fake names - here's the list - that were very similar to real ones.

Is there a specific rule/law that says which is good and which is not?

# Answer
> 41 votes
> *I'm not a lawyer, this is not a legal advice site, this opinion is offered as is. You should consult with a lawyer to have a definitive answer.*

There are no specific rules that govern this.

The ultimate decision will be done by a judge in a court.

But you will not be able to get to that point.

What's most likely to happen is that the FIFA's legal team will send you a letter asking you to do whatever they want (it can range from a smooth 'change the names', to 'take down your game from the stores and give us all money made from it', to 'cease all game creation activities', etc).

They can send you that letter because you don't have money to defend against it in court. This would have cost them only 1000$, but it will be enough to scare you. Legal battles can be long and extremely expensive. They'll assume you don't want to go that path because they have more money that you do to prove them they're wrong.

In any case, it can cost you a lot of money, either in lawyer fees to defend yourself in court, or in money you'd have to pay them as 'compensations'.

---

I'd create original characters and not get inspired by real players.

# Answer
> 17 votes
While I am not licensed to provide legal advice, I can point out some important information regarding this topic to help you make an informed decision.

First, as to the question of whether there have been suits like this before, there have been *similar* lawsuits. The NCAA Athletes v EA lawsuit comes to mind:

http://www.usatoday.com/story/sports/college/2015/11/07/ncaa-college-ea-sports-lawsuit-payouts/75367410/

The details are slightly different, but I assume it's safe to guess that EA has greater legal and financial resources at their disposal than you do, and they still lost to the tune of US$40 million.

I can understand the drive to make stats and names and such similar, but it's not worth it. Make a great game that stands on it's own without having to stand on the backs of real people in the sport. You'll be much, much safer.

You can look up information on the *Rogers Test* that may be useful, though it's more for copyright and trademark (though personal names can, ostensibly, be part of a trademark).

# Answer
> 7 votes
IANAL.

Why attribute the creation of names to a human at all? Another option is to have the names be randomly generated from a list of the first and last names. If you get a collision (first name, last name, physical attributes, position) then it is provably coincidental and unintended. You'll need to check, but IMO that makes it less dangerous.

Then if there is a complaint you could theoretically just remove the first or last name from the list and it won't happen again.

Note: The generation needs to be live and different for each player. You can't just roll the dice and use "Reggie Bush" with a similar likeness because that's what came up for you.

Second Note: This may require additional design and testing of the system/stats etc in order to ensure that the different combinations work, whereas a static system may require less testing in this regard.

# Answer
> 4 votes
The matter is up to a court, more than likely even multiple courts if you release the game in multiple jurisdictions.

In practice, either nothing happens, or you will receive a letter that will ask you to change the names. The letter will also threaten that you'll have to pay their lawyers' bills if you don't comply. The letter may also ask for a percentage of your proceeds so far, and it may also ask for a lump sum as well, even if you comply with their other demands. You may receive multiple letters with some of them being scams and others being real.

If you go after famous football/soccer players you are pretty much guaranteed to receive several such letters, because there are multiple organizations involved that take trademark protection very seriously.

If you ignore the letters and don't pay a lawyer to represent you in court, chances are very high that you will have to pay damages and cover some part of the other party's lawyer fees.

---

In short, if you do this, you will end up needing a lawyer. You save money by talking to the lawyer now, instead of after the release.

# Answer
> 2 votes
In cases like these the *intent* turns out to play a role in lawsuits, and it's obvious from this question that your *intent* is to portray existing people within your game.

In other words, you could change a lot and it might not be enough since your stated desire is to skirt the law while still making sure your customers experience a game constructed around existing people.

As such, I suggest you abandon the idea of making stats and names that specifically match existing people, and instead create characters from scratch. Thoroughly document the process you use to generate characters (randomizer with some tweaks by a person experienced in game balance but not familiar with the sport's players, for instance) because inevitably some of the random characters will appear to some to be copies of existing people. In other words, even if you purposefully avoid building characters that remind people of existing players, you'll find that humans, being adept at finding similarities, will make such connections anyway. This is good for your game, but means you may need to work harder to make sure you can prove in court that your process precludes that possibility.

If your game is not marketable without real-life characters, then you should reconsider whether to pursue it at all.

# Answer
> 0 votes
Use mocking names. Then at least if they sued you you'd get the satisfaction of asking if they really think that *Cretino Ritardo* makes people think of them.

---
Tags: copyright
---


# Question
Title: Is Rete an efficient algorithm to implement a system that allows NPCs to make decisions based on their world views and inner state?
I'm developing an AI "mind" engine, which allows NPCs (non playable characters) to think and make decisions, based on their view on the game world, and their own inner states (in the future I may add the NPCs' memory - long or short term - if necessary).

Given those inputs, they can give a list of possible actions, with possibilities, for example with a rabbit:

* World view: a wolf (enemy) is 100m away, the carrot is 40m away.
* Inner state: it is hungry, it has big courage and can take risks.

So the expected type of output will be the actions that the rabbit can do:

* Runs away: 40%
* Bites one bite of carrot then run: 80%
* Keep eating and don't give a damn about the wolf: 20%

Based on the desired actions, it will give its decision: which action to take. But that's future works, now I'm concentrating on how to produce that list of actions.

I read the chapter 5, book Artificial Intelligence for Games, Ian Millington and I found the Rete algorithm, which allows match a rule sets to a given database - in my case, the database will be the combination of the NPC's world view and inner state. It seems suit well with my needs, but after making a search, I can see very few (actually, zero) projects that use this algorithm.

Is it so heavy and slow for computer games? Or does it have any more drawbacks that can't be widely used?

# Answer
> 1 votes
It's trivial enough to determine actions via a fast formula (including bitwise ops) or a LUT (lookup table which could be a dense array, sparse array or hashmap), given the available info coming in via AI senses. Combine with FSM and you'll have a simpler, quicker, more debuggable system.

I don't think you really need inference, here! You could instead demand various arguments to the formula and just leave unknown ones as defaults (e.g. zero) such that they don't contribute (much) to the end result in terms of actions to be taken by the AI.

I suppose one benefit you would get from Rete is the ability to "remember" without a full recalc each time... but I doubt that's something to be concerned about given your relatively tiny datasets. Bear in mind that any graph structure like Rete's tends to be much slower than dense or even sparse arrays of equal node count, as CPU cache benefits greatly by linear alloc / read-ahead as opposed to the random access style that dynamically-allocated graph nodes demand.

---
Tags: ai, npc
---


# Question
Title: Is Unity + Scala.js possible or even makes sense?
I never actually used Unity (yet) and I have no possibility to check anything now, but I'm thinking about Unity for my project. I actually know C# (and hate it for some unimportant reason) and I think I'm able to learn JS or UnityScript, but I just want to use a language I know and love - Scala.

There is Scala.js - a tool that compiles Scala code to JS code. And i'm thinking: is it possible to write Scala code in some IDE (Intellij), compile it to JS code and load into Unity? And if it IS possible, what difficulties may I encounter? Does this idea even makes sense, or should I forget it, use C#/Learn JS/UnityScript or just search some Scala game frameworks?

# Answer
It does not seem possible, because you will not have access to essential classes and namespaces provided by Unity while coding in Scala.

I suggest you to learn C# and use Unity. Because it doesn't seem like there are enough community out there using Scala to develop games, which makes the whole process difficult.
> 1 votes

# Answer
The Unityscript scripting language is *inspired* by Javascript but has some notable syntactical differences. So trancompilation with tools designed for normal Javascript won't work. And when it *would* work, it wouldn't be a very convenient way to work because the integration into the normal Unity workflow would be quite bad.

When you want to work with Unity you should really learn C# or Unityscript.
> 0 votes

---
Tags: unity
---


# Question
Title: libgdx - Should I use OOP in ECS framework?
For example I have OOP class of Bullet and I have created the pool and factory. Should I convert it to componet based? Like BulletComponent, then handle by BulletSystem? by the way I'm using Ashley ECS framework.

# Answer
> 0 votes
> DISCLAIMER: I am still a newbie when it comes to ECS so do not consider the following as a definitive answer

To me it seems that a bullet should be an entity instead of a component since it probably has to be rendered (unless you're taking the hitscan route) and has to interact with the world a.k.a. physics.

As for pooling, it depends on what has to be pooled. I'm assuming that for rendering you're using the same texture for all bullets so the only thing that would have to be pooled is probably the physics object which I would handle within the physics system itself. However you could also create a separate `BulletPoolSystem` if you wish, it's completely up to you.

---
Tags: java, 2d, libgdx, oop
---


# Question
Title: What's the "appLinkUrl" parameter in the "AppInvite" method for?
I'm trying to figure out what should I assign the `appLinkUrl` parameter of `FB.Mobile.AppInvite` method. In documentation it says:

> The AppLink URL to identify your app and also used for deep-linking

Should i pass my Play Store link to it?

Thanks in advance.

---

The documentation page for FB.Mobile.AppInvite: https://developers.facebook.com/docs/unity/reference/current/FB.Mobile.AppInvite

# Answer
> 3 votes
In simple words, it is modified url to redirect user to your app via facebook app invite. For example if you have created Android Facebook app you want to use facebook app invite through your game, then go to this url and in **Modify an existing App Link URL?** field enter your existing Facebook id in this format: **https://fb.me/FACEBOOK\_APP\_ID** that will provide you the modified url in same format. That would be the url that you can use for App Invite.

**NOTE:** For example if you send invitation from Android. Then receiver can only see your invitation in the same device (Android in this case).

# Answer
> 3 votes
It is NOT play store link or your web page link. It is a link to specially setup page that must response with applink format, see an example in App invite documentation. Looks like this:

```
<html>

<head>
  <meta property="al:ios:url" content="couchinapp://invite_from_fb?referral=123456789" />
  <meta property="al:ios:app_store_id" content="123456789" />
  <meta property="al:ios:app_name" content="Couchin'" />
  <meta property="al:android:url" content="couchinapp://invite_from_fb?referral=123456789" />
  <meta property="al:android:app_name" content="Couchin" />
  <meta property="al:android:package" content="com.mycompany.couchin" />
  <meta property="al:web:url" content="http://www.couchinapp.com/myapp.html" />
</head>

<body>
  Couchin App Link
</body>

</html>

```

If you pass something else or another page that has wrong format, it will trigger "Applink URL error" upon inviting people. You can setup this kind of page on your own server or let FB generate it for you by hosting app link on Facebook

## Advanced technique:

And actually, this deep link string will also reach the another party that you are inviting, says B, when B click on notification on his Facebook feed. If the URL looks like `-ttps://fb.me/123456789`, you can append query string on A side like:

```
-ttps://fb.me/123456789?from=A&reward=100&couponcode=1234

```

Which on B's app side, can process this URL via "deep link" or "deferred deep link", so B can see `from=A&reward=100&couponcode=1234` part and act according to it. It is quite complicate process so I will leave that work for reader to search.

---
Tags: unity, facebook, google-play
---


# Question
Title: Unity random.range value not same as last value
Quick one,

Currently using Unity Random.Range to set a var with the value of an enum state.

State has 4 possible values, up, down, left,right. I call it like :

```
currentState = (StateType)Random.Range(0, 3);

```

This gets set at certain conditions.

My issue is though I don't want the new setting to be the same as the current one.

I have taken a look at the random.range on the API but haven't found anything useful.

Is there an easy way to basically say "randomize but not the same as the current state"

EDIT:

Currently im using a while loop.

```
while (currentState == LastState)
{
    currentState = (StateType)Random.Range(0, 3);
}

```

Is there anything i can do to remove the while loop?

# Answer
Yes, choose from range 1 unit smaller and if the result is greater or equal to current, add 1 to it.

```
var newState = Random.Range(0, (3 - 1)); //choose from range 1 smaller
currentState = (StateType)(newState >= (int)currentState ? newState + 1 : newState);

```

---

Edit: if you like really fancy syntax, you can also make it generic extension to `enum`s:

```
public static void Randomized<T>(this T except) where T : struct, IConvertible
{
   if (!typeof(T).IsEnum) throw new ArgumentException("T must be an Enum type");

   var values = Enum.GetValues(typeof(T));
   int @new = Random.Range(0, values.Length - 1);

   return (T)values.GetValue(@new >= ((IList)values).IndexOf(except) ? @new + 1 : @new);
}

```

from now on you can call `Randomized()` on any enum type variable:

```
//declared somewhere in your class
private StateType stype = StateType.Anarchy;
// ...
//when you want to randomize it just do:
stype = stype.Randomized();

```
> 4 votes

# Answer
Why not just get a random state from the enum and place in the variable. Use something like this.

```
private static System.Random _Random = new System.Random(Environment.TickCount);

 public static T RandomEnumOf<T>(int exclusion)
            {
                if (!typeof(T).IsEnum)
                    throw new InvalidOperationException("Must use Enum type");
                Array enumValues = Enum.GetValues(typeof(T));
                return (T)enumValues.GetValue(_Random.Next(enumValues.Length - exclusion));
            }

```

Usage : `EnumType enum = RandomEnumOf<EnumType>(0);` You can modify the exclusion param to fit your criteria.
> 1 votes

# Answer
In this case, I would just keep a list of random values to pick from.

Have some sort of index to use:

```
 int[] Range = new int[Max-1];

```

Then have a method to update this index when required:

```
int idx = 0;
for (int i = 0; i < Max; i++)
{
    if (i == currentValue) continue;

    Range[idx] = i;
    idx++;
}

```

Then use this for your random:

```
int value = Range[Random.Range(1, Max-1)];

```
> 0 votes

---
Tags: unity
---


# Question
Title: Why does Unity allow me to use GameObjects created from non-existent prefabs?
I have code similar to the following in a Unity project. I was trying to shoot a projectile when spacebar was hit, but a projectile wasn't appearing. I found out the problem was caused because I moved my bullet prefab to `/Assets/Resources/prefabs/bullet.prefab`. Bullets started appearing upon updating the string in `Resources.Load`, but I then questioned why I didn't encounter some sort of runtime error when I tried to perform operations on the non-existent bullet.

```
if (Input.GetKeyDown(KeyCode.space))
{
    // Bullet is actually in /Assets/Resources/prefabs/bullet, so this won't find it.
    var bullet = Resources.Load("bullet") as GameObject;
    bullet.transform.position = new Vector3(0, 0, 0);
    Instantiate(bullet);
}

```

Could someone please tell me why Unity doesn't throw an exception or any sort of runtime error when loading a resource that doesn't exist? Maybe there are exceptions/recoveries happening but I just didn't notice because the game updates much faster than I can push the space bar?

# Answer
Either you weren't seeing the error, or you were experiencing a bug.

The documentation for `Resources.Load` says:

> Returns the asset at path if it can be found otherwise returns null.

I'd expect you'd have a null pointer exception with the second line in your code block `bullet.transform.position`.

Since you weren't getting a null pointer, apparently `Resources.Load` was finding *something*. It could have been because you needed to rebuild, or you have another prefab named 'bullet' or some other reason.

If you didn't have the position code there before, `Instantiate` would produce an error saying something like "The thing you want to instantiate is null". This would just be an error message in the console, so if you're not using to looking for errors there, you might have missed it.
> 1 votes

# Answer
If you try to use a variable or something that is null, Unity will print an Error to its console saying something along the lines of:

> "Object reference not set to instance of an object"

At which point Unity will breaks out of the method it is running and the exception is passed to the calling method. What this means in practice is that if you cause an exception to be thrown in the Start(), Update(), or pretty much any other method fundamental to MonoBehaviour, Unity will end up disabling the script, which prevents any of its other code running and potentially causing a fatal crash.

This can cause some strange behaviours when you are trying to have multiple objects interact and one or two of them aren't moving or something due to a thrown exception. But it's good because it means that you have the option of continuing on and testing other things, further investigating in that session to see what might be causing the issue, or just stopping and restarting the game to replicate the issue.

And most importantly, it means Unity itself doesn't crash, which is a nice bonus.

TL;DR - Unity DOES throw an exception, it just turns into a Debug.LogError.
> 1 votes

---
Tags: unity, assets, loading, exceptions
---


title: MMORPG networkconnection like Vindictus

text:
# Question
Title: MMORPG networkconnection like Vindictus
to be honest, I like to make "small" MMORPG with my frends. We are 4 guys and are using Unity3D and Blender. I am a Programmer and I am using Eclipse. I know, it's silly to start a Question like "How to make an MMORPG like WOW". We want to make a very small MMORPG based on 4 levels (1 Town, 2 fields, 1 Dungeon). In the Dungeon you can join with max. 8 Person. In the fields you don't have to see other players. The one thing, I like to have is that in the Town you should be able to see all people who are in the town.

I never did network programming. Because of that, I have to hire sombody who would do the network programming.

Now my Question: How much does it costs, to make a game let you see each other in the town and to have a Texteditor who they can chat with each other. They can't trade and they can't do anything with each other in the Town. In the dungeon they have a Texteditor too and they can all hit the enemy and the enemy lose health according to the last hit of player x.

Sorry for my bad english. I hope I have explained it good.

**I may have also another Question.**
How much do you think will cost the server for such a game? Unity Cloud would want for round about 500 600€. I dont thinks, that this is the normal pricing.

Thank you all and I hope you can help me. :)

# Answer
While there is no way to answer your question in terms of cost with the information you've given, you may be interested in looking at Unity's Unity Multiplayer which is free for up to 20 concurrent players.

Also available is Amazon Lumberyard, which integrates with Amazons GameLift, which also has a free tier.

The price will increase as the number of player increases, but my advice would be to start small on a free tier and work your way up. If you reach more than 20 players then you can look to grow, but until then don't pay for bandwidth you don't need.

Both of these are good starting points, and hide a lot of the complicated networking problems for you, so you won't necessarily need a network programmer (which, for such a small game won't be worth the expense). Be aware that making an MMORPG is incredibly complicated and you would likely be better off with a smaller, easier to manage project to test the water with these products (such as a small co-op game)
> 0 votes

---
Tags: unity, software-engineering, mmo, unity-networking, costs
---