2017-01-23 99 views
0

雖然我知道我的方式C#我是在遊戲開發和Unity中使用它的新手。我想要讓球彈跳起來。我可以很容易地讓球左右移動,但是當我的代碼從「滾動」改變爲「反彈」時,我得到下面的結果:(球沿對角線不上下)enter image description here統一:向上和向下移動Sprite

但是我想:

enter image description here

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

     if (moveDown) { 
      transform.localScale = new Vector3 (-1f, 1f, 1f); 
      GetComponent<Rigidbody2D>().velocity = new Vector2 (speed, GetComponent<Rigidbody2D>().velocity.x); 
     } else { 
      transform.localScale = new Vector3 (1f, 1f, 1f); 
      GetComponent<Rigidbody2D>().velocity = new Vector2 (-speed, GetComponent<Rigidbody2D>().velocity.x); 
     } 
    } 

我相信答案一定是簡單的東西,但一整天后,我的大腦已經到玉米粥。任何人都可以建議嗎?

詩左至右代碼工作是這樣的:

transform.localScale = new Vector3 (-1f, 1f, 1f); 
      GetComponent<Rigidbody2D>().velocity = new Vector2 (speed, GetComponent<Rigidbody2D>().velocity.y); 
+0

'var vel = GetComponent ().velocity; vel.y * = -1; GetComponent ().velocity = vel;' – Gusman

+0

這似乎接近我所需要的,但並不完美。球慢慢地死了,但每秒都會有一點點震動,看起來就像在振動。我需要調查發生了什麼。 – Phil3992

+0

只有當球擊中頂部或底部時,纔會調用代碼,而不是在每一幀上。 – Gusman

回答

0

一個Vector2有兩個組件; X和Y.速度的「X」分量代表物體的水平速度(左/右)。速度的「Y」分量表示物體的垂直速度(上/下)。

要向上和向下移動直接,速度的「X」分量必須爲「零」(0),否則對象將繼續水平以及垂直移動,從而形成對角線。

當爲Vector2調用構造方法時,傳入兩個參數;第一個參數是「X」值,第二個參數是「Y」值。在您的示例代碼中,您會在第一個(X)參數中傳遞一個非零值,從而產生對角線移動。

+0

當我嘗試這個: transform.localScale = new Vector2(0,1f); GetComponent ().velocity = new Vector2(speed,GetComponent ().velocity.x); 我的球只是消失 – Phil3992

+0

@ Phil3992多數民衆贊成多數民盟這是因爲你正在調整球的比例爲0 ...基本上是一個32x32像素的球1仍然是32x32像素的比例,所以改變x比例爲0使球0x32(大小*比例),所以如果球沒有大小或單位它不會是可見的,如果你有球上的對撞機,你prolly也有一個抱怨這個警告。 – Eddge

-1

您可以凍結的x位置是否有幫助。

enter image description here

+0

這不是一個答案,它是一個評論。 – Gusman