# Question
Title: Unity C# issue with very basic event management system
*There is quite a lot of code involved in this so I'm going to keep this as basic as possible.*

**Scenario**

I have a scene that loads & unloads other scenes to produce the environment I need. There are a number of Event Triggers and Listeners throughout. Long story short the `HUD` is listening for `Level.LOADED` which happens every time a new level is loaded in via `LoadScene`. The `Level` class is attached to each level scene via script component.

**Problem**

When level1 is unloaded and level2 is loaded the `Level.LOADED` event fires as planned. Where it gets weird is that the HUD, which has remained alive in a different scene the whole time, stops listening to `Level.LOADED` after level1 is unloaded.

I've logged all the events being listened for, during Level1 I see `LEVEL_LOADED` on the `HUD`, after level2 is loaded I do not see `LEVEL_LOADED` on the `HUD` anymore. I also logged everything that has run through `StopListening()` and I never see `Level.LOADED` go through there so I'm rather confused as to why it's missing from the listen-to list of the `EventManager`. Since `Level.LOADED` is a public static member of the `Level` class I wouldn't think that unloading `Level1` would be an issue. I've also tried making `Level.LOADED` more global by moving it to the game level (persistent) with no success.

**Question**

Why does my `HUD` object stop listening for `Level.LOADED` once Level1 is unloaded?

**Notes**

* I tried moving `Level.LOADED` to a class that is never loaded/unload with no success.

**EDIT with "solution"**

I found the issue, an unexpected release of `EventManager` when an adjacent scene is unloaded.

Consider my project heiarchy:

MainScene - persistent

* EventManager script

GameScene - active, persistent

* HUD

LevelX - changes per level

* Level stuff

`MainScene` and `GameScene` are never unloaded. I eventually found out that the EventManager's `OnDestroy` is triggered when `LevelX` (any level) is unloaded. This destroys my event list and then on `Init` a new one is created, empty. I have NO IDEA how scene load / unload is effecting my `EventManager` class as it's on `MainScene`

My solution was to make my EventManager's `eventDictionary` a static variable, this way it does not get destroyed when the EventManager is destroyed.

This leads me to post another question. Why does my script from one (permanent) scene get destroyed from a script in a completely different scene when that scene is unloaded? I plan to post a completely separate question with a recreatable example demonstrating this new problem.

**EDIT PS**

The `GameScene` does not `OnDestroy` when `LevelX` unloads so I made `MainScene` the active scene and `GameScene` becomes destroyed on level unload. I thought this was the issue until I noticed that `EventManager` is still getting destroyed.

The answer I accepted is more relevant to the OP context. Thx to @Evorlor

**Code**

# EventManager.cs

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

public class EventManager : MonoBehaviour
{
    private List<Event> eventDictionary;
    private static bool _errorDisplayed = false;

    private static EventManager eventManager;

    public static EventManager instance
    {
        get
        {
            if (!eventManager)
            {
                eventManager = FindObjectOfType(typeof(EventManager)) as EventManager;

                if (!eventManager)
                {
                    if (!EventManager._errorDisplayed)
                    {
                        EventManager._errorDisplayed = true;
                        Debug.LogWarning("There needs to be one active EventManger script on a GameObject in your scene.");
                    }
                }
                else
                {
                    eventManager.Init();
                }
            }

            return eventManager;
        }
    }

    void Init()
    {
        if (eventDictionary == null)
        {
            eventDictionary = new List<Event>();
        }
    }

    void OnDestroy() {
        EventManager.instance.eventDictionary.Clear();
    }

    public static bool HasListener(string eventName, Action<object> listener)
    {
        if (EventManager.instance == null
            || EventManager.instance.eventDictionary.Count <= 0) return false;

        bool ret = false;
        EventManager.instance.eventDictionary.ForEach(e =>
        {
            if (e.eventName == eventName && e.listener == listener)
            {
                ret = true;
            }
        });

        return ret;
    }

    public static void StartListening(string eventName, Action<object> listener)
    {
        if (!EventManager.instance)
        {
            Debug.LogError("EventManager has not been initted. Is there one added to your scene yet?");
            return;
        }

        //Debug.Log("EventManager.StartListening: " + eventName);

        Event e = new Event(eventName, listener);
        EventManager.instance.eventDictionary.Add(e);
    }

    public static void StopListening(string eventName, Action<object> listener)
    {
        //Debug.Log("EventManager.StopListening: " + eventName);

        //System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace();
        //Debug.Log(stackTrace.GetFrame(1).GetMethod().Name);

        if (EventManager.instance == null
            || EventManager.instance.eventDictionary.Count <= 0) return;

        EventManager.instance.eventDictionary.ForEach(e =>
        {
            if (e.eventName == eventName && e.listener == listener)
                EventManager.instance.eventDictionary.Remove(e);
        });

        //Debug.Log("event listener count: " + EventManager.instance.eventDictionary.Count);
    }

    public static void TriggerEvent(string eventName, object opts = null)
    {
        //Debug.Log("TriggerEvent: " + eventName);

        if (EventManager.instance == null) {
            Debug.LogError("This shouldn't happen unless gameplay stopped"); // @jkr
        }

        //Debug.Log("TriggerEvent length: " + EventManager.instance.eventDictionary.Count);

        EventManager.instance.eventDictionary.ForEach(e =>
        {
            //Debug.Log(e.eventName);
            if (e.eventName == eventName)
            {
                //if (eventName.Equals(Level.LOADED)) {
                //    Debug.Log(e.listener);
                //}
                e.listener.Invoke(opts);
            }
        });
    }
}

class Event
{
    public string eventName;
    public Action<object> listener;

    public Event(string eventName, Action<object> listener)
    {
        this.eventName = eventName;
        this.listener = listener;
    }
}

```

# Level.cs

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

// @jkr

public class Level : MonoBehaviour {

    public static string BEGIN = "Level.BEGIN"; // countdown finished @jkr
    public static string FINISH = "Level.FINISH"; // time for the next level @jkr
    public static string LOADED = "Level.LEVEL_LOADED";

    private const int LEVEL_BEGIN_DELAY = 1;
    private const int LEVEL_FINISH_DELAY = 1;

    public static Level instance;

    private int _levelId;
    private int _timeLimit = 1;

    // Use this for initialization
    void Start () {
        Debug.Log("Level.Start: " + this.gameObject.scene.name);

        // self assign level id;
        string levelName = this.gameObject.scene.name;
        string id = levelName.Substring(6);
        this._levelId = int.Parse(id);

        if (Level.instance == this) {
            Debug.Log("Should never be set to the same instance, definitely check this out @jkr");
            return;
        }

        Level.instance = this;

        EventManager.StartListening(GameTimer.FINISH, this.GameTimerFinishHandler);

        //GameTimer.instance.StopWithSeconds(this._timeLimit);

        EventManager.TriggerEvent(Level.LOADED, null);
        Invoke("Begin", Level.LEVEL_BEGIN_DELAY);
    }

    void OnDestroy() {
        //Debug.Log("Level.OnDestroy: " + this.gameObject.scene.name);

        EventManager.StopListening(GameTimer.FINISH, this.GameTimerFinishHandler);
    }

    void GameTimerFinishHandler(object opts)
    {
        Invoke("Finish", Level.LEVEL_FINISH_DELAY);
    }

    void Begin() {
        EventManager.TriggerEvent("Level.BEGIN", new Dictionary<string, object>() { { "this", this } });
    }

    void Finish()
    {
        EventManager.TriggerEvent("Level.FINISH", new Dictionary<string, object>() { { "this", this } });
    }

    public static int TimeLimit {
        get {
            return Level.instance._timeLimit;
        }
    }

    public static int Id {
        get {
            return Level.instance._levelId;
        }
    }
}

```

# HUD.cs

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

// @jkr

public class HUD : MonoBehaviour {

    private int _score = 0;

    // Use this for initialization
    void Start () {
        Debug.Log("HUD.Start");
        EventManager.StartListening(Level.LOADED, LevelLoadedHandler);

        //EventManager.StartListening(, PointsChangeHandler); // points

        EventManager.StartListening(GameTimer.START, GameTimerStartHandler);
        EventManager.StartListening(GameTimer.CHANGE, GameTimerChangeHandler);
        EventManager.StartListening(GameTimer.FINISH, GameTimerFinishHandler);

        EventManager.StartListening(Target.HIT, TargetHitHandler);

        this.LevelText = 0;
        this.TimeLeftText = 0;
        this.ScoreText = 0;
    }

    private void LevelLoadedHandler(object opts) {
        Debug.Log("HUD.LevelLoadedHandler: " + Level.Id);
        this.LevelText = Level.Id;

        //Debug.Log("Level Loaded; timeLimit: " + Level.TimeLimit);
        this.TimeLeftText = Level.TimeLimit;
        this.CaptionText = "Get Ready!";
    }

    private void TargetHitHandler(object opts) {
        IDictionary dopts = (IDictionary)opts;

        if (!dopts.Contains("this")) return;
        Target target = (Target)dopts["this"];

        if (!target) return;

        this.ScoreText += target.TargetValue;
    }

    private void GameTimerStartHandler(object opts) {
        this.GameTimerChangeHandler(opts);

        this.CaptionText = "";
    }

    private void GameTimerChangeHandler(object opts) {
        int timeLeft = GameTimer.instance.Seconds;

        this.TimeLeftText = timeLeft;
    }

    private void GameTimerFinishHandler(object opts)
    {
        this.GameTimerChangeHandler(opts);

        this.CaptionText = "Round Over";
    }

    private string CaptionText {
        set
        {
            //Debug.Log("CaptionText SET: " + value.ToString());
            Text t = GameObject.Find("Caption Text").GetComponent<Text>();

            //if (value.Equals(""))
            //{
            //    t.gameObject.SetActive(false);
            //    return;
            //}

            //t.gameObject.SetActive(true);
            t.text = value.ToString();
        }
    }

    private int LevelText {
        set
        {
            Text t = GameObject.Find("Level Text").GetComponent<Text>();
            t.text = value.ToString();
        }
    }

    private int TimeLeftText {
        set {
            Text t = GameObject.Find("Time Left Text").GetComponent<Text>();
            t.text = value.ToString();
        }
    }

    private int ScoreText
    {
        get {
            return this._score;
        }
        set
        {
            this._score += value;

            Text t = GameObject.Find("Score Text").GetComponent<Text>();
            t.text = this._score.ToString();
        }
    }
}

```

# Answer
I think your approach is too complicated. Unity SceneManager has built-in events for when a scene/level is loaded or unloaded. Unity also has two messages, OnEnable and OnDisable. They are called when a component is enabled or disabled, respectively. This is where you should register and unregister for events.

So what you should do is clean up all of the extra code used to listen for scenes/levels being loaded and unloaded. From there, you can add this code to HUD.cs:

```
/// <summary>
/// Unity will call this when script is enabled, but you can also register for events elsewhere
/// </summary>
private void OnEnable()
{
    SceneManager.sceneLoaded += OnSceneLoaded;
    SceneManager.sceneUnloaded += OnSceneUnloaded;
}

/// <summary>
/// Unity will call this when the script is disabled, but you can also unregister for events elsewhere
/// </summary>
private void OnDisable()
{
    SceneManager.sceneLoaded -= OnSceneLoaded;
    SceneManager.sceneUnloaded -= OnSceneUnloaded;
}

/// <summary>
/// Called from the event registered above
/// </summary>
/// <param name="scene">Scene which was loaded</param>
/// <param name="loadSceneMode">Whether this scene was loaded additively or as a single scene</param>
private void OnSceneLoaded(Scene scene, LoadSceneMode loadSceneMode)
{
    Debug.Log(scene.name + " was loaded as a(n) " + loadSceneMode + " scene!");
}

/// <summary>
/// Called from the event registered above
/// </summary>
/// <param name="scene">Scene which was unloaded</param>
private void OnSceneUnloaded(Scene scene)
{
    Debug.Log(scene.name + " was unloaded!");
}

```

Be sure to include the `UnityEngine.SceneManagement` namespace.

In general, you want to use Unity's UnityAction for event handling. This is done like such:

```
//Class 1
public UnityAction MyAction;

private void CallAction()
{
    MyAction?.Invoke(); //In .NET 4+

    if(MyAction != null) //In .NET 2.5
    {
        MyAction();
    }
}

//Class 2
private void OnEnable()
{
    Class1.MyAction += DoIt;
}

private void OnDisable()
{
    Class1.MyAction -= DoIt;
}

private void DoIt()
{
    //This is called when CallAction() is called.
}

```
> 2 votes

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


# Question
Title: Unity 2D: Inconsistent jump height in game window
Whenever I start the unity editor and play it in the Game windows, sometimes the object can jump higher sometimes it is just small jump. I didn't change any value in my script nor changed it in inspector window.

It usually happens when I restart the unity editor or having my computer shutdown / restart and reopening the project.

Here are the jump code

```
void jump() {
     if (isInGround) {
         float currentJumpForce = jumpForce * Mathf.Abs(rigidBody.velocity.x) / 3.53f;
         rigidBody.AddForce(Vector2.up * currentJumpForce);
         animator.SetTrigger("isJump");
     }
}

```

I place the code inside the `FixedUpdate` method, for what I have read the physics calculation should be inside `FixedUpdate` right?

```
private void FixedUpdate() {
    if (Input.GetKeyDown(KeyCode.UpArrow)) {
        jump();
    }
}

```

I have read many are having similar problem, but it really doesn't answer this question.

**UPDATE:**

I forget to explain it in the question. The `jumpForce` is calculated based on the velocity of the gameObject has. I capped the velocity to certain speed based on this code

```
void accelerate() {
     if (rigidBody.velocity.x <= maxSpeed) {
         rigidBody.AddForce(Vector2.right * acceletateForce);
     }
}

```

where `maxSpeed` is a constant. I know this is probably not the accurate way to cap the velocity, or is it? Maybe this is where it gets messed up?

I just kinda assume the velocity is the capped from the camera movement and the 'display' or the movement of the screen. It seems the same to me.

# Answer
Physics calculations should indeed be in the FixedUpdate. However, Input should be captured in the Update. This is because the FixedUpdate is called whenever the physics engine updates, while Update is called whenever the screen updates. You can thus have more than one call to FixedUpdate in the frame where the user pressed the key.

There are two options to solve this. First, call the jump function in the Update function, which works, though not entirely correct. Or set a flag in the Update and call the Jump function in FixedUpdate.

See also this
> 1 votes

---
Tags: unity, 2d, physics
---


# Question
Title: simple data source on hard disk for android game
i have a big library on my game. its word library. there is no need of it to be on ram.any moment some part of it can be searched so there is no need to make a list or dictionary for it. is there any type of file data that can be added to apk file?

# Answer
> 2 votes
I'm not sure how your library is organised, but it seems it's just a data library with some interface to access such data.

You can have a separate file with all the data you need (the words) which can be in any format you like (a raw text file, or a json file etc), then you'll need one script file, to access that data and load/unload the file at will. The script file can be structured to call first `LoadFile()` and then `FindWord(String word)` followed by `UnloadFile()`, to make sure the data are not in ram when not needed. This assumes you will need to find plenty words in a short period of time (like a bunch of words for every stage of a game?).

I assume your current library is already in Java, so it would be fairly easy to change it to fit the above description. There are also plenty json parsers for android online which you may be able to use, so you don't have to bother on parsing the file yourself.

---
Tags: android, data
---


# Question
Title: Is Update() called on the very first frame in Unity?
I'm calling `Time.frameCount` inside `Update()` and then immediately `Debug.Break()` to pause the simulation before `Update()` is finished. This of course happens (supposedly) on the very first frame, and yet `Time.frameCount` returns `1`, as if one frame had already been rendered by at that point. Also, I'm calling `Time.deltaTime` the same way, on the first frame inside `Update()`, and it returns a value too, as if a previous frame had been rendered and took X milliseconds.

Considering `Time.deltaTime` returns the value of the *"time it took to complete the last frame"*, and I'm calling it on the first frame and it's returning a value, is there an "invisible" first frame that `Update()` doesn't run on?

I couldn't find any reference to this specific issue on the Unity docs.

# Answer
> 2 votes
`Update()` is called during a frame. `Time.frameCount` counts the *number of frames* that have occurred. It's a count, not an index, so during frame *zero* (the first frame) the total number of frames (`Time.frameCount`) will be one.

There is no invisible first frame. It's typical to initialize "delta time" values with some reasonable small number for the first frame, because any values that are "technically correct" such as 0 or the time since you last launched the application are generally meaningless for the purposes of running the game simulation.

---
Tags: unity, frame-rate, timestep
---


title: Simulating Enums with Javascript

text:
# Question
Title: Simulating Enums with Javascript
When developing in Javascript, it seems useful especially for event systems to use enum-likes, but not string comparison for performance considerations (also because it doesn't protect against typos). How do you use Enums in JS? Should I switch to Typescript?

# Answer
Use Symbols.

Symbols are unique. Even if you pass the same value to them, they won't be the same.

```
let MY_ENUM = Symbol(1);
let MY_ENUM2 = Symbol(2);

alert(MY_ENUM == MY_ENUM2); // false

```

So store these in an object. To make sure the enum you reveive in a function is of a certain type, just use the `in` keyword.

```
let myEnumObj = {
    MY_ENUM: Symbol(1)
};

function foo(bar) {
    if (bar in myEnumObj) { ... }
}

```
> 2 votes

# Answer
I also use Symbols, and have implemented them in an object literal like below using a setter.

I am using the object key as the string description inside `()` for easier debugging, and throw an error if the key is invalid.

```
export default {

  currentScreen: null,

  SCREEN: {
    TITLE_SCREEN: Symbol('TITLE_SCREEN'),
    GAME_SCREEN: Symbol('GAME_SCREEN'),
    PAUSE: Symbol('PAUSE'),
    GAMEOVER_SCREEN: Symbol('GAMEOVER_SCREEN'),
  },

  set setScreen(key) {
    if (key in this.SCREEN) {
      this.currentScreen = this.SCREEN[key];
    } else {
      throw new TypeError(`${key} is invalid key for SCREEN object`);
    }
  },

}

```
> 0 votes

---
Tags: javascript, events
---


# Question
Title: Why are points adjusted using the projection and inverse view matrix during picking?
I am working on my first 3D game, which contains several vehicles placed on a board. I want to implement mouse picking of the vehicles. I found this great tutorial and used its code. But I don't understand part of the math.

Early in the function (listed below), I convert the input mouse coordinates into the -1 to +1 range:

```
// Create picking ray from camera position and mouse click
void VehiclePicker::SetPickingRay(LONG mouseX, LONG mouseY) {
    float pointX, pointY;

    /* Conversion to -1 to +1 here: */
    // Move the mouse cursor coordinates into the -1 to +1 range.
    pointX = ((2.0f * static_cast<float>(mouseX)) / static_cast<float>(SCREEN_WIDTH)) - 1.0f;
    pointY = (((2.0f * static_cast<float>(mouseY)) / static_cast<float>(SCREEN_HEIGHT)) - 1.0f) * -1.0f;

    ...

```

Next, I adjust the points using the projection matrix. Listed below:

```
    XMFLOAT4X4 prMtrx;
    // Convert projectionMatrix from XMMATRIX into XMFLOAT4X4 in order to pick its members
    XMStoreFloat4x4(&prMtrx, _d3d->GetProjectionMatrix());
    pointX = pointX / prMtrx._11;
    pointY = pointY / prMtrx._22;

```

I don't understand what is exactly done here. I understand that I should somehow transform the points using the inverted projection matrix into world space. But in the tutorial they are using non-inverted projection matrix and using only two elements from it for dividing the points. Why? In tutorial, they say they want "Adjust the points using the projection matrix to account for the aspect ratio of the viewport." Could somebody please explain it?

The same question is for the next part of the code. In tutorial they say "Calculate the direction of the picking ray in view space." Could you please also explain this one?

```
    // Get the inverse of the view matrix.
    XMFLOAT4X4 invViewMtrx;
    // Convert inverseViewMatrix from XMMATRIX into XMFLOAT4X4 in order to pick its members
    XMStoreFloat4x4(&invViewMtrx, XMMatrixInverse(nullptr, _camera->GetViewMatrix()));
    XMFLOAT3 dir;
    dir.x = (pointX * invViewMtrx._11) + (pointY * invViewMtrx._21) + invViewMtrx._31;
    dir.y = (pointX * invViewMtrx._12) + (pointY * invViewMtrx._22) + invViewMtrx._32;
    dir.z = (pointX * invViewMtrx._13) + (pointY * invViewMtrx._23) + invViewMtrx._33;
    _pickingRayDirection = XMLoadFloat3(&dir);

```

I understand that the goal is to invert the process of rendering 3D scene into 2D screen. But I don't understand the math used.

Here's the rest of the function, for context:

```
    // Get the origin of the picking ray which is the position of the camera.
    _pickingRayOrigin = _camera->GetPosition();

    // And finally I must normalize the final vector
    _pickingRayDirection = XMVector3Normalize(_pickingRayDirection);
}

```

# Answer
> 1 votes
Your world geometry is translated to the view via your world and projection matrix. Your raycast is starting in the screen space and needs to be converted back to world space. Usually your world space is an identity matrix. To convert your Ray firstly you have established it's co-ordinates in the screen/projection view. You then invert your projection matrix to convert your Ray back into world space so then you can test collisions with your world.

What you will find us that the next trick is to effectively test your Ray against the world objects is to convert the ray to local space of each object. You can then use things such as AABB tests etc to detect collisions.

Good luck

---
Tags: directx, picking
---


# Question
Title: Preventing a Combination of Rigidbody Jump Force & Bounce Magnitude in Unity3D
I'm building a fairly simple marble racing game in Unity3D. The ball is a 3D physics object that moves only on the X and Y axes. It has the ability to roll left and right, and to jump. Pretty basic stuff, except that I've hit a game-breaking problem: When falling and striking the ground, the ball's bounce magnitude can be combined with its jumping force to create an extra-high jump. This means that, with well-timed button presses, the player can cause the ball to bounce exponentially higher, reaching unintended heights. I can't properly design levels until this glitch is fixed. I've illustrated this example:

The jumping, however, isn't as simple as just firing the ball straight upwards. In order to facilitate more complexity in the level design, I've programmed the jump angle to be relative to the surface that the ball is rolling on.

**Figure 3**, in that illustration, is how my game works thus far; not **Figure 4**. This makes solving for the bounce + jump problem much more challenging, because I can't simply measure and set an exact force or velocity on the Y-axis. Doing so results in weird behaviour, which becomes dramatically more noticeable as the ball travels on steeper slopes.

So far, I've been able to conceive a solution to all the other design problems in this game and then find out how to program them, but this one has me stuck. I've attempted a number of different approaches, but none of them have worked.

Here's the C# script that controls the ball's jumping:

```
using UnityEngine;
using System.Collections;

public class BallJumping : MonoBehaviour {

    public System.Action onJump;
    public Rigidbody objRigidbody; // Set this to the player
    public bool isGrounded; // Determines whether or not the ball is on the ground
    public Transform groundChecker; // A child object that's slightly larger than the ball
    public float groundRadius = 0.6f;
    public LayerMask whatIsGround; // Determines what layers qualify as ground
    public AudioClip jumpSFX;
    public AudioClip stickyJumpSFX;
    private float p_WillJumpTimeRemaining; // Grace periods before/after hitting the ground to trigger jump
    private float p_CanJumpTimeRemaining;
    public float earlyJumpToleranceDuration = 0.2f;
    public float lateJumpToleranceDuration = 0.2f;
    public float jump = 500f; // Jumping power
    private float halfJump = 250f; // Used for the sticky puddles
    public bool stuck = false; // Used for sticky materials
    private float contactX;
    private float contactY;

    // Input for jumping
    void Update () {
        if (Input.GetButtonDown ("Jump") && isGrounded == true) {
            ProcessJump();
        }
    }

    // Continuously checks whether or not the ball is on the ground
    void FixedUpdate () {
        if (Physics.CheckSphere (groundChecker.position, groundRadius, whatIsGround) == true) {
            isGrounded = true;
        } else {
            isGrounded = false;
        }
    }

    // Sets a grace period for before or after the ball contacts the ground for jumping input
    void ProcessJump () {
        bool boolGetJump = Input.GetButtonDown("Jump");

        if (boolGetJump && isGrounded == false) {
            p_WillJumpTimeRemaining = earlyJumpToleranceDuration;
        } else {
            if (p_WillJumpTimeRemaining > 0) {
                p_WillJumpTimeRemaining -= Time.fixedDeltaTime;
            }
        }

        if (isGrounded) {
            p_CanJumpTimeRemaining = lateJumpToleranceDuration;
        }

        if (isGrounded || p_WillJumpTimeRemaining > 0) {
            Jump();
        }

        if (p_CanJumpTimeRemaining > 0) {
            p_CanJumpTimeRemaining -= Time.fixedDeltaTime;
        }
    }

    // Sticky puddles script -- hinders jumping while in the puddle
    void OnTriggerEnter (Collider collision) {
        if (collision.gameObject.tag == "Sticky") {
            stuck = true;
        }
    }

    void OnTriggerExit (Collider collision) {
        if (collision.gameObject.tag == "Sticky") {
            stuck = false;
        }
    }

    // Calculates the normals for the jump angle
    void OnCollisionStay (Collision collision) {
        Debug.Log ("Collision.");
        foreach (ContactPoint contact in collision.contacts) {
            contactX = contact.normal.x;
            contactY = contact.normal.y;
        }
    }

    // Controls jumping
    void Jump() {
        Debug.Log ("Jump.");
        p_WillJumpTimeRemaining = 0.0f;
        p_CanJumpTimeRemaining = 0.0f;
        halfJump = jump * 0.5f; // Cuts jumping force in half while in a sticky puddle

        GetComponent<AudioSource>().volume = 1;
        GetComponent<AudioSource>().pitch = Random.Range (0.9f, 1.1f);

        if (stuck == false) {
            objRigidbody.AddForce (contactX * jump, contactY * jump, 0);
            GetComponent<AudioSource>().clip = jumpSFX;
            GetComponent<AudioSource>().Play ();
        }
        else if (stuck == true) {
            objRigidbody.AddForce (contactX * halfJump, contactY * halfJump, 0);
            GetComponent<AudioSource>().clip = stickyJumpSFX;
            GetComponent<AudioSource>().Play ();
        }

        if (onJump != null) {
            onJump();
        }
    }
}

```

My latest attempt was to try **jump - rigidbody.velocity.magnitude * 50** , to reduce the jumping power by the speed that the ball is travelling. It almost solved the bounce + jump problem, by proportionally reducing the jump force down to zero as the ball's speed reached what seemed to be the equivalent in velocity.magnitude. It worked from a standstill, but the problem is, it also accounts for the magnitude while the ball is grounded, preventing the ball from rolling at full speed and jumping. I was close, but not quite there!

I'm a novice programmer, and I'm stumped here. Can anyone help me find a creative solution to this problem? As long as the player is able to continuously bounce and jump higher and higher, I can't design any levels, because they'll all just be able to be cheated through. I'd love to move onward -- this issue has been holding me back for a long time, so I'd greatly appreciate some advice!

# Answer
While I personally love bunny hopping... As a starting point we should know the intended "Jump Speed" as a delta velocity. This figure represents the velocity increase (in the line with the "Jump Normal") during the instant of jumping once.

Any velocity the player already has in line with the Jump Normal can be seen as a pre-existing "Jump Energy". This leads to a straightforward solution: The instantaneous delta velocity can be limited such that it never results in the player being accelerated beyond the target velocity.

In order to measure your pre-existing Jump Speed, we can take the dot product of your normalized your Jump Vector, and your player's velocity:

```
Vector2 JumpNormal = Vector2(contactX, contactY).normalized;
Vector2 PlayerVelocity = objRigidbody.velocity;
float ExistingSpeed = Vector2.Dot(PlayerVelocity, JumpNormal);
if (ExistingSpeed < 0) ExistingSpeed = 0;

```

The "Existing Speed" is also forced non-negative here; When the player is falling, a negative existing jump speed will compensate for their falling, allowing them to bounce on thin air if they trigger the jump while falling.

Now that we know how much to reduce the delta velocity precisely, we can compute the effective "Jump Vector" by scaling the Jump Normal to the target delta velocity.

```
float AdjustedSpeed = JumpSpeed - ExistingSpeed;
if (AdjustedSpeed < 0) AdjustedSpeed = 0;
Vector2 JumpVector = JumpNormal * AdjustedSpeed;
objRigidbody.velocity += JumpVector;

```

This time the Adjusted Jump Speed is being forced non-negative; If the player is already rising faster than they should be able to jump, they would attain a negative adjusted speed, which allows them to use the "jump" action as brakes. (to slow down to the intended jump speed instantly!)

Note: I believe your contact X and Y are already normalized as a pair. I included explicit detail for completeness sake though.
> 1 votes

# Answer
First of all, i want to say that your question is very well written and it's a pleasure :), you would just need to remove what's not necessary in the code (audiosources, etc.) and it would be perfect. Cheers for that.

For the answer, you could clamp your velocity when jumping, which would prevent you from reaching too high speeds when pressing the jump button.
> 0 votes

# Answer
This answer is perhaps more of a design change than you're looking for, but how about this - the ball has a short period after the jump button is pressed where it stays firmly on the ground and cancels any upward vertical momentum (maybe squashing a bit to denote a spring-like compression), *then* leaps upward after that period has concluded. This would solve the problem of the bounce's momentum adding to the jump, although it would also allow players to control whether or not they bounced or just jumped. It also adds a delay to the jump function, which can be seen as good (feels more natural) or bad (doesn't allow players enough time to respond).
> 0 votes

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


# Question
Title: How can I write an additive mesh shader that splits the RGB channels while accounting for depth?
I'm trying to create a sort of "hologram" effect. So far, what I have is an additive, three-pass shader that uses ColorMask for each pass to separate the RGB channels. The problem is that doing so requires ZWrite to be off (first image) so that each pass doesn't intersect the others (second image). However, doing so means that the model geometry overlaps itself, which I don't want.

I've tried the various methods of taking depth into consideration with transparency (This, for example) but they all cause problems when trying to separate the RGB channels. Is there some way to have each pass take depth into consideration within itself, but not with the other passes?

# Answer
You should look into Grab Pass (details here). Basically it grabs the scene before you render for pretty much this exact purpose. It's not the cheapest operation, but unless you're going crazy with it I doubt you'll have any real problems.
> 0 votes

---
Tags: unity, shaders, fragment-shader, depth-buffer, transparency
---


title: Coloring a Voronoi Graph

text:
# Question
Title: Coloring a Voronoi Graph
**Intro:**

I want to convert a Voronoi Graph made with this awesome library by jceipek on GitHub into something I can work on.

So far so good, this user provides with a demo to start with and shows how to generate the VG.

**Question:**

**How do I convert the VG (made by edges and that dot in the middle) into something that I can work with?**

Such as, after you generate some noise and apply to it (height), you colour the polygons based on it.

**Thoughts:**

Something comes to my mind about instantiating meshes and tiles based on the edges and the position of the dot as a start, but it won't work if I can't "detect" the polygon.

**Expected result:**

Image from this blog about Voronoi Mapping link

**What I have:**

It is drawn with Gizmos (for visual debugging in Unity)

I want to know how to color my polygons as in the expected image above. So I thought about doing a mesh or individual tile (and color it based on height afterwards but that is sauce for another question if needed)

**Edit of my progress:**

To further explain this question I provide the next image.

The image shows that I could use that position data somehow and turn that random polygon shape into a "tile" that will have a colour (mesh?) and possible data in it (script).

I hope this helps otherwise let me know in the comments.

# Answer
While you could detect the polygon, it would be simpler to directly use the data that was used to generate them.

If you check `Voronoi.cs` there is a method called `Regions ()` which returns a `List<List<Vector2>>`. Each sub list is list of points for a given region. From there you can turn the points into a mesh.
> 3 votes

# Answer
So you can do this by placing a cone mesh (tip facing the camera) at each point.

Assuming each cone has a unique color (and sufficient radius), the depth buffer should automatically "segment" your colors (assuming an ortho camera).
> 0 votes

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


# Question
Title: Unity3d Pause RigidBody object, don't stop time
`Time.timeScale = 0` obviously works to stop physics but it's also stoping my `Invoke` calls. How can I get around this to pause ONLY the game physics?

**EDIT**

Temporarily I'm using `isKinematic = true` on all of my rigid body objects via event trigger.

# Answer
Turn off auto physics simulation:

https://docs.unity3d.com/ScriptReference/Physics-autoSimulation.html

Or if you happen to be doing 2D:

https://docs.unity3d.com/ScriptReference/Physics2D-autoSimulation.html
> 2 votes

---
Tags: unity, physics, timer
---


# Question
Title: Multi-threaded MMO Server with complex inter-dependencies.
I am working on a Mobile MMO and I am using .NET to build a MMO Server. My current application architecture is as follows.

* Clients are accepted using Async Calls (BeginAccept/EndAccept).
* Data incoming from the client is read using Async Calls again (BeginRead/EndRead).
* The data is parsed and handled directly on the Threadpool (EndRead) call.
* I have a dedicated thread for Monsters, which is essentially a thread with a tight while loop.

This simple architecture works fine for the most part. Now the tricky part is when I try to include interactive elements. Consider the following use-cases.

* **A Player attempts to attack other player B.** In this case the Player A's thread will try to reduce the HP of Player B. Player B on the other hand can increase the HP using Potions. There are certain kinds of attacks which will inflict self-injury on the attacking player. In this case to reduce A's HP I will have to either have a nested lock on both the players or first reduce A's HP with a lock on A and then reduce B's HP with a lock on B. Having a nested lock will be a disaster for deadlock since if B executes the same actions, then the lock order will be reversed creating a deadlock between A and B. If I first lock on A and then lock on B, what will happen if the lock on A reduces A's HP and lock on B waits because B is attempting to teleport back to town? In this case B will take the hit when B is back in the town which is not something that should happen. I could add a check to detect the range, but if the range check fails, how will I reverse the A's HP decrease? To make things more complex, multiple players can attack A or B or each other.
* **Player Discovery.** If a player moves in the game, the thread of the player scans the map cells for other players. The thread would then send the appear packet of itself to B and B's appear packet to itself. This has to be done with a lock on B, since B's appearance can change with the items worn or potion used. I will have to resort to nested locks again because I will have to make sure that when I send the packet to B, A's position is fixed and vise-versa since there are skills that could affect the location of players (Pushing the player away). In case I don't lock on A, if another player tries to use a skill to push A to another position, the updated location packet of A could reach B first before A's appear packet, which will cause the latest location packet to go useless.
* **Trading.** Players can do 1-1 trade with other players. So when the trade happens, Player A's trade items will be transferred to player B and Player B's trade items will be transferred to player A. I will have to do something like (lock A) {(lock B) { A = BItem; B=AItem; }}. This nested lock is again dangerous. If I do (lock A){ A = BItem; }; (lock B) { B = AItem; } Imagine what would happen if the A lock section is executed and by the time B is being executed, B player gets disconnected? I will have to rollback A with another lock again which is seemingly complex.
* **Monsters Attacking Players / Monster Discovery.** Similar to the discussed issues with Player Discovery and Player Attacks.

Keeping the above points in mind I would like few clarifications.

1. As you can see there is a lot of inter-dependency which will only get more and more complex once there are more features introduced in the game, is threading really worth it? With the amount of obvious lock requirements for concurrency, I might as well switch everything to a single thread and not waste time on trying to fix bugs that I can't clearly reproduce.
2. Will it be a better approach to have the packet parsing and decryption on the Threadpool thread and queue all of the packets to a mainthread that will run sequentially? The monster thread could also queue character related operations like attacking to the main thread so that every action is carried out sequentially. The network calls will still be async.

Is there any better and a proven approach that I can take to deal with these issues? The key to a successful project is always a solid architecture and I want to get it right before moving into the core development.

# Answer
> 1 votes
I'm just a hobby gamedev but it sounds to me that you have an general desing issue.

I belive it's not a good design to handle player actions on a per thread basis, for sure you can move calculations to some threads. But in general your server just:

* receives messages
* verify them
* store them in a list
* do some calculation based on received messages
* create new outgoing messages to the involved parties

In this case just incomming and outgoing messages are handled by threads. The main gamelogic stays in you game loop which works on the list of received messages. And this would be the place where things have to be synchronized.

For example you could have som threads who received messages and write to an incomming Queue. This incommig Queue will be copied everytime your game steps ahead into maybe an MessagesToProcessQueue which you gameloop works an. As an result a OutputMessageQueue will be created which will held the information which client has to be informed about what. And your threads are just dequeueing items from here to tell the clients.

So in a multiplayer game your clients (in general) are stupid and just rendering things.

## 1) A Player attempts to attack other player B

For your example the server has the information about position and health for client A and B.

When A tries to attack B, there's just a message from client A to server which tells the server that A tries to attack B.

The server then does some checks:

* is player A near to B?
* was the attack successful?
* if yes, calculate health for client B
* send a health update message for client B to client A and B

## 2) Player Discovery

The server knows all player positions. So a naive approch would be to check at a given time for each client which other clients are inside his view range. Just check if the position is inside a circle (you define how big it is) around the player.

## 3) Trading

This is the most difficult thing. Because a lot of things can go wrong, and result often in bugs like item duping in games. For example a client can abort the trade. The connection can abort and so on.

So you have to create a transaction around the whole process, and when this transaction would succeed inform all parties that it could be executed and then execute it. But you must be able to roll back the whole thing if something goes wrong (Db error, network error).

You first have to check if it could be executed because you have to check things like:

* Are the involved parties near to each other?
* Does the player own the item he want's to trade?
* Does the player have enough credits?
* Many more things to check

Because even when the player owns the item at the start of the trade. He could maybe destroy it or throw it to the ground etc.

## 4) Monsters Attacking Players / Monster Discovery

Same as 1)

---
Tags: mmo, multithreading, .net
---


# Question
Title: Simple 2D games - what is faster to render - images or drawing?
I am developing simple 2D environment in Pygame (Python 3.6), however I think this question is general. The environment is moving (player is rendered on the same position and everything else is scrolling).

I have two ideas how to display the environment:

1. I can draw it with built-in functions - circles, rectangles, polygons (pretty much like simple HTML5 canvas).
2. I can load images (textures) and build the environment from them.

My questions:

**What option is easier for CPU?** \- Does it depend on resolutions of textures? Does it depend on how many elements I would draw instead of image? Is there some general guideline what approach is better for what situation? Should I combine both approaches?

**Should I care?** The game will also contain a lot of other real-time computations - for example path-finding for various objects etc. So, should I even care about optimization of that simple 2D graphics?

# Answer
> 2 votes
Blitting is always faster on todays machines. One reason is that you do not need any other calculations except adding indexes. Even for a Polygon you need multiple calculations per line instead of a single blit.

Pygame is not using any GPUs but is painting the stuff merely in memory.

So blitting works also fairly well with cache mechanisms on CPUs as the SDLs software blitmethods are layout in memory byte-by-byte. On drawing individual pixels like circles or polygons you will experience a lot of cache-misses slowing down your drawings much more than blitting

Last but not least you are much more scalable by blitting: If you want to create a tree out of 10 green circles and you need to paint 50 trees you will paint 500 circles instead of 50 blits.

# Answer
> 2 votes
When in doubt, measure it. Programmers can make educated guesses, but they are just that: guesses. If you really want to know what's faster in *your* case on *your* target platform, create a benchmark. Create one program which blits a couple hundred bitmaps each frame and a second one which draws the same number of geometric shapes and see which one reaches a higher framerate.

But in the end this is mostly an academic exercise, because in a real game project you will almost always be working with images only. The reason is that images give your graphic artists a lot more creative freedom. Using geometric primitives instead of bitmaps *was* a method which was sometimes used decades ago to conserve memory and speed up rendering in *some* edge-cases, but such tricks are unnecessary on today's hardware. Even a low-end mobile phone should have no issues with reaching a proper framerate if it fills the whole screen with small bitmaps.

---
Tags: graphics, python, pygame
---


# Question
Title: Can I 'emulate' a device by booting its BIOS on my PC?
So for example let's take a SEGA Genesis (Mega Drive).

Let's say I have a usb Genesis cartridge loader with Sonic 1 plugged in. In that case, could I 'hardware emulate' a Genesis by booting a Genesis BIOS from USB (or any other way to boot a Genesis BIOS) and use that to play or mod Sonic 1, or develop & test home-brew games for the console?

# Answer
> 2 votes
No, the BIOS is not sufficient to emulate console hardware for development purposes, or running software generally.

A BIOS is firmware designed to work with specific hardware. Your PC is not a console, and loading a BIOS image won't transform it into one. At best, the BIOS image will be completely meaningless to your PC, like handing an English-speaker a set of instructions written in Greek.

What you're looking for is an Emulator. This is software that runs on one device, and simulates the behaviour of a different device. You'd need this kind of simulation layer to even make sense of a BIOS image designed for a different device.

---
Tags: emulation
---


# Question
Title: Unable to rotate a 2D object, wanting to move it like a ball/wheel
I'm using Unity2D.

I have a very basic 2D space with a platform, a ball and 2D physics.

Physics is being applied and ball sits on top of the platform.

However, it will not spin.

Below is the script attached to the ball:

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

public class Circle : MonoBehaviour
{
    private Vector3 screenPoint;
    private Vector3 offset;
    private float speed = 10f;
    public Rigidbody rb;

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

    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

        rb.maxAngularVelocity = 999;
        rb.AddTorque(movement * speed);
    }

    void OnMouseDown()
    {
        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }

    void OnMouseDrag()
    {
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
        transform.position = curPosition;
    }
}

```

The script is attached to the ball, I know this because I'm able to drag it (see `OnMouseDown`).

I have also tried with other objects such as a rounded-corner square, but I just can't get any spin or torque to be applied.

Below is a screenshot of the inspector on the element. Circle.cs (the script) is the above pasted script.

Any help appreciated.

# Answer
I need to reference `Rigidbody2D` instead of `Rigidbody`.

Code:

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

public class Circle : MonoBehaviour
{
    private Vector3 screenPoint;
    private Vector3 offset;
    private float speed = 10f;
    public Rigidbody2D rb;

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

    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

        rb.AddTorque(speed);
    }

    void OnMouseDown()
    {
        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }

    void OnMouseDrag()
    {
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
        transform.position = curPosition;
    }
}

```
> 0 votes

---
Tags: unity, c#, 2d, physics, torque
---


# Question
Title: Render moveable entities into 3D isometric world?
I have a separate list of moveable entities, and then the regular 3D map, represented by a 2D array of stacks of tiles. My problem is that right now, I'm rendering my moveable entities after the map, and so they end up in the right place, but rendering over everything. If I were to render my entity list at the right place, however, in the map rendering process, it would be very slow because I'd have to iterate over the moveable entity list to find one with the correct (x, y) coordinates each tile that's rendered. Here's what my world looks like:

Here is a screenshot of a particularly awkward example of this issue. The colonists are positioned (or seem to be) on the right tiles, but they draw in front of trees and hills they are actually behind.

Here's my current moveable entity drawing code:

Apologies for using a screenshot, but I can't paste into this text box for some reason. Anyway, my map drawing code is just a nested for loop over the map, pretty much. How do I merge these two? My drawing library doesn't have a Z-axis function.

# Answer
> 2 votes
You need a container to hold a reference to each object in the current tile/block.

**If your map is made of tiles**

Each tile has a height (as in games like Roller Coaster Tycoon or Transport Tycoon). You have a container for each position (x, y) of the map. When an object moves, it is removed from the container at (x, y) and added to the container at (x', y'). The container must be sorted by the altitude which the object is at.

Then, you iterate the tiles. For each tile, render the tile first, then the objects referenced in the container, starting from the object with lower altitude to the object with higher altitude. This is the reason you need to sort the container by the altitude the object is at.

OpenRTC2 uses similar approach, but optimized to use a compact pool for the references of objects.

**If your map is made of blocks**

Blocks don't have an height, at least not like in Roller Coaster Tycoon or Transport Tycoon, but they are like blocks in Minecraft. The map can have "holes" in it, in this case.

The approach is similar, but there's a container for each block. That is, there's a container for each position (x, y, z) of the map. In most cases, if the object is at (x, y, z), it means there's no block there to render. That is, you will render only a block ***or*** only objects for the position (x, y, z). Some cases are special. I see there are some brushes in your game, so maybe a character can enter the brushes, then you render the block first, then you render the character with a sprite where the bottom of the character is not drawn, to give the illusion the bottom part of the character is inside the brushes.

**Can be applied to both approaches**

You will possibly want to sort the references also by (x, y) position *inside* the tile/block, since objects can have different positions inside the tile/block, and therefore the order of their rendering is different.

---
Tags: rendering, sprites, graphics-programming, terrain-rendering, rust
---


# Question
Title: About floating point precision and why do we still use it
Floating point has always been troublesome for precision on large worlds.

This article explains behind-the-scenes and offers the obvious alternative - fixed point numbers. Some facts are really impressive, like:

"Well 64 bits of precision gets you to the furthest distance of Pluto from the Sun (7.4 billion km) with sub-micrometer precision. "

Well sub-micrometer precision is more than any fps needs (for positions and even velocities), and it would enable you to build really big worlds.

My question is, why do we still use floating point if fixed point has such advantages? Most rendering APIs and physics libraries use floating point (and suffer it's disadvantages, so developers need to get around them).

Are they so much slower?

Additionally, how do you think scalable planetary engines like outerra or infinity handle the large scale? Do they use fixed point for positions or do they have some space dividing algorithm?

# Answer
> 21 votes
If you will allow me a shameless plug, I'll give you an example from a real game I'm working on (YouTube video link).

The game has an infinite, procedurally generated world on a physics engine. It uses single-precision floating point. After a few hundred meters of game space, precision issues start to arise (and get progressively worse the further from the origin you get).

My solution? Every 200m or so I move the entire world back by 200m towards the origin (if you care to find and try one of the prototypes on my site, and bring up the \[w\]orld debug overlay, you can see this happen).

Why not use fixed point? Or double precision? Instead of single-precision? **Because *everything else* is using single precision floating point!**

The physics engine I'm using uses it, XNA uses it, the data that gets loaded onto the graphics card is formatted as single-precision floating point. Even the *language itself* is designed to work with floating point numbers -- writing and (more importantly) reading `0.5f` is far easier than `0x80000000L`.

It's simply a matter of what is easier in practice. And the clear winner is being aware of floating point precision issues and writing fairly simple "move-the-world-back-to-zero" functions (or implementing space partitioning or whatever suits your game).

And finally another example - Orbiter is game (simulation, really) that really needs to care about precision. Not just in space but also in time (time acceleration plus orbiting bodies - don't want them to fall out of the sky, now). It also uses floating point numbers and employs a hack to maintain stability.

# Answer
> 11 votes
First - yes, they are significantly faster. Even if you can get fixed point working as fast as a "normal" FPU, real floating point has advantageous instructions like fsel to stop branching, or SIMD to work on many floats at once. GPUs also use floating point, at least in their user-facing interfaces.

Secondly, 64 bits gets you pretty far in floating point as well - most people still use 32, but the primary advantage is that it scales. That fixed point scale has a fixed accuracy. Whether you're measuring the sun to Pluto, or across the street, you get the same precision. Floating point will give you much more accurate results when all values involved are smaller. Since generic physics libraries are expected to work at least passably with lots of games at different scales - and some games themselves may have vastly different scales - they need to use a kind of number that works at many scales.

# Answer
> 5 votes
Another important point to make is that floats aren't so inaccurate as people here seems to think. A 32-bit float has 24-bits of full integer precision. This means that it is at least as accurate as a 24-bit fixed point value for any given range. While floats get less accurate the larger the value becomes, a fixed point value will simply overflow and wrap around at some point. Reducing accuracy is a better fallback. Floats may also overflow, but far, far later. I would like to see your faces when your world suddenly wraps around to -2^31 due to fixed point overflow.

64-bit floating point values have 53-bits of integer precision, so they are really accurate.

# Answer
> 3 votes
In an FPS context, fixed-point values might actually be a liability. Close to zero floating-point is more accurate. It is only over large distances fixed-point becomes more preferable. The answer is simply that its dependent on context.

In something like a galaxy you can use frames of reference. Use a huge scale for the solar systems and then use the center of the Sun (or similar point) as the point of origin for anything inside the system. Using this system you can have your cake and eat it, so to speak, and its not difficult to envision.

IIRC, the dev on Infinity stated that he was continuously iterating around scale issues in one of his interviews.

# Answer
> 1 votes
If you didn't yet, you should definitively check out the Planet Rendering tutorial on GameDev.net. As for space division, one solution is to keep two separate position variables -- one macro scale and one micro scale. This works quite well (tested).

The exact solution depends on how do you plan to handle extreme distances in the engine -- do you plan jump gates, or time compression?

# Answer
> 1 votes
One of the reasons is that floating point arithmetic is "good enough" (or at least it has been), it produces fairly accurate results quickly.

As long as you are aware of the limitations of floating point arithmetic and change your algorithms to cope with them (see Andrew Russell's answer) then you'll produce code that "works".

# Answer
> -1 votes
I am writing a game. In my game/program, I draw a spaceship at the origin using a fairly fixed camera and my planet I draw using a separate camera. And these two things take care of the issue for me, but my planet isn't very detailed yet. As for the solution Andrew Russell mentioned about moving the world ( and i'm assuming the camera and its inhabitants back toward the origin ) I really wouldn't try that if you ever plan on making the game a networked game. If you moved the world on the server application based on each clients movements then the world would end up struggling for a position. And would take its position all the time from everyone playing which would be a huge glitch.

---
Tags: graphics, physics
---


# Question
Title: How can I prevent clicks from going through a GUI.Box?
I have a GUI.Box that I slide in from the side of the screen. How can I prevent mouse interaction from going to any objects under it (another GUI.Button for instance, or for that matter an GameObject)?

# Answer
> 2 votes
This is one of the annoying limitations of the built-in version of Unity's GUI. From most accounts I've seen, you have to do it yourself. Write an input manager that checks locations of mouse clicks and then decides to forward or not the clicks to whatever game systems you want.

Alternatively, use a different kind of input system that is based off of colliders. A popular one is NGUI.

# Answer
> 1 votes
This could be done fairly simply and elegantly with GUI.depth and styling a GUI button as a box.

```
void OnGUI()
{
    int prevDepth = GUI.depth;
    GUI.depth = 0;
    if(GUI.Button(someRect, "Some Button","Box"))
    {
        // Do something
        Event.current.Use();
    }
    GUI.depth++;
    // Do other stuff
    GUI.depth = prevDepth;
}

```

# Answer
> 0 votes
If we have lots of objects in a scene it's often preferable to use a single script that handles the click Raycast itself instead of every collider object also having an `void OnMouseDown()` callback.

When performing the Raycast ourselves we can check `GUIUtility.hotControl` to see if an IMGUI UI control was just clicked.

Here is an example that performs such a raycast on an arbitrary number of collider objects in the scene and handles both having mouse clicks be blocked by Immediate Mode UI as well as Canvas-based UI (just for good measure).

Here is the source code: https://gist.github.com/JohannesMP/3d3882e6bd57e378412fa5d7d95d0c47

---
Tags: unity, gui
---


# Question
Title: Blocking Physics Raycasts with Unity's 4.6 UI?
I use raycasts to determine hit objects and object selection in our game. I want these to be blocked by UI elements. Before I had a crude form of that where I just excluded rects of the screen, though with a non-rectangle shaped UI that's pretty difficult.

I want to have physics raycasts NOT go through UI objects, can this be done? My initial thought it adding colliders to the UI objects, though I'm not sure if the colliders will scale with elements based on screen size.

Note: Canvas Group does not apply to physics.raycast

# Answer
> 4 votes
The physics raycast is a different system and doesn't see UI elements. So you can not cause the UI to block physics raycasts. However you have options:

What you can do is cast two rays. One raycast for your UI elements and one for your physics objects. If your UI raycast detects a UI element, you know a UI element is in the way, and you shouldn't cast your physics ray cast.

Or, you can use the event system (which is already casting a ray into the UI elements) to tell you if you're over a UI element:

```
UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()

```

`IsPointerOverGameObject` does respond to Canvas Group, so make sure to disable the raycast block if your UI element is invisible (if you don't want to detect invisible UI elements).

# Answer
> 0 votes
In the old Immediate Mode GUI (so not the newer canvas-based UI which indeed should use `IsPointerOverGameObject()`) you can use `GUIUtility.hotControl`.

Here is a quick example that showcases both the old and the new UI blocking clicks to some colliders:

Example Source: https://gist.github.com/JohannesMP/3d3882e6bd57e378412fa5d7d95d0c47

---
Tags: unity, gui, raycasting
---


# Question
Title: Converting copyrighted song to 8 bit. Is it legal?
I would like to get a copyrighted song, convert into a 8 bit song and use it in my game. Is that legal?

# Answer
I am not a lawyer.

In most cases: nope.

But to be more clear, we need to know what is the license that the song was released at. When the publication has only `copyright (c) bla bla 201X`, usually means that only the publisher has rights to distribute and/or make derivatives.

Sometimes someone release their artwork under the terms of one of the Creative Commons license (https://creativecommons.org/licenses). There are multiples of them. Some allow derivative work. Some allow free distribution. Some allow commercial usage. Some doesn't allow commercial usage. That is, some are more permissive, others are less.

Then there are the cases of sampling. Which is a gray area, but still risky. But, you said convert, which means maintaining the melody. That's much more risky than sampling. You still see a lot of people doing it, but you should be aware that people doing it are doing at their own risk.
> 1 votes

---
Tags: legal, copyright, music
---


# Question
Title: How can I reorder the order in which the vertices are in an .obj file?
Blender saves the files with the structure of

1. All the vertices
2. All the normals
3. All the UV

The game to which I want to import the model, only accepts the following order in structure

1. 1 vertex
2. 1 normal
3. 1 UV
4. 1 vertex
5. 1 normal
6. 1 UV

and so on all the time ...

I need any 3d model that you download from the internet or blender with the first structure, be saved in the second structure automatically.

How can I achieve that?

Image examples:

# Answer
You should be reordering the data in a .obj on load anyway to convert the data to use a single index. It's a pretty bad format for modern day graphics. In your shipped game you should be using another format that doesnt' need all that parsing.

For example IQM fits that bill. It's binary (with a ascii relative IQE) so you don't need to do (slow) string processing on load. The devkit on that page includes a tool to convert obj to iqm.
> -1 votes

---
Tags: models, blender, modding, vertex, obj
---


# Question
Title: How do I call the sprite auto-slicer from a script in the Unity editor
First of all let me start with an apology. I know this may not be the right place for this question, but the good people over at stackoverflow did not answer me and neither did I get a answer over at Unity Answers, so I'm hoping that someone here will know. So without further ado here is my problem.

I'm writing my own asset importer and would like to automatically slice the sprite sheet.Slicing it with a grid is not viable since we have sprites with different sizes and I need to use the automatic slice option form the Sprite Editor. So far if the imported file has "sheet" in the name I can set all the properties I want. All that is left is do the automatic slicing but I cant even find anything in the documentation. Is this even possible ?

Edit: here is a screen shot. I want to access this functionality from my custom EDITOR script.

In simples words I want to click this button from a script instead of the artist when he imports a new spritesheet.

# Answer
> 0 votes
Alright I know this post is old, but I guess that if someone else bump into it, like I did, they might actually want an answer.

I found that guy called Shadesbelow made an editor script that slices your sprites.

Edit to your own need: https://gist.github.com/shadesbelow/8a6ddc54db795241f3cff539db6ea487

# Answer
> 2 votes
Actually I don't think that's possible.

Sprite Editor is just a tool to help prepare your spritesheet before you can actually "use" it in your game.

# Answer
> 0 votes
There's a free plugin that can semi-automatically slice sprite sheets: https://assetstore.unity.com/packages/tools/sprite-management/texturepacker-importer-16641

The advantage is that it can work with tightly packed sprite sheets (polygons in stead of rectangles) and trimmed sprites (sprites that have obsolete transparency removed, re-aligned by using pivot points).

The plugin requires a sprite sheet description file with names and locations of the sprites. The sprite sheet with the file can easily be created with a tool called TexturePacker.

---
Tags: c#, unity, spritesheet, tools
---


title: Put layout over Surfaceview

text:
# Question
Title: Put layout over Surfaceview
I have this problem: I'm trying to create new `RelativeLayout` over whole screen - which also contains `SurfaceView` in the middle - and display some things on this `RelativeLayout` (in my case `Imageview` containing animation). Almost everything is working ok - `Imageview` is displayed, animation is working... but SurfaceViews drawings (`Bitmaps`) are on the top of my `RelativeLayout` with `Imageview`, which I'm trying to appear it on top.

Calling `bringtofront()` doesn't work. Although I've created `RelativeLayout` with `ImageView` after `SurfaceView`, it's still below it.

So my question is: how to bring this `RelativeLayout` with `ImageView` to the top of `SurfaceView`?

**In Activity:**

```
// Layout, on which I'm adding Surfaceview programmatically
RelativeLayout layout = (RelativeLayout) findViewById(R.id.middle_layout);
layout.addView(new SurfaceView((getApplicationContext())));

// Layout which should be top over everything
RelativeLayout topLayout = new RelativeLayout(getApplicationContext());
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                                 RelativeLayout.LayoutParams.MATCH_PARENT,
                                 RelativeLayout.LayoutParams.MATCH_PARENT);
topLayout.setLayoutParams(rlp);

// Although I'm adding SurfaceView first and Relative second, no hierarchy order is visible...
layout.addView(topLayout);
// OR
root_layout.addView(topLayout);
// ^ Both attempts are displayed under SurfaceView

```

**SurfaceView class:**

```
public class SurfaceView extends SurfaceView implements SurfaceHolder.Callback
{
    public SurfaceView (Context context)
    {
            super(context);

            getHolder().addCallback(this);

            this.setZOrderOnTop(true);

            getHolder().setFormat(PixelFormat.TRANSPARENT);

            setFocusable(true);
    }

    ...
}

```

PS: I need to create SurfaceView programmatically.

Thanks for any help!

# Answer
Result: it's not possible. `surfaceView.setZOrderOnTop(true)` will cause SF to be on the very top, so you just can't draw anything over it. And with `setZOrderOnTop(false)`, you can put views over SF, but its background won't be transparent (and that's what I need too..). And that's quite sad.
> 2 votes

# Answer
It is possible to draw over the surface view with another fragment when it is added programmatically over the top of the activity/fragment that contains the surface view.
> 0 votes

---
Tags: java, android, view
---


title: Get triangles after subdivision

text:
# Question
Title: Get triangles after subdivision
I was able to do subdivision on a triangle mesh with midpoints but then I get polygons with too many faces. How do I convert to triangles after?

Similar to this picture:

# Answer
> 1 votes
I found the solution.

Each edge in the old model is subdivided and we keep a lookup of the edge to the new vertex it generates. Then we can loop through the triangles and generate the new edges.

---
Tags: geometry
---


# Question
Title: A ball hits the corner, where will it deflect?
I need to brush up my trigonometry and hope you can help here with a simple mathematical model. Here is my model so far in the image attached. I am aware that the frame animation has other problems when the ball is moving very fast, but for now I just need to calculate ballDx and ballDy. It is also possible that ballDx = 0 (vertical movement only), but when the ball deflects ballDx may get a different value.

# Answer
> 46 votes
Note: All of the following assumes the ball's surface is frictionless (so it won't start spinning or rebound differently because it is).

At the moment of collision, the ball will be touching the corner. When solid objects collide, a force will act along the so called surface normal, i.e. perpendicular to the surface at the point of collision.

Since it's a ball, perpendicular to the surface is towards to ball's center. Ok, so we know the direction of the force, what about its magnitude? Assuming an elastic collision (and that the rectangle can't move), the ball must rebound at the same velocity it impacted with.

Let (nDx, nDy) be the velocity after collision, (oDx, oDy) the velocity before collision, and (x,y) the position of the ball at the point of collision. Let's further assume the corner the ball collides with is at (0,0).

Expressing our insights as formulae, we have:

```
(nDx, nDy) = (oDx, oDy) + c * (x, y)
length (nDx, nDy) = length (oDx, oDy)

```

Which is equivalent to:

```
nDx = oDx + c * x
nDy = oDy + c * y
nDx^2 + nDy^2 = oDx^2 + oDy^2

```

Substituting the first two equations in the last one, we get:

```
(oDx + c * x)^2 + (oDy + c * y)^2 = oDx^2 + oDy^2

```

Expanding using the binomial thorem

```
(a+b)^2 = a^2 + 2ab + b^2

```

yields:

```
oDx^2 + 2 * oDx * c * x + (c * x) ^ 2 + oDy^2 + 2 * oDy * c * y + (c * y) ^ 2 = oDx^2 + oDy^2
2 * oDx * c * x + 2 * oDy * c * y + (c * x) ^ 2 + (c * y) ^ 2 = 0
(2 * oDx * x + 2 * oDy * y) * c + (x^2 + y^2) * c^2 = 0

```

This quadratic equation for `c` has two solutions, one of which is 0. Obviously, that's not the solution we are interested in, as generally the direction of the ball will change as a result of the collision. To get the other solution, we divide both sides by c and get:

```
(2 * oDx * x + 2 * oDy * y) + (x^2 + y^2) * c = 0

```

That is:

```
 c = -(2 * oDx * x + 2 * oDy * y) / (x^2 + y^2)

```

To summarize, we have:

```
c = -(2 * oDx * x + 2 * oDy * y) / (x^2 + y^2)
nDx = oDx + c * x
nDy = oDy + c * y

```

**Edit**: In code:

```
if (collision) {
    float x = ballX - cornerX;
    float y = ballY - cornerY;
    float c = -2 * (ballDx * x + ballDy * y) / (x * x + y * y);
    ballDx = ballDx + c * x;
    ballDy = ballDy + c * y;
}

```

A few implementation considerations: While you can approximate (x,y) with the ball's position after the simulation step, this approximation will change the angle of deflection and hence be very noticeable, so your simulation steps need to be very fine (perhaps such that the ball doesn't move more than 1/20 of its diamater per step). For a more accurate solution, you could compute the time the collision occurs, and split that simulation step at that time, i.e. do a partial step until the point of collision, and another partial step for the remainder of the step.

**Edit 2: Computing the point of impact**

Let r be the radius, (x0, y0) the position and (dx, dy) the velocity of the ball at the beginning of the simulation step. For simplicity, let's further assume that the corner in question is located at (0,0).

We know:

```
(x,y) = (x0, y0) + (dx, dy) * t

```

We want

```
length(x,y) = r

```

That is

```
(x0 + dx * t) ^ 2 + (y0 + dy * t) ^ 2 = r^2
x0^2 + 2 * x0 * dx * t + dx^2 * t^2 + y0^2 + 2 * y0 * dy * t + dy^2 * t^2 = r ^ 2
(dx^2 + dy^2) * t^2 + (2 * x0 * dx + 2 * y0 * dy) * t + (x0^2 + y0^2 - r^2) = 0
\____  _____/         \____________  ___________/       \_______  ________/
     \/                            \/                           \/
     a                             b                            c

```

That is a quadratic equation in t. If its discriminant

```
D = b^2 - 4 * a * c

```

is negative, it has no solutions, i.e. the ball will never hit the corner on its present course. Otherwise, its two solutions are given by

```
t1 = (-b - sqrt(D)) / (2 * a)
t2 = (-b + sqrt(D)) / (2 * a)

```

We are interested in the time the collision started, which is the earlier time `t1`.

Your method would become:

```
    // compute a,b,c and D as given above

    if (D >= 0) {
        t = (-b - sqrt(D)) / (2 * a);
        if (0 < t && t <= ts) {
            // collision during this timestep!

            x = x + t * dx;
            y = y + t * dy;
            ts = ts - t;

            // change dx and dy using the deflection formula
        }
    }

    x = x + ts * dx;
    y = y + ts * dy;

```

# Answer
> 13 votes
Here's a visual way of looking at a problem.

The original problem set is circle vs. rectangle (gray in the image below). This is equivalent to point vs. rounded rect (shown in black).

So this is a multi-part problem. You're testing your point collision vs. 4 lines (extruded out from the edge of the box by the radius of the original circle) and 4 circles (at the corners of the rectangle with the same radius of the original circle).

With the rough velocity in your original image, the point will hit the bottom right corner circle. All you have to do is figure out the point on the corner circle that you would hit, calculate the angle of that, and reflect off of it.

I'll leave the derivation of that as an exercise to the reader.

# Answer
> 2 votes
I'm working on a game and also stuck here. But I guess it goes this way:

There's another view My problem is that I don't know how to quickly calculate the new dx, dy (to me using traditional math requires too many calculations).

# Answer
> 0 votes
Kinematics is all about choosing the correct, as in *most convenient* for calculations, frame of reference.

Here we will first define the transformation **T** that resolves our axes into components parallel (**x'**) and perpendicular (**y'**) to a line between the centre of the ball and the corner. The inverse transformation **T\*** will restore our original coordinate system.

In this new frame of reference, by reflection (and the time and space symmetry of physics), we have the velocity transformation of contact **M** (a *point impulse*) as that which reverses the **x'** component and leaves unchanged the **y'** component. In *matrix* terms this is the diagonal matrix with -1 and 1 on the diagonal.

Then the velocity after the collision is simply: **V'** = **T\*** . **M** . **T** . **Vo**.

The time of impact *t* is then just the solution for (**T** . **Do**) + (**X** . **T** . **Vo**) (*t*) = *r* where **X** is the X-axis projection operator and *r* is the radius of the ball. Rearranged, we obtain
*t* = ( *r* \- (**T** . **Do**) ) / ( (**X** . **T** . **Vo**) (*t*) )

This has the distinct advantage of burying all the complex mathematics in rigorously written, tested, and debugged standard graphics libraries. This solution is also identical for 2D and 3D situations - just switch graphics library. Finally, it highlights that one should first think about appropriate *frames of reference* before tackling any physics problem. There is always the NIH temptation, but in truth that is just a recipe for bugs when more succinct solutions are available.

---
Tags: mathematics, collision-detection
---


# Question
Title: Do I have to re-assign localized text every time the game loads?
I am trying to build a localization system for games. And I have stumbled upon a problem where in Unity you basically have to change all the text in `Text` components / any other references like audio - when loading a game every time.

To better explain it - if the default language is English and user decided to change language to any other. Even if you localize all the files used in the game via code, later on you will have to do it again, when user loads the game after quiting it. Because components don't persist data changed via code in run-time.

How do I make it so that user would be able to change the language once, and all of those references and text... would persist and didn't require re-set up every time the game is loaded? Is that even possible in Unity?

Or should I just localize after the game has been made. And just allow people to download different language versions. But then again, it makes it difficult for people who want to change their language.

# Answer
Localization systems I've seen generally work in a "pull" approach, rather than a "push".

ie. instead of pushing out a change to all text in the game when the player changes the language, instead each text field pulls-in its text when it's time to be displayed.

How it might look in Unity is you could have a LocalizedText component on the GameObjects that need text. Each LocalizedText component knows the language-independent ID of the text it's looking for, eg. "Menu-Label-LoadGame".

Inside its OnEnable method (called when the object is spawned or toggled to active state), it asks the localization system for the correct localized string for "Menu-Label-LoadGame" in the user's currently selected language, the the localization system looks it up and returns the display text, eg. "Load Game". The LocalizedText component then populates that into its display field.

When the language changes at runtime, you can fire an OnLanguageChange event that all LocalizedText components subscribe to, telling them to refresh their text again.

This way, the only thing you need to store is the player's last selected language. Everything else will be looked up on demand.
> 3 votes

---
Tags: unity, text, localization
---


# Question
Title: Decoupling Input from Update/Physics Movement in a Game Engine
I have some troubles figuring out how to decouple the input handling from the physics part (includes movement).

My Game loop looks like this

```
while GAMEISRUNNING
    HandleInput()
    Update()
    Render()

```

From what I have found on the internet I can do something like this in the `HandleInput` method

```
HandleInput()
{
    if A key is pressed
        MOVEFORWARD = true
    ...
}

```

and then in the `Update` I can just check the boolean flags and update properly. The problem is that my `Update` method uses the `Physics Engine` to iterate over the entities and call their `Integrate` method. This means that I cannot just adjust the position because the integrate method is the same for all the entities.

```
Integrate(float deltaTime)
{
    #position and velocity are vectors
    position += velocity * deltaTime
}

```

Where can i actually perform the update to movement in this scenario? I was thinking that in the global `Update` method I can iterate over all the entities before the physics engine and adjust their velocities. That means that every GameObject will have `GameObjectUpdate` method and there I can adjust the velocities accordingly. This means that the global `Update` method will iterate over all the entities twice. Generally O(n) is pretty good, but I am not sure if this is the optimal way to do it.

# Answer
It's not at all unusual to have a separate "game logic update" step and "physics integration" step in a game engine.

The physics is generally integrated by a specialized library with just that one responsibility, so logic specific to each game entity needs to be processed elsewhere.

As some examples, in Unity a `FixedUpdate` method can be called on every object, before each iteration of the physics engine's integration, followed by collision messages and post-physics coroutines:

Unreal Engine uses the concept of "Ticking Groups" controlling when certain game logic should be stepped - PrePhysics, DuringPhysics, or PostPhysics, among others.

Iterating over the objects twice or more might seem wasteful, but it can actually be more efficient in some scenarios. A tight loop that does just one consistent thing to all objects, accessing similar data structures (eg. collision broadphase data) will tend to make good use of the processor's cache and branch prediction features.

If you had a mixed group of objects needing different types of game logic updates, or none at all, and some needing physics updates, or none at all, and tried to update them all in one loop, the processor would have to spend more of its time figuring out which kinds of updates to run, and looking up the instructions/data for update type C (since the cache is full of update type A & B). So the single loop might not be much faster or could even be slower than doing the steps in their own tight loops on just the objects that need them.
> 2 votes

---
Tags: architecture
---


# Question
Title: How to access `GameObject` to which `MonoBehaviour` is added from C# `Attribute`
Unity's `RequireComponent` inherits from `System.Attribute`. Somehow they made it that whenever component is added it has a reference to `GameObject` it`s being added to. So they can call`AddComponent\` to it.

I am trying to replicate that behaviour.

My theory is that because `UnityEngine.RequireComponent` has types stored inside class - they do it by reflection later. In method `AddComponent<T>` they get `T` class attributes from type and then try to cast them, get information from them, and apply to `GameObject`. If that is the case, then I doubt I will be able to do something with it, unless I have access to change `AddComponent<T>` somehow.

Is there another way around it?(that is no problem to do in code (just extension), but what about how it will work in inspector) Maybe apply different method to Unity\`s default component addition.

**EDIT**

```
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class RequireComponentAttribute : Attribute
{
    public RequireComponentAttribute(Type type, int quantity)
    {
        if (quantity < 0)
            throw new ArgumentOutOfRangeException("Required components quantity cannot be negative");
    }

#if UNITY_EDITOR
#endif
}

```

# Answer
> 1 votes
C# attributes do not work the way you'd need them to work to do what you want, here.

* The constructor for your attributes don't run until the attribute is recovered through the reflection API (e.g., by calling `Type.GetCustomAttributes()`).
* There's no API or other mechanism for the code in the attribute to "see outside" to what the attribute instance is attached to.

The behavior you're seeing from Unity is likely handled by reflection or something similar: when creating an instance of some type, the type is inspected (via `GetCustomAttributes`) for `RequiredComponent` attributes and instances of the types specified by any such attributes found are created and attached to the object.

If you create a wrapper around the creation of objects that you use everywhere, you can implement similar behavior via reflection. But you can't do it from the members of the attribute subclass code itself.

---
Tags: unity
---


# Question
Title: Is RPC Safe and what is security layer of RPC?
We're creating a MMO and I wonder is RPC safe or not ? Isn't RPC easily hackable by injecting to client and what is the security layer of RPC on Unreal Engine ?

For example; a player is walking and sending that information (*new position, rotation etc*) to other players, can't that player change movement speed or position with injecting ? What is validating; is that movement is valid or it was a hack ?

I checked on Google but didn't get answer for my questions.

Thanks o/

# Answer
Unreals' RPCs are just another mechanism for communicating data between clients and the server. They're not specifically about providing any kind of secure channel: that's your job.

You can mark an RPC as `WithValidation` and then implement `YourRPC_Validate`. As explained in the documentation, this provides a mechanism for the server to check the RPC inputs. But all it can do is return true or false, and if it returns false the client is simply disconnected.

That behavior may be sufficient for some cases, but if you want really robust anti-cheat verification the onus is still on you to provide it in your server code yourself, whether you use RPCs or replication or bare sockets to communicate the data is largely orthogonal.
> 1 votes

---
Tags: networking, mmo, unreal-4
---


# Question
Title: Alternatives to remove Unity splash screen after developing a game with the free version?
I developed a simple game using the free version of Unity. I want to understand how much it would cost me to remove the Unity Splash Screen to know if it's worth it.

Right now Unity professional edition costs $75 per month, does this mean I have to pay every month while the game is on the app store or can I pay just for the month I have to release the game so I remove the Unity Splash Screen and that's all (provided I don't need to update the game later)?

# Answer
According to the Unity store page, the $75/month subscription is locked in for 12 months, so it would cost $900 for one year. (click the $75/month price link for subscription details)

If you wanted to update your game after one year, you would need another subscription after that, so maybe $1,800 all up if you plan on updating your game after a year.

Or, you could pay the full one-off $1,500 price and have Unity 5 Pro be yours forever.

---

Edit: according to the Unity FAQ:

> **Do I need iOS + Android Pro in order to build to iOS + Android devices?**
>
> Unity Personal Edition includes deployment to Android and iOS with the Personal Edition splash screen. To deploy to iOS and Android without the Personal Edition Splash Screen you must purchase Unity Professional Edition together with iOS Pro and/or Android Pro deployment add-ons.

So it sounds like you would also need another $75/month or one-off $1,500 cost for the iOS Pro Add-on on top of Unity Pro.

So all up, you'd have to either pay for subscriptions for one year for both Unity Pro and iOS Pro for a total of $1,800 (assuming you weren't ever going to update your app after one year), *or* pay $3,000 for both as a one-off.
> 8 votes

# Answer
On android there is a file called splash.png that you can simply replace with something else.
> -3 votes

---
Tags: unity, licensing
---


title: Figuring out damage distribution

text:
# Question
Title: Figuring out damage distribution
My problem -

Each round, each of the 5 champions get to strike each of the 99 monsters once; however, their attacks are such that one third of each champion's attacks are ineffective, causing 0 damage; one third cause normal damage (1 point) and one third cause bonus damage (2 points). (The numbers have been simplified for the purposes of this example.) So, in total each of the monsters can get hit anywhere from 0-10 points of damage each round, but the amount will vary depending on whether the attack was ineffective, caused normal damage or caused bonus damage. As I'm trying to figure out the right percentages between ineffective, normal and bonus damage attacks (in the example above, they're each at one third, but I'm not sure that will make sense for the gameplay), I need to know how the damage will be distributed among the 99 monsters as I change the percentages associated with each of the three different types of attacks. In other words, if I use these x percentages, they will result in y monsters receiving 10 points of damage, z monsters receiving 9 points of damage, etc.) Does anyone know how I can do that?

# Answer
> 5 votes
A good tool to simulate this is AnyDice.com. It is supposed to be used to simulate dice throws in tabletop games, but it can in many cases be easily adapted to do the same with random chances in video games. In your case, the damage roll is `output 5d{0, 1, 2}` ("take a three-sided die with the values 0, 1 and 2, throw it 5 times and add up the results") which results in a probability distribution curve like this:

As you can see, there is only a 0.41% chance for each enemy to die.

This intuitively sounds too low. But we can verify that this is in fact correct by calculating the odds manually.

For an enemy to receive 10 damage, you need to roll a 2 five times in a row.

* The chance to roll a 2 is 1/3.
* The chance to roll two 2's in a row is (1/3)² or 1/9.
* The chance to roll three 2's in a row is (1/3)³ or 1/27.
* The chance to roll four 2's in a row is (1/3)⁴ or 1/81.
* The chance to roll five 2's in a row is (1/3)⁵ or 1/243.
* 1/243 is (rounded) 0.00412

Anydice is surprisingly powerful. You should check out the documentation for more information. Your question asks for how you can play around with different probabilities of rolling 0, 1 and 2. In other words, you need a *loaded* die. AnyDice can do that as well.

This AnyDice program simulates 5 rolls, each with a 20% chance to roll 0, 50% chance to roll 1 and 30% chance to roll 2:

```
output 5d{ 0:20, 1:50, 2:30 }

```

But when you hit the limit of what can be done with AnyDice, then you might want to simply write your own little program to simulate your game mechanics.

---
Tags: game-design, random, probability
---


# Question
Title: How to get 60fps animation in terms of rounding/truncating position/alpha floats
I am wondering what gives the best animation performance running at 60fps with lots of objects. I have seen in a few places such as this that you should *round* or *truncate* your values so you don't get `54.2356345234578px`, but instead get `54.24px`.

```
animationValue = +animationValue.toFixed(2)

```

For `x`, `y`, `alpha`, etc. Any float values. I sort of understand why this is, but I am interested to know if there are any ideal heuristics to take into account. For example, maybe rounding `.toFixed(2)` is not ideal for particle animations. Maybe it is choppy for alpha transitions. Wondering if this has been solved, and what to truncate the values to for performance. Also in terms of calculating velocity or physics stuff, just generally what the scale of rounding/truncation should be so there are no noticeable effects.

# Answer
> 2 votes
There’s no case I can think of where rounding values during an animation is a good idea. Color and opacity already get “rounded” by the display’s color depth (i.e. to one of 256 brightness values), and two decimal places’ worth of rounding will be less than the eye’s temporal JND in most cases; rounding the position of an object while it’s moving can cause it to appear to be speeding up and slowing down as it moves, which is visually jarring.

I suspect the reason the author of the article you linked recommended rounding position values is that if the animation **stops** on a fractional position the result will be blurry, but that’s a reason to round your positions to the nearest whole pixel after the animation completes, not while it’s ongoing.

---
Tags: animation, performance, vector, linear-algebra, transparency
---


title: Unity2D: Vector3.Lerp - smooth movement

text:
# Question
Title: Unity2D: Vector3.Lerp - smooth movement
I have a script that randomly chooses a position to move a game object every 5 seconds, however instead of moving my object smoothly, my script make my object jumps, which is not desirable! How would I make my object move to position smoothly! Thank you!

```
public float timer;
public float speed;

public int newtarget;

public float xPos;
public Vector3 desiredPos;

void Start() {
}

void Update () {
    timer += Time.deltaTime;
    if (timer >= newtarget) {
        newTarget ();
        timer = 0;
    }
}

void newTarget() {
    xPos = Random.Range(-4.5f, 4.5f);
    desiredPos = new Vector3(xPos, transform.position.y, transform.position.z);

    transform.position = Vector3.Lerp (transform.position, desiredPos, Time.deltaTime * speed);
        if (Vector3.Distance(transform.position, desiredPos) <= 0.01f)
        {
            xPos = Random.Range(-4.5f, 4.5f);
            desiredPos = new Vector3(xPos, transform.position.y, transform.position.z);
        }
}

```

# Answer
> 3 votes
Before I go into the code, I want to go over how Lerp works.

```
Vector3.Lerp(Vector3 start,Vector3 end, float fraction);

```

The above code will return a Vector3 that is between the start and end positions at some fraction of the way along a line between two points. So:

```
transform.position=Vector3.Lerp(Vector3 start,Vector3 end, float t);

```

If t is 0.5f, this will teleport the object right between start and end, if t is 0.25f, the object will be teleported to a quarter of the way along the line from start to end. So you want to "move" your object by changing it's position little by little using Update(), and keep track of your start position and distance to your desired position.

You can find more information about Lerp at the Unity Docs reference page for Lerp

```
private Vector3 startPosition; //You will need to keep track of your initial position as well as your desired position
private float startTime;//You will need to get the time when the movement has started
private bool moving;//You will need to keep track of when the object is moving or not

public float timer;
public float speed;
public int newtarget;
public float xPos;
public Vector3 desiredPos;

void Update()
{
    timer += Time.deltaTime;
    if (timer >= newtarget)
    {
        NewTarget();
        timer = 0;
    }
    if (moving) //This part of the code will execute when moving is set to true in NewTarget()
    {
        float timePast = Time.time - startTime; //How many seconds has it been since moving was set to true
        float distanceCovered = timePast * speed; //Make sure to keep speed small, when distanceCovered reaches 1, the movement will be over
        //The object will arrive at its desired position in 1/speed seconds
        transform.position = Vector3.Lerp(startPosition, desiredPos, distanceCovered); //when distanceCovered is 0, the object will be on startPosition, when it is at 1, the object will be on desiredPos
        if (distanceCovered >= 1)//If the object reached the end, it is not moving anymore, if you want the wait to always last newtarget amount of seconds, you might want to reset the timer here instead and change if(timer >= newtarget) to if(timer >= newtarget && !moving)
        {
            moving = false;
        }
    }
}

void NewTarget()
{
    //I tried to keep as much of your code as possible and I am assuming you only want to move the object in the X axis in this case
    xPos = Random.Range(-4.5f, 4.5f);
    desiredPos = new Vector3(xPos, transform.position.y, transform.position.z);

    moving = true;//The new target is acquired so the movement begins
    startPosition = transform.position; //Keep track of the object's original position
    startTime = Time.time; //Remember the moment when the movement started so you can calculate the distance
    distance = Vector3.Distance(startPosition, desiredPos);//Get the distance to your desired position in float

    //You need to do your Lerping in Update() instead
}

```

I hope this is helpful.

---
Tags: unity, 2d, movement, objects
---