Unity安卓端立方体转向控制改造:替换键盘AD为屏幕左右点击
Convert Unity Keyboard Control to Android Touch Input
Got it, let's tweak your code to work with Android touch input instead of keyboard keys. The core idea is splitting the screen into left/right halves and triggering movement based on which side the user taps or holds.
Here's the modified FixedUpdate method:
void FixedUpdate () { rb.AddForce (0, 0, forwardForce * Time.deltaTime); // Check if there's an active touch on the screen if (Input.touchCount > 0) { Touch touch = Input.GetTouch(0); // Grab the first touch (we'll ignore multi-touch for this simple setup) // Option 1: Trigger movement ONCE when the user starts tapping if (touch.phase == TouchPhase.Began) { // Split the screen at its horizontal midpoint if (touch.position.x > Screen.width / 2) { // Tap right half: apply rightward force rb.AddForce(sidewaysRight * Time.deltaTime, 0, 0, ForceMode.VelocityChange); } else { // Tap left half: apply leftward force rb.AddForce(sidewaysLeft * Time.deltaTime, 0, 0, ForceMode.VelocityChange); } } // Option 2: Continuous movement while the user holds their finger down // Uncomment this and comment Option 1 if you want hold-to-move behavior /* if (touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Stationary) { if (touch.position.x > Screen.width / 2) { rb.AddForce(sidewaysRight * Time.deltaTime, 0, 0, ForceMode.VelocityChange); } else { rb.AddForce(sidewaysLeft * Time.deltaTime, 0, 0, ForceMode.VelocityChange); } } */ } }
Quick Explanations:
- Screen Boundary:
Screen.width / 2creates a resolution-agnostic split between left and right, so it works on any Android device. - Touch Phases:
TouchPhase.Begantriggers movement only once per tap, which is great for tap-to-shift controls.TouchPhase.Stationarykeeps applying force while the user holds their finger down, if you prefer continuous movement.
- Multi-Touch: We're only using the first touch (
Input.GetTouch(0)) to keep things simple. If you need to handle multiple taps later, you can loop through all touches with aforeachonInput.touches.
Don't forget to test this on an actual Android device or use Unity's Android Emulator—you can click/drag in the emulator to simulate touch input!
内容的提问来源于stack exchange,提问作者Rodriquez
相关产品推荐
相关产品推荐

