I am wondering how to set the rigidbody.velocity to the direction of the mouse pointer in unity 2d. I need the objects initial velocity to be in that direction. Afterward, it will be affected by gravity. Here is what I tried:
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)
I have tried this repeatedly, but the object seems to fire in a random direction.
First you add up your two mouse axis and that does not create a Vector2
. Test it with
Debug.Log(Input.mousePostion.x);
Debug.Log(Input.mousePostion.y);
Debug.Log(posTotal);
the sum is nothing that really makes sense.
instead use 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
to get a direction. You can apply a velocity in that direction with the Vector3
from that operation.
Good luck
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.