我在我的播放器网格中添加了一个角色控制器,但由于某种原因,角色控制器没有随着播放器网格移动。
这是角色移动的代码
// 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);
}
[在我开始和搬入之前的 CharacterController 和 Player Mesh 的图片
[1]:https ://i.stack.imgur.com/P3jzh.png [1]
[那是我进入游戏模式并移动]游戏]
[2]:https ://i.stack.imgur.com/Bg1g7.png [2]