text:
How are Roguelike/Bullet Hell mechanics stored in Unity?
I'm going to be creating a roguelike bullet hell game wherein the play will be a bullet hell game, but you will be traveling between "rooms" wherein the action takes place. The "rooms" will be randomly generated like in roguelikes such as The Binding of Isaac, but with bullet hell play similar to Touhou or Batsugun, with a possible twist. It will be similar to Enter the Gungeon, but there will be some differences.
I'd like to know how Unity will deal with storing possibly thousands of different "rooms" and generating these each time, along with the enemies and bullets these enemies will begin to shoot after you enter the room. Only one room will be visible at a time.
How would Unity deal with mapping possibly thousands of rooms, and will it be able to store this while generating bullet patterns? I know that in classic bullet hell arcade games, when there were many bullets on the screen, the game tended to slow down because of hardware limitations.

The trick behind these roguelike mechanics is that typically you don't store much at all.
The shape/contents of each room are determined by an algorithm that's generally seeded with the position of the room, and possibly a unique key for each "new game" session.
This algorithm, which can take many forms, is effectively a deterministic machine: put the same numbers in, and you'll get the same room out. (But put in different numbers, and you'll get different rooms!) So you don't need to store the contents of the room to be able to re-draw it if the player doubles back. Just put the same position in again and you'll automatically get the same room.
This is how early roguelike and procedural games managed to pack such immense explorable worlds onto the tiny floppy drives and limited RAM of early PCs.
If the player can make changes to the rooms, then you do need to store those changes to be able to reproduce them faithfully. This storage generally grows linearly with play time, and can be discarded when the player hits a permadeath point, so even if it's conceptually unbounded it can usually be kept quite modest.
You can tune how much you need to store by the design of your mechanics: if the room repopulates whenever the player leaves it without clearing it entirely, then you only need a single bit of storage per room: a "cleared" flag. Or if the player's changes are limited to discrete cases: killed enemy/bombed breakable wall, you can similarly keep it scoped to some worst-case number of bits per visited room. Or you could have the player's changes "age out" after they move more than 10 rooms or 30 minutes' game time away, allowing complex state tracking with a limited time horizon. Games like Minecraft, which allow much deeper player customization of visited chunks, correspondingly have much more intense storage needs.
As for how "Unity" deals with this: it handles it however you tell it to. It doesn't have a built-in roguelike bullet hell component you're forced to use. So you can script whatever custom system you find will meet your game design/player experience goals and performance needs on your target hardware. Generating the next room's contents, discarding old rooms, storing what you deem important along the way, all of that is your responsibility.
If you ask a narrower question with details of a specific mechanic or piece of your generation strategy you'd like some help with, we can provide tailored answers about that particular problem.

Thanks! I'm going to ask for a little bit more advice here- I do not wish to store much about each room, only ones that contain things that the player may want to interact with later, such as shops. As such, would it be simpler if I wrote in something that stated that the room has an object that you can interact with, and only record data for that room, storing it separately from the data about random generation of rooms, or should I store them together?

This decision will probably become clearer as you get deeper into your architecture & implementation. If a room can just happen to have a shop, you won't be able to store the state of that shop until it happens to get generated somewhere: it's runtime instance data, not part of the generator's pre-loaded knowledge. So you just note it down when it happens. But if only certain kinds of rooms can have certain kinds of shops, or a shop needs to occur no less than once in every 10 rooms, that kind of shop data needs to feed into your generation algorithm itself.

If your game is like Binding of Isaac where each room is full-screen, then it might be a good idea to actually only have one scene with one room. When the player moves to a different "room", you just modify that room accordingly by Destroying and Instantiateing the room-specific objects.
When you do want scrolling transitions between rooms, you could do a room transition by instantiating the new room from a prefab, set it up, pan the camera to the new room, and destroy the previous room.


text:
Is there a term for placeholder graphics for dialog systems?
I'm working on a game that has a lot of dialog. It has a dialog system similair to Phoenix Wright, where the characters appear onscreen when they talk, either in sprite form or as a 3d model. Usually there's mouth and eye animations as well, and their facial expressions change depending on the context of the scene.
Here's my problem: I suck at drawing. Like, massively. I enjoy writing dialog and I already have lots of dialog written down. I even made a little program for myself, which mimics how the dialog would play out in my game. Something that I don't enjoy doing, however, especially when I implement the dialog into my game, is have tags everywhere that describe the characters mood/expression instead of showing it visually. Example:
John: mostly neutral, slightly worried How was your day?
Jane: sad Not so great...
Even in the prototype stage, I would like something more... visual, to convey the scene better to everyone else and really get the right mood and expression of the character across. That way, it would be easier for the future artist to draw the necessary poses, expressions, animations, etc. for each character.
What I would like to do is have placeholders of blank (mostly featureless) characters that have lots of different expressions to convey what I want the character to look like in that situation. I'm not asking where to find something like that, I simply want to know if there is some sort of game developer jargon/term for this kind of thing (animated or still), so I can narrow down my search a little.

"Placeholder" is already the term usually used to describe assets hastily made  and used as stand-ins while artists still work on a more production-quality version of them.
Placeholders should intentionally be made as ugly as possible. When they are not ugly enough, you might get so used to looking at them that you become blind to their lack of quality and end up shipping them.
My recommendation for dialog portraits would be to create the placeholders with MS Paint. Use the mouse to draw a free-hand smiley face conveying each emotion. To represent different characters, either paint in a different color or write the character name below it. Do not spend more than one minute on each one.
A practice you sometimes see is that people use assets ripped from a different game as placeholders during development. I would recommend you to not do this, because it is easy to lose track of which assets are placeholders and which are your own. If you accidently end up shipping a placeholder (or even just publish a development screenshot with one), you are committing a copyright violation which might get you into a nasty lawsuit.

I generally use the term emoji.
The term conveys what it is, and since they're part of Unicode, maybe your infrastructure supports them out of the box.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
How can i draw a curve in modern Opengl?
OpenGl is capable of rendering points, lines, triangles and quads;  but what if i want to draw a bezier curve? I read online you should use something called GL_STRIP, but the solutions were using either legacy Opengl, or they were not explaining well the process. The question is: How can i render bezier curves in Modern Opengl? I'm using C++.

To my knowledge there's no built-in bezier curve primitive, so your options are either approximating it with a sequence of short straight line/strip segments, or drawing a bounding polygon with a custom shader to evaluate the curve function per pixel. Do you have a preference of the two?

@DMGregory i think that for the moment, the first approach is the most suitable and easiest of the two, so I'm gonna use that one..

First of all, the basics:
The bèzier equations are very simple. You basically take the line segment created by the points, get the lines between them, then you linearly interpolate a point between the starting and ending point of each line. This way you get one less point than before. You do the same with the lines defined by these, and so on until you get a single point. This will draw your bezier curve.
You can also just use specialized equations, like for instance for the 4 point version:
$$P = (1−t)^3P_1 + 3(1−t)^2tP_2 +3(1−t)t^2P_3 + t^3P_4$$
After this you just loop through between 0 and 1 in as many steps as precise you want the curve to be and plug the value into the interpolations or into the equation as t. This gives you 2d vectors. You can put those values into a buffer and render them using GL_LINES (make sure to use LINES, LINE doesn't work) and voilá, you have your bézier curve.
A bézier curve has the nice effect of getting denser around curves, so you won't have to make the precision much higher to get a smooth curve
After the happiness of rendering something smooth subsides, forget what I just said and never use built-in lines in production again. They don't work very well, when they're wider than a couple of pixels. Instead create a custom one using triangles, but that topic is far too complicated to cover here. You should be able to either figure out or find a tutorial about it.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Objects desync position when speed is not multiple of 10
While finishing up game loop and rendering integration, i made some blocks move back and forth in the x axis to test things out. Their initial positions are as follows:

The first block starts at 0,0(Top-left) and subsequent ones add 40 to both x and y.
Move code
s16 speed = 10;

if(block->sprite->position.x >= viewportWidth - block->sprite->width)
{
    block->sprite->position.x = viewportWidth - block->sprite->width;
    block->dir = -1;
}
else if(block->sprite->position.x <= 0)
{
    block->sprite->position.x = 0;
    block->dir = 1;
}

block->sprite->position.x += speed * block->dir;

However, if i change the speed to a number not multiple of 10(or using deltaTime to influence the speed), the blocks will de-sync when changin directions, as shown bellow:
Result of using roundf(1000 * deltaTime) as speed

Result of using 13 speed and removing the clamping of position

I thought it was related to me using ints instead of floats for positions, tried to change but no luck. Looking at the game loop update, no block is being left out of any update phase either.
What bit of math an i missing? What causes this?
Thanks.

Your value of movespeed=10 is a special case where each block collides with the wall at the same distance into the wall.
In order to keep your spacing the same, the boxes must each travel a distance of movespeed every frame.
Think of a 1D problem with a single point on a line that goes from 0 to 100. Using your algorithm lets start at P1 = 97 and go through the steps.
P1 = 97 + 10 = 107
Next frame
P1 = 100 - 10 = 90
Since the point was brought back to 100, then you subtract 10, the point traveled 17 in one frame, which makes it desync from other boxes that align more accurately with the wall.
In order to fix the problem, you need to make sure the point always travels the same distance i.e.
If P1 = 97 and you add 10,
then P1 = 100 + (100-(97+10)) = 93
Meaning that P1 traveled a distance of 3 towards the wall and then 7 away from the wall for a total of 10.
A way to implements this would be to change the previous lines to the following...
block->sprite->position.x = 2*(viewportWidth - block->sprite->width) - (block->sprite->position.x+movespeed);

and
block->sprite->position.x = -(block->sprite->position.x-movespeed);

and include the normal movement code in an else bracket
else
{
    block->sprite->position.x += speed * block->dir;
}


text:
Different gameplay throughout game?
I want to create a top-down rpg kind of game. It doesn't have the turn-based battles, for the most part, as it's more of a puzzle type game with an overarching mystery to solve, with not much action. However, I've been playing with the idea of adding different kinds of gameplay from other genres that mixes well with this top-down perspective, such as Zelda-style melee combat, fast "kill 'em all" shoot 'em up action like Hotline Miami, and stealth like the Metal Gear series.
Lets say I have ten chapters of around two hour length each. The distribution of each gameplay element would, for example, go something like this:

Chapter 1: regular top-down
Chapter 2: regular top-down (small stealth segments)
Chapter 3: Zelda
Chapter 4: regular top-down (small rpg turn based fight)
Chapter 5: Metal Gear
Chapter 6: Hotline Miami (small stealth segments)
Chapter 7: regular top-down
Chapter 8: Zelda
Chapter 9: Hotline Miami
Chapter 10: mix of Zelda, Hotline Miami, Metal Gear and turn based rpg fight

These gameplay styles fit with the narrative, which would've previously only been cutscenes. The Zelda parts for example are flashbacks to medieval times, where it shows how the evil bad guy was born and how the first few attempts at destroying him went for an order of knights (spoilers: not too well, but they did manage to slay many of the bad guy's monster army and weaken him a bit).
Now, regardless of whether or not you think I could pull something like this off (I have my doubts as well, but that's not the point of the question), could this be a bad idea? Variety is the spice of life after all, but I feel that maybe the player could be overwhelmed or annoyed having to learn different mechanics from different genres. Could it be disruptive to the gaming experience if you suddenly play a different kind of game? Or does it not matter as long as it's integrated well with the rest of the gameplay and story?

This question looks very opinion-based to me in its current formulation. "Could it be disruptive to the gaming experience?" Well, sure, every mechanic could be disruptive to the gaming experience if you do it badly. Whether your design and implementation is able to pull this off successfully is something we can't evaluate with the limited description here. If this is a direction you believe in, own it, try it, prototype and evaluate it to see if it can meet your goals (and budget). Is there something you need from us internet strangers before you can start this investigation?

@DMGregory I was hoping I could get some pros and cons of altering gameplay like that, maybe with some good and bad examples of past games, if there are any. Usually in a game like mine, different gameplay is reserved for small throwaway sidequests (fishing for example), but in my game, it's gameplay that persists for chapters.

Nier: automata comes instantly to mind when reading the title.

The interplay between the game designer and the player is very important. By introducing a piece of gameplay to the player, you're making a promise to the player. In particular, that by investing time in mastering this gameplay, their time will be rewarded. They will be better able to play through the later stages of the game.
By radically shifting gameplay styles for relatively long periods of time, you are reneging on that promise. Whatever time investment they had in your Chapters 1 & 2 is lost for the entire next chapter.
This is different from the case of a game like Mario Party, where there is an up-front expectation that the game is composed of mini-games. This is also different from things like stealth sections of games or mini-games within a game. Those are used simply to break up the monotony; 90+% of your gameplay is still in the style you were using before.
In your case, you have given the player consistent gameplay for a reasonably long period of time, and then you take that away from them. Without up-front notice, I would consider that perfidy.
What you need to do is choose a general gameplay style that can fit into all of your time periods. Different periods would have different weapons, which influences your play styles. But the core root gameplay should still be the same.
For example, consider a top-down perspective, where you move the character with the arrow keys and attack by clicking with the mouse in a particular direction.
Such a system is amenable to multiple styles of combat. Melee-style sections means getting close to targets. Shooter-style sections can involve cover, since you have some control over your locations. You can even do stealth-shooter sections.
But they're all using the same perspective and same core gameplay. Lessons learned in one style map to others. Melee teaches you to avoid getting surrounded, which is also an important skill in shooter sections. Stealth sections teach you how to use terrain, which can be important for shooter sections where you may need cover. And so forth.
While the dynamics of any particular chapter can and should have their own unique flavor, the totality of your game still needs to have reasonably consistent gameplay.

This isn't to say that it can't work. There's one game I'm remembering (but blanking on the name of) that explicitly did what the asker is talking about and it works for that game because it was intended to be a "through the history of video games." The art style and mechanics would change as the game took place in different eras of video game history.  But yes, in general, DO NOT DO THIS THING unless you know exactly what you're doing.

@Draco18s Was it this one? http://store.steampowered.com/app/233470/Evoland/

@noClue That's the one.


text:
LibGDX and Typing Label
I am attempting to have animated dialog text for my libGDX game. I found a useful resource on github called Typing Label and i am having some troubled getting it working. Could someone help me with this. Also in the examples it says stage.add and i dont have a stage object declared. what type of object should that be.
 TypingLabel label = new TypingLabel("Hello world!", skin);

Your stage  object should be of type 'Stage'.
https://github.com/libgdx/libgdx/wiki/Scene2d

To use any type of Actor (TypingLabel is an Actor) you need a Stage object like the examples say. You also need to draw and update this stage object every game tick so that the Actors can animate and render properly.
// Instance variable
private Stage stage;

@Override
public void create() {
    stage = new Stage(); // Note: There are multiple constructors available
    stage.add(new TypingLabel("Hello world!", skin));

    Gdx.input.setInputProcessor(stage); // Only needed if you have input such as buttons
}

@Override
public void render(float delta) {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Clear screen so we don't get artifacts.

    stage.act(); // Update all actors
    stage.draw(); // Draw all actors
}

The official libgdx wiki has more information about how to use Stage, Actors, and other parts of Scene2D.


text:
Queueing with Unity's NavMeshAgent
I have created a strategy game where the units use Unity's NavAgent pathfinding and flocking algorithms.  This works well.  However, I need to add queueing so that units will queue sensibly.  This works most of the time, but it isn't perfect and I want to know if there's a better way of doing it.
My first draft was to simply check which unit is closest to the destination, but this caused issues because a group might be navigating around an obstacle and the unit closest is at the back of the queue... so the whole group stops.
Second draft checked the distance to destination based upon the length of the path each unit had to take.  This works far more often, but sometimes still has issues.  Sometimes the same problem happens, but much less often.  The one who is supposed to be moving stops, and so the entire group stops.
There's also a problem I've noticed, where the waiting units could sometimes benefit from rotating, even if they shouldn't be moving.  Unfortunately they sometimes get stuck and will wait before they can move, to rotate.  If they could rotate when forbidden from moving it'd help considerably too.
What I need to know...

How can I make Unity NavAgent's queue, so that they will wait for the other agents closest to the destination to move first?
How can I ensure that this does not stop agents from rotating while in a queue (rotating may move them into a better position in the queue).

Code:
Unit Movement Function
private void Movement()
{
    // Unit is moving.
    if (moveVectors.Count > 0)
    {
        navAgent.isStopped = false;

        // Check for whether to wait in queue.
        Vector3 nextVector = transform.position;
                nextVector += transform.forward * speed * Time.deltaTime;

        foreach (Unit unit in list)
        {
            if (unit != this &&
                unit.moveVectors.Count > 0 &&
                Vector3.Distance(unit.transform.position, nextVector) <= (unit.footprint + footprint) &&
                PathDistance(unit) < PathDistance(this))
            {
                navAgent.isStopped = true;
                return;
            }
        }
    }
}

There's a bit more to Movement, but it's not relevant so we'll ignore it for now.
PathDistance Function
private float PathDistance(Unit unit)
{
    Vector3 startPosition = unit.transform.position;
    Vector3 endPosition = unit.moveVector;
    Vector3 lastPosition = startPosition;
    Vector3[] path = unit.navAgent.path.corners;
    float distance = 0;

    for (int i = 0; i < path.Length; i++)
    {
        distance += Vector3.Distance(lastPosition, path[i]);
        lastPosition = path[i];
    }

    distance += Vector3.Distance(lastPosition, endPosition);
    return distance;
}

Is there a better way of achieving the result I want?

You could use Collaborative Diffusion, or adjust yours in some way to integrate CD with your current solution - mutual obstruction between entities is resolved automatically, doesn't suffer from the same blocking problems as traditional pathfinding e.g. A*, as the entities are just doing hill-climbing and only looking one tile ahead to do so. As I know little about Unity's built-in pathfinding solutions, I can't advise on exact integration method. If this helps, let me know, and I will turn it into an answer for bounty.

@ArcaneEngineer Unity's navigation system handles pathfinding and flocking.  But it doesn't manage queueing, or at least I haven't found the functionality to do this.  Maybe something like that could help?

Second draft checked the distance to destination based upon the length of the path each unit had to take. This works far more often, but sometimes still has issues. You don't say what issues. This is important, because this approach is the only sane way to begin tackling the problem. Do they still get stuck? That is probably because the shortest path is taking into account other units that are moving. You have to get the shortest path as if the map were otherwise empty. You can then prioritise who gets to move first in order of decreasing shortest-path proximity, i.e. closest first.

Also, if you are able to make your code run in interactive mode, that is, every time you press e.g. spacebar, someone moves, then the simulation waits to move the next entity. This way if you aren't already doing so, you can see / think through exactly what is happening with the logic (even more so if you hook up to VS debugger). You also want to ideally be able to see the map (possibly per entity) showing pathing values.

@ArcaneEngineer Thanks for the questions.  Yes, I've edited to clarify that - it stops and everything stops.  That may be the problem!  Those are also very good points about debugging, thank you.

Let me know what happens, soon as possible. I'm going to post an answer in the next day or so because your bounty will otherwise be lost (you won't get it back, and nobody else will receive it). I don't want to do that unless there is some certainty that I've helped you solve your problem. Good luck and keep me posted.

@ArcaneEngineer Think I've fixed issue #1.  This value used instead of my custom calculation seems to work.  I still notice the agents are not turning if they're queueing, but this happens much less now.

How did it go in the end? Reminder that if you don't accept my answer, the bounty will go to waste as I would need 2 upvotes for it to be auto-assigned to me. No pressure tho' ;) it's totally your call.

@ArcaneEngineer I went on holiday shortly after my last message. Issue is not completely resolved, just works better. Still need a unity specific solution so I have the logic for allowing agents to turn if they need to while they queue, otherwise you get staggered movement which is odd. Also while the aforementioned library's value works much better than my raw calculation, it still isn't perfect.

Nearest-first movement priority

Second draft checked the distance to destination based upon the length
  of the path each unit had to take. This works far more often, but
  sometimes still has issues.

You don't say which issues, but I think we can assumed "ending up blocked". This is important, because this approach you mention is the only sane way to begin tackling the problem. Blocking probably happens because the shortest path is taking into account other units that are moving. You have to get the shortest path as if the map were otherwise empty. You can then prioritise who gets to move first in order of decreasing shortest-path proximity, i.e. closest first.
Inspiration for this idea is road traffic. Especially at stop streets, people don't constantly stop/start to wait for one another. They know when they have right of way, and they go confidently, otherwise they know they'll hold up traffic in the long run. I think the same applies in your case. If you get the shortest path in an otherwise clear map, you should not have this problem as no-one is trying to avoid anyone else, they are just moving to the goal - but in this case, they must do so in order of nearest to furthest proximity to the goal. We do the same when traffic merges into a single lane - we tend to let the guys who are already in front, go first. This assures a smooth flow, no accidents.
EDIT: At worst, a hybrid approach will be required where, perhaps if a unit does get locked up by the usual method, you occasionally attempt a straight move, or even a random movement to an available neighbouring cell, in order to let things settle into a nice queue - a bit like shaking up a tin to compact it and let the small stones go to the bottom. Knowing whether an agent is "locked up" is a matter of identifying patterns in its most recent moves.
General dev tips
If you're able to make your code run in interactive mode, that is, rather than the simulation running on freely, instead you press e.g. spacebar, then another entity moves, and the simulation waits for another press to move the next entity, so you are manually stepping through what would ordinarily be each frame of processing. If you aren't already doing so, you can then see / think through exactly what is happening with the logic (even more so if you hook up to VS debugger, which will allow you to step through the logic one instruction at a time, although Unity native assembly code may be inaccessible).
You also want to ideally be able to see the map (possibly per entity) showing A* pathing values..


text:
It lags when it collides. Help? :(
I am trying (and believing) to make a game of pong. I have got a slightly decent working game. I haven't implemented the scoreboard or AI yet because I want the physics to work first. I am trying to reverse the direction of the ball when it hits either paddle just to make it work cleanly and am having the issue where it changes direction twice, it bounces off the paddle as expected and then goes in the opposite direction to when it hit the paddle -.- If anyone could help me, it would be much appreciated.
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class BallController : MonoBehaviour {

        private float randomNumber;
        private float range;
        private float pointOfContact;
        private float paddleTop;
        private float paddleBottom;
        private float[] limits;
        private int speed;
        private int caseNumber;
        private Vector2 direction;
        private Rigidbody2D ballRigidbody;

        void Start () {
            //Getcomponent finds the rigidbody of the attached object.
            ballRigidbody = GetComponent<Rigidbody2D> ();

            speed = 5;
            caseNumber = Random.Range (0, 2);
            range = PickARange (caseNumber);
            ballDirection (speed, range);
        }

        void FixedUpdate() {

        }

        void OnCollisionEnter2D (Collision2D coll) {
            if (coll.gameObject.tag == "Player" || coll.gameObject.tag == "Computer") {
    //          pointOfContact = ballRigidbody.position.y;
    //          print (pointOfContact);

                ballRigidbody.velocity = new Vector2 (ballRigidbody.velocity.x, ballRigidbody.velocity.y * -1);
            }
        }

        void ballDirection (int ballSpeed, float yDirection) {
            randomNumber = (Random.Range (0, 100));

            if (randomNumber < 49) {
                direction = new Vector2(Random.Range (-1.0f, -0.5f), yDirection);
                ballRigidbody.velocity = (direction * ballSpeed);
            } else {
                direction = new Vector2(Random.Range (0.5f, 1.0f), yDirection);
                ballRigidbody.velocity = (direction * ballSpeed);
            }
        }

        float PickARange (int number) {
            switch (number) {
            case(0):
                range = Random.Range (0.5f, 1.0f);
                return range;
            case(1):
                range = Random.Range (-1.0f, -0.5f);
                return range;
            default:
                range = 1.0f;
                return range;
            }
        }
    }

I thought to multiply the whole velocity by -1 but that just caused a loop because of the lag. Even though that's the right way to reverse the direction. I think.
Thanks Peeps!

Normally the collision itself will deflect the velocity, so you might be double-reflecting here, countering the physics engine's own bounce. What do you get without this collision handler?

That does make a lot of sense. I thought however, that this collision handler would override any original collisions. I do get a normal collision without it. I can also increase the speed of the ball after the collision without the lag. If I changed the angle I might still get the lag however, any suggestions on how to fix it? Thanks very much for the help by the way!! Also, is there a way to follow your own posts and get notifications of replies? I stopped coding last night because I was trying all day to make the game and thought I'd get an email if anyone replied.

Please don't edit a question that already has answers to change it into a different question. Asking new questions is free, so just post a new one when you want to learn something new. You can link to your previous question for context.

OnCollisionEnter(Collision collision) handlers run after the physics engine has resolved the collision by displacing the objects and updating their velocities.
That means that at this moment, the ball has already bounced off the wall/paddle, and reversing its velocity will tend to send it back into collision which can cause it to linger in contact and look like it's lagging/stalled. The game's still running at normal speed, but the ball is changing direction too frequently to make progress until, by some luck, it eventually lands outside of collision and can continue on its way.
If you want to control your velocity after a bounce, the Collision argument contains information about the impact that you can use.
Specifically, if the collider you hit was not itself moving, then:
var preCollisionVelocity = -1f * collision.relativeVelocity;

will give you your incoming velocity, before the collision resolver ran. You can safely use that as the source to reflect from.
Just note that an object might experience several collisions in a single physics step, so you'll want to watch out for literal corner cases where you've reflected off two or more surfaces in rapid succession.

Thanks for clearing up a lot for me. The first two paragraphs helped a bunch. I was just wondering whether you could help me with understanding Dynamic and Kinematic, I've looked on the APIs but am still struggling. I am also still struggling after using the above to correct the issue and wondered whether it was linked in any way to the Body Type property? Thanks again!

That sounds like a new question to me. :)

I'm so sorry haha. I have been working on it for hours, trying different things to make it work as I want it to and that's the only thing I can think of that links to the physics that's causing the problem. I've looked all over google for people with a similar situation to me, asking others and you're the only one who responded. You're my god xD

That's not true, prithul also offered suggestions. In any case, if you have a question about kinematic & dynamic bodies, post it as a new question and you can get answers to that. We don't do follow-up questions in the comments here, as it makes for a more convoluted & hard-to-follow thread. The one question --> one accepted answer format makes it much quicker to find solutions to problems.

Yeh, true, sorry. That's my bad for rushing to get to a solution, just have so little time with work as well. I apologise. I will definitely post a separate question. Thanks for the help however.

Have you checked whether OnCollisionEnter2D is invoked multiple times when a collision happens? If that is the case, it might be that Unity is detecting several points on the ball to have collided with the paddle. In that case, you can cause the ball to be immune to direction-change for a short amount of time.
Or it could be that you are negating the ball's direction after it has already changed its direction on collision.

I think that it's the second one because without it, it still collides as expected. Is there something you can suggest to fix this? Sorry, I'm new to coding in general and tried so hard yesterday haha. Thanks for the help by the way!


text:
Dynamic vs Kinematic, do either of these cause a collision before OnCollisionEnter2D?
Firstly, it would be a great deal of help if someone could explain to me the differences between Dynamic, Kinematic and Static (especially if there is a box for static by the name of the object. I've looked at the APIs and tried playing around with them, they are so confusing. :/
Secondly, I understand that the physics engine evaluates first and can cause a collision (when the ball hits the paddle in my Pong game) but is there a way around this? I'm trying to send the ball in the opposite direction to which it hit the paddle by using OnCollisionEnter2D but this method gets called second and therefore the ball changes direction twice and the physics engine causes an unnecessary collision...
I have looked to tutorials on the movement in pong and tried following the tutorials but get the same problem (even though their game is faultless), this leads me to think that it's the Body Type property that is causing the physics engine to produce the extra collision because theirs is an older unity version. It could possibly be the bouncy material with no friction also, I don't know much purely because I'm a newbie to unity. I wonder whether anyone has had the same problem as me and can set me free.
Thanks in advance. I seriously appreciate any help I can get! :)

is there a way around this? Not likely. As for your first question: static means it never changes (no movement), kinematic means the object is moved via code, not the physics engine, the last means it's wholly under control of the physics engine.

Static bodies have no Rigidbody component attached to them, so the physics engine does not consider them to be moving. (Avoid moving these frequently or you'll violate that expectation)
Use static colliders for level geometry like the ground and immovable walls, or stationary trigger volumes.
Static colliders on their own won't set off trigger/collision messages like OnCollisionEnter, unless there's a Rigidbody on the other participant.
Dynamic bodies have a Rigidbody component attached to them and their isKinematic flag set to false. These objects move at the whims of physics according to their velocities/angular velocities and the forces/torques and collision impacts exerted on them. The physics engine takes responsibility for resolving their collisions with static, kinematic, and other dynamic objects and rebounding them as needed.
Use these for basic physics objects you want to be able to stack & topple and have them behave plausibly with minimal intervention, or for objects that you want to steer in a physics-focused way, like a rocketship.
Kinematic bodies have a Rigidbody component with the isKinematic flag set to true. This tells the physics engine "this object moves, but I'll handle that part" — the kinematic object will process collisions with other rigidbodies, but only dynamic objects will automatically react by bouncing away, and cause OnCollisionEnter messages to be sent.
The kinematic object itself won't move except how you tell it to with MovePosition()/MoveRotation() — its velocity won't automatically integrate each timestep.
Use this for objects that you want to control in ways that don't behave like simple physics bodies — like a bipedal character controller or highly custom vehicle controls. Use physics queries like overlap checks and shape casts to scan for collisions preemptively, since they won't stop your object automatically.

You can refer to the Collision Action Matrix at the bottom of this documentation page for a quick reference of what types of collision are checked for each type of body.
For your case though, I think a simple dynamic Rigidbody is all you need. Just set its collider's isTrigger flag to true. Trigger colliders detect collisions, but do not generate collision resolution responses. That way the velocity of the object stays under your control.
Instead of OnCollisionEnter2D(Collision2D collision), you'll listen for collisions with OnTriggerEnter2D(Collider2D other)

Dude, thanks to you and everyone else, I have nearly finished the game :) Thanks very much for your help! It's looking juicy now xD It all makes much more sense I think.

Most Clear explanation seen so far.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
"lazy follow" - term?
For one of my games, I need an enemy that pursues the player in a sort of "lazy" way, where they don't exactly follow the player's movement and instead have somewhat slippery movement. Example: the player does a sharp turn to the right, the enemy will go to that direction too, but it will slightly "overshoot" the distance and go beyond the point where the player turned to the right before going to the new direction. Here is an example:

Some examples from games:

Missiles (Super Meat Boy)
Phanto (Super Mario Bros. 2, the USA one)

Is there a term for this kind of "lazy" movement for homing enemies?

I'd just say your enemy entity has momentum.
Usually this means the steering function can only affect the acceleration but not the velocity, so it cannot stop on a dime.


text:
Special moves using mouse movement?
Recently, I accidently broke my PC controller and I was forced to play Skullgirls using the keyboard. Needless to say, it sucked. Fighting games are the kind of games where a controller is (almost objectively) better to use than a keyboard, just like how keyboard + mouse is better to use for FPS games than a controller. Keyboards just don't allow the same freedom a controller offers for fighting games, especially because of the analog stick.
So while I was getting my *** kicked and (of course) blaming only my keyboard instead of myself, I had an idea: why don't fighting games use the mouse, too? Couldn't the mouse movements be used as the directional input for the special moves instead of the arrow keys? Examples:

Hadouken - quick flick with the mouse into the direction you're facing
Shoryuken - a steep upward curve towards the direction you're facing
Roundhouse kick - a quick circle motion

What are the advantages and limitations using the mouse in such a way? Are there any examples out there? Maybe there are some limitations I'm not seeing right now? To me, this looks like a way to give players the same freedom in fighting games with keyboard + mouse as a controller would provide, so I'm surprised I don't see more fighting games with that control option.

Speculating on reasons why this might not be a widespread control scheme is not this site's strength. Have you tried prototyping your idea to see how it feels to play? Have you run into any trouble with the design or implementation that we might be able to help with?

what do you refer to as a controller? xbox/ps or a arcade stick? because keyboard is definitely not objectively worse than a xbox/ps controller. wasd allows for way quicker movement inputs... hell, the mixbox exists for a reason.

Might be possible to rephrase this into a better fit for the site as "What are the advantages / limitations of mouse as input mechanism over gamepad?"

@MrCranky Reworded it a bit, although I don't think it will do much.

When you use the controller's analog stick, you use your fingers. Your fingers are very fast and they don't have to move that much. Combine that with the fact, that there's a  maximum angle the joysticks can bend, which allows for fast stops and you get something with a high precision, speed and the ability to change direction very fast.
Since you use your wrists or arms when you move a mouse, you can't get the same combination.
Most fighting games also use the left joystick and the right (non-directional) buttons. Most PC users on the other hand use their right hand for 2D movement (mouse) and their left for buttons (WASD). Ask any professional fighting game player about what getting the second player feels like (most arcade machines put the joystick and the buttons on different sides for the second player and it's disorienting).


text:
Use heightmaps or direct vertex manipulation for runtime terrain editing in UE4?
I am creating a terrain editor and creator for in our game, in which we should be able to create hills and dales, create different shapes(forms) in the terrain etc. I came up with 2 approaches on achieving what we want,
1. modify 2d heightmaps by darkening / lightening colours; update terrain vertices based thereon.
2.  Create a plane and modify the vertices of the plane to shape what we want.
So my question is, which way would be faster/better for a ingame terrain editor? And why would you recommend that?
Or, if you know of a better way, I would love to hear.
Thanks

This sounds like a situation where you could quickly prototype both options and profile them to see whether one is faster, or discover in the process of implementation whether one is neater/more scalable & maintainable.

(1) Provides an intermediate data structure.
(2) Is exactly the same as (1) but it provides no such structure.
Do you need an intermediate tonal heightmap? If you don't, then don't use one. Individual vertex typically offers finer control over terrain, which from an aesthetic perspective is preferable. You can also have the heightmap represent the heights of vertices and not tiles, which you may mean in (1).
For example, a game where the player must be able to stand on a flat tile at every point (think Minecraft) is better off using a heightmap, since otherwise you will have non-flat tiles if you edit vertices individually.

Thanks for your reply, I think i will just start developing the second option, and if i don't like it, I will just convert it over.
with option 1. i meant to have each vertex in the picture, but i think i might be better off just saving the z values in an array(which is probably faster then reading a texture anyway), thanks


text:
pygame KEYUP KEYDOWN events only once per frame?
I've been playing around with pygame, and I ran into a bit of an odd issue with input on the pygame event queue. Consider the following test code:
import pygame as pg

def main():
    pg.init()
    pg.display.set_mode([640,480])
    clock = pg.time.Clock()
    while True:
        clock.tick(1)
        events = pg.event.get()
        print("There are %d events in the queue." % len(events))
        for event in events:
            print(event)
        print()

if __name__ == "__main__":
    main()

Here I'm intentionally running the game loop just once per second. What I observe is that the pygame event queue can easily receive dozens of mouse-related events per frame, but only ever a single KEYDOWN or KEYUP event at a time.
This is the output after pressing four keys simultaneously and quickly pressing the left mouse button a few times at the same time:
There are 0 events in the queue.

There are 1 events in the queue.
<Event(5-MouseButtonDown {'pos': (494, 392), 'button': 1})>

There are 8 events in the queue.
<Event(2-KeyDown {'unicode': 'f', 'key': 102, 'mod': 0, 'scancode': 41})>
<Event(6-MouseButtonUp {'pos': (494, 392), 'button': 1})>
<Event(5-MouseButtonDown {'pos': (494, 392), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (494, 392), 'button': 1})>
<Event(5-MouseButtonDown {'pos': (494, 392), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (494, 392), 'button': 1})>
<Event(5-MouseButtonDown {'pos': (494, 392), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (494, 392), 'button': 1})>

There are 3 events in the queue.
<Event(2-KeyDown {'unicode': 'q', 'key': 113, 'mod': 0, 'scancode': 24})>
<Event(5-MouseButtonDown {'pos': (494, 392), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (494, 392), 'button': 1})>

There are 1 events in the queue.
<Event(2-KeyDown {'unicode': 'e', 'key': 101, 'mod': 0, 'scancode': 26})>

There are 1 events in the queue.
<Event(2-KeyDown {'unicode': 'w', 'key': 119, 'mod': 0, 'scancode': 25})>

There are 1 events in the queue.
<Event(3-KeyUp {'key': 119, 'mod': 0, 'scancode': 25})>

There are 1 events in the queue.
<Event(3-KeyUp {'key': 113, 'mod': 0, 'scancode': 24})>

There are 1 events in the queue.
<Event(3-KeyUp {'key': 101, 'mod': 0, 'scancode': 26})>

There are 1 events in the queue.
<Event(3-KeyUp {'key': 102, 'mod': 0, 'scancode': 41})>

There are 0 events in the queue.

At 1 FPS, it takes pygame 8 seconds to process just 4 keypresses, one for each KEYUP and KEYDOWN signal. Is this intended behavior? Am I missing something here? It seems odd to me that pygame cannot register multiple keypresses per frame. I'm a bit of a newbie when it comes to gamedev, so I'm not sure where this is coming from.

I can't reproduce this behavior. The events appear in the next frame for me. What OS, Python and pygame version do you use?

@skrx I'm working on Linux (Fedora 27, kernel 4.15.6) using python 3.6.4 with pygame 1.9.3. I just tested it on a Windows 7 installation a while ago on another PC and there it was indeed working fine (I should have probably done that sooner, my bad). Anyway, that gives me a starting point to test this on a few different setups and hopefully track down the source of the problem. Thanks for taking the time to test it.

Better post this to the mailing list to contact the developers.

Please use the function pygame.key.set_repeat(delay, interval) once before starting the infinite while loop.
I use as delay 1 and an interval of 25.
From the docs: pygame.key module

The delay is the number of milliseconds before the first repeated pygame.KEYDOWN will be sent.
  After that another pygame.KEYDOWN will be sent every interval milliseconds.
  When pygame is initialized the key repeat is disabled.

This is the equivalent of for example a key pressed event in Game Maker


text:
Why is overlapping a possibility?
I have three dynamic Rigidbody2D's, two of them paddles and the other a ball - this ball is also a trigger. If I used OnCollisionEnter before, I understand that the physics engine calculates the collision that should happen based on the position and velocity of the ball and paddle. This created the so called lag problem I had where seemingly two collision results happened. However, now I am using OnTriggerEnter and have a couple questions related to the problem I'm having.
When the ball is level with the paddle on the x-axis and you move up to hit it, the paddle is able to go through the ball but the collision happens from where the ball hit the paddle originally. Why is this? Also, if I print the x position of the ball, the position should be 7.175 but instead it's 7.19996, is there a way to get the actual point of collision? Is this linked to the first question?
Thanks!

It sounds like you might be asking about continuous collision detection.
When this is enabled, the physics engine considers the full swept movement of the object over the duration of the physics time step. If there is a collision, we can pinpoint the precise moment of contact and respond accordingly.
The trouble is, this is a very expensive way to detect collisions. So the default behaviour for most game physics is a simpler method: move every object through its full displacement for the physics time step, then check if any are overlapped. If they are (and aren't triggers - triggers detect collisions but don't resolve them), try to nudge them so they're no longer overlapped.
If you need full continuous collision precision for a small number of objects in your scene, you can enable it in their Rigidbody2D's collision detection mode property. Or you can "scan ahead" of the object with raycasts/circle casts to find pending collisions and handle the bouncing yourself.


text:
Why does component.GetComponent<Rigidbody>() return "null", when a rigid body is NOT attached?
In the following code, when T is Rigidbody, calling componentToLookIn.GetComponent<T>() returns "null" when there is no rigidbody attached, instead of simply null:
public static class ComponentExtensions
{
    public static bool TryFindComponent<T>(this Component componentToLookIn, out T componentToLookFor)
    {
        componentToLookFor = componentToLookIn.GetComponent<T>();
        return componentToLookFor != null;
    }
}

Here is the debug window:

As a result, componentToLookFor != null ends up being true, which is obviously not what I want.
When I invoke componentToLookIn.GetComponent<T>() where T is NOT Rigidbody, null is returned as expected when there is no component of type T found.
What is so special about components of the Rigidbody type that GetComponent<Rigidbody>() behaves differently?
EDIT:
For contrast, here is the debug window when GetComponent<BoxCollider>() is invoked on a game object that does not have any component of the type BoxCollider:

As you can see, the value of childComponent is simply null, not "null". componentToLookFor != null therefore returns false.

If it is a string it would say so in the type, no? Are you sure you aren't calling this method more often and are looking at the wrong call?

Possible duplicate of How to make an Assert.IsNull test pass when the value is reported as ?

@Sidar I am 100% certain that I am looking at the correct call. I have updated my question to include more details.

Every time you try to GetComponent<T>() on a game object that doesn't have that T component, Unity return that pseudo-null indicated by "null", as suggested by Tyyppi_77. Can you post the code that calls the extension method in the case of the rigidbody and the boxcollider?

Did the object never have this component attached, or was it attached then destroyed?

@DMGregory AFAIK it doesn't matter if the component isn't attached, or if it was and it's destroyed, in both cases the base value becomes "null" (ofc in the first case is  "null" as soon as GetComponent is executed) before the next Update() is called (I just tested it quickly to be sure).

@DMGregory It was never attached.

This happens only when running in the Unity editor, and only with certain built-in component types.
In a release build, GetComponent<T>() always returns null if the GameObject does not have a component of type T attached.
When running inside the Unity Editor, GetComponent<Rigidbody>() instead returns a Rigidbody component that's been marked as a "stub" - an empty reference that perhaps the developer forgot to wire-up in the inspector. (It's not the string "null", that's just how it's configured to print when represented as text)
For these, Unity's overridden == operator for types deriving from UnityEngine.Object will return true when comparing to null (similar to what happens if you hold onto a reference to a component after it/its GameObject has been destroyed).
But the fact that it's not really null lets Unity offer more descriptive error messages, like...

"Unassigned Reference Exception" (Inspector field not populated)
"Missing Component Exception" (GetComponent<> with no matching component attached)
"Missing Reference Exception" (Component has been destroyed)

So, if Unity's == is overridden to compare as equal to null in this case, why doesn't your null check work?
Because your generic method doesn't know that T is a Component, so it doesn't know to apply Unity's overridden operator.
To solve this and get consistent null detection between Editor and builds, you can add a where T : Component type constraint to your method, or cast your reference to a Unity type like a component first, then do your comparison with that.

Thank you for your very informative answer! I suppose another alternative is to change my return statement to return !childComponent.Equals(null);?


text:
Script executes fine but randomly crashes with NullRefferenceExpectation
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Zombie_Spawn : MonoBehaviour
{
    public float timer = 0.0f;
    public bool m_spawn = false;
    public GameObject m_Zombie;
    Vector2 pos;

    void Update()
    {
        if (m_spawn == true)
        {
            timer += Time.deltaTime;
            if (timer > 2.0f)
            {
                pos = Camera.current.ViewportToWorldPoint(new Vector2(1f, 0.135f)); //this executes fine but will Null out randomly
                Instantiate(m_Zombie, pos, Quaternion.identity);
                timer = 0;
            }
        }
        else
        {
            timer = 0f;
        }
    }
}

And the exception (not expectation) says what?

It's clearly written in the documentation:

Use this function (Camera.current) only when implementing one of the
  following events: MonoBehaviour.OnRenderImage,
  MonoBehaviour.OnPreRender, MonoBehaviour.OnPostRender.

Outside of those three callbacks, you need to use Camera.main


text:
Input.GetAxis() always returns 0
Here is a screenshot of the Input Manager for my project:

The 9th and 10th axis refer to Axis1D.PrimaryIndexTrigger (Squeeze) and Axis1D.SecondaryIndexTrigger (Squeeze) respectively, as documented on this page.
However, Input.GetAxis(trigger) always returns 0, even when

the trigger name is correct, and
I am squeezing the corresponding trigger really hard.

While running the debugger, I used my right Oculus controller to interact with objects in my scene. Here is the debug window:

Even though I was squeezing the corresponding trigger on my right Oculus controller, Input.GetAxis(trigger) still returned 0, thus causing my method to return early.
Here are the fields and properties of my Hand class, in which I am invoking the Input.GetAxis(trigger) method:
public enum XRHandControllerNode
{
    Left,
    Right
}

private XRNode trackedXRNode =>
    this.TrackedXRNode == XRHandControllerNode.Left ? XRNode.LeftHand : XRNode.RightHand;

private const float MinimumSqueeze = 0.8f;
private string trigger =>
                   this.TrackedXRNode == XRHandControllerNode.Left ?
                   "LeftIndexTrigger" :
                   "RightIndexTrigger";

public XRHandControllerNode TrackedXRNode;

Why does Input.GetAxis always return 0, and what changes should I make to ensure that any squeeze of the trigger will be correctly detected?

It was a timing issue. Input.GetAxis(trigger) returned values that are negligibly close to 1 in subsequent invocations of Update() as I continued squeezing the corresponding trigger on my Oculus controller.


text:
NullReferenceException shown every single time a change is applied to my prefab
I created a prefab out of a game object in my scene. Every single time I hit Apply after making changes to my game object, I see the following stack trace:

However, as far as I can surmise, the changes are applied nonetheless, because the bolded field (indicating that its value is yet to be applied to the prefab) immediately becomes un-bolded once I hit Apply.

If, contrary to my belief, my changes are not applied to my prefab, what should I do to ensure that they are?
If the error message appears even when I successfully apply my changes to my prefab, what can I do to make it go away?

UPDATE 1:
I noticed that after the first time I hit Apply, the game object went from being highlighted in blue (indicating that it mirrors a prefab) to being highlighted in black (indicating that it no longer mirrors a prefab).
Game objects that mirror other prefabs work fine. This is the only exception.
UPDATE 2:
I deleted the prefab, and created another prefab from the same game object. This time, after hitting Apply, I still see the same exception, but the game object remains highlighted in blue (indicating that it is still mirroring a prefab).

I've been getting a few random but so-far-seemingly-harmless errors & exceptions from Unity's internal editor processes in 2017 versions, though I have not observed this one in particular. It's likely a case to log as a bug, especially if you can narrow down the steps to reproduce it. Does it occur with every prefab (say, create a default cube and make a prefab of that) or only ones with particular scripts/assets in use?

@DMGregory I have updated my post with more details.

Cool. Try making a copy of the object, and change one thing about it — like remove a particular component. Then prefab that, and see if it exhibits the same problem. Or try rebuilding a similar object from scratch and try prefabbing it. Keep tweaking & checking the prefab behaviour to see if you can isolate what it is about this object that's triggering the error. Maybe try saving the prefab to different names/folders too.

@DMGregory I made another update -- please read and let me know if the situation rings a bell...

You don't need to @ me with each discovery. ;) Keep trying different variations until you have what's called a minimal complete verifiable example: a set of instructions you could hand to someone that would let them reproduce this error.

@DMGregory The error occurs only with that game object with all its children and nested children. Once I delete one of its children -- any children -- and create a prefab from it, everything works as expected.

What I did to resolve the issue:
I deleted the game object from the scene, along with its prefab. I checked my changes into source control.
I asked my game designer to add the game object back into the scene, and then to check in his change.
I pulled his change, and re-created a prefab from the game object. Everything started working as expected -- I no longer see the error message, and all changes I make to the game object are now correctly applied to the prefab as well.
I still don't understand what happened in the first place to cause the problem, but the aforementioned approach fixed it.


text:
Elegantly exposing properties in Unity inspector
There are various game objects in my scene that share some common characteristics, so I created an interface, like so:
public interface IHasLimitedRangeOfMotionAlongZAxis
{
    float MinimumZ { get; }
    float MaximumZ { get; }
}

For certain types that implement this interface, I would like MinimumZ and MaximumZ to be publicly assignable in the Unity inspector. Therefore, I would like to be able to expose these properties in Unity.
I am aware that one approach is to write C# scripts in the Editor folder to implement an ExposePropertyAttribute (see here).
However, this approach is unsatisfactory for two reasons:

My solution is not co-located with my Assets folder. I write my code in a separate solution, and then use pdb2mdb.exe to import my scripts into my Unity scenes. (The reason for doing this is to avail myself of C# language features introduced beyond C# 4.0, which nonetheless target .NET Framework 3.5.)
I shall have to create a custom editor for every single type that implements the interface with publicly assignable properties. This leads to a lot of boilerplate code.

Is there a more elegant approach than adding private backing fields with the SerializeField attribute for all of my public properties?

It should be noted for newer readers that current versions of Unity support later C# features natively, so the workaround described above with pdb2mdb.exe should not be necessary.

You can use Auto-Implemented Property Field-Targeted Attributes to expose properties in the inspector. You still have to use SerializeField but you don't need to write the backing field manually anymore.
[field: SerializeField]
public Transform Ball { get; set; }

This is only supported in newer versions of Unity that support C# 7.3.
Clarification: By newer versions of Unity, I mean any version of Unity that supported the .NET 4.6 runtime (I think). The documentation does not exist for all versions, but it has been supported since at least Unity 2018.4 [source].

AFAIK at the moment there aren't solutions different from using [SerializeField] on the private fields of the property or implementing some editor code that exposes properties like the one you linked.

I would like MinimumZ and MaximumZ to be publicly assignable in the Unity inspector.

This is not possible. You've declared these properties as read only.

float MinimumZ { get; } //no setter
float MaximumZ { get; }

No matter what inspector options exist or are possible, or even might be possible for Interface types, you've explicitly denied writing to these properties.
The only option you have is using [SerializeField] on the private backing object.

I can have a class that implements IHasLimitedRangeOfMotionAlongZAxis with public float MinimumZ { get; set; }, and also inherits from MonoBehaviour. If I assign the script containing this class to a game object, I would like MinimumZ to show up in the inspector. Is this not possible?

@MY_G I think at that point you fall under the purview of Galandil's answer. In either case I haven't tried, but I saw your Interface definition and knew there was going to be a problem regardless of what might exist.

Autoproperties are the bane of Unity's Inspector. :D


text:
Relative motion physics
So, I built a simple physics engine (without rotation as of now)
You can click and then release to create block with velocity.
https://codepen.io/kingofdelphi/pen/vRZvxQ

Now, I want to apply force at the bottom most block. Currently, the block will only slide without affecting the other top blocks.
Now, I can only think of a simple algorithm to make all the top blocks slide when the bottom one slides which goes like this,

shift the current block
find the blocks on top that touch the current block,
recurse each such block and goto step 1

But there are problems with this algorithm(double additions for example, but easy to fix with a boolean flag).
So guys, how do I make all top blocks slide when the bottom one moves?

Moving a cube under another one is the same as moving the one on top in the other direction. Friction keeps them together. So, when you detect a collision from the top, get the force applied  to the bottom cube and apply it to the one on top as well.

Can you add some references so that I can study more
in depth? By the way is it an easy problem?

Look for "static friction," specifically.

The force on top cube should be equal to the force applied on the bottom one, minus a slight amount, which is the dynamic friction coefficent

how do i handle complex block structure where more than two blocks are on top of the bottommost block?


text:
Update() method never called
I have a class BlinkingBehaviour which inherits from MonoBehaviour. Game objects attached to scripts containing classes that inherit from BlinkingBehaviour should, as the name suggests, blink.
BlinkingBehaviour is a small class so I will share the entirety of its code here:
public class BlinkingBehaviour : MonoBehaviour
{
    private Renderer renderer;

    public bool BlinkingEnabled;
    public Color BlinkingColour = new Color(1.0f, 127f / 255f, 39f / 255f);

    protected float CurrentColourScale;
    protected float ColourScaleIncrementPerUpdate = 0.005f;

    protected const float MaxColourScale = 2f;

    protected void Start()
    {
        this.renderer = this.gameObject.GetComponent<Renderer>();
    }

    protected void Update()
    {
        if (this.BlinkingEnabled)
        {
            SetBlinkingColour();
        }
        else
        {
            SetColour();
        }
    }

    protected void SetColour()
    {
        if (this.CurrentColourScale <= 1f)
        {
            this.renderer.material.SetColor("_EmissionColor", this.BlinkingColour * this.CurrentColourScale);
        }
        else
        {
            this.renderer.material.SetColor("_EmissionColor", this.BlinkingColour * (MaxColourScale - this.CurrentColourScale));
        }
    }

    protected virtual void SetBlinkingColour()
    {
        SetColour();
        this.CurrentColourScale += ColourScaleIncrementPerUpdate;

        if (this.CurrentColourScale <= MaxColourScale)
        {
            return;
        }

        ResetBlinkingColourScale();
    }

    protected void ResetBlinkingColourScale()
    {
        this.CurrentColourScale = 0f;
    }
}

I have a class Lamp which inherits from BlinkingBehaviour. I attached Lamp.cs to an object in my scene. In my inspector, I checked the BlinkingEnabled option, expecting to see the Lamp game object blinking after I pressed "Play".
However, the object did not blink.
Here is my Lamp class:
public class Lamp : BlinkingBehaviour
{
    private void Start()
    {
        base.Start();
    }

    private void Update()
    {
        base.Update();
    }
}

After setting various breakpoints, I could see that the Start() method was hit in both Lamp and BlinkingBehaviour. I could also see that this.gameObject.GetComponent<Renderer>(); returned a valid component.
On the other hand, my breakpoint in the Update method in Lamp was never hit.
What can I do to fix this issue?
UPDATE:
I deleted the Start() and Update() methods from my derived class. I discovered something new: The Update() method in BlinkingBehaviour is never called, even though Start() is.

@Bálint by default, Update is private, and it can be protected or public, in this case it doesn't really matter since the superclass' callback is called anyway if there's no overriding Update method in the inheriting class.

@Bálint Why not? Unity calls MonoBehaviour messages through reflection, so they don't need to be public/etc. for it to access them.

The Update in the derived class should be an override of a protected virtual Update in the base class.
Imagine when Unity reflects the non-public members on your behavior -
BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic;
MethodInfo theMethod = typeof(Lamp).GetMethod("Update", flags);
theMethod.Invoke(lampInstance);

Which Update method gets called? By having private and a protected methods that aren't associated as an override, both are available so one will be chosen depending on the underlying implementation - possibly throwing an exception.
The proper way to implement this pattern would be:
public class BlinkingBehaviour : MonoBehaviour
{
    protected virtual void Update()
    {
        // ...
    }
}
public class Lamp : BlinkingBehaviour
{
    protected override void Update()
    {
        base.Update();
        // ...
    }
}

I quickly tried your code by copy/pasting it on a test scene, and it's working perfectly fine.
First of all, you can delete both Start and Update methods from Lamp: since it inherits from BlinkingBehaviour, both Start and Update methods will be called anyway from the superclass if there're no overriding methods in the inheriting class.
The fact that Update from BlinkingBehaviour is never called, tells that there's something wrong elsewhere.
Are you sure that the Lamp script component is active?

Thank you for your reply! Yes, the script component is attached to an active object in the scene.

I don't mean the game object, but the script component itself. Just to be sure, create a new scene, create a simple cube and attach the Lamp script and see if it works (it should).

I have just double-checked -- yes, the script component is active. However, I will use your approach and test it in a new scene as well.


text:
Torque Generation
I have written a basic physics engine. It is able to handle rotations. But how do I handle case like this where an object sits on top of another and needs to rotate due to the effect of gravity ?
I know that when the center of mass is outside the body will fall down. But I am unable to express this in algorithm. I could make it work for a regular convex polygon (by finding if center of mass is outside of the contact surface). But how do I make it work for irregular convex polygon?
Basically, I need a clear idea of what kinds of forces are acting on the top body so that I am able to make it fall down due to gravity.

Whenever you exert a force also exert a torque at the intersection point. T=Fxd where d is distance from the center of mass to the point. There is no torque from gravity.

So, what are the intersection points? Since the top object is parallel to the botttom one, I see a line segment. So, what will be the force and the application points?

Physically correct would be to say a torque is acting at every point along the line segment between 1 and 2. We can approximate it by using the midpoint of the two contacts. Though it will very very quickly become contact 1 as the upper rect starts to rotate.

As for the force, you should be using some numerical integration to apply forces and torques like Euler or Verlet integration. So given the forces of the two bodies, their collision normals, and mass we can calculate the resulting force. For example, say the bottom rect was unmoveable (infinite mass). Then all the force going into it would be reflected for it to come to rest. In this case the force going into it is Fg. So -Fg is exerted on the upper body at the contact. This is an edge case. But often the case in a platformer like game. Then Torque = cross(Force, dist from CoM)


text:
Clamping always returns 0
I have a class with three fields:

StartingAngleOnRotationPlane is 180
MinimumRotatedAngleX is 0
MaximumRotatedAngleX is 140

Here is the offending code:
public virtual float ClampRotatedDegreesWithinAllowedRange()
{
    float rotatedAngle = this.transform.GetRotatedAngleOnXPlane();
    Debug.Log("Rotated " + rotatedAngle);

    float clampedRotatedAngle =
        Mathf.Clamp(
            AngleNormaliser.BetweenNegativeAndPositive180(this.StartingAngleOnRotationPlane + rotatedAngle),
            this.MinimumRotatedAngleX,
            this.MaximumRotatedAngleX);

    return clampedRotatedAngle;
}

Here is the debug window:

As you can see, when the breakpoint was hit, rotatedAngle was -178.9446.
To calculate clampedRotatedAngle, rotatedAngle is added to StartingAngleOnRotationPlane, supplied to a method called AngleNormaliser.BetweenNegativeAndPositive180(float input), and then clamped between MinimumRotatedAngleX (0) and MaximumRotatedAngleX (140).
Here is the code for AngleNormaliser.BetweenNegativeAndPositive180(float input):
public static float BetweenNegativeAndPositive180(float angleBetween0And360)
{
    while (angleBetween0And360 > 180)
    {
        angleBetween0And360 -= 360;
    }

    while (angleBetween0And360 < -180)
    {
        angleBetween0And360 += 360;
    }

    return angleBetween0And360;
}

Here is the debug window when AngleNormaliser.BetweenNegativeAndPositive180(float input) was invoked:

By the time the return statement was hit, the result 1.055389 should be returned and assigned to the variable clampedRotatedAngle, since 1.055389 is within the clamping range (0 - 140).
However, that was not the case:

As you can see, clampedRotatedAngle was still zero.
In fact, clampedRotatedAngle is always zero, regardless of what I feed into the Mathf.Clamp function:

How can I fix this?

Please post your code as text, not as screenshots.

@Galandil Done :-)

are you sure MinimumRotatedAngleX is 0?

@Bálint Yes. I will take another debugger screenshot with that value included.

Also, what'a StartingAngleOnRotationPlane?

@Bálint It is a float.

FYI converting to and from angles is not the best way to go about things. Instead use trigonometric identities to do your math as much as possible.

@DMGregory he's right though, since angleBetween0And360 is 1.055389, and the boundaries of Clamp are 0-140, the latter should return 1.055389 and not 0. Unless there's something wrong not shown here due to the use of this and from where he calls the methods.

Apologies, I'm on mobile and misread the method when scrolling horizontally. I notice that -178.9446 is very close to -180 + 1.055. Are you certain that at runtime, this.StartingAngleOnRotationPlane is +180 and not -180?

To verify that clamping is actually the problem, dump the min & max values to output immediately before calling clamp.

StartingAngleOnRotationPlane is 180
MinimumRotatedAngleX is 0
MaximumRotatedAngleX is 140

Are these variables public or serialized? In that case Unity might be taking the values set from editor. In this case I think your MaximumRotatedAngleX is set to 0.


text:
Struggling with the uncertainty of a position of a collision
I've been trying so hard to complete a working game of pong for the last couple of weeks but, simply put, the physics of trying to get the ball to bounce correctly of the paddle is preventing me from having a working game. What I would like to do is get the ball to hit the paddle, then bounce off correctly depending on the point of collision with respect to the paddles position:

If it hits the top or bottom of the paddle, I would like it to just
reflect the y velocity.
If it hits the front of the paddle, calculate the normalised position and then redirect it based on this.

The main problem I'm having is, the point of collision isn't exact and always changes, even if I used FixedUpdate() for physics based calculations. There's always a point around the corner that gives the ball a very small and unexpected velocity. Sometimes it even hits the paddle (when the ball is going in the same direction as the paddle) and just travels straight upwards once it hits the paddle. I've tried OnCollisionEnter2D and OnTriggerEnter2D and haven't achieved the expected behaviour.
If anyone could help me to understand what I should do in this situation. That would be incredible as I don't really have anyone to turn to..
Thanks again!
(I thought my code wouldn't really be that beneficial but I have added it anyways, it's what I have right now, the paddle, ball and walls all have colliders and the paddles and ball have rigidbodies, if that helps.)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BallMovement : MonoBehaviour {

private float speed = 5f;
private float hitCount = 1f;
public static int playerCount = 0;
public static int computerCount = 0;
private static Rigidbody2D ballRigidbody;
private Vector2 theBallVelocity;
private string whichPaddle;

void Start () {
    ballRigidbody = GetComponent<Rigidbody2D> ();
    ballRigidbody.velocity = Vector2.left * speed;
    whichPaddle = "";
}

void FixedUpdate() {
    theBallVelocity = ballRigidbody.velocity;

}

void OnCollisionEnter2D(Collision2D collision) {

    //Calculates the position of the ball on collision and reflects with an angle and velocity relative to the position it collided at.
    if (collision.gameObject.tag == "Player") {

        Vector2 thePosition = ballRigidbody.position;
        float proportionPosition = CalculatePosition (thePosition, collision.transform.position, collision.collider.bounds.size.y);
        float theDifference = 0.0f;

        if (whichPaddle != "Player" && (proportionPosition > 0.52f || proportionPosition < -0.52f)) {
            ballRigidbody.velocity = new Vector2 (theBallVelocity.x, theBallVelocity.y * -1f);
            print ("it's hitting the edge" + proportionPosition);
        }

        if (proportionPosition <= 0.52f && proportionPosition >= -0.52f)  {
            Vector2 direction = new Vector2 (1, proportionPosition).normalized;
            ballRigidbody.velocity = direction * speed * (1f + 0.05f * hitCount);
            hitCount += 1;
            print ("it's not hitting the edge");
        }

        whichPaddle = "Player";
    }

    //Calculates the position of the ball on collision and reflects with an angle and velocity relative to the position it collided at.
    if (collision.gameObject.tag == "Computer") {

        Vector2 thePosition = collision.transform.position;
        float proportionPosition = CalculatePosition (transform.position, collision.transform.position, collision.collider.bounds.size.y);
        float theDifference = 0.0f;

        if (whichPaddle != "Computer" && (proportionPosition > 0.52f || proportionPosition < -0.52f)) {
            ballRigidbody.velocity = new Vector2 (theBallVelocity.x, theBallVelocity.y * -1f);
            print ("it's hitting the edge" + proportionPosition);
        }

        if (proportionPosition <= 0.52f && proportionPosition >= -0.52f) {
            Vector2 direction = new Vector2 (-1, proportionPosition).normalized;
            ballRigidbody.velocity = direction * speed * (1f + 0.05f * hitCount);
            hitCount += 1;
            print ("it's not hitting the edge");
        }

        whichPaddle = "Computer";
    }

    //Reflect the ball when it hits this boundary.
    if (collision.collider.name == "TopBoundary") {
        ballRigidbody.velocity = new Vector2 (theBallVelocity.x, theBallVelocity.y * -1f);
    }

    //Reflect the ball when it hits this boundary.
    if (collision.collider.name == "BottomBoundary") {
        ballRigidbody.velocity = new Vector2 (theBallVelocity.x, theBallVelocity.y * -1f);
    }

    //Essentially resetting everytime a player scores until they only need one more goal.
    if (collision.collider.name == "LeftBoundary") {
        if (computerCount == 8) {
            Reset (ballRigidbody);
        } else {
            ballRigidbody.position = new Vector3 (0, 0, 0);
            ballRigidbody.velocity = Vector2.left * speed;
        }
        hitCount = 1f;
        computerCount += 1;
    }

    //Essentially resetting everytime a player scores until they only need one more goal.
    if (collision.collider.name == "RightBoundary") {
        if (playerCount == 8) {
            Reset (ballRigidbody);
        } else {
            ballRigidbody.position = new Vector3 (0, 0, 0);
            ballRigidbody.velocity = Vector2.left * speed;
        }
        hitCount = 1f;
        playerCount += 1;
    }
}

//Calculate the percentage point at where th ball hits the paddle.
float CalculatePosition(Vector2 ballPosition, Vector2 paddlePosition, float paddleHeight) {
    float y = (ballPosition.y - paddlePosition.y) / paddleHeight;
    return y;
}

//Reset the balls position.
void Reset(Rigidbody2D ball) {
    ball.position = new Vector3 (0, 0, 0);
    ball.velocity = new Vector2 (0, 0);
}
}

If the default discrete collision detection isn't giving your the fidelity you need, have you tried using continuous collision detection or circle casting?

Oh, I haven't no. I took away the material I had that was causing the unnecessary extra change in direction and thought I could continue down this path but I failed :P I will definitely try this tomorrow and look up tutorials on how to implement it. I thought OnCollisionEnter2D would provide me with the exact coordinates of collision and it doesn't, meaning they're never precise enough to cover the scenarios. With continuous collision detection, will it help me to achieve this?


text:
Instantiate prefab as a type that inherits from MonoBehaviour
I have a CeilingTile class. In this class, I have an InstantiateCeilingLamp() method, which instantiates from a CeilingLamp prefab.
Here is the code:
protected void InstantiateCeilingLamp()
{
    Object ceilingLampPrefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));

    CeilingLamp ceilingLamp =
        Instantiate(ceilingLampPrefab, this.transform.position, Quaternion.identity)
            as CeilingLamp;

    if (ceilingLamp == null)
    {
        Debug.Log("Failed to instantiate the ceiling lamp.");
        return;
    }

    ceilingLamp.transform.SetParent(this.transform);
}

prefabPath is a const string defined within the class.
Stepping through my code using the debugger, I can see that ceilingLampPrefab is non-null after executing AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));.
However, Instantiate(...) as CeilingLamp; returns null, because the instantiated prefab cannot be cast to the type CeilingLamp, which inherits from MonoBehaviour.
How should I modify my code in order to instantiate a prefab as a type that inherits from MonoBehaviour?

The CeilingLamp prefab has the CeilingLamp.cs script (which inherits from MonoBehaviour) attached to it, so by modifying the code as follows, I am able to do what I want:
protected void InstantiateCeilingLamp()
{
    Object ceilingLampPrefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));

    GameObject lampObject =
        Instantiate(ceilingLampPrefab, this.transform.position, Quaternion.identity)
            as GameObject;

    CeilingLamp ceilingLamp = lampObject.GetComponent<CeilingLamp>();

    if (CeilingLamp == null)
    {
        Debug.Log("Failed to instantiate the ceiling lamp.");
        return;
    }

    ceilingLamp.transform.SetParent(this.transform);
}

I think you can simplify this substantially by making it var ceilingLampPrefab = (CeilingLamp)AssetDatabase.LoadAssetAtPath(prefabPath, typeof(CeilingLamp) then your Instantiate method will return the reference to the instance's ceiling lamp script directly.


text:
OnTriggerExit() called when game object with collider component gets re-parented
I have an object Hand, with a rigid body attached to it. In every Update() call, the user's hand controller rotation and position are tracked.
In my scene, there is an object Pin, with a mesh collider attached to it.
In OnTriggerEnter() (inside the Hand class), Pin becomes re-parented to Hand. (Pin's original parent is something else.)
My scene also contains other objects with colliders. However, these other objects do not get re-parented -- only Pin does.
Once this re-parenting takes place, OnTriggerExit() (in the Hand class) is called immediately. This is surprising to me -- I had expected OnTriggerStay() (in the Hand class) to be invoked instead, since Hand is still in contact with Pin.
Is such behaviour by design? Is there an elegant way of working around such behaviour?
UPDATE:
In response to this comment:

Does the pin object have a parent before it becomes a part of the
  hand?

Yes. As mentioned in my post, Pin's original parent is something else.

Or is it placed inside another collider? And does the pin leave any of
  these collider areas when the parenting takes place?

As mentioned in my post, Pin itself has a mesh collider component attached to it. Perhaps I am not understanding the question correctly...

You can prevent the hand's script from getting this OnTriggerExit by
  adding a seperate rigidbody to the pin.

I added a separate rigid body to the pin (setting isKinematic to true), but OnTriggerExit() inside the Hand class is still called immediately after Pin gets re-parented.
MORE INFORMATION:

Pin's original parent (before it gets re-parented to Hand) does not itself have a collider component.
When OnTriggerExit(Collider collider) gets called immediately after the re-parenting takes place, the collider argument passed to the method is the Pin itself.

Does the pin object have a parent before it becomes a part of the hand? Or is it placed inside another collider? And does the pin leave any of these collider areas when the parenting takes place? In this case it makes sense to have the OnTriggerExit called. You can prevent the hand's script from getting this OnTriggerExit by adding a seperate rigidbody to the pin

Thank you for your comment. I will update my question to make things clearer.

"And does the pin leave any of these collider areas when the parenting takes place?" - What I mean is whether or not the pin's collider was in contact with another collider and does this contact break when the parenting takes place. I feel like the answer is yes since it was already a child of something else. Try adding a kinematic rigidbody to the pin. This will prevent the hand's script from getting the OnTriggerExit call

Thank you for your reply. I have added a separate rigid body to the pin (setting isKinematic to true), but OnTriggerExit() is still called in the Hand class.

@Aj_ I have added more information to the question.

Does the object that has the script (which gets OnTriggerExit) attached to it have a rigidbody? If not, add a rigidbody to it as well.

@Aj_ Both the Hand and the Pin have rigid bodies attached. That does not fix the problem.

Re-parenting is a somewhat complicated operation in the physics world. In older versions of Unity it was recommended to disable colliders before changing parents, then re-enable them afterward, because it was a noticeably slow operation.
The physics system more or less has to remove the object from the whole world (triggering OnTriggerExits), then re-insert it into a new place. Even if that place ends up being equivalent, the physics engine either can't or just doesn't guarantee that up-front, so it conservatively handles all collision exit/enter events along the way to make absolutely sure no collision changes get missed.
So, it's generally a good idea not to reparent objects as a means to change their physics behaviour at runtime. Instead, you may want to consider using Joints to attach physics objects when you want them to move together.


text:
Turning a simple HTML5/JS single-player game into a multi-player one
CONTEXT:
I am currently developing the front-end/ client of a simple browser game using HTML5 Canvas/JavaScript. In the future, I would like to add a multi-player dimension to it, most likely using node.js/mongoDB. At this point, however, I have no experience whatsoever with the required back-end technologies.
DESIRED OUTCOME:
The game involves some simple interactions (e.g. collect a key; once you've collected it, you can open the door, etc.). In the multi-player mode, the outcomes of said interactions carried out by any player are supposed to affect the game state for all players (e.g. if any player has opened the door, it stays open for all players). This will likely require setting up a database.
QUESTION:
At what point do I need to start writing the code in a way which involves referencing a database?
Does it make any sense at all to first develop the "game logic" in JavaScript only (as if it was only meant to be played as a single player) and only afterwards proceed to rewriting the code referencing a database?
Apologies if my question sounds idiotic. Newbie here!

Turning a game developed for singleplayer into a multiplayer game when it was not designed for that from the start can be extremely difficult, both regarding software architecture and regarding game design.
But there are some things you can do which make it much easier to add multiplayer later while not hampering your development progress too much while you are still single-player.
Software Architecture
The most important is having a clear separation of concerns from the start. Strongly encapsulate the input, game mechanics, game state, graphic engine and UI of your game. Have them communicate with each other using clearly defined, loosely coupled functions which assume nothing about the inner workings of the other modules.
This allows you to later replace these local modules with remote modules which then communicate with the remaining local modules using the same functions you already have.

When a second local player joins the game, you simply create a new instance of the input module which listens to different keys and assign it to a new instance of the player entity.
When a new remote player joins the game, then a network input module takes the role of the local input module.
When you move game mechanics to a server, then the server networking module takes the role of a local gameplay module.
To send local events to the server, you could either add a second consumer to your input module or use the same functions which are used by the UI module to monitor changes in the game state.

You might also go a step further and develop your singleplayer game as if it were a multiplayer game. Assume every game entity is remote-controlled, but "fake" that remote control with a local controller. That way most of your game architecture won't know and won't care if a game entity is an enemy controlled by a local AI controller or another player controlled by a network controller.
And besides, proper encapsulation and separation of concerns is always a good guideline for a clear and easily maintainable and extensible software architecture.
Game Mechanics
But besides the architectural concerns, there are also game design concerns. Multiplayer games are often far harder to design than single player games for a couple reasons:

Game balance is more important. When you accidentally have a feature in your game which is so overpowered that it breaks the game, then single-players will often be able to show at least some restraint from abusing it until it stops the game from being fun. You might also see players trying to finish the game without using that overpowered feature as a self-imposed challenge. In multiplayer, however, players will have far less quarrels. Competitive multiplayers will usually do everything it takes to win, even if it makes the game boring to play for everyone including themselves.
Counter play becomes an important consideration. When you give the player a new ability in a single-player game, you just have to wonder "How does this make the game more fun for the user?". But in a multiplayer game you also have to wonder "How does this make the game more fun for the one it is used against?". For example, freezing an enemy in a block of ice for a couple minutes might be fun in single-player, but in multi-player it is extremely annoying for the one being frozen and unable to play. Extra Credits made a good video about this topic.
Time skipping becomes impossible. In a single player game you can skip boring sequences by either speeding up time (common in strategy and puzzle games) or by simply omitting them (fast-travel systems are a common example). However, when multiple players share the same game world, they also share the same game time. You can usually not speed up the game for some players who are currently in a boring phase but not for those who are currently in a more complex game phase.

Again, the best way to address these problems early is to design your single-player game as if it were a multiplayer game. To address balance and counter-play, consider to follow a general rule that whatever the player can do can also be done by the AI opponents. And if you notice that parts of your game are boring and tedious, don't take the easy way out by simply using time-skipping. Try to find a proper solution to make those phases as interesting as the rest of the game or to speed them up in a way which is plausible within the fiction of the game and does not break game balance in multiplayer.
Narration
There are also narrative differences between single player and multiplayer. In single player, the player-character (PC) can be someone special. There is no issue with making the PC the chosen Mary Sue character the whole world turns around. But the more players you add, the more limited you become regarding the role of the PC in your game's narration. In a multiplayer game, the PCs have to share the spotlight with each other. Not everyone can be "the chosen one".
In a massive multiplayer game where you have thousands of PCs, it becomes almost impossible to add any convincing narrative which makes the PC and their experience seem unique. Some MMO games try by having those quests of the game designed to be played alone make the PC somehow special, hoping that the player ignores the fact that all the people around them currently experience the exact same story they do. But the illusion falls apart as soon as you enter the cooperative content.
But in exchange for that, you get a completely different narrative angle. You can give the player the feeling of being part of something greater and making a useful contribution to a coordinated group effort. This is challenging (but not impossible) to pull off in a single-player game due to the lack of empathy for the NPC characters, but it can be a very satisfying experience in a massive multiplayer game where the player knows that all those people they fight alongside are in fact real humans.

Knowing the technologies you are going to use for the network layer is usually a big advantage so you don't write your whole game in a certain way, and find out 40% needs to be rewritten to adjust to the network technology you will be working with.
For a multiplayer you are surely going to need to work with Sockets, for real time communication.

I think Philipp has covered the main architectural concerns.
Just one more point I'd like to add is to plan for your game actions to resolve asynchronously.
Imagine we write the local version of the "spend key to unlock door" interaction something like this:
function UseKey(door) {
   if(door.isLocked == false)
       return false;

   door.Unlock();
   inventory.remove(key);
   return true;
}

If we port that to a multiplayer form naively, we could have two players each try to unlock the door at the same time, before either one has gotten the message that the door is already unlocked. So they both consume their keys for just one door unlocking — or you need more complicated reconciliation logic to detect this conflict and roll back the consequences to give back one of the keys after the fact.
Instead you'll want your game actions to take some form of "request & confirm" form, where using the key just sends a signal to the [local or server] door authority that you intend to unlock it, but doesn't immediately alter your game state. Then you have some kind of event or callback that can happen after the initial use interaction has returned, which actually confirms whether the interaction succeeded and applies the consequences to your game state.
Setting up even your local/single-player version of the game to work this way will make it much easier when you later want to replace the local gameplay logic with a server authority, without massive structural changes to every action that could result in a conflict with other players, or cheating with a hacked client.

In this case (as I did) you need to move all you game mechanic to backend. Not a big deal with NodeJS. And develop your wrapper for WebSocket to provide auth and way you will communicate between clients and server (as your client is browser - "you can't trust anyone).
Client in this case only do what server say.
UPD: Think careful about communication protocol. Constant parsing JSON is not good idea. For example you can separate variables in message with non-print character.

I would say there's no real need to think about it right now, just implement the game client-side but make sure to keep the core 'rules' decoupled from the rest of the code.
Reason 1 would be from a purely architectural standpoint, you don't want your client-side code to be too coupled to your rendering code and you won't want the server code too coupled to the database, so it should be written to be flexible anyway.
Reason 2 - if you end up going with Node for the backend (which I recommend), the game logic can be very similar -- you could even share the 'rules' module across the client and the server -- because the environments (Node and the browser) are both event-driven and Node allows you to have variables that persist between requests (as opposed to, for example, PHP where everything would have to be loaded from the database on each request).
See the code behind meteorchess.com for an example of this being done: lightsquare (client), lightsquared (server) and chess (chess rules module used unaltered by both).  In this app, the database (Mongo) is only used for archiving the games once finished.  While in-play, the games are just in memory on the server.