首页 > 解决方案 > 你如何进行剑攻击

问题描述

大佬们怎么打出剑法?我问这个问题是因为我不知道如何进行剑攻击,而我正在观看的教程仅显示了射弹攻击。我想学习如何为我正在创建的游戏制作剑攻击。这是我展示的代码

    void AttackPlayer()
{
    //Make sure that the enemy doesn't move
    agent.SetDestination(transform.position);

    transform.LookAt(player);
    if (!alreadyAttacked)
    {
        //Attack Code Is underneath
        Rigidbody rb = Instantiate(projectile, transform.positino, Quaternion.identity).GetComponent<Rigidbody>();
        rb.AddForce(transform.forward * 32f, ForceMode.Impulse);
        rb.AddForce(transform.up * 8f, ForceMode.Impulse);

        //Attack Code Is Above. I want a sword attack instead of a projectile
        alreadyAttacked = true;
        Invoke(nameof(ResetAttack), timeBetweenAttacks);
    }
}

标签: c#unity3d

解决方案


如果您有剑的 3D 对象以及动画,您可以向其添加对撞机,并在挥动动画期间启用它。

以上将非常准确,但这可能不是您真正想要的行为。如果您想让玩家使用更“简单”的东西,您可以在玩家面前添加一个带有球体碰撞器的单独对象。同样,您可以在动画期间启用它,甚至可能在一瞬间启用它。

可能更好的方法是在您的代码中使用SphereCast来“及时”检查玩家面前的区域。文档中的示例代码,稍作修改:

void Attack()
{
    RaycastHit hit;

    // _hitCenterGameObject would be a GameObject you would create under your character GameObject. Position it wherever you want the hit to be centered
    // This makes it really easy to see and understand where your attack will be in relation to you character
    var spherePosition = _hitCenterGameObject.position;
    
    // How big is the sphere going to be
    var radius = 1f;

    float distanceToObstacle = 0;

    // Cast a sphere to see if it we hit anything.
    if (Physics.SphereCast(spherePosition, radius, transform.forward, out hit, 10))
    {
        // You got a hit, probably want to figure out what it is, and whether or not to apply damage.
        distanceToObstacle = hit.distance;
    }
}

注意:您可能想要使用它,SphereCastAll因为它会返回所有被光线投射击中的对象。或者你可能会根据武器或攻击类型来改变它。也许挥杆可以击中多个目标而刺击只能击中一个目标?只是一个想法。


推荐阅读