- Home /
Bullets flying in a random direction.
Hey so, I am currently struggling to set up my bullets travelling.
The ship that fires the bullets rotates and flys on X/Z axis which I realise is dumb. Either way, when I shoot my bullets they sometimes behave erratically. https://gyazo.com/6deac90d8cc3b4750a7713ed1c99d602
The player has a location for where to spawn the bullets and this is the code to spawn the bullets.
void Shoot ()
{
var bulletToShoot = (GameObject)Instantiate (
bullet,
bulletSpawnLocation.position,
bulletSpawnLocation.rotation);
Destroy (bulletToShoot, 8.0f);
}
Next the bullet itself is a prefab with the bullet controller code as such:
void Update () {
transform.Rotate (0, player.transform.rotation.y, 0);
transform.Translate (0, 0, bulletSpeed * Time.deltaTime);
bullet.transform.position += transform.forward * Time.deltaTime * bulletSpeed;
}
I am unsure why it does this so any help would be appreciated.
Answer by qobion · Oct 15, 2018 at 06:45 PM
You are rotating your bullets constantly in your update function. So just rotate it once at Start() and then move forward.
void Start(){
transform.Rotate (0, player.transform.rotation.y, 0);
}
void Update () {
bullet.transform.position += transform.forward * Time.deltaTime * bulletSpeed;
}
I made that change and they still move very erratically
I think your bullet variable is prefab…
So try this
void Start(){
transform.Rotate (0, player.transform.rotation.y, 0);
}
void Update () {
transform.position += transform.forward * Time.deltaTime * bulletSpeed;
}
Answer by brunopagno · Oct 15, 2018 at 06:51 PM
I can't test right now but I believe your problem is that you are using "transform.forward", and since you are rotating your game object the forward direction in changing.
bullet.transform.position += transform.forward * Time.deltaTime * bulletSpeed;
You could possibly solve storing the "forward" when the bullet is instantiated and then using that value in your calculation.
Vector3 _localForward;
void Start() {
_localForward = transform.forward;
}
void Update() {
...
bullet.transform.position += _localForward * Time.deltaTime * bulletSpeed;
}
Let me know if it works for you.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
2D Shooting right only. Doesn't flip direction with character 1 Answer
2d bullet shot at bullet emitter 0 Answers