1

私がやろうとしているのは、プレイヤーの前にある敵とタグ付けされたすべてのオブジェクトを見つけるレイキャストを作成することです.Fキーを押したときにそれらがその領域にある場合、それはいくらかの健康を必要としますそれらのそれぞれについて、誰かが私を助けてくれませんか? ここに私のコードがあります:

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);
}
}
4

1 に答える 1

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への方向性を導き出そうとしないのが最善です。UnityのレイキャストエンジンにレイとNPCの交差テストを任せましょう。この方法では、NPCにコライダーが必要です。

于 2012-12-17T06:52:53.727 に答える