Jump to content
This forum will be closing down. Please move to the respective dedicated project forums.

Click position in scaled game


Dower
 Share

Recommended Posts

This is probably going to be a simple answer, but it's eluding me.

I setup a simple game object and I want to move the position of my sprite to a touched/clicked location in the game world. But the event.x and event.y don't seem to line up, since I have the scaleMode set. I seem to be missing some sort of offset to get the click location. The bird.png fie is just a simple 50x50 cube.

 

Here's my code for reference (I bolded the code that seems to be my trouble spots), thanks for any assitance:

 

var mainState = {
  preload: function() {
    // Scale our game
    this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
    this.scale.pageAlignHorizontally = true;
    this.scale.pageAlignVeritcally = true;
    
    this.stage.backgroundColor = "#71c5cf";
    this.load.image("bird", "assets/bird.png"); 
  },
  create: function() {
    // create our sprites
    this.bird = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, "bird");
    this.bird.anchor.setTo(0.5,0.5);
 
    // Detect Input on Screen
    this.game.input.onDown.add(this.moveMe, this);
    
  },
  update: function() {
  },
  moveMe: function(sprite, event) {
    this.bird.x = event.x;
    this.bird.y = event.y;
  }
  
};
 
var game = new Phaser.Game(400, 490, Phaser.AUTO);
 
game.state.add("main", mainState);
game.state.start("main");
 
Link to comment
Share on other sites

 

get the pixelRatio value:

var = pixelRatio = originallWidth / scalledlWidth

and calculate result:

this.bird.x = event.x / pixelRatio;

 

Hmm I tried this but it still doesn't seem right. I found that the game object has it's own width and height and so does the game.scale.

 

So here's the change I made to the moveMe Function:

 

  moveMe: function(sprite, event) {
    var pixelRatioX = this.game.width / this.game.scale.width;
    var pixelRatioY = this.game.height / this.game.scale.height;
    var nX = event.x / pixelRatioX;
    var nY = event.y / pixelRatioY;
    
    this.bird.x = nX;
    this.bird.y = nY;
  }

 

Even with the change, the positioning isn't quite right. I do notice that when the game starts it starts in the 400x460 size and quickly scales up to fill the screen.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...