- Home /
How do I spawn a bullet correctly and add velocity to it?
In my game each player has a shootpoint so the game knows where I want the bullet to be spawned, but I encountered some problems.
Every time when player 1 joins, it spawns a bullet at the spawn location of player 1 and the shootpoint. When player 2 spawns and shoots, the bullet only spawns from the shootpoint. Both player 1 and 2 use the same script. Here is my code:
public void Shoot(InputAction.CallbackContext context){
Instantiate(Bullet, shootpoint.position, shootpoint.rotation);
if(gameObject.transform.rotation.eulerAngles.y == -180){
Bullet.gameObject.GetComponent<Rigidbody2D>().velocity = Vector2.left * force;
} else if(gameObject.transform.rotation.eulerAngles.y == 0){
Bullet.gameObject.GetComponent<Rigidbody2D>().velocity = Vector2.right * force;
}
}
As you can see I am using the new inputsystem and I am also trying to make the bullet fly a little, you know like a real bullet... In the beginning I did it with 2 separate scripts but I think it's better if I do it with 1 script.
Does anyone know how to fix that bug and/or make the bullet fly?
Answer by GeroNL · Feb 24, 2021 at 02:18 PM
Try to change these line :
Instantiate(Bullet, shootpoint.position, shootpoint.rotation);
to be :
Instantiate(Bullet, shootpoint.position, shootpoint.rotation, give it the transformation that you want);
Hope it help.
I used the following line:
Instantiate(Bullet, shootpoint.position, shootpoint.rotation, BRB.velocity = Vector2.left * force);
(The BRB is the bullet rigidbody) When I do that, it gives me an error that I can't use Unity.Vector2, I need to use Unity.Transform.
is there a transform method that I can use to make the bullet fly?
That place is just for tansform, like position and rotation,. try to just change the line, if you want force move, you need to keep it into variable :
Rigidbody clone;
clone = Instantiate(.....)
then use the clone to give it velocity or etc.