Reputation: 161
So I have two objects. SquareA and SquareB. SquareA follows the movement of the cursor. Now I want to make SquareB mirror the movement of SquareA but in reverse.
Example:
SquareA goes left, SquareB goes right. SquareA goes down, SquareB goes up.
I currently have this code to make squareB follow squareA
// update squareA to mouse
squareA.x = mouseX - (squareB.width * .5);
squareA.y = mouseY - (squareB.height * .5);
// update squareB to squareA
squareB.x = squareA.x;
squareB.y = squareA.y - (squareA.height * 2);
But I can't think of a way to reverse squareB's movement.
Here's the pen for the problem
https://codepen.io/ricjonsu098/pen/xxZrvZP?editors=0010
Upvotes: 1
Views: 202
Reputation: 12035
Full solution:
// create a canvas to work with
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
// style canvas
canvas.id = "canvas";
canvas.width = 400;
canvas.height = 400;
canvas.setAttribute("style", "border: 1px solid black;");
// get 2D context
var context = canvas.getContext('2d');
var squareA = {x:10, y:30, width: 25, height: 25 };
var squareB = {x:10, y:30, width: 25, height: 25 };
// place holders for mouse x,y position
var mouseX = 0;
var mouseY = 0;
var centerX = canvas.width/2;
var centerY = canvas.height/2;
// Render Loop
function update() {
// update squareA to mouse
squareA.x = mouseX - (squareB.width * .5);
squareA.y = mouseY - (squareB.height * .5);
// update squareB to squareA
squareB.x = centerX - (squareA.x - centerX);
squareB.y = centerY - (squareA.y - centerY);
// clear the canvas
canvas.width = canvas.width;
// draw first rectangle
context.fillStyle = "blue";
context.fillRect (squareA.x,squareA.y,squareA.width,squareA.height);
// draw second rectangle
context.fillStyle = "green";
context.fillRect (squareB.x,squareB.y,squareB.width,squareB.height);
}
// update mouse position
canvas.onmousemove = function(e) {
mouseX = e.offsetX;
mouseY = e.offsetY;
update();
}
Note that I got rid of the interval. You can just update whne the mouse moves.
Upvotes: 1
Reputation: 4562
I hope this helps, 400 is canvas size
// update squareA to mouse
squareA.x = mouseX;
squareA.y = mouseY;
// update squareB to squareA
squareB.x = 400 - squareA.x;
squareB.y = 400 - squareA.y;
Upvotes: 1