简体   繁体   中英

How do I limit z-axis rotation in unity?

I'm writing a 2d game for android. I have a character that rotates from 180 to - 180 degrees. But I need to limit transform rotation by z to 50 and -50. I know it's possible via Math.Clamp(), but I can't apply it. Please help me: Here is my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public : MonoBehaviour
{
 
    private Camera myCam;
    private Vector3 screenPos;
    private float angle0ffset;
    private Collider2D col;
    private void Start()
    {
myCam = Camera.main;
col = GetComponent<Collider2D>();
       
    }
    private void Update()
   {
     
Vector3 mousePos = myCam.ScreenToWorldPoint(Input.mousePosition);
   ( (Input.GetMouseButtonDown(0))
 
screenPos = myCam.WorldToScreenPoint(transform.position);
Vector3 vec3 = Input.mousePosition - screenPos;
angle0ffset = (Mathf.Atan2(transform.right.y, transform.right.x) - Mathf.Atan2(vec3.y, vec3.x)) * Mathf.Rad2Deg;
 
   }
      }
  ( (Input.GetMouseButton(0))
   {
 
  if(col == Physics2D.OverlapPoint(mousePos))
    {
      Vector3 vec3 = Input.mousePosition ;
      float angl = Mathf.Atan2(vec3.y, vec3.x) * Mathf.Rad2Deg;
      transform.eulerAngles = new Vector3(0,0, angl + angle0ffset);
     
    }  
     
  }
     
           }  
    }

What you can do is, indeed, use Mathf.Clamp() . What you would do is:

rotationZ = Mathf.Clamp(transform.localRotation.z, -lookZLimit, lookZLimit); transform.localRotation = Quaternion.Euler(rotationZ, 0, 0);

In your case you rotationX would be:

rotationZ = Mathf.Clamp(transform.localRotation.z, -50, 50);

And then to apply the newly calculated rotation:

transform.localRotation = Quaternion.Euler(rotationZ, 0, 0);

Note: this has to be done in Update() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM