liabru / matter-js

a 2D rigid body physics engine for the web ▲● ■
MIT License
16.37k stars 1.95k forks source link

How to move camera in matter.js world? #1287

Open TheInvoker opened 2 months ago

TheInvoker commented 2 months ago

I am making a RTS game in matter.js, similar to starcraft. One thing I want to implement is panning around with viewports.

I created the canvas and the world

const canvas = document.getElementById("canvas");

// create a renderer
var render = Render.create({
    //element: document.body,
    canvas: canvas,
    engine: engine,
    options: {
        width: 650,
        height: 600,
        hasBounds: true,
        wireframes: false, // required for images
        background: 'green'//'transparent'
    }
});

canvas.width = 600;
canvas.height = 600;

Note that I have the canvas dimensions smaller than the world dimensions. This is because the canvas dimensions represents the viewport, and the world dimensions represent the actual game dimensions.

I'm running into an issue when I want to set the viewport though. It seems to be scaling it wrong.

    Render.lookAt(render, [{
        "min": {
            "x": 50,
            "y": 0
        },
        "max": {
            "x": 600,
            "y": 600
        }
    }]);

I'm not sure how LookAt works, but its showing me a much smaller part of the game stretched into the canvas. I am trying to for example show the viewport at x=50, y=0, width=600, height=600. This is basically the viewport moved to the right most.

The goal is for game room to be large rectangle, and viewport to be smaller rectangle. image

Does anyone know how to fix it?

Thanks

epurban commented 1 month ago

Hi TheInvoker, your image seems to be unavailable. Are you still having this issue?

Xantji commented 1 month ago

Hi TheInvoker.

I solve focusing the screen with:

Bounds.shift(render, {x: xPosition, y: yPosition});
Render.world(render);

Additional info: I dont use the matter render loop. So i do rendering with 'Render.world' manually. So propably you don't need my second line of code.

I just use the matter renderer to have an physics overlay over my game world, rendered with a render framework, so my variables for x and y define the upper left corner world view of the render ramework.

I think you could solve the adjustment stuff really easy.

image