我刚做了一些bug修复,发现了一个我似乎无法弄清楚的错误。我的2D角色攻击,在动画结束时它调用函数DealDamage()。问题是,当我的玩家面向右边并且正在攻击右边的敌人时,它的效果非常好。当它面向左侧时,好像敌人不在那里,并且“没有”可以击中。我检查过并且Raycast返回null,因此它甚至没有注册敌人。我使用了DrawRaycast,而Raycast清楚地击中了敌人。我不知道该怎么办。
public void DealDamage()
{
if (facingRight == true && weaponReach < 0)
{
weaponReach *= -1;
}
else if (facingRight == false && weaponReach > 0)
{
weaponReach *= -1;
}
RaycastHit2D hit = Physics2D.Raycast(origin.position, new Vector2(weaponReach, 0), weaponReach, whoIsEnemy);
if (hit.transform.gameObject.layer == 12)
{
EnemyHealth EnemHealth = hit.transform.gameObject.GetComponent<EnemyHealth>();
EnemHealth.TakeDamage(attackDamage);
}
}
当我使用以下代码制作Raycasthit2D时,一切都神奇地工作。问题是距离是无限的,我绝对不希望玩家在一英里之外击中敌人。
RaycastHit2D hit = Physics2D.Raycast(origin.position, new Vector2(weaponReach, 0), weaponReach, whoIsEnemy);
我希望双方能够以同样的方式完美地工作。
我想说的问题是,当你面向左边时,你将weaponReach
作为distance
的负值传递到光线投射。在这种情况下,它将简单地使用0
,因为距离不能为负。
您应该将方向与距离分开,因为方向可以是标准化矢量:
// for the direction you actually only
// need a normalized vector either
// pointing right or left
var direction = Vector2.right * (facingRight ? 1 : -1);
这是一种速记形式的写作
var distance = new Vector2(1, 0);
if(facingRight)
{
// Actually you could ofcourse also
// completely skip that case
direction *= 1;
}
else
{
direction *= -1;
}
然后在光线投射总是传递一个积极的weaponReach
作为距离,但在正面或负面的direction
RaycastHit2D hit = Physics2D.Raycast(origin.position, direction, weaponReach, whoIsEnemy);
// You then should always check
if(hit != null)
{
...
}
顺便说一句不是你的支票
if (hit.transform.gameObject.layer == 12)
因为你已经将光线投射仅投射到某个图层掩码whoIsEnemy
上,所以多余了?