向目标射击子弹

时间:2015-07-23 09:46:45

标签: c# unity3d game-physics

我使用团结并试图让我的子弹向目标射击。我点击了鼠标,我想向那个方向发射子弹。

我已经获得了鼠标点击的坐标并尝试计算向量。然后我尝试在我的位置实例化子弹预制件(它有刚体部件并位于场景前面)然后朝着鼠标的方向射击。

我可以看到我的对象在我的层次结构窗格中实例化但无法在屏幕上看到任何内容!

我不确定我是否正确处理向量(newb here),但如果我点击Yoshi的头部,我就会得到(-2.0, -0.4)。听起来不错吗?

代码:

void fireBullet(float mousePositionX, float mousePositionY)
    {

        Vector2 position = new Vector2(mousePositionX, mousePositionY);
        position = Camera.main.ScreenToWorldPoint(position);
        GameObject bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity) as GameObject;
        bullet.transform.LookAt(position);
        Debug.Log(position);
        bullet.rigidbody2D.AddForce(bullet.transform.forward * 1000);
    }

enter image description here

编辑:

void fireBullet(float mousePositionX, float mousePositionY)
    {


        Vector2 position = new Vector2(mousePositionX, mousePositionY);

        //screen space to world space
        position = Camera.main.ScreenToWorldPoint(new Vector3(position.x, position.y, -1));

        Vector2 direction = (Input.mousePosition - transform.position).normalized;

        //instantiate bullet
        GameObject bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity) as GameObject;

        //rotates the transform so forward vector points at targets current position
        bullet.transform.LookAt(position);
        Debug.Log(position);

        //fire the bullet
        bullet.rigidbody2D.AddForce(direction * 1000);
    }

2 个答案:

答案 0 :(得分:0)

如果您的相机朝向Z方向,则您的子弹正在使用错误的Z坐标生成。正如我在评论中提到的,你应该改变你的代码来告诉Unity哪个z位置放入你的子弹(因为对于每个屏幕位置,有无限多个相应的世界位置,大多数在摄像机的视图平面之外)。这是您需要传递给ScreenToWorldPoint的第三个值,否则偏移量将为零,并且对象将在相机顶部生成:

float zPos = something; // Wherever your other scene objects are, more or less
float camZPos = Camera.main.transform.position.z;
float zOffset = zPos - camZPos;
Vector3 bulletPosition = Camera.main.ScreenToWorldPoint(
    new Vector3(mousePositionX, mousePositionY, zOffset));

答案 1 :(得分:0)

我尝试复制你的场景,并在那里发现了一个可能的问题。你的bulletPrefab是否设置好预制件的前向矢量和你的精灵在同一个平面上?通过将子弹预制件放在场景视图中来验证这一点。如果没有,你必须设置它。

如果您的子弹的前向矢量垂直于精灵平面,如下例所示,当您向Yoshi发射子弹时,精灵将不可见。

enter image description here

通过将精灵放在另一个GameObject内来解决这个问题,并将此GameObject设为bulletPrefab。像这样:

enter image description here enter image description here