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
}
`