Position wall of arrows in front of player

131 Views Asked by At

I am having difficulty positioning a wall of objects(arrows) in front of the player. What I want is a solid wall of arrows to be shot in front of the player perpendicular to the view. So far I have the spawning of the objects correct and the y-axis placement correct. Now I just need to get the z and x-axis alignment correct. My code is as follows:

void run()
{
    Vector3 pos = transform.position;
    Quaternion angle = transform.rotation;
    GameObject clone;

    float startx = pos.x;

    pos.y += 0.7f;
    pos.z += 2f;

    for(int y = 0; y < maxarrows; y++)
    {
        pos.y += 0.5f;

        for(int x = 0; x < maxarrows; x++)
        {
            pos.x -= 0.5f;

            clone = arrowPool.getArrowOld();
            if(clone != null)
            {
                clone.transform.position = pos;
                clone.transform.rotation = angle;
                clone.rigidbody.velocity = clone.transform.forward*force;
            }
        }

        pos.x = startx;
    }
}
1

There are 1 best solutions below

1
On BEST ANSWER

You're not taking into account the orientation of your player when you calculate the positions of all the arrows. What you could do is work in the player's local coordinate space and then transform to world space.

First we choose some points in the player's local coordinate space.

Vector3[] points = {
    Vector3(-1, 1, 0), // upper-left
    Vector3(1, 1, 0), // upper-right
    Vector3(-1, -1, 0), // lower-left
    Vector3(1, 1, 0), // lower-right
    Vector3(0, 0, 0) // centre
};

Now we need to transform these points into world space. We can do this using Unity's Transform::TransformPoint function, which just multiplies the passed point by the transform's localToWorldMatrix:

for (int i = 0; i < 5; ++i) {
    points[i] = transform.TransformPoint(points[i]);
}

Now you have the spawn positions for your arrows in world space.