Image won't change when key is pressed - java

I am making my own little copy of Mario that I started today, and I am stuck on a little animation.
When UP is pressed, Mario jumps, but the sprite won't change.
I have tried if-else to set it, but it's not working:
PImage brick1;
PImage bg;
PImage Flag;
float playerX;
float playerY;
float brickX;
float Lives;
float Level;
float Time;
void setup(){
size(1000,800);
smooth();
if (keyPressed){
if (keyCode == UP){
bg = loadImage("Mario3.png");
}
}else{
bg = loadImage("Mario1.png");
}
I expect the image to change while UP is held down, but it says the "Mario1.png" sprite.

You've to implement a draw function.
Load the images in setup:
PImage bg1, bg3;
void setup() {
size(1000, 800);
smooth();
bg1 = loadImage("Mario1.png");
bg3 = loadImage("Mario3.png");
}
And draw the proper image dependent on the state of keyPressed and keyCode.
Use image() to draw an image to the display:
e.g.
void draw() {
background(0);
if (keyPressed && keyCode == UP) {
image(bg3, 0, 0);
} else {
image(bg1, 0, 0);
}
}

Related

Full screen image using canvas and bitmap

I am tryin to set an image in full screen using canvas and bitmap but whenever I load the app the image gets zoomed in and only displays half of what it's supposed to. How would I do this? I have attached my code snippet and i have tried updating the canvas.drawbitmap line of code inside the onDraw method but it doesn't help, the image still appears zoomed in. Some help would greatly be appreciated thank you in advance...
public class Fish extends View {
private Bitmap fish [] =new Bitmap[2];
private int fishX=10;
private int fishY;
private int fishSpeed;
private int canvasWidth, canvasHeight;
private int yellowX, yellowY, yellowSpeed=16;
private Paint yellowPaint=new Paint();
private int greenX, greenY, greenSpeed=20;
private Paint greenPaint=new Paint();
private int redX, redY, redSpeed=25;
private Paint redPaint=new Paint();
private int score, lifeCountOfLife;
private boolean touch=false;
private Bitmap backgroundImage;
private Paint scorePaint= new Paint();
private Bitmap life[]=new Bitmap[2];
//updates the background
public Fish(Context context) {
super(context);
fish [0]=BitmapFactory.decodeResource(getResources(),R.drawable.fish1);
fish [1]=BitmapFactory.decodeResource(getResources(),R.drawable.fish2);
//updates the bg
backgroundImage=BitmapFactory.decodeResource(getResources(),R.drawable.mn);
//creates the ball/foood color
yellowPaint.setColor(Color.YELLOW);
yellowPaint.setAntiAlias(false);
greenPaint.setColor(Color.GREEN);
greenPaint.setAntiAlias(false);
redPaint.setColor(Color.RED);
redPaint.setAntiAlias(false);
// updates score
scorePaint.setColor(Color.WHITE);
scorePaint.setTextSize(70);
scorePaint.setTypeface(Typeface.DEFAULT_BOLD);
scorePaint.setAntiAlias(true);
//displays the heart and life
life[0]=BitmapFactory.decodeResource(getResources(),R.drawable.heartts);
life[1]=BitmapFactory.decodeResource(getResources(),R.drawable.greyheart);
fishY=550;
score=0;
lifeCountOfLife=3;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvasWidth=canvas.getWidth();
canvasHeight=canvas.getHeight();
//displays it to the main actiivty
canvas.drawBitmap(backgroundImage,canvasWidth,canvasHeight,null);
int minFish= fish[0].getHeight();
int maxFishY=canvasHeight-fish[0].getHeight() *3;
fishY=fishY+fishSpeed;
if(fishY<minFish){
fishY=minFish;
}
if(fishY> maxFishY){
fishY=maxFishY;
}
fishSpeed=fishSpeed+2;
if(touch){
canvas.drawBitmap(fish[1], fishX,fishY, null);
touch=false;
}else{
canvas.drawBitmap(fish[0],fishX,fishY,null);
}
yellowX=yellowX-yellowSpeed;
//updates the score if the ball is collected
if(hitBallChecker(yellowX,yellowY)){
score=score+10;
yellowX=-100;
}
if(yellowX<0){
yellowX=canvasWidth+21;
yellowY=(int) Math.floor(Math.random() * (maxFishY-minFish))+ minFish;
}
//increases size of ball
canvas.drawCircle(yellowX, yellowY, 25, yellowPaint);
//Green ball
greenX=greenX-greenSpeed;
if(hitBallChecker(greenX,greenY)){
score=score+20;
greenX=-100;
}
if(greenX<0){
greenX=canvasWidth+21;
greenY=(int) Math.floor(Math.random() * (maxFishY-minFish))+ minFish;
}
//increases size of ball
canvas.drawCircle(greenX, greenY, 25, greenPaint);
//red ball
//if the ball gets hit
redX=redX-redSpeed;
if(hitBallChecker(redX,redY)){
redX=-100;
lifeCountOfLife--;
if(lifeCountOfLife==0){
Intent gameOverIntent= new Intent(getContext(), GameOverActivity.class);
gameOverIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
gameOverIntent.putExtra("score", score);
getContext().startActivity(gameOverIntent);
}
}
//increases size of ball
if(redX<0){
redX=canvasWidth+21;
redY=(int) Math.floor(Math.random() * (maxFishY-minFish))+ minFish;
}
canvas.drawCircle(redX, redY, 30, redPaint);
canvas.drawText("Score: " +score, 20, 60, scorePaint);
for(int i=0; i<3; i++){
int x=(int) (580+life[0].getWidth() * 1.5 * i);
int y=30;
if(i<lifeCountOfLife){
canvas.drawBitmap(life[0], x,y, null);
}else{
canvas.drawBitmap(life[1], x,y, scorePaint);
}
}
}
public boolean hitBallChecker(int x, int y){
if(fishX< x && x<(fishX+fish[0].getWidth()) &&fishY<y &&y<(fishY+ fish[0].getHeight())){
return true;
}
return false;
}
//updates fish speed
#Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_DOWN){
touch=true;
fishSpeed=-22;
}
return true;
}
}
public void drawBitmap (Bitmap bitmap,
float left,
float top,
Paint paint)
In drawBitmap left and top define the (x,y) of the top left corner of the image, which in your case should be (0,0).
If you want to draw a canvas sized backgound it would probably be best to use:
public void drawBitmap (Bitmap bitmap,
Rect src,
Rect dst,
Paint paint)
Where src is the Rect that defines the subset of the Bitmap that you want to draw (you can leave it at null to draw the entire Bitmap), and dst is the destination Rect that will automatically be filled with the Bitmap.
You are going to need to define the destination Rect:
Rect backgroundRect = new Rect(0, 0, canvas.getWidth(), canvas.getHeight());
You can now call
canvas.drawBitmap(backgroundImage,null,backgroundRect,null);

How to make a 'texture' jump up and return to starting position android java libgdx

So I am just trying to make my game character, which is a texture (ball), to jump up in the air and then return back down to the position that it started at when the screen is pressed. I was just wondering if someone could give me a code example or help me to do this with my current code which is below. I have basically just drawn the background and the ball texture and positioned the ball where I want it to start the jump. The ball texture is what I want to make jump straight up.
public class MyGdxGame extends ApplicationAdapter {
SpriteBatch batch;
Texture background;
Texture ball;
#Override
public void create () {
batch = new SpriteBatch();
background = new Texture("gamebackground.png");
ball = new Texture("ball2.png");
ball.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);
}
#Override
public void render () {
batch.begin();
float scaleFactor = 2.0f;
batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.draw(ball, 80, 145, ball.getWidth() * scaleFactor, ball.getHeight() * scaleFactor);
batch.end();
}
#Override
public void dispose () {}
}
There are a million ways to do this.
Here's a simple (and not very flexible way). Create a Ball class that has variables for x and y position, velocity, and acceleration. Then give it an update method for applying the acceleration and velocity to the position:
public class Ball {
public static final float GRAVITY = -100; // size depends on your world scale
public static final float BOUNCE_DAMPENING = 0.6f;
public final Vector2 position = new Vector2();
public final Vector2 velocity = new Vector2();
public final Vector2 acceleration = new Vector2(0, GRAVITY);
public void update (){
float dt = Gdx.graphics.getDeltaTime();
velocity.add(acceleration.x * dt, acceleration.y * dt));
position.add(velocity.x * dt, velocity.y * dt);
if (position.y <= 0){ // hit ground, so bounce
position.y = -position.y * BOUNCE_DAMPENING;
velocity.y = -velocity.y * BOUNCE_DAMPENING;
}
}
}
This is a very rudimentary way of handling physics. It would be more sophisticated to use Box2D, but the above is fine if you're just learning.
Now, you need to create a ball instance and use it to track your ball position. Use the Ball object's position when drawing it. And you can react to taps to apply a velocity.
public class MyGdxGame extends ApplicationAdapter {
SpriteBatch batch;
Texture background;
Texture ballTexture;
Ball ball;
#Override
public void create () {
batch = new SpriteBatch();
background = new Texture("gamebackground.png");
ballTexture = new Texture("ball2.png");
ballTexture.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest);
ball = new Ball();
}
#Override
public void render () {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // don't forget to clear screen
if (Gdx.input.justTouched())
ball.velocity.y += 100;
ball.update();
batch.begin();
float scaleFactor = 2.0f;
batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.draw(ballTexture, ball.position.x, ball.position.y, ballTexture.getWidth() * scaleFactor, ballTexture.getHeight() * scaleFactor);
batch.end();
}
#Override
public void dispose () {
batch.dispose();
background.dispose();
ballTexture.dispose();
}
}
You also need to read up on pixel units vs. world units and how to solve the scale problem with Viewports. See https://xoppa.github.io/blog/pixels/ and https://github.com/libgdx/libgdx/wiki/Viewports

Overlapping of Buttons with canvas for mouseinput

I am currently making a RPG hack and slash in java with just the standard libraries.
For these games , I had made a CustomButton class in an independent package that I just copy and paste in almost all of my games and then make some game-specific modifications.
This is the class::
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import objects.Collectable;
public final class CustomButton implements MouseListener {
// private BufferedImage image;
private String text = "";
private boolean pressed = false;
private int x;
private int y;
private int width;
private int height;
private Color currentColor, defaultColor, hoverColor, pressColor;
private Point mousePoint = new Point(0, 0);
private ButtonListener btnListener = null;
private Canvas canvasObject;
private BufferedImage image;
private BufferedImage darkImage;
private String actionCommand = "default";
private Collectable object;
private boolean enabled;
/*
* private CustomButton(Canvas canvasObject,JFrame frame) { this.x=100;
* this.y=100; this.width=100; this.height=100;
*
* canvasObject.addMouseListener(this); currentColor=new Color(255,255,255);
* defaultColor=new Color(255,255,255); hoverColor=new Color(255,255,255);
* pressColor=new Color(255,255,255); }
*/
public CustomButton(int x, int y, int width, int height, Canvas canvasObject) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.canvasObject = canvasObject;
canvasObject.addMouseListener(this);
currentColor = Color.GREEN;
currentColor = new Color(255, 255, 255);
defaultColor = new Color(255, 255, 255);
hoverColor = new Color(255, 255, 255);
pressColor = new Color(255, 255, 255);
enabled = true;
}
public CustomButton(int x, int y, int width, int height, Canvas canvasObject, BufferedImage image,
Collectable object) {
this.image = image;
this.darkImage = darkenImage(image);
this.x = x;
this.y = y;
this.width = width;
this.height = height;
canvasObject.addMouseListener(this);
currentColor = Color.GREEN;
currentColor = new Color(255, 255, 255);
defaultColor = new Color(255, 255, 255);
hoverColor = new Color(255, 255, 255);
pressColor = new Color(255, 255, 255);
this.canvasObject = canvasObject;
this.object = object;
enabled = true;
}
public void render(Graphics g) {
if (image == null) {
g.setColor(currentColor);
if (!pressed)
g.fillRect(this.x, this.y, width, height);
else
g.fill3DRect(this.x, this.y, width, height, true);
g.setColor(Color.BLACK);
g.drawString(text, this.x + 10, this.y + 15);
} else {
if (enabled) {
g.drawImage(image, x, y, width, height, null);
} else {
g.drawImage(darkImage, x, y, width, height, null);
}
}
}
public Rectangle getBounds() {
return new Rectangle(x, y, width, height);
}
public void tick() {
mousePoint = getMouseLocation();
changeColor();
}
private Point getMouseLocation() {
int x = 0;
int y = 0;
try {
x = (int) (canvasObject.getMousePosition().getX());
y = (int) (canvasObject.getMousePosition().getY());
} catch (NullPointerException nl) {
}
return new Point(x, y);
}
public void changeColor() {
if (!pressed) {
if (getBounds().contains(mousePoint))
currentColor = hoverColor;
else
currentColor = defaultColor;
} else {
currentColor = pressColor;
}
}
public void addButtonListener(ButtonListener btnListener) {
this.btnListener = btnListener;
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
if (enabled) {
if (btnListener != null) {
if (getBounds().contains(mousePoint)) {
ButtonID id = ButtonID.UNDETERMINABLE;
if (e.getButton() == MouseEvent.BUTTON1) id = ButtonID.LEFT;
if (e.getButton() == MouseEvent.BUTTON2) id = ButtonID.RIGHT;
btnListener.buttonClicked(new ButtonEvent(id, object, actionCommand));
}
}
}
}
public void mousePressed(MouseEvent e) {
if (getBounds().contains(mousePoint)) pressed = true;
}
public void mouseReleased(MouseEvent e) {
pressed = false;
}
public void setActionCommand(String actionCommand) {
this.actionCommand = actionCommand;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public void setDefaultColor(Color c) {
defaultColor = c;
}
public void setHoverColor(Color c) {
hoverColor = c;
}
public void setPressColor(Color c) {
pressColor = c;
}
public Collectable getObject() {
return object;
}
public void setObject(Collectable object) {
this.object = object;
}
public void destroy() {
canvasObject.removeMouseListener(this);
}
public void disable() {
enabled = false;
}
public void enable() {
enabled = true;
}
public boolean isEnabled() {
return enabled;
}
private BufferedImage darkenImage(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
image = deepCopy(image);
WritableRaster raster = image.getRaster();
for (int xx = 0; xx < width; xx++) {
for (int yy = 0; yy < height; yy++) {
int[] pixels = raster.getPixel(xx, yy, (int[]) null);
pixels[0] -= 50;
pixels[1] -= 50;
pixels[2] -= 50;
pixels[0] = Math.max(pixels[0], 0);
pixels[1] = Math.max(pixels[0], 0);
pixels[2] = Math.max(pixels[0], 0);
raster.setPixel(xx, yy, pixels);
}
}
return image;
}
private BufferedImage deepCopy(BufferedImage bi) {
ColorModel cm = bi.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
WritableRaster raster = bi.copyData(null);
return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}
}
As you can probably see from the mouseClicked() method that a event is sent to the ButtonListener class.The ButtonListener interface is also declared in the package.
This button is drawn on the canvas itself.For example, in the levelmap, there is a button in the lower-right corner, which on clicking will open the inventory.Let this button be called btn_INV.
Until now,I have been taking inputs for moving the player through the keyboard.But I plan to change keyInput to mouse input where the player will move to the tile where the user clicks on.
For that I have to make a class , sayMouseInput that implements MouseListener.Now the problem is that when I click btn_INV , not only will the button generate an event, but also, since the button is actually drawn on the canvas, the MouseInput class will also get an event as to the tile to which the player wants to moving.Now, I thought that when the MouseInput class gets a MouseEvent, it will check with the buttons as whenever there is a mouse click on the canvas, the buttons always gets informed, although it may not generate a ButtonEvent, as you can see from the code.But this is a rather bad method and highly inefficient.So , I want another method for this.
NOTE : I thought of creating another canvas for displaying the HUD and the btn_INV and other such buttons, but that does not really solve the issue as much as bypass it.
I think there's two ways to solve this problem :
The first will be to divide your game screen into two parts : one for the buttons, the other for the tiles, so you can test whilecatching a MouseEvent if the click is positionned on the tiles or not. Note that the tiles can be placed on a new button. This solution is easy to implement but you won't be able to place buttons on your tile's area.
The second will be to create a "ButtonManager". Your game class will have this button manager that will listen for mouse event and send then to the buttons. Buttons won't listen directly to this event. They will say one after one if the click is on their bounds and if no button have been fired it means that the click occured on the tiles. This method is little bit more difficult to implement but allows you to create a priority beetween buttons and so buttons would be able to have thei bounds intersecting !
Hope it helped you !
Generally speaking, concepts like button listeners are used in applications, not games.
Games generally work with a game loop which will have an update and a draw phase. During the update phase, user input is caught (well... more checked than caught, but I'll get to that in a moment) and interpreted.
So you'd just have one big mouse listener that would then check to see which button might be pressed or if the mouse is within the game area so the character should get the move command.
Of course technically that mouse listener shouldn't directly do anything, as it is bound to the swing thread. It should just change some variables (like: "left mouse button is down, position is x, y") that will then be checked in your update phase, which will then actually work with it. That way, you're no longer dependant on the swing thread (which isn't ideal for games anyway) and - almost as important - your game logic is completely predictable.
However, you'd still have to make sure your draw method gets called regularly and actually paints what and when you want it to paint. That's besides the question though, so I won't go into more detail on it.
Keep in mind that even swing isn't just some magical construct. When the mouse is clicked, swing will also iterate through all elements you have and see if one of them should get an event. If you write your own Buttons, that's what you're gonna have to do, too.
Giving each button it's own Mouse Listener will only get confusing the bigger your game gets. It will also destroy your game loop as mouse events can be thrown and caught at any time regardless of what you're doing at the moment. If your game logic happens in a seperate thread from swing (which it should), it's even possible that you get an event while you're processing something. Which will screw up your result.
This may also lead to a couple of very odd one-time errors that you don't understand and can't reproduce. So be very careful with that.

Creating a playButton in libGdx with InputHandler

I've created a game that uses 4 different GameStates: READY,RUNNING,GAMEOVER,and HIGHSCORE(variation of GAMEOVER except this one notifies the player that a highscore has been reached). My issue is that the way I've set up my InputHandler is that in the GameState.READY form the user can touch anywhere in the screen to advance into the GameState.RUNNING form. I've tried multiple tactics into creating a playButton, however nothing seems to be working my way. I created a PlayButton class as such:
public class PlayButton {
private Vector2 position;
private Rectangle boundingRectangle;
private int width;
private int height;
private PlayScreen playScreen;
public PlayButton (float x, float y, int width, int height) {
this.width = width;
this.height = height;
position = new Vector2(x, y);
boundingRectangle = new Rectangle();
}
public void update(float delta) {
boundingRectangle.set(position.x,(position.y),width,height);
}
public float getTheX() {
return position.x;
}
public float getY() {
return position.y;
}
public float getWidth() {
return width;
}
public float getHeight() {
return height;
}
public Rectangle getBoundingRectangle(){
return boundingRectangle;
}
}
and in my InputHandler i tried this:
public InputHandler(GameWrold myWorld, float scaleFactorX, float scaleFactorY){
this.myWorld = myWorld;
mySam = myWorld.getSam();
playButton = new PlayButton(45,gameHeight-75,50,-35);
buttonPlay = myWorld.getPlayButton();
int midPointY = myWorld.getMidPointY();
this.scaleFactorX = scaleFactorX;
this.scaleFactorY = scaleFactorY;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
Vector2 touchPos = new Vector2();
touchPos.set(Gdx.input.getX(), Gdx.input.getY());
Vector2 tuch = new Vector2(screenX,screenY);
buttonPlay.getBoundingRectangle();
touch = new Rectangle(touchPos.x,touchPos.y,5,5);
if (myWorld.isReady()) {
if(playButton.getBoundingRectangle().contains(touchPos)){
myWorld.start();
}
}
mySam.onClick();
if (myWorld.isGameOver() || myWorld.isHighScore()) {
// Reset all variables, go to GameState.READ
myWorld.restart();
}
return true;
}
}
As you can see I tried creating a Rectangle with the touch variable and I tried checking if touch collided with the playButton boundingRectangle like this:
if(Intersector.overlaps(touch,playButton.getBoundingRectangle())){ or
(playButton.getBoundingRectangle().overlaps(playButton.getBoundingRectangle()))
Do not invent a circle and don't break open doors.
Use Scene2d :)
It is a simple UI framework fully compatible with libGDX that allows you to create Buttons, Sliders, Windows and another widgets in about one line of code.
You will find a nice description in a link I've attached above but TLDR version is:
Create Skin and pack a texture atlas for this using TexturePacker (free version is enough usually)
Create a Stage with appropriate Viewport
Stage stage = new Stage(new FitViewport(WIDTH, HEIGHT));
Set the stage as input processor (it means that all event on the stage will be catched)
Gdx.input.setInputProcessor(stage);
Create a Button with appropriate style (defined in Skin)
Button button = new Button(skin, "style");
Attach a ClickListener with appropriate action to the Button
button.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y)
{
//some action
}
});
Set it's position and add it to the stage
button.setPosition(x, y);
stage.addActor(button);
Fire act() and draw() stage's methods in your render()
//render()
stage.act();
stage.draw();
You've earned few hours ;)

Clicklistener - different coordinates while resizing

I have a tiled map on which I set characters(every character is of the size of one tile). I managed to make them clickable, even when screen resizes everything works perfect. Every time I click on character I want a button to show up above it. For a button I use stage and place the button in the place I clicked with small transition and it also works.
My problem is when I try to use clicklistener on this button. If the screen does not resize, clicklistener works. Problem starts when the screen get resized - clicks on players works well, only button does not work - after a resize the clicking space and the button space are not aligned. For test purposes I made a test map that shows me grids. It seems that stage is not properly resized. Picture for a reference. I tried many solutions I came upon on the Internet and still can't find a solution to my problem. I have shortened my code down to a minimum basic example:
public class Test extends ApplicationAdapter {
public static Stage stage;
public TiledMap tiledMap;
static OrthographicCamera camera;
TiledMapRenderer tiledMapRenderer;
public static boolean showMenu;
GestureDetector gesture;
InputMultiplexer myInputMultiplexer;
public static int posx, posy;
public static Image move;
public Texture moveMenu;
#Override
public void create() {
moveMenu = new Texture(Gdx.files.internal("move.png"));
gesture = new GestureDetector(new MyGestureListener());
myInputMultiplexer = new InputMultiplexer();
float unitScale = 1 / 32f;
camera = new OrthographicCamera();
camera.setToOrtho(true, 33, 21);
stage = new Stage(new ScreenViewport());
stage.getViewport().setCamera(camera);
tiledMap = new TmxMapLoader().load("test.tmx");
tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap, unitScale);
myInputMultiplexer.addProcessor(stage);
myInputMultiplexer.addProcessor(gesture);
Gdx.input.setInputProcessor(myInputMultiplexer);
move = new Image(moveMenu);
move.setWidth(2);
move.setHeight(2);
move.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
move(); //my action, works fine
showMenu = false;
}
});
stage.addActor(move);
}
#Override
public void render() {
super.render();
stage.act();
tiledMapRenderer.setView(camera);
camera.update();
tiledMapRenderer.render();
if (showMenu) {
mainMenuDraw();
}
}
public static void mainMenuDraw() {
move.setPosition(posx, posy-2);
stage.draw();
}
public void resize(int width, int height) {
stage.getViewport().update(width, height, true);
}
public static OrthographicCamera getCamera() {
return camera;
}
public static Vector3 unprojectCoords(Vector3 coords) {
camera.unproject(coords);
return coords;
} }
and part of my gesturelistener:
public boolean touchDown(float x, float y, int pointer, int button) {
Vector3 temp_coord = new Vector3(x, y, 0);
Vector3 coords = Test.unprojectCoords(temp_coord);
return false;
}
#Override
public boolean tap(float x, float y, int count, int button) {
Vector3 temp_coord = new Vector3(x, y, 0);
Vector3 coords = Test.unprojectCoords(temp_coord);
Test.posx = (int) coords.x;
Test.posy = (int) coords.y;
tap = true;
Test.showMenu = true;
return false;
}
I would suggest to you read more about re-sizing and displaying pixels.
You need to recalculate pixels always when you render something.
- player, background image, buttons, events.
Actually you don't need to use resize method, just get the camera width and height.
You need to share more code, because it depends on everything.
I don't see how you are doing rendering.
tiledMapRenderer.render(), background rendering / layers?
player rendering?
menu rendering?
buttons rendering?
Example: (the same should be for event handler)
public GameButton(TextureRegion reg, float x, float y, OrthographicCamera cam) {
this.reg = reg;
this.x = x;
this.y = y;
this.cam = cam;
width = reg.getRegionWidth();
height = reg.getRegionHeight();
vec = new Vector3();
Texture tex = Game.res.getTexture("hud");
font = new TextureRegion[11];
for(int i = 0; i < 11; i++) {
font[i] = new TextureRegion(tex, 32 + i * 9, 16, 9, 9); //use height and width here)
}
}

Categories