Unity角色移动时Shift键切换音效异常问题及修复咨询
问题与解决
我需要实现按下左Shift键(对应Input.GetButton("Walk"))时实时切换为行走音效,松开时切回奔跑音效,但出现以下异常:
- 按住W键开始移动的同时按下左Shift键,音效不切换;
- 按住W键+左Shift键开始移动后松开左Shift键,音效也不切换。
将判断条件Input.GetButton("Walk")改为hAxis != 0、!Input.GetButton("Walk")改为vAxis != 0后,功能恢复正常。
相关代码如下:
void Move() { moveVec = new Vector3(hAxis, 0, vAxis).normalized; // Camera moveVec = cameraTransform.TransformDirection(moveVec); moveVec *= moveSpeed; moveVec.y = 0; if (isSide && moveVec == sideVec) { moveVec = Vector3.zero; } // move transform.position += moveVec * moveSpeed * (wDown ? 0.3f : 1f) * Time.deltaTime; // animation anim.SetBool("isRun", moveVec != Vector3.zero); anim.SetBool("isWalk", wDown); // sound if (moveVec != Vector3.zero) { if (Input.GetButton("Walk") && !isRunningSound) { Debug.Log("walk"); CancelInvoke(currentSound); currentSound = "WalkSound"; InvokeRepeating(currentSound, 0f, 0.7f); isRunningSound = true; } else if(!Input.GetButton("Walk") && !isRunningSound) { Debug.Log("run"); CancelInvoke(currentSound); currentSound = "RunSound"; InvokeRepeating(currentSound, 0f, 0.3f); isRunningSound = true; } } else { CancelInvoke(currentSound); isRunningSound = false; } } void RunSound() { audio.clip = audioRun; audio.Play(); } void WalkSound() { audio.clip = audioWalk; audio.Play(); }
内容的提问来源于stack exchange,提问作者Ori
相关产品推荐
相关产品推荐

