- Home /
2D Shooting Prefab
So I need a prefab shooting device, I am making a clone of the online game Defly.io , I have gotten the movement system down and the character is always looking at the mouse, However when ever I shoot one of two things happens, The bullet goes directly to the mouse like a heat seaking missle no matter where I move mouse (I want it fire in a certain direction and the bullet just goes strraight) or if I change my code it will only go direction Ex. I use a vector2.right whenever I shoot it only goes right public float speed; //private Rigidbody2D rb; void Start(){ // rb = GetComponent<Rigidbody2D> (); } void Update (){ rb.AddForce (Vector3.right * speed); Vector3 mousePosition = Input.mousePosition; mousePosition = Camera.main.ScreenToWorldPoint (mousePosition); transform.position = Vector2.MoveTowards (transform.position, mousePosition, speed * Time.deltaTime); if (transform.position.x == mousePosition.x && transform.position.y == mousePosition.y) { Destroy (gameObject); }
Answer by MT369MT · May 25, 2018 at 05:43 PM
Hi, is this script attached to the Bullet right? If you want to make the bullet go in the position of the mouse when you shot you must store in a variable the last Mouse Position for example in Start().
public Rigidbody2D rb; public float speed; public Vector3 mousePosition; Start () { rb = GetComponent<Rigidbody2D>(); speed = 5; mousePosition = Input.mousePosition; mousePosition = Camera.main.ScreenToWorldPoint (mousePosition); } Update () { rb.velocity = mousePosition.normalize * speed; }
It tells me Vector3 doesn't contain a definition for 'normalize' its asking me if im missing an assembly refernce
Your answer
Follow this Question
Related Questions
Shooting around defense position without contact 1 Answer
Shooting at an object 2 Answers
Bullet disappears for no reason 2 Answers
Instantiate after setting values? 0 Answers