0
\$\begingroup\$

I am making a multiplayer game with gravity mechanics and planetary motion. I started by hard coding coordinates according to canvas size but now I am realizing that for different resolution planet position would not be the same. for same resolution devices collision would occur but in devices with different resolution planets would miss each other by few pixels. I searched about this issue and everyone is suggesting to convert world coordinate to device coordinate. I tried it but it's not working, maybe I am doing something wrong. I have attached code for planet motion. If anyone can help with the conversion it would be much appreciated.

class Planet{
    constructor(x, y, radius, color, mass, context, blackhole, canvasWidth, canvasHieght,ratio) {
      this.canvasWidth = canvasWidth;
      this.canvasHieght = canvasHieght;
      this.color=color;
      this.x = x;
      this.y = y;
      this.acclx = 0.001;
      this.accly = 0.001;
      this.mass = mass;
      this.r = 0.0;
      this.ctx = context; 
      this.max = 1;
      this.min = -1;
      this.radius = radius;
      this.dirx = Math.floor(Math.random() * (+this.max - +this.min)) + +this.min;
      this.diry = Math.floor(Math.random() * (+this.max - +this.min)) + +this.min;
      if (this.dirx == 0 && this.diry == 0) {
        this.dirx = -1;
        this.diry = 1
      }
      this.speedx = Math.sqrt(Math.sqrt(Math.pow(blackhole.x - this.x, 2) + Math.pow(blackhole.y - this.y, 2)) * this.acclx) * this.dirx;
      this.speedy = Math.sqrt(Math.sqrt(Math.pow(blackhole.x - this.x, 2) + Math.pow(blackhole.y - this.y, 2)) * this.accly) * this.diry;
      this.speedx=this.speedx/ratio;
      this.speedy=this.speedy/ratio;
    }
    
    move() {
      if(this.x> this.canvasWidth)
        this.x=0;
      else if(this.x<0)
          this.x= this.canvasWidth;
      else if(this.y<0)
          this.y= this.canvasHieght;
      else if(this.y> this.canvasWidth)
          this.y=0;     
      this.x+=this.speedx;
      this.y+=this.speedy;
      this.ctx.beginPath();
      this.ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
      this.ctx.fillStyle=this.color;
      this.ctx.fill();
      //this.ctx.stroke();
    }
      }

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.