我有一个Android游戏,用户通过触摸屏幕的左右两侧来移动玩家。我在Android上试过游戏,一切正常。但有一天它停止工作:按钮工作但我无法通过触摸屏幕两侧来控制播放器。我试图重新安装Unity,删除Library文件夹,甚至尝试其他操作系统。它没有帮助。我该如何修复我的项目?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MovingPlayer : MonoBehaviour
{
public float playerSpeed;
public float maxPos = 2.7f;
Vector3 position;
public uiManager ui;
public AudioManager am;
public Text coinCount;
int coin;
bool currntPlatformAndroid = false;
Rigidbody2D rb;
public GameObject particleSystemPrefab;
void Awake()
{
rb = GetComponent<Rigidbody2D>();
#if UNITY_ANDROID
currntPlatformAndroid = true;
#else
currentPlatformAndroid = false;
#endif
am.playerSound.Play();
}
// Use this for initialization
void Start()
{
coin = 0;
position = transform.position;
}
// Update is called once per frame
void Update()
{
if (currntPlatformAndroid == true)
{
TouchMove();
//AccelerometerMove();
}
else
{
position.x += Input.GetAxis("Horizontal") * playerSpeed * Time.deltaTime;
position.x = Mathf.Clamp(position.x, -2.7f, 2.7f);
transform.position = position;
}
position = transform.position;
position.x = Mathf.Clamp(position.x, -2.7f, 2.7f);
transform.position = position;
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "CubeObstacle")
{
//Destroy (gameObject);
foreach (ContactPoint2D contact in col.contacts)
{
Instantiate(particleSystemPrefab, contact.point, Quaternion.identity);
}
//gameObject.SetActive(false);
GameOverActivated();
ui.gameOverActivated();
am.playerSound.Stop();
}
if (col.gameObject.tag == "Coin")
{
Destroy(col.gameObject);
coin += 1;
coinCount.text = coin.ToString();
Debug.Log("Coin");
}
}
public void GameOverActivated()
{
Time.timeScale = 0;
PlayerPrefs.SetInt("coins", PlayerPrefs.GetInt("coins") + coin);
}
void AccelerometerMove()
{
float x = Input.acceleration.x;
if (x < -0.1f)
{
MoveLeft();
}
else if (x > 0.1f)
{
MoveRight();
}
else
{
SetVelocityZero();
}
}
void TouchMove()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
float middle = Screen.width / 2;
if (touch.position.x < middle && touch.phase == TouchPhase.Began)
{
MoveLeft();
}
else if (touch.position.x > middle && touch.phase == TouchPhase.Began)
{
MoveRight();
}
}
else
{
SetVelocityZero();
}
}
public void MoveLeft()
{
rb.velocity = new Vector2(-playerSpeed, 0);
}
public void MoveRight()
{
rb.velocity = new Vector2(playerSpeed, 0);
}
public void SetVelocityZero()
{
rb.velocity = Vector2.zero;
}
}
答案 0 :(得分:1)
您不需要使用Input.Touches
,这应该可以正常工作:
void Update()
{
#if UNITY_EDITOR
position.x += Input.GetAxis("Horizontal") * playerSpeed * Time.deltaTime;
position.x = Mathf.Clamp(position.x, -2.7f, 2.7f);
transform.position = position;
#else
if (Input.GetMouseButton(0))
{
if (Input.mousePosition.x > Screen.width/2)
{
MoveRight();
}
else
{
MoveLeft()
}
}
else
{
SetVelocityToZero();
}
#endif
}
希望这会有所帮助:)