Quantcast
Viewing all articles
Browse latest Browse all 1488

Deal damage on collision

Hi, I want my game to work so if the enemy collides with the player the player loses 10 health but I don't know what to do and I've tried every tutorial out there. Please help I am desperate. using UnityEngine; using System.Collections; public class PlayerVitals : MonoBehaviour { public GameObject guiObject; public int curHealth = 100; public int maxHealth = 100; public int recoveryAmount = 1; public float recoverySpeed = 3; public Color bloodColor = new Color(1.0f, 0.0f, 0.0f, 1.0f); public Texture2D bloodyScreen; public float fallDamageHeight = 8; public AudioClip fallDamage; [HideInInspector] public float percent; private float alpha; private float iv2; private float minimumHealth = 40; private float bmhRatio; private PlayerMovement pm; private CharacterController controller; void Start() { minimumHealth = 40; pm = GetComponent(); if(recoveryAmount != 0) { StartCoroutine(Regenerate(0)); } controller = GetComponent(); } void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody rigid = hit.collider.attachedRigidbody; if(rigid == null || rigid.isKinematic || hit.moveDirection.y < -0.3f) { return; } Vector3 pushDir = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z); rigid.velocity = pushDir * controller.velocity.magnitude * pm.pushPower / rigid.mass; } void OnGUI() { GUI.color = new Color(bloodColor.r, bloodColor.g, bloodColor.b, alpha); GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), bloodyScreen); } void FixedUpdate() { alpha = Mathf.Lerp(alpha, 0.9f - (percent * 0.9f), Time.deltaTime * 7); curHealth = Mathf.Clamp(curHealth, 0, maxHealth); percent = (float)curHealth / (float)maxHealth; iv2 = pm.impactVelocity; if(curHealth <= 0) { Die(); } Repud.GetChild(guiObject, "health_text").GetComponent().text = curHealth.ToString() + "/" + maxHealth.ToString(); Repud.GetChild(guiObject, "health_bar").SendMessage("UpdateSize", percent); bmhRatio = maxHealth / minimumHealth; if(pm.grounded && pm.floating && iv2 > 1) { SendMessage("FallAnimation", iv2); } if(pm.grounded && pm.floating && iv2 > fallDamageHeight) { FallDamage(((iv2 - (fallDamageHeight * 0.8f)) * ((iv2 - (fallDamageHeight * 0.8f)) * 0.5f))); iv2 = 0; pm.floating = false; } } public IEnumerator Regenerate(int amount) { curHealth += amount; yield return new WaitForSeconds(recoverySpeed); StartCoroutine(Regenerate(recoveryAmount)); } private void FallDamage(float prc) { if((int)(prc) <= 0) {return;} ApplyDamage((int)prc); audio.clip = fallDamage; audio.volume = 0.02f; audio.Play(); } public void ApplyDamage(float amount) { curHealth -= (int)amount; } public void Die() { Destroy(gameObject); } }

Viewing all articles
Browse latest Browse all 1488

Trending Articles



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