1
我是新來的團隊,我想要做的就是創建一個raycast,它可以找到所有標記爲敵人的對象,這些對象位於我的玩家面前,如果他們在當我按下F鍵時,需要每個人的健康,有人可以幫助我嗎?這裏是我的代碼:Physics.RaycastAll使用標籤查找敵人
using UnityEngine;
using System.Collections;
public class meleeAttack : MonoBehaviour {
public GameObject target;
public float attackTimer;
public float coolDown;
private RaycastHit hit;
// Use this for initialization
void Start() {
attackTimer = 0;
coolDown = 0.5f;
}
// Update is called once per frame
void Update() {
if(attackTimer > 0)
attackTimer -= Time.deltaTime;
if(attackTimer < 0)
attackTimer = 0;
if (Input.GetKeyUp(KeyCode.F)) {
if(attackTimer == 0)
Attack();
attackTimer = coolDown;
}
}
private void Attack() {
float distance = Vector3.Distance(target.transform.position, transform.position);
Vector3 dir = (target.transform.position - transform.position).normalized;
float direction = Vector3.Dot(dir, transform.forward);
Debug.Log(direction);
if (distance < 3 && direction > 0.5) {
enemyhealth eh = (enemyhealth)target.GetComponent("enemyhealth");
eh.AddjustCurrentHealth(-10);
}
}
}
using UnityEngine;
using System.Collections;
public class enemyhealth : MonoBehaviour {
public int maxHealth = 100;
public int currentHealth = 100;
public float healthBarLength;
// Use this for initialization
void Start() {
healthBarLength = Screen.width/2;
}
// Update is called once per frame
void Update() {
AddjustCurrentHealth(0);
}
void OnGUI() {
GUI.Box(new Rect(10, 40, healthBarLength, 20), currentHealth + "/" + maxHealth);
}
public void AddjustCurrentHealth(int adj){
currentHealth += adj;
if (currentHealth < 0)
currentHealth = 0;
if (currentHealth > maxHealth)
currentHealth = maxHealth;
if (maxHealth < 1)
maxHealth = 1;
healthBarLength = (Screen.width/2) * (currentHealth/(float)maxHealth);
}
}