0
我想讓我的球員在與我的對象發生碰撞時在各個方向上彈跳,我知道當它撞擊到我的對象的左側時,我的球員會被擊退回到左側,右側,但我怎麼能包括我的對象的頂部和底部。如果我沒有任何意義,請看這些圖片(X = 0 Y = 1)和(X = 0 Y = -1)。 (http://noobtuts.com/content/unity/2d-pong-game/vector2_directions.png)Unity:各方向擊倒
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);
}
}
謝謝,但似乎沒有發生任何事情。我確信這是觸發器被檢查。 –
您可以插入一些'Debug.Log'語句來查看得到的速度值是什麼? (並確保該方法被調用)? – Draco18s
恩,我該怎麼做? –