2017-09-06 63 views
0

我希望我的對象永遠向目標方向移動或直到它碰撞,碰撞部分我已經處理它;但是,我在運動部分遇到問題。翻譯對象直到碰撞

我第一次嘗試使用的代碼

Vector2 diff = target - transform.position; 
float angle = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg; 
transform.rotation = Quaternion.Euler(0.0f, 0.0f, angle); 

這些線路這完美的作品和我的對象,我希望它的方向旋轉旋轉我的目標。 在我更新的方法,我有以下

if (isMoving) 
    { 
     Vector2 f = transform.forward; 
     transform.position = Vector3.MoveTowards(transform.position, target + Vector3.forward, speed * Time.deltaTime); 
    } 

現在這個運行,但未能完成目標,我知道爲什麼,這是有道理的,但不知道如何解決它。物體以正確的方向移動,但我不希望它停在目標上,我希望它繼續前進。

我也試過

rb.MovePosition(rb.position + f * Time.deltaTime * speed); 

RB是rigidbody2D

以及

rb.AddForce(rb.position + f * Time.deltaTime * speed); 

但在這兩種情況下,物體旋轉,但從來沒有移動

我也用翻譯和MovePosition的行爲相同

P.S.這是一個2D遊戲

+0

發佈完整的代碼,包括更新,碰撞觸發等... – Isma

+0

@Isma謝謝你,我可以通過使用直線方程來解決它。我回答了我的問題,如果你想看看這種方法。 –

回答

0

看過網絡後,我沒有找到任何真正符合我所尋找的內容的東西,您無法永遠翻譯運動對象(顯然,您必須處理該對象應該得到的東西在某個點或某處銷燬,但這不是問題)。所以我繼續,並決定寫我自己的圖書館,以使這個簡單。我能夠使用直線方程實現我的目標。簡單的我採取了這些步驟來解決我的問題。

  1. 在啓動我得到2點間的斜率
  2. 計算y截距
  3. 使用具有固定的X值(步驟)的直線方程平移對象,每一個x值找到對應的y值並將對象翻譯成它。
  4. 在FixedUpdate中重複步驟3,就是這樣。

當然還有更多的情況,處理x = 0的情況,這會給斜坡0或y = 0等分......我解決了庫中的所有問題。對於任何感興趣的人,你可以在這裏查看EasyMovement

如果你不想要庫,那麼這裏是一個簡單的代碼。

//Start by Defining 5 variables 
private float slope; 
private float yintercept; 
private float nextY; 
private float nextX; 
private float step; 
private Vector3 direction; //This is your direction position, can be anything (e.g. a mouse click) 

開始方法

//step can be anything you want, how many steps you want your object to take, I prefer 0.5f 
step = 0.5f; 

//Calculate Slope => (y1-y2)/(x1-x2) 
slope = (gameObject.transform.position.y - direction.y)/(gameObject.transform.position.x - direction.x); 

//Calculate Y Intercept => y1-x1*m 
yintercept = gameObject.transform.position.y - (gameObject.transform.position.x * slope); 

現在FixedUpdate

//Start by calculating the nextX value 
//nextX 
if (direction.x > 0) 
    nextX = gameObject.transform.position.x + step; 
else 
    nextX = gameObject.transform.position.x - step; 

//Now calcuate nextY by plugging everything into a line equation 
nextY = (slope * nextX) + yintercept; 

//Finally move your object into the new coordinates 
gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, new Vector3(nextX, nextY, 0), speed * Time.deltaTime); 

請記住,這不會做繁重,有很多的條件這需要考慮。