Search code examples
c#game-physicsunity-game-engine

Shooting a projectile but goes in wrong direction - 2D game


I am trying to make a simple game where I am shooting a projectile when the user touches the screen, I first spawn 8 projectiles (sprites) and when the user touches the screen I would like the top projectile to fly in the touch direction. I was able to do this; However, every time I shoot, the projectile goes in the wrong direction, here is an image which will illustrate the issue.

Projectile

Obviously the image is still here but the object will continue flying until it goes out of the screen and then gets destroyed.

Here is the code snippet that handles this

GameplayController.cs

if (Input.GetMouseButtonDown(0))
    {
        Vector3 position = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);
        position = Camera.main.ScreenToWorldPoint(position);

        GameObject target;
        target = new GameObject();
        target.transform.position = position;


        Arrow comp = currentArrows[0].GetComponent<Arrow>();
        comp.setTarget(target.transform);
        comp.GetComponent<Arrow>().arrowSpeed = 12;
        comp.GetComponent<Arrow>().shoot = true;
        currentArrows.RemoveAt(0);
        Destroy(target);
    }

I know I am getting the mouse input here and not the phone touch and that's fine for me, later I will convert it to the touch input.

Arrow.cs

public bool shoot = false;
public float arrowSpeed = 0.0f;
public Vector3 myDir;
public float speed = 30.0f;
private Transform target;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if(shoot)
    {
        transform.position += transform.right * arrowSpeed * Time.deltaTime;
    }

}


public void setTarget(Transform targetTransform)
{
    this.target = targetTransform;
    Vector3 vectorToTarget = target.position - transform.position;
    float angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
    Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
    transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * speed);
}

private void OnBecameInvisible()
{
    print("Disappeared");
    Destroy(gameObject);
    Gameplay.instance.isShooting = false;
}

Solution

  • Vector3 position = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0);

    I think that your problem is that you're getting the screen coordinates by click, not the world coordinates, which is actually two different things. In order to direct your projectile correctly you need to convert your screen coordinates to world like it's done here.

    The next thing is how you move the projectile:

    transform.position += transform.right * arrowSpeed * Time.deltaTime;
    

    You're moving the projectile to the right and then rotating it somehow. Maybe you should try to move it with Vector3.Lerp, which will be easier and rotate it with Transform.LookAt.