用jQuery模拟一个堕落的对象

时间:2017-09-02 19:07:40

标签: javascript jquery css animation

我在jQuery中模拟一个保龄球游戏。所以,我扔球(通过动画功能),当它击中一个引脚我模拟它落下(也通过动画功能)。但我只能让它旋转。我希望它在原地,左边或右边摔倒。像this一样。这是pin动画的jQuery代码:

this.animation = function (pinID) {
    var rdm = ((Math.random()*10)+1);
    var degree;
    if (rdm <= 5)
        degree = -90;
    else
        degree = 90;
    $(pinID).animate({ deg: degree },
    {
        duration: 1000,
        step: function (now) {
            // In the step-callback (that is fired each step of the animation),
            // the pin will rotate to the current degree of the animation
            $(pinID).css({
                transform: 'rotate(' + now + 'deg)'
            });
        },
        complete: function () {
            // When the animation is complete, removes the pin from play
            $(pinID).css({
                "left": -200, "top": -200
            });
        }
    });
}

我试图在动画功能的开头有一个左侧和顶部,它只是模拟了一个奇怪的动作。 如果有人能帮助我,我会很感激。感谢。

编辑这是结果(感谢 Zs V ):

this.animation = function (pinID) {
    if (knockedPins.indexOf(pinID) == -1) {
        var rdm = ((Math.random() * 10) + 1);
        var degree;
        var transFormOrigin;
        if (rdm <= 5) {
            degree = -90;
            transFormOrigin = '0% 100%';
        }
        else {
            degree = 90;
            transFormOrigin = '100% 100%';
        }
        $(pinID).css({ "transform-origin": transFormOrigin });
        knockedPins.push(pinID);

        $(pinID).animate({ deg: degree },
        {
            duration: 1000,
            step: function (now) {
                // In the step-callback (that is fired each step of the animation),
                // the pin will rotate to the current degree of the animation
                $(pinID).css({
                    transform: 'rotate(' + now + 'deg)'
                });
            },
            complete: function () {
                // When the animation is complete, removes the pin from play
                $(pinID).css({
                    "left": -200, "top": -200
                });
            }
        });
    }
}

我添加了transform-origin属性,并且必须使用数组来存储已被敲击的引脚的ID,否则它会震动直到它被搁置。和合

1 个答案:

答案 0 :(得分:1)

您必须围绕其角落而不是中心旋转对象(图片)。这里讨论如何做到这一点:https://stackoverflow.com/a/6633676/6624619