Hi y’all,
I’m tryna make a 2d top down shooter, and the player movement and stuff works fine. The only problem is that when it shoots the bullet, the player moves a lil bit like it has kickback, and I’m not sure if it’s my rigidbody body components that are weird or if it’s the script. Also, any tips to clean up the code would be helpful too.
My rigidbody is dynamic for both of them and all the drags and gravity are 0. ![]()
public float speed = 3f;
Rigidbody2D rb2d;
Vector2 movement;
Vector3 mousePos;
float angle;
public GameObject bullet;
// Use this for initialization
void Start () {
rb2d = gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
MovePlayer();
RotatePlayer();
if(Input.GetButton("Fire1"))
{
//Debug.Log("Shoot");
ShootBullet();
}
}
void MovePlayer()
{
float x = Input.GetAxis("Horizontal");
float y = Input.GetAxis("Vertical");
movement = new Vector2(x, y);
rb2d.velocity = movement * speed;
}
void RotatePlayer()
{
Vector3 mousePos = Input.mousePosition;
Vector3 playerPos = Camera.main.WorldToScreenPoint(transform.position);
Vector3 offset = new Vector3(mousePos.x - playerPos.x, mousePos.y - playerPos.y);
angle = Mathf.Atan2(offset.x, offset.y) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.back);
}
void ShootBullet()
{
Vector3 shootDirection;
shootDirection = Input.mousePosition;
shootDirection.z = 0.0f;
shootDirection = Camera.main.ScreenToWorldPoint(shootDirection);
shootDirection = shootDirection - transform.position;
float bulletSpeed = .5f;
Rigidbody2D bulletInstance = Instantiate(bullet.GetComponent<Rigidbody2D>(), transform.position, Quaternion.Euler(new Vector3(0, 0, 0))) as Rigidbody2D;
bulletInstance.velocity = new Vector2(shootDirection.x * bulletSpeed, shootDirection.y * bulletSpeed);
}