I am trying to develop my very first android game and it is game named "brick breaker". I believe everyone knows it.
Everything was fine until i came to the ball bouncing part.
To handle collisions I use this found code :
scene.registerUpdateHandler(new IUpdateHandler() {
public void reset() { }
public void onUpdate(final float pSecondsElapsed) {
if(ball.collidesWith(paddle)) {
ball.bounceWithRectangle(paddle);
}
else if (ball.getY() >= Game.getCAMERA_HEIGHT() - 30) {
scene.setBackground(new ColorBackground(255f, 0f, 0f));
}
else {
for (int i = 0; i < bricks.length; i++) {
for (int j = 0; j < bricks[0].length; j++) {
scene.setBackground(new ColorBackground(0f, 0f, 0f));
if(ball.collidesWith(bricks[i][j])) {
bricks[i][j].setPosition(CAMERA_HEIGHT+20, CAMERA_WIDTH+20);
scene.getTopLayer().removeEntity(bricks[i][j]);
ball.bounceWithRectangle(bricks[i][j]);
}
}
}
}
}
});
And this is how Ball.java class looks like:
package com.example.zaidimas;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.entity.primitive.Rectangle;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import java.lang.Math;
public class Ball extends AnimatedSprite {
float velocity = 100;
int i =0;
private Engine mEngine;
public Ball(float positionX, float positionY, TiledTextureRegion positionTextureRegion, Engine mEngine) {
super(positionX, positionY, positionTextureRegion);
this.mEngine = mEngine;
}
protected void onManagedUpdate(final float pSecondsElapsed) {
if(this.mX < 0) {
this.setVelocityX(velocity);
} else if(this.mX + this.getWidth() > Game.getCAMERA_WIDTH()) {
this.setVelocityX(-velocity);
}
if(this.mY < 0) {
this.setVelocityY(velocity);
} else if(this.mY + this.getHeight() > Game.getCAMERA_HEIGHT()) {
this.setVelocityY(-velocity);
}
super.onManagedUpdate(pSecondsElapsed);
}
public void bounceWithRectangle(Rectangle rectangle){
this.setVelocityY(-this.getVelocityY());
}
}
It works and it is pretty clear.
But the problem is that the ball always bounces in the same angle from all surfaces. I think that angle is 90 degrees.
- I would love to know how to make ball bounce in different angles, how to calculate theese angles and all other informacion which would help to make game more realistic.
I already found some information, but i can not adjust it to this project.
- Maybe someone can explain it to me in more detailed way, give some examples or even help fix it in this project?
I hope my problem is clear.
P.S. game is based on AndEngine aaand the most important thing - sorry for my bad English :D
Have a nice day/night!