- Home /
Trying to get a player to shoot in Unity 2D.
Hello.
I have a player that I am trying to get to shoot in a Unity 2D game. I would like the bullet to shoot toward the mouse clicking on the screen. From looking around, I came up with this code, but, the problem with it is that the closer to the player that I click, the slower the bullet moves, to almost a stop if I click on the player. What am I doing wrong?
private float _bulletSpeed = 5.0f;
_shootDirection = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - _player.transform.position);
Rigidbody2D bulletInstance = Instantiate(_bullet, _player.transform.position, Quaternion.identity) as Rigidbody2D;
bulletInstance.velocity = new Vector2(_shootDirection.x * _bulletSpeed, _shootDirection.y * _bulletSpeed);
Thank you.
Answer by privatecontractor · Feb 06 at 12:37 PM
Hi @IntrovertGenius,
Belive that you issue is due to diffrent Vector2 length. So if click point is far from player - Vector2 will have bigger length, if point of click will be close - Vecto2 will have smaller length. Answer for question is Vector2.Normalize - so giving him length of 1 with same direction... then we need to give bullet speed so we just multiplaying this Vector2 by speed, so to conclude, instead of:
bulletInstance.velocity = new Vector2(_shootDirection.x * _bulletSpeed, _shootDirection.y * _bulletSpeed);
write:
bulletInstance.velocity = new Vector2.Normalize(_shootDirection.x, _shootDirection.y) * _bulletSpeed;
Hope that will do, let me know.
Yes, that worked with a slight adjustment. For some reason it didn't accept it as you typed it.
bulletInstance.velocity = new Vector2(_shootDirection.x, _shootDirection.y).normalized * _bulletSpeed;
Thank you very much!
Hi @IntroGenius,
For some reason it didn't accept it as you typed it.
Sry my bad, when typing on phone instead of code editor not always able to use code precise enough. But glad could help!
No, it is all good, and perfect. :) I was able to figure it out from what you posted. Thank you so much.
Your answer
