Quantcast
Channel: Questions in topic: "enemy"
Viewing all articles
Browse latest Browse all 1488

Enemy Health GUI Issues

$
0
0
Hi all, I'll try to explain this as best as possible. I am making a basic RPG in attempt to gain a better understanding of programming in Unity, and C#. ***The Plan:*** In the game, users can target a single enemy at a time. When an enemy is targeted, a health bar is displayed for that enemy only. Players can use KeyCode.Alpha1 to cast an spell (currently a simply sphere) that travels towards the targeted enemy, deals damage to that enemy ONLY, and is destroyed on impact. This projectile should deal I have four scripts to support this system: Targeting, EnemyHealthSystem, PlayerAttack, and EnergyBlast. I can select targets, and fire projectiles at the selected target, but I have encountered several problems: - Enemies appear to share one health pool. - Upon being hit by an energy blast, the health bar of the selected enemy disappears, even when the enemy is not deselected. The enemy remains selected however, but once shot, it's health bar is never seen again (whatever I try). - Unity keeps asking for an inspector reference to the public GameObject in Targeting, yet this is only set when a target is selected in-game. I feel it needs to be public so that that damage can be dealt to that particular enemy. Thank you for your time, here are my scripts! ***Targeting:*** using UnityEngine; using System.Collections; using System.Collections.Generic; public class Targeting : MonoBehaviour { private Transform selectedTarget; public GameObject enemyTarget; void Start() { selectedTarget = null; enemyTarget = selectedTarget.gameObject; } void Update() { if (Input.GetMouseButtonDown(0))// when button clicked... { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // cast a ray from mouse pointer: if (Physics.Raycast(ray, out hit) && hit.transform.CompareTag("Enemy"))// if enemy hit... { DeselectTarget(); // deselect previous target (if any)... selectedTarget = hit.transform; // set the new one... SelectTarget(); // and select it } else { DeselectTarget(); } } else { return; } enemyTarget = selectedTarget.gameObject; } private void SelectTarget() { selectedTarget.GetComponent().enabled = true; //PlayerAttack pa = (PlayerAttack)GetComponent("PlayerAttack"); //pa.target = selectedTarget.gameObject; } private void DeselectTarget() { if (selectedTarget) { // if any target is selected, deselect it selectedTarget.GetComponent().enabled = false; selectedTarget = null; } } } ***EnemyHealthSystem*** using UnityEngine; using System.Collections; using UnityEngine.UI; public class EnemyHealthSystem : MonoBehaviour { public int currentEnemyHealth; public int maxHealth = 100; public AudioClip skeletonHurtSound; // Sound when this enemy dies. public Texture enemyHealthBarTexture; // Only one texture needed (red), as no background private float lifeRatio; // % Of life remaining - used to set size of health bar private float lifeBarWidth; // Width of life bar. private float lifeBarHeight; // Height of life bar. private float lifeBackgroundWidth; private int healthBarLeft = 20; private Vector3 screenPosition; private Vector3 worldPosition; private int barTop = 3; private float adjustment = 2.3f; private Transform myTransform; private float distance; private Camera myCamera; private GameObject myCam; private bool inRange; private GameObject thePlayer; Targeting targeting; // Component References AudioSource enemyAudio; Animator anim; CapsuleCollider capsuleCollider; public bool isDead; //bool isFading; void Awake() { thePlayer = GameObject.Find("ThirdPersonController"); targeting = thePlayer.GetComponent(); myCam = GameObject.FindGameObjectWithTag("MainCamera"); //I removed the space from the camera's name in the Unity Inspector, so you will probably need to change this myCamera = Camera.main; lifeBackgroundWidth = 30.0f; lifeBarHeight = 3.0f; myTransform = transform; enemyAudio = GetComponent(); //anim = GetComponent(); capsuleCollider = GetComponent(); currentEnemyHealth = maxHealth; isDead = false; } void Update() { lifeRatio = currentEnemyHealth/maxHealth; lifeBarWidth = lifeRatio * lifeBackgroundWidth; } void OnGUI() { distance = Vector3.Distance(myCam.transform.position, transform.position); //gets the distance between the camera, and the intended target we want to raycast to if (distance < 25f) { inRange = true; } else { inRange = false; } worldPosition = new Vector3(myTransform.position.x, myTransform.position.y + adjustment,myTransform.position.z); screenPosition = myCamera.WorldToScreenPoint(worldPosition); //if something obstructs our raycast, that is if our characters are no longer 'visible,' dont draw their health on the screen. if (inRange && targeting.enemyTarget != null && targeting.enemyTarget.gameObject.transform == this.transform) //isSelected /* && isVisible*/) { GUI.DrawTexture(new Rect (screenPosition.x - healthBarLeft / 2.0f, Screen.height - screenPosition.y - barTop, lifeBarWidth, lifeBarHeight), enemyHealthBarTexture); //displays a healthbar } else{ return; } } public void TakeDamage(int amount) { if (isDead) return; enemyAudio.Play(); currentEnemyHealth -= amount; Debug.Log("My current health is " + currentEnemyHealth); if (currentEnemyHealth <= 0) { Death(); targeting.enemyTarget = null; } } void Death() { //isDead = true; //capsuleCollider.isTrigger = true; //anim.SetTrigger ("Dead"); // enemyAudio.clip = deathClip; //enemyAudio.Play (); } // Method to fade the enemies body away after a certain amount of time following its death. /* public void FadeAway() { GetComponent ().enabled = false; GetComponent ().isKinematic = true; isFading = true; Destroy(gameObject, 2f); }*/ } ***PlayerAttack*** using UnityEngine; using UnityEngine.UI; using System.Collections; /// /// This Script will contain all the attacks available to the player. It will contain information about /// their costs, the damage of the attacks (to the target), and will control their animations. /// Attacks cost the player Arcane (or possibly later, energy) which will regenerate slowly. /// public class PlayerAttack : MonoBehaviour { GameObject thePlayer; PlayerStats playerStats; public Rigidbody EnergyBlast; // One off energy blast. void Awake() { thePlayer = GameObject.Find("ThirdPersonController"); playerStats = thePlayer.GetComponent(); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { // Arcane Control if(playerStats.currentArcane >= 0) { playerStats.currentArcane += Time.deltaTime * playerStats.arcaneRegenRate; } // Spells. Number 1 is a one-off spell, number 2 is channeled spell. if (Input.GetKeyDown(KeyCode.Alpha1) && playerStats.currentArcane >= playerStats.arcaneCostSpell1 /*&& targeting.selectedTarget != null && enemyHealth.currentEnemyHealth > 0 && enemyHealth.isDead == false*/) { Instantiate(EnergyBlast); playerStats.currentArcane -= playerStats.arcaneCostSpell1; } if (Input.GetKey(KeyCode.Alpha2)) { playerStats.currentArcane -= Time.deltaTime * playerStats.arcaneFallRateChannelling; } } } ***EnergyBlast*** using UnityEngine; using System.Collections; public class EnergyBlast : MonoBehaviour { // Transforms to act as start and end markers for the journey. private Transform enemy; private Transform spellSpawn; // Reference to player so we can set starting transform of ability appropriately. GameObject thePlayer; GameObject spellSpawnCube; public int damagePerSpell; public float spellRange; // Movement speed of attack in units/sec. public float speed; // Time when the movement started. private float startTime; // Total distance between the player and the selected enemy. private float journeyLength; void Awake() { // Sets reference to player game object, so we can get transform. thePlayer = GameObject.FindGameObjectWithTag("Player"); // Obtains and sets transform of 'enemy' to players selected target. enemy = thePlayer.GetComponent().enemyTarget.transform; // Sets location of spellSpawn to transform of spellSpawnCube. spellSpawnCube = GameObject.Find("SpellOrigin"); spellSpawn = spellSpawnCube.transform; } // Use this for initialization void Start () { // Keeps track of time the object was instantiated. startTime = Time.time; // Calculates the journey length the object will travel (distance between enemy and player). journeyLength = Vector3.Distance(spellSpawn.position, enemy.position); } // Update is called once per frame void Update () { // Distance moved is equal to time * speed. float distCovered = (Time.time - startTime) * speed; // Fraction of journey completed = current distance divided by total distance. float fracJourney = distCovered / journeyLength; // Sets position of spell as a fraction of the distance between the player and enemy. transform.position = Vector3.Lerp (spellSpawn.position, enemy.position, fracJourney); // Code to allow object to curve. transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.LookRotation (enemy.transform.position - spellSpawn.position), 2 * Time.deltaTime); transform.rotation = Quaternion.LookRotation (enemy.position - spellSpawn.position) * Quaternion.AngleAxis (30, transform.up); } void OnTriggerEnter (Collider other) { if (other.gameObject.CompareTag("Enemy")) { Destroy(gameObject); EnemyHealthSystem enemyHealth = other.gameObject.GetComponent (); if(enemyHealth != null) { enemyHealth.TakeDamage(10); } } } }

Viewing all articles
Browse latest Browse all 1488

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>