2017-06-21 75 views
0

我是Unity新手,一直在關注如何製作Captain Blaster 2D遊戲教程,但是我想將其轉換爲Android,我想通過拖動他來控制玩家跨越一個手指在屏幕,不明白這有什麼錯我的代碼,任何幫助,感謝Android Drag Sprite代碼Unity 5

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 
using UnityEngine.SceneManagement; 

public class ShipControl : MonoBehaviour { 

    public float playerSpeed = 10f; 
    public GameControl gameController; 
    public GameObject bulletPrefab; 
    public float reloadTime = 1f; 

    private float elapsedTime = 0; 


    void Update() 
    { 

     elapsedTime += Time.deltaTime; 
     if (Input.touchCount >= 1) 
     { 
      foreach (Touch touch in Input.touches) 
      { 
       Ray ray = Camera.main.ScreenPointToRay (touch.position); 
       RaycastHit hit; 
       if (Physics.Raycast (ray, out hit, 100)) { 

       } 
      } 

     if (elapsedTime > reloadTime) 
     { 
      Vector3 spawnPos = transform.position; 
      spawnPos += new Vector3 (0, 1.2f, 0); 
      Instantiate (bulletPrefab, spawnPos, Quaternion.identity); 

       elapsedTime = 0f; 
     } 
     } 
    } 
    void OnTriggerEnter2D(Collider2D other) 
    { 
     gameController.PlayerDied(); 
    } 

} 
+0

嗯,代碼確定手指是部分,事實上,觸摸的東西是空的... – Draco18s

回答

1

我會做的是添加一個名爲「拖動」布爾和之後,你是否光線投射打什麼你也檢查命中對象是否爲玩家遊戲對象。 只要用戶沒有釋放觸摸 - 使玩家的剛體向觸摸位置移動(所以如果有任何障礙物,它不會直接穿過它們)。

代碼可能會是這樣的(你也應該增加一些定時檢查玩家釋放觸摸,並設置拖動布爾爲false):

public float playerSpeed = 10f; 
public GameControl gameController; 
public GameObject bulletPrefab; 
public float reloadTime = 1f; 

private float elapsedTime = 0; 

private bool dragging = false; 


void Update() 
{ 

    if (Input.touchCount >= 1) 
    { 
     foreach (Touch touch in Input.touches) 
     { 
      Ray ray = Camera.main.ScreenPointToRay (touch.position); 
      RaycastHit hit; 

      if (Physics.Raycast (ray, out hit, 100)) 
      { 
       if(hit.collider.tag == "Player") // check if hit collider has Player tag 
       { 
        dragging = true; 
       } 
      } 

      if(dragging) 
      { 
       //First rotate the player towards the touch (should do some checks if it's not too close so it doesn't glitch out) 
       Vector3 _dir = Camera.main.ScreenToWorldPoint(touch.position) - transform.position; 
       _dir.Normalize(); 

       float _rotZ = Mathf.Atan2(_dir.y, _dir.x) * Mathf.Rad2Deg; 
       transform.rotation = Quaternion.Euler(0f, 0f, _rotZ - 90); 

       //Move towards the touch 
       transform.GetComponent<Rigidbody>().AddRelativeForce(direction.normalized * playerSpeed, ForceMode.Force); 
      } 
     } 
    } 
}