1
\$\begingroup\$

My game is a 2D, top-down game where you aim with the mouse and the gun follows it. I'm trying to get the bullet to go in the direction of where the mouse is. The code will be a component of the bullet prefab. here my code:

public class BulletBehavior : MonoBehaviour {

public float speed;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    GetComponent<Rigidbody2D>().velocity = new Vector2(speed, GetComponent<Rigidbody2D>().velocity.y);
}


private void OnTriggerEnter2D(Collider2D collision)
{
    Destroy(gameObject);
}

}

\$\endgroup\$
1
\$\begingroup\$

use this code it will lock the mouse position

  this.transform.position = Input.mousePosition; 

and then add your bullet direction to follow it.

\$\endgroup\$
  • \$\begingroup\$ It is better if you convert the screen coordinates to world coordinates before assigning to position \$\endgroup\$ – Luis Masuelli Apr 13 '18 at 15:58
  • \$\begingroup\$ And how would I have the bullet direction follow it? Also, how do I convert the screen coordinates to world coordinates? \$\endgroup\$ – Conner Apr 13 '18 at 20:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.