title: LibGdx Bluetooth Game with Android

text:
# Question
Title: LibGdx Bluetooth Game with Android
I've created a simple 2d platformer with libGdx and box2d and i wanted to add some kind of a multiplayer to it.I found an implementation over the internet that uses bluetooth with libGdx and i've tried to adapt it to my game but whenever i start the app it gives me this:

```
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.mygdx.game, PID: 15414
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mygdx.game/com.mygdx.game.AndroidLauncher}: android.view.InflateException: Binary XML file line #24: Binary XML file line #24: Error inflating class fragment
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2955)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3030)
                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
                      at android.os.Handler.dispatchMessage(Handler.java:105)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6938)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
                   Caused by: android.view.InflateException: Binary XML file line #24: Binary XML file line #24: Error inflating class fragment
                   Caused by: android.view.InflateException: Binary XML file line #24: Error inflating class fragment
                   Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'com.badlogic.gdx.files.FileHandle com.badlogic.gdx.Files.internal(java.lang.String)' on a null object reference
                      at com.badlogic.gdx.graphics.g2d.TextureAtlas.<init>(TextureAtlas.java:211)
                      at com.mygdx.game.screens.PlayScreen.<init>(PlayScreen.java:60)
                      at com.mygdx.game.views.fragment.GdxFragment.onCreateView(GdxFragment.java:31)
                      at android.support.v4.app.Fragment.performCreateView(Fragment.java:2074)
                      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1061)
                      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1264)
                      at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1366)
                      at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2409)
                      at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
                      at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:374)
                      at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:33)
                      at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:75)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:780)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
                      at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:280)
                      at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                      at com.mygdx.game.AndroidLauncher.onCreate(AndroidLauncher.java:77)
                      at android.app.Activity.performCreate(Activity.java:7174)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2908)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3030)
                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
                      at android.os.Handler.dispatchMessage(Handler.java:105)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6938)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Application terminated.

```

This is the main activity:

```
<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<fragment
    android:name="com.mygdx.game.views.fragment.GdxFragment"
    android:id="@+id/fragment_libgdx"
    android:layout_height="0dp"
    android:layout_width="fill_parent"
    android:layout_weight="1"/>

<fragment
    android:name="com.mygdx.game.views.fragment.BluetoothFragment"
    android:id="@+id/fragment_ui"
    android:layout_height="0dp"
    android:layout_width="match_parent"
    android:layout_weight="0.3"/>

```

I've also tried to build, rebuild the project but it's still giving me the same exception. Do you guys know where the problem comes from? i don't really understand

# Answer
It looks like your **libGDX** `AndroidApplication` isn't initialized. Make sure to call `initialize` in `onCreate` in your `AndroidLauncher` class.
> 1 votes

---
Tags: libgdx, multiplayer, bluetooth
---


# Question
Title: Which of these two codes are 'better'? Making a local variable or a class variable?
Im making more games and asking more stupid questions.

Hopefully this one is very brief. I'm making a very basic class which just moves a Player object by applying force to a rigidbody, but it got me wondering, should I be making a class reference to the rb or just a local variable inside Update every frame? (bearing in mind it already exists in the Monobehaviour.GameObject unity parent class).

I'm wondering if doing many local variables would slow down the loop as a whole(by local I mean inside the function itself and not at the top of the class - hope im using the correct term) .

Here is what I mean, the two ways I was thinking of doing it:

```
public class Player : MonoBehaviour {

private void FixedUpdate()
{
    Rigidbody rb = GetComponent<Rigidbody>();

    float v = Input.GetAxis("Vertical");

    rb.AddForce(v * rb.transform.forward * Const.walkForce);
}
}

```

or...

```
public class Player : MonoBehaviour {
Rigidbody rb;

private void Awake()
{
    rb = GetComponent<Rigidbody>();
}

private void FixedUpdate()
{
    float v = Input.GetAxis("Vertical");

    rb.AddForce(v * rb.transform.forward * Const.walkForce);
}
}

```

# Answer
> 26 votes
In general, I've found that you should scope data as narrowly as possible to start with and broaden the scope as you discover you need to. That means if you *can* make it a local variable instead of a member, you should probably start there.

This is because a narrower scope reduces the number of places in the code where you must reason about that data, and thus reduces the number of places you can reason about it incorrectly (which leads to bugs).

Actually *declaring* local variables alone is never going to practically be a performance concern: they're cheap, and modern compilers may even optimize "extras" out.

Initializing them may be a concern; in your case your rigid body is looked up every time via `GetComponent`, which has some non-zero cost. If you know that the rigid body component will *not change* for this particular game object, you can look it up once and store the result in a member variable and avoid a small bit of per-call overhead.

It's unlikely that per-call overhead is going to be significant in this one instance, but over time doing this for many components may add up. You'd want to apply a profiler to be sure.

So, to summarize: in general, default to making things as local as possible, but in this case it's probably reasonable to make `rb` a member so you can perform the lookup once in `Awake` and avoid having to do it every `FixedUpdate` call.

# Answer
> 2 votes
Josh Petrie's answer is very good - here's a complementary perspective.

When you work with code which you understand the domain of fairly well, you can scope variables to where they make sense.

For instance if I have a `Person` class with a `waveGoodbye` method, it's possible that my class didn't have a `hand` object before and so I could declare it locally in `waveGoodbye`. Now here it's obvious a person has a hand so you might naturally declare it as a member of `Person` without thinking about it, but the same issue applies.

If you declare `hand` locally then later you might add a `karateChop` method which also requires a hand. This is when declaring variables locally can become problematic - because junior developers often fall back to copy/pasting the declaration from `waveGoodbye` and now you have the same concept located in two spots. Any changes to `hand` then need to be modified in both places and thus begins a ~~ant~~ bug hill.

So all in all,

1. If you're confident in the placement of your declaration, scope it to where it makes sense to.
2. If you're not confident, then start local and make sure to refactor when you get a whiff of code reuse.

Edit: Oh and don't make the same mistake I have of spending too much time figuring out where to scope your declarations. It's difficult to understand the structure of your data up front, and as you write your code the structure has a way of revealing itself.

---
Tags: unity, c#, game-loop
---


title: Coroutine stops when Time.timeScale = 0

text:
# Question
Title: Coroutine stops when Time.timeScale = 0
I have a coroutine that smoothly changes a variable in my UI, but when I pause the game, the coroutine pauses too. How can I fix that?

Code:

```
using UnityEngine;
using System.Collections;

public class HUDController : MonoBehaviour {
    public void PauseGame() {
        FreezeTime();
        StartCoroutine(ShowPauseMenu());
    }

    private void FreezeTime() {
        Time.timeScale = 0;
    }

    private IEnumerator ShowPauseMenu() {
        var pauseMenuCanvasGroup = GameObject.FindWithTag("PauseMenu").GetComponent<CanvasGroup>();
        var alphaValue = 1f;
        var velocity = 0f;
        var time = 0.15f;

        while (!Mathf.Approximately(pauseMenuCanvasGroup.alpha, alphaValue)) {
            pauseMenuCanvasGroup.alpha = Mathf.SmoothDamp(pauseMenuCanvasGroup.alpha, alphaValue, ref velocity, time);
            yield return null;
        }

        pauseMenuCanvasGroup.alpha = 1; // Since float is not accurate, manually set the alpha to 1
        pauseMenuCanvasGroup.interactable = true;
    }
}

```

# Answer
> 13 votes
This is sure to happened because `Mathf.SmoothDamp` uses `Time.deltaTime` in default calculation. When you set `Time.timeScale = 0` then `Mathf.SmoothDamp` won't give the expected value but only first value, repeatedly.

You can further verify by printing alpha value to console, print it in your `while` loop so that you can confirm it by the unlimited logs of same value.

Here is the Documentation on Mathf.SmoothDamp.

You can fix this by passing your own deltaTime to keep it from using its default `Time.deltaTime`. Just add one more parameter to the end of the call:

```
pauseMenuCanvasGroup.alpha = Mathf.SmoothDamp(
  pauseMenuCanvasGroup.alpha,
  alphaValue,
  ref velocity,
  time,
  1000,          // <-- Fifth parameter Optionally allows you to clamp the maximum speed.
  1.0f/30.0f);   // <-- Add a sixth parameter representing your framerate.

```

You can use a function that measures realtime elapsed instead of a constant, if your rendering framerate is variable.

# Answer
> 0 votes
I had this problem and the situation was like this, and **I SOLVED IT**. User presses the pause button then some objects goes off (these objects has couroutine(s) ). THIS IS THE PROBLEM. **I must not turn off those game objects**. The coroutines working fine while the game object is on and when you turn them off every thing is going to be mess.

---
Tags: unity
---


title: HTML5 Canvas - Drawing with Floats

text:
# Question
Title: HTML5 Canvas - Drawing with Floats
I'm trying to implement a game where you have car moving along a line in HTML5 Canvas. Using a little bit of trigonometrie I managed to get the right x and y coordinates to add to the coordinates of my image each frame to get to the end of the "line". Now the problem is, the image I use for the car starts to stutter in the process of rendering. The problem has to be the values I'm adding. (first I thought the problem would be the render loop but when using the render loop from paul irish the same problem occurs) My question is, how can I use floats in context.drawImage(img,...) smoothly?

What I tried was rounding the values where the image should move to (e.g. context.drawImage(img, Math.round(car.x), Math.round(car.y))) but this doesn't work also.

simple code example to demonstrate the issue: (using a simpler loop, but like I said, the problem isn't the loop)

How it looks:

Here is the whole thing:

```
var canvas = document.getElementById("canvasID");
var context = canvas.getContext("2d");

var car = new Car(20,10);
var carImg = new Image();

carImg.src = "https://i.stack.imgur.com/L2XQW.png";
function Car(x,y)
{
  this.x = x;
  this.y = y;
}
Car.prototype.advancePosition = function(x,y)
{
   this.x = lerp(car.x, car.x + x, 1);
   this.y = lerp(car.y, car.y + y, 1);
}
 function update()
 {
   car.advancePosition(0.91,0.4);
 }
function lerp (start, end, amt){
  return (1-amt)*start+amt*end
}
function render()
{
  context.beginPath();
  context.clearRect(0,0, canvas.width, canvas.height);
  context.drawImage(carImg, car.x, car.y);
  context.closePath();
}

window.requestAnimFrame = (function(callback) {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame ||                    window.mozRequestAnimationFrame|| window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
        function(callback) {
          window.setTimeout(callback, 1000 / 100);
        };
      })();

(function mainLoop(){
  requestAnimFrame(mainLoop);
  render();
  update();
})();
```

```
#canvasID
{
    z-index: 1;
    background: #eee;
    display: block;
    vertical-align: middle;
    margin: 0 auto;
    z-index: 1;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    position: absolute;
    -webkit-transform:translateZ(1);
}
```

```
<html>
  <head>
    <meta charset = "utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>test</title>
  </head>
  <body>
    <div class = "canvas_wrapper">
      <canvas id="canvasID" width="500" height="450">Canvas not supported, please update your browser</canvas>
   </div>
    <script src="main.js"></script>
  </body>

</html>
```

I would be happy if someone could help me out

Thanks

edit: Tried the suggestions from the comments but nothing worked.

# Answer
> -1 votes
Just to clarify if your problem is the stuttering movement of the sprite then you should try using a Lerp (Linear Interpolation) to move smoothly between the current (value) position and the next.

```
 //start value (current posistion),
 //end value (next position)
 //time (amount of time it will take to reach end value
function lerp (start, end, amt){
  return (1-amt)*start+amt*end
}

```

This function from the codepen link (not my own just googled it) should hopefully do the job.

Something like

```
var carX = lerp(car.x, 0.91, 0.1);
var carY = lerp(car.y, 0.4, 0.1);
car.advancePosition(carX , carY );

```

It might also be a good idea to move the Lerp inside your advancePosition function.

```
Car.prototype.advancePosition = function(x, y) {
 //no += here as the value is being set to the value returned from the lerp on each update and not added on each time
 this.x = lerp(this.x, this.x + x, 0.101);
 this.y = lerp(this.x, this.x + x, 0.101);
}

```

If you can prove a barebones example of the problem I may be able to help you with it.

Are you using any framework for this?

https://en.wikipedia.org/wiki/Linear\_interpolation

https://codepen.io/ma77os/pen/KGIEh

---
Tags: javascript, html5, html-canvas
---


title: Move ball based on player angle

text:
# Question
Title: Move ball based on player angle
I am trying to program a simple football game for practice purposes. I am trying to kick the ball forward based on the players position he came from. I found this question about moving a ball by applying a force, but it doesnt help me since it's for Unity and C# and they don't provide any logic on how to do that but only methods working for Unity and C#.

Here I have made an image to explain what I mean if it wasn't clear yet:

Logic and/or Java code is requested.

Thanks in advance.

# Answer
Here's how I would do it:

On collision, get the position vector of the player and the position vector of the ball.

Position vector ball - position vector player = the direction the ball travels in.

Divide the vector by the magnitude of the vector to get the unit vector (I'm not sure about Java, but C# Unity has a built-in method for this).

Finally multiply that vector by some constant (e.g. kicking strength). Set the ball's velocity to that vector and it should work (not super realistically, but good enough for anyone asking this question).

I don't have experience with Java, hence the lack of code, but the above should be a general solution for just about anything.
> 1 votes

# Answer
I don't know what technology you are using but I can propose something :

Save the position from the last frame in a variable so that you have a vector formed by this point and the position in the current frame which is the vector you will use to move the ball

```
//Called each frame
Update()
{
    ball.move(Vector(lastPosition,this.position) * speed)
    lastPosition = this.position
}

```
> 1 votes

---
Tags: java, physics
---


# Question
Title: How can I rotate the cube left and right?
I want to rotate a cube left and right with that:

```
using UnityEngine;

public class PlayerMovement : MonoBehaviour {

    private Vector3 offset;
    public GameObject player;
    public GameObject center;
    public GameObject Left;
    public GameObject Right;
    public int step = 9;
    bool input = true;
    public float speed = 0.01f;

    void Update()
    {
        if(input == true)
        {
            if (Input.GetKey("a"))
            {
                StartCoroutine("moveLeft");
                input = false;
            }        }
        if (input == true)
        {
            if (Input.GetKey("d"))
            {
                StartCoroutine("moveRight");
                input = false;
            }
        }
    }

    IEnumerator moveLeft()
    {
        for(int i = 0; i < (90/step); i++)
        {
            player.transform.RotateAround(Left.transform.position, Vector3.forward, step);
            yield return new WaitForSeconds(speed);
        }
        center.transform.position = player.transform.position;
        input = true;
    }

    IEnumerator moveRight()
    {
        for (int i = 0; i < (90 / step); i++)
        {
            player.transform.RotateAround(Right.transform.position, Vector3.back, step);
            yield return new WaitForSeconds(speed);

        }
        center.transform.position = player.transform.position;

        input = true;
    }
}

```

and the problem is when I press a and d cube move left or right but + 0.5 up.

---

I also have tried this update method, but now it turns only on the y rotation axis:

```
public float rotationSpeed = 10f;
public GameObject player;

void Update()
{
    if(Input.GetAxis("Horizontal") < 0)
    {
        player.transform.Rotate(
            0,
            Input.GetAxis("Horizontal") * rotationSpeed * Time.deltaTime,
            0);
    }

    if (Input.GetAxis("Horizontal") > 0)
    {
        player.transform.Rotate(
            0,
            Input.GetAxis("Horizontal") * rotationSpeed * Time.deltaTime,
            0);
    }
}

```

# Answer
> 1 votes
I've done something similar. As isammour mentioned, use Input.GetAxis. As for why it's 0.5 up, that has to do with your RotateAround point of rotation. The easy way to solve it would be:

```
player.transform.RotateAround(Right.transform.position - new Vector3(0, 0.5, 0), Vector3.back, step);

```

or to work with other cube sizes:

```
player.transform.RotateAround(Right.transform.position - transform.localScale.y / 2, Vector3.back, step);

```

If you want to use the orientation of the phone to determine the input, I recommend you start here: https://unity3d.com/learn/tutorials/topics/mobile-touch/accelerometer-input or perhaps ask another question.

Edit:
full code for what I did, but I'm a fairly novice programmer and recommend you don't copy this in its entirety, it's probably quite flawed.

```
public float rotateSpeed;
private Vector3 turnPoint;
private float degX;
private float degZ;
private float direction;

private void Start()
{
    degX = 0; // As far as I know, it defaults to 0 without declaration, so this 2 lines aren't necessary
    degZ = 0;
}

private void FixedUpdate()
{
    Turn("Horizontal", 1, 0, Vector3.back, ref degX);
    Turn("Vertical", 0, 1, Vector3.right, ref degZ);
}

private void Turn(string button, int x, int z, Vector3 axis, ref float deg)
{
    if (Input.GetButton(button) && degX == 0 && degZ == 0) // So that it only turns in one direction at once
    {
        direction = Input.GetAxisRaw(button); // Direction needs to be stored for future use
        turnPoint = transform.position + new Vector3(0.5f * direction * x, -0.5f, 0.5f * direction * z); // Location of edge
        transform.RotateAround(turnPoint, axis, rotateSpeed * direction); // Turn around the edge
        deg += rotateSpeed * direction; // How much it has turned so far
    }
    if (deg != 0) // If the full rotation has not yet been made, repeat
    {
        transform.RotateAround(turnPoint, axis, rotateSpeed * direction);
        deg += rotateSpeed * direction;
        if (deg % 90 == 0) // % is a failsafe, deg should ideally be 90 or -90
        {
            deg = 0;
        }
    }
}

```

The way I've done it has it as a method. For now we can just ignore different scale cubes. The parameter button is either "Vertical" or "Horizontal", for now since you're working in 2 dimensions, you can just use "Horizontal" (or the accelerometer input, which I'm not sure how to use). Parameters x and z are used to locate the edge of the cube, but I feel like there's a better way of using this. Axis is just to determine direction of rotation.

# Answer
> 0 votes
You can achieve this without using Couroutines, for example in your case you want to rotate left or right according to the player input.

So you should use Input.GetAxis()

```
if(Input.GetAxis("Horizontal") != 0)
{
    player.transform.Rotate(0,Input.GetAxis("Horizontal") * rotationSpeed * Time.deltaTime,0);
    player.transform.Translate(Vector3.forward * movementSpeed * Time.deltaTime);
}

```

Note that the value of **Input.GetAxis()** will be in the range -1...1

> \<0 is for "a" button
>
> \>0 is for "d" button
>
> =0 When no input

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


# Question
Title: Issue importing TileMaps/TileSets in Monogame.Extended 1.0
I've just started coding my first ever videogame using Monogame/Xna. I've reached a point where I would like to start editing maps and importing them into my game using the program Tiled. After reading through the tutorials for Monogame.Extended, I was able to install version 1.0 using NuGet commands, and configure the content pipeline tool references accordingly. Right now, my packages file looks like this:

```
<packages>
<package id="MonoGame.Extended" version="1.1.0" targetFramework="net45" />
<package id="MonoGame.Extended.Content.Pipeline" version="1.1.0" targetFramework="net45" />
<package id="MonoGame.Extended.Graphics" version="1.1.0" targetFramework="net45" />
<package id="MonoGame.Extended.Tiled" version="1.1.0" targetFramework="net45" />
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net45" />
</packages>

```

And Content.mgcb looks like this:

```
#-------------------------------- References --------------------------------#
/reference:..\..\packages\MonoGame.Extended.Content.Pipeline.1.1.0\tools\MonoGame.Extended.Content.Pipeline.dll

```

I have a basic map \[Orthographic\] that is 64 x 64 tiles of size 32 x 32. The content manager allows me to import both the Map.tmx and Tileset.tsx into the project. However, it will fail to compile with one of two errors:

1) If there is a Tileset.tsx file in the Content Manager:

```
Couldn't find a default importer for 'C:/Users/*****/source/repos/HeavyMetalMachines/HeavyMetalMachines/Content/maps/Test.tsx'!

```

2) If there is **only** Map.tmx file in the Content Manager:

```
DirectoryNotFoundException: Could not find a part of the path 'C:\maps\TestMap.xnb'.

```

My Content is obviously not directly under my C:\ drive, so I am confused by the second error. It almost seems as if VStudio is converting the map to binary and then trying to place the converted map under C:? The command I am using to import the content is as follows:

```
//Tiled Test
private MonoGame.Extended.Tiled.TiledMap lcTestMap;
.
Content = new ContentManager(this.Services, "Content");
.
lcTestMap = Content.Load<MonoGame.Extended.Tiled.TiledMap>("/maps/TestMap");

```

I would like to know if I missed a critical step in the configuration, or if I am not using these classes correctly. I do plan on strictly using Isometric maps in this game, so I'm hoping that it will not be too different from this test. Oh, and I'm using Visual Studio Pro 2017 with Monogame 3.6 - in case that has some impact as well...

Thanks in advance for any help you might have!

# Answer
> 1 votes
Okay, so let me explain in more detail what's going on here.

> 1) If there is a Tileset.tsx file in the Content Manager: Couldn't find a default importer

I think what's happening here is that we don't support external tileset files (`.tmx`) in MonoGame.Extended 1.1. We'll be adding support for this in 2.0.

This is because the Tiled importer was written when the Tiled Map Editor embedded the tileset into the map by default. Now, in newer versions embedding the tileset is an option you need to turn on manually as shown in the screenshot below:

> ```
> var tiledMap = Content.Load<TiledMap>("/maps/TestMap");
>
> ```
>
> DirectoryNotFoundException: Could not find a part of the path 'C:\maps\TestMap.xnb'.

When you put a leading slash in front of the path you're actually saying "make this path relative to the root of the current drive". To be honest, it seems a little odd that the MonoGame `ContentManager` would even let you load content this way, but in any case it does explain why it's trying to load the file from the path shown in the error.

Simply removing the leading slash tells the `ContentManager` that you want to load the content relative to the `Content` folder as you'd expect.

```
var tiledMap = Content.Load<TiledMap>("maps/TestMap");

```

Happy coding!

---
Tags: c#, xna, monogame, visual-studio, tiled
---


# Question
Title: Unity. Input in function for UI button OnClick
I am trying to create multiple selections for some items on my UI. To perform multiple selections of items I want a user to hold left control button. But then I add

```
if (Input.GetKeyDown(KeyCode.LeftControl)){
/* Logic */
}

```

It registers in debugger what LeftControl is pressed but it skips all logic in brackets. This function is public and created for UI button. Is Input and Button.OnClick compatible at all?

# Answer
*Answer extracted from comment*

With your current code, your user needs to press the key the **same frame** he / she clicks on the UI button, which is quite hard.

Instead, you should simply check if the key is currently pressed by using Input.GetKey. This function returns `true` **while** the user holds down the key:

```
if (Input.GetKey(KeyCode.LeftControl))
{
   /* Logic */
}

```
> 2 votes

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


# Question
Title: Deleting/Cleaning Screen-Objects with all child-objects in libGDX
For my game, Im using

* libGDX
* Ashley (ECS)
* Box2D

Ive got a lot of screens but for simplification: `MainMenuScreen` and `InGameScreen`.

In InGameScreen Im init the ECS (Ashley) and create a lot of entities. Some have PhysicsComponent. The PhysicsSystem will catch them and call Box2D to spawn some objects based on the parameters within the PhysicsComponents.

So far so good.

Now, when the player dyes, I run `setScreen(new MainMenuScreen());` from my "Main"-Class (MyGame.java).

1. the game starts and `MyGame` loading at first the `MainMenuScreen`
2. than the `InGameScreen` will get loaded (when player presses a key)
3. than the player dyes
4. `MyGame` recognized it and loading again (throu calling `setScreen(...)`) the `MainMenuScreen`
5. When Player press key: `MyGame` loading another round (`setScreen(new InGameScreen)`)

I guess I have to do something like a complete clean up between switching screens. But how should I implement this? Just "deleting" the old InGameScreen-Object shouldent be enought, right?

* Do I have to use the `dispose()`-Method?
* Is it enough to instantiate everything new (in the `init` from `InGameScreen`) since it will instantiate all child-object new for its own like `Box2DWorld world = new World();`

# Answer
Making a new instance of a screen, each time you set it is ok. It will clean everything in your screen.

Since InGameScreen will need to reset every time you set it, it's a possibility.

But for screen that don't need to be reloaded / cleaned like a menu screen, you could use **singletons**. This way you only share one instance of the screen in your code and don't reload it for nothing.

Basically:

* Screen which need clean reload - `setScreen(new YourScreen);`
* Screen which don't need clean reload (which contain a simple menu with user interactions) - `setScreen(YourMenuScreen.instance);`

---

You can push this arthictecture by making all screens **singletons**, set up the screen (load what need to be loaded) by overriding `Screen.show()` (called on setScreen) and clean everything that need to be cleared by overriding `Screen.hide()` (called when screen is not longer active screen).

This way, all your screens are instanciated at start. Your screen load the strict necessary on show, and clear (clear collection for example, instead of re-instanciating by instanciating the screen each time you set it) what's need to be cleared when it's no longer the active screen). You will win a certain amount of time at runtime with this architecture ;)

Hope it helps !
> 1 votes

---
Tags: libgdx, architecture
---


title: Getting the bounding box of a sphere

text:
# Question
Title: Getting the bounding box of a sphere
I have a sphere with values `center,radius` and I need to convert the sphere to a bounding box with values `min,max`.

How do I convert a sphere into a bounding box?

# Answer
> 4 votes
Calculating the bounding box of a sphere is pretty trivial given the simplicity of sphere geometry.

Let's assume we have the radius of the sphere defined as a scalar (float or integer) value \\$r\\$, and the centre of the sphere defined as a vector \\$\overrightarrow c\\$ like this:

$$ \overrightarrow c = \begin{pmatrix}x \\ y \\ z\end{pmatrix} $$

We can calculate the outer bound coordinate vectors \\$\overrightarrow{min}\\$ and \\$\overrightarrow{max}\\$ by doing the following:

$$ \begin{align} \overrightarrow{min} &= \begin{pmatrix} c\_x - r \\ c\_y - r \\ c\_z - r \end{pmatrix} \\ \\ \overrightarrow{max} &= \begin{pmatrix} c\_x + r \\ c\_y + r \\ c\_z + r \end{pmatrix} \end{align} $$

In code, that means:

```
// given
Vector3 center = new Vector3(10, 20, 30);
int radius = 5;

// then
Vector3 boundingBoxMin = new Vector3(
    center.x - radius,
    center.y - radius,
    center.z - radius
);
Vector3 boundingBoxMax = new Vector3(
    center.x + radius,
    center.y + radius,
    center.z + radius
);

```

If we'd prefer, another way to calculate this same thing is to define a vector \\$\overrightarrow {r\_{\text{offset}}}\\$ for doing that addition, which simply represents the offset from the center to a corner of the bounding box:

$$ \text{given} \\; \overrightarrow c = \begin{pmatrix}x \\ y \\ z\end{pmatrix} \\; \text{and} \\; \overrightarrow {r\_{\text{offset}}} = \begin{pmatrix} r \\ r \\ r \end{pmatrix}, \\ \begin{align} \overrightarrow {min} &= \overrightarrow c - \overrightarrow {r\_{\text{offset}}} \\ \overrightarrow {max} &= \overrightarrow c + \overrightarrow {r\_{\text{offset}}} \end{align} $$

```
// given
Vector3 center = new Vector3(10, 20, 30);
int radius = 5;
Vector3 radiusOffset = new Vector3(radius, radius, radius);

// then
Vector3 boundingBoxMin = center - radiusOffset;
Vector3 boundingBoxMax = center + radiusOffset;

```

# Handling the 2D case

For the 2D case, calculating the rectangular bounding box of a circle, we omit the Z values like normal: \\$\overrightarrow c\\$, \\$\overrightarrow{r\_{\text{offset}}}\\$ (if you're using that), \\$\overrightarrow{max}\\$, and \\$\overrightarrow{min}\\$ will just be 2D vectors and we'll just do only the x and y calculations.

# Diagram!

The following diagram of the 2D scenario might help visualise what's going on here:

---

One's first instinct might be to calculate a hypotenuse using the Pythagorean theorem (\\$\sqrt{x^2 + y^2}\\$) and use that as the magnitude of a vector \\$\vec h\\$, but that's more computationally expensive than necessary: \\$\overrightarrow{r\_{\text{offset}}}\\$ will give us the same result.

# Answer
> 1 votes
Here is something that helped me.

```
min = (center.x - radius, center.y - radius, center.z - radius);
max = (center.x + radius, center.y + radius, center.z + radius);

```

Hope it helps someone else.

---
Tags: geometry, aabb, sphere
---


title: SDL2 GUI (same window)

text:
# Question
Title: SDL2 GUI (same window)
I have a problem: I working on a simple game and want to use some GUI (think of simple input for player name, etc). I've googled a lot of GUIs that can be used with SDL, but:

1. Most of them are using OpenGL while I'm using SDL2 render system. Docs say I can't mix these two, so I need to render GUI in a separate window. I know I can make it borderless and always-on-top, but I still need to manage this as a separate window (e.g. if main window moves, I need to move the gui window, etc, basically, I need to implement the childing myself). That makes me sad.
2. Those few which are using SDL as render (without OpenGL) either abandoned / unfinished / can't be compiled / etc or I can't figure out how to mix them with my rendering.

What I want to achieve: to render GUI in some place on the screen (think of a sidebar) and game stuff on the rest of the screen. Like:

```
SDL_Window* w = ...;
SDL_Renderer * r = ...;

while(running)
{
    renderGui(r, 0, 0, 100, 100); // Minimap located at 0,0 of size 100
    renderGameScreen(r, 100, 100, 100, 100); // Rest of the game located at 100, 100
}

```

Is there a way to do that? How GUI supposed to be used in alongside the SDL? May be my design is broken.

Sorry, I'm completely novice and may mix the things. Thanks.

**Update**:

Thanks for your answers. Quick update: I've tried so far:

1. nanogui-sdl - it uses opengl context, I was not able to mix it with SDL 2d render: it either flickers (because opengl and sdl fight for the screen and over-drawing the contents) or just draws the either thing: ui or game screen. Moreover, it crashes on some controls (like color-picker) and significantly affects rendering time (it drops 2-3 times when I add nanogui rendering with a couple of basic widgets)
2. nuklear - the same thing as with nanogui
3. I was not able to compile ToT KiWi - there are some syntax error (like `#elsif` instead of `#else if` or `#elif` so I'm not ever sure it can be compiled at all).

I'm going to try: imgui, kiss and gwen (gwork).

In the end, I can switch my drawing to opengl (fortunately I need some basic primitives, like circles, rectangles, triangles, etc, nothing complex) if I can't find a UI to work with SDL 2d render.

**Update 2**:

Sorry for not selecting the answer - was very busy during the week. I marked answer as accepted. I also tried to upvote both answers, since they are both useful, but I don't have enough reputation to do that. Thanks.

For those who wondering is I solve the problem: yes, kind of. I've switched over to SFML. I really like SDL and know it's very stable and mature, but I really need basic graphics for my pet project, so I'm OK with SFML too. It makes working with OpenGL a bit easier, so I can adopt the GUI library.

# Answer
> 1 votes
You mentioned you tried a few, but did not list them. Which ones did you try?

These are SDL2 based, without OpenGL, and are actively maintained:

# Answer
> 1 votes
PDCurses ( https://github.com/wmcbrine/PDCurses ) might be worth investigation. It's strictly text mode, but there's a SDL back end. There's an example that comes with it that shows using SDL graphics with PDCurses text user interface functionality.

---
Tags: gui, sdl, sdl2
---


# Question
Title: How to drag 2D objects and stop it if collides with other 2D object?
This is the code I am using but it's not working. It drags other object on collision:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TileControllerHorizontal : MonoBehaviour
{

    private Vector3 screenPoint;
    private Vector3 offset;
    public bool check;

    // Use this for initialization
    void Start ()
    {

    }

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

    }

    void OnMouseDown ()
    {
        screenPoint = Camera.main.WorldToScreenPoint (gameObject.transform.position);

        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
        transform.name = "draging";

    }

    void OnMouseDrag ()
    {
        if (!check) {
            Vector3 point = Camera.main.ScreenToWorldPoint (Input.mousePosition);
            point.z = gameObject.transform.position.z;
            point.y = gameObject.transform.position.y;
            gameObject.transform.position = point;
        }
    }

    void OnMouseUp ()
    {
        check = false;
        transform.name = "Tile";

    }

    void OnCollisionEnter2D (Collision2D col)
    {
        Debug.Log (col.gameObject.tag);
        if (col.gameObject.tag == "Player" && transform.name == "draging") {
            check = true;
        }
    }
}

```

# Answer
> 1 votes
I made a little sample project of how I would implement this, as a component you can simply attach to any gameobject you want to be made draggable.

I will include the code for the mono behaviour here too, each sprite you want to be able to collide needs a BoxCollider2D and a RigidBody2D, if you don't want physics to apply to the objects make sure to set GravityScale to 0 and Mass to something really low like 0.00001 on the rigidbody2d components.

```
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DragComponent : MonoBehaviour {

//try to explicity declare variables when you can so you're always sure what a variables state is at any given line
public bool dragging = false;

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

    CheckForClicks();

    //if this is currently being dragged
    if (this.dragging)
    {
        //create a variable to hold the mouse position just because it looks clearer and easier to read
        Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        //now we create a second vector3 as we don't want the sprite z axis to match the mouse position only on X and Y we want to stay on the same z axis
        Vector3 position = new Vector3(mousePosition.x, mousePosition.y, 1);
        //set its position equal to the vector3 we just created
        transform.position = position;
    }
}

private void CheckForClicks()
{
    //if left click
    if (Input.GetMouseButtonDown(0))
    {
        //get mouse position as world position
        Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        //ray cast and whatever was hit gets returned
        RaycastHit2D hit = Physics2D.Raycast(mousePosition, Vector2.zero);

        //did we hit something with a collider?
        if (hit.collider != null)
        {
            //is the collider we hit the same as the whichever object is currently running this script?
            if (hit.collider.gameObject == gameObject)
            {
                //yes it is so set draggable to true, which lets the update function lock its position to the mouse position
                this.dragging = true;
            }

        }

    }
    //if we press right click stop draggin this object
    else if(Input.GetMouseButtonDown(1))
    {
        //and if whatever is running this script is currently being dragged
        if (this.dragging)
        {
            //set dragging to false
            this.dragging = false;
        }
    }
}

private void OnCollisionEnter2D(Collision2D collision)
{

    Debug.Log(collision);
    //if the game object we collided with is not equal to the current game object (so anything other than itself)
    if (collision.gameObject != gameObject)
    {
        //turn dragging for this object off because we hit something
        this.dragging = false;
    }
    }

}

```

https://www.dropbox.com/s/k464kgvewg88owl/dragging\_demo.unitypackage?dl=0

Notice in the example project the draggable script is added to both objects and you can drag either one into the other and it will stop moving.

You could change in the collision function

```
        //turn dragging for this object off because we hit something
        this.dragging = false;

```

to

```
        //turn dragging for this object off because we hit something
        Destroy(collison.gameObject)
        this.dragging = false;

```

and it will now destroy whatever it hits.

You could go one further and move the logic of what happens when an object is collided with to its own component script that way you can have different behaviours for different tiles.

Adding this to a gameObject that has a Collider2D and RigidBody2D will make the obejct destroy itself when hit, you can easily expand this so other objects may become larger when hit by creating a different component and adding it to the object.

```
public class BreakableComponent : MonoBehaviour
{

private void OnCollisionEnter2D(Collision2D collision)
{
    //if the game object we collided with is not equal to the current game object (so anything other than itself)
    if (collision.gameObject != gameObject)
    {
        //KILL THIS OBJECT
        Destroy(gameObject);
    }
}

```

}

---
Tags: 2d, tilemap, unityscript, draw-order
---


# Question
Title: Show Unity Line Renderer as 3d cable or wire
I am dynamically making a line renderer which is pull by the character to show that a character is pulling a wire. The line renderer working fine but unfortunately its display is not according to my expectation. Like it showing as 2D.

Is there any way available to make it more realistic wire/cable? Maybe any shader will help ?

# Answer
What you can do is activate the generateLightingData option. Then depending of what you want to make use a custom material with a shader to render what you want. For example you could use a standart shader with a 3d cable normal map/albedo/metalic texture to get a pretty good looking cable. In the case of wanting a chain it will be harder since you will need an alpha transparency mask to hide (transparent) the parts between each chain. I highly recomend you to use a shader program (like Amplify Shader Editor) or use the new shader graph in unity 2018+ if you never used shaders before.
> 1 votes

---
Tags: unity, c#, shaders, materials, line-renderer
---


# Question
Title: Best way to handle abstraction of behaviors(attack,jump, dodge) within Unity?
I have behaviors for my player such as attack, jump, dodge. I want these to act differently depending on the character the player has selected. I thought about making an abstract class for each of these actions, using an interfaces for each one might be a good way to go, but i'm not sure the best way to go about it within unity.

How do you handle abstracting behaviors like this within your projects? What are the pros and cons of the methods you use.

# Answer
> 1 votes
I would make one base abstract class that implements the interfaces you want all the characters to have (Attack, Jump, Dodge) etc.

Then extend each character from that base class and implement the interface behaviors which is what interfaces are for :)

That way if you need to get every object that can move you can do

```
List<IMoveable> moveableList = GameObject.FindObjectOfType(typeof(IMoveable));

```

I don't recommend using `GameObject.FindObjectOfType(typeof(IMoveable));` itself just as an example because I dont want to write the code out for a raycast or sphere cast etc.

The point is you can refer to what might be a Enemy Class object just as a IMoveable if you need to move stuff or IAttack if you need to attack stuff, so while Player and Enemy are different classes they both share the fact they can move in common.

```
public interface IMove
{
    void Move(float xPos, float yPos);

}

public abstract class Entity : MonoBehaviour, IMove
{
    public int moveSpeed;

    public abstract void Move(float xPos, float yPos);
}

public class Mage : Entity
{
     //set moveSpeed in inspector to 2 for example
    public override void Move(float xPos, float yPos)
    {
        Debug.Log("I move " + moveSpeed +  " tiles at a time");
    }
}

public class Warrior : Entity
{
   //set moveSpeed in inspector to 1 for example
    public override void Move(float xPos, float yPos)
    {
        Debug.Log("I move " + moveSpeed +  " tiles at a time");
    }
}

```

---
Tags: unity
---


# Question
Title: Is component-based design an architectural pattern or design pattern?
When using the component-based paradigm in game development with engines like Unity, is component-based design an architectural pattern, or a design pattern?

Can I even say that component-based design is my "main" architectural pattern for my game?

I see architectural patterns as being more high-level than design pattern. The component-based design in game development's context (like with Unity engine) seems to fit as an architectural pattern to me. However, on some sites, I read that component-based design is a behavioural pattern, much like other behavioural design patterns, and not so much like an architectural pattern like MVC.

# Answer
Here's a great question (and answers) on the differences between Architectural Patterns and Design Patterns:

https://stackoverflow.com/questions/4243187/difference-between-design-pattern-and-architecture

According to this (and filtered through my understanding), the component based way of Unity is closer to a design pattern than an architectural pattern.

I believe that because as you say (and I think so too) architectural patterns are more high level than design patterns (i.e. architectural patterns are about the whole system, as viewed from a high level, while design patterns refer to more granular components). As such the architectural level of Unity deals with the fact that you have a game loop, and how that game loop is designed and acts on everything you have in there (entities, physics, collisions, etc). The design level of unity deals with a lower level and more specific part, namely how each of the elements which are just listed in the architectural design is more actually...well.. designed, entities included.

So I guess we can talk about Unity's architecture as being one "specific to"/"good for" a game engine (game loop and the classification of the elements it interacts with in various categories like game objects, physics, collisions, etc), and then we can talk about the design pattern for each of these elements (a game object supports this and that component, it can have behaviors attached to it, etc. In turn the design pattern for the behaviors is "each is an object of a certain class in a certain OO language).
> 1 votes

# Answer
An architectural pattern as the wiki states:

> An architectural pattern is a general, reusable solution to a commonly occurring problem in software architecture within a given context.

A design pattern as the wiki states:

> In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design.

Those definitions look nearly identical, so what's the difference?

**Point of Confusion**

The problem lies in the naming. "Design Pattern" is an extremely broad name, but when we talk of design patterns we typically mean on a smaller scale than architectural.

**The Difference**

MVC is an architectural pattern because it's a pattern for the entire presentation layer. MVC states that you have a controller that will pass some model (which holds the data) to a view so that it may render. It's a very broad method, that view could be Razor, aspx, php, etc. That controller could do who knows what. It simply states that the architectural layout will be MVC.

On the other hand, the Strategy pattern (which we typically think of as a 'design pattern') usually applies to having multiple algorithms for one action (e.g. You might use the strategy pattern to determine how and/or where you will log information). This could be use with or without MVC as an architectural pattern.

**Conclusion**

So from my experience and interpretation of definitions, the only real difference is scope of the pattern. Meaning that realistically there is going to be overlap and with how wide-spread the use of the component pattern is in Unity it could easily be referred to as an architectural pattern, though it is traditionally a design pattern.
> 1 votes

---
Tags: architecture, entity-system
---


title: What is the unit of speed in unity3d?

text:
# Question
Title: What is the unit of speed in unity3d?
I have cars in my unity scene, I am not sure in what units speed is specified in unity.

# Answer
> 2 votes
It's grid units per second.

If you have a frictionless object without gravity at coordinates (0, 0, 0), set its velocity to (1.0f, 0, 0) and wait 10 seconds, it will be at (10.0f, 0, 0).

Regarding what's a "grid unit" in meters: That depends on what you want it to be in your game. In a game where you build a space empire, it could be 1 light-year. In a game where you control a bacteria, it could be 1 µm. But the default assumption seems to be 1 meter. 1m = 1 unit is the scale of most assets you will find on the asset store. Also, the default value for gravity is 9.81f, which would be the value you would expect if your game uses a 1m scale and takes place on the surface of planet Earth.

# Answer
> 0 votes
**Meters per Second** is Unity's default measurement.

---
Tags: unity, simulations, car
---


# Question
Title: How to incorporate delta time into movement?
I want to use delta time in my movement code for my player, and I'm not sure how to do it. At the moment, I have this:

```
else if (keyboardState.IsKeyDown(Keys.D))
        {
            double moveSpeed = 0.3 * delta;

            if (velocity < 0)
            {
                double turnSpeed = 0.5 * delta;
                velocity += turnSpeed;
            }
            else
            {
                if (velocity + moveSpeed > .1)
                {
                    velocity = .1;
                }
                else
                {
                    velocity += moveSpeed;
                }
            }
        }

        position.X += (float)velocity;

```

Is this correct? I'm trying to make my player's movement gradually speed up until it hits the maximum velocity.

position.X is the Vector2 X of the player. delta is set to gameTime.ElapsedGameTime.TotalSeconds.

# Answer
The code you've got there is going to produce some *really* small numbers.

Let's say your game is running at 60 frames per second (that's pretty typical for MonoGame). The `delta` variable will be about `0.016666` seconds or 16 milliseconds.

So that means after the first calculation your `moveSpeed` is going to be equal to `0.0005`. That's probably not what you want.

The first thing you need to do is decide what your numbers actually represent. I normally think about things in "pixel" units. So in my case `moveSpeed = 300` would mean "move 300 pixels per second".

Once you've come to grips with that concept it's easier to reason about what's going on in your code. For example, you're trying to calculate how far your guy will move in "one frame" if he's moving at 300 pixels per second. So..

```
position.X += moveSpeed * delta;

```

will move the guy one frame. After 60 frames (1 second) he will have moved 300 pixels.

Honestly, I don't really understand what you're trying to do in the code you posted so it's quite difficult to tell you how to fix it. My guess is you've got a little confused along the way.

My suggestion, start over, start simple and work your way up to the more complex stuff.
> 3 votes

# Answer
Generally the speed value is multiplied by Time.deltaTime to give a new velocity vector (Velocity is Direction + Speed) that is independent of how many frames a second any given client can handle.

This isn't always the case it depends what you're doing but in your case multiplying the velocity Vector by speed * delta below should work fine.

```
velocity += moveSpeed * Time.deltaTime;

```

Misread framework in question, How to work with delta time?

@craftworkgames Answers this question better than I.
> 0 votes

---
Tags: c#, monogame
---


# Question
Title: Swapping Y and Z causes problems with Camera
I am trying to swap the Y and Z axis in my program. Everything worked great when Y used to be the axis coming out of the plane. After having swapped y and x, I have been able to draw my terrain using the X Y as the plane and Z as the height, however when converting the code for the camera I am running into trouble.

Here is the code that gives me the correct camera (so y is the axis coming out of the plane), along with an illustration. The code is in SharpDX which is a C# wrapper for DirectX

```
// Setup the position of the camera in the world.
      Vector3 position = new Vector3(PositionX, PositionY, PositionZ);

      // Setup where the camera is looking  forwardby default.
      Vector3 lookAt = new Vector3(0, 0, 1.0f);

      // Set the yaw (Y axis), pitch (X axis), and roll (Z axis) rotations in radians.
      float pitch = RotationX * 0.0174532925f;
      float yaw = RotationY * 0.0174532925f;
      float roll = RotationZ * 0.0174532925f;

      //// Create the rotation matrix from the yaw, pitch, and roll values.
      Matrix rotationMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, roll);

      // Transform the lookAt and up vector by the rotation matrix so the view is correctly rotated at the origin.
      lookAt = Vector3.TransformCoordinate(lookAt, rotationMatrix);
      Vector3 up = Vector3.TransformCoordinate(Vector3.UnitY, rotationMatrix);

      // Translate the rotated camera position to the location of the viewer.
      lookAt = position + lookAt;

      // Finally create the view matrix from the three updated vectors.
      ViewMatrix = Matrix.LookAtLH(position, lookAt, up);

```

Here is an illustration of what this produces, I am able to successfully move the camera around with the mouse by having the mouse differences affect the x and y rotation:

Now if I swap all the X and Y in my terrain, without affecting the camera, I get this:

So now the camera is facing the terrain directly, and attempts to yaw will not produce the desired view. (the world will revolve around the camera when looking perpendicular to the terrain, and spin in place when looking at the horizon, the exact opposite of what we want.)

Now I thought that maybe if I just change the lookAt to 0, 1.0f, 0 ; swap the y and z rotations, and change the Up vector to use Vector3.UnitZ, it would solve all my problems.

```
// Setup the position of the camera in the world.
      Vector3 position = new Vector3(PositionX, PositionY, PositionZ);

      // Setup where the camera is looking  forwardby default.
      Vector3 lookAt = new Vector3(0, 1.0f, 0);

      // Set the yaw (Y axis), pitch (X axis), and roll (Z axis) rotations in radians.
      float pitch = RotationX * 0.0174532925f;
      float yaw = RotationZ * 0.0174532925f;
      float roll = RotationY * 0.0174532925f;

      //// Create the rotation matrix from the yaw, pitch, and roll values.
      Matrix rotationMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, roll);

      // Transform the lookAt and up vector by the rotation matrix so the view is correctly rotated at the origin.
      lookAt = Vector3.TransformCoordinate(lookAt, rotationMatrix);
      Vector3 up = Vector3.TransformCoordinate(Vector3.UnitZ, rotationMatrix);

      // Translate the rotated camera position to the location of the viewer.
      lookAt = position + lookAt;

      // Finally create the view matrix from the three updated vectors.
      ViewMatrix = Matrix.LookAtLH(position, lookAt, up);

```

However, doing this, I get the same issue as before, the world will revolve around when looking perpendicular to the ground, but spin in place when looking parallel to the ground (so towards the horizon). I believe the camera now looks like this:

Which doesn't make sense to me, since I thought changing the Up vector to UnitZ would make Z face up and not parallel to the ground. Any suggestions to change the second code block is appreciated.

# Answer
> 0 votes
I figured it out on my own, and posting the answer.

If you take a look at the documentation for the DirectX equivalent of Matrix.RotationYawPitchRoll, found here: https://msdn.microsoft.com/en-us/library/windows/desktop/bb205361(v=vs.85).aspx

You notice that the function assumes that x is pitch, y is yaw, and z is roll. Since there does not exist a function that assumes z is the axis pointing up, you have to multiply manually, and the order of multiplication does matter..

```
float pitch = RotationX * 0.0174532925f;
float yaw = RotationZ * 0.0174532925f;
float roll = RotationY * 0.0174532925f;

Matrix rotationRoll = Matrix.RotationY(roll);
Matrix rotationPitch = Matrix.RotationX(pitch);
Matrix rotationYaw = Matrix.RotationZ(yaw);

Matrix rotationMatrix = rotationRoll * rotationPitch * rotationYaw;

```

Then it should work.

# Answer
> 0 votes
You can't just swap two axes: if you do so, you change the handed-ness of the coordinate system. Either from left-handed to right-handed or vice versa.

You need to add a negation somewhere, like

```
newy = -z;
newz = y;

```

or:

```
newy = z;
newz = -y;

```

---
Tags: camera, sharpdx
---


# Question
Title: Fair combat system for new players on RTS game
I'm working on an idea/concept for a multiplayer game that I want to develop after my functional analysis but I'm still thinking of a way to implement a proper, fair combat system between new and existing players.

A player can create a new village/town once, anywhere on a map (**this is key!**). There is an attacking period where players can attack each other but I want to limit the possibility that more progressed players can attack beginners and prevent them from growing. Tribal Wars for example does this by creating new villages further away from the more progressed players. In my case, a user can create his town anywhere on the map, so I'm looking for a fair solution for all players.

A few examples of combat systems used in other games that I thought off:

1. RuneScape

> Any player within a particular level range of your combat level can be attacked in the Wilderness. The range is calculated by taking your current combat level and adding or subtracting the current Wilderness level you are in.

2. Tribal Wars

> Every new player is assigned a new village at the border from the previous players. So older, longer players are in the center while new players are further away from them, repeatedly. Combat system is based on the distance between 2 villages, so if older players want to attack a new player, it would take significantly more time to attack those players for less rewards.

# Answer
At this point, there were good examples of preventing lowling bashing, so I want to suggest a different approach: encourage the protection of lowbies.

The only High level player's dangers are basically other high level players. It is unlikely, that many lower levels gather togehter to attack someone higher.

So, to stay ahead of the enemys, his economy needs to support a basically evergrowing army, while he needs to grow his economics to support this growth.

That's why many high level players tend to raid (or "farm") low level players, because the army is there, while abusing the economy of lower players.

Instead of "farming", what if you give the option for defensive pacts? New players seek for protection from higher level players, which in return give a small amount of their production or maybe just something created from thin air (resources and/or something like vassal points). This would increase the economics of the higher level, while not wasting military potential on farming.

This is less about the combat system. It would only need to allow support for other players.

Additionally, when someone tries to attack the vassals, the player may strike against the others base, while his army is out of base farming.

At some point, the vassal might try to become independent (maybe to have vassals on their own), but the newer players may decide that on their own. This could lead to interesting dynamics in the game.
> 26 votes

# Answer
Base building and drop-in multiplayer are two features which don't go very well together.

One option is to allow new players to progress very quickly. Give them the tools and resources to defend themselves after a very short playtime. Further progression is either horizontal (more variety, but all newly unlocked options are tradeoffs which are different but not strictly better than the starting options) or focuses mostly on offensive capabilities.

Another is to discourage players from picking on newbies using your risk and reward mechanics. Limit the number of attacks a player can perform in a given timeframe and give them very little to no reward for attacking lowbies. Make sure that in order to maximize their rewards they will need to spend the limited attacks they have on the strongest opponents around. Also don't forget about your risk mechanics. If the risk one takes when attacking a lowbie is a lot smaller than the risk when attacking an equal or superior enemy, then it might still make sense to attack lowbies. So make sure that the attacker's risk is not linearly proportional to the strength of the defender.
> 10 votes

# Answer
> I'm still thinking of a way to implement a proper, fair combat system between new and existing players

Abstracting the answer a bit, there is a more general underlying question: how to make things engaging for both newcomers and experts? There are a few interesting case studies here:

---

## 1. Opt-in complexity

One method that I'm particularly fond of is opt-in complexity. As a simple example:

In the **Civilization** series (among other 4X games), cities can change their resource output based on assigning the population to work particular tiles. This can give the player incredibly detailed control, but it can also become very tedious to manage from the start (especially when you're a new player).

Civ implements an opt-in complexity. It provides an average default implementation that the player doesn't need to manage; but it also allows the player to override the default if he chooses to engage in this tedious chore. It even has tiers of complexity:

* **Default** \- the city will automatically strive for a balanced resource output. It will reassign citizens based on changes to tile yields.
* **Focus** \- The player can choose which resource(s) need(s) to be focused on. The citizens are still assigned automatically, ensuring that basic needs (e.g. food output) are minimally met before dedicating itself to the focused resource(s).
* **Full control** \- The player assigns every population unit to a specific tile, and can prevent the game from rebalancing the assignments. The player can also choose to only force *certain* tiles to be worked, while leaving the rest of the assignments up to the automatic behavior (focused or default).

This creates an incredibly intuitive approach.

* A new player who doesn't even know about resource management won't be bothered by having to make decisions about it. They can instead focus on other parts of the game.
* A player that wants to increase a particular resource output can find the focus buttons with relative ease.
* A player that wants to micromanage their city needs to find the right menu option.

Complicated approaches are hidden for players *unless they go looking for it*. This achieves the best of both worlds: players who don't care about it aren't bothered, players who do care get to do it their way.

As a second example, consider **EVE Online**. In a vast map of solar systems, every system had a rating from 0 to 1 (in 0.1 increments).

* 1.0 is fully under Concord (the NPC police) control. Anyone who misbehaves would very quickly be killed by the automated NPC security forces.
* 0.6 space would still be under Concord protection, but their response would be slower (and less forces would be dispatched).
* 0.3 space was hardly regulated. While there was some security near space stations and ports, the rest of the system was mostly unprotected.
* 0.0 space (known as nullsec) was pirate waters. No Concord protection was provided. Players would be on their own. Safety would only be provided by player-built stations. It's essentially what we think of when we say "the Wild West".

The security rating was clearly visibly for every system. Players would be able to avoid going below a certain security level, if they felt uncomfortable doing so.

However, nullsec was vastly more **profitable** specifically because it was such a hard place to survive in. Resources that were only available in low-security regions would be much more expensive, and thus much more profitable to mine.

The main conclusion to take away here is **when there is a pro vs con situation (increased control vs. increased tedium, or increased profit vs less protection), giving the player the freedom to choose their approach keeps everyone happy**.

---

## 2. Opt-in symmetrical play

You can often see a symmetry in gemplay: if a player wants to attack others, he'll also have to defend from being attacked by others.

This can be done via opting in. A simple example here is World of Warcraft:

On non-PVP-enabled servers, there was still the option to engage in PVP combat. However, it required **consent from both players** (direct or indirect).
Very simply put, both players needed to set their "PVP flag" in order to be attackable by the other party.

* A1 wants to fight B1, B1 wants to fight A1. Both players raise their PVP flag. They can attack each other.
* Player A2 approaches, but is not interested in PVP fighting. He does not raise his PVP flag. He cannot be harmed by the PVP combat, even if B1 wanted to attack A2.
* Player B2 approaches. He wants to help B1. Because A1 has his PVP flag enabled, B2 can attack him immediately (A1 has already explicitly consented to PVP combat). However, when B2 lands an attack on A1, B2's PVP flag will be raised automatically. B2 indirectly consented to engage in PVP combat by attacking a player who had already consented.
* A2 decides to not attack anyone, but he does heal A1. Since this aids A1 in his PVP combat, that counts as consenting to PVP play, which means that A1's PVP flag is now also automatically raised.
* To prevent abuse, lowering a PVP flag is only possible after 5 minutes of not engaging in PVP combat. A player could mark himself for non-PVP earlier, but it wouldn't take effect until after the 5 minutes are up.

The main conclusion to take away here is that **mutual consent prevents either opponent from feeling wronged**.

---

## 3. Challenge upwards, not downwards.

I used to play on GameKnot (online chess) years ago. There is a *massive* gap between casual and grandmaster chess players. The system needed tiered leagues in order to ensure roughly equal chess skills.

This was done via an ELO rating. Very simply put, it's a number that goes up when you win, and down when you lose (the amount won/lost depends on your opponent's rating versus yours).

However, there was an interesting feature added for tournaments specifically:

* Suppose a tournament opened for registering, with a skill level set between 1300 and 1500.
* A player with 1400 skill could obviously join the tournament.
* A player with 2400 skill could obviously not join the tournament.
* A player with 400 skill would get a *warning* when trying to join the tournament, **but would be allowed to join**.

This creates an interesting option for players: trying to play in the big leagues. Jumping in the deep end is a good way to learn the ropes (for some people, at least), so they ensured that it was possible for players to do so.
However, the opposite (playing in the little leagues) was prevented, because a high ranked player could easily ruin the fun for lower ranked players.

The main conclusion to take away here is that **the underdog needs to consent to playing a game where they are the underdog**.

---

## 4. Equivalence matching

This is just a short comparison.

In **World of Warcraft**, PVP battlegrounds would be ranked in brackets, based on player level:

* 10-19
* 20-29
* 30-39
* 40-49
* ...

This was necessary (due to exponential power growth in levels), but not a perfect solution. It created a metagame: *twinks*. These were special characters that players would take to the max level of a bracket (19,29,39, ...) in order to have the statistical upperhand on other players. The twinks were then given statistically superior (and exceedingly rare) gear in order to maximize their upper hand.
At worst, twinks would play against other twinks and it'd be a fair game. At best, they'd play against lower ranked players who they could easily win from.

Because PVP games did not award XP, twinks (who only played PVP) would never level up and could remain at the top of their bracket.
They later addressed this by giving tiny XP boosts for playing PVP, to eventually cause twinks to move up to the next bracket. It was a massive improvement, but still not perfect.

Comparatively, **Guild Wars 2** had a much more interesting solution that was not prone to this abuse. Instead of dividing their player base in bracket, what they did was boost every player to max level.

* Player gear stats were boosted to be with an equivalent balance to top level gear.
* Players would be able to pick talents/traits just like any "real" top level character.

Inside the PVP battleground, everyone had the same level. You couldn't see a difference between characters based on their level. The game was one of skill, both in character design (stats) and gameplay (combat).

Note that gear wasn't fully nullified. There was still better and worse PVP gear. But by boosting the stats, a lvl 20 player that was boosted to lvl 80 would be given the lvl 80 equivalent of his lvl 20 gear, which did a lot in terms of leveling the playing field.

The main conclusion to take away here is that **leveling the playing field can remove non-skill-based differences, reducing the game to one of skill, not acquired gear**.

---

## For your game

There are many different ways to level the playing field, while also catering to both new and experienced players. Now let's try to implement these based on your particular game.

> A player can create a new village/town once, anywhere on a map (this is key!). There is an attacking period where players can attack each other but I want to limit the possibility that more progressed players can attack beginners and prevent them from growing. Tribal Wars for example does this by creating new villages further away from the more progressed players. In my case, a user can create his town anywhere on the map, so I'm looking for a fair solution for all players.

1. **Opt-in complexity**

Players choose their own location on the map. If a player were able to see dangerous regions (i.e. with high level opponents), they would be able to choose whether they'd want to be close to these players.

This can be done via resources:

* Dangerous regions contain valuable resources, but also high level enemies. Usually, only high level players will go there. But low level players shouldn't be *prohibited* from going there, they should only be *warned*.
* Dangerous regions contain *different* resources from safe regions. These resources are only needed in the late game (high level players), not in the early game. There is no reason for low level players to settle there until they need the resources.

This can also be done via map design:

* Certain lands are under the King's protection. Any violence by any player will quickly be stomped by the foot of overpowered NPC security forces. High level players will avoid the region if they have nefarious intentions.

Or even by unrelated consequences:

* If your game implements a reputation feature, attacking low level players could ruin the player's reputation. Note that there needs to be a significant drawback to having a bad reputation. Players who already do not play the reputation game are then not punished from ruining their non-existent reputation.

2. **Opt-in symmetrical play**

A town can only be attacked once it builds a Barracks. Until then, it is a peaceful town that cannot be invaded or attacked.

This gives players the option to opt out of combat.

You can, if you want to, eventually force players out of peaceful play by making the barracks a requirement to progress further in the game. But the player must be aware that they are opening the door to PVP play.

3. **Challenge upwards, not downwards.**

Towns are given a military rating (similar to how e.g. Stellaris provides estimated fleet power). This is calculated based on the player's property and defenses.

Players are not able to attack towns with a significantly lower military rating.

Players are able to attack towns with a higher military rating.

This creates a curve of protection: the more powerful a player becomes; the less he is able to attack beginning players.

4. **Equivalence matching**

When a higher level player attacks a lower level player, that lower level player gets boosted to match the higher level player's level. When a lower level player attacks a higher level player, no one gets boosted.

In short: the defending player will always get boosted up (but not down) to the level of the attacking player.

Alternatively, you can deincentivize high level players from attacking low level players by removing the rewards. In most RPGs, a player no longer gets XP for killing enemies several levels lower than him, specifically to prevent players from attacking too easy opponents.
This does not protect against griefing however (attacking low level players for no benefit other than ruining the other player's game experience).
> 7 votes

# Answer
You can use something like Elo Rating System

So that players can attack each other based on their elo range.

To make things clear:

Suppose playerOne attacks playerTwo knowing that they are in the same elo range. Now suppose playerOne army consists of 100 soldiers (making things generic as possible cz I know there should be more conditions and more units) and playerTwo army consists of 80 soldiers.

PlayerOne army killed 60 soldiers and playerTwo army killed 40 soldiers.

So the new elo's of the players are calculated for example like this

```
playerOneElo = currentElo + (playerTwoKilledSoldiers * playerTwoElo * smoothingConstant) - (lostSoldiers * playerTwoElo * smoothingConstant)

```

And of course in real example each unit should have a factor added to elo calculation that reflects it's strength.

Going back to the question, new players can attack and be attacked by players with elo's less than 1000 for example.
> 6 votes

# Answer
You could try to discourage players by introducing some kind of karma/morale system.

Player that attacks much weaker enemy would lose his karma. Karma would be gained every day/hour/X, or when fighting with players of similar level, or when spending in-game money, or when helping allies - basically whatever fits your theme.

Now karma could affect combat(troops with low karma are less effective), looting(troops with low karma hold less resources), production, prevent certain actions, increase karma gained by enemies when attacking player with low karma... The consequences depend on how you want your gameplay to look like.

You could also turn 180 degrees around and provide users with mentor system. Mentors would help players somehow(e.g. by sending them resources or troops or coordinating their attacks). This would in turn affect their production, fighting capabilities, etc.

I would probably prefer the mentoring idea; this could make your community less toxic (because game encourages positive interactions), or make your gameplay much more chaotic/deceptive (because you help others, but you have to make sure that they don't stab you in the back).

The last thing you could consider is providing a (very) cheap option to minimize the damage and enemy's gain (e.g. Tribal Wars' Hiding Place). Players attack others to obtain some profit. If attacking other player yields no profit, it means that the units are actually losing money(because they could be elsewhere, making profit). If player is able to quickly make themselves a bad target, they will be much safer.
> 3 votes

# Answer
You need to add a way for new weak players to harm bullys. How about some asymmetric warfare?

Our village was raided, they stole food and gold, and killed 5 of our peasants. Lets have some guerilla fun.

> Send a random guy with some matches

They keep raiding us!

> I think his Peasants need some help founding a labor union.

He kind of doesn't get the message.

> Spread some rumors and have him excluded from raids and traiding guilds as a person of ill repute.

They keep comming!

> Sabotage his army, maybe steel some trained mounts to downgrade a bunch of his units

He keeps throwing his army at us

> We showed them some crying babies and they defected to us!

For this to be really satisfying you should add estimated damage to the status messages of the new player, something like "One of our guys burnt a depot in noobslayercity, destroying 1750 units of Food. We estimate that the repairs will take 6 days and cost around 24000 gold."
> 2 votes

# Answer
I created a game which requires player 1 to be within a given range of levels to player 2 in order to fight.

Here are some constraints I put in:

I don't let players fight real players until they reach a certain level. This allows them to understand basic game play before being vulnerable in fights.

Players advance through the first levels really quickly, so stronger players cannot stay at the lower levels.

Level jumping slows down as play progresses.

The range of levels grows as the player's level grows. So for example, players at level 5 can only see players at level 4, 5 and 6. But players at level 100 can see players between 80 and 120. This helped increase the number of "fightable" players that were available when the game was new.

**Pros:**

Easy to implement

This actually worked remarkably well for my situation

**Considerations:**

Developing fight strength is built into the game play. Part of advancing in levels is performing tasks that advance the player's strength. For example, performing a task requires the player to buy a ship, which adds to their strength. So early on, all players are developing strength similarly.

In a new system with few players, there may be no one for players at certain levels to fight. Maybe this could be overcome by AI players or something.

In my situation, this accidentally worked out well. A certain percent of players get a few levels in and quit. There are always some of these non-playing players and they are available for low level players to fight. The players fighting the non-playing players don't know that those players aren't being played.

Related: In this game, when players aren't playing, other players can combat them. If players are offline a lot, they can actually move up in levels when someone fights them. So sometimes, weaker players can advance by not playing a lot.

**Additionally:**

A couple more notes based on the discussion.

The level range is actually skewed upwards. So lets say for example, a player at level 80 could choose to fight up to players at level 100 but can only fight down to say level 70 players.

Second, on the home page, it shows a list of which players fought you while you were out and the result of the fight. You can fight anyone on that list. So even if you couldn't normally see that opponent, you can always fight back.

Third, you can click on any opponent and see their status and what fight "boosts" they have. So you can get a rough guess of how a fight might turn out. This allows lower level players to access the risk of fighting a higher level player. The benefit of fighting a higher level player is they have better drops, more cash, etc.

But, the fight algorithm has a random element too, so a lower skilled player could beat a higher skilled player if chance was in their favor.

Long story short, this solution worked well for my situation.
> 1 votes

# Answer
So, this is mostly my perspective as a gamer, not a developer, but the best option I see is:

### Use a rating system of some sort, and match players based on that.

This is what is done by a vast majority of 'esport' games, such as most MOBA's and FPS's. This has a couple of significant advantages:

* It makes things reasonably easy for you as a developer. You define how the rating shifts based on battle results, define a starting value, and define a matchmaking threshold (IE, the maximal difference between the highest and lowest in match), and you're pretty much done.
* It is well tested, and easily understood. Gamers are used to this type of system, and people who aren't gamers have a very easy time understanding it.
* It scales well. With this approach, you can have a variable match size very easily, which simplifies matchmaking (you just set up an exponential backoff so that the longer someone is in queue for a match, the lower the minimum number of people for a match becomes).

It also has a handful of drawbacks:

* You have to have matchmaking queues, you can't do drop-in combat.
* It's non-trivial to get the starting point and scalings right. Ideally, you want people to start with a rating around the 20th to 30th percentile in terms of skill, so that people who are actually good rise easily, but those who aren't won't fall too far and can more easily recover. If you start people too high, everyone will lose a lot right off the bat and not like the game, if you start them too low, you run the risk of alienating lower skill players (keep in mind most of your player-base will be low skill) because they'll always get matched against new people and still lose.
* It doesn't work for reliably for team-based games. It's used a lot for them, but it *really* does not work reliably for team-based games. There are just too many variables to account for (to handle it equitably, you have to factor in the performance of everyone *on both teams* to figure out how to adjust each person's rating, otherwise you get people climbing because they are queuing with a friend who's insanely good, even if they're crap). This goes double if you let people queue as a group without factoring in their rating.

You can also combine this with other factors to disincentivize things like smurfing (creating extra accounts just to play with a lower rating) or general hazing. Options include:

* Use a level offset system. This is what Runescape and most other MMO's do. As they implement it, it only works for open-world type games. However, some games use a variant of this combined with rating for matchmaking. World of Tanks for example has a progression system where you unlock higher quality vehicles as you play, and you get matched based on what tier of vehicle you are using, and your rating.
* Taking another example from World of Tanks, penalize people for actively poor behavior. In WoT, if you shoot an ally, you're liable for their repair costs. If you kill an ally, you get marked for it, and people can kill you without having to pay your repair costs. Kill allies enough, and you get deprioritized in queue and end up with other jerks who do the same thing. Similarly, if you actively suicide on a regular basis (not just charging in, but things like drowning yourself all the time, or constantly flipping yourself over), you similarly end up in a lower priority queue and matched with similar people.
* Have everyone start each match with the same amount of resources, and don't give veterans any inherent bonus for being veterans. This may alienate some people, but it reduces the veterans' advantage to a simple matter of skill, which is much easier for other players to deal with.
* Give newer (lower ranked) players a handicap of some sort. This could be extra resources, a free turn, priority in placement of villages, or just about anything you can think of.
> 1 votes

# Answer
Make it so that you can only attack and be attacked by other players within a level range. You could also create separate worlds (e.g. beginner world, intermediate, veteran, etc.) and allow (or make) the player move to the higher level world after a certain amount of time or achievement.
> 0 votes

# Answer
**Make attacks expensive:** scale the cost according to the size of your force.

Costs can be fuel/food , attrition due to environmental factors (eg: stepped in a rabbit hole and broke his leg / dissapeared into quicksand / friendly fire).

Also have your soldiers each pilfer or destroy some amount of the spoils.

During the raid (some amount) of the victims resources just go missing. the larger the force the more fields are trampled, sacks torn, barrels split and treasures purloined.

Send a force of 1000 against 100 defenders and you'll come out behind on resources.
> 0 votes

# Answer
There was a game released in 2001 called Battle Realms. My friends and I loved this game, and it had an interesting mechanic which limited early game rush balance issues. Quoting from the Wikipedia page entry:

> Unlike other real-time strategy games though, the basic worker units (peasants), which are used for resource gathering and construction, also act as the base unit to be upgraded into military units. Thus, military buildings in Battle Realms are used for transforming and upgrading units rather than producing them directly.
>
> Another unusual trait is unit generation, where peasants are produced automatically at no cost. The rate at which new peasants are produced is inversely proportionate to the current population of the player's army.

Because you're not necessarily combating the game time with regards to rush timings or perfect/optimal unit composition, you're actually fighting against your own time constraint, that being the ever decreasing rate of unit production. This promoted more frequent skirmishes as your tech tree allowed you to create stronger units, but getting those stronger units wouldn't be as easy if your old units weren't engaged in combat.
> 0 votes

---
Tags: game-design, rts, combat
---


title: Why RaycastAll misses some objects?

text:
# Question
Title: Why RaycastAll misses some objects?
**Update 2 (see below)**

I'm writing a turn-based game. During setup phase time scale modifier equals to 0, what prevents running of any physics-based code and FixedUpdates. User have freezed action and may make decisions.

The problem is that sometimes I cannot select objects during the setup mode. I'm doing selection in the following way:

* I obtain mouse position ray
* I run RaycastAll against this ray without limitations
* I check for hit objects, which has Selectable script on them. Then rest of the logic happens.

Mouse handling looks like following:

```
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

(...)

RaycastHit[] hits = Physics.RaycastAll(ray);

// DEBUG
string debug = "Raycast all gave " + hits.Length + " hits:";
for (int i = 0; i < hits.Length; i++)
    debug += hits[i].collider.gameObject.name + "; ";
Debug.Log(debug);
// END DEBUG

```

Sometimes though I'm not getting valid results from RaycastAll. Take a look at the following example:

I clicked top-left blue ship. You may see a small sphere on it - I wrote a debug code, which generates a series of spheres along the ray to make sure, that it is valid. Since you see only one sphere here, it seems like everything's OK (note that I added this code to diagnose the problem. Spheres surely aren't causing it)

The scene view looks like following:

It should be clear on this image, that ray hits the ship's box collider. In this specific case, a couple of units next to ship is an explosion, which has bigger sphere collider.

You can also see debug log from the session, which clearly says, that RaycastAll only hit explosion and it missed the ship, which is just next to it.

Now the question is: **why RaycastAll doesn't return the ship along with the explosion?**

Note, that this problem happens more often and without near objects with colliders, sometimes I just cannot select a ship and all I have to do is to move camera, such that object is closer to center of the screen.

---

**Edit:** Now this gets interesting!

I added some debugging. After the RaycastAll, I manually go over all colliders in the scene and verify the raycast. The code now looks like following:

```
        RaycastHit[] hits = Physics.RaycastAll(ray);

        // DEBUG
        string debug = "Raycast all gave " + hits.Length + " hits:";
        for (int i = 0; i < hits.Length; i++)
            debug += hits[i].collider.gameObject.name + "; ";
        Debug.Log(debug);

        var colliders = GameObject.FindObjectsOfType<Collider>();
        foreach (var collider in colliders)
        {
            RaycastHit temp;
            if (collider.Raycast(ray, out temp, float.PositiveInfinity))
            {
                Debug.Log("Manually verified, that ray hits " + collider.gameObject.name);
            }
        }

        // END DEBUG

```

And when I try to click the "un-raycastable" object, I get:

```
Raycast all gave 1 hits:MissileExplosion(Clone);
Manually verified, that ray hits MissileExplosion(Clone)
Manually verified, that ray hits Falcon(Clone)

```

A bug in Unity engine?

---

**Edit:** Yup, a bug in Unity engine.

> Hey,
>
> We have been able to reproduce this bug and have sent it for resolution with our developers.
>
> Regards, Unity QA

# Answer
> 0 votes
This seems to be a bug in Unity engine. It has been sent to Unity devs for resolution and hopefully a fix will be in place in next Unity version.

---
Tags: unity, collision-detection, raycasting
---


# Question
Title: At what stage of game development is it a good time to ask for feedback?
I'm making a 2D top-down fantasy "Nuclear Throne"-like game. I'm at the point where a player can walk around, pick up weapons and kill some enemies. I'm not an artist, so it looks pretty rough and its clearly unfinished as you can't even progress to newer levels. I want to know if its too soon to ask my friends/family/coworkers and the sort to give the game a test run to see how they like the base combat mechanics. Or even post some screenshots and start getting social media coverage up and running. If now isn't the time, when will I know it is?

I do plan on marketing the game commercially, I am the sole developer at the moment, and its my first commercial game.

# Answer
> 3 votes
Fail Faster!

Game development is an iterative process.

Playtest early, playtest often. Playtest with many different people. Never be afraid of feedback. Test stuff before you polish it, so you don't waste as much work when you throw it away and rebuild it from scratch.

I made that mistake before. I once spent months building a game around a specific game idea. I wanted to do everything right from the beginning. It was supposed to be multiplayer, so I had a client/server architecture from the beginning. I added a persistence layer. I wrote a custom UI system with window handling. I added an NPC dialog system with a scripting engine, etc. etc.. And when it was finished it all worked great. But then I realized for the first time that the whole game idea just did not work out. My basic game mechanic just wasn't any fun. And no amount of polish or tweaking would have been able to fix that.

I could have figured that out within hours if I had just built a quick&dirty prototype first to test the basic game mechanics in a simple offline environment. I would have been able to realize its flaws before building a whole game around it. It would have saved me months of work.

So always do the core gameplay first, so you have something you can testplay. Add polish and frills later.

But regarding posting screenshots on social media to build up hype: I would recommend you to wait with this until you found out how you want your game to look and have enough assets in production-ready quality to demonstrate those aesthetics. Screenshots are mostly about the visuals. When your first screenshots show only primitive placeholder art, then you will turn away a lot of people who expect more. And when you later get around to give your game the look you wanted it to have, then those people you did get on the hype train might be disappointed because it's not the look they expected.

# Answer
> 3 votes
It's always a good time to get feedback. Earlier feedback can help avoid spending a lot of time developing something you end up not using or changing later on.

It's particularly good in your case to discover things that you as the lone developer may not notice. Maybe the game doesn't run well on other platforms. Maybe you hadn't considered how to build? Maybe it's difficult to understand what's going on?

These things may in turn require core changes to your project. Might as well discover them early on.

A prototype game is also very motivating, and lets you discover problems yourself.

However, it may not be worth spending all your time gathering feedback. As the time spent developing would then suffer. For a project the size of yours, I would recommend asking a friend to test it, perhaps while you watch, and ask a few simple questions afterwards.

Posting screenshots and social media do not have these advantages. It may help you garner interest to get willing testers, but in your case, I feel time spent marketing might as well be spent after the product is complete. You can only do so much at once.

Keeping screenshots to track your progress might be motivating to look back at.

# Answer
> 1 votes
If you have enough code in the game already to demo the concept of the game, regardless of the textures/models etc then it's actually a good time to get some feedback as there are always things you don't consider when writing pretty much all software that the users not personally involved in coding it will pick up on.

All I'd suggest is be as specific as you can about what you want testing when asking someone to test.

Just my two cents, in no way an expert (I'm a web dev same applies, Game dev is for fun) just read a lot of programming books/articles.

---
Tags: game-mechanics, playtesting
---