# Question
Title: Weird movement / rotation of Unity editor scene view camera
I am using the Unity 2017.3.0f3 Personal (64) bit editor for Pc, Mac and Linux Standalone (DX11 on DX10 GPU). I was editing my terrain when suddenly my camera for moving around in the editor went absolute wack.

The camera now rotates around any object I click on and pretty much doesn't work at all. I cannot move using the WASD keys anymore.

I have never had this problem before so I believe I just accidentally clicked the wrong button. Is there any way I can fix this?

# Answer
I'm not a Unity dev, but a causal search of the navigation documentation suggests you might need to click the Scene Gizmo to get back to a Perspective view.

The Scene Gizmo looks like a square with cones pointing to the faces (aligned on the XYZ axes) & looks like this:
> 4 votes

# Answer
On your scene, under the square with cones around it and the letters y and x, under that there is a thing that will say iso. click that.
> 0 votes

---
Tags: unity
---


# Question
Title: In Unity how do I make a button call everything suscribed to the "onEndEdit" event of an InputField?
How do I make a method (that is going to be called every time that a button is pressed) to call everything subscribed to the "onEndEdit" event of an InputField?

I expected something like this:

```
public class DoneButtonInputField : MonoBehaviour
{
    [SerializeField] private InputField inputField;

    public void ClickDoneButton()
    {
        inputField.onEndEdit();
    }
}

```

But it does not work and I do not know how to search for the answer (probably by vocabulary lack).

# Answer
> 1 votes
This is the way:

```
inputField.onEndEdit.Invoke(inputField.text);

```

I'm trying to do it because the InputField component does not allow you to have a button to finish the editing of the text, so I'm adding it. That's why I want to call the event when the button is pressed, which means that the edit is finished.

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


# Question
Title: When do you use StartCoroutine and when Invoke?
I am confused. Both seem to do the same thing: Delay a method.

Both Invoke and StartCoroutine allow you to call a method by name (string).

```
StartCoroutine("functioncalls", 2f);
StartCoroutine(functioncalls());

```

Invoke:

```
void Call()
{
    Invoke("FunctionCall",2f);
}

void FunctionCall()
{
    Debug.Log("this function run");
}

```

StartCoroutine:

```
void Call()
{
      StartCoroutine(functioncalls());
}

IEnumerator functioncalls()
{
    yield return new WaitForSeconds(2f);
    Debug.Log("this function run");
}

```

Both do the same thing, or not?

What exactly is the difference between Invoke and StartCouroutine? In which situation would I use one and when the other?

# Answer
> 9 votes
Invoke is useful if you want to do something one time only.

A coroutine is able to pause, let the game continue running, and then do something else later. This makes them useful for processes which run over time. Also, you can pass arguments to a coroutine. The Invoke method does not allow that.

Example of a coroutine which implements a countdown:

```
 IEnumerator Countdown(int seconds)
 {
       while (seconds > 0) {
            Debug.Log(seconds);
            seconds--;
            yield return new WaitForSeconds(1f);
       }
       Debug.Log("Go!);
 }

```

You can now use this function to do a countdown of arbitrary length. For example, if you want to start a 10 second countdown, you would call

```
 StartCoroutine(Countdown(10));

```

---

However, if you want to do something in 10 seconds without having a visible countdown leading up to the event, then it would be easier to use Invoke:

```
 void Go()
 {
       Debug.Log("Go!);
 }

```

...

```
 Invoke("Go", 10f);

```

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


# Question
Title: Measure force of an impact to deal damage
I don't know how to name what I am searching for... Force, Impact?
It's easier to explain with an image for me.

We have two GameObjects with colliders, A and B. They can move in any direction (top down game with 360° movement possibilities).

* First case (left): A goes to the right at a speed of 2, B to the left at a speed of 1 and they collide. I'd like to calculate that A takes 1 damage (from the speed of B in its direction) and B takes 2.
* Second case: A goes to the right at speed of 2 and B to the right at speed of 1. A takes 0 damage and B takes 1.

I am using `Collision2D` which doesn't have "impulse" property. I have no idea how to calculate thing like this manually.

# Answer
This is commonly done with collision.relativeVelocity, something like this:

```
void OnCollisionEnter(Collision) {
    Vector3 impactVelocity = collision.relativeVelocity;

    // Subtracting a minimum threshold can avoid tiny scratches at negligible speeds.
    float magnitude = Mathf.Max(0f, impactVelocity.magnitude - minimumDamageThreshold);
    // Using sqrMagnitude can feel good here,
    // making light taps less damaging and high-speed strikes devastating.

    float damage = magnitude * collisionDamageScale;

    healthComponent.TakeDamage(damage);
}

```

But this version will apply symetrically to both participants. (From the view of either A or B, the other object is approacing just as fast, so we should take the same damage)

If you want an object to take damage only when it hits something that's not moving away (at a slower speed), then we'll need to reconstruct the absolute velocities the objects had in the world's inertial frame just before this collision (the velocities you see in the collision handler are post-resolution).

Note that this isn't how real-world physics works, where there's no privileged inertial frame, but sometimes breaking the rules makes for more intuitive behaviour for game purposes.

```
// Cache this in Start()
Rigidbody _body;

void OnCollisionEnter(Collision collision) {

    Vector3 normal = collision.GetContact(0).normal;
    Vector3 impulse = collision.impulse;

    // Both bodies see the same impulse. Flip it for one of the bodies.
    if (Vector3.Dot(normal, impulse) < 0f)
        impulse *= -1f;

    Vector3 myIncidentVelocity = _body.velocity - impulse / _body.mass;

    Vector3 otherIncidentVelocity = Vector3.zero;
    var otherBody = collision.rigidbody;
    if(otherBody != null) {
        otherIncidentVelocity = otherBody.velocity
        if(!otherBody.isKinematic)
            otherIncidentVelocity += impulse / otherBody.mass;
    }

    // Compute how fast each one was moving along the collision normal,
    // Or zero if we were moving against the normal.
    float myApproach = Mathf.Max(0f, Vector3.Dot(myIncidentVelocity, normal));
    float otherApproach = Mathf.Max(0f, Vector3.Dot(otherIncidentVelocity, normal));

    float damage = Mathf.Max(0f, otherApproach - myApproach - minimumDamageThreshold);

    healthComponent.TakeDamage(damage * collisionDamageScale);
}

```

Note that this particular formula also deals no damage to an object that strikes a stationary target (though the target takes damage)

---

In 2D, you have to total up the impulse to use yourself:

```
static Vector2 ComputeTotalImpulse(Collision2D collision) {
    Vector2 impulse = Vector2.zero;

    int contactCount = collision.contactCount;
    for(int i = 0; i < contactCount; i++) {
        var contact = collision.GetContact(i);
        impulse += contact.normal * contact.normalImpulse;
        impulse.x += contact.tangentImpulse * contact.normal.y;
        impulse.y -= contact.tangentImpulse * contact.normal.x;
    }

    return impulse;
}

```

One benefit of this is that each object in the collision sees its own version of the impulse, so you don't need the flipping line I included in the 3D version.
> 3 votes

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


# Question
Title: Extending control remapping script to work with mouse buttons
I have created a default key map for my game, however I have also included an option in the settings where the player can change the key bindings.

My issue is if the player clicks on the button for shooting, which is defaults to mouse0, or aim on mouse1, then click on another key, they can never go back to mouse0 or mouse1.

I am unsure of how to include all the mouse buttons/scroll wheel into the viable buttons the player can choose from.

Here is the part of my code that deals with the changing of the keys:

```
private void OnGUI()
{
    if(curKey != null)
    {
        Event e = Event.current;
        if (e.isKey)
        {
            keyBinds[curKey.name] = e.keyCode;
            curKey.transform.GetChild(0).GetComponent<Text>().text = e.keyCode.ToString();
            curKey.GetComponent<Image>().color = normal;
            curKey = null;
        }
    }
}

```

# Answer
> 0 votes
First you'll need to extend your input binding map to handle things that aren't key codes, something like this:

```
public enum BindingType {
    Unset,
    Keyboard,
    MouseButton,
    MouseScroll
}

[System.Serializable]
public struct InputBinding {

    public BindingType type;

    public KeyCode key;

    public int mouseButton;

    public Vector2 scrollDirection;

    public InputBinding(KeyCode key) {
        type = BindingType.Keyboard;
        this.key = key;
        mouseButton = -1;
        scrollDirection = Vector2.zero;
    }

    public InputBinding(int mouseButton) {
        type = BindingType.MouseButton;
        key = KeyCode.None;
        this.mouseButton = mouseButton;
        scrollDirection = Vector2.zero;
    }

    public InputBinding(Vector2 scrollDirection) {
        type = BindingType.MouseScroll;
        key = KeyCode.None;
        mouseButton = -1;
        this.scrollDirection = scrollDirection;
    }

    public bool Fire() {
        switch(type) {
            case BindingType.Keyboard:
                return Input.GetKeyDown(key);
            case BindingType.MouseButton:
                return Input.GetMouseButtonDown(mouseButton);
            case BindingType.MouseScroll:
                return Vector2.Dot(Input.mouseScrollDelta, scrollDirection) > 0f;
        }
        Debug.LogError("Looks like you added a new input type and forgot to wire up the Fire() method.");
        return false;
    }

    public override string ToString() {
        switch(type) {
            case BindingType.Keyboard:
                return key.ToString();
            case BindingType.MouseButton:
                switch(mouseButton) {
                    case 0: return "Primary Click";
                    case 1: return "Secondary Click";
                    case 2: return "Middle Click";
                    default: return "Error - Invalid Mouse Button";
                }
            case BindingType.MouseScroll:
                if (scrollDirection.y > 0)
                    return "Mouse Scroll Up";
                if (scrollDirection.y < 0)
                    return "Mouse Scroll Down";
                if (scrollDirection.x > 0)
                    return "Mouse Scroll Right";
                if (scrollDirection.x < 0)
                    return "Mouse Scroll Left";
                return "Error - Invalid Mouse Scroll";
        }
        return "Error - Invalid Input BindingType";
    }
}

Dictionary<string, InputBinding> inputBindings = new Dictionary<string, InputBinding>();

```

You could also do this with polymorphism rather than a union, but the way shown here lets you manipulate these bindings in the Unity inspector, which doesn't handle serialization of polymorphic types as well as we might like. Note that you could compact the storage of this type by overlapping the fields, since they're mutually exclusive in use.

Then you can break out your search for an input:

```
InputBinding CaptureFirstInput() {

    Event e = Event.current;

    if (e.isKey && e.keyCode != KeyCode.None)
        return new InputBinding(e.keyCode);

    for (int i = 0; i < 3; i++)
        if (Input.GetMouseButtonDown(i))
            return new InputBinding(i);

    if(Input.mouseScrollDelta != Vector2.zero)
        return new InputBinding(Input.mouseScrollDelta);

    return default(InputBinding);
}

```

And apply the return value to your input mapping:

```
private void OnGUI()
{
    if(curKey != null)
    {
        var input = CaptureInput();
        if(input.type != BindingType.None) {
            inputBindings[curKey.name] = input;
            curKey.transform.GetChild(0).GetComponent<Text>().text = input.ToString();
            curKey.GetComponent<Image>().color = normal;
            curKey = null;
        }
    }
}

```

# Answer
> 0 votes
I presume the flow for setting the key is to click the box of the action and then pressing the key the player wants to bind to it.

You can also listen to mouse clicks in that time and use the first action that is performed.

---
Tags: unity, c#, input, mouse
---


# Question
Title: SetIKHintPosition and SetIKHintPositionWeight seems to have no impact
I have recently been exploring Unity's inverse kinematics, to further polish the interaction between our rigged avatars and props.

I have made a sample project, using PuppetMaster's basic humanoid for the model, rig, and idle animation, but without Final IK; meaning this is Unity's inverse kinematics. Inside our `OnAnimatorIK` method, we set the right elbow's `SetIKHintPosition` and `SetIKHintPositionWeight` like we did with the hand IK:

```
animator.SetIKHintPosition(avatarIKHint, hintPosition);
animator.SetIKHintPositionWeight(avatarIKHint, hintBlendValue);

animator.SetIKPosition(sourceIKGoal, targetPosition);
animator.SetIKPositionWeight(sourceIKGoal, blendValue);

```

You can see the left and right hand correctly move to where we set it. However, it seems like the right elbow is ignoring the hint position entirely. You can see the white debug line connecting the elbow to the hint position in the picture above.

It seems like the elbow ONLY bends if it absolutely must for the hand to reach the target position, regardless of where the hint is set, and the weight value given.

I have fiddled with this on and off for days and still haven't found a solution. Others have asked the same question here and on other sites, but no one has posted an answer.

# Answer
> 1 votes
I notice that the `AvatarIKHint` enumeration supports applying hints to only the elbows and knees.

This suggests to me that Unity uses a simple 2-bone IK solution for this case. That means it thinks of the shoulder or hip joint as fixed, and finds the best solution it can using only the upper arm & forearm bones, or thigh and shin bones for legs.

The advantage of this approach is it's *fast*: you can find the best solution in a single step with a little high school trigonometry, without having to iterate over longer bone chains and converge gradually toward a solution.

Now, a 2-bone IK system with a root point (shoulder / hip) and a target point has one extra degree of freedom: the rotation about the line from the root to the target. Imagine doing the arm-flapping motion of the chicken dance: the line from your shoulder to your wrist stays fixed, as does the joint angle at your elbow; all that changes is the rotation at your shoulder to position your elbow low/tucked-in close to your body or raised outward. All of these poses are potential, equally-valid solutions for this IK problem, so if we care which of these poses we adopt, then we need to hint the solver in the desired direction.

It looks like that degree of freedom is what these hint methods serve to control. So for instance if your FPS character was putting their elbow way out to the side like a novice when holding their weapon, you could use a hint to guide the elbow down to a more professional-looking tucked-in position.

Once the arm or leg is fully extended however, there's no extra degree of freedom left: the elbow/knee has to sit along the line from the shoulder/hip to the wrist/ankle. Putting the elbow anywhere else would make the end effector deviate from the target (bad) or distort the skeleton (also bad).

So, it looks like what you're trying to accomplish with this hint is not what this hint is made to do. What you should do instead depends on what your ultimate aim is.

If you want the character to lean to the side, bringing the shoulder closer to give the elbow more room to bend & position itself away from the direct shoulder-to-target line, then you might have luck applying that lean as an additive animation layer.

---
Tags: unity, rigging, inverse-kinematics, animator
---


title: What is a Frame and Frame Per Second?

text:
# Question
Title: What is a Frame and Frame Per Second?
I'm new to the unity Editor, trying to understand Unity scripting.

What is frame? I can't tell from how it's used whether "frame" is a function, or a measure of time.

I see this term used in different ways:

* Update() is called every frame - Unity Document says
* Update() is called during a frame - Some People Says
* Update() is called once per frame - Some People Says

I'm confuse by these statements - what is true/false?

Is `frame()` a function?

Or is frame a unit of time?

And what is frames per second (fps)?

I've been trying to investigate using this code:

```
void Update ()
{
    CallThisOne();   // how many frame per second by default ex 60fps,30fps??
    CallThisTwo();   // how many frame per second by default ex 60fps,30fps??
}

void CallThisOne()
{
    Debug.Log("CallThisOne");
}

void CallThisTwo()
{
    Debug.Log("CallThisTwo");
}

```

Output:

# Answer
> 6 votes
Games inherited this term from animation, film, and video.

There, a "frame" is one still image in the sequence. By playing lots of frames in rapid succession, we create the illusion of motion.

See this strip of 35 mm film from the Museum of Obsolete Media. In it, we can see three consecutive frames of a Spider-Man movie.

The framerate of a piece of animation/film/video is a measure of how quickly we move from one frame to another. Common values you'll see are 24, 30, or 60 frames per second - that's where the "FPS" abbreviation comes from. In an animation running at 24 fps, 24 different frames (pictures) are displayed for each one second of playback time.

So, at a particular framerate, we can also think of one "frame" as a measure of time - say 1/24th of a second for a 24 fps animation.

All of this carries over to games - the difference is that we typically have to create each image a fraction of a second before it's displayed, rather than just playing back an already-existing image sequence. That includes both the actual work of drawing, and the work to update the internal state of the game - like the positions of the characters - so that we know what to draw.

In games we can say...

* A **rendered frame** is one complete image presented to the player's screen.
* By rendering and displaying new frames very quickly, games create the illusion of motion.
* The **frame rate** a game is running at is a measure of how many new frames it displays every second - so a 60 fps game is rendering and displaying 60 new images every second.
* A **frame interval** is the span of time between displaying two consecutive frames. For a game running at 60 fps, that's just over 16 milliseconds.

You'll often hear game developers and players call this span of time "a frame" - like when a fighting game player says "this attack takes 5 frames to hit" what they mean is that 5 frame intervals pass between the time the player hits the attack button and when the attack actually does damage - leaving a potential window to interrupt or block the attack.
* We'll also sometimes loosely refer to all the work that the game has to do in order to prepare the next rendered frame as "a frame".

So we do use this word to mean a few different but related things. Generally it's pretty clear what's intended based on the context.

Let's dig into Unity's context to see how this applies.

The Unity game engine has a sequence of steps it goes through for each rendered frame it presents to the player's screen. I'll simplify a little here, but you can find the full breakdown in the documentation.

1. First, the engine reads the player's input since the last time it checked - things like keyboard key presses, mouse movements & clicks, gamepad buttons, sticks, and triggers, anything you can access via the `Input` class.
2. Next, the engine ticks forward the game's physics simulation. This involves running all active scripts' `FixedUpdate()` methods, then integrating movements using the physics engine, then calling any collision-handling methods like `OnCollisionEnter()` or `OnTriggerStay()`.

It repeats this trio of operations as many times as it needs to for the game simulation to catch up to the current time (up to a limit). So if the game has been running slow and a lot of time has passed since the last physics step, it might have to loop these several times to catch up. But if the game has been running very fast, it can sometimes skip the physics step entirely, because not enough time has passed for a new one.
3. Third, it calls all `Update()` methods on scripts.
4. Fourth, it updates any animations that are currently playing and applies IK fix-ups.
5. Then it runs any `LateUpdate()` methods on scripts, to do last-minute fix-ups that need to react to work that happened earlier in the frame interval.

This could be things like moving a camera, label, or selection cursor that needs to exactly follow another game object that moves in `Update()` or via animation.
6. Then it renders the scene, producing a new image - a new rendered frame.
7. It publishes the new frame to the graphics device, to be presented to the player's screen.
8. If VSync is enabled, the game waits until the next time the screen is ready for a new image before starting over at 1.

Otherwise, it jumps right back to 1 and does it all again - possibly going faster than the screen can display images. This means that it draws some rendered frames that the player might never see in full - they might get skipped entirely, or get seen partially because they got sent to the screen halfway through a repaint, creating an artifact called "tearing".

So, looking at all the work done during a frame interval, to produce one rendered frame, we can see that all of these statements are true:

> Update() is called every frame - Unity Document says

Yes, the `Update()` method is called on every active script instance, for every frame interval, before drawing each rendered frame. `Update()` is never skipped (unlike `FixedUpdate()` for example).

> Update() is called during a frame - Some People Says

Yes, `Update()` is called at step 3 of the sequence of work in each frame interval to produce a rendered frame.

> Update() is called once per frame - Some People Says

Yes, each active instance's `Update()` is called only once in each frame interval. It's never called twice for the same rendered frame (unlike `FixedUpdate()` for example).

In your screenshot, we can see that `Update()` has been called 506 times since the last time the console was cleared. If you have just one instance of your script in your scene, then this means 506 frames have been drawn in that time. (If you had two instances of this script, then this would represent 253 frames, calling Update once on each instance every frame)

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


# Question
Title: Is the Microsoft recommendation to use C# properties applicable to game development?
I get that sometimes you need properties, like:

```
public int[] Transitions { get; set; }

```

or:

```
[SerializeField] private int[] m_Transitions;
public int[] Transitions { get { return m_Transitions; } set { m_Transitions = value; } }

```

But my impression is that in game development, unless you have a reason to do otherwise, *everything* should be nearly as fast as possible. My impression from things I've read is that Unity 3D is not sure to inline access via properties, so using a property will result in an extra function call.

Am I right to constantly ignore Visual Studio's suggestions to not use public fields? (Note that we do use `int Foo { get; private set; }` where there is an advantage in showing the intended usage.)

I'm aware that premature optimization is bad, but as I said, in game development you don't make something slow when a similar effort could make it fast.

# Answer
> 44 votes
> But my impression is that in game development, unless you have a reason to do otherwise, everything should be nearly as fast as possible.

Not necessarily. Just like in application software, there is code in a game which is performance-critical and code which is not.

If the code is executed several thousand times per frame, then such a low-level optimization might make sense. (Although you might first want to check first if it is actually necessary to call it that often. The fastest code is code you don't run)

If the code is executed once every couple seconds, then readability and maintainability is far more important than performance.

> I've read is that Unity 3D is not sure to inline access via properties, so using a property will result in an extra function call.

With trivial properties in the style of `int Foo { get; private set; }` you can be pretty certain that the compiler will optimize the property wrapper away. But:

* if you actually have an implementation, then you can not be that sure anymore. The more complex that implementation, the less likely that the compiler will be able to inline it.
* Properties can hide complexity. This is a double-edged sword. On the one hand, it makes your code more readable and changeable. But on the other hand, another developer who accesses a property of your class might think they are just accessing a single variable and not realize how much code you've actually hidden behind that property. When a property starts to become computationally expensive, then I tend to refactor it into an explicit `GetFoo()` / `SetFoo(value)` method: To imply that there is a lot more happening behind the scenes. (or if I need to be even more sure that others get the hint: `CalculateFoo()` / `SwitchFoo(value)`)

# Answer
> 10 votes
When in doubt, use best practices.

You are in doubt.

---

That was the easy answer. Reality is more complex, of course.

First, there's the myth that game programming is ultra super high performance programming and everything has to be as fast as possible. I classify game programming as *performance aware programming*. The developer must be aware of performance constraints and work within them.

Second, there's the myth that making every single thing as fast as possible is what makes a program run fast. In reality, identifying and optimizing bottlenecks is what makes a program fast, and that is much easier/cheaper/faster to do if the code easy to maintain and modify; extremely optimized code is hard to maintain and modify. It follows that *in order to write extremely optimized programs, you have to use extreme code optimization as often as needed and as rarely as possible.*

Third, the benefit of properties and accessors is that they are robust to change, and thus make code easier to maintain and modify - which is something you need to write fast programs. Want to throw an exception whenever someone wants to set your value to null? Use a setter. Want to send a notification whenever the value changes? Use a setter. Want to log the new value? Use a setter. Want to do lazy initialization? Use a getter.

And fourth, personally I don't follow Microsoft's best practice in this instance. If I need a property with trivial and *public* getters and setters, I just use a field, and simply change it to a property when I need to. However, I very rarely need such a trivial property - it's far more common that I want to check for boundary conditions, or want to make the setter private.

# Answer
> 2 votes
It is very easy for the .net runtime to inline simple properties, and often it does. But, this inlining is normally disabled by profilers, hence it is easy to be misled and think that changing a public property to a public field will speed up software.

In code that is called by other code that will not be recompiled when your code is recompiled there is a good case for using properties, as changing from a field to a property is a breaking change. But for most code, other than being able to set a breakpoint on the get/set, I have never seen benefits in using a simple property compared to a public field.

The primary reason I used properties in my 10 years as a professional C# programmer was to stop other programmers telling me I was not keeping to the coding standard. This was a good tradeoff, as hardly ever was there a good reason not to use a property.

# Answer
> 2 votes
Structs and naked fields will ease interoperability with some not managed APIs. Often you will find that the low level API wants to access the values by reference, which is good for performance (as we avoid an unnecessary copy). Using properties is an obstacle to that, and often times the wrapper libraries will do copies for ease of use, and sometimes for security.

Because of that, you will often get better performance having vector and matrix types that do not have properties but naked fields.

---

Best practices are not creating in vaccum. Despite some cargo cult, in general best practices are there for a good reason.

In this case, we have a couple:

* A property allows you to change the implementation without changing the client code (on a binary level, it is possible to change a field to a property without changing the client code on a source level, however it will compile to something different after the change). That means, that by using a property from the start, the code that references yours will not have to be recompiled just to change what the property does internally.
* If not all the possible values of the fields of your type are valid states, then you do not want to expose them to client code that code modify it. Thus, if some combinations of values are invalid, you want to keep the fields private (or internal).

I have been saying client code. That means code that calls into yours. If you are not making a library (or even making library but using internal instead of public), you can usually get away with it and some good discipline. In that situation the best practice of using properties is there to prevent you from shooting yourself in the foot. Furthermore, it is much easier to reason about code if you can see all the places where a field can change in a single file, instead of having to worry on whatever or not it is being modified somewhere else. *In fact, properties are also good to put breakpoints when you are figuring out what went wrong.*

---

Yes, there is value is seeing what is being done int industry. However, do you have a motivation to go against the best practices? or are you just going against the best practices – making the code harder to reason about – just because somebody else did it? *Ah, by the way, "others do it" is how you start a cargo cult.*

---

So... Is your game running slow? You are better of devoting time to figure out the bottleneck and fixing that, instead of speculating what could it be. You can rest assured that the compiler will do plenty of optimizations, because of that, chances are you are looking at the wrong problem.

On the flip side, if you are deciding what to do to begin with, you should worry about what algorithms and data structures first, instead of worrying about smaller details such as fields vs properties.

---

Finally, do you earn something by going against best practices?

For the particulars of you case (Unity and Mono for Android), does Unity takes values by reference? If it doesn't, it will copy the values anyway, no performance gain there.

If it does, if you are passing this data to an API that takes ref. Does it make sense to make the field public, or you could make the type able to call the API directly?

Yes, of course, there could be optimizations that you could do by using structs with naked fields. For example, you access them with pointers `Span<T>`, or similar. They are also compact on memory, making them easy to serialize to send over the network or put in permanent storage (and yes those are copies).

Now, have you picked the right algorithms and structures, if they turn out to be a bottleneck, then you decide what is the best way to fix it... that could be structs with naked fields or not. You will be able to worry about that if and when it happens. Meanwhile you can worry about more important matters such as making a good or fun game worth playing.

# Answer
> 2 votes
For basic stuff like that, the C# optimizer's going to get it right anyway. If you worry about it (and if you worry about it for more than 1% of your code, *you're doing it wrong*) an attribute was created for you. The attribute `[MethodImpl(MethodImplOptions.AggressiveInlining)]` greatly increases the chance a method will be inlined (property getters and setters are methods).

# Answer
> 1 votes
> ...my impression is that in game development, unless you have a reason to do otherwise, *everything* should be nearly as fast as possible.

:

> I'm aware that premature optimization is bad, but as I said, in game development you don't make something slow when a similar effort could make it fast.

You are right to be aware that premature optimisation is bad but that is only half the story (see the full quote below). Even in game development, *not everything* needs to be as fast as possible.

First make it work. Only then, optimise the bits that need it. That's not to say that the first draft can be messy or needlessly inefficient but that optimisation is not a priority at this stage.

"*The real problem is that **programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times**;* premature optimization is the root of all evil (or at least most of it) in programming." Donald Knuth, 1974.

# Answer
> 0 votes
Exposing structure-type members as properties rather than fields will often yield poor performance and semantics, especially in cases where structures are actually treated as structures, rather than as "quirky objects".

A structure in .NET is a collection of fields duct-taped together, and which can for some purposes be treated as a unit. The .NET Framework is designed to allow structures to be used in much the same way as class objects, and there are times this can be convenient.

Much of the advice surrounding structures is predicated on the notion that programmers will be wanting to use structures as objects, rather than as taped-together collections of fields. On the other hand, there are many cases where it can be useful to have something that behaves as a taped-together bunch of fields. If that's what one needs, the .NET advice will add needless work for programmers and compilers alike, yielding worse performance and semantics than simply using structures directly.

The biggest principles to bear in mind when using structures are:

1. Don't pass or return structures by value or otherwise cause them to be copied unnecessarily.
2. If principle #1 is adhered to, large structures will perform just as well as small ones.

If `Alphablob` is a structure containing 26 public `int` fields named a-z, and a property getter `ab` which returns the sum of its `a` and `b` fields, then given `Alphablob[] arr; List<Alphablob> list;`, the code `int foo = arr[0].ab + list[0].ab;` will need to read fields `a` and `b` of `arr[0]`, but will need to read all 26 fields of `list[0]` even though it will ignore all but two of them. If one wanted to have a generic list-like collection that could work efficiently with a structure like `alphaBlob`, one should replace the indexed getter with a method:

```
delegate ActByRef<T1,T2>(ref T1 p1, ref T2 p2);
actOnItem<TParam>(int index, ActByRef<T, TParam> proc, ref TParam param);

```

which would then invoke `proc(ref backingArray[index], ref param);`. Given such a collection, if one replaces `sum = myCollection[0].ab;` with

```
int result;
myCollection.actOnItem<int>(0,
  ref (ref alphaBlob item, ref int dest)=>dest = item,
  ref result);

```

that would avoid the need to copy portions of the `alphaBlob` that aren't going to be used in the property getter. Since the passed delegate doesn't access anything other than its `ref` parameters, the compiler can pass a static delegate.

Unfortunately, the .NET Framework doesn't define any of the kinds of delegates needed to make this thing work nicely, and the syntax ends up being kind of a mess. On the other hand, this approach makes it possible to avoid copying structures needlessly, which will in turn make it practical to perform in-place actions on large structures stored within arrays, which is the most efficient way of accessing storage.

---
Tags: unity, performance, optimization
---


title: Making 2 Player UI

text:
# Question
Title: Making 2 Player UI
For practice, I'm trying to remake the character select screen from Street Fighter II.

I managed get it working with a Grid Layout Group, ScriptableObjects, and some scripts to have the 1P cursor move around and change the portrait and text on the left.

What I don't know is how to make it 2 Player. The white area on the right is where I'm intending to show the selection for the second player, however I can't get 2 players to work here.

Currently, the Player selection works using WASD or the Arrow Keys (and the mouse, though I'd like some way to turn that off for now since it causes weird things to happen).

I'd like P1 to work with WASD and P2 to work with the arrow keys.

I've tried to make 4 new axes for the X & Y of each player with different buttons and apply them to different Standalone Input Module components, but that doesn't work (one often ends up disabling the other).

I've also looked into Event Systems, but wasn't sure if this was applicable. I don't know much beyond the basics of UI programming and I've never really dealt with Event Systems and Event Triggers before this. Nothing I do seems to let a second player exist in this selection scene.

This is the script that I'm currently using for selection. It uses parameters from a Character ScriptableObject I made to control the graphics. However, my navigation inputs in the UI seem to be driven by the Standalone Input Module.

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

public class SelectionScript : Selectable
{

    //Our variables
    Image characterPortrait;
    Image characterNameSprite;
    Text characterName;
    CharDisplay character;
    public GameObject P1cursor;

    BaseEventData m_BaseEvent;//This is a way for us to track certain events in a Selectable object in the Event System.

    // Start is called before the first frame update
    void Start()
    {
        character = GetComponent<CharDisplay>(); //We're going to use this to access anything we want inside of the CharDisplay

        characterName = character.nameText; //The UI object in the CharDisplay Script we said we wanted to represent the name text
        characterNameSprite = character.charName; // The UI Object we want to show the Name Sprite
        characterPortrait = character.portrait; //The UI object we want to show the Portrait Art

        P1cursor = GameObject.FindGameObjectWithTag("P1Cursor"); // Automatically finds the P1cursor based on tag
    }

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

        if ((IsHighlighted(m_BaseEvent) == true)){ //If an object is highlighted...
            P1cursor.transform.position = gameObject.transform.position; //Move the cursor to it.
            characterPortrait.sprite = character.character.Portrait; //Make the sprite of the Portrait UI Image we're accessing become the CharDisplay Character's defined Portrait sprite.
            characterNameSprite.sprite = character.character.CharName; //Make the sprite of the Name Sprite UI Image we're accessing become the CharDisplay Character's defined Name sprite.
            characterName.text = character.character.name; //Make the name in the extra textbox we made equal the CharDisplay Character's defined name text.
        }

        //This let's us know what we are selecting.
        if ((IsHighlighted(m_BaseEvent)== true) && Input.GetKey(KeyCode.Space))
        {
            Debug.Log("You have selected " + characterName.text.ToString());//We need to translate the name of the character into a string for the console.
        }
    }
}

```

Anyone have any advice on making a 2-Player UI? I'm glad I was able to figure the 1P out, but I'd really appreciate being able to learn how to make a multiplayer UI.

# Answer
> 1 votes
This is possible, but you have to keep track of one selection for each player separately, and handle reading each player's input/reacting to it yourself.

But you can still reap the benefits of the UI system's navigation mapping, highlighted state transitions, etc.

We can do this with a `MonoBehaviour` script that represents one player's selection state. Our scene can contain one or more instances of this script, or even spawn/enable more on the fly as players join.

This script is responsible for:

* reading one player's inputs
* updating the selected item based on those inputs
* reflecting the current selection using that player's cursor and the UI selected states (think button highlights, etc)
* notifying other scripts when this player's selection has changed, via an `onSelect` event

(Your selected character name & portrait panel can subscribe to this event and peek at the selected item to determine what to show)

Here's a proof of concept:

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

public class IndividualSelection : MonoBehaviour
{
    // Use this to position a cursor or selection highlight for each player.
    public RectTransform cursor;

    // Choose which UI element this player should select by default.
    public Selectable defaultSelection;

    // Names for this player's axes & buttons,
    // so they're not both listening to the same inputs.
    public string horizontalAxis;
    public string verticalAxis;
    public string acceptButton;
    public string cancelButton;

    // To make an analog stick "clicky" - you might need to soup-up the
    // sensitivity & gravity values beyond their defaults in the Input Manager.
    public float activationThreshold = 0.1f;

    // Debouncing / rejecting holds on the axis.
    Vector2 _axisMemory;

    // Keeping track of current selection state.
    Selectable _currentSelection;
    static Dictionary<Selectable, int> _selectionCount = new Dictionary<Selectable, int>();

    // Expose an event for when the player's selection changes.
    // Hook into this to update your portrait / etc.
    [System.Serializable]
    public class SelectionEvent : UnityEvent<Selectable> { }
    public SelectionEvent onSelect;

    public UnityEvent onAccept;

    public Selectable GetCurrentSelection() { return _currentSelection; }

    void Start() {
        // Selection has to start somewhere
        // (you can also inject this from the script that spawns the player
        // or handles joining in progress, or choose a default selection randomly)
        Select(defaultSelection);
    }

    public void Select(Selectable target) {
        // A more complete solution might see us create our own EventSystem
        // or InputModule that's multiplayer-aware, but this will do for now.
        var fakeEvent = new BaseEventData(EventSystem.current);

        // Deselect the old selection if we're the last one to leave it.
        // (But don't deselect something another player is still hovering over)
        if (_currentSelection != null && --_selectionCount[_currentSelection] == 0) {
            _currentSelection.OnDeselect(fakeEvent);
            _selectionCount.Remove(_currentSelection);
        }

        // Handle highlighting our current selection.
        _currentSelection = target;
        if (_selectionCount.ContainsKey(_currentSelection))
            _selectionCount[_currentSelection]++;
        else {
            _selectionCount.Add(_currentSelection, 1);
            target.OnSelect(fakeEvent);
        }

        // Position our cursor over the selected control.
        // There are nicer ways to animate this, but this served for a quick test.
        cursor.position = _currentSelection.transform.position;

        // Let listeners know that this player's selection has changed.
        if(onSelect != null)
            onSelect.Invoke(_currentSelection);
    }

    void Update() {
        Vector2 input = new Vector2(Input.GetAxis(horizontalAxis), Input.GetAxis(verticalAxis));

        Selectable nextSelection = null;

        // Don't keep bouncing down the list until the player releases/reverses.
        // TODO: handle repeat rate for holding in one direction, if desired.
        if (input.x * _axisMemory.x <= 0f) {
            _axisMemory.x = 0f;
            if (Mathf.Abs(input.x) > activationThreshold) {
                if (input.x > 0f) {
                    nextSelection = _currentSelection.FindSelectableOnRight();
                    _axisMemory.x = 1f;
                } else {
                    nextSelection = _currentSelection.FindSelectableOnLeft();
                    _axisMemory.x = -1f;
                }
            }
        }

        if (input.y * _axisMemory.y <= 0f) {
            _axisMemory.y = 0f;
            if (Mathf.Abs(input.y) > activationThreshold) {
                if (input.y > 0f) {
                    nextSelection = _currentSelection.FindSelectableOnUp();
                    _axisMemory.y = 1f;
                } else {
                    nextSelection = _currentSelection.FindSelectableOnDown();
                    _axisMemory.y = -1f;
                }
            }
        }

        if(nextSelection != null) {
            Select(nextSelection);
        } else if(Input.GetButtonDown(acceptButton)) {
            // If we're selecting something clickable,
            // handle the accept button like a click.
            var clickable = _currentSelection.GetComponent<IPointerClickHandler>();
            if (clickable != null) {
                if (_currentSelection.IsInteractable()) {
                    clickable.OnPointerClick(new PointerEventData(EventSystem.current));
                }
            // Otherwise, pass the accept on to any other interested listeners.
            } else if (onAccept != null) {
                onAccept.Invoke();
            }
        }
    }
}

```

---
Tags: unity, multiplayer, gui, selection
---


# Question
Title: Collision detection and solution causes teleportation on corners
I am making my own game engine on Python and I got stuck with collision between objects.

```
# If we go Right
if (collision_rect.right >= object_collision_rect.left) and \
        (collision_rect.left <= object_collision_rect.left):
    if (collision_rect.bottom > object_collision_rect.top) and \
            (collision_rect.top < object_collision_rect.bottom):
        if self.acceleration.x > 0:
            self.acceleration.x = 0
            moving.x = object_collision_rect.left - collision_rect.right

 # Bottom
 if (collision_rect.bottom >= object_collision_rect.top) and \
         (collision_rect.top <= object_collision_rect.top):
     if (collision_rect.right > object_collision_rect.left) and \
             (collision_rect.left < object_collision_rect.right):
         if self.acceleration.y > 0:
             self.acceleration.y = 0
             moving.y = object_collision_rect.top - collision_rect.bottom

```

There are two more for left and top.

It makes teleporting on corners. And if we change the second conditions from \< \> to \<= \>=, we get teleporting on edges, if we have acceleration x and y both != 0

# Answer
I found solution. First of all I made collision detection function for readability, then I made collision for each axis apart.

```
self.collision(objects_around, Vector2D(self.acceleration.x, 0))
self.collision(objects_around, Vector2D(0, self.acceleration.y))

def collision(self, objects, acceleration):
    if not self.collision:
        return

    self.position += acceleration
    collision_rect = self.get_collision_rect()

    for object in objects:
        if not object.isCollision or self.id_ == object.id_:
            continue
        object_collision_rect = object.get_collision_rect()
        if not collision_rect.intersects(object_collision_rect):
            continue

        if acceleration.x > 0:
            self.position.x += object_collision_rect.left - collision_rect.right
        elif acceleration.x < 0:
            self.position.x += object_collision_rect.right - collision_rect.left

        if acceleration.y > 0:
            self.position.y += object_collision_rect.top - collision_rect.bottom
        elif acceleration.y < 0:
            self.position.y += object_collision_rect.bottom - collision_rect.top

```
> 1 votes

---
Tags: collision-detection, python, collision-resolution, collision-avoidance
---


title: Sort buttons in unity 2D

text:
# Question
Title: Sort buttons in unity 2D
I've a list of buttons that I create using XML stored data. To achieve it, I've created a `Prefab`. These buttons are created correctly, and now I want them to be sorted for the user.

```
public List<GameObject> myButtons;

```

As I said, now I want to sort them. I've found out that sorting the `List` itself, buttons are sorted in the UI.

```
myButtons.Sort((x, y) => ...);

```

The problem is, that I don't have the necessary data to sort them within them. This leaves the `.Sort()` method unavailable for use.

I've tried to sort them adding an script to each one, which contains the data that I need to use to sort them. However, it doesn't work correctly and I seem unable to find out why, so I'm wondering about other more direct methods to sort them.

Notice that I'm referring to simple buttons in a 2D game, and that they're all inside the same `parent/gameobject`.

## Technical Details

Let's start by the basics: I want to order the buttons taking into account if the user has reached a point in which the item it represents should be `available`.

This is stored in an instance of a class that represents the items related to the buttons of the question.

```
public class myItemClass
    {
        # Here there are other properties
        public bool available;
    }

```

Therefore, we've a correspondence between two lists:

```
public List<myItemClass> myItems;
public List<GameObject> myButtons;

```

Where:

> myItems\[0\] is related/represented by myButtons\[0\]
>
> ...

NOTICE that this relation exist at the initialization of the game, so i need to keep it at any moment (meaning, having to sort both lists).

## What I tried

To be able to order my buttons depending on if the items are available or not, what I've done is:

1. Creating an script `myItemScript`, which has a reference to my original items from the other list.
2. Sorted the items using `Sort` function over them.

```
public class myItemScript: MonoBehaviour {
    public OtherClass.myItemClass dataObject;
}

```

And then sorting them like:

```
myButtons.Sort((x, y) => y.GetComponent<myItemScript>().dataObject.available.CompareTo(x.GetComponent<myItemScript>().dataObject.available));

```

As I said before, both list need to be following the same order, so just after it, I order the item list as well:

```
myItems.Sort((x, y) => y.available.CompareTo(x.available));

```

## Checking/Debug

As result, I found that items were in fact sorting different. However:

* Items inside `myItems` List were sorted as expected.
* Buttons in UI (and hence, `myButtons` List were not sorted as expected. Mixed items (available = true/false) were mixed and not ordered in two blocks, one first and then the other one.

This was checked using breakpoints within VS2017 and pausing the game in Unity interface.

# Answer
> 0 votes
To change the order of UI elements, you can use Transform.SetSiblingIndex. Be careful though, if Unity uses arrays to store child elements, changing their order will be an expensive operation.

# Answer
> 0 votes
It looks like you're sorting using a boolean value as your sort key. That means many items in your list will compare as equal (`true == true` and `false == false`)

When two items are equal, an unstable sort like `List.Sort(Comparison<T>)` is allowed to put them in any order. And it's allowed to make different decisions from one run to another (this nondeterminism is important for getting good performance from algorithms like QuickSort)

So it could put all the `true` items and all the `false` items together in both the list of items and the list of buttons, but use a different order of items within the `true` partition or within the `false` partition.

It's also strictly more work than you need. You can sort all the true items to the start of your array in linear time, deterministically:

```
int SortAvailableFirst(List<Item> items, List<GameObject> buttons) {
    int firstFalseIndex = 0;
    for(int i = 0; i < items.Count; i++) {
        var item = items[i];
        var button = buttons[i];
        if(item.available == false)
            continue;

        items[i] = items[firstFalseIndex];
        buttons[i] = buttons[firstFalseIndex];
        items[firstFalseIndex] = item;
        buttons[firstFalseIndex] = button;
        firstFalseIndex++;
    }

    // Return the number of available items.
    return firstFalseIndex;
}

```

This maintains the order of the available items, putting them at the front of the list. It does scramble the order of the unavailable items, but it scrambles them the same way when given the same sequence of trues & falses — it makes no random choices.

Or, with a little extra effort you can maintain the order of both true and false items.

Or, another way to get the order consistent is to sort your items first, then spawn your buttons in order by walking over the list of already-sorted items.

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


title: How to construct this collision vector?

text:
# Question
Title: How to construct this collision vector?
I have a 3d game, but for movement I use only two axes (X and Z) - X is vertical, Z is horizontal

Here's what I'm trying to achieve:

Player is the circle, InputDirection is Blue, NewInputDirection is Green. I'm struggling on getting the desired green direction.

**Image 1** The player moves up (he's pushing onto the wall)

`InputDirection: (-1f, 0f, 0f)`

`NewInputDirection: (0f, 0f, 0f) because we should stop him.`

**Image 2** The player moves towards the wall and the bottom. When he reaches the wall, his horizontal axis should be blocked - set to 0, so he slides)

`InputDirection: (0.5f, 0f, -0.5f)`

`NewInputDirection: (0.5f, 0f, 0f)`

**Image 3** Same thing as above, but the wall is rotated.

Right now, my code looks like this:

```
RaycastHit hit;
bool collides = Physics.Raycast(this.playerRigidbody.position, inputDirection, out hit, 1f); // ray in front of the player

if(collides){ // if there's a collision
    // calculate the direction from the player to the collision contact point
    Vector3 collisionNormal = (hit.point - playerRigidbody.position).normalized;
    // idk...
}

```

I don't know how to calculate it. I've tried various ways. Should I also take the wall's rotation into account?

# Answer
> 1 votes
The simple answer here is vector projection. If `n` is a unit vector (length 1), then...

```
float projection = Vector3.Dot(n, someVector);`

```

is the signed length of the component of `someVector` that's parallel to `n`. We can subtract that component to leave only the perpendicular component:

```
Vector3 perpendicular = someVector - n * projection;

```

It looks like you have more going on here than just the vector math question, so I'll expand on that below.

---

You seem to be using this to let the player character move up to and along a wall, without penetrating through it.

For that purpose, I'd recommend using a spherecast or capsulecast instead. The reason is that the ray can squeeze into spaces that your player character couldn't, so if you just position yourself at the end of the ray, you might clip into an obstacle the ray barely missed to one side or the other.

```
RaycastHit hit;
bool collides = Physics.SphereCast(
                 playerRigidbody.position,
                 playerAvoidanceRadius,
                 inputDirection,
                 out hit,
                 1f);

if(collides){ // if there's a collision
    // I've found that adding a slight extra margin here helps avoid unwanted intersections.
    float uninterruptedDistance = hit.distance - 0.001f;
    // Compute our blue arrow.
    Vector3 directTravel = inputDirection * uninterruptedDistance;

    // Subtract out the component of the direction that goes into the wall.
    // Leaving the direction that's parallel.
    float projection = Vector3.Dot(inputDirection, hit.normal);
    // Compute our green arrow direction.
    Vector3 slideDirection = (inputDirecton - hit.normal * projection).normalized;

    // If you want to move as far as you can along the blue, then start moving along the green...
    float remainingDistance = moveDistance - uninterruptedDistance;
    Vector3 slideTravel = slideDirection * remainingDistance;

    Vector3 totalTravel = directTravel + slideTravel;

    // Do what you want with it.
}

```

Note that we scanned for obstacles along only the blue arrow - so it's possible moving to the end of the green arrow will put us in collision with something we didn't scan for. So if you want to be really exacting here, you can recurse and fire a new ray/sphere/capsule cast along the new direction. I show an example of doing that in this answer.

---
Tags: unity, collision-detection, rotation
---


title: Android: 2d scrolling background

text:
# Question
Title: Android: 2d scrolling background
I am a very beginner in game development. All I want to achieve in the beginning is a free scrollable background like in a strategy game with my custom graphics. In my case it is supposed to be a 2d city map where the user can select buildings. How can I achieve that as easy as possible in android? With OpenGL? Die you have any examples especially for this scrolling functionality?

# Answer
I think you should go with frameworks like Libgdx rather than using directly OpenGL. Libgdx allow you to draw graphical assets and program interactivity with them.

Here is some starting points :
> 1 votes

# Answer
If you want the buildings in the backgroudn to be clickable you could create different classes for each building, assign an image to the object and use ArrayLists to determine how many you would like in the background.

You would have to run a thread in your main class to move the buildings either right or left, check the locations and if `x - image.getWidth < 0` then the whole building has left the screen, this means another building needs to be added to the right.
> 1 votes

# Answer
I had a similar problem when I wanted to create a scrolling background. I found the following tutorial (in Java) which is quite easy and worked:

http://gamecodeschool.com/android/coding-a-parallax-scrolling-background-for-android/
> 0 votes

---
Tags: android, opengl-es
---


# Question
Title: Wrong return type on IEnumerator method (AsyncOperation.progress)
I am basically just using this script from the documentation as it's the exact same thing that I want to do.

https://docs.unity3d.com/ScriptReference/AsyncOperation-progress.html

Just replacing it with my own buttons and scene number but I get the error:

```
CS0407: 'IEnumerator MenuController.LoadScene()' has the wrong return type

```

What should be done differently?

```
public class MenuController : MonoBehaviour
{
    public Button StartButton;
    public Text EasyButtonText;

    // Start is called before the first frame update
    void Start()
    {
        StartButton.onClick.AddListener(LoadScene);
    }

    IEnumerator LoadScene()
    {
        yield return null;

        //Begin to load the Scene you specify
        AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(1);
        //Don't let the Scene activate until you allow it to
        asyncOperation.allowSceneActivation = false;
        Debug.Log("Pro :" + asyncOperation.progress);
        //When the load is still in progress, output the Text and progress bar
        while (!asyncOperation.isDone)
        {
            //Output the current progress
            EasyButtonText.text = "Loading progress: " + (asyncOperation.progress * 100) + "%";

            // Check if the load has finished
            if (asyncOperation.progress >= 0.9f)
            {
                //Change the Text to show the Scene is ready
                EasyButtonText.text = "Press space";
                //Wait to you press the space key to activate the Scene
                if (Input.GetKeyDown(KeyCode.Space))
                    //Activate the Scene
                    asyncOperation.allowSceneActivation = true;
            }

            yield return null;
        }
    }

}

```

# Answer
> 1 votes
You cut out this part of the sample:

```
void LoadButton()
{
    //Start loading the Scene asynchronously and output the progress bar
    StartCoroutine(LoadScene());
}

```

The button's `onClick` event can only work with methods that match the signature it's looking for, specifically:

```
void SomeFunctionName() { ... }

```

No return value, no arguments.

But your `LoadScene` method is a coroutine, with a signature that looks like:

```
 IEnumerator SomeCoroutineName(...) { ... }

```

So it doesn't match. Moreover, to get the benefit of resuming a coroutine after it's `yield`ed, you have to start it via `StartCoroutine()`.

That's what `LoadButton()` does above. It acts as an adapter, providing a listener function that can be attached to the button's `onClick` event, and then doing the work of starting the coroutine.

So `StartButton.onClick.AddListener(LoadScene);` should be `StartButton.onClick.AddListener(LoadButton);` using the method from the sample.

When copying code from the Internet, make sure you didn't accidentally delete anything - it might have been important!

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


# Question
Title: Unity detect tap on object or area with Raycast turned off on the object
I have a large dial which can be rotated by touch. I have a circular crosshairs at the top to show which number is selected. I have had to turnoff the `Raycast Target` on the crosshairs because it was stopping the dial rotation when the when the finger touch was moving over it.

My problen now is that when the desired number is selected in the crosshairs I want to be able to tap the crosshairs to go to that level. Is it possible to detect the tap on the crosshairs?

Here is the code I have attached to the dial for rotation.The crosshairs is the very next `GameObject` in the hierarchy.

```
public void OnDrag(PointerEventData eventData)
{
    //CHECK IF CAN DRAG
    if (!_canDrag)
    {
       return;
    }
    transform.rotation = finalRotation;

```

# Answer
> 1 votes
You can reference the Image crosshair and on start you can disable the raycast so it does not interfere with the dial as you mentioned.

```
Image crosshair
void Start()
{
    crosshair = GetComponent<Image>();
    crosshair.raycastTarget = false;
}

```

then after your desired number is selected set the image raycast back to true for the crosshair so it can be selectable again.

```
crosshair.raycastTarget = true;

```

---
Tags: unity
---


# Question
Title: How to make procedurally generated terrain look realistic
I generated a terrain using a technique from this blog post, everything worked well and I got the wanted result. This is what my generated island looks like:

As you can see the terrain have a polygon structure. Here is the graph that generated this mesh:

This is the code used to generate this mesh from the graph:

```
    void DrawPolygons(){
    List<Vector3> vertices = new List<Vector3>();
    List<int> triangles=new List<int>();
    List<Color32> colors = new List<Color32>();

    foreach(Center c in centers){
        float zp = zScale*c.elevation;
        vertices.Add(new Vector3(((Vector2)c.point).x,zp,((Vector2)c.point).y));
        Color c0 = getColor(c);
        colors.Add(c0);
        int centerIndex=vertices.Count-1;
        var edges = c.borders;
        int lastIndex = 0;
        int firstIndex = 0;

        for(int i =0;i<c.borders.Count;i++){
            if(edges[i].v0 == null && edges[i].v1 == null)
                break;

            //get voronoi edge
            Corner corner0 = edges[i].v0;
            Corner corner1 = edges[i].v1;

            //get vertices height
            float z0 = zScale*corner0.elevation;
            float z1 = zScale*corner1.elevation;

            //add color
            if(edges[i].river>0){
                c0 = Color.cyan;
            }else{
                c0 = getColor(c);
            }

            colors.Add(c0);
            colors.Add(c0);

            //creat voronoi edge points
            Vector3 v0 = new Vector3(((Vector2)corner0.point).x,z0,((Vector2)corner0.point).y);
            Vector3 v1 = new Vector3(((Vector2)corner1.point).x,z1,((Vector2)corner1.point).y);

            //add points to vertices
            vertices.Add(v0);
            var i2 = vertices.Count - 1;
            vertices.Add(v1);
            var i3 = vertices.Count - 1;

            //add triangles calculating surface normals so i can always add triangles clockwise correctly
            var surfaceNormal = Vector3.Cross (v0-(new Vector3(((Vector2)c.point).x,zp,((Vector2)c.point).y)), v1-(new Vector3(((Vector2)c.point).x,zp,((Vector2)c.point).y)));
            if(surfaceNormal.y>0)
                AddTriangle(triangles, centerIndex, i2, i3);
            else
                AddTriangle(triangles, centerIndex, i3, i2);

            firstIndex = i2;
            lastIndex = i3;
        }
    }

    //calculating uv's
    Vector2[] uvs = new Vector2[vertices.Count];
    for (int i = 0; i < uvs.Length; i++)
    {
        uvs[i] = new Vector2(vertices[i].x / SIZE, vertices[i].z / SIZE);
    }

    mesh.Clear();
    mesh.vertices = vertices.ToArray();
    mesh.triangles = triangles.ToArray();
    mesh.uv = uvs;
    mesh.colors32 = colors.ToArray();
    mesh.RecalculateNormals();
    mesh.RecalculateBounds();
    meshFilter.sharedMesh = mesh;
    meshCollider.sharedMesh = mesh;

}

```

I would like to know if it's possible to have a noisy/realistic looking terrain from this. How would I implement such a thing?

Basically I want something with no hard edges, terrain that looks smooth but not too smooth, something like this video shows:

# Answer
> 3 votes
First of all, note that Unity already has a very nice terrain system out-of-the-box. It gives you a lot of nice features for free like LOD, occlusion culling and a lot more. Also, it can look pretty neat. You can still generate terrain procedurally, but the input data it expects isn't a mesh but a height map in form of a two-dimensional array of floats. So if you want to keep using that cell-based algorithm, you will have to convert it to output a heightmap instead of a list of vertices.

But no matter which technical implementation you choose to render your map: If you want to generate a landscape which combines discernible large features with small details, then it is usually a good idea to layer multiple terrain generation algorithms on top of each other. Use a pass with a high amplitude and a low resolution to generate the basic shapes (like you already do), and then run another pass with a lower amplitude but a higher resolution to create detail.

You could, for example, apply the same algorithm you are already using again for each cell to subdivide it further. Or you could use a completely different algorithm to "rough up" each cell like Perlin Noise.

Also, don't underestimate the effect of good textures. A high-resolution texture with a good normal map could make a terrain surface look a lot less plastic-like. Keep in mind that you need to also call `mesh.RecalculateTangents()` on your mesh for normal maps to render correctly.

I am looking forward to exploring the procedurally generated worlds in your game.

# Answer
> 1 votes
A good way to generate realistic terrain is to *simulate* physical processes like

* corrosion
    + either with a "uniform" corrosion algorithm or simulation of water or both
* simulation of interaction of multiple sediment layers, don't forget that the origin of a lot of amazing landscapes are the sediments and the interactions of them with water underneath, like stone, dirt, sand, etc.
* plate tectonics(?) (no idea which game simulates that but it's maybe possible)

---
Tags: unity, procedural-generation, 3d-meshes, terrain-rendering
---


title: Multiplayer platformer

text:
# Question
Title: Multiplayer platformer
I'm considering building a multiplayer game having a central server handling the game and keep clients updated. I was checking various examples of ".io" games styles of implementation and seems pretty straight forward that the logic is on server and clients are mostly dummy.

Now the question that I have is .. how dummy should be the client? Where do you draw the line?

To give more context, I was thinking of building a platformer with 2 players on it, a few obstacles on the way etc.

What is clear for me is:

* any input the characters receive needs to be sent to the server and updated the other client.
* any map event logic will stay on the server and update clients when happening

What is not clear for me is:

* where do you place basic physics? like keeping the character on the map
* how about a simple movement like Jumping? should it be like a state sent to the server?
* what about the whole map? should the server know the entire map?
* what if I want to destroy one tile of the map?

I would appreciate your point of view or if you know some examples / links where I can find more info about these things.

Cheers!

# Answer
> What is clear for me is:
>
> * any input the characters receive needs to be sent to the server and updated the other client.
> * any map event logic will stay on the server and update clients when happening

That is the gist of it.

---

> where do you place basic physics? like keeping the character on the map

Given that you have decided on a central server...

Physics happen on the server. If a player jumps, the server needs to compute the movement and notify all players so they can see the player jumping. That means that physics on the server is a must. Your server is your single source of truth for the state of the game, and thus everybody differs to the server to know what happens.

By the way, being the server the single source of truth is how you prevent cheating. For example, if the server were to let the players tell it that they have powers ups, that there is not a wall, or that they do not take damage, or whatever... well, you can imagine... somebody figures out how to modify or make a rogue client, that's it.

With that said, there is value is having physics on the client (in addition to having physics on the server). It is used so that he client can have feedback while it gets the update from the server. When that update comes, you can interpolate the state to the result from the server. *Your game can, and should be able to work without this, however, it can improve player experience.*

---

> how about a simple movement like Jumping? should it be like a state sent to the server?

The playes uses the jump input (button, touch, whatever it is), and then the client notifies the server. *If you are simulating on the client, the character can start moving right away using client side physics. In fact, in general, you want hide the latency in the animation.* The server will get the notifications from all the clients, and each server cycle/tick/iteration, the server will send updates to every player.

The clients will not send state, they will send commands to the server.

For the server you have options... it can send updates (send just what changed), or whole states. For a small game, for only a handful of people, there is no much difference.

---

Of course sending just what changed will mean less bandwidth, which is good... the reason to send whole updates is that a client has fallen behind could benefit from getting the current state instead of working its way up through the updates. That is, at some point the backlog of updates is havier than the whole state.

Thus, the server will have to decide if it is sending updates or the whole state about each object to which players. The first rule is that if for a given object, if the log of what changed about it that you would have to send to a given player is more information than just sending the current state, you send the current state.

---

> what about the whole map? should the server know the entire map?

Yes, of course. The server will know the whole state. The server needs to simulate physics there anyway. The server is the single source of truth about the world. While there are things that can be client side only (because only one player can see them, and they cannot affect other players), in general the server is aware of everything.

With that said, if the map is too large, it is worth considering not sending updates of the whole map to all the players. The players only need to receive updates about things that they can see, which means that you do not have to waste bandwidth in notifying the clients about stuff that is happening at the other side of the world.

That will be your second rule: if the server knows that a player cannot see an object, it does not send notifications about it to that player.

See, that is a way players can fall behind! If the player is not getting notifications about an object, when the player gets to a point it can see the object, it will need the state of it from the server. In fact, the client could offload from memory all the map it cannot see, in which case the server will have to send the whole state of any new area the player walks in.

*We usually do not want to send a log of all that changed in an area the player was not seeing. Why? Not only because bandwidth, but because, we do not want the client playing everything that happened in fast forward. The player should only see the current state, thus the server should only send to the client the current state.*

---

In case it is not evident, you do not need to send the sate of things that cannot change its state. Thus, if the whole map is pre-designed (not procedurally generated as you explore※), and small enough※※, the players can download it all before hand, and now the network code only needs special considerations about dynamic objects.

※: even if the map is procedurally generated, you could send everybody a seed that is used to generate at the start. Then again, if the players can destroy tiles, it means that tiles are dynamic, and thus the server will have to send their state. However, if the player were unable to destroy or modify tiles... well, the network code does not need special considerations about it.

※※: If the map is too big, then the special consideration is to break it into chuncks that can be downloaded on demand.

---

As you would know, to simulate physics it is a good idea to have a space aware structure where you can query nearby objects (so that you do not compute collision with everything, just what is nearby). It is the same structure that will tell you about what objects you need to send notifications to a client.

*In fact, you could have the server stop simulating things that nobody can see, and in doing so, save CPU time.*

---

> what if I want to destroy one tile of the map?

The client send the command to the server. The server decides what happens.

*In some situations the client could be aware that a tile cannot be destroyed, in which case it can save you a bit of bandwidth by not sending the command.*

Now, the server will decide if the tile gets destroyed, *and if there is a drop, if that action triggers something, or whatever*, and notify each player – that can see the change – about it. If it weren't done like this, a player could – as far as they can tell – destroy the tile but other players won't see the tile being destroyed.

---

Of course, there is an alternative. If each player sends commands to the other players, they can simulate them. That is what you would do in a P2P game. However, you have decided to have a central server. Hybrid? Possible. Too complicated. If you are not using a library that handles networking that is designed for that, I suggest to not do it.

*If you want to try your hand at doing such library, well, be my guest.*

---

To sum it up, I'll give you a bonus case:

> The player opens a chest

If you were to let the player decide what is the chest, cheat, cheat, cheat. Thus, the server decides what is in the chest. That means that the client has to ask the server.

However, you do not want to allow the client to randomly query what is in every chest without having to open them. That would be cheating too.

Thus, the client must only be able to send commands. It is Tell, Don't Ask. And the command is that it opens the chest.

Now, the server has to tell that client what happens (was it empty? did a monster jump up from inside of it? was it locked? did it contain apples?). Of course, the network will take a little while. You can put an animation of the player going for the chest to hide the few milliseconds the network could take.

The server also has to notify every other client that could see, that the chest is being open, and the client could play the animation of the other player opening it, with sound and all.

Oh, but, some players were to far, there is no need to send a notification to them. Instead, when they get to this area the server will tell them about the chest. However, do not send an update, the client should not be playing the animation of opening the chest... instead, the client should see how the chest ended up (already open, for example), so the server needs to send the state, not what changed.

---

You say you are making a platformer. However, were you doing a multiplayer shooter, the advice I would give you would have been the same. Nothing in my answer – before this paragraph – is predicated on the game being a platformer. Thus, I would like to encourage to look for how networking works for multiplayer games, regardless of whatever they are platformers or not.

*We are also not talking about databases and persistence, that is beyond the scope of this question.*

Now, being your game a platformer, you may be able to do some optimizations. For instance, if you are constraining your players to a single screen (I do not know if you do), then you know you only care about objects that are in that screen. That makes figuring out who to notify about what, much simpler. In fact, you won't have the case of a player entering an area where another player did something, if the players are together the whole time.

Addendum: if you want to do like the old games where stuff would reset (enemies respawn, etc.) as soon as they are off-screen. You can do that too. It would be simpler code.
> 2 votes

---
Tags: multiplayer, platformer, websocket, adventure-games
---


# Question
Title: Unity 2019 depth-only camera now overwrites everything
We have a pretty traditional camera stacking set up: UI camera on top of a everything-else camera.

The UI camera is set to only clear depth, and only draws the UI layer. The everything-else camera is set to clear via skybox and all layers but UI. Only the everything-else camera contains a post-processing layer component; disabling it does seem to make everything work the way it used to.

The UI camera has a higher depth than the everything-else camera, in case someone suggests otherwise.

In 2018 this exact arrangement worked as intended. In 2019, the UI camera's view is the only thing visible.

I've found several forum posts on Unity by Unity Technologies about the light-weight pipeline breaking this functionality, but we're not using any of the new pipelines. We simply upgraded, and I can't find any indication that we are using the new pipelines. Supposedly everything works normally as long as you don't use the new pipelines, but this is proving false so far.

Since this camera arrangement is very common, I can't imagine I am alone!

# Answer
> 2 votes
Unchecking "Directly to Camera Target" on the Post Processing Layer component did the trick. I am not completely certain what the option does yet, but I am guessing it may mean that the post-processing renders its output after all other camera renders, instead of during that particular camera's depth.

Unchecking "Directly to Camera Target" seems to muck with viewport settings in a weird way. The viewport minimum X value seems to act double-ish when this option is disabled...? We had a value of 0.24, but now 0.1 is necessary to recreate that. Very strange.

If anyone can help me understand what's going on, I'd appreciate it.

---
Tags: unity, camera, gui
---


title: Anti-Aliasing Problem

text:
# Question
Title: Anti-Aliasing Problem
So, I was annoyed by how the HUD for my GameState was very pixel-ated and I wanted to change that through the use of anti-aliasing. However, it works with a small exception:

It adds all these lines to the HUD, which is not what I want at all, is there a way to prevent this from occurring?

Here's what it looked like before anti-aliasing:

Also, here's the code:

```
    public void render(GameContainer container, StateBasedGame game, Graphics graphics) throws SlickException {
    graphics.setAntiAlias(true);
    renderOverlayGui(graphics);
    renderGui(graphics);
    graphics.setAntiAlias(false);
    renderIcons(graphics);
}

private void renderIcons (Graphics graphics) {
    graphics.drawImage(imgHeart, this.radius - 4, 1);
    graphics.drawImage(imgCoolDown, this.radius - 4, 18);
}

private void renderGui (Graphics graphics) {
    graphics.setColor(GameColour.brown);
    graphics.fill(guiCircle);
    graphics.fill(guiBox);
}

private void renderOverlayGui (Graphics graphics) {
    graphics.setColor(Color.black);
    graphics.fill(guiOverlayCircle);
    graphics.fill(guiOverlayBox);
}

```

# Answer
> 2 votes
It looks like the edges get a fractional alpha based on the edge coverage. Problem arises when two edges fill 100% together but are blended as translucency, not coverage, only applying ~75% color. It's like the difference between covering your eyes with both hands vs covering your eyes with two pair of sunglasses.

I only know how this works in opengl, but basically the technique requires you to render front to back order, no depth buffering, having alpha channel in destination framebuffer and set a special blending function (glBlendFunc(GL\_SRC\_ALPHA\_SATURATE,GL\_ONE)).

I don't know much about slick, but you could start out checking if you have an alpha channel in your framebuffer/window. Slick just might do the rest for you. I'll check out the library more closely when I have the chance.

**Edit** When looking closer at the slick source code (Graphics.java) it appears not being able to anti-alias triangle meshes without artifacts. It does appear possible to fix the source. I'll look into it.

Until then it might be best to draw textures instead that are anti-aliased from the beginning using GIMP or similar tool.

# Answer
> 0 votes
When you enable anti-aliasing in Slick2D, it should look like this.

```
g.setAntiAlias(true);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA_SATURATE, GL11.GL_ONE);

```

GL11 class is provided by LWJGL which is required by Slick2D.

Call that line after every time you enable AA to be safe, I haven't checked the Slick2D source code.

Note that with this whatever you draw first will be on top, rather than what you draw last. So you may need to reverse rendering order.

For more info: https://stackoverflow.com/questions/32151974/slick2d-using-anti-aliasing-with-animations-images

---
Tags: java, graphics-programming, slick, antialiasing
---


# Question
Title: How do I simulate color blindness for accessibility testing?
Is there an application I can download (or some configuration of Windows, or something) that will let me see how my game will appear to users with different color-blindnesses?

There are already good questions about how to avoid badly-designing your game for colour blindness. There's also a Photoshop filter from VisCheck is a nice idea, except their image-processing upload service is down.

Is there, therefore, a tool I can use to simulate colour blindness and see how things look? Ideally, I would like to try different types (red/green, blue/yellow, mild/severe).

If not, how do other game developers test/avoid this problem, other than ignoring it, or having access to a color-blind person (which I don't)?

# Answer
There's a list of software to simulate color blindless here, on Daltonize.org. The shame is that most of the links are dead.

One listed entry is Visolve, which seems to be relatively serious commercial software. If it really transforms the entire computer display colors, then that would be a perfect fit, if you're OK with paying the price.

Side note: if I understand correctly, color blindness can be simulated using simple color lookup tables. Example taken from Daltonize.org:

Color LUTs are also used for HDR tone mapping in (relatively) modern graphics engines. If your engine supports that, then it might be quite easy to plug those LUTs directly in your post-process chain.
> 5 votes

# Answer
## Windows 10 Settings

In Settings app, there is a section of "Ease of Access".In this section, in the "Color filters" tab on the left, you can "Turn on color filters". This can simulate vision of people who cannot see any color.

## Intel UHD Graphics Control Panel

For users with Intel graphics card, in the "Color Enhancement" section of "Color Settings", by lowering the saturation of each color, the filter can simluate all kinds of color blind. Refer to this StackOverflow question for detailed adjustments. Multiple profiles can be created for fast-switching.
> 4 votes

# Answer
Check out the Coblis color blindness simulator. Its a web app and you can jut upload an image.

Also there are color blind communities such as http://www.reddit.com/r/colorblind. If you put some effort into it I'm sure you can find a real color blind person to help out.
> 2 votes

---
Tags: tools, color, accessibility
---


# Question
Title: Unity: transform.LookAt(target) not "looking at" target?
I have been troubleshooting a prefab for several hours and am out of ideas. It concerns a method that I thought I was comfortable with, transform.LookAt(target). I have this prefab:

As you can see, I verified that the registration points for the eyes are at the center of mass; I also verified that they rotate correctly for the X, Y and Z axes. That yellow ball you see is the target object and **IS NOT** inside the prefab.

I have tried two means to get the eyes to look at the target. The first is this script, and it caused the eyes to dart 90 degrees counter-clockwise about the y axis (which is very wrong). *I applied this script to both eyes*. Check it out:

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

public class LookAt : MonoBehaviour
{
    public Transform target = null;

    // Update is called once per frame
    void Update()
    {
        transform.LookAt(target);
    }
}

```

And please, before you think it: **Yes**, I remembered to set the target object in the editor. You can see the eyes pointing to the side instead of the target:

I found this other script on the Unity documentation that didn't work at first, but then I changed "Rotation" to "LocalRotation", saw that I was close, reversed the "relativePos" vector, and *it worked--but only about the y axis*:

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

public class LookAt : MonoBehaviour
{
    public Transform target = null;

    // Update is called once per frame
    void Update()
    {
        Vector3 relativePos = transform.position - target.position;

        // the second argument, upwards, defaults to Vector3.up
        Quaternion rotation = Quaternion.LookRotation(relativePos, Vector3.up;
        transform.localRotation = rotation;

    }
}

```

You can see here that it works in the XY plane at eye level, but take my word for it when I say the eyes cannot look up or down if I move the ball up or down:

**How can I fix this so that the eyes always look at the target I need it to?** Thank you sincerely for your time.

**EDIT:** I fixed it by this sloppy additional rotation, but there has to be a better way:

```
void Update()
    {
        //transform.LookAt(target);

        Vector3 relativePos =  target.position - transform.position;

        // the second argument, upwards, defaults to Vector3.up
        Quaternion rotation = Quaternion.LookRotation(relativePos, new Vector3(0,1,0));
        transform.rotation = rotation*Quaternion.Euler(0,90,0);
    }

```

# Answer
**The Problem:**
Your eyes default rotation makes them look to the negative X axis.
However, Transform.LookAt() rotates the transform, so that the Transform.forward looks at the target.
The Transform.forward always looks to the positive Z axis.
(All directions in local space).

**Solution 1:**
Rotate the texture or mesh, so that the eye's default look direction is along the positive Z axis.
Then LookAt will work as expected.

**Solution 2:**
After the call of Transform.LookAt, correct the rotation by the correct rotation.

```
transform.LookAt(target);
transform.rotation *= Quaternion.FromToRotation(Vector3.left, Vector3.forward);

```

Where Vector3.left represents the default forward direction of the eyes.
> 10 votes

---
Tags: unity, rotation, vector
---


# Question
Title: Mimicking enemy boss movement of Wonderboy in Monster Land
I want to imitate the movement of the "Death" boss enemy in Wonderboy in Monster Land.

At first, I thought it just moves with a sine wave, but it's not. The up and down movement is erratic.

I thought it changes its facing direction at the player's x position, but as you see in the video, it did not change direction when player jumped.

And if the player sits under the boss, the boss just moves up and down and changes direction irregularly.

So far I've tried to imitate its movement with this:

```
transform.position = pos + transform.up * Mathf.Sin(Time.time * frequency) * amplitude;

```

I used sine, but it's quite different from movement of the boss. How can I change the behaviour in my game to be more like this boss's movement?

# Answer
I never played that game myself.

It looks like it has a state machine.
If the horizontal offset between player and boss is high enough, it moves in a horizontal + sinus movement.
If it is near the player, it moves up to evade the player, abandoning the sinus.
After it avoided the player, it keeps doing a slightly larger sinus above the player, and sometimes collides with the player.

I think the erratic moves are the state switches, going from horizontal + sin, to evade, to stationary + sin to horizontal + sin.
I don't see an attack pattern, it's more of an follow and don't touch movement.
I believe the difficulty from this boss stems from the fact that the player is mele, and still needs to do damage without accidentally hitting the ghost.

Thus to replicate the movement, you would need to replicate these four states and their respective movement pattern.
> 2 votes

# Answer
One tool I find very useful for creating movement patterns is the timeline asset. The advantage of using timelines for this is that you can describe the movement patterns using curves in a visual editor instead of describing them as mathematical functions or algorithms. This is usually far more intuitive and designer-friendly.

You can even do it in the Unity editor. When you want the boss to be in the upper left corner at second 2 and in the center of the screen at second 3, then you:

1. enable recording for that object in the timeline editor
2. move the timeline to second 2
3. move the object to the first position using the usual editor controls,
4. move the timeline to second 3,
5. move the object to the second position.

The timeline editor will now have generated curves for the x and y coordinate which smoothly interpolate between these positions. You can then tweak these movement curves by adding additional points in between or moving points around.

For example, my entry "Slacking At Work Simulator" for the Useless Simulation Game Jam two weeks ago on itch.io makes a lot of use of timelines. The most visible example is the movement of the antagonist. His x position, y position and rotation is controlled completely by one 5 minute long timeline.

However, timelines have one crucial disadvantage: They can not react to what happens in the game.

Going back to the boss monster from the youtube video in the question: It appears to me as if the y-position of the opponent follows a fixed pattern while the x-position reacts to the player position. So you could combine a timeline which controls transform.y with a script which controls transform.x by always moving towards the current position of the player.
> 0 votes

---
Tags: unity, c#, game-mechanics, transformation
---


title: App name containing spaces?

text:
# Question
Title: App name containing spaces?
My new app is ready to publish but I have big dilema: will space characters in title hurt my game in search engines (google, google play, itunes)? There are two teams in the game called 'MAD' and 'MED' teams. Until now I used 'MADorMED', because I wanted to create a new and unique title which was never used before. But I found google play search doesnt find the app if a user searches for 'mad or med'. Plus if I search google 'mad or med', it doest find my domain madormed.com either.

Is it better to use spaces? Will the engines find it better?

It is also a thing to consider some users will swap words and look for 'med or mad'.

I personally dont like the version with spaces, as it is not a unique name, and it is made of very common word. I afraid 'mad' and 'med' words are so common words my app will be lost among other popular titles.

But if its a logical move I will rename it and use spaces.

I'm very grateful for any advice.

Thanks, Mate

# Answer
> 1 votes
As TomTsagk points out in the comments to your question, the algorithms Google (and other engines) use aren't (usually) public. They're also likely to be highly subject to change without much in the way of warning. Generally speaking, the goal of a search algorithm is going to trend towards finding *actually relevant* information and away from allow exploitative SEO, however.

Consequently, I'd advocate for picking a name that represents your game the best in the general case for marketing and word-of-mouth. That would lead me to suggest keeping the spaces in the between the words, because they *are* words and because otherwise you're likely to get people thinking the game is "Madormed" because folks tend to be bad at paying attention to capitalization. While "Madormed" is certainly a unique name, it no longer has as much bearing on the actual game, so it's sort of six-of-one, half-dozen of the other, potentially.

You could also consider "Mad/Med" "Mad x Med" or "Mad vs Med" or similar: the idea there being to replace the very commonly-used "or" (which may get dropped from search query terms entirely or considered an operator). On the other hand, that may still require people to use quotes in search terms to capture the full phrase, so it's not entirely without cons.

---
Tags: appstore
---