例如,我有一个脚本附着在火上,如果玩家离火势的距离更近,我想对他造成伤害。
public float fireDamageRange = 5;
public float fireDamage = 10;
private Vector3 origin;
private Vector3 direction;
void Update(){
origin = transform.position;
direction = transform.forward;
RaycastHit fireHit;
if (Physics.SphereCast(origin, fireDamageRange, direction, out fireHit) && fireHit.transform.gameObject.layer == LayerMask.NameToLayer("Player") && !makingDamage)
{
makingDamage = true;
MakeDamage(fireHit);
StartCoroutine(WaitToMakeDamage());
}
}
IEnumerator WaitToMakeDamage()
{
yield return new WaitForSecondsRealtime(0.2f);
makingDamage = false;
}
脚本已附加到火上。 仅当Player实际上离原点有fireDamageRange时,才返回true,而如果他靠近原点,则不返回。我在做什么错了?
答案 0 :(得分:2)
只需计算玩家与火之间的距离,并检查其是否在射程范围内
可以轻松计算距离public float fireDamageRange = 5;
public float fireDamage = 10;
public GameObject player; // the player
private Vector3 origin;
private Vector3 direction;
void Update(){
float distance = Vector3.Distance(player.transform.position, transform.position);
if (distance <= fireDamageRange)
{
// handle damage to the player
}
}