Recarregador de armas
5 participantes
SchultzGames :: UNITY 3D :: Resolvidos
Página 1 de 1
Recarregador de armas
Heae amigos blz
Estou aqui com um sistema de armas sao uma pistola e um rifre estou tentando fazer um carregador para elas mais nao deu certo um script das armas fica no Player e o outro em cada arma
Bom dia e obrigado
Estou aqui com um sistema de armas sao uma pistola e um rifre estou tentando fazer um carregador para elas mais nao deu certo um script das armas fica no Player e o outro em cada arma
- Código:
//script da arma
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Collider))]
[RequireComponent(typeof(Rigidbody))]
public class Weapon : MonoBehaviour
{
private Collider col { get { return GetComponent<Collider> (); } set { col = value; } }
private Rigidbody rigidBody { get { return GetComponent<Rigidbody> (); } set { rigidBody = value; } }
private Animator animator { get { return GetComponent<Animator> (); } set { animator = value; } }
private SoundController sc;
public enum WeaponType
{
Pistol, Rifle
}
public WeaponType weaponType;
[System.Serializable]
public class UserSettings
{
public Transform leftHandIKTarget;
public Vector3 spineRotation;
}
[SerializeField]
public UserSettings userSettings;
[System.Serializable]
public class WeaponSettings
{
[Header("-Bullet Options-")]
public Transform bulletSpawn;
public float damage = 5.0f;
public float bulletSpread = 5.0f;
public float fireRate = 0.2f;
public LayerMask bulletLayers;
public float range = 200.0f;
[Header("-Effects-")]
public GameObject muzzleFlash;
public GameObject decal;
public GameObject shell;
public GameObject clip;
[Header("-Other-")]
public GameObject crosshairPrefab;
public float reloadDuration = 2.0f;
public Transform shellEjectSpot;
public float shellEjectSpeed = 7.5f;
public Transform clipEjectPos;
public GameObject clipGO;
[Header("-Positioning-")]
public Vector3 equipPosition;
public Vector3 equipRotation;
public Vector3 unequipPosition;
public Vector3 unequipRotation;
[Header("-Animation-")]
public bool useAnimation;
public int fireAnimationLayer = 0;
public string fireAnimationName = "Fire";
}
[SerializeField]
public WeaponSettings weaponSettings;
[System.Serializable]
public class Ammunition
{
public int carryingAmmo;
public int clipAmmo;
public int maxClipAmmo;
}
[SerializeField]
public Ammunition ammo;
WeaponHandler owner;
bool equipped;
bool resettingCartridge;
[System.Serializable]
public class SoundSettings {
public AudioClip[] gunshotSounds;
public AudioClip reloadSound;
[Range(0, 3)] public float pitchMin = 1;
[Range(0, 3)] public float pitchMax = 1.2f;
public AudioSource audioS;
}
[SerializeField]
public SoundSettings sounds;
// Use this for initialization
void Start()
{
GameObject check = GameObject.FindGameObjectWithTag ("Sound Controller");
if (check != null) {
sc = check.GetComponent<SoundController> ();
}
}
// Update is called once per frame
void Update()
{
if (owner) {
DisableEnableComponents(false);
if (equipped) {
if (owner.userSettings.rightHand) {
Equip();
}
} else {
if (weaponSettings.bulletSpawn.childCount > 0) {
foreach (Transform t in weaponSettings.bulletSpawn.GetComponentsInChildren<Transform>()) {
if (t != weaponSettings.bulletSpawn) {
Destroy (t.gameObject);
}
}
}
Unequip(weaponType);
}
} else { // If owner is null
DisableEnableComponents(true);
transform.SetParent(null);
}
}
//This fires the weapon
public void Fire(Ray ray)
{
if (ammo.clipAmmo <= 0 || resettingCartridge || !weaponSettings.bulletSpawn || !equipped)
return;
RaycastHit hit;
Transform bSpawn = weaponSettings.bulletSpawn;
Vector3 bSpawnPoint = bSpawn.position;
Vector3 dir = ray.GetPoint(weaponSettings.range) - bSpawnPoint;
dir += (Vector3)Random.insideUnitCircle * weaponSettings.bulletSpread;
if(Physics.Raycast(bSpawnPoint, dir, out hit, weaponSettings.range, weaponSettings.bulletLayers))
{
HitEffects (hit);
if (hit.transform.root.GetComponent<CharacterStats> ()) {
hit.transform.root.SendMessage("Damage",weaponSettings.damage);
}
}
GunEffects ();
if (weaponSettings.useAnimation)
animator.Play(weaponSettings.fireAnimationName, weaponSettings.fireAnimationLayer);
ammo.clipAmmo--;
resettingCartridge = true;
StartCoroutine(LoadNextBullet());
}
//Loads the next bullet into the chamber
IEnumerator LoadNextBullet()
{
yield return new WaitForSeconds(weaponSettings.fireRate);
resettingCartridge = false;
}
void HitEffects(RaycastHit hit)
{
if (hit.collider.gameObject.isStatic)
{
if (weaponSettings.decal)
{
Vector3 hitPoint = hit.point;
Quaternion lookRotation = Quaternion.LookRotation(hit.normal);
GameObject decal = Instantiate(weaponSettings.decal, hitPoint, lookRotation) as GameObject;
Transform decalT = decal.transform;
Transform hitT = hit.transform;
decalT.SetParent(hitT);
Destroy(decal, Random.Range(15.0f, 20.0f));
}
}
}
void GunEffects()
{
if (weaponSettings.muzzleFlash)
{
Vector3 bulletSpawnPos = weaponSettings.bulletSpawn.position;
GameObject muzzleFlash = Instantiate(weaponSettings.muzzleFlash, bulletSpawnPos, Quaternion.identity) as GameObject;
Transform muzzleT = muzzleFlash.transform;
muzzleT.SetParent(weaponSettings.bulletSpawn);
Destroy(muzzleFlash, 2.0f);
}
if (weaponSettings.shell)
{
if (weaponSettings.shellEjectSpot)
{
Vector3 shellEjectPos = weaponSettings.shellEjectSpot.position;
Quaternion shellEjectRot = weaponSettings.shellEjectSpot.rotation;
GameObject shell = Instantiate(weaponSettings.shell, shellEjectPos, shellEjectRot) as GameObject;
if (shell.GetComponent<Rigidbody>())
{
Rigidbody rigidB = shell.GetComponent<Rigidbody>();
rigidB.AddForce(weaponSettings.shellEjectSpot.forward * weaponSettings.shellEjectSpeed, ForceMode.Impulse);
}
Destroy(shell, Random.Range(15.0f, 20.0f));
}
}
PlayGunshotSound ();
}
void PlayGunshotSound () {
if (sc == null) {
return;
}
if (sounds.audioS != null) {
if (sounds.gunshotSounds.Length > 0) {
sc.InstantiateClip (
weaponSettings.bulletSpawn.position, // Where we want to play the sound from
sounds.gunshotSounds [Random.Range (0, sounds.gunshotSounds.Length)], // What audio clip we will use for this sound
2, // How long before we destroy the audio
true, // Do we want to randomize the sound?
sounds.pitchMin, // The minimum pitch that the sound will use.
sounds.pitchMax); // The maximum pitch that the sound will use.
}
}
}
//Disables or enables collider and rigidbody
void DisableEnableComponents(bool enabled)
{
if(!enabled)
{
rigidBody.isKinematic = true;
col.enabled = false;
}
else
{
rigidBody.isKinematic = false;
col.enabled = true;
}
}
//Equips this weapon to the hand
void Equip()
{
if (!owner)
return;
else if (!owner.userSettings.rightHand)
return;
transform.SetParent(owner.userSettings.rightHand);
transform.localPosition = weaponSettings.equipPosition;
Quaternion equipRot = Quaternion.Euler(weaponSettings.equipRotation);
transform.localRotation = equipRot;
}
//Unequips the weapon and places it to the desired location
void Unequip(WeaponType wpType)
{
if (!owner)
return;
switch (wpType)
{
case WeaponType.Pistol:
transform.SetParent(owner.userSettings.pistolUnequipSpot);
break;
case WeaponType.Rifle:
transform.SetParent(owner.userSettings.rifleUnequipSpot);
break;
}
transform.localPosition = weaponSettings.unequipPosition;
Quaternion unEquipRot = Quaternion.Euler(weaponSettings.unequipRotation);
transform.localRotation = unEquipRot;
}
//Loads the clip and calculates the ammo
public void LoadClip()
{
int ammoNeeded = ammo.maxClipAmmo - ammo.clipAmmo;
if(ammoNeeded >= ammo.carryingAmmo)
{
ammo.clipAmmo = ammo.carryingAmmo;
ammo.carryingAmmo = 0;
}
else
{
ammo.carryingAmmo -= ammoNeeded;
ammo.clipAmmo = ammo.maxClipAmmo;
}
}
//Sets the weapons equip state
public void SetEquipped(bool equip)
{
equipped = equip;
}
//Sets the owner of this weapon
public void SetOwner(WeaponHandler wp)
{
owner = wp;
}
}
- Código:
//script do player
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class WeaponHandler : MonoBehaviour
{
private Animator animator { get { return GetComponent<Animator> (); } set { animator = value; } }
private SoundController sc;
public bool isAI;
[System.Serializable]
public class UserSettings
{
public Transform rightHand;
public Transform pistolUnequipSpot;
public Transform rifleUnequipSpot;
}
[SerializeField]
public UserSettings userSettings;
[System.Serializable]
public class Animations
{
public string weaponTypeInt = "WeaponType";
public string reloadingBool = "isReloading";
public string aimingBool = "Aiming";
}
[SerializeField]
public Animations animations;
public Weapon currentWeapon;
public List<Weapon> weaponsList = new List<Weapon>();
public int maxWeapons = 2;
public bool aim { get; protected set; }
private bool reload;
private int weaponType;
private bool settingWeapon;
// Use this for initialization
void OnEnable()
{
GameObject check = GameObject.FindGameObjectWithTag ("Sound Controller");
if (check != null)
sc = check.GetComponent<SoundController> ();
SetupWeapons ();
}
void SetupWeapons () {
if (currentWeapon)
{
currentWeapon.SetEquipped(true);
currentWeapon.SetOwner(this);
AddWeaponToList(currentWeapon);
if (currentWeapon.ammo.clipAmmo <= 0)
Reload();
if (reload)
if (settingWeapon)
reload = false;
}
if(weaponsList.Count > 0)
{
for(int i = 0; i < weaponsList.Count; i++)
{
if(weaponsList[i] != currentWeapon)
{
weaponsList[i].SetEquipped(false);
weaponsList[i].SetOwner(this);
}
}
}
}
// Update is called once per frame
void Update()
{
Animate();
}
//Animates the character
void Animate()
{
if (!animator)
return;
animator.SetBool(animations.aimingBool, aim);
animator.SetBool(animations.reloadingBool, reload);
animator.SetInteger(animations.weaponTypeInt, weaponType);
if (!currentWeapon)
{
weaponType = 0;
return;
}
switch (currentWeapon.weaponType)
{
case Weapon.WeaponType.Pistol:
weaponType = 1;
break;
case Weapon.WeaponType.Rifle:
weaponType = 2;
break;
}
}
//Adds a weapon to the weaponsList
void AddWeaponToList(Weapon weapon)
{
if (weaponsList.Contains(weapon))
return;
weaponsList.Add(weapon);
}
//Puts the finger on the trigger and asks if we pulled
public void FireCurrentWeapon (Ray aimRay)
{
if (currentWeapon.ammo.clipAmmo == 0) {
Reload ();
return;
}
currentWeapon.Fire (aimRay);
}
//Reloads the current weapon
public void Reload()
{
if (reload || !currentWeapon)
return;
if (currentWeapon.ammo.carryingAmmo <= 0 || currentWeapon.ammo.clipAmmo == currentWeapon.ammo.maxClipAmmo)
return;
if (sc != null) {
if (currentWeapon.sounds.reloadSound != null) {
if (currentWeapon.sounds.audioS != null) {
sc.PlaySound (currentWeapon.sounds.audioS, currentWeapon.sounds.reloadSound, true, currentWeapon.sounds.pitchMin, currentWeapon.sounds.pitchMax);
}
}
}
reload = true;
StartCoroutine(StopReload());
}
//Stops the reloading of the weapon
IEnumerator StopReload()
{
yield return new WaitForSeconds(currentWeapon.weaponSettings.reloadDuration);
currentWeapon.LoadClip();
reload = false;
}
//Sets out aim bool to be what we pass it
public void Aim(bool aiming)
{
aim = aiming;
}
//Drops the current weapon
public void DropCurWeapon()
{
if (!currentWeapon)
return;
currentWeapon.SetEquipped(false);
currentWeapon.SetOwner(null);
weaponsList.Remove(currentWeapon);
currentWeapon = null;
}
//Switches to the next weapon
public void SwitchWeapons()
{
if (settingWeapon || weaponsList.Count == 0)
return;
if (currentWeapon)
{
int currentWeaponIndex = weaponsList.IndexOf(currentWeapon);
int nextWeaponIndex = (currentWeaponIndex + 1) % weaponsList.Count;
currentWeapon = weaponsList[nextWeaponIndex];
}
else
{
currentWeapon = weaponsList[0];
}
settingWeapon = true;
StartCoroutine(StopSettingWeapon());
SetupWeapons ();
}
//Stops swapping weapons
IEnumerator StopSettingWeapon()
{
yield return new WaitForSeconds(0.7f);
settingWeapon = false;
}
void OnAnimatorIK()
{
if (!animator)
return;
if (currentWeapon &&
currentWeapon.userSettings.leftHandIKTarget &&
weaponType == 2 &&
!reload &&
!settingWeapon &&
!isAI)
{
animator.SetIKPositionWeight(AvatarIKGoal.LeftHand, 1);
animator.SetIKRotationWeight(AvatarIKGoal.LeftHand, 1);
Transform target = currentWeapon.userSettings.leftHandIKTarget;
Vector3 targetPos = target.position;
Quaternion targetRot = target.rotation;
animator.SetIKPosition(AvatarIKGoal.LeftHand, targetPos);
animator.SetIKRotation(AvatarIKGoal.LeftHand, targetRot);
}
else
{
animator.SetIKPositionWeight(AvatarIKGoal.LeftHand, 0);
animator.SetIKRotationWeight(AvatarIKGoal.LeftHand, 0);
}
}
}
Bom dia e obrigado
Última edição por Callyde Jr em Qui Jan 26, 2017 1:07 pm, editado 1 vez(es)
Re: Recarregador de armas
Bom dia cara! uma observação, você abriu o tópico na área errada, em "Formação de equipes".
Abraço!
Abraço!
Re: Recarregador de armas
Que parte não está dando certo?
JohnRambo- Moderador
- PONTOS : 5173
REPUTAÇÃO : 661
Idade : 24
Áreas de atuação : Unity;
Programação;
Música e Sonorização;
Graduado em Análise e Desenvolvimento de Sistemas;
Respeito as regras :
Re: Recarregador de armas
Obrigado por corrigir o meu erro no topico.
Bom eu estava tentando fazer um recarregador ingual aquele que o Marcos fez nesse Tutorial
O script da muniçao que marcos fez e esse queria modificalo para meu sistema.
Bom eu estava tentando fazer um recarregador ingual aquele que o Marcos fez nesse Tutorial
O script da muniçao que marcos fez e esse queria modificalo para meu sistema.
Re: Recarregador de armas
Eu estou tentando faze-lo assim
para meu sistema de vida deu certo para o de armas esta dando erros
- Código:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
[RequireComponent(typeof(Collider))]
public class Municao : MonoBehaviour {
private Collider col { get { return GetComponent<Collider> (); } set { col = value; } }
private WeaponHandler wp { get { return Player.GetComponent<WeaponHandler> (); } set { wp = value; } }
public Transform Player;
public float Recarregar = 2;
public bool Ativar;
public KeyCode TeclaPegarMunicao = KeyCode.E;
public AudioClip SomPegarMunicao;
public float distanciaDoItem = 3;
bool podePegarOItem;
AudioSource emissorSom;
// Use this for initialization
void Start () {
Ativar = false;
emissorSom = GetComponent<AudioSource> ();
}
// Update is called once per frame
void Update () {
float distancia = Vector3.Distance (transform.position, Player.gameObject.transform.position);
if (distancia < distanciaDoItem) {
podePegarOItem = true;
} else {
podePegarOItem = false;
}
if (Input.GetKeyDown (TeclaPegarMunicao) && podePegarOItem) {
Ativar = true;
if(Player.gameObject.GetComponent<Weapon> ()) {
if (wp)
{
if (wp.weaponType.currentWeapon == null) {
wp.weaponType.currentWeapon.ammo.carryingAmmo + Recarregar;// Aqui vc Declara o Sist de Vida do Player e o Dano que ele Vai Receber
}
GameObject emissorSom = new GameObject ();
emissorSom.AddComponent (typeof(AudioSource));
emissorSom.GetComponent<AudioSource> ().PlayOneShot (SomPegarMunicao);
Destroy (emissorSom.gameObject, 5);
Destroy (gameObject);
}
}
}
}
void OnGUI(){
if (podePegarOItem == true) {
GUIStyle stylez = new GUIStyle ();
stylez.alignment = TextAnchor.MiddleCenter;
GUI.skin.label.fontSize = 20;
GUI.Label (new Rect (Screen.width / 2 - 50, Screen.height / 2 + 50, 200, 30), "Pressione: " + TeclaPegarMunicao);
}
}
}
para meu sistema de vida deu certo para o de armas esta dando erros
Re: Recarregador de armas
você esta usando abstração para fazer as armas ?
Weslley- Moderador
- PONTOS : 5728
REPUTAÇÃO : 744
Idade : 26
Áreas de atuação : Inversión, Desarrollo, Juegos e Web
Respeito as regras :
Re: Recarregador de armas
Opa boa tarde amigo
abstração?
No script da arma essas sao onde indica balas, balaextras, e TipodeArmas.
weaponType //tipo da arma
carryingAmmo //balas extras
clipAmmo //balas
maxClipAmmo //maximodebalas
o script WeaponHandler que eu postei fica no Player e o script Weapon fica nas armas que sao duas pistola e rifre.
abstração?
No script da arma essas sao onde indica balas, balaextras, e TipodeArmas.
weaponType //tipo da arma
carryingAmmo //balas extras
clipAmmo //balas
maxClipAmmo //maximodebalas
o script WeaponHandler que eu postei fica no Player e o script Weapon fica nas armas que sao duas pistola e rifre.
Re: Recarregador de armas
Bom dia amigos
Fiz ele assim nao deu erros mais nao adiciona a muniçao extra
Fiz ele assim nao deu erros mais nao adiciona a muniçao extra
- Código:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
[RequireComponent(typeof(Collider))]
public class Municao : MonoBehaviour {
private CharacterStats cs { get { return Player.GetComponent<CharacterStats> (); } set { cs = value; } }
private Collider col { get { return GetComponent<Collider> (); } set { col = value; } }
private WeaponHandler wp { get { return Player.GetComponent<WeaponHandler> (); } set { wp = value; } }
public int weaponType;
public GameObject Weapon;
public Transform Player;
public float Recarregar = 2;
public bool Ativar;
public KeyCode TeclaPegarMunicao = KeyCode.E;
public AudioClip SomPegarMunicao;
public float distanciaDoItem = 3;
bool podePegarOItem;
AudioSource emissorSom;
// Use this for initialization
void Start () {
Ativar = false;
emissorSom = GetComponent<AudioSource> ();
}
// Update is called once per frame
void Update () {
float distancia = Vector3.Distance (transform.position, Player.gameObject.transform.position);
if (distancia < distanciaDoItem) {
podePegarOItem = true;
} else {
podePegarOItem = false;
}
if (Input.GetKeyDown (TeclaPegarMunicao) && podePegarOItem) {
if (Weapon.gameObject.GetComponent<WeaponHandler> ()) {
wp.currentWeapon.ammo.carryingAmmo = wp.currentWeapon.ammo.carryingAmmo + Recarregar;
GameObject emissorSom = new GameObject ();
emissorSom.AddComponent (typeof(AudioSource));
emissorSom.GetComponent<AudioSource> ().PlayOneShot (SomPegarMunicao);
Destroy (emissorSom.gameObject, 5);
Destroy (gameObject);
}
}
}
void OnGUI(){
if (podePegarOItem == true) {
GUIStyle stylez = new GUIStyle ();
stylez.alignment = TextAnchor.MiddleCenter;
GUI.skin.label.fontSize = 20;
GUI.Label (new Rect (Screen.width / 2 - 50, Screen.height / 2 + 50, 200, 30), "Pressione: " + TeclaPegarMunicao);
}
}
}
Re: Recarregador de armas
Boa tarde a todos
Consegui concertar o script agora esta funcionando direitinho
no script da arma eu modifiquei para float essa parte
carryingAmmo //balas extras
clipAmmo //balas
Adicione essa parte ao script do carregador
public enum WeaponType
{
Pistol, Rifle
}
public WeaponType weaponType;
public List<Weapon> weaponsList = new List<Weapon>();
Pronto esta resolvido obrigado amigos.
Consegui concertar o script agora esta funcionando direitinho
- Código:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
[RequireComponent(typeof(Collider))]
public class Municao : MonoBehaviour {
private CharacterStats cs { get { return Player.GetComponent<CharacterStats> (); } set { cs = value; } }
private Collider col { get { return GetComponent<Collider> (); } set { col = value; } }
private WeaponHandler wp { get { return Player.GetComponent<WeaponHandler> (); } set { wp = value; } }
public enum WeaponType
{
Pistol, Rifle
}
public WeaponType weaponType;
public List<Weapon> weaponsList = new List<Weapon>();
public Transform Player;
public float Recarregar = 2;
public bool Ativar;
public KeyCode TeclaPegarMunicao = KeyCode.E;
public AudioClip SomPegarMunicao;
public float distanciaDoItem = 3;
bool podePegarOItem;
AudioSource emissorSom;
// Use this for initialization
void Start () {
Ativar = false;
emissorSom = GetComponent<AudioSource> ();
}
// Update is called once per frame
void Update () {
float distancia = Vector3.Distance (transform.position, Player.gameObject.transform.position);
if (distancia < distanciaDoItem) {
podePegarOItem = true;
} else {
podePegarOItem = false;
}
if (Input.GetKeyDown (TeclaPegarMunicao) && podePegarOItem) {
if (Player.gameObject.GetComponent<WeaponHandler> ()) {
wp.currentWeapon.ammo.carryingAmmo = wp.currentWeapon.ammo.carryingAmmo + Recarregar;
GameObject emissorSom = new GameObject ();
emissorSom.AddComponent (typeof(AudioSource));
emissorSom.GetComponent<AudioSource> ().PlayOneShot (SomPegarMunicao);
Destroy (emissorSom.gameObject, 5);
Destroy (gameObject);
}
}
}
void OnGUI(){
if (podePegarOItem == true) {
GUIStyle stylez = new GUIStyle ();
stylez.alignment = TextAnchor.MiddleCenter;
GUI.skin.label.fontSize = 20;
GUI.Label (new Rect (Screen.width / 2 - 50, Screen.height / 2 + 50, 200, 30), "Pressione: " + TeclaPegarMunicao);
}
}
}
no script da arma eu modifiquei para float essa parte
carryingAmmo //balas extras
clipAmmo //balas
Adicione essa parte ao script do carregador
public enum WeaponType
{
Pistol, Rifle
}
public WeaponType weaponType;
public List<Weapon> weaponsList = new List<Weapon>();
Pronto esta resolvido obrigado amigos.
SchultzGames :: UNITY 3D :: Resolvidos
Página 1 de 1
Permissões neste sub-fórum
Não podes responder a tópicos