OneBigLoser
OneBigLoser
发布于 2024-06-15 / 9 阅读
0
0

Unity X/Z轴移动射线碰撞检测+旋转物体 C#代码参考

CapsuleCast可以替换成你需要的Cast类型,这里使用的是新的inputSystem,你可以替换成自己的旧的,

//  Vector2 inputVector = gameInput.GetMovementVectorNormalized(); 例如下面的
 float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
private void Update()
{
    Vector2 inputVector = gameInput.GetMovementVectorNormalized();
    Vector3 moveDirection = new Vector3(inputVector.x, 0.0f, inputVector.y);
    isWalking = moveDirection != Vector3.zero;
    float moveDistance = moveSpeed * Time.deltaTime;
    float playerRadius = 0.7f;
    float playerHeight = 2f;

    Vector3 capsuleStart = transform.position;
    Vector3 capsuleEnd = transform.position + Vector3.up * playerHeight;

    // 检查主要方向的移动
    bool canMove = !Physics.CapsuleCast(capsuleStart, capsuleEnd, playerRadius, moveDirection, moveDistance);

    // 如果主要方向被阻挡,尝试沿X轴方向移动
    if (!canMove)
    {
        Vector3 moveDirX = new Vector3(moveDirection.x, 0, 0);
        canMove = !Physics.CapsuleCast(capsuleStart, capsuleEnd, playerRadius, moveDirX, moveDistance);

        // 如果X轴方向可以移动,设置新的移动方向
        if (canMove)
        {
            moveDirection = moveDirX;
        }
        else
        {
            // 如果X轴方向被阻挡,尝试沿Z轴方向移动
            Vector3 moveDirZ = new Vector3(0, 0, moveDirection.z);
            canMove = !Physics.CapsuleCast(capsuleStart, capsuleEnd, playerRadius, moveDirZ, moveDistance);

            // 如果Z轴方向可以移动,设置新的移动方向
            if (canMove)
            {
                moveDirection = moveDirZ;
            }
        }
    }

    // 如果可以移动,更新角色位置
    if (canMove)
    {
        transform.position += moveDirection * moveDistance;
    }

    // 平滑地改变角色朝向
    if (isWalking)
    {
        transform.forward = Vector3.Slerp(transform.forward, moveDirection, 10 * Time.deltaTime);
    }
}


评论