![](/img/trans.png)
[英]Set rigidbody.velocity to direction of mouse in Unity2d: Updated Version
[英]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.