【问题标题】:KnokBack of Player击退玩家
【发布时间】:2022-11-28 04:59:35
【问题描述】:

我想要此代码的回击效果,但我不知道如何实现。 我是编码新手,还在学习东西!

这是我希望 KnockBack 生效的代码。 PlayerMovement.MyBody 是一个附有刚体的脚本。

    /// <summary>
    /// If We CanDamage LifeScorecount minus 1 and stes CanDamage to false and starts Coroutine. 
    /// If Life is higher than 0 change thet text to the new life
    /// If life is 0 then stop Time and start Coroutine RestartGame
    /// </summary>
    public void DealDamage()
    {
        if(CanDamage)
        {
            Anim.Play("Stun");
            LifeScoreCount--;
            Vector2 direction = (transform.position, 0);

            PlayerMovement.myBody.AddForce(direction * -10f);

            if (LifeScoreCount >= 0)
            {
                TextLife.text = "x" + LifeScoreCount;
            }
            if (LifeScoreCount == 0)
            {
                Time.timeScale = 0f;
                StartCoroutine(RestartGame());
            }
            CanDamage = false;
            StartCoroutine(WaitForDamage());
        }
    }

【问题讨论】:

  • 您可以分享 PlayerMovement 代码吗?

标签: unity3d 2d


【解决方案1】:

这取决于您如何实施运动以及您希望击退效果如何。 假设您只是想将刚体推开,您可以像您已经尝试过的那样添加一个力。要使用“一次性”推送,您可以使用 ForceMode.Impulse。 对于要使用两个点的方向。对象的 transform.position,被推开,减去对象的 transform.position,这将角色推开。 所以如果你想让敌人推开玩家,你可以尝试这样的事情:

Vector3 playerPosition = new Vector3(transform.position.x, 0, transform.position.z);
Vector3 enemyPosition = new Vector3(enemy.transform.position.x, 0, enemy.transform.position.z);
Vector3 knockbackDirection = (playerPosition - enemyPosition).normalized;
float power = 2f
rb.AddForce(knockbackDirection * power, ForceMode.Impulse);

如果您还希望击退沿 y 轴起作用,只需使用变换位置而不是新的 Vector3。 如果你没有对敌人的引用,你可能想添加一个参数,所以每当敌人对玩家造成伤害时,他都会将自己的位置作为参数传递。

也许考虑使用 SerializeField 作为击退力,这样您就可以在编辑器中轻松编辑它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多