During rotation, the block runs into two static blocks side by side. How to prevent collisions?
var CELLSIZEPIX = 64;
var SPEED = 0.02;
var FRICTION = 0;
var RESTITUTION = 1;
var SLOP = 0.05;
var FRICTIONAIR = 0.2;
var tank;
var bodies = [];
var engine = Matter.Engine.create();
engine.world.gravity.y = 0;
var render = Matter.Render.create({
element: document.getElementById("canvas_div"),
engine: engine,
options: {
width: 600,
height: 400,
hasBounds: true,
showAngleIndicator: true
}
});
tank = Matter.Bodies.rectangle(
64,
64,
110,
90,
{
friction: FRICTION,
frictionAir: FRICTIONAIR,
frictionStatic: 10,
dencity: 1,
restitution: RESTITUTION,
slop: SLOP
}
);
bodies.push(tank);
var block1 = Matter.Bodies.rectangle(0, 0, CELLSIZEPIX, CELLSIZEPIX, {
friction: FRICTION,
isStatic: true,
restitution: RESTITUTION,
slop: SLOP
});
bodies.push(block1);
var block2 = Matter.Bodies.rectangle(128, 128, CELLSIZEPIX, CELLSIZEPIX, {
friction: FRICTION,
isStatic: true,
restitution: RESTITUTION,
slop: SLOP
});
bodies.push(block2);
Matter.World.add(engine.world, bodies);
Matter.Render.run(render);
var keyboards = {};
var eInfo = document.getElementById("info");
(function run() {
window.requestAnimationFrame(run);
Matter.Engine.update(engine, 1000 / 60);
for (var p in keyboards) {
switch (+p) {
case 65: { // A
Matter.Body.rotate(tank, -0.02);
break;
}
case 87: { // W
var dx = -SPEED * Math.cos(tank.angle);
var dy = -SPEED * Math.sin(tank.angle);
Matter.Body.applyForce( tank, {x: tank.position.x, y: tank.position.y}, {x: dx, y: dy});
break;
}
case 68: { // D
Matter.Body.rotate(tank, 0.02);
break;
}
case 83: { // S
var dx = SPEED * Math.cos(tank.angle);
var dy = SPEED * Math.sin(tank.angle);
Matter.Body.applyForce( tank, {x: tank.position.x, y: tank.position.y}, {x: dx, y: dy});
break;
}
}
}
Matter.Render.lookAt(render, tank, { x: 200, y: 200 });
eInfo.innerText = "Tank: x=" + (tank.position.x).toFixed(1) + ", y=" + (tank.position.y).toFixed(1) + ", angle=" + (tank.angle / Math.PI * 180).toFixed(1) + "\nBodies count=" + bodies.length;
})();
addEventListener("keydown", onKeyDown, false);
addEventListener("keyup", onKeyUp, false);
function onKeyDown(e) {
keyboards[e.keyCode] = 1;
}
function onKeyUp(e) {
delete keyboards[e.keyCode];
}
See working example here: https://jsfiddle.net/azdm9ns1/3/
You can move and rotate the central unit using the keys A, S, D, W.