问题描述
我在游戏中添加了蹲伏的能力。我这样做的方法是更改控制器高度和中心 y 值。问题是当我蹲在平台下方时,即使有足够的空间,玩家仍然会与平台发生碰撞。
如果我将控制器高度设置为蹲伏高度作为默认高度,玩家就可以毫无问题地从平台下方移动。虽然,如果我使用中心偏移会发生碰撞问题。
bool isCrouching; float defaultHeight; Vector3 localCameraPos;
private CharacterController controller = null;
private Camera camera;
void Start()
{
controller = GetComponent<CharacterController>();
camera = camera.main;
localCameraPos = camera.transform.localPosition;
defaultHeight = controller.height;
}
void Update()
{
isCrouching = Input.GetKey(KeyCode.C);
}
void FixedUpdate()
{
DoCrouch();
}
void DoCrouch()
{
var height = isCrouching ? defaultHeight / 2 : defaultHeight;
controller.height = Mathf.Lerp(controller.height,height,5 * Time.deltaTime);
controller.center = Vector3.down * (defaultHeight - controller.height) / 2.0f;
var camPos = new Vector3(0,camera.transform.localPosition.y,0);
camPos.y = Mathf.Lerp(camPos.y,localCameraPos.y - (defaultHeight - controller.height),5 * Time.deltaTime);
camera.transform.localPosition = camPos + localCameraPos;
}
玩家通过调用 CharacterController.move() 函数移动。
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
isWalking = !Input.GetKey(KeyCode.LeftShift);
Vector2 _inputVector = new Vector2(horizontal,vertical);
if (_inputVector.sqrMagnitude > 1) { _inputVector.normalize(); }
Vector3 desireMoveDir = transform.right * _inputVector.x;
desireMoveDir += transform.forward * _inputVector.y;
if (Physics.SphereCast(transform.position,controller.radius,Vector3.down,out RaycastHit hit,controller.height / 2f,1))
{
desireMoveDir = Vector3.ProjectOnPlane(desireMoveDir,hit.normal).normalized;
}
moveDirection = desireMoveDir * MoveSpeed;
controller.Move(moveDirection * Time.fixedDeltaTime);
}
我该如何解决这个问题?谢谢
解决方法
刚刚解决了这个问题。我将步进偏移设置为 0.7。将其更改为 0,解决了问题。只花了我两天...很好