You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 / 2 creates a resolution-agnostic split between left and right, so it works on any Android device.
  • Touch Phases:
    • TouchPhase.Began triggers movement only once per tap, which is great for tap-to-shift controls.
    • TouchPhase.Stationary keeps 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 a foreach on Input.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 08:32:38