- Home /
How can I add a Vector2 to a Vector3?
I have a Vector2 that indicates an "offset" from a Vector3. I want to add the Vector2 to the Vector3 such that the x and y of the Vector2 are being added along the normal plane of the Vector3.
I am trying to simulate a shotgun spread. The Vector3 is the direction of the shotgun and the Vector2 is the random spread (from Random.insideUnitCircle)
Any ideas?
If you simply want to add the x and y from the Vector2 to the Vector3 you can do this: shotGunDir = new Vector3(shotGunDir.x + offset.x, shotGunDir.y + offset.y, shotGunDir.z);
But I want the vector2 to be added to the normal plane of the vector3. Like it needs to be perpendicular to the vector3
A i was too quick when reading your post. Sorry about that. Could you make a quick sketch and upload that demonstrates how you want the bullets to fly because i'm having a bit hard time getting a picture in my head what you want to archive.
Answer by Bunny83 · Apr 26, 2020 at 05:17 PM
Well since you want to simulate bullet spread the approach you've menioned isn't a great solution. First of all by adding the vector to your direction vector you will also change the vector length. So the greater the offset vector the longer the over all vector gets. Of course the result can be normalized but the random distribution isn't uniform.
As it is with most issues usually there's already a solution out there somewhere. In this case you can use my GetPointOnUnitSphereCap method. It does something similar to Random.onUnitSphere but restricts the output to a certain orientation with a max angle which defines the size of the "cap" on the unitsphere.
The original question had a quite nice image illustrating what he wanted, unfortunately he used an external image hoster and the image got deleted.
Answer by Snubber · Apr 26, 2020 at 10:43 PM
I finally figured it out.
forward
is the direction I am shooting in. rand
is the Vector2 offset. I turned the Vector2 into a Vector3 and applied the rotation of the transform to it (the rotation must be on the left of the *
) and added that to the forward direction.
forward + (transform.rotation * new Vector3(rand.x, rand.y, 0))
Your answer
Follow this Question
Related Questions
Vector2 Normalize ? 3 Answers
Get RaycastHit Local Coords (C#) 1 Answer
Get a position relative to a gameobject 0 Answers
Vector2 vs Vector3 performance? 2 Answers
Rotate Local Space Vector to World Space with heading vector 0 Answers