I have encountered the problem with my buttons. My code is as follows.
public class rarsterinco implements ApplicationListener {
Texture background;
Texture background2;
Texture background3;
Vector2 backgroundmove;
Vector2 backgroundmove2;
SpriteBatch batch;
Rectangle bounds;
CharSequence line = "got touched."; // = myScore;
Rectangle bounds2;
boolean check;
boolean collision;
int beginning;
CharSequence headup = "got touched";
Vector2 pos;
Vector2 position;
Vector2 size;
Vector2 size2;
BitmapFont font;
Texture mysteryCloud;
Texture mario;
Texture water;
Vector2 watermove;
Vector2 watersize;
Stage stage;
TextureAtlas buttonAtlas;
TextButtonStyle buttonStyle;
TextButton button;
Skin skin;
#Override
public void create() {
BitmapFont font = new BitmapFont();
skin = new Skin();
buttonAtlas = new TextureAtlas("buttons/pause.pack");
skin.addRegions(buttonAtlas);
buttonStyle = new TextButtonStyle();
buttonStyle.up = skin.getDrawable("imgres");
buttonStyle.over = skin.getDrawable("imgres");
buttonStyle.down = skin.getDrawable("imgres");
button = new TextButton("", buttonStyle);
stage.addActor(button);
mysteryCloud = new Texture(Gdx.files.internal("data/mysteryCloud.jpg"));
batch = new SpriteBatch();
mario = new Texture(Gdx.files.internal("data/mario.jpg"));
background = new Texture(Gdx.files.internal("data/background1.jpg"));
background2 = new Texture(Gdx.files.internal("data/background2.jpg"));
background3 = new Texture(Gdx.files.internal("data/background3.jpg"));
position = new Vector2();
pos = new Vector2();
backgroundmove = new Vector2();
backgroundmove2 = new Vector2();
size2 = new Vector2(mario.getWidth() ,mario.getHeight() );
//size2.y = trash.getHeight();
//size2.x = trash.getWidth();
size = new Vector2(mysteryCloud.getWidth() ,mysteryCloud.getHeight());
bounds= new Rectangle(pos.x, pos.y, size.x, size.y);
bounds2= new Rectangle(position.x, position.y, 32, 32);
}
#Override
public void dispose() {
//font.dispose();
}
public void update(){
bounds.set(pos.x, pos.y, 32, 32);
bounds2.set(position.x, position.y, size2.x, size2.y);
position.x = position.x + 5* Gdx.input.getAccelerometerY();
//float pos1=Gdx.input.getAccelerometerY();
//position.x = position.x - 5*pos1;
//float pos2=Gdx.input.getAccelerometerY();
//position.y = position.y - 5*pos2;
}
#Override
public void render() {
beginning = beginning+ 1;
if(beginning == 1){
backgroundmove.x = Gdx.graphics.getWidth();
}
position.y = position.y -10;
if(position.x<0){
Gdx.input.vibrate(250);
}
if(position.x>Gdx.graphics.getWidth()){
Gdx.input.vibrate(250);
}
//if(position.y<0){
//Gdx.input.vibrate(250);
//}
if(position.y>Gdx.graphics.getHeight()){
Gdx.input.vibrate(250);
}
if(bounds.overlaps(bounds2)){
collision=true;
}else{
collision= false;
}
if(position.x<0){
position.x= position.x+80;
}
if(position.x>Gdx.graphics.getWidth() - mario.getWidth()){
position.x= position.x-80;
}
if(Gdx.input.isTouched()){
position.y = position.y + 30;
}
if(position.y<0){
position.y= position.y+80;
}
if(position.y>Gdx.graphics.getWidth() +mario.getHeight()){
position.y= position.y-80;
}
pos.x = pos.x - 10;
if(pos.x <0 && collision == false){
pos.x = Gdx.graphics.getWidth();
Random randomGenerator = new Random();
pos.y = randomGenerator.nextInt(Gdx.graphics.getHeight()-30);
}
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if(Gdx.input.getAccelerometerX() == 10){
}
if(collision){
pos.x = Gdx.graphics.getWidth();
Random randomGenerator = new Random();
pos.y = randomGenerator.nextInt(Gdx.graphics.getHeight()-30);
}
backgroundmove.x = backgroundmove.x - 10;
backgroundmove2.x = backgroundmove2.x - 10;
if(backgroundmove.x <-Gdx.graphics.getWidth()){
backgroundmove.x = Gdx.graphics.getWidth();
}
if(backgroundmove2.x <-Gdx.graphics.getWidth()){
backgroundmove2.x = Gdx.graphics.getWidth();
}
update();
batch.begin();
// if(!collision){
// batch.draw(mysteryCloud, pos.x, pos.y, 64, 64);
// }
// batch.draw(mysteryCloud, pos.x, pos.y, 64, 64);
// if(collision){
// mysteryCloud.dispose();
// }
// if(pos.x<0 && collision == true){
// batch.draw(mysteryCloud, pos.x, pos.y, 64, 64);
// }
//
//batch.draw(background3, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
//batch.draw(background, backgroundmove.x, backgroundmove.y, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
//batch.draw(background2, backgroundmove2.x, backgroundmove2.y, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.draw(mario, position.x,position.y);
batch.draw(mysteryCloud, pos.x, pos.y, 64, 64);
font.setScale(4);
font.setColor(0.0f, 1.0f, 1.0f,1.0f);
stage.draw();
batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
What I realized was that when I commented the stage.draw() and the other button code my app worked, but when I uncommented the code it said mylibgdxgame has stopped working.
The button code is as follows:
TextureAtlas buttonAtlas;
TextButtonStyle buttonStyle;
TextButton button;
Skin skin;
#Override
public void create() {
BitmapFont font = new BitmapFont();
skin = new Skin();
buttonAtlas = new TextureAtlas("buttons/pause.pack");
skin.addRegions(buttonAtlas);
buttonStyle = new TextButtonStyle();
buttonStyle.up = skin.getDrawable("imgres");
buttonStyle.over = skin.getDrawable("imgres");
buttonStyle.down = skin.getDrawable("imgres");
button = new TextButton("", buttonStyle);
stage.addActor(button);
,
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: No Drawable, NinePatch, TextureRegion, Texture, or Sprite registered with name: imgres at com.badlogic.gdx.scenes.scene2d.ui.Skin.getDrawable(Skin.java:291) at com.me.rarsterinco.rarsterinco.create(rarsterinco.java:64) at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:136) at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)
Exception in thread "LWJGL Application" java.lang.IllegalArgumentException: Missing LabelStyle font. at com.badlogic.gdx.scenes.scene2d.ui.Label.setStyle(Label.java:77) at com.badlogic.gdx.scenes.scene2d.ui.Label.<init>(Label.java:71) at com.badlogic.gdx.scenes.scene2d.ui.TextButton.<init>(TextButton.java:48) at com.me.rarsterinco.rarsterinco.create(rarsterinco.java:69) at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:136) at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)
Related
I'm doing a small school project of object detection by color. When the object arrives in the center of the screen, it must have a sound. So the sound does not stay uninterrupted, I tried to put a delay on it. But every time the application arrives at the point of playing the sound, it closes. I already researched here and in other forums and the solutions presented did not work.
public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2{
static {
if(!OpenCVLoader.initDebug()){
Log.d("TAG", "OpenCV not loaded");
} else {
Log.d("TAG", "OpenCV loaded");
}
}
public void voltatela(View v) {
setContentView(R.layout.activity_main);
}
Mat imgHVS, imgThresholded;
Scalar sc1, sc2;
JavaCameraView cameraView;
int largura, altura;
public void Verde(View v) {
sc1 = new Scalar(45, 20, 10);
sc2 = new Scalar(75, 255, 255);
irTelaCamera();
}
public void Azul(View v) {
sc1 = new Scalar(80, 50, 50);
sc2 = new Scalar(100, 255, 255);
irTelaCamera();
}
public void Vermelho(View v) {
sc1 = new Scalar(110, 100, 50);
sc2 = new Scalar(130, 255, 255);
irTelaCamera();
}
public void irTelaCamera(){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.telacamera);
cameraView = (JavaCameraView)findViewById(R.id.cameraview);
cameraView.setCameraIndex(0); //0 para traseira e 1 para dianteira
cameraView.setCvCameraViewListener(this);
cameraView.enableView();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager windowmanager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
windowmanager.getDefaultDisplay().getMetrics(displayMetrics);
}
#Override
protected void onPause() {
super.onPause();
cameraView.disableView();
}
#Override
public void onCameraViewStarted(int width, int height) {
imgHVS = new Mat(width,height, CvType.CV_16UC4);
imgThresholded = new Mat(width,height, CvType.CV_16UC4);
largura = width;
altura = height;
}
#Override
public void onCameraViewStopped() {
}
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
Point centrotela = new Point((largura*0.5),(altura*0.5));
final MediaPlayer som = MediaPlayer.create(this, R.raw.bip);
Imgproc.medianBlur(imgHVS,imgHVS,1);
Imgproc.cvtColor(inputFrame.rgba(), imgHVS,Imgproc.COLOR_BGR2HSV);
Core.inRange(imgHVS, sc1, sc2, imgThresholded);
Imgproc.GaussianBlur(imgThresholded, imgThresholded, new Size(3, 3), 1, 1);
Mat circles = new Mat();
double dp = 1.2d;
int minRadius = 20;
int maxRadius = 0;
double param1 = 100, param2 = 20;
int desvio = (int) (minRadius*0.5);
Imgproc.HoughCircles(imgThresholded, circles, Imgproc.HOUGH_GRADIENT, dp, imgThresholded.rows()/4, 100, 20, minRadius, maxRadius);
int numCircles = (circles.rows() == 0) ? 0 : circles.cols();
for (int i = 0; i < numCircles; i++) {
double[] circleCoordinates = circles.get(0, i);
int x = (int) circleCoordinates[0], y = (int) circleCoordinates[1];
Point center = new Point(x, y);
int radius = (int) circleCoordinates[2];
if((((center.x-desvio) <= centrotela.x) && ((center.x+desvio) >= centrotela.x))) {
if ((((center.y-desvio) <= centrotela.y) && ((center.y+desvio) >= centrotela.y))) {
som.start();
Imgproc.circle(imgThresholded, center, radius, new Scalar(100, 255, 255), 4);
// Play sound after 2 sec delay
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
som.stop();
}
}, 2000);
}}
}
Imgproc.circle(imgThresholded,centrotela,50, new Scalar(100,255,255),7);
Imgproc.circle(imgThresholded,centrotela,25, new Scalar(100,255,255),4);
Imgproc.circle(imgThresholded,centrotela,5, new Scalar(100,255,255),-1);
return imgThresholded;
}
}
You have to write sop.start(); instead of sop.stop() inside the handler;
Have you tried playing the sound in a different thread (AsyncTask? See example here). You would have to keep track if you have already spawned a task though, otherwise, you will end up creating too many threads playing the same sound.
I am just started using libgdx , I am a newbie in game development and I want that my camera follows my sprite but it doesn't follow my sprite(Player) but rather sprite just move back and forth very little and not going upward(as I want).
Here is my show() method
public void show() {
world = new World(new Vector2(0, 25), true);
renderer = new Box2DDebugRenderer();
cam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0);
cam.update();
Gdx.input.setInputProcessor(new InputController() {
#Override
public boolean keyDown(int keycode) {
if(keycode == Input.Keys.A)
box.setLinearVelocity(0f, 60f);
if(keycode == Input.Keys.D)
box.setLinearVelocity(0f, 20f);
if(keycode == Input.Keys.ESCAPE)
((Game) Gdx.app.getApplicationListener()).setScreen(new MainMenu());
return true;
}
#Override
public boolean keyUp(int keycode) {
if(keycode == Input.Keys.A)
box.setLinearVelocity(0f, 0f);
if(keycode == Input.Keys.D)
box.setLinearVelocity(0f, 0f);
return true;
}
});
shapeRenderer = new ShapeRenderer();
batch = new SpriteBatch();
texture = new Texture("img/imgs.png");
sprite = new Sprite(texture);
sprite.setSize(47, 45);
sprite.setOrigin(sprite.getWidth()/2, sprite.getHeight()/2);
sprite.setBounds(200, 200, 64, 64);
//sprite.setPosition(Gdx.graphics.getWidth()/2 -sprite.getWidth()/2, Gdx.graphics.getHeight()/2-sprite.getHeight()/2);
//Body definition
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(0, Gdx.graphics.getHeight()/2 - 250);
box = world.createBody(bodyDef);
//Polygon Shape
PolygonShape shape = new PolygonShape();
shape.setAsBox(10, 20);
//fixture definition
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = 5f;
fixtureDef.friction = .5f;
box.createFixture(fixtureDef);
box.setUserData(sprite);
shape.dispose();
Here is my render method
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
world.step(1/60f, 6, 2);
cam.position.set(0,sprite.getY()+sprite.getHeight()/2,0);
cam.update();
batch.setProjectionMatrix(cam.combined);
batch.disableBlending();
batch.begin();
world.getBodies(tmpBodies);
for(Body body: tmpBodies)
if(body.getUserData() instanceof Sprite){
Sprite boxsprite = (Sprite) body.getUserData();
boxsprite.setPosition(body.getPosition().x - sprite.getHeight()/2, body.getPosition().y- sprite.getHeight()/2);
boxsprite.setRotation(body.getAngle() * MathUtils.radiansToDegrees);
boxsprite.draw(batch);
}
batch.end();
shapeRenderer.setColor(Color.RED);
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
shapeRenderer.rect(0, 200, 50, 50);
shapeRenderer.translate(1, 0, 0);
shapeRenderer.end();
renderer.render(world, cam.combined);
}
And Here is my resize method
public void resize(int width, int height) {
cam.viewportWidth = width;
cam.viewportHeight = height;
cam.update();
}
I've tried every possible solution but couldn't get the desired result.
I just want that my camera follows my sprite and also sprite does work properly.
please help me to provide the better solution. Thank you in advance
I have been making a game and lately i have had a problem of making an image disappear. My code is as follows
package com.me.fixGame;
import java.util.Random;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
//import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.utils.Scaling;
import com.sun.jmx.snmp.tasks.Task;
public class fixGame implements ApplicationListener {
SpriteBatch batch;
SpriteBatch spriteBatch;
Texture trash;
Texture paper;
SpriteBatch spritebatch;
Vector2 position;
Vector2 pas;
boolean collide;
boolean countMe=false;
Vector2 size;
Vector2 size2;
Vector2 pos;
Rectangle bounds;
Rectangle bounds2;
float delay = 1; // seconds
boolean counted= false;
int score = 3;
//Texture Gogreen;
String myScore;
Texture background;
CharSequence str = "Lives left: 3"; // = myScore;
CharSequence line = "Score: 0"; // = myScore;
String myLife;
int life=0;
BitmapFont font;
float x;
float y;
boolean collision = false;
#Override
public void create() {
//Gogreen = new Texture(Gdx.files.internal("data/gogreenNow.jpg"));
background = new Texture(Gdx.files.internal("data/trash.png"));
x= background.getWidth();
y=background.getHeight();
//float delaySeconds = 1;
spriteBatch = new SpriteBatch();
trash = new Texture(Gdx.files.internal("data/trash.png"));
paper = new Texture(Gdx.files.internal("data/paper1.jpg"));
position = new Vector2(100, 50);
pos = new Vector2(54, 14);
batch = new SpriteBatch();
BitmapFont font = new BitmapFont();
size2 = new Vector2(trash.getWidth() ,trash.getHeight() );
//size2.y = trash.getHeight();
//size2.x = trash.getWidth();
size = new Vector2(paper.getWidth() ,paper.getHeight());
bounds= new Rectangle(pos.x, pos.y, size.x, size.y);
bounds2= new Rectangle(position.x, position.y, size2.x, size2.y);
}
#Override
public void dispose() {
}
public void update(){
bounds.set(pos.x, pos.y, size.x, size.y);
bounds2.set(position.x, position.y, size2.x, size2.y);
position.x = position.x -2- Gdx.input.getAccelerometerX();
}
#Override
public void render() {
if(bounds.overlaps(bounds2)){
collision=true;
counted=true;
}else{
collision=false;
}
if(collision==true){
}
if(pos.y<640){
counted=false;
} else if(pos.y > 640 && collision==false && counted==false){
counted=true;
score= score-1;
myScore = "Lives left: " + score;
str = myScore;
}
if(bounds.overlaps(bounds2)){
countMe=true;
life= life+50;
myLife = "Score: " + life;
line = myLife;
}
if(position.x<0){
position.x= position.x+11;
}
if(position.x>425){
position.x= position.x-11;
}
update();
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
pos.y=pos.y-12;
if(pos.y<0){
pos.y = 700;
Random randomGenerator = new Random();
pos.x = randomGenerator.nextInt(500);
}
BitmapFont font = new BitmapFont();
batch.begin();
batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.draw(paper, pos.x, pos.y);
batch.draw(trash, position.x, position.y);
font.setScale(3);
font.setColor(0.0f, 0.0f, 1.0f,1.0f);
font.draw(batch, str, 200,900);
font.draw(batch, line, 200, 700);
batch.end();
font.dispose();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
I want to make my image called paper to disappear which I instantiate here.
x= background.getWidth();
y=background.getHeight();
//float delaySeconds = 1;
spriteBatch = new SpriteBatch();
trash = new Texture(Gdx.files.internal("data/trash.png"));
paper = new Texture(Gdx.files.internal("data/paper1.jpg"));
position = new Vector2(100, 50);
pos = new Vector2(54, 14);
batch = new SpriteBatch();
BitmapFont font = new BitmapFont();
And where i want it to disappear is below:
if(bounds.overlaps(bounds2)){
countMe=true;
life= life+50;
myLife = "Score: " + life;
line = myLife;
}
What i want to do is when the two objects overlap(bounds and bounds2) the score should be changed and one of the objects, the paper, should hide. How do i make an image hide?
Becuase you already are setting the collision state to a variable, in the render() method you just need to wrap the batch.draw() method. I've tested this code and it works. You also need to set collision to false when you set the paper back to the top, I'm guessing you want it to hide completely until it resets. Please note I've also made some small tweaks just so it's easier to test. If there are still runtime bugs it's not related to this change.
#Override
public void render() {
if (bounds.overlaps(bounds2)) {
collision = true;
counted = true;
}
if (pos.y < 640) {
counted = false;
} else if (pos.y > 640 && collision == false && counted == false) {
counted = true;
score = score - 1;
myScore = "Lives left: " + score;
str = myScore;
}
if (bounds.overlaps(bounds2)) {
countMe = true;
life = life + 50;
myLife = "Score: " + life;
line = myLife;
}
if (position.x < 0) {
position.x = position.x + 11;
}
if (position.x > 425) {
position.x = position.x - 11;
}
update();
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
pos.y = pos.y - 2;
if (pos.y < 0) {
pos.y = 700;
Random randomGenerator = new Random();
pos.x = 250;
collision = false;
}
BitmapFont font = new BitmapFont();
batch.begin();
batch.draw(background, 0, 0, Gdx.graphics.getWidth(),
Gdx.graphics.getHeight());
if (!collision) {
batch.draw(paper, pos.x, pos.y);
}
batch.draw(trash, position.x, position.y);
font.setScale(1.5f);
font.setColor(0.0f, 0.0f, 1.0f, 1.0f);
font.draw(batch, str, 20, 50);
font.draw(batch, line, 20, 100);
batch.end();
font.dispose();
}
I'm creating small balloon game. where balloons pop up randomly and disappear after a little while. When i clicked on them those i want to disappear them and show +1 instead of the balloon. When i click on the balloon, i want to deattach the balloon sprite.
My problem is when i call sprite.detachSelf() in the code, the sprite just disapears but actually the sprite hasn't being removed. It only becomes invisible. When i click again on that place the balloon appears, even after the balloon has disappear it shows +1. Which means i think the balloon hasn't deattached correctly.
Here is my code:
#Override
protected Scene onCreateScene() {
//this.mEngine.registerUpdateHandler(new FPSLogger());
scene = new Scene();
backgroundSprite = new Sprite(0, 0, this.mBackgroundTextureRegion,
getVertexBufferObjectManager());
backgroundSprite.setSize(CAMERA_WIDTH, CAMERA_HEIGHT);
scene.attachChild(backgroundSprite);
scene.unregisterTouchArea(backgroundSprite);
text = new Text(0, 0, font, "Score : 00",
getVertexBufferObjectManager());
scene.attachChild(text);
textTime = new Text(displayMetrics.widthPixels - 220, 0, font,
"00 : 60", getVertexBufferObjectManager());
scene.attachChild(textTime);
timer = new TimerClock(1, new TimerClock.ITimerCallback() {
TimerClock t = timer;
public void onTick() {
System.out.println("timer inside");
if (time > 0) {
time = time - 1;
System.out.println("timer inside : " + time);
scene.detachChild(textTime);
textTime = new Text(displayMetrics.widthPixels - 220, 0,
font, "00 : " + time,
getVertexBufferObjectManager());
if (time < 10) {
textTime.setColor(1, 0, 0);
}
scene.attachChild(textTime);
deleteSpriteSpawnTimeHandler(sprite);
}
else{
scene.unregisterUpdateHandler(this.t);
}
}
});
this.mEngine.registerUpdateHandler(timer);
createSpriteSpawnTimeHandler();
return scene;
}
private void deleteSpriteSpawnTimeHandler(final IEntity ball) {
TimerHandler spriteTimerHandler1;
final Engine e = mEngine;
this.getEngine().registerUpdateHandler(
spriteTimerHandler1 = new TimerHandler(0.5f, true,
new ITimerCallback() {
#Override
public void onTimePassed(
final TimerHandler spriteTimerHandler1) {
spriteTimerHandler1.reset();
deleteSprite(ball);
}
}));
}
private void gameOverSpawnTimeHandler() {
TimerHandler spriteTimerHandler1;
final Engine e = mEngine;
this.getEngine().registerUpdateHandler(
spriteTimerHandler1 = new TimerHandler(60, true,
new ITimerCallback() {
#Override
public void onTimePassed(
final TimerHandler spriteTimerHandler1) {
spriteTimerHandler1.reset();
timeDue = 0;
scene.detachChild(textComment);
textComment = new Text(CAMERA_WIDTH / 2 - 100,
CAMERA_HEIGHT / 2, font,
"Game Over...!!!",
getVertexBufferObjectManager());
textComment.setColor(1.0f, 0.0f, 0.0f);
scene.attachChild(textComment);
SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs",
MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
String score1 = myPrefs.getString("SCORE1", "0");
String score2 = myPrefs.getString("SCORE2", "0");
int scoreInt1 = Integer.parseInt(score1);
int scoreInt2 = Integer.parseInt(score2);
System.out.println("session in" + score1 + " "
+ score2);
currScore = totalScore;
if (currScore > scoreInt1 && currScore > scoreInt2) {
prefsEditor.clear();
prefsEditor.commit();
prefsEditor.putString("SCORE1", String.valueOf(currScore));
prefsEditor.putString("SCORE2", String.valueOf(scoreInt1));
prefsEditor.commit();
} else if (currScore < scoreInt1 && currScore > scoreInt2) {
prefsEditor.clear();
prefsEditor.commit();
prefsEditor.putString("SCORE1", String.valueOf(scoreInt1));
prefsEditor.putString("SCORE2", String.valueOf(currScore));
prefsEditor.commit();
} else {
}
}
}));
}
private void createSpriteSpawnTimeHandler() {
TimerHandler spriteTimerHandler;
final Engine e = mEngine;
this.getEngine().registerUpdateHandler(
spriteTimerHandler = new TimerHandler(0.75f, true,
new ITimerCallback() {
#Override
public void onTimePassed(
final TimerHandler spriteTimerHandler) {
spriteTimerHandler.reset();
// scene.detachChild(backgroundSprite);
// scene.attachChild(backgroundSprite);
// Random Position Generator
final float xPos = MathUtils.random(50.0f,
(CAMERA_WIDTH - 50.0f));
final float yPos = MathUtils.random(75.0f,
(CAMERA_HEIGHT - 75.0f));
gameOverSpawnTimeHandler();
if (timeDue > 0) {
createSprite(xPos, yPos);
}else{
//scene.unregisterUpdateHandler(spriteTimerHandler);
}
}
}));
}
private void createSpriteTextSpawnTimeHandler() {
TimerHandler spriteTimerHandler;
final Engine e = mEngine;
this.getEngine().registerUpdateHandler(
spriteTimerHandler = new TimerHandler(mEffectSpawnDelay, true,
new ITimerCallback() {
#Override
public void onTimePassed(
final TimerHandler spriteTimerHandler) {
spriteTimerHandler.reset();
if (totalScore > 50 && totalScore < 60) {
textComment = new Text(150, 100, font,
"Ohhhh...you are doing good.",
getVertexBufferObjectManager());
textComment.setColor(1.0f, 0.0f, 0.0f);
scene.attachChild(textComment);
}
deleteSpriteSpawnTimeHandler(textComment);
// e.getScene().detachChild(backgroundSprite);
// e.getScene().attachChild(backgroundSprite);
}
}));
}
private void createSprite(final float pX, final float pY) {
sprite = new Sprite(pX, pY, this.mrball, getVertexBufferObjectManager()) {
Engine e = mEngine;
TextureRegion gball = mgball;
float x = pX;
float y = pY;
private int score = totalScore;
private Text textComment;;
#Override
public boolean onAreaTouched(
org.andengine.input.touch.TouchEvent pSceneTouchEvent,
float pTouchAreaLocalX, float pTouchAreaLocalY) {
if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN) {
this.e.getScene().detachChild(this);
if (timeDue > 0) {
mBrushDrawingSound.play();
totalScore = totalScore + 1;
String score = "Score : " + totalScore;
scene.detachChild(text);
text = new Text(0, 0, font, score,
getVertexBufferObjectManager());
scene.attachChild(text);
//sprite.detachSelf();
createSpriteTextSpawnTimeHandler();
textScorePlus = new Text(x, y, font, "+1",
getVertexBufferObjectManager());
scene.attachChild(textScorePlus);
scene.unregisterTouchArea(textScorePlus);
deleteSpriteSpawnTimeHandler(textScorePlus);
}
} else if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP) {
}
// e.getScene().unregisterTouchArea(sprite);
return true;
}
};
spriteBalloon.add(sprite);
sprite.setSize(100, 100);
sprite.setAlpha(0.8f);
Random randomGenerator = new Random();
red = randomGenerator.nextInt(255);
green = randomGenerator.nextInt(255);
blue = randomGenerator.nextInt(255);
sprite.setColor(red, green, blue);
scene.registerTouchArea(sprite);
scene.attachChild(sprite);
deleteSpriteSpawnTimeHandler(sprite);
}
private void deleteSprite(IEntity pBall) {
IEntity gball = pBall;
scene.detachChild(gball);;
}
When you attach, you need to detach; when you scene.registerTouchArea(sprite), you need to scene.unregisterTouchArea(sprite).
I am doing simple application that should put circle on Canvas when the user taps the screen and then put that circle in the PhysicalWorld I have defined.
I draw the circle in "onDraw" method, but when it is created its position does not change (seems like the gravity and staff are not applied) and the circle is static (stays on the position where it's created).
can you check this code and tell me if I am doing anything wrong:
[update]
public class PhysicsWorld extends SurfaceView implements SurfaceHolder.Callback {
private AABB worldAABB;
private World world;
private PolygonDef groundShapeDef;
public int W_width, W_height;
private static final String TAG = PhysicsWorld.class.getSimpleName();
protected static final int GUIUPDATEIDENTIFIER = 0x231;
public int targetFPS = 40;
public float timeStep = (10.0f/targetFPS);
public int iterations = 5 ;
private int count=0;
private Body[] theBodies ;
private Paint paint;
private float radius = 20;
private MyThread mMyThread;
public PhysicsWorld(Context context) {
super(context);
}
public PhysicsWorld(Context context, AttributeSet set) {
super(context, set);
getHolder().addCallback(this);
W_width = 500;
W_height = 700;
worldAABB = new AABB();
Vec2 min = new Vec2(-50, -50);
Vec2 max = new Vec2(W_width+50, W_height+50);
worldAABB.lowerBound.set(min);
worldAABB.upperBound.set(max);
Vec2 gravity = new Vec2((float) 10.0, (float) 9.8);
boolean doSleep = false;
world = new World(worldAABB, gravity, doSleep);
BodyDef groundBodyDef = new BodyDef();
groundBodyDef.position.set(new Vec2((float) 0.0, (float) -10.0));
Body groundBody = world.createBody(groundBodyDef);
groundShapeDef = new PolygonDef();
groundShapeDef.setAsBox(W_width, 10);
groundBody.createShape(groundShapeDef);
// up :
groundBodyDef = new BodyDef();
groundBodyDef.position.set(new Vec2((float) 0.0, (float) (W_height + 10.0)));
groundBody = world.createBody(groundBodyDef);
groundShapeDef = new PolygonDef();
groundShapeDef.setAsBox(W_width, 10);
groundBody.createShape(groundShapeDef);
// left :
groundBodyDef = new BodyDef();
groundBodyDef.position.set(new Vec2(-10, (float) 0.0));
groundBody = world.createBody(groundBodyDef);
groundShapeDef = new PolygonDef();
groundShapeDef.setAsBox(10, W_height);
groundBody.createShape(groundShapeDef);
// right :
groundBodyDef = new BodyDef();
groundBodyDef.position.set(new Vec2((float) W_width + 10, (float) 0.0));
groundBody = world.createBody(groundBodyDef);
groundShapeDef = new PolygonDef();
groundShapeDef.setAsBox(10, W_height);
groundBody.createShape(groundShapeDef);
theBodies = new Body[50];
paint = new Paint();
paint.setStyle(Style.FILL);
paint.setColor(Color.RED);
paint.setAntiAlias(true);
// setWillNotDraw(false);
}
public void addBall(int x, int y) {
BodyDef bodyDef = new BodyDef();
bodyDef.position.set(x, y);
Log.d(TAG,"Ball Created At: " + Integer.toString(x) + "," + Integer.toString(y));
theBodies[count] = world.createBody(bodyDef);
CircleDef circle = new CircleDef();
circle.radius = radius;
circle.density = (float) 1.0;
circle.restitution = 0.5f;
theBodies[count].createShape(circle);
theBodies[count].setMassFromShapes();
count+=1;
}
public void update() {
world.step(timeStep, iterations);
postInvalidate();
}
#Override
protected void onDraw(Canvas canvas) {
paint = new Paint();
paint.setStyle(Style.FILL);
paint.setColor(Color.RED);
for (int j = 0; j < count; j++) {
canvas.drawCircle(theBodies[j].getPosition().x, W_height - theBodies[j].getPosition().y, radius, paint);
Log.v(TAG + " x: ", String.valueOf(theBodies[j].getPosition().x));
Log.v(TAG + " y:", String.valueOf(W_height - theBodies[j].getPosition().y));
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
addBall((int)event.getX(),(int)event.getY());
}
return true;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
mMyThread = new MyThread(holder, this);
mMyThread.setFlag(true);
mMyThread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
My experience with box2D is in C++ and iPhone, but it seems your forgetting to make the Ball dynamic.
I've kinda guessed at the solution as I don't know the exact syntax for JBox2D (Please edit if anyone knows actual code)
bodyDef.type = BodyDef.dynamicBody;
I've had a look at the documentation on google code and I think you should use world.createDynamicBody(bodyDef);