java - Player can move off screen? -


so, i'm creating simple 2d video game. noticed player can move off screen, added code:

if (newx <= size * tagscanvas.scale) {             newx = size * tagscanvas.scale;         } else if (newx >= tagscanvas.canvas_width - (size * tagscanvas.scale) - getaabb().getradx()) {             newx = tagscanvas.canvas_width - (size * tagscanvas.scale) - getaabb().getradx();         }          if (newy <= size * tagscanvas.scale) {             newy = size * tagscanvas.scale;         } else if (newy >= tagscanvas.canvas_height - (size * tagscanvas.scale) - getaabb().getrady()) {             newy = tagscanvas.canvas_height - (size * tagscanvas.scale) - getaabb().getrady();         } 

tagscanvas.canvas_width width of canvas object. height height of canvas object. size size of player, , scale scale of game (at moment it's 2). getaabb().getradx() returns radius center of player edge (the 'player' square box).

now, x works fine, y part doesn't. it'll block player moving off map (the first statement), let player go 20 points far down. appreciated!

what can have wraparound using modulo operator (i.e. remainder after integer division).

say want move 5 units: have method:

public void move(int amt){  pos = (pos + amt) % tagscanvas.canvas_width. } 

the modulo operator makes sure value never equal or greater tagscanvas.canvas_width.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -