我正在尝试使用 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;
}
}