[英]Unity: RigidBody2D, how to move GameObject in straight lines (no curves)
大家好,我對 Unity 很陌生,也很困惑。
我正在創建一個自上而下、無重力的測試游戲,類似於 PacMan(即考慮角色在直線上的移動)。
目前,我正在嘗試以直線(無曲率)移動 object(見圖)。
我的游戲對象附加了RigidBody2D
,以及Linear
、 Angular
和Gravity
設置為 0。
我目前正在通過增加力來控制我的游戲對象:
private Rigidbody2D _playerRB2D;
public float _speed;
private void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector2 movement = new Vector2(moveHorizontal, moveVertical);
_playerRB2D.AddForce(movement * _speed);
}
這個想法是游戲 object不會減速,所以一直在運動(直線)。 與物體的碰撞顯然也很重要!
任何要查看的幫助或信息都會有很大幫助,謝謝!
這個想法基本上是重置在每個改變方向上施加在rigidBody2D上的力。 實際上,您必須測試從水平方向輸入的方向是否大於 x 軸的垂直方向,以及 y 軸的逆方向,因此如果為真,則將相反的方向更改為 0f。 你通常會:
Vector2 movement = new Vector2(moveHorizontal < moveVertical ? moveHorizontal: 0f, moveVertical < moveHorizontal ? moveVertical: 0f);
_playerRB2D.velocity = movement * speed;
編輯:通過測試輸入值,您可以使用模擬 controller 移動 RigidBody2D,從而如您所願!
Unity 有一個內置的物理引擎,可以根據速度(和碰撞等)計算運動。通過使用 Rigidbody2D.AddForce,您可以增加剛體的速度。 這意味着,如果您按向上箭頭,然后按向右箭頭,則按向上箭頭的速度保持不變,從而導致對角速度和彎曲路徑。 如果你想要直線,你可以使用 Rigidbody2D.velocity或者只使用 Transform.translate。
_playerRB2D.velocity = movement * _speed;
編輯:你說碰撞很重要,所以保持剛體
或刪除剛體2D組件並使用
transform.Translate(movement * _speed);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.