C# 如何在Unity上限制android的触摸移动
我正在为android设备开发一款2D赛车游戏。我已经为我的汽车编码了触摸运动。但问题是这辆车开得太远了。我如何限制汽车的运动,我的意思是我如何为我的汽车编码,使其保持在屏幕上(屏幕分辨率为480*800,汽车精灵的最大位置为4.2,最小位置为-4.2)。这是我的C#汽车控制器脚本C# 如何在Unity上限制android的触摸移动,c#,android,unity3d,C#,Android,Unity3d,我正在为android设备开发一款2D赛车游戏。我已经为我的汽车编码了触摸运动。但问题是这辆车开得太远了。我如何限制汽车的运动,我的意思是我如何为我的汽车编码,使其保持在屏幕上(屏幕分辨率为480*800,汽车精灵的最大位置为4.2,最小位置为-4.2)。这是我的C#汽车控制器脚本 using UnityEngine; using System.Collections; public class carController : MonoBehaviour { public floa
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;
}
}
}
}
使用UnityEngine;使用系统集合;
公共类carController:单行为{
公共交通速度;
//每帧调用一次更新
无效更新(){
如果(Input.touchCount==1){
触摸=输入。触摸[0];
如果(触摸位置x<屏幕宽度/2){
transform.position+=Vector3.left*carSpeed*Time.deltaTime;
}
else if(触摸位置x>屏幕宽度/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;
}
}
void更新(){
如果(Input.touchCount==1){
触摸=输入。触摸[0];
如果(触摸位置x<屏幕宽度/2){
transform.position+=Vector3.left*carSpeed*Time.deltaTime;
}
else if(触摸位置x>屏幕宽度/2){
transform.position+=Vector3.right*carSpeed*Time.deltaTime;
}
矢量3位置=变换位置;
位置x=主夹(位置x,-4.2f,4.2f);
变换位置=位置;
}
}