我有一个为网络打造的突破风格游戏,它使用鼠标左右移动球拍,点击球时发射。我试图实现的是在我的Android设备上运行正确的控件,因为此时测试它不能正常工作,因为我在手机上触摸屏幕的那一刻球发射和桨控制移动奇怪!这里有球拍和球的脚本,如果有人可以帮助或指出我,我会非常感激它,因为我只是团结一致。
public class Paddle : MonoBehaviour {
private Ball ball;
void Start(){
ball = GameObject.FindObjectOfType<Ball> ();
}
void Update () {
MoveWithMouse ();
}
void MoveWithMouse(){
Vector3 paddlePos = new Vector3 (4.7f, this.transform.position.y, 0f);
float mousePosInBlocks = Input.mousePosition.x / Screen.width * 16;
paddlePos.x = Mathf.Clamp (mousePosInBlocks, 4.7f, 11.3f);
this.transform.position = paddlePos;
}
}
public class Ball : MonoBehaviour {
private Paddle paddle;
private bool hasStarted = false;
private Vector3 paddleToBallVector;
void Start () {
paddle = GameObject.FindObjectOfType<Paddle> ();
paddleToBallVector = this.transform.position - paddle.transform.position;
}
// Update is called once per frame
void Update () {
if (!hasStarted) {
//lock ball relative to the paddle
this.transform.position = paddle.transform.position + paddleToBallVector;
//wait for mouse press to start
if (Input.GetMouseButtonDown (0)) {
hasStarted = true;
this.GetComponent<Rigidbody2D> ().velocity = new Vector2 (2f, 10f);
}
}
}
void OnCollisionEnter2D(Collision2D collision){
Vector2 tweak = new Vector2 (Random.Range(0f,0.2f),Random.Range(0f,0.2f));
if (hasStarted) {
GetComponent<AudioSource> ().Play ();
GetComponent<Rigidbody2D>().velocity += tweak;
}
}
}
答案 0 :(得分:1)
球发射的原因是因为Input.GetMouseButtonDown(0)
在移动设备上触摸屏幕时也会返回true。为了抵消这种情况,您可能希望使用特定于移动设备的控件。如果你想举起手指时释放球......你可以这样做:
if (Input.GetTouch(0).phase == TouchPhase.Ended)
要使用手指位置移动球拍,您可以在更新方法中输入类似的内容:
if (Input.TouchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
Touch touch = Input.GetTouch(0);
paddlePos = new Vector3(touch.position.x, transform.position.y, transform.position.z);
transform.position = paddlePos;
}