Unity FPS游戏开发报错:Vector3与Vector3无法使用*运算符
Unity FPS 移动代码Vector3相乘报错解决办法
报错CS0019: Operator '*' cannot be applied to operands of type 'Vector3' and 'Vector3'的原因很明确——你在MovePlayer方法里错误地把两个Vector3类型的方向向量直接相乘了,C#不支持这种操作。
你原本的代码行:
moveDirection = orientation.forward * verticalInput * orientation.right * horizontalInput;
这行里orientation.forward * verticalInput得到的是Vector3,再乘以orientation.right(另一个Vector3)就触发了错误。
正确的做法是分别计算前后、左右方向的移动分量,再将两个分量相加,修改后的MovePlayer方法如下:
private void MovePlayer() { // 分别计算前后和左右的移动分量,再相加得到最终移动方向 moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput; rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force); }
简单解释下:
orientation.forward * verticalInput:根据垂直输入(W/S键)得到前后方向的移动向量orientation.right * horizontalInput:根据水平输入(A/D键)得到左右方向的移动向量- 把这两个向量相加,就得到了符合玩家输入的最终移动方向
这样修改后,代码就能正常运行,实现基于角色朝向的FPS移动逻辑了。
内容的提问来源于stack exchange,提问作者34bllurh
相关产品推荐
相关产品推荐

