1
\$\begingroup\$

I've applied the below script to a gun object to instantiate bullets to the direction of the mouse position.

The bullet collision is not getting triggered since the bullet has been rotated.

How to solve this.

void FixedUpdate()
    {

        mousePosition = Input.mousePosition;
        mousePosition.z = 0.0f;

        //Gun Rotation

        objectPosition = Camera.main.WorldToScreenPoint(transform.position);

        mousePosition.x = mousePosition.x - objectPosition.x;
        mousePosition.y = mousePosition.y - objectPosition.y;

        angle = Mathf.Atan2(mousePosition.y, mousePosition.x) * Mathf.Rad2Deg - 90;

        Vector3 rotationVector = new Vector3(0, 0, angle);
        transform.rotation = Quaternion.Euler(rotationVector);

        //Gun Rotation

        if (Input.GetMouseButtonDown(0))
        {
            GameObject bullet = (GameObject)Instantiate(bulletObject, transform.position, transform.rotation);
            bullet.transform.LookAt(mousePosition);
            bullet.GetComponent<Rigidbody2D>().AddForce(bullet.transform.forward * bulletSpeed);
        }

    }
\$\endgroup\$
  • \$\begingroup\$ Is the Pivot point of the bullet sprite set to Center? \$\endgroup\$ – jgallant Oct 7 '15 at 11:46
  • \$\begingroup\$ yes, its in the center \$\endgroup\$ – AvenashKrish Oct 7 '15 at 14:43
0
\$\begingroup\$

LookAt is a 3D operation. If you change your view to 3D, you'll see that the face of the sprite has been rotated in 3D space to face the target:

enter image description here

Since LookAt is defined as changing the forward vector (i.e. the blue arrow in the image) to point at the desired target, this isn't something you're going to be able to use for 2D operations.

Instead, just use the same code you're using to point your gun object in the same direction. bullet.rotation = Quaternion.Euler(new Vector3(0, 0, angle));

(If your gun-pointing code isn't working, then that's an entirely different situation altogether.)

\$\endgroup\$
  • \$\begingroup\$ Thanks alot @ketura. The below code solved the problem. ` bullet.transform.rotation = Quaternion.Euler(new Vector3(0,0,angle + 90)); bullet.GetComponent<Rigidbody2D>().AddForce(bullet.transform.right * bulletSpeed); ` \$\endgroup\$ – AvenashKrish Oct 10 '15 at 11:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.