2012-12-15 4 views
1

나는 화합의 대상이 아니므로, 내 플레이어 앞에있는 모든 객체에 태그가 달린 레이캐스팅을 만들고, 그 안에 있다면 영역 내가 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); 
} 
} 

답변

0
private void Attack(){ 
    int user_defined_layer = 8; //use the 'User Layer' you created to define NPCs 
    int layer_mask = 1 << user_defined_layer; 

    RaycastHit[] hits; 

    // Get direction in front of your player 
    Vector3 direction = transform.TransformPoint(Vector3.forward); 
    hits = Physics.RaycastAll(transform.position, direction, Mathf.Infinity, layer_mask) 

    foreach(RaycastHit hit in hits) 
    { 
     //NPC is hit, decrease his/her/its life 
    } 
} 

그것은 당신이 당신의 NPC들에게 위치에서 방향을 도출하려고 시도하지 않는 것이 좋습니다 : 여기 내 코드입니다. 유니티의 레이 캐스트 엔진이 당신을 위해 레이 -NPC 교차 테스트를 처리하게하십시오. 이 방법을 사용하려면 NPC에 Collider가 있어야합니다.

관련 문제