Is it possible to disable/restrict free movement?

I would like my player to only move in four directions - forwards/backwards, left/right… (Think of a rook in chess)

I can for example press forwards and right at the same time, and it will move my pawn in a diagonal line.

How would I make it so I can disable diagonal/free movement?

Hi,

The solution is simple. First of all, try to figure out what diagonal means compared to forwards/backwards and left/right respectively. Once you did that, you will very likely know how to make your idea work.

Let me know what you figured out. :slight_smile:

Hello,

Thank you for the reply.

I think you mean that the diagonal movement is using multiple axes at once (X & Z), so I need to constrain my pawn only to move at one axis at a time. :thinking:

Is this something that should be added in the movement script somehow, or can it be toggled on/off somewhere in the inspector?

Yes, exactly. :slight_smile:

Is this something that should be added in the movement script somehow, or can it be toggled on/off somewhere in the inspector?

Do you already know if-statements? If so, you could create one if and one else if to check the user input.

At the moment, we don’t check for “horizontal” or “vertical” user input. We use use the user input “as it is”. See here:

void MovePlayer()
{
    float xValue = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
    float zValue = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
    transform.Translate(xValue,0,zValue);
}
If you don't know if-statements or would like to get a hint:
void MovePlayer()
{
   float xValue = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
   float zValue = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;

   // "horizontal input"
   if (xValue != 0f) { transform.Translate(xValue, 0f, 0f); }
   // "vertical input"
   else if (???) { transform.Translate(???); }
}

Since floats are often dangerous in regards to precision, it is better not to check for exactly 0. When you use a gamepad, you often don’t get exactly 0 even if you don’t move the stick.

For this reason, it is advisable check against a threshold. In this case, I would simply check the absolute value. Unity has got a method for that: Mathf.Abs(xValue). And then you could check: Mathf.Abs(xValue) > 0.01f, where 0.01f is my threshold. Of course, you could use another value.

Thank you very much!

This helped me a lot as I managed to solve it. :blush:
I will continue to read up on the methods that Unity has for a better understanding.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms