Unity3d CharacterController Collider没有随着Player Mesh移动



我添加了一个角色控制器到我的玩家网格,但由于某些原因,角色控制器没有随着玩家网格移动。

这是字符移动的代码

// Vars
[SerializeField] private float moveSpeed;
[SerializeField] private float walkSpeed;
[SerializeField] private float runSpeed;
private Vector3 moveDirection;
private Vector3 velocity;
[SerializeField] private bool isGrounded;
[SerializeField] private float groundCheckDistance;
[SerializeField] private LayerMask groundMask;
[SerializeField] private float gravity;
[SerializeField] private float jumpHeight;
// Ref
private CharacterController controller;
private Animator anim;
private void Start()
{
controller = GetComponent<CharacterController>();
anim = GetComponentInChildren<Animator>();
}
private void Update()
{
Move();
if (Input.GetKeyDown(KeyCode.Mouse0))
{
StartCoroutine(Attack());
}
}
private void Move()
{
isGrounded = Physics.CheckSphere(transform.position, groundCheckDistance, groundMask);

if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float moveZ = Input.GetAxis("Vertical");
float moveY = Input.GetAxis("Horizontal");
moveDirection = new Vector3(moveY, 0, moveZ);
moveDirection = transform.TransformDirection(moveDirection);

if (isGrounded)
{
if (moveDirection != Vector3.zero && !Input.GetKey(KeyCode.LeftShift))
{
Walk();
}
else if (moveDirection != Vector3.zero && Input.GetKey(KeyCode.LeftShift))
{
Run();
}
else if (moveDirection == Vector3.zero)
{
Idle();
}
moveDirection *= moveSpeed;
if (Input.GetKeyDown(KeyCode.Space))
{
Jump();
}
}
controller.Move(moveDirection * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
private void Idle()
{
anim.SetFloat("Speed", 0, 0.1f, Time.deltaTime);
}
private void Walk()
{
moveSpeed = walkSpeed;
anim.SetFloat("Speed", 0.5f, 0.1f, Time.deltaTime);
}
private void Run()
{
moveSpeed = runSpeed;
anim.SetFloat("Speed", 1f, 0.1f, Time.deltaTime);
}
private void Jump()
{
velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
}
private IEnumerator Attack()
{
anim.SetLayerWeight(anim.GetLayerIndex("Attack Layer"), 1);
anim.SetTrigger("Attack");
yield return new WaitForSeconds(0.9f);
anim.SetLayerWeight(anim.GetLayerIndex("Attack Layer"), 0);
}

[在我开始和移动之前的字符控制器和播放器网格的图片

[1] https://i.stack.imgur.com/P3jzh.png [1]

[And That's after I enter game mode And move] game]

[2] https://i.stack.imgur.com/Bg1g7.png [2]

看起来玩家网格与玩家GameObject(因此也是角色控制器)是分离的。确保它是父级的,这样变换就会一起移动。

相关内容

  • 没有找到相关文章

最新更新