How to change the direction of the shot using the analog stick in a 2D game?

Hello friends.

I’m a beginner and I’m trying to create a shot mechanic in a 2d game where the bullets are directed using the analog control, however I am not able to keep the speed of the bullets constant regardless of the pressure applied to the analogs, when I apply little pressure to the controlle the bullet moves slowly.

public class Bullet : MonoBehaviour
{
    private Rigidbody2D bulletRb;
    public float speed = 80f;
    private float inputX, inputY;

    // Start is called before the first frame update
    void Start()
    {
        bulletRb = GetComponent<Rigidbody2D>();

        inputX = Input.GetAxisRaw("Horizontal");
        inputY = Input.GetAxisRaw("Vertical");
        if (inputX != 0f || inputY != 0f)
        {
            bulletRb.velocity = new Vector2(inputX * speed, inputY * speed);           
        } else {
            bulletRb.velocity = transform.right * speed;
        }
    }

    void OnBecameInvisible()
    {
        Destroy(gameObject);
    }
}

@LeoFeitosa

Did you try using Input.GetAxis instead of Input.GetAxisRaw? As raw versions of input will only give you on/off kind of results.

@eses
I tried using Input.GetAxis and unfortunately I have the same result

@LeoFeitosa

Maybe I did read your original post incorrectly… do you actually want to keep the speed of bullet consistent / same when firing it to any direction? Then you should normalize your direction vector and multiply it with your desired speed. This way you get consistent speed no matter which direction you are aiming in 2D:

bulletRb = GetComponent<Rigidbody2D>();

var dir = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")).normalized;

if (dir.magnitude > 0)
{
    bulletRb.velocity = dir * speed;
}
else
{
    bulletRb.velocity = transform.right * speed;
}
1 Like

Thank you very much @eses it worked as I expected, but apparently the image of the shot is leaving a ghost trail.

@LeoFeitosa

“but apparently the image of the shot is leaving a ghost trail.”

Well that sounds like a completely different issue… no idea what is going on it could be anything from your displays refresh to something related to graphics. Maybe take a screenshot with print screen.

@eses
It is strange, playing it seems to have a ghost trail but when I print the game screen there is no ghost.

@LeoFeitosa

Well then, that is just most likely your display, like I mentioned. Go do a “UFO test” for your display, and you see how slow/fast it is. There is nothing strange going on most likely, sideways movement just shows like that on LCD displays unless it has a relatively fast panel.

@eses
I did a test using this site https://www.testufo.com/ and apparently the ghosts decrease when there is more fps, do you know if there is any way to mitigate this?