bberak / react-game-engine

A lightweight Game Engine for the web (React) 🕹⚡🎮
MIT License
413 stars 24 forks source link

Change initial position of a game object origin so that it calculates everything from the centre? #8

Closed michaelcuneo closed 4 years ago

michaelcuneo commented 4 years ago

This is more of a usage question than anything else, I have a bunch of balls up on the screen, continuing on from the previous project I was working on late last year. They resize and move, but they do it from the top left hand corner which is I suspect the default origin for the .CSS components. I have set

Change initial position of a game object origin so that it calculates everything from the centre?

I appear to need to have the ball set as absolute to force it to stay on the screen in it's own space, without making the other components resize when I move them around, but this forces me to use top: left: positions, which throws it all out.

bberak commented 4 years ago

Hi @michaelcuneo,

Apologies if I have misunderstood your query..

I generally set the styles of all of my game objects to be position: "absolute". After this, I logically consider all entities as being positioned from their centre and perform the offset in the renderer. It just helps with handling touch inputs and interfacing with physics plugins and other libraries

This does mean that I need to track (or hardcode) the size of the entity though:

//-- Box entity

import React, { PureComponent } from "react";

class Box extends PureComponent {
  render() {
    const size = 100;
    const x = this.props.x - size / 2;
    const y = this.props.y - size / 2;
    return (
      <div style={{ position: "absolute", width: size, height: size, backgroundColor: "red", left: x, top: y }} />
    );
  }
}

export { Box };

//-- GameEngine

import React, { PureComponent } from "react";
import { GameEngine } from "react-game-engine";
import { Box } from "./renderers";
import { MoveBox } from "./systems"

export default class SimpleGame extends PureComponent {
  render() {
    return (
      <GameEngine
        style={{ width: 800, height: 600, backgroundColor: "blue" }}
        systems={[MoveBox]}
        entities={{
          //-- Notice that each entity has a unique id (required)
          //-- and a renderer property (optional). If no renderer
          //-- is supplied with the entity - it won't get displayed.
          box1: { x: 200,  y: 200, renderer: <Box />}
        }}>

      </GameEngine>
    );
  }
}
michaelcuneo commented 4 years ago

Hey Thanks,

I'll double check this evening to make sure I'm doing the math properly on my objects. Must be where I'm going wrong.

michaelcuneo commented 4 years ago

Yes, it was just a matter of my CSS... Thanks.