user11660804
user11660804

Reputation:

Make a projectile to rotate

in the game that I'm producing, the player can shoot and I'd like to make the projectile rotates continuously when the player shoot it. Each player have an empty gameobject called SpawBala which instantiates the projectile.

I'm using these lines of code to instantiate it, but the rotation is not working:

//instantiates the bullet
                 GameObject tiro = Instantiate(projetil, SpawBala.transform.position, SpawBala.transform.rotation);
                 Rigidbody BalaRigid = tiro.GetComponent<Rigidbody>();

                 if (SpawBala.tag == "Bala1" && gameManager.playerTurn == 1)
                 {
                     BalaRigid.AddForce(Vector3.forward * ProjetilVeloc);
                     BalaRigid.transform.Rotate(new Vector3(Bulletspeed * Time.deltaTime, 0, 0));
                     gameManager.PontoAcaop1--;
                 }

How could I solve it?

Upvotes: 0

Views: 429

Answers (1)

derHugo
derHugo

Reputation: 90813

Your call to Rotate only happens exactly once and rotates the object about a given amount.


Anyway since there is a Rigidbody in play you shouldn't set transforms via the transform component at all because it breaks the physics.

Rather always go through the Rigidbody component.


I actually would not use AddForce and for rotation btw AddTorque when spawning a bullet. You would have to calculate the required forces depending on the bullet's weight in order to get the desired velocity(s).

Instead rather set a fix initial velocity and for the rotation angularVelocity.

Also note that currently you are always shooting in global World-Space Z direction no matter how your SpawnBala object is oriented in space. You should rather use SpawnBala.transform.forward as direction vector:

BalaRigid.velocity = SpawnBala.transform.forward * ProjetilVeloc;
// Note that your variable names are confusing
// You should probably rename it to BulletRotationSpeed e.g.
BalaRigid.angularVelocity = SpawnBala.transform.right * Bulletspeed;

Upvotes: 2

Related Questions