2016-01-23 133 views
0

我創建了我的第一個統一的遊戲,我有一個敵人角色,從左上角移動到右側完全正常,但後來我有一個預製(該字符的複印件)那突然停止移動,但是當我拿起他與位置工具角色開始再次移動,然後再次停止。我正在使用Unity 5.2.3f1版本遊戲人物停止移動

下面是我使用

public class EnemyPatrol : MonoBehaviour { 

    public float moveSpeed; 
    public bool moveRight; 

    public float wallCheckRadius; 
    public Transform wallCheck; 
    public LayerMask whatIsWall; 
    private bool hittingWall; 

    private bool notAtEdge; 
    public Transform edgeCheck; 

    // Use this for initialization 
    void Start() { 

    } 

    // Update is called once per frame 
    void Update() { 
     //GetComponent<Rigidbody2D>().velocity=new Vector2(3,0); 
     //Debug.Log("Premikam se desno "+GetComponent<Rigidbody2D>().velocity); 

     //hittingWall = Physics2D.OverlapCircle (wallCheck.position, wallCheckRadius, whatIsWall); 
     wallCheckRadius = 0.6f; 
     notAtEdge = Physics2D.OverlapCircle (edgeCheck.position, wallCheckRadius, whatIsWall); 


     hittingWall = false; 
     //notAtEdge = true; 
     if (hittingWall || !notAtEdge) { 
      moveRight = !moveRight; 
      Debug.Log ("Zadene steno " + hittingWall + " Ni na robu " + notAtEdge); 
     } 
     // Prepreci krozenje igralca (zabavna zadeva) 
     GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeRotation; 

     if (moveRight) { 
      transform.localScale = new Vector3 (1f, 1f, 1f); 
      GetComponent<Rigidbody2D>().velocity=new Vector2(3,0); 
      Debug.Log("Premikam se desno "+GetComponent<Rigidbody2D>().velocity); 
     } else { 
      transform.localScale = new Vector3 (-1f, 1f, 1f); 
      GetComponent<Rigidbody2D>().velocity=new Vector2(-3,0); 
      Debug.Log("Premikam se levo"+GetComponent<Rigidbody2D>().velocity); 
     } 
    } 
} 

的代碼,這是它的外觀在遊戲中的畫面。

enter image description here

- 圈撞機顯示了「殺戮地帶」的撞機範圍內,如果玩家接觸它他死了。

- 箱撞機檢查,如果他是在地面上

- 綠球檢查,如果他得到了拐角

- 黃球檢查,如果他撞牆(我在這裏並沒有真正使用,只是爲了以防萬一我需要它)

回答

1

你不能在Update中做物理。

......好吧,你可以,但是這打破了Unity。各種奇怪的東西都會發生。在文檔中的任何地方,他們都明確表示「不這樣做」。

對於涉及物理的任何事情,請使用FixedUpdate。


另外,您應該將腳本附加到探測器本身。您應該將它們作爲觸發器來實施,並使用OnTriggerEntered等。

讓Unity物理部門爲您做好工作 - 這就是它的存在。

例如閱讀關於:http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerEnter2D.html