User9213
User9213

Reputation: 130

Javascript/Canvas: Mouse coordinates don't match after scaling (collision)

After resizing the square, there is a collision problem, GIF animation problem, sample https://jsfiddle.net/8jkxdhfv/. What can i do? Should i untransformed mouse coordinates to transformed coordinates ? But how? How can i update x and y in my collision function?

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

Upvotes: 0

Views: 945

Answers (2)

User9213
User9213

Reputation: 130

I have updated the function and it works:

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

Upvotes: 0

Oen44
Oen44

Reputation: 3206

You are getting mouse position based on entire window, not canvas. Some math and you will get what you want.

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

Upvotes: 1

Related Questions