简体   繁体   中英

How can I make my rigid body bullets shoot in a straight line no matter my mouse movement?

I'm making a very simple 3D game in Unity where I have this space shuttle I can move around in space around asteroids and I can shoot when pressing/holding the mouse button. I'm doing this by Instantiating a sphere at the "Emitter" transform.position and then just applying a forward Force to that bullet object. It all works fine, but the one thing I don't like and also don't know how to fix is how the bullets keep their position when shooting and moving the mouse left-right, instead of keeping a perfectly straight line at all times.

This is how it looks when I'm shooting and moving my camera at the same time:

Screenshot while shooting

Here's a gif for better visualization.

Right now it looks like I'm pissing lasers, which is never good. I tried making the bullet speed a lot faster, but then the bullets become harder and harder to see and it doesn't look as good.

This is the code by which I'm shooting the bullets:

private void Fire()
    {
        GameObject bullet = Instantiate(laserPrefab);
        GameObject bullet2 = Instantiate(laserPrefab);

        Physics.IgnoreCollision(bullet.GetComponent<Collider>(), shuttleCollider.GetComponent<Collider>());
        Physics.IgnoreCollision(bullet2.GetComponent<Collider>(), shuttleCollider.GetComponent<Collider>());

        bullet.transform.position = laserEmitter.position;
        bullet2.transform.position = laserEmitter2.position;
        /*Vector3 rotation = bullet.transform.rotation.eulerAngles;
        Vector3 rotation2 = bullet2.transform.rotation.eulerAngles;
        bullet.transform.rotation = Quaternion.Euler(rotation.x, transform.eulerAngles.y, rotation.z);
        bullet2.transform.rotation = Quaternion.Euler(rotation2.x, transform.eulerAngles.y, rotation2.z);*/

        bullet.GetComponent<Rigidbody>().AddForce(laserEmitter.forward * laserSpeed, ForceMode.Impulse);
        bullet2.GetComponent<Rigidbody>().AddForce(laserEmitter.forward * laserSpeed, ForceMode.Impulse);

        StartCoroutine(DestroyBulletAfterTime(bullet, bulletDeathTime, bullet2));
    }

Don't mind the commented lines, I was just messing around trying to see if I can get it to work. The shooting behaves the same with or without those commented lines.

Of course, a projectile based system will behave and look like a projectile system.

If you want laser behavior use a LineRenderer. Raycast where your laser line should end (either laser max distance or the point of hitting an object in range).

If you don't like the "static" looks of it, change the LineRenderer Material to something that changes over time (search for shaders/ LineRenderer effects).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM