2016-11-19 12 views
2

私はJavascriptを使い始めたばかりで、簡単なゲームを始めました。キャラクターの銃を回転させてマウスに追従させたい。これまでのところ、動きと他のすべてがうまくいきます。ただし、回転機能を追加すると、文字は画面の周りの巨大な円で回転しているようです。ここでjsfiddleだ:何か他https://jsfiddle.net/jvwr8bug/#HTMLキャンバスキャラクターの銃をマウスの顔に回転させる

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); 

エラーがどこかのようですが、明らかにそれは可能性があり

**編集:修正のための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); 
関連する問題