如何通过触摸拖拽输入绕Z轴旋转2D GameObject?
Hey there, I totally get the frustration of hunting for solutions only to find mostly JavaScript implementations—let’s fix that with a clean, reliable C# script built specifically for Unity. This will let your players drag their finger across the screen to rotate a 2D object around its Z-axis smoothly and intuitively.
Core Idea
We’ll track the touch’s movement as the user drags, calculate the horizontal (X-axis) delta of that movement, and convert it into a rotation angle applied directly to the GameObject’s Z-axis. This maps the natural left/right drag motion to the expected rotation direction.
Complete C# Script
Attach this script to your target 2D GameObject:
using UnityEngine; public class TouchRotate2D : MonoBehaviour { [SerializeField] private float rotationSpeed = 0.5f; // Adjust in Inspector for sensitivity private void Update() { // Handle touch input if (Input.touchCount > 0) { Touch activeTouch = Input.GetTouch(0); switch (activeTouch.phase) { case TouchPhase.Moved: // Grab the horizontal movement of the touch float touchDeltaX = activeTouch.deltaPosition.x; // Apply rotation around Z-axis—negative sign matches intuitive drag direction transform.Rotate(0, 0, -touchDeltaX * rotationSpeed); break; } } } }
Key Details to Note
- Sensitivity Control: Tweak the
rotationSpeedvalue in the Inspector to make rotation faster or slower. Higher values mean more rotation per pixel dragged. - Intuitive Direction: The negative sign in
transform.Rotateensures dragging left rotates the object counterclockwise, and dragging right rotates it clockwise. Flip the sign if you prefer the opposite behavior. - Editor Testing: To test with a mouse in the Unity Editor, add this block inside the
Update()method:// Optional: Mouse support for editor testing if (Input.GetMouseButton(0)) { float mouseDeltaX = Input.GetAxis("Mouse X"); transform.Rotate(0, 0, -mouseDeltaX * rotationSpeed * 10); // Multiply by 10 to match touch sensitivity }
Bonus: Clamp Rotation (Optional)
If you want to limit the object’s rotation to a specific range (e.g., -90° to 90°), add this line right after the transform.Rotate call to fix Euler angle wrap-around issues:
// Clamp rotation between -90 and 90 degrees (adjust values as needed) Vector3 currentRotation = transform.eulerAngles; currentRotation.z = Mathf.Clamp(currentRotation.z > 180 ? currentRotation.z - 360 : currentRotation.z, -90, 90); transform.eulerAngles = currentRotation;
内容的提问来源于stack exchange,提问作者CHAMCHOUN

