moumed
moumed

Reputation: 135

How to Set object rotation limits around a pivot in Unity3d C#?

I'm working on a zigzag Game as shown here : [1]: https://i.sstatic.net/miKmH.jpg [ZigZagGame][1].

The goal is to make the ball pass all along the path (ZigZag), by rotating the path (Up, Down, Left, and right) around a pivot that I put to the other end of the ZigZag, using the Mouse Drag. I want to put limits on the orientation of the path. Here is my code to realize:`

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

public class RotationCheminOnDragMouse : MonoBehaviour
{
  float speed = 1.2f;

private void OnMouseDrag()
  {
      float rotx = Input.GetAxis("Mouse X") * speed * Mathf.Deg2Rad;
      float roty = Input.GetAxis("Mouse Y") * speed * Mathf.Deg2Rad;

      Vector3 backAngle = Vector3.back;
      Vector3 leftAngle = Vector3.left;

      transform.RotateAround(backAngle, -rotx);
      transform.RotateAround(leftAngle, roty);

  }

  private void Update()
  {
      if (Input.GetMouseButtonDown(0))
      {
          OnMouseDrag();
      }

  }


}

` So how can I put these limits? Knowing that I do not understand how to manage the angles of unity in C #. I hope you can help me with this. And thank you in advance for any response.

Upvotes: 1

Views: 615

Answers (2)

derHugo
derHugo

Reputation: 90580

You should keep track of how much you rotated already and then limit the new rotation like e.g.

public class RotationCheminOnDragMouse : MonoBehaviour
{
    float speed = 1.2f;

    [SerializeField] float minY = -45;
    [SerializeField] float maxY = 45;
    [SerializeField] float minX = -45;
    [SerializeField] float maxX = 45;

    private Vector2 alreadyRotated;

    private void OnMouseDrag()
    {
        var rotx = Input.GetAxis("Mouse X") * speed * Mathf.Deg2Rad;
        var roty = Input.GetAxis("Mouse Y") * speed * Mathf.Deg2Rad;

        // Now here you limit how much you can rotate
        if(rotX < 0)
        {
            rotx = Mathf.Max(rotx, minX - alreadyRotated.x));
        }
        else if(rotX > 0)
        {
            rotx = Maths.Min(rotx, maxX - alreadyRotated.x));
        }

        if(rotY < 0)
        {
            roty = Mathf.Max(roty, minY - alreadyRotated.y));
        }
        else if(rotY > 0)
        {
            roty = Maths.Min(roty, maxY - alreadyRotated.y));
        }

        transform.RotateAround(Vector3.forward, rotx);
        transform.RotateAround(Vector3.left, roty);

        alreadyRotated += new Vector2 (rotX, rotY);
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            OnMouseDrag();
        }
    }
}

Upvotes: 0

Poke Clash
Poke Clash

Reputation: 96

you may be using Mathf.Clamp, or Mathf.Clamp is used just for that, to limit a rotation.

Upvotes: 3

Related Questions