- Home /
How to fire bullet in x-y direction in 2-D game?
I am using a gun GameObject to fire this bullet. The bullet needs to be a child of gun as it is moving with
Input.Getmouseposition. The bullet needs to fire simultaneously with the gun's movement. Ask for any more details. My player and gun are facing x-y direction.
This is my GunBehaviourScript.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GunBehaviourScript : MonoBehaviour { float angle; public GameObject bullet; // public float distance = 10; public Transform bulletSpawn; public float fireRate; private float nextFire=0; // Update is called once per frame void Update () { Vector3 pos = Input.mousePosition; pos.z = -(transform.position.x - Camera.main.transform.position.x); Vector3 objpos = Camera.main.ScreenToWorldPoint(pos); pos.x = Mathf.Clamp (pos.x, 15f, 20f) - objpos.x; pos.y = Mathf.Clamp (pos.y, -7f, 8f) - objpos.y; angle = ((Mathf.Atan2 (pos.y, pos.x) * Mathf.Rad2Deg-50)); transform.rotation = Quaternion.Euler(0, 0, -angle); if (Input.GetButton ("Fire1") && Time.time > nextFire) { nextFire = Time.time + fireRate; Instantiate(bullet, bulletSpawn.position, bulletSpawn.rotation); } } }
This is my mover.cs for bullet
using System.Collections; using System.Collections.Generic; using UnityEngine; public class mover : MonoBehaviour { public float speed; //public GameObject gameObject; //public Rigidbody rigidbody; // Use this for initialization void Start () { Rigidbody rigidbody = gameObject.GetComponent<Rigidbody> (); rigidbody.velocity = transform.forward * speed; } // Update is called once per frame }
You need to tidy up this code and post it using the code quotes, this is just plain unreadable...
Answer by Camilohoyos16 · Aug 16, 2017 at 05:06 PM
Maybe the problem is transform.forward when you assign the velocity, because generally, the forward of any gameobject is the z vector. So try to change that forward for the other option with transform.(somthing). Or maybe you just need to rotate image when the bull is instantiated. Make sure the direction movement of the bullet when you fire.
Your answer
Follow this Question
Related Questions
Shoot Bullet At Touch Position : 2D 1 Answer
2D Shooting & Direction 1 Answer
Problem creating a 2D scroller shooting game 2 Answers
Shoot second cell in 2d 0 Answers