Unity:如何将两个 Vector3 相乘? [已关闭]

问题描述 投票:0回答:3

我正在尝试在 Unity 中创建第一人称角色控制器。当尝试使用

Vector3
计算速度时,我收到一条错误消息,指出不可能将两个
Vector3
相乘:

Vector3 velocity = (transform.forward * currentDir.y * transform.right * currentDir.x) * walkSpeed * Vector3.up * velocityY;

Operator '*' cannot be applied to operands of the type 'Vector3' and 'Vector3'

为什么

Vector3
结构缺少乘法运算符,以及如何将这个
Vector3
链相乘在一起?

c# unity-game-engine
3个回答
3
投票

您不能将向量与

*
相乘,因为这是标量运算。您可以将向量乘以标量,这意味着增加其大小,但是向量与
*
标量运算符相乘没有意义。 您需要使用带有 Vector3.Dot 的 dotProduct 或带有 Vector3.Cross 的 crossProduct,具体取决于您想要执行的操作。

考虑到

transform.forward
transform.up
是游戏对象在世界坐标系中的局部轴,因此它们是向量。与
Vector3.up
相同,即 (0,1,0)。因此,如果您使用
*
链接其中任何一个,则不应编译。

当您错误地尝试此操作时,您可以检查编译器告诉您的内容:

Vector3 whatever = Vector3.up * Vector3.zero;

->
Operator '*' cannot be applied to to operands of type Vector3 and Vector3

此外,对于一行或备用操作来说并不是什么大问题,但为了提高效率,首先将所有标量相乘,然后将所得标量与向量相乘以减少操作量是有意义的。


1
投票

您可以使用 Vector3.Scale - 如果您需要的话。

将两个向量按分量相乘。

结果中的每个分量都是 a 乘以 b 的相同成分。

https://docs.unity3d.com/ScriptReference/Vector3.Scale.html


1
投票

其他答案重点关注两个

Vector3
之间有哪些运算符,但它们在您的用例中都没有真正意义。

从你所拥有的来看,在我看来,实际上你只是想要

+
而不是
*
喜欢

Vector3 velocity = (transform.forward * currentDir.y + transform.right * currentDir.x) * walkSpeed + Vector3.up * velocityY;
© www.soinside.com 2019 - 2024. All rights reserved.