繁体   English   中英

如何在Unity上限制Android的触摸移动

[英]How to restrict touch movement for android on Unity

我正在为Android设备开发2D赛车游戏。 我已经为我的汽车编码了触摸运动。 但是问题是汽车已经超越了轨道。 我如何限制汽车的移动,我的意思是如何编码使我的汽车停留在屏幕上(屏幕分辨率为480 * 800,汽车子画面的最大位置为4.2,最小位置为-4.2)。 这是我的C#汽车控制器脚本。

using UnityEngine; using System.Collections;

public class carController : MonoBehaviour {

     public float carSpeed;


     // Update is called once per frame
     void Update () {

         if (Input.touchCount == 1) {

             Touch touch = Input.touches[0];
             if(touch.position.x < Screen.width/2){
                 transform.position += Vector3.left * carSpeed * Time.deltaTime;


             }
             else if(touch.position.x > Screen.width/2){
                 transform.position += Vector3.right * carSpeed * Time.deltaTime;

             }

         }
     }


}

立即的解决方案是使用这样的钳位功能,因为您知道在计算所需的运动之后的最大值和最小值。

 void Update () {

     if (Input.touchCount == 1) {

         Touch touch = Input.touches[0];
         if(touch.position.x < Screen.width/2){
             transform.position += Vector3.left * carSpeed * Time.deltaTime;


         }
         else if(touch.position.x > Screen.width/2){
             transform.position += Vector3.right * carSpeed * Time.deltaTime;

         }
         Vector3 position = transform.position;
         position.x = Mathf.Clamp(position.x, -4.2f, 4.2f);
         transform.position = position;

     }
 }

暂无
暂无

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

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