0

我正在尝试使用 Rigidbody2D.MovePosition 使角色移动,但它仅适用于水平移动。

我期待正常的逼真跳跃,但是当我移动角色时它会随机跳跃并且不会使用空格按钮跳跃。

我的墙跳也不起作用。

预计角色会跳起来并水平移动到对面的墙上。确实如此,但功率非常小。

我正在使用 Unity 2019.4.16f

using UnityEngine;

public class D2Movement : MonoBehaviour
{
public byte moveSpeed;
public byte plusJumpCount;
public float jumpStrength;
public byte wallJumpStrenght;
public bool isGrounded = false;
byte origJumpCount;
bool isWallL;
bool isWallR;
Rigidbody2D rb;

void Start()
{
    rb = GetComponent<Rigidbody2D>();
}

void Update(){
    Vector2 velocity = new Vector2(Input.GetAxis("Horizontal") * moveSpeed, 0f);
    if(Input.GetKeyDown(KeyCode.Space) && (plusJumpCount > 0 || isGrounded == true)){
        velocity.y = jumpStrength;
        plusJumpCount -= 1;
    }
    
    if(isGrounded == true){
        velocity.y = 0;
        plusJumpCount = origJumpCount;
    } else {
        velocity.y -= 10 * Time.deltaTime;
    }
    
    if(Input.GetKey(KeyCode.LeftShift)){
        rb.MovePosition((Vector2)transform.position + velocity * Time.deltaTime * 2);
    } else {
        rb.MovePosition((Vector2)transform.position + velocity * Time.deltaTime);
    }
}

void OnCollisionStay2D(Collision2D other){
    if(other.collider.tag == "Wall_L"){
        isWallL = true;
        if(Input.GetKeyDown(KeyCode.Space)){
            rb.AddForce(new Vector2(wallJumpStrenght, jumpStrength / 2), ForceMode2D.Impulse);
        }
    }
    
    if(other.collider.tag == "Wall_R"){
        isWallR = true;
        if(Input.GetKeyDown(KeyCode.Space)){
            rb.AddForce(new Vector2(-wallJumpStrenght, jumpStrength / 2), ForceMode2D.Impulse);
        }
    }
}

void OnCollisionExit2D(Collision2D other){
    isWallL = false;
    isWallR = false;
}
}
4

2 回答 2

1

我真的不明白为什么您会在这段代码中遇到这些错误,但是发生了一些不寻常的事情。也许试试

  • 使用内置重力。您可以在刚体组件中设置重力。
  • 决定使用 rb.MovePosition 还是 rb.addForce 跳跃
  • 保持代码简单 --> isWallL 和 isWallR 并没有真正使用,避免重复代码
  • 在 FixedUpdate() 中做与物理相关的事情
  • 避免幻数(使用 const)

编写更好的代码会减少错误!

也可以考虑直接设置 rb.velocity 。

于 2021-02-09T22:43:05.310 回答
0

Pikramag Channel,你有没有为collision2D添加相关的Component,比如Rigidbody2D和boxcollision?只有我看到您的编辑器代码,我不确定是否会出错。

于 2021-02-02T16:22:49.600 回答