繁体   English   中英

Javascript:计算余数不起作用?

[英]Javascript: Calculating the Remainder not working?

我正在开发一款游戏,其中玩家/敌人有一个带有3个叠加层的平衡杆。 我想做的是操纵第一个叠加层,这样它就可以按百分比完全穿过该条。

例如:第一个叠加是敌人平衡的50%。 然后进入另一个“阶段”或“状态”。 然后,该叠加层消失,第二个叠加层被触发并开始减小。

酒吧的宽度是200像素,所以我想做的是说“嘿,如果50%的敌人平衡消失了,那么触发/激活第二个叠加层。

我遇到的问题是余下的线。 当我击打敌人时说。10点平衡伤害为200。这将给我剩余的适当百分比,剩余的适当剩余部分。 但是一旦我达到50%,其余的就等于0! 这是该行或功能不再正常工作的地方,它破坏了我想做的设计模式。 这是控制台日志中的示例。

balanceCounter: function (character, boss){
    var percentage = Math.floor((boss.balance/200) * 100)
    var remain = 100 % percentage; // <--- This is not working properly
    console.log(percentage);
    console.log(remain);
    if (character.virtue == "hero"){ 
        if (percentage > 49){
        $("#bossbalanceoverlay2").animate({
            width: percentage * 2 - (remain * 2)
            }, 200)
        }
        else 
            $("#bossbalanceoverlay1").animate({
            width: percentage * 2 - (remain * 2)
            }, 200); 
        }


**click attack button**
97 // <--- Percent
3 // <--- Remainder

**click attack button**
95 // <--- Percent
5 // <--- Remainder

**click attack button**
92 // <--- Percent
8 // <--- Remainder

(When i hit the 50% mark)

**click attack button**
50 // <--- Percent
0 // <--- Remainder  **Why 0?**

**click attack button**
47 // <--- Percent
6 // <--- Remainder  **Why 6 instead of 3?**

**click attack button**
45 // <--- Percent
10 // <--- Remainder **Why 10 instead of 5?**

您可能要这样做,而不是%

var remain = 100 - percentage;

您希望余数remain + percentage总等于100,因此这是您所需要的减法,而不是取模运算。

通常,百分比为50时使用% (取模)会得到零,因为100是50的倍数,因此没有余数。

您面临的问题是%返回余数。

100%45 =>可以被45整除两次,余数= 10。

100%50 =>可被50整除两次,余数= 0。

您想要的是remain = 100 - percentage

首先,我会添加缺少的分号。

其次,您的else括号似乎缺少花括号{},这可能导致两个代码块都被击中,具体取决于代码的格式。

第三,我会仔细阅读%运算符,您可能会认为过分;)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM