Unity 3D第三人称相机开发遇CS0103错误:targetAngle未定义
问题解决:CS0103 targetAngle不存在于当前上下文
错误原因
targetAngle是在if(direction.magnitude >= 0.1f)代码块内部声明的局部变量,作用域仅局限于该代码块。当你在代码块外的Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;语句中访问它时,编译器找不到这个变量,因此抛出CS0103错误。
修复步骤
- 将
targetAngle的声明移到if代码块之外,确保它的作用域覆盖到后续使用它的代码; - 修正Start方法里的错误:
_playerMove是bool类型,你却给它赋值GetComponent<PlayerMovement>(),这会导致类型不匹配错误,直接删除这句即可。
修改后的完整代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { public CharacterController controller; public Transform cam; public float speed = 12f; public float gravity = -9.81f; public float jumpHeight = 3f; public float _doubleJumpMultiplier = 1.5f; public float turnSmoothTime = 0.1f; private float turnSmoothVelocity; public Transform groundCheck; public float groundDistance = 0.4f; public LayerMask groundMask; Vector3 velocity; bool isGrounded; private bool _canDoubleJump = false; bool _playerMove = false; private void Start() { // 移除错误的赋值语句:_playerMove是bool类型,不能赋值PlayerMovement组件 } void Update() { isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask); if(isGrounded && velocity.y < 0) { _canDoubleJump = true; velocity.y = -2f; } else { if(Input.GetButtonDown("Jump") && _canDoubleJump) { velocity.y = 3f * _doubleJumpMultiplier; _canDoubleJump = false; } } float vertical = Input.GetAxisRaw("Vertical"); float horizontal = Input.GetAxisRaw("Horizontal"); Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized; // 提前声明targetAngle并初始化默认值 float targetAngle = transform.eulerAngles.y; if(direction.magnitude >= 0.1f) { // 这里不再重新声明,直接赋值 targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y; float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime); transform.rotation = Quaternion.Euler(0f, angle, 0f); } Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward; controller.Move(moveDir * speed * Time.deltaTime); if(Input.GetButtonDown("Vertical") && isGrounded && _canDoubleJump) { _playerMove = true; } else if(!Input.GetButtonDown("Vertical") && isGrounded && _canDoubleJump) { _playerMove = false; } if(Input.GetButtonDown("Horizontal") && isGrounded && _canDoubleJump) { _playerMove = true; } else if(!Input.GetButtonDown("Horizontal") && isGrounded && _canDoubleJump) { _playerMove = false; } if(Input.GetButtonDown("Jump") && isGrounded) { velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity); } velocity.y += gravity * Time.deltaTime; controller.Move(velocity * Time.deltaTime); } }
额外说明
把targetAngle的初始值设为transform.eulerAngles.y,可以让玩家在静止时保持当前朝向,避免无输入时移动方向跳转到世界正前方。
内容的提问来源于stack exchange,提问作者RedWolf
相关产品推荐
相关产品推荐

