Unity脚本中如何修改骨骼的Z轴旋转值?
问题描述
在2D枪械场景中旋转骨骼时,发现骨骼仅绕Z轴旋转。现有Rotate脚本代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Rotate : MonoBehaviour { public GameObject forBone; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } }
请问如何在该脚本中修改Z轴旋转值?
解决方案
以下是几种修改骨骼Z轴旋转值的实用实现方式:
方式一:直接设置固定Z轴角度
在Update方法中直接修改目标骨骼的欧拉角Z分量,适合需要固定旋转角度的场景:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Rotate : MonoBehaviour { public GameObject forBone; // 可在Inspector面板调整目标Z轴旋转角度 public float targetZRotation = 45f; void Update() { if (forBone != null) { Vector3 currentAngles = forBone.transform.eulerAngles; currentAngles.z = targetZRotation; forBone.transform.eulerAngles = currentAngles; } } }
方式二:平滑过渡到目标Z轴角度
如果需要平滑旋转的过渡效果,使用Mathf.LerpAngle实现插值旋转:
using System.Collections; using System.Collections; using UnityEngine; public class Rotate : MonoBehaviour { public GameObject forBone; public float targetZRotation = 45f; // 旋转速度,值越大旋转越快 public float rotateSpeed = 2f; void Update() { if (forBone != null) { float currentZ = forBone.transform.eulerAngles.z; float smoothedZ = Mathf.LerpAngle(currentZ, targetZRotation, rotateSpeed * Time.deltaTime); forBone.transform.eulerAngles = new Vector3(0, 0, smoothedZ); } } }
方式三:跟随鼠标自动旋转(2D枪械常用需求)
针对2D枪械场景,可让骨骼跟随鼠标位置自动计算Z轴旋转角度:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Rotate : MonoBehaviour { public GameObject forBone; void Update() { if (forBone != null) { // 将鼠标屏幕坐标转换为世界坐标,保持Z轴与骨骼一致 Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition); mouseWorldPos.z = forBone.transform.position.z; // 计算骨骼指向鼠标的方向向量 Vector3 direction = mouseWorldPos - forBone.transform.position; // 将方向转换为角度值 float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg; // 设置骨骼Z轴旋转角度 forBone.transform.rotation = Quaternion.Euler(0, 0, angle); } } }
内容的提问来源于stack exchange,提问作者a3egd
相关产品推荐
相关产品推荐

