简体   繁体   English

如何统一限制 z 轴旋转?

[英]How do I limit z-axis rotation in unity?

I'm writing a 2d game for android.我正在为 android 编写 2d 游戏。 I have a character that rotates from 180 to - 180 degrees.我有一个从 180 度旋转到 - 180 度的角色。 But I need to limit transform rotation by z to 50 and -50.但我需要将 z 的变换旋转限制为 50 和 -50。 I know it's possible via Math.Clamp(), but I can't apply it.我知道可以通过 Math.Clamp() 实现,但我无法应用它。 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() .实际上,您可以做的是使用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:在您的情况下,您的rotationX将是:

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() .注意:这必须在Update()中完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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