2017-04-13 212 views
0

調整正方形大小後,出現碰撞問題GIF animation problem,樣本https://jsfiddle.net/8jkxdhfv/。我能做什麼?我應該將未轉換的鼠標座標轉換爲座標嗎?但是如何?我如何更新我的碰撞函數中的x和y?Javascript/Canvas:縮放後的​​鼠標座標不匹配(碰撞)

HTML

<canvas id="test" width="480" height="380"></canvas> 
<div id="text">Use mouse wheel to change square size</div> 

JAVASCRIPT

var ctx = test.getContext('2d'); 
var obj = { x:100,y: 100,width: 100,height: 100} 
var mouse = {x:0, y:0, width:10, height:10}; 
var zoom = 1; 

setInterval(function(){ 
    ctx.clearRect(0,0,test.width,test.height); 
    ctx.save(); 

    var cx = obj.x+obj.width/2; 
    var cy = obj.y+obj.height/2; 

    // draw 
    ctx.translate(cx, cy); 
    ctx.scale(zoom,zoom); 
    ctx.translate(-cx,-cy); 
    ctx.fillRect(obj.x,obj.y,obj.width,obj.height); 
    ctx.restore(); 

    // check collision 
    if(collision(obj,mouse)){ 
     ctx.fillText("===== COLLISION =====", 110,90); 
    } 
},1000/60); 

function collision(obj1,obj2){ 
    if(obj1.x < obj2.x + obj2.width * zoom && 
    (obj1.x + obj1.width * zoom) > obj2.x && 
    obj1.y < obj2.y + obj2.height * zoom && 
    (obj1.height * zoom + obj1.y) > obj2.y){ 
     return true; 
    } 
    return false; 
} 

window.addEventListener('mousewheel', function(e){ 
    if(e.deltaY>0 && zoom<2){ 
     zoom+=0.5; 
    } 

    if(e.deltaY<0 && zoom>0.5){ 
     zoom-=0.5; 
    } 
}, false); 

window.addEventListener('mousemove', function(e){ 
    mouse.x = e.pageX; 
    mouse.y = e.pageY; 

}, false); 

回答

0

我已經更新的功能和它的工作原理:

function collision(obj1,obj2){ 
    var eW = (obj1.width-(obj1.width*zoom))/2; 
    var eH = (obj1.height-(obj1.height*zoom))/2; 
    //console.log(eW); 
    if(obj1.x+eW < obj2.x + obj2.width * zoom && 
    (obj1.x + obj1.width * zoom) + eW> obj2.x && 
    obj1.y + eH < obj2.y + obj2.height * zoom && 
    (obj1.height * zoom + obj1.y) + eH > obj2.y){ 
     return true; 
    } 
    return false; 
} 
0

您是基於整個窗口,不是帆布獲得鼠標的位置。有些數學,你會得到你想要的。

test.addEventListener("mousemove", function(evt) { 
    var mousePos = getMousePos(test, evt); 
    mouse.x = mousePos.x; 
    mouse.y = mousePos.y; 
}); 

function getMousePos(canvas, event) { 
    var rect = canvas.getBoundingClientRect(); 
    return { 
    x: event.clientX - rect.left, 
    y: event.clientY - rect.top 
    }; 
} 
+0

感謝的答案,但我使用CSS中的位置是:絕對的,左:0像素;頂:0像素;但「有些數學」聽起來很有趣......;) – User9213