繁体   English   中英

在Unity2d中将rigidbody.velocity设置为鼠标的方向

[英]Set rigidbody.velocity to direction of mouse in Unity2d

我想知道如何将rigidbody.velocity 设置为统一2d 中鼠标指针的方向。 我需要物体的初始速度在那个方向。 之后,它会受到重力的影响。 这是我尝试过的:

float maxVel = 10f
float posTotal = Input.mousePosition.x + Input.mousePosition.y
float xVel = Input.mousePosition.x / posTotal
float yVel = Input.mousePosition.y / posTotal
Vector3 velTotal = new Vector3(xVel * maxVel, yVel * maxVel, 0)

我已经反复尝试过,但 object 似乎在随机方向发射。

首先,您将两个鼠标轴相加,这不会创建Vector2 测试它

Debug.Log(Input.mousePostion.x);
Debug.Log(Input.mousePostion.y);
Debug.Log(posTotal);

总和没有什么真正有意义的。

改为使用Camera.ScreenToWorldPoint https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html

and substract the player.position from that WorldPoint like this https://docs.unity3d.com/Manual/DirectionDistanceFromOneObjectToAnother.html

得到一个方向。 您可以使用该操作中的Vector3在该方向上应用速度。

祝你好运

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM