Javascript Поплавок становится NaN после использования - PullRequest
0 голосов
/ 09 февраля 2020

У меня есть следующий класс

function Sprite( sprite, frameWidth, frameHeight )
{
    this.frameWidth = frameWidth;
    this.frameHeight = frameHeight;
    this.sprite = sprite;
    this.cycles = new Array( [ new AnimationPoint( 0, 0 ) ] );
    this.currentFrame = 0;
    this.currentCycle = this.cycles[ 0 ];
    this.scaleFactor = 1;
    this.pause = false;
    this.x = 0.0;
    this.y = 0.0;
    this.orientation = 0.0;
    this.transformQue = new Array();
    this.QueRotation = function( radians ) {
        this.transformQue.push( radians );
    }
    this.AddAnimationCycle = function( animationPoints ) {
        this.cycles.push( animationPoints );
    }
    this.Pause = function() {
        this.pause = true;
    }
    this.UnPause = function() {
        this.pause = false;
    }
    this.SelectAnimationCycle = function( cycle ) {
        this.currentFrame = 0;
        this.currentCycle = this.cycles[ cycle ];
    }
    this.Forward = function() {
        this.x += Math.cos( this.orientation ) * grid.UnitToPixelX( canvas );
        this.y += Math.sin( this.orientation ) * grid.UnitToPixelY( canvas );
    }
    this.Animate = function ()
    {
        renderContext.save();
        var rotation = this.transformQue.pop();
        var x = ( ( this.frameWidth * this.scaleFactor ) / 2 );
        var y = ( ( this.frameHeight * this.scaleFactor ) / 2 );
        renderContext.translate( this.x + x,
                this.y + y );
        renderContext.rotate( this.orientation += rotation );
        renderContext.translate( -( this.x + x ),
            -( this.y + y ) );
        renderContext.drawImage( this.sprite, 
                this.currentCycle[ this.currentFrame ].x * this.frameWidth, 
                this.currentCycle[ this.currentFrame ].y * this.frameHeight, 
                this.frameWidth, this.frameHeight, this.x, this.y, 
                this.frameWidth * this.scaleFactor, this.frameHeight * this.scaleFactor );
        renderContext.restore();
        if( this.pause == false )
        {
            ++this.currentFrame;
            if( this.currentFrame >= this.currentCycle.length )
                this.currentFrame = 0;
        }
    }
}

Если я в своей функции рендеринга сделаю что-то вроде

mySprite.QueRotation( .1 )

Это работает вечно.

Однако, если я есть функция, которая вызывает QueRotation, например,

function MySpriteClockWise() {
    mySprite.QueRotation( Math.PI / 2 );
}

Она переходит к NaN.

По-прежнему странно, однако this.orientation = 0.0;, если я не касаюсь функции QueRotation внутри моего Функция рендеринга, это идет к NaN! Даже после того, как его просто присвоили нулю и не коснулись его! Если я выполняю такую ​​функцию, как:

starting = 0;

function MySpriteStart() {
    if( starting++ < 4 )
        MySpriteClockWise();
}

и наблюдаю за значением в консоли, он просто отлично рассчитывает столько раз, сколько я хочу запустить функцию, но как только это делается в функция рендеринга, она становится NaN!

Это как если бы JS до сих пор не думал, что мне нужно значение больше, даже если я создаю функцию вроде:

this.Forward = function() {
    this.x += Math.cos( this.orientation ) * grid.UnitToPixelX( canvas );
    this.y += Math.sin( this.orientation ) * grid.UnitToPixelY( canvas );
}

, чтобы попытаться уговорить его не выбрасывая ценность, это все еще делает! Это большая проблема, потому что я пишу сценарии через lua весь смысл проекта в том, чтобы (учебник по кодированию) пользователи могли создавать сценарии для управления "mySprite" (символом) через lua чтобы учиться! Это поведение как в firefox, так и в хроме. Пожалуйста, помогите!

Ответы [ 2 ]

0 голосов
/ 09 февраля 2020

Нашел ошибку, которая объясняла проблему, я торопился, мне казалось, что на ресурсах я тоже что-то экономлю, извините.

0 голосов
/ 09 февраля 2020

При вызове mySprite.QueRotation( .1 ) функция this внутри QueRotation не указывает на объект mySprite. Вместо этого используйте функцию стрелки

this.QueRotation = ( radians ) => {
   this.transformQue.push( radians );
}

Редактировать :

Кажется, у вас нет поддержки ES6. В этом случае используйте это при вызове QueRotation function

mySprite.QueRotation.call(mySprite, .1)
...