I am trying to animate one of my TiledSprites after the player makes contact with the sprite. Here is my code so far:
levelObject = new AnimatedSprite(x, y, resourceManager.wooden_crate_region, vbom)
{
#Override
protected void onManagedUpdate(float pSecondsElapsed)
{
super.onManagedUpdate(pSecondsElapsed);
if (player.collidesWith(this))
{
addToScore(1);
final long[] CRATE_ANIMATE = new long[] { 1000, 1000, 1000, 10000};
this.animate(CRATE_ANIMATE, 0, 3, true);
this.setIgnoreUpdate(true);
}
}
};
But when I try to play the game, the player makes contact and goes through the sprite. Not sure whats going on. It does add the score, but no animation.
Any help would be appreciated.
remove the line
this.setIgnoreUpdate(true);
this line ignores any update on your object, means it won't animate it either.
Related
While trying to develop a small game with LibGDX, I have a behavior that I don't explain : when I run my game in Android Studio Emulator (Nexus 5X API28) and on my phone (Samsung Galaxy S20), I have noticed a difference that I can't explain :
on the emulator, the touch (emulated with a click) is detected as expected
on my phone the touch is detected ~50-100 pixel higher than expected
My guess is that there is something to do with the way LibGDX handle the phone resolution and/or ratio
Here is a sample of the type of code I have:
LevelScreen(final PixGame game) {
this.game = game;
mTouchPoint = new Vector3();
camera = new OrthographicCamera();
camera.setToOrtho(false, 720, 1280);
FitViewport viewport = new FitViewport(720, 1280, camera);
Gdx.gl.glViewport(0, 0, 720, 1280);
viewport.update(game.ScreenWidth, game.ScreenHeight, true);
mStage = new Stage(viewport);
InputProcessor processor1 = new InputAdapter() {
#Override
public boolean touchDown(int x, int y, int pointer, int button) {
game.mTouchUp = false;
return false;
}
#Override
public boolean touchUp(int x, int y, int pointer, int button) {
game.mTouchUp = true;
return false;
}
};
InputMultiplexer inputMultiplexer = new InputMultiplexer(processor1,mStage);
Gdx.input.setInputProcessor(inputMultiplexer);
Gdx.graphics.setContinuousRendering(false);
}
#Override
public void render(float delta) {
if(game.mTouchUp) {
mTouchPoint.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(mTouchPoint);
game.mTouchUp = false;
Gdx.app.debug("TOUCH", "Touchpoint coordinates : " + mTouchPoint);
}
}
I have removed all the game part on the code above, this is just the way I detect and handle touch event (and probably it's not the smartest way but hey, I'm not a pro-developer).
I have a PNG image as a background, and if I touch the same spot on the emulator and on my phone, I have the following result :
EMULATOR : Touchpoint coordinates : (90.0,1103.7681,0.0)
PHONE : Touchpoint coordinates : (95.33334,1054.3251,0.0)
The X coordinate is about the same (within the margin of error of my finger), the Y coordinate has always a minus 50-100px gap. I have tested many times on different positions on the screen and still the same behavior.
Any guess what I should do to handle this? Maybe the difference of screen ratio between the two (16:9 vs 16:10) ? Many thanks for the help.
After different tries, I've figured out what was happening : the problem was indeed coming from the ratio that is different between the two phones (16:9 vs 16:10).
In order to neutralize that, I have changed the line
FitViewport viewport = new FitViewport(720, 1280, camera);
with
Viewport viewport = new ScalingViewport(Scaling.stretch, 720, 1280, camera);
This is now handling the touch coordinates the same way on the 2 devices.
My teacher is having us write code to draw a logo on the screen using awt, swing, and the graphics class. I decided to draw the google drive symbol, but I am getting stuck on the yellow third.
public class DriveLogo extends JApplet
{
public void init()
{
JRootPane rootPane = this.getRootPane();
rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
}
public void paint(Graphics g)
{
int num_rect_points = 4;
g.setColor(Color.black);
g.fillRect(0,0,getSize().width, getSize().height);
/*************************************Yellow 1/3**********************************/
//Order of vertices: Left, right, lower-right, lower-left
int p1x1 = 150, p1x2 = 250, p1x3 = 350, p1x4 = 300;
int p1y1 = 25, p1y2 = 25, p1y3 = 280, p1y4 = 280;
int[] poly_1_x = {
p1x1, p1x2, p1x3, p1x4
};
int[] poly_1_y = {
p1y1, p1y2, p1y3, p1y4
};
Polygon yellow = new Polygon(poly_1_x, poly_1_y, num_rect_points);
/*************************************Draw**********************************/
g.setColor(Color.yellow);
g.fillPolygon(yellow);
}
}
This produces the following result:
There should be a yellow rhombus/rectangle slanted to the left. I asked my teacher, and she reviewed my code, but could not isolate the problem, and told me it "should" be working. Should doesn't mean it is however, and this is a rather large grade. Spent most of two class periods and downloaded the project to my home computer to debug, but I just can't seem to figure out what the problem is.
Things I know; the polygon coordinates must be in order, so to draw a rectangle, I cannot list them top-left, bottom-right, bottom-left, top-right, but I can list them top-left, top-right, bottom-right, bottom-left.
Okay, I solved this by experimenting around. For whatever reason, the call to g.fillPolygon(Polygon p) was not working, but when I called g.fillPolygon(poly_1_x, poly_1_y, num_recto_points); it worked properly.
I'm trying to learn the 3D side of LibGDX, and I've came to a problem. I want to draw a line from 0, 0, -5 to 0, 0, 5. I've tried a few things to make this work.
First I looked to see if I could create a line as a Model. As far as I can see, I can't do this.
What I then realised is that theoretically I can draw a line using a ShapeRenderer. Here's my code to try to do this.
public class Main implements ApplicationListener {
...
public ShapeRenderer srend;
...
#Override
public void create() {
...
srend = new ShapeRenderer();
srend.setColor(Color.RED);
...
}
#Override
public void render() {
...
srend.begin(ShapeType.Line);
srend.line(0, 0, -5, 0, 0, 5);
srend.end();
...
}
...
}
But for some reason this doesn't appear to work. I use ShapeRenderers a lot, but it's possible that I'm making a mistake initializing or using it, I don't think that's the problem though.
I've only just started using the 3D part of LibGDX, so I assume the problem is around where I'm drawing the actual line.
Model Builder works well for me.
ModelBuilder modelBuilder = new ModelBuilder();
modelBuilder.begin();
MeshPartBuilder builder = modelBuilder.part("line", 1, 3, new Material());
builder.setColor(Color.RED);
builder.line(0.0f, 0.0f, -5.0f, 0.0f, 0.0f, 5.0f);
lineModel = modelBuilder.end();
lineInstance = new ModelInstance(lineModel);
You need to set camera matrix before rendering:
#Override
public void create() {
...
srend = new ShapeRenderer();
srend.setProjectionMatrix(new Matrix4())
srend.setColor(Color.RED);
...
}
I don't know why, but this helps. Matrix4() is just identity matrix. With identity camera matrix right side of the screen has coordinate 1, left -1. So if coordinates inside cube -1..1, you should see them.
In real code (for example, for drawing gizmos in 3d world) you can set matrix from PerspectiveCamera:
shapeRenderer.setProjectionMatrix(camera.combined)
I am trying to add text for debugging purposes in my program. I call the players debugDraw method like so in the main class:
public void create () {
//Initialize essentials
cam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.setToOrtho(false);
rend = new ShapeRenderer();
rend.setAutoShapeType(true);
batch = new SpriteBatch();
// Initialize Entities
player = new Player(new Vector2(100, 100), new Vector2(100,100));
enemy = new Enemy(new Vector2(100, 100), new Vector2(100,10));
}
#Override
public void render () {
//Update player
player.update();
//Update camera then set matrix of batch
cam.update();
batch.setTransformMatrix(cam.combined);
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// ShapeRenderer begin
rend.begin();
player.render(rend);
enemy.render(rend);
rend.end();
// ShapeRenderer end
// SpriteBatch begin
batch.begin();
player.renderDebugText(batch);
batch.end();
// SpriteBatch end
}
Here is the entity class which is the parent class to player:
public Entity(Vector2 coords, Vector2 dims){
//Assign constructors
position = coords;
dim = dims;
//For debugging purposes of all entities
debugText = new BitmapFont();
debugText.setColor(Color.WHITE);
}
public void renderDebugText(SpriteBatch batch){
debugText.draw(batch, "Vel.x: " + vel.x, 100, 100);
}
However when I run the program, I just get my normal screen with no text at all. I can't seem to figure out why this isn't working. Any help is extremely appreciated.
Nothing immediately looks wrong with the code you posted, so here's a few ideas;
The default BitmapFont is 15pt, if this is drawn at 15px height then it could be very small if you force your game to a high resolution, like Full-HD. My current project is Full-HD and the font I use looks just about right at 45px, so you could try scaling yours by a factor of 3 or 4. E.g. use this after initialising your font;
bitmapFont.getData().setScale(3);
Your Camera should also have the virtual/viewport dimensions, so if you are forcing a particular resolution then you should pass in your virtual dimensions instead.
As #Tenfour04 has suggested, you should try to avoid multiple instances of the same font, so instead of initialising your font in the Entity class, initialise it in your main game and pass it through the Entity constructor. I can't see how this would fix your issue though as this would be purely for performance.
I made a very simple mistake, but from how much code I posted, it is easily missed. On the line where I put
batch.setTransformMatrix(cam.combined);
it should be replaced with
batch.setProjectionMatrix(cam.combined);
Then all errors go away, sorry, I don't know why it took me so long to figure out. Thanks for all the help!
I am writing a game for Android using AndEngine GLES 2. Everything was working properly - I had a background image, there were sprites moving around and even some music - until recently I tried something new (I wanted to be able to switch between two different scenes) when the display turned black.
I could still execute the game and there were no error shown. All log entries I made during the game were shown, even the music was playing so I knew the game was running "properly", but I couldn't see any image. Nothing. All black.
So I thought, changing everything back to before this "error" appeared, would do the trick. But still the screen is black.
I even tried commenting everything out but the background image - nothing.
Now if it is not too much to ask, could anyone please look over this short piece of code and tell me what is wrong there?
This are the variables I use:
private SmoothCamera camera;
private BitmapTextureAtlas bitmapTextureAtlas;
private Scene scene;
private Sprite background;
The EngineOptions I never changed, so they should be alright.
#Override
public EngineOptions onCreateEngineOptions() {
float positionX = 80f; // horizontal (x) position of the camera
float positionY = 280f; // vertical (y) position of the camera
float velocityX = 200f; // velocity of the horizontal camera movement
float velocityY = 200f; // velocity of the vertical camera movement
float zoomFactor = 1f; // the camera's zoom Factor (standard := 1)
this.camera = new SmoothCamera(positionX, positionY, this.getWindowManager().getDefaultDisplay().getWidth(), this.getWindowManager().getDefaultDisplay().getHeight(), velocityX, velocityY, zoomFactor);
EngineOptions options = new EngineOptions(true, ScreenOrientation.LANDSCAPE_SENSOR, new RatioResolutionPolicy(this.camera.getWidth(), this.camera.getHeight()), this.camera);
return options;
}
Here I create the TextureAtlas and load a background image.
#Override
protected void onCreateResources() {
// create the TextureAtlas
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.bitmapTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 1024, 1600, TextureOptions.NEAREST);
// background
this.background = new Sprite(0, 0, BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.bitmapTextureAtlas, this, "background.png", 0, 0, 1, 1), this.getVertexBufferObjectManager());
this.mEngine.getTextureManager().loadTexture(this.bitmapTextureAtlas);
}
And finally the Scene is instantiated and the background gets attached.
#Override
protected Scene onCreateScene() {
this.scene = new Scene();
this.scene.attachChild(this.background);
return this.scene;
}
Now why would this small Activity not show? I forgot: its a SimpleBaseGameActivity.
Well, since AndEngine GLES2 is not running on the emulator, I have to use my phone (Samsung Galaxy GIO) and can't test the app on another machine.
Did anyone stumble upon a similar problem?
Any help is really much appreciated and thank you for your time !
Christoph
I think the problem is here:
this.bitmapTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 1024, 1600, TextureOptions.NEAREST);
The dimensions of the Atlas are supposed to be powers of 2.