2015-12-20 25 views
0

我想讓我的球員在與我的對象發生碰撞時在各個方向上彈跳,我知道當它撞擊到我的對象的左側時,我的球員會被擊退回到左側,右側,但我怎麼能包括我的對象的頂部和底部。如果我沒有任何意義,請看這些圖片(X = 0 Y = 1)和(X = 0 Y = -1)。 (http://noobtuts.com/content/unity/2d-pong-game/vector2_directions.pngUnity:各方向擊倒

public float xForceToAdd; 
public float yForceToAdd; 
// Use this for initialization 
void Start() { 

    } 

    // Update is called once per frame 
    void Update() { 

    } 
    void OnTriggerEnter2D(Collider2D other) { 
    if (other.gameObject.tag == "Player") 
    { 
     //Store the vector 2 of the location where the initial hit happened; 
     Vector2 initialHitPoint = new Vector2 (other.gameObject.transform.position.x, other.gameObject.transform.position.y); 
     float xForce = 0; 
     float yForce = 0; 
     //Grab our collided with objects rigibody 
     Rigidbody2D rigidForForce = other.gameObject.GetComponent<Rigidbody2D>(); 
     //Determine left right center of X hit 
     if (initialHitPoint.x > (this.transform.position.x + (this.transform.localScale.x /3))) 
     { 
     xForce = 1; 
     } 
     else if (initialHitPoint.x < (this.transform.position.x - (this.transform.localScale.x /3))) 
     { 
     xForce = -1; 
     } 
     else 
     { 
      xForce = 0; 
     } 
     if (initialHitPoint.y > (this.transform.position.y + (this.transform.localScale.y /3))) 
     { 
      yForce = 1; 
     } 
     else if (initialHitPoint.y < (this.transform.position.y - (this.transform.localScale.y /3))) 
     { 
      yForce = -1; 
     } 
     else 
     { 
      yForce = 0; 
     } 
     rigidForForce.velocity = new Vector2(xForce * xForceToAdd, yForce * yForceToAdd); 
    } 

} 

回答

0

做到這一點,而不是

void OnTriggerEnter2D(Collider2D other) { 
    if (other.gameObject.tag == "Player") { 
     Vector2 v = other.gameObject.transform.position - this.transform.position; 
     //Grab our collided with objects rigibody 
     Rigidbody2D rigidForForce = other.gameObject.GetComponent<Rigidbody2D>(); 
     rigidForForce.velocity = v.normalized; 
    } 
} 

不是搞清楚,如果你應該去上/下/左/右,使用矢量數學函數。如果您只對推進正交方向感興趣,請對最後一行執行此操作

 boolean onX = Mathf.Abs(v.x) > Mathf.Abs(v.y); 
     rigidForForce.velocity = new Vector2(Mathf.Sign(v.x)*onX?1:0,Mathf.Sign(v.y)*onX?0:1); 
+0

謝謝,但似乎沒有發生任何事情。我確信這是觸發器被檢查。 –

+0

您可以插入一些'Debug.Log'語句來查看得到的速度值是什麼? (並確保該方法被調用)? – Draco18s

+0

恩,我該怎麼做? –