# How to limit the directions an object can move?

Hi,
I need a way to limit the directions a 2d object can move. The object shouldn’t be able to move in any directions in a curtain angle (red).

Thx for any help

Hi, you can define transformation (it has 3 directions), for each axe you can set angles min, max - this creates circle part on plane. Object has a transformation, you can use Z axe as direction, for check you needs to project this direction to plane and calculate angle (Cross product) between defined transform axe and projected vector, next you check this angle for min-max. It should be inside min-max for all 3 axes to make sure this direction is not allowed.

For 2D case you need only 1 axe.

I would make a method that takes in an angle from 0f to 360f and returns a constrained version of it based on the minimum and maximum allowed rotation. You can then assign that value to a transform’s eulerAngle.

Cooked up a small utility class. Here’s a sample:

``````using System;
using UnityEngine;

public class RotationTest : MonoBehaviour
{
[Range(0f, 360f)]
[SerializeField]
private float maxRotation = 360f;

[Range(0f, 360f)]
[SerializeField]
private float minRotation = 0f;

private Camera mainCamera;

private void Start()
{
mainCamera = Camera.main;
}

private void Update()
{
LookAtCursor();
LimitRotation();
}

private void LookAtCursor()
{
Vector3 mousePosition = mainCamera.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = new Vector2(
mousePosition.x - transform.position.x,
mousePosition.y - transform.position.y);

transform.up = direction;
}

private void LimitRotation()
{
float newRotation = RotationUtility.LimitRotation(
transform.eulerAngles.z,
minRotation,
maxRotation);

transform.eulerAngles = new Vector3(
transform.eulerAngles.x,
transform.eulerAngles.y,
newRotation);
}
}

public static class RotationUtility
{
/// <param name="rotation">
///  Value of 0f to 360f.
///  Rotation that will be limitted to a certain angle.
/// </param>
public static float LimitRotation(
float rotation,
float minRotation,
float maxRotation)
{
if (minRotation > maxRotation)
{
throw new ArgumentException("Min rotation cannot exceed the max!");
}

if (rotation < 0f ||
rotation > 360f)
{
throw new ArgumentException("Rotation has to be a value in range from 0f to 360f!");
}

if (rotation > maxRotation ||
rotation < minRotation)
{
float rotationDistanceFromMaxValue = Mathf.Abs(Mathf.DeltaAngle(rotation, maxRotation));
float rotationDistanceFromMinValue = Mathf.Abs(Mathf.DeltaAngle(rotation, minRotation));

if (rotationDistanceFromMaxValue < rotationDistanceFromMinValue)
{
return maxRotation;
}
return minRotation;
}

return rotation;
}
}
``````