目標
我對 Unity 比較陌生,我希望我的角色能夠同時奔跑和跳躍,從而使角色沿對角線上升。
問題
然而,在對角色進行一些調整后,跳躍似乎清除了所有現有的速度,這意味著角色上升然后向一邊而不是同時兩個:

(我很抱歉,如果它有點難以看到)
代碼
這是我的角色移動腳本:
Rigidbody2D rb;
BoxCollider2D bc;
[Header("Run")]
float xInput = 0f;
public float maxRunSpeed;
public float acceleration;
[Space]
[Header("Jump")]
public float jumpHeight;
public float lowJumpHeight;
public float fallSpeed;
public float airControl;
[Space]
public LayerMask groundLayer;
public bool onGround;
[Space]
public Vector2 bottomOffset;
public Vector2 boxSize;
public float coyoteTime;
void Start() {
// Gets a reference to the components attatched to the player
rb = GetComponent<Rigidbody2D>();
bc = GetComponent<BoxCollider2D>();
}
void Update() {
Jump();
// Takes input for running and returns a value from 1 (right) to -1 (left)
xInput = Math.Sign(Input.GetAxisRaw("Horizontal"));
}
// Applies a velocity scaled by runSpeed to the player depending on the direction of the input
// Increaces the velocity by accerleration until the max velocity is reached
void FixedUpdate() {
rb.velocity = Math.Abs(rb.velocity.x) < Math.Abs(xInput) * maxRunSpeed ? rb.velocity new Vector2(acceleration * xInput, rb.velocity.y) * Time.deltaTime : new Vector2(xInput * maxRunSpeed, rb.velocity.y);
}
void Jump() {
// Checks whether the player is on the ground and if it is, replenishes coyote time, but if not, it starts to tick it down
coyoteTime = onGround ? 0.1f : coyoteTime - Time.deltaTime;
// Draws a box to check whether the player is touching objects on the ground layer
onGround = Physics2D.OverlapBox((Vector2)transform.position bottomOffset, boxSize, 0f, groundLayer);
// Adds an upwards velocity to player when there is still valid coyote time and the jump button is pressed
if (Input.GetButtonDown("Jump") && coyoteTime > 0) {
rb.velocity = Vector2.up * jumpHeight;
}
// Increases gravity of player when falling down or when the jump button is let go mid-jump
if (rb.velocity.y < 0 ) {
rb.velocity = Vector2.up * Physics2D.gravity.y * (fallSpeed - 1) * Time.deltaTime;
} else if (rb.velocity.y > 0 && !Input.GetButton("Jump")) {
rb.velocity = Vector2.up * Physics2D.gravity.y * (lowJumpHeight - 1) * Time.deltaTime;
}
}
很抱歉有很多不必要的代碼,只是我不確定是什么導致了問題,所以我不想洗掉任何東西。希望我的評論有意義嗎?
uj5u.com熱心網友回復:
發生這種情況是因為您直接使用 設定剛體的速度rb.velocity = Vector2.up * jumpHeight。所以這將消除所有現有的速度。
如果您只想為速度添加一個力而不是完全替換它,您可以使用Rigidbody2D.AddForce 之類的方法來做到這一點。
uj5u.com熱心網友回復:
而在其他情況下你保持你的速度值,只略微修改它們很難覆寫絕對velocity的
rb.velocity = Vector2.up * jumpHeight;
擦除任何速度X。
你可以簡單地保留你在另一個軸上的任何東西,只覆寫Y像
var velocity = rb.velocity;
velocity.y = jumpHeight;
rb.velocity = velocity;
或者
rb.velocity = new Vector2(rb.velocity.x, jumpHeight);
基本上與您FixedUpdate在水平方向上的操作方式相同。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/408550.html
標籤:
