2016-11-19 2 views
2

Я очень новичок в Javascript, и я начал простую игру. Я хочу, чтобы пистолет персонажа вращался, чтобы следовать за мышью. Пока что движение и все остальное прекрасно работают, за исключением того, что когда я добавил функциональность вращения, персонаж поворачивается в огромном круге вокруг экрана. Вот jsfiddle: https://jsfiddle.net/jvwr8bug/#HTML Canvas Вращение пистолета персонажа для мыши

function getMousePos(canvas, evt) { 
    var rect = canvas.getBoundingClientRect(); 
    var mouseX = evt.clientX - rect.top; 
    var mouseY = evt.clientY - rect.left; 
    return { 
    x: mouseX, 
    y: mouseY 
    }; 
} 

window.addEventListener('load', function() { 
    canvas.addEventListener('mousemove', function(evt) { 
    var m = getMousePos(canvas, evt); 
    mouse.x = m.x; 
    mouse.y = m.y; 
    }, false); 
}, false); 

ошибка, кажется, где-то там, но очевидно, что это может быть что-то еще

** Edit: Благодаря Blindman67 для исправления.

ответ

0

Вы вращали текущее преобразование на rotation каждый кадр. ctx.rotate(a) вращает текущее преобразование, поэтому каждый раз, когда он называется, вы увеличиваете количество оборотов на a. Подумайте об этом как относительном вращении, а не о настройке абсолютного вращения.

Чтобы исправить код замены канона рендеринга с

//cannon 
    //ctx.rotate(rotation); // << you had 

    // setTransform overwrites the current transform with a new one 
    // The arguments represent the vectors for the X and Y axis 
    // And are simply the direction and length of one pixel for each axis 
    // And a coordinate for the origin. 
    // All values are in screen/canvas pixels coordinates 
    // setTransform(xAxisX, xAxisY, yAxisX, yAxisY, originX, originY) 
    ctx.setTransform(1,0,0,1,x,y); // set center of rotation (origin) to center of gun 
    ctx.rotate(rotation); // rotate about that point. 
    ctx.fillStyle = "#989898"; 
    ctx.fillRect(15, - 12.5, 25, 25); // draw relative to origin 
    ctx.lineWidth = 2; 
    ctx.strokeStyle = "#4f4f4f"; 
    ctx.strokeRect(15,- 12.5, 25, 25); // draw relative to origin 
    //body 
    ctx.fillStyle = "#5079c4"; 
    ctx.beginPath(); 
    ctx.arc(0, 0, size, 0, Math.PI * 2); // draw relative to origin 
    ctx.fill(); 
    ctx.stroke(); 

    // can't leave the transformed state as is because that will effect anything else 
// that will be rendered. So reset to the default. 
    ctx.setTransform(1,0,0,1,0,0); // restore the origin to the default 

И еще несколько проблем, чтобы получить его работу

Чуть выше рендеринга каноник получить направление к мыши

// you had coordinates mixed up 
// rotation = Math.atan2(mouse.x - y, mouse.y - x); // you had (similar) 

rotation = Math.atan2(mouse.y - y, mouse.x - x); 

И ваш слушатель событий мыши смешивает координаты и не работает очень эффективно

Замените все коды мыши на. Вы не нуждаетесь в onload, поскольку холст уже существует.

canvas.addEventListener('mousemove', function(evt) { 
    var rect = this.getBoundingClientRect(); 
    mouse.x = evt.clientX - rect.left; // you had evt.clientX - rect.top 
    mouse.y = evt.clientY - rect.top; // you had evt.clientY - rect.left 
}, false); 
Смежные вопросы