2015-04-25 2 views
0

У меня есть сетка, в которую я пытаюсь запрограммировать курсор, есть центральная точка в сетке, и я пытаюсь сделать курсор только для перемещения x количества квадратов из этого центрального точка, вот код, у меня естьjavascript логика, возвращающая странные результаты

var makecursor = function (axis, operation) { 
    oppositeAxis = axis === 'y' ? 'x' : 'y'; 

    // app.cursor contains the x and y coordinates of the cursor 
    app.cursor[axis] = 

    // calcualte the difference between the current cursor location and the origin 
    Math.abs(app.cursor[axis] - origin[axis]) + 

    // calculate the difference between the opposite axis and 
    // the origin and add it to the previous calculation 
    Math.abs(app.cursor[oppositAxis] - origin[oppositeAxis]) 

    // add the operation to be performed (movement of cursor, 1 or -1) 
    + operation 

    // if the sum of the x, y and current operation are greater then the allowed 
    // movement, then make "app.cursor[axis]" equal to itself (dont move) , 
    // otherwise make "app.cursor[axis]" equal to itself plus the operation (move) 

> origin.movement ? app.cursor[axis] : app.cursor[axis] + operation; 
} 

«операция» либо 1 или -1, для направленного

«origin.movement» это число квадратов от начала координат вы можете перемещать курсор.

Мои надежды/ожидаемое поведение заключается в том, что из квадрата на моей сетке вы можете перемещать только столько квадратов, сколько указано в переменной «origin.movement». но он возвращает странные числа, когда я распечатываю результаты, и он не правильно вычисляет местоположения, т. е. происхождение должно быть равным нулю, но вместо этого одно или два в зависимости от предыдущих движений, многие другие аномалии, которые у меня нет были в состоянии понять. любая помощь с этой проблемой была бы оценена, спасибо!

+0

sry его немного поздно, и я устал .. Я не копировал его правильно, теперь исправлено .. Я думаю, все между 'app.cursor [axis] =' и конец находится на одной строке –

ответ

0

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

Math.abs(app.cursor[axis] - origin[axis]) + 

    // calculate the difference between the opposite axis and 
    // the origin and add it to the previous calculation 

    Math.abs(app.cursor[oppositeAxis] - origin[oppositeAxis]) + 

    // add the operation to be performed (movement of cursor, 1 or -1) 
    operation; 

должно быть на самом деле так:

// add operation to curser location to account for movement 
Math.abs((app.curser[axis] + operation) - origin[axis]) + 

// instead of the adding operation at the end 
Math.abs((app.curser[oppositeAxis]) - origin[oppositeAxis]); 
0

Вам нужно поставить parens вокруг выражения, которое вы тестируете, для > origin.movement, чтобы использовать результат этого выражения; без них, выражение разбивается ранее:

var makecursor = function (axis, operation) { 
    var oppositeAxis = axis === 'y' ? 'x' : 'y'; 

    app.cursor[axis] = (
     // calculate the difference between the current cursor location and the origin 
     Math.abs(app.cursor[axis] - origin[axis]) + 

     // calculate the difference between the opposite axis and 
     // the origin and add it to the previous calculation 
     Math.abs(app.cursor[oppositeAxis] - origin[oppositeAxis]) + 

     // add the operation to be performed (movement of cursor, 1 or -1) 
     operation 

     // if the sum of the x, y and current operation are greater then the allowed 
     // movement, then make "app.cursor[axis]" equal to itself (dont move) , 
     // otherwise make "app.cursor[axis]" equal to itself plus the operation (move) 
    ) > operation ? app.cursor[axis] : app.cursor[axis] + operation; 
} 

Но, я бы не сделать это на одной длинной линии с себя назначение-к-во всяком случае, я бы разбить его для ясности и простоты отладки, и просто использовать if:

Итак:

var makecursor = function (axis, operation) { 
    var oppositeAxis = axis === 'y' ? 'x' : 'y'; 

    var movement = 
     // calculate the difference between the current cursor location and the origin 
     Math.abs(app.cursor[axis] - origin[axis]) + 

     // calculate the difference between the opposite axis and 
     // the origin and add it to the previous calculation 
     Math.abs(app.cursor[oppositeAxis] - origin[oppositeAxis]) + 

     // add the operation to be performed (movement of cursor, 1 or -1) 
     operation; 

    // If the sum of the x, y and current operation are less than or equal 
    // to the allowed movement, add the operation to `app.cursor[axis]` 
    if (movement <= origin.movement) { 
     app.cursor[axis] += operation; 
    } 
} 

Side Примечание: Ваш код был также стать жертвой The Horror of Implicit Globals не объявляя свою переменную oppositeAxis (она также была опечатана позже). Я исправил опечатку и зафиксировал неявный глобальный, добавив var выше.

+0

все еще страдает от тех же ошибочных результатов .. я не понимаю .. что не так с логикой? –

+0

Я думаю, что должно быть что-то странное с переменным входом .. idk, спасибо за вашу помощь! –

Смежные вопросы