Hi everyone! I’m trying to create a simple first persone shooter game. I imported the first person character controller from the standard unity asset, than I gave to my player a machine gun. Than I imported a bullet (Ammu Pack | 3D Weapons | Unity Asset Store) and made it shoot with this script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun_1ControllerScript : MonoBehaviour {
public int Ammo, Ammo_max = 20, AmmoPack, AmmoPack_max = 5;
Animator anim;
public GameObject bulletPrefab;
public Transform bulletSpawn;
// Use this for initialization
void Start () {
Ammo = Ammo_max;
AmmoPack = AmmoPack_max;
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
}
private void FixedUpdate()
{
//-------------------------------------------------
if (Input.GetKey(KeyCode.Mouse0)) //Fire
{
if (!anim.GetCurrentAnimatorStateInfo(0).IsName("MachineGun_reload")) //is he's not reloading...
{
if (Ammo > 0)
{
anim.SetBool("isShooting", true);
fire();
Ammo -= 1;
}
else if (AmmoPack > 0)
{
anim.SetTrigger("DoReload");
Ammo = Ammo_max;
AmmoPack -= 1;
}
else
{
//no ammo at all!
}
}
else
{
//He's reloading! you can't shoot!
}
}
else
{
anim.SetBool("isShooting", false);
}
if (Input.GetKey(KeyCode.LeftShift))
anim.SetBool("Aim", true);
else
anim.SetBool("Aim", false);
if (Input.GetKey(KeyCode.LeftShift)) //call aim()
aim(true);
else
aim(false);
}
void fire() //throw bullets!
{
// spawn the bullet
var bullet = (GameObject)Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
// Add velocity to the bullet
bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * 6;
// Destroy the bullet after 5 seconds
Destroy(bullet, 5.0f);
}
void aim(bool b) //aim
{
if (b)
transform.localPosition = new Vector3 (-0.035f, -0.341f, 0);
else
transform.localPosition = new Vector3 (0.118f, -0.46f, 0.3f);
}
void OnGUI() //prints Ammo & AmmoPack on screen
{
GUI.Label(new Rect(10, 10, 100, 20), Ammo.ToString());
GUI.Label(new Rect(30, 10, 100, 20), "|");
GUI.Label(new Rect(40, 10, 100, 20), AmmoPack.ToString());
}
float cos(float n)
{
return Mathf.Cos(n);
}
float sin(float n)
{
return Mathf.Sin(n);
}
}
I set “bulletPrefab” to the prefab of my bullet and “bulletSpawn” to the transform of SpawnPoint, a child of my gun, placed at the end of the barrel. it has rotation (0, -90, 0) because if set on 0,0,0 it shot on the right instead of forward. But if I shoot, the bullet goes in the right direction, but it is orientated to the sky!
I made bullets bigger so you can see them better… I tried to rotate my spawnpoint everywhere, but I didn’t fix it… What should I do?
Thank you in advance! bye!