[英]How to reverse gravity immediately?
我正在制作一個2D游戲。 我有一個立方體對象從屏幕頂部掉下來,我有立方體應該通過反轉重力通過的管道。
好吧,我的物體正在從屏幕頂部掉下來。 我點擊屏幕來反轉重力,但它不會立即上升:改變重力方向需要時間。 當我點擊屏幕時,我的物體繼續下落然后上升。 當我點擊屏幕時,我的動作正在形成U
形。 當它上升時也會發生同樣的事情:我點擊它下降,在這種情況下,我的運動形成了∩
的形狀。
我想要實現的是,當我點擊屏幕時,我的對象的運動有即時響應。
此外,我想要某種衰減、阻尼或平滑。
我試過這些例子沒有成功:
http://docs.unity3d.com/ScriptReference/Vector2.Lerp.html
http://docs.unity3d.com/Documentation/ScriptReference/Vector3.SmoothDamp.html
這是我的代碼:
public class PlayerControls : MonoBehaviour
{
public GameObject playerObject = null;
Rigidbody2D player;
public float moveSpeed;
public float up;
Vector2 targetVelocity;
void Start()
{
player = playerObject.GetComponent<Rigidbody2D>();
// Set the initial target velocity y component to the desired up velocity.
targetVelocity.y = up;
}
void Update()
{
for (int i = 0; i < Input.touchCount; i++)
{
Touch touch = Input.GetTouch(i);
if (touch.phase == TouchPhase.Ended && touch.tapCount == 1)
{
// Flip the target velocity y component.
targetVelocity.y = -targetVelocity.y;
}
}
}
void FixedUpdate()
{
// Ensure if moveSpeed changes, the target velocity does too.
targetVelocity.x = moveSpeed;
// Change the player's velocity to be closer to the target.
player.velocity = Vector2.Lerp(player.velocity, targetVelocity, 0.01f);
}
此腳本附加到下降的立方體。
當受到恆定力(在您的代碼中,重力)影響時,對象將沿拋物線運動。 您正在觀察拋物線: U
形。 為避免拋物線並獲得即時響應( V
形),請勿使用力。 用類似的東西替換gravityScale
代碼:
Vector2 velocity = player.velocity;
velocity.y = -velocity.y;
player.velocity = velocity;
這會反轉速度的 y 分量,使玩家向上移動。
你還提到你想解決這個問題。 我建議添加另一個變量:目標速度。
要實現這一點,請將Vector2 targetVelocity
添加到您的組件中。 然后,在每次FixedUpdate
期間,您可以從當前速度向目標速度進行插值以逐漸改變速度。 替換當前代碼中的這一行:
player.velocity = new Vector2(moveSpeed, player.velocity.y);
有了這個:
player.velocity = Vector2.Lerp(player.velocity, targetVelocity, 0.01f);
這將緩慢地將速度更改為與目標速度相同,從而平滑運動。 0.01f
是舊速度和玩家速度設置的新速度之間的位置。 選擇較大的數字可以更快地進行插值,選擇較小的數字可以更慢地改變方向。
然后,不要在點擊屏幕時更改velocity
,而是更改targetVelocity
。 確保targetVelocity
的x
分量等於moveSpeed
,否則對象根本不會水平移動!
結合這兩個更改, Start
和FixedUpdate
方法應如下所示:
void Start()
{
player = playerObject.GetComponent<Rigidbody2D>();
// Set the initial target velocity y component to the desired up velocity.
targetVelocity.y = up;
}
void Update()
{
for (int i = 0; i < Input.touchCount; i++)
{
Touch touch = Input.GetTouch(i);
if (touch.phase == TouchPhase.Ended && touch.tapCount == 1)
{
// Flip the target velocity y component.
targetVelocity.y = -targetVelocity.y;
}
}
}
void FixedUpdate()
{
// Ensure if moveSpeed changes, the target velocity does too.
targetVelocity.x = moveSpeed;
// Change the player's velocity to be closer to the target.
player.velocity = Vector2.Lerp(player.velocity, targetVelocity, 0.01f);
}
請注意,您不應在FixedUpdate
使用Input
,因為輸入每幀FixedUpdate
更新,而FixedUpdate
可能每幀運行多次。 這可能會導致輸入被讀取兩次,尤其是當幀速率變慢並且固定更新更可能需要每幀運行多次時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.