I want to detect if the user clicks a llama and increase the money but it won't work(nothing happens if I click the (moving) llama). I didn't find a solution for this in the internet.
I added this in render():
if(Gdx.input.justTouched()){
for (Lama lama : lamas) {
if(lama.lamarect.contains(Gdx.input.getX(), Gdx.input.getX())){
money+=100;
}else{
Gdx.app.setLogLevel(Application.LOG_DEBUG);
Gdx.app.debug("POSITION", "X touched: " + Gdx.input.getX() + " Y touched: " + Gdx.input.getY());
}
}
}
EDIT:
#Override
public void create() {
spawnLama();
textureAtlas = new TextureAtlas(Gdx.files.internal("data/lamination.pack"));
animation = new Animation(1/15f, textureAtlas.getRegions());
camera = new OrthographicCamera(1280, 720);
...
private void spawnLama() {
Lama lama = new Lama();
lama.x = MathUtils.random(-1000, -200);
lama.y = MathUtils.random(-350, 100);
lama.speedx = MathUtils.random(-5, 5);
if(lama.speedx >= -1 && lama.speedx <=1){
lama.speedx = 2;
}
lama.speedy = MathUtils.random(-5, 5);
if(lama.speedy >= -1 && lama.speedy <=1){
lama.speedy = 2;
}
Rectangle livinglama = new Rectangle();
livinglama.x = lama.x;
livinglama.y = lama.y;
livinglama.width = 64;
livinglama.height = 64;
lama.lamarect = livinglama;
lamas.add(lama);
lastLamaTime = TimeUtils.nanoTime();
}
#Override
public void render() {
Gdx.gl.glClearColor(110 / 255F, 211 / 255F, 43 / 255F, 1 / 255F);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
elapsedTime += Gdx.graphics.getDeltaTime();
if(spawnlama == true){
spawnLama();
spawnlama = false;
}
for (Lama lama : lamas) {
if(lama.x <= -1000){
lama.speedx = -lama.speedx;
}
else if(lama.x >= -200){
lama.speedx = -lama.speedx;
}
if(lama.y <= -350){
lama.speedy = -lama.speedy;
} else if(lama.y >=100){
lama.speedy = -lama.speedy;
}
if(lama.x == -500){
if(lama.speedx < 0){
lama.speedx --;
}
if(lama.speedx >= 0){
lama.speedx++;
}
}
lama.move();
}
if(Gdx.input.justTouched()){
for (Lama lama : lamas) {
Vector3 touch = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touch);
if(lama.lamarect.contains(touch.x, touch.y)){
money+=100;
}else{
Gdx.app.setLogLevel(Application.LOG_DEBUG);
Gdx.app.debug("POSITION", "X touched: " + touch.x + " Y touched: " + touch.y);
}
}
}
batch.begin();
for (Lama lama : lamas) {
TextureRegion currentFrame;
currentFrame = animation.getKeyFrame(elapsedTime, true);
if(!currentFrame.isFlipX()) {
if (lama.speedx >= 0) {
currentFrame.flip(true, false);
}
}else{
if (lama.speedx < 0) {
currentFrame.flip(true, false);
}
}
batch.draw(currentFrame, lama.x, lama.y, currentFrame
.getRegionWidth(), currentFrame.getRegionHeight());
}
elapsedTime += Gdx.graphics.getDeltaTime();
Lama class:
public class Lama {
public int x, y, speedx, speedy;
public Rectangle lamarect;
// float delay = 1; // seconds
void move() {
x += speedx;
y += speedy;
lamarect.x = x;
lamarect.y = y;
}
}
Gdx.input.getX and Gdx.input.getY give screen coordinates and these need to be converted back to world coordinates. If you are using a camera you can use camera.unproject(touchVector) if you are working with a stage without a specified camera you can get the camera by stage.getCamera().
If you do not have either then you have to convert it back yourself, I believe you have to flip the y coordinate first then add them to the bottom left point you are looking at in your game world. But you make your life easier by implementing a camera.
if(Gdx.input.justTouched()){
Vector3 touch = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touch);
for (Lama lama : lamas) {
if(lama.lamarect.contains(touch.x, touch.y)){
money+=100;
}else{
Gdx.app.setLogLevel(Application.LOG_DEBUG);
Gdx.app.debug("POSITION", "X touched: " + touch.x + " Y touched: " + touch.y);
}
}
}
Other then that you are passing Gdx.input.getX() two times in the contains method.
Related
I have no clue how to change this into p5.js. Just trying to work on conversions. Please help me get this code to work in p5.js.
I know that this is old code and p5.js have different rules. Maybe the array isn't working. I have no clue.
Myself myself;
ArrayList<Enemy> enemies;
`enter code here`ArrayList<Enemy> enemies;
ArrayList<Bullet> myBullets;
ArrayList<Bullet> eneBullets;
void setup(){
size(640, 640);
rectMode(CENTER);
myself = new Myself();
enemies = new ArrayList<Enemy>();
myBullets = new ArrayList<Bullet>();
eneBullets = new ArrayList<Bullet>();
}
void draw(){
background(0);
myself.display();
for(Enemy enemy: enemies){
enemy.display();
}
for(Bullet bullet: myBullets){
bullet.display();
}
for(Bullet bullet: eneBullets){
bullet.display();
}
myself.update();
ArrayList<Enemy> nextEnemies = new ArrayList<Enemy>();
for(Enemy enemy: enemies){
enemy.update();
if(!enemy.isDead){
nextEnemies.add(enemy);
}
}
enemies = nextEnemies;
ArrayList<Bullet> nextMyBullets = new ArrayList<Bullet>();
for(Bullet bullet: myBullets){
bullet.update();
if(!bullet.isDead){
nextMyBullets.add(bullet);
}
}
myBullets = nextMyBullets;
ArrayList<Bullet> nextEneBullets = new ArrayList<Bullet>();
for(Bullet bullet: eneBullets){
bullet.update();
if(!bullet.isDead){
nextEneBullets.add(bullet);
}
}
eneBullets = nextEneBullets;
if(random(1) < 0.02){
enemies.add(new Enemy());
}
}
class Myself{
PVector loc;
float size;
int coolingTime;
boolean isDead;
Myself(){
size = 25;
loc = new PVector(width / 2, height - size / 2 - 10);
coolingTime = 0;
isDead = false;
}
void display(){
if(isDead){
fill(255, 255, 0);
stroke(0, 255, 0);
} else {
noFill();
stroke(0, 255, 0);
}
rect(loc.x, loc.y, size, size);
}
void update(){
isDead = false;
float dmx = mouseX - loc.x;
dmx = constrain(dmx, -5, 5);
loc.x += dmx;
coolingTime++;
if(mousePressed && coolingTime >= 10){
myBullets.add(new Bullet());
coolingTime = 0;
}
for(Bullet b: eneBullets){
if((loc.x - size / 2 <= b.loc.x && b.loc.x <= loc.x + size / 2)
&& (loc.y - size / 2 <= b.loc.y && b.loc.y <= loc.y + size / 2)){
isDead = true;
b.isDead = true;
break;
}
}
for(Enemy e: enemies){
if(abs(loc.x - e.loc.x) < size / 2 + e.size / 2 && abs(loc.y - e.loc.y) < size / 2 + e.size / 2){
isDead = true;
e.isDead = true;
break;
}
}
}
}
class Bullet{
PVector loc;
float vel;
boolean isMine;
boolean isDead;
Bullet(){
loc = new PVector(myself.loc.x, myself.loc.y);
vel = -10;
isMine = true;
}
Bullet(Enemy enemy){
loc = new PVector(enemy.loc.x, enemy.loc.y);
vel = 5;
isMine = false;
}
void display(){
if(isMine){
stroke(0, 255, 0);
} else {
stroke(255, 0, 0);
}
line(loc.x, loc.y, loc.x, loc.y + vel);
}
void update(){
loc.y += vel;
if((vel > 0 && loc.y > height) || (vel < 0 && loc.y < 0)){
isDead = true;
}
}
}
class Enemy{
PVector loc;
float vel;
float size;
int coolingTime;
boolean isDead;
Enemy(){
size = 25;
loc = new PVector(random(size / 2, width - size / 2), -size / 2);
vel = 3;
coolingTime = int(random(60));
isDead = false;
}
void display(){
noFill();
stroke(255, 0, 0);
rect(loc.x, loc.y, size, size);
}
void update(){
loc.y += vel;
if(loc.y > height){
isDead = true;
}
coolingTime++;
if(coolingTime >= 60){
eneBullets.add(new Bullet(this));
coolingTime = 0;
}
for(Bullet b: myBullets){
if((loc.x - size / 2 <= b.loc.x && b.loc.x <= loc.x + size / 2)
&& (loc.y - size / 2 <= b.loc.y && b.loc.y <= loc.y + size / 2)){
isDead = true;
b.isDead = true;
break;
}
}
}
}
If you could just tell me what parts i need to change or fix it it would help me a lot thankyou.
You shouldn't try to translate code line-by-line. Instead, you need to take a step back and understand what the program does, and then you implement that in the target language.
They syntax for Processing (which is based on Java) is very different from the syntax for p5.js (which is based on JavaScript).
Instead of trying to "convert" the code, you need to think in terms of what the code actually does. And then start with a new program in p5.js and do that using p5.js. It's not always going to be a line-by-line conversion.
here's your code:
class myself{
constructor()
{
this.x = 0;
this.y = height-35;
this.size = 25;
this.health = 25;
this.cooldown = 0;
this.plrBullets = [];
}update(){this.cooldown++;
if (mouseIsPressed && this.cooldown>10)
{
this.cooldown = 0;
this.plrBullets.push(new Bullet(true,this.x,this.y));
}
let nextPlrBullets = [];
for (let i = 0; i<this.plrBullets.length; i++)
{
this.plrBullets[i].update();
if (this.plrBullets[i].alive)
{
nextPlrBullets.push(this.plrBullets[i]);
}
}
this.plrBullets = nextPlrBullets;
this.x += constrain(mouseX - this.x, -10, 10);
for (let i = 0; i<eneBullets.length; i++)
{
let c = eneBullets[i];
if (c.x > this.x && c.x < this.x + 25 && c.y > this.y && c.y < this.y + 25)
{
this.health--;
c.alive = false;
if (this.health<=0)
{
print("you lost")
}
}
}
noFill();
stroke(0,255,0);
rect(this.x,this.y,this.size,this.size);
}
}
class enemy{
constructor()
{
this.x = random(15,width-15);
this.y = random(-100,0);
this.size = 25;
this.cooldown = 0;
this.alive = true;
}
update()
{
this.y+=2.5;
this.cooldown++;
if (this.cooldown>20)
{
this.cooldown = 0;
eneBullets.push(new Bullet(false,this.x,this.y));
}
let nextEneBullets = [];
for (let i = 0; i<eneBullets.length; i++)
{
eneBullets[i].update();
if (eneBullets[i].alive)
{
nextEneBullets.push(eneBullets[i]);
}
}
eneBullets = nextEneBullets;
for (let i = 0; i<my_self.plrBullets.length; i++)
{
let c = my_self.plrBullets[i];
if (c.x > this.x && c.x < this.x + 25 && c.y > this.y && c.y < this.y + 25)
{
this.alive = false
c.alive = false;
}
}
if (this.y>height+35)
{
this.y = random(-100,0);
}
noFill();
stroke(255,0,0);
rect(this.x,this.y,this.size,this.size);
}
}
class Bullet{
constructor(dir,x,y)
{
this.x = x;
this.speed = 5;
this.dir = dir;
this.alive = true;
this.y = y;
}
update()
{
if (this.dir)
{
this.y -= this.speed;
}else{
this.y += this.speed;
}
if (this.y<-20)
{
this.alive = false;
}//this.y = -25;
if(this.dir)
{
stroke(0,255,0);
}else{
stroke(255,0,0);
}
line(this.x,this.y,this.x,this.y+25);
}
}
let my_self;
let eneBullets = [];
let enemies = [];
function setup()
{
createCanvas(640,640);
rectMode(CENTER);
my_self = new myself();
for (let i = 0; i<10; i++)
{
enemies.push(new enemy());
}
}
function draw()
{
background(0);
if(random(1) < 0.02 && enemies.length<15){
enemies.push(new enemy());
}
my_self.update();
let newEnimies = [];
for (let i = 0; i<enemies.length; i++)
{
enemies[i].update();
if (enemies[i].alive)
{
newEnimies.push(enemies[i]);
}
s}
enemies = newEnimies;
if (enemies.length == 0)
{
print("you win");
}
}
Sorry that the collisions are a bit wacky but when converting processing to p5 here are some tips:
1: don’t use array lists use arrays with push instead of add
2: no data types only LET
3: print not println
4: class constructors are declared as “constructor” instead of class name
5: use “function” before function declaration instead of void
6: pvector is vector
7: google is your friend
8: the p5 documentation
I am currently coding a game with Android Studio in the style of FlappyBird. I have two Cooldowns that give the user the possibility to use extra abilities.
In the main game view you can see 2 images that are grey and a timer under them. The timer goes from 10 to 0 and when zero is reached the number disappears, the image gets colored and the user knows he is able to activate the ability in the pause screen.
The problem:
When the game is starting the timer starts also and goes down as i wanted. But if the user enters the Pause Menu the Timer should stop and if he leaves it the Timer should run again.
I have a
long startTime = 0;
and a
long elapsedTime = (System.currentTimeMillis() - startTime) / 1000;
It all works but I cannot save the current time in a long and can't find any function for it!
I know the code is very long but the important part is in the drawWorld()-method in the if statement GameState.Running.
public class PlaneGame extends ApplicationAdapter{
private static final float PLANE_JUMP_IMPULSE = 350;
private static final float GRAVITY = -20;
private static final float PLANE_VELOCITY_X = 200;
private static final float PLANE_START_Y = 240;
private static final float PLANE_START_X = 50;
private static final int STATE_START = 0;
private static final int STATE_RUNNING = 1;
private static final int STATE_OVER = 2;
SpriteBatch batch;
OrthographicCamera camera;
OrthographicCamera uiCamera;
Texture background;
TextureRegion ground;
float groundOffsetX = 0;
TextureRegion ceiling;
TextureRegion rock;
TextureRegion rockDown;
TextureRegion planeSmall;
TextureRegion planeSmallBlack;
Animation plane;
TextureRegion ready;
TextureRegion gameOver;
TextureRegion pause;
BitmapFont font;
Vector2 planePosition = new Vector2();
Vector2 planeVelocity = new Vector2();
float planeStateTime = 0;
Vector2 gravity = new Vector2();
Array<Rock> rocks = new Array<Rock>();
GameState gameState = GameState.Start; /*neeeeeeewwwww*/
int score = 0;
long startTime = 0;
long startTime2;
long elapsedTime;
long savedTime;
boolean wantToSeeTime = true;
boolean wantToSeeTimePause = true;
float timeCdRock = 0;
float timeCdPlane = 0;
Rectangle rect1 = new Rectangle();
Rectangle rect2 = new Rectangle();
Music music;
Sound point;
Sound explode;
//this gets called repeatedly to run the game
#Override
public void render () {
//clear the screen so we can draw the next one
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
long saveTime = elapsedTime;
//update the position of the plane and rocks
updateWorld();
elapsedTime = saveTime;
//now draw the updated screen
drawWorld();
}
//initialize objects and load assets when game starts
#Override
public void create () {
startTime = TimeUtils.nanoTime(); /*Neeeewwwwwwwww !!!*/
Gdx.input.setInputProcessor(new GestureDetector(new MyGestureListener()));
batch = new SpriteBatch();
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
uiCamera = new OrthographicCamera();
uiCamera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
uiCamera.update();
font = new BitmapFont(Gdx.files.internal("arial.fnt"));
background = new Texture("background.png");
ground = new TextureRegion(new Texture("ground.png"));
ceiling = new TextureRegion(ground);
ceiling.flip(true, true);
rock = new TextureRegion(new Texture("rock.png"));
rockDown = new TextureRegion(rock);
rockDown.flip(false, true);
Texture frame1 = new Texture("plane1.png");
frame1.setFilter(TextureFilter.Linear, TextureFilter.Linear);
Texture frame2 = new Texture("plane2.png");
Texture frame3 = new Texture("plane3.png");
planeSmall = new TextureRegion(new Texture("planeSmall.png"));
planeSmallBlack = new TextureRegion(new Texture("planeSmallBlack.png"));
ready = new TextureRegion(new Texture("ready.png"));
gameOver = new TextureRegion(new Texture("gameover.png"));
pause = new TextureRegion(new Texture("pause.png"));
plane = new Animation(0.05f, new TextureRegion(frame1), new TextureRegion(frame2), new TextureRegion(frame3), new TextureRegion(frame2));
plane.setPlayMode(PlayMode.LOOP);
music = Gdx.audio.newMusic(Gdx.files.internal("music.mp3"));
music.setLooping(true);
music.play();
point = Gdx.audio.newSound(Gdx.files.internal("point.ogg"));
explode = Gdx.audio.newSound(Gdx.files.internal("explode.wav"));
resetWorld();
}
//reset the state of the game
private void resetWorld() {
score = 0;
startTime = 0;
groundOffsetX = 0;
planePosition.set(PLANE_START_X, PLANE_START_Y);
planeVelocity.set(0, 0);
gravity.set(0, GRAVITY);
camera.position.x = 400;
//randomize the position and direction of the rocks
rocks.clear();
for(int i = 0; i < 5; i++) {
boolean isDown = MathUtils.randomBoolean();
rocks.add(new Rock(700 + i * 200, isDown?480-rock.getRegionHeight(): 0, isDown? rockDown: rock));
}
}
//use the time elapsed since the last call to render() to determine how much to update the game
private void updateWorld() {
float deltaTime = Gdx.graphics.getDeltaTime();
planeStateTime += deltaTime;
/*if(Gdx.input.justTouched()) {
if(gameState == STATE_START) {
gameState = STATE_RUNNING;
}
if(gameState == STATE_RUNNING) {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
}
if(gameState == STATE_OVER) {
gameState = STATE_START;
resetWorld();
}
}*/
if(gameState != GameState.Start) planeVelocity.add(gravity);
planePosition.mulAdd(planeVelocity, deltaTime);
camera.position.x = planePosition.x + 350;
if(camera.position.x - groundOffsetX > ground.getRegionWidth() + 400) {
groundOffsetX += ground.getRegionWidth();
}
rect1.set(planePosition.x + 20, planePosition.y, plane.getKeyFrames()[0].getRegionWidth() - 20, plane.getKeyFrames()[0].getRegionHeight());
for(Rock r: rocks) {
//if the rock is off the screen, give it a new location in front of the plane
if(camera.position.x - r.position.x > 400 + r.image.getRegionWidth()) {
boolean isDown = MathUtils.randomBoolean();
r.position.x += 5 * 200;
r.position.y = isDown?480-rock.getRegionHeight(): 0;
r.image = isDown? rockDown: rock;
r.counted = false;
}
rect2.set(r.position.x + (r.image.getRegionWidth() - 30) / 2 + 20, r.position.y, 20, r.image.getRegionHeight() - 10);
//check if the plane crashed
if(rect1.overlaps(rect2)) {
if(gameState != GameState.GameOver) explode.play();
gameState = GameState.GameOver;
planeVelocity.x = 0;
}
//award a point for not crashing into a rock
if(r.position.x < planePosition.x && !r.counted) {
score++;
r.counted = true;
point.play();
}
}
//check if the plane crashed
if(planePosition.y < ground.getRegionHeight() - 20 ||
planePosition.y + plane.getKeyFrames()[0].getRegionHeight() > 480 - ground.getRegionHeight() + 20) {
if(gameState != GameState.GameOver) explode.play();
gameState = GameState.GameOver;
planeVelocity.x = 0;
}
}
//draw the background, rocks, and plane to the screen and possibly some ui text
private void drawWorld() {
elapsedTime = (System.currentTimeMillis() - startTime) / 1000;
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(background, camera.position.x - background.getWidth() / 2, 0);
for(Rock rock: rocks) {
batch.draw(rock.image, rock.position.x, rock.position.y);
}
batch.draw(ground, groundOffsetX, 0);
batch.draw(ground, groundOffsetX + ground.getRegionWidth(), 0);
batch.draw(ceiling, groundOffsetX, 480 - ceiling.getRegionHeight());
batch.draw(ceiling, groundOffsetX + ceiling.getRegionWidth(), 480 - ceiling.getRegionHeight());
batch.draw(plane.getKeyFrame(planeStateTime), planePosition.x, planePosition.y);
batch.end();
batch.setProjectionMatrix(uiCamera.combined);
batch.begin();
if(gameState == GameState.Start) {
batch.draw(ready, Gdx.graphics.getWidth() / 2 - ready.getRegionWidth() / 2, Gdx.graphics.getHeight() / 2 - ready.getRegionHeight() / 2);
}
if(gameState == GameState.GameOver) {
batch.draw(gameOver, Gdx.graphics.getWidth() / 2 - gameOver.getRegionWidth() / 2, Gdx.graphics.getHeight() / 2 - gameOver.getRegionHeight() / 2);
}
if(gameState == GameState.GameOver || gameState == GameState.Running) {
font.draw(batch, "" + score, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() - 60);
}
if(gameState == GameState.Running || gameState == GameState.Pause) {
//font.draw(batch, "" + (10 - elapsedTime), (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 260);
if(wantToSeeTime){
font.draw(batch, "" + (5 - elapsedTime), (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 260);
}
if((5 -(elapsedTime) > 0)) {
batch.draw(planeSmallBlack, (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 250);
}else {
batch.draw(planeSmall, (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 250);
wantToSeeTime = false;
}
}
if(gameState == GameState.Pause){
batch.draw(pause, Gdx.graphics.getWidth() / 2 - pause.getRegionWidth() / 2, Gdx.graphics.getHeight() / 2 - pause.getRegionHeight() / 2);
if(wantToSeeTimePause){
font.draw(batch, "" + (savedTime), (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 260);
}
}
batch.end();
}
//object to hold all pertinent information for a rock
static class Rock {
Vector2 position = new Vector2();
TextureRegion image;
boolean counted;
public Rock(float x, float y, TextureRegion image) {
this.position.x = x;
this.position.y = y;
this.image = image;
}
}
// Neeeeeeeewwwww
static enum GameState {
Start, Running, GameOver, Pause
}
private class MyGestureListener implements GestureDetector.GestureListener {
#Override
public boolean touchDown(float x, float y, int pointer, int button) {
return false;
}
#Override
public boolean tap(float x, float y, int count, int button) {
if(gameState == GameState.Start) {
gameState = GameState.Running;
startTime = System.currentTimeMillis();
}
if(gameState == GameState.Running) {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
}
if(gameState == GameState.GameOver) {
gameState = GameState.Start;
resetWorld();
}
/*if((gameState == GameState.Pause) && (count == 2)) {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
gravity.set(0,GRAVITY);
gameState = GameState.Running;
}*/
return true;
}
#Override
public boolean longPress(float x, float y) {
return false;
}
#Override
public boolean fling(float velocityX, float velocityY, int button) {
if(gameState == GameState.Running) {
planePosition.set(planePosition.x, planePosition.y);
planeVelocity.set(0,0);
gravity.set(0, 0);
savedTime = System.currentTimeMillis() / 1000;
wantToSeeTime = false;
wantToSeeTimePause = true;
gameState = GameState.Pause;
} else {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
gravity.set(0,GRAVITY);
wantToSeeTime = true;
wantToSeeTimePause = false;
elapsedTime -= savedTime;
gameState = GameState.Running;
}
/*if(gameState == GameState.Pause) {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
gravity.set(0,GRAVITY);
gameState = GameState.Running;
}*/
return true;
}
#Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
return false;
}
#Override
public boolean panStop(float x, float y, int pointer, int button) {
return false;
}
#Override
public boolean zoom(float initialDistance, float distance) {
return false;
}
#Override
public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1, Vector2 pointer2) {
return false;
}
public void pinchStop() {
}
}
}
Thanks for your help!
You can use joda time for advanced operations
Please check the link for your reference
http://www.joda.org/joda-time/userguide.html
I'm going to assume that your game runs as part of a loop. Ideally what you should have is a starting time when the ability is activated, which counts down during the cooldown based on how much time has elapsed since the last iteration of your loop. For example, for an ability with a 10 second cooldown:
final long abilityLength = 10 * 1000;
long cooldownRemaining = 0;
long lastTimestamp;
boolean isPaused = false;
private void doAbility() {
if (cooldownRemaining <= 0) {
cooldownRemaining = abilityLength;
}
}
public void main(int[] args) {
lastTimestamp = System.currentTimeMillis();
while(true) { // your main game loop
// Time (in ms) elapsed since the last iteration of this loop
long delta = System.currentTimeMillis() - lastTimestamp;
... // Other game code
if (cooldownRemaining > 0 && !isPaused) {
// Subtract the delta from the remaing cooldown time.
cooldownRemaining -= delta;
}
lastTimeStamp = System.currentTimeMillis();
}
}
What i need to do is, when the points its "example 10" the speed of the ball raise, when the points its "example 20" the speed of the ball raises again, etc. I dont know if i do that in the Ball class or in the GameScreen class and i dont know how to do it. Thanks for your help!.
public class Ball {
//THE SPEED OF THE BALL
private static final float SPEED=1100;
//THE POINTS IS
puntuacion =0;
//AND THE METHOD WHEN THE POINTS IS INCREAMENTING
private void updatePuntuacion(){
if(ball.getBordes().overlaps(Lpaddle.getBordes())) {
puntuacion = puntuacion + 1;
if(puntuacion > puntuacionMaxima)
puntuacionMaxima = puntuacion;
}
if(ball.getBordes().x <= 0)
sonidoex.play();
if(ball.getBordes().x <= 0)
puntuacion =0;
if(ball.getBordes().x <=0)
Gdx.input.vibrate(1000);
if(ball.getBordes().x <=0)
Screens.juego.setScreen(Screens.MAINSCREEN);
ball.comprobarPosicionBola();
}
}
EDIT:
This is my GameScreen class.
public class GameScreen extends AbstractScreen {
private SpriteBatch batch;
private Texture texture;
private Paddle Lpaddle, Rpaddle;
private Ball ball;
private BitmapFont font;
private int puntuacion, puntuacionMaxima;
private Preferences preferencias;
private Music music;
private Sound sonidoex;
public GameScreen(Main main) {
super(main);
preferencias = Gdx.app.getPreferences("PuntuacionAppPoints");
puntuacionMaxima = preferencias.getInteger("puntuacionMaxima");
music =Gdx.audio.newMusic(Gdx.files.internal("bgmusic.mp3"));
music.play();
music.setVolume((float) 0.3);
music.setLooping(true);
sonidoex = Gdx.audio.newSound(Gdx.files.internal("explosion5.wav"));
}
public void show(){
batch = main.getBatch();
texture = new Texture(Gdx.files.internal("spacebg.png"));
Texture texturaBola = new Texture(Gdx.files.internal("bola.png"));
ball = new Ball(Gdx.graphics.getWidth() / 2 - texturaBola.getWidth() / 2, Gdx.graphics.getHeight() / 2 - texturaBola.getHeight() / 2);
Texture texturaPala= new Texture(Gdx.files.internal("pala.png"));
Lpaddle = new LeftPaddle(80, Gdx.graphics.getHeight()/2 -texturaPala.getHeight() /2);
Rpaddle = new RightPaddle(Gdx.graphics.getWidth() -100, Gdx.graphics.getHeight()/2 - texturaPala.getHeight() /2, ball);
font = new BitmapFont(Gdx.files.internal("pointsfont.tf.fnt"), Gdx.files.internal("pointsfont.tf.png"), false);
puntuacion = 0;
}
public void render(float delta){
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
updatePuntuacion();
Lpaddle.update();
Rpaddle.update();
ball.update(Lpaddle, Rpaddle);
batch.begin();
batch.draw(texture, 0, 0,texture.getWidth(), texture.getHeight());
ball.draw(batch);
Lpaddle.draw(batch);
Rpaddle.draw(batch);
font.draw(batch, "Points: " + Integer.toString(puntuacion), Gdx.graphics.getWidth() / 4 ,Gdx.graphics.getHeight() - 5);
font.draw(batch, "High score: " + Integer.toString(puntuacionMaxima),Gdx.graphics.getWidth() - Gdx.graphics.getWidth() / 4 ,Gdx.graphics.getHeight() - 5);
batch.end();
}
private void updatePuntuacion(){
if(ball.getBordes().overlaps(Lpaddle.getBordes())) {
puntuacion = puntuacion + 1;
if(puntuacion > puntuacionMaxima)
puntuacionMaxima = puntuacion;
}
if(ball.getBordes().x <= 0)
sonidoex.play();
if(ball.getBordes().x <= 0)
puntuacion =0;
if(ball.getBordes().x <=0)
Gdx.input.vibrate(1000);
if (puntuacion % 10 == 0){
SPEED = 200;
}
if(ball.getBordes().x <=0)
Screens.juego.setScreen(Screens.MAINSCREEN);
ball.comprobarPosicionBola();
}
public void hide(){
font.dispose();
texture.dispose();
}
#Override
public void dispose(){
preferencias.putInteger("puntuacionMaxima", puntuacionMaxima);
preferencias.flush();
}
public void resize(int width, int height){
float widthImage = texture.getWidth();
float heightImage = texture.getHeight();
float r = heightImage / widthImage;
if(heightImage > height) {
heightImage = height;
widthImage = heightImage / r;
}
if(widthImage > width) {
widthImage = width;
heightImage = widthImage * r;
}
}
}
I need 50 reputation to comment so instead I'll post an answer and try to make it as helpful as possible.
First of all I'm not too sure of your question, but from what I understand, you want to increase the speed of your ball when puntuacion reaches certain values (10, 20, etc).
The first thing you have to do is remove the final from your SPEED variable, since a final primitive can only be set once, thus denying you from changing it later on.
As for updating the speed, if you want to do it at specific values of punctuacion, then simply do
if(punctuacion == 10 || punctuacion == 17) { // etc
speed += x; // x being the value you want to increase the speed by
}
Alternatively, if you want to update the speed every 10 increments for example, you could do
if (punctuacion % 10 == 0){
speed += x;
}
Do note that for this second example, when punctuacion is 0, the if statement will return true, so work around that if you have to.
As for where to put this code, it really depends on your classes and you definitely didn't post enough code for me to be able to help you with that, but my best guess would be to put it right after you increment punctuacion, since I'm assuming you want the ball's speed update check to be performed immediately after punctuacion updates.
This is my GameScreen class.
public class GameScreen extends AbstractScreen {
private SpriteBatch batch;
private Texture texture;
private Paddle Lpaddle, Rpaddle;
private Ball ball;
private BitmapFont font;
private int puntuacion, puntuacionMaxima;
private Preferences preferencias;
private Music music;
private Sound sonidoex;
public GameScreen(Main main) {
super(main);
preferencias = Gdx.app.getPreferences("PuntuacionAppPoints");
puntuacionMaxima = preferencias.getInteger("puntuacionMaxima");
music =Gdx.audio.newMusic(Gdx.files.internal("bgmusic.mp3"));
music.play();
music.setVolume((float) 0.3);
music.setLooping(true);
sonidoex = Gdx.audio.newSound(Gdx.files.internal("explosion5.wav"));
}
public void show(){
batch = main.getBatch();
texture = new Texture(Gdx.files.internal("spacebg.png"));
Texture texturaBola = new Texture(Gdx.files.internal("bola.png"));
ball = new Ball(Gdx.graphics.getWidth() / 2 - texturaBola.getWidth() / 2, Gdx.graphics.getHeight() / 2 - texturaBola.getHeight() / 2);
Texture texturaPala= new Texture(Gdx.files.internal("pala.png"));
Lpaddle = new LeftPaddle(80, Gdx.graphics.getHeight()/2 -texturaPala.getHeight() /2);
Rpaddle = new RightPaddle(Gdx.graphics.getWidth() -100, Gdx.graphics.getHeight()/2 - texturaPala.getHeight() /2, ball);
font = new BitmapFont(Gdx.files.internal("pointsfont.tf.fnt"), Gdx.files.internal("pointsfont.tf.png"), false);
puntuacion = 0;
}
public void render(float delta){
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
updatePuntuacion();
Lpaddle.update();
Rpaddle.update();
ball.update(Lpaddle, Rpaddle);
batch.begin();
batch.draw(texture, 0, 0,texture.getWidth(), texture.getHeight());
ball.draw(batch);
Lpaddle.draw(batch);
Rpaddle.draw(batch);
font.draw(batch, "Points: " + Integer.toString(puntuacion), Gdx.graphics.getWidth() / 4 ,Gdx.graphics.getHeight() - 5);
font.draw(batch, "High score: " + Integer.toString(puntuacionMaxima),Gdx.graphics.getWidth() - Gdx.graphics.getWidth() / 4 ,Gdx.graphics.getHeight() - 5);
batch.end();
}
private void updatePuntuacion(){
if(ball.getBordes().overlaps(Lpaddle.getBordes())) {
puntuacion = puntuacion + 1;
if(puntuacion > puntuacionMaxima)
puntuacionMaxima = puntuacion;
}
if(ball.getBordes().x <= 0)
sonidoex.play();
if(ball.getBordes().x <= 0)
puntuacion =0;
if(ball.getBordes().x <=0)
Gdx.input.vibrate(1000);
if (puntuacion % 10 == 0){
SPEED = 200;
}
if(ball.getBordes().x <=0)
Screens.juego.setScreen(Screens.MAINSCREEN);
ball.comprobarPosicionBola();
}
public void hide(){
font.dispose();
texture.dispose();
}
#Override
public void dispose(){
preferencias.putInteger("puntuacionMaxima", puntuacionMaxima);
preferencias.flush();
}
public void resize(int width, int height){
float widthImage = texture.getWidth();
float heightImage = texture.getHeight();
float r = heightImage / widthImage;
if(heightImage > height) {
heightImage = height;
widthImage = heightImage / r;
}
if(widthImage > width) {
widthImage = width;
heightImage = widthImage * r;
}
}
}
I am writing an Android game right now and I would need some help in the collision of the wall on screen. When I drag the ball in the top and right it able to collide in wall but when I drag it faster it was able to overlap in the wall
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
// if the player moves
case MotionEvent.ACTION_MOVE: {
if (playerTouchRect.contains(x, y)) {
boolean left = false;
boolean right = false;
boolean up = false;
boolean down = false;
boolean canMove = false;
boolean foundFinish = false;
if (x != pLastXPos) {
if (x < pLastXPos) {
left = true;
} else {
right = true;
}
pLastXPos = x;
}
if (y != pLastYPos) {
if (y < pLastYPos) {
up = true;
} else {
down = true;
}
pLastYPos = y;
}
plCellRect = getRectFromPos(x, y);
newplRect.set(playerRect);
newplRect.left = x - (int) (playerRect.width() / 2);
newplRect.right = x + (int) (playerRect.width() / 2);
newplRect.top = y - (int) (playerRect.height() / 2);
newplRect.bottom = y + (int) (playerRect.height() / 2);
int currentRow = 0;
int currentCol = 0;
currentRow = getRowFromYPos(newplRect.top);
currentCol = getColFromXPos(newplRect.right);
if(!canMove){
canMove = mapManager.getCurrentTile().pMaze[currentRow][currentCol] == Cell.wall;
canMove =true;
}
finishTest = mapManager.getCurrentTile().pMaze[currentRow][currentCol];
foundA = finishTest == Cell.valueOf(letterNotGet + "");
canMove = mapManager.getCurrentTile().pMaze[currentRow][currentCol] != Cell.wall;
canMove = (finishTest == Cell.floor || finishTest == Cell.pl) && canMove;
if (canMove) {
invalidate();
setTitle();
}
if (foundA) {
mapManager.getCurrentTile().pMaze[currentRow][currentCol] = Cell.floor;
// finishTest
letterGotten.add(letterNotGet);
playCurrentLetter();
/*sounds.play(sExplosion, 1.0f, 1.0f, 0, 0, 1.5f);*/
foundS = letterNotGet == 's';
letterNotGet++;
}if(foundS){
AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity);
builder.setTitle(mainActivity.getText(R.string.finished_title));
LayoutInflater inflater = mainActivity.getLayoutInflater();
View view = inflater.inflate(R.layout.finish, null);
builder.setView(view);
View closeButton =view.findViewById(R.id.closeGame);
closeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View clicked) {
if(clicked.getId() == R.id.closeGame) {
mainActivity.finish();
}
}
});
AlertDialog finishDialog = builder.create();
finishDialog.show();
}
else {
Log.d(TAG, "INFO: updated player position");
playerRect.set(newplRect);
setTouchZone();
updatePlayerCell();
}
} // end of (CASE) if playerTouch
break;
} // end of (SWITCH) Case motion
}//end of Switch
return true;
}//end of TouchEvent
private void finish() {
// TODO Auto-generated method stub
}
public int getColFromXPos(int xPos) {
val = xPos / (pvWidth / mapManager.getCurrentTile().pCols);
if (val == mapManager.getCurrentTile().pCols) {
val = mapManager.getCurrentTile().pCols - 1;
}
return val;
}
/**
* Given a y pixel position, return the row of the cell it is in This is
* used when determining the type of adjacent Cells.
*
* #param yPos
* y position in pixels
* #return The cell this position is in
*/
public int getRowFromYPos(int yPos) {
val = yPos / (pvHeight / mapManager.getCurrentTile().pRows);
if (val == mapManager.getCurrentTile().pRows) {
val = mapManager.getCurrentTile().pRows - 1;
}
return val;
}
/**
* When preserving the position we need to know which cell the player is in,
* so calculate it from the centre on its Rect
*/
public void updatePlayerCell() {
plCell.x = (playerRect.left + (playerRect.width() / 2))
/ (pvWidth / mapManager.getCurrentTile().pCols);
plCell.y = (playerRect.top + (playerRect.height() / 2))
/ (pvHeight / mapManager.getCurrentTile().pRows);
if (mapManager.getCurrentTile().pMaze[plCell.y][plCell.x] == Cell.floor) {
for (int row = 0; row < mapManager.getCurrentTile().pRows; row++) {
for (int col = 0; col < mapManager.getCurrentTile().pCols; col++) {
if (mapManager.getCurrentTile().pMaze[row][col] == Cell.pl) {
mapManager.getCurrentTile().pMaze[row][col] = Cell.floor;
break;
}
}
}
mapManager.getCurrentTile().pMaze[plCell.y][plCell.x] = Cell.pl;
}
}
public Rect getRectFromPos(int x, int y) {
calcCell.left = ((x / cellWidth) + 0) * cellWidth;
calcCell.right = calcCell.left + cellWidth;
calcCell.top = ((y / cellHeight) + 0) * cellHeight;
calcCell.bottom = calcCell.top + cellHeight;
Log.d(TAG, "Rect: " + calcCell + " Player: " + playerRect);
return calcCell;
}
public void setPlayerRect(Rect newplRect) {
playerRect.set(newplRect);
}
private void setTouchZone() {
playerTouchRect.set(
playerRect.left - playerRect.width() / TOUCH_ZONE,
playerRect.top - playerRect.height() / TOUCH_ZONE,
playerRect.right + playerRect.width() / TOUCH_ZONE,
playerRect.bottom + playerRect.height() / TOUCH_ZONE);
}
public Rect getPlayerRect() {
return playerRect;
}
public Point getPlayerCell() {
return plCell;
}
public void setPlayerCell(Point cell) {
plCell = cell;
}
}*
This is an architectural problem. You can read more about it here.
In essence, your physics simulation (as simple as might be) is coupled to your framerate (which is capped at 60fps). Any events occurring faster than 60Hz cannot be processed accurately hence your bug.
The solution is to run the collision detection on an independent thread and draw the state it calculates at 60fps.
Also, take a look at these gamedev questions that refer to the same article.
Having a massive problem with this piece of code. I'm working with Java in processing.
I've created a game where users must guide a character away from objects.
All the objects, health system and score system are based on mills().
Once the game ends we need to reset millis(), resetting the objects, score and health system.
I have searched implemented advice from friends and previously asked questions on here but the advice differs very slightly. I'm assuming it's something that I can't see.
I would really appreciate your help with this, I only ever use this site as a last resort not just when I'm feeling lazy.
//these are used to set the times which the games increases difficulty
//int timeDelay = 30000;
int delayOne = 2000;
int delayTwo = 5000;
int delayThree = 80000;
int delayFour = 90000;
int display = 2000;
//for collisions
float[] xpos = new float[6];
float[] ypos = new float[6];
//timer counts how many millis() each game lasts for
int timeStamp = 5000;
int timer;
int timer2 = millis() - timer;
//always at zero
//outputting score at the end of a game
int score;
int start;
//trying to get lives working
boolean lost = false;
//variable to store & output gale force when giving score
int Gale = 0;
//Changing length rectangle
float rX = 350.0;
float x1 = 20;
float y1 = 20;
float w1 = 100;
float h1 = 30;
//DECLARE OBJECTS JELLY CLASS
Jelly myObject;
Jelly myObject1;
Jelly myObject2;
Jelly myObject3;
//GENTLEMAN CLASS
gentleMan mygentleMan;
//LOLLY CLASS
Lolly myCow;
Lolly myCow1;
//PImages
PImage loader;
PImage bg;
PImage uh;
PImage bg1;
PImage bolt;
PImage over;
void setup()
{
bg=loadImage("backy1.png");
bg1 = loadImage("backy.png");
over = loadImage("over.png");
PFont L = loadFont("Lobster1.3-48.vlw");
textFont( L, 16);
size(400, 600);
smooth();
//begin = millis();
imageMode(CENTER);
//INITIALISE
myObject = new Jelly(320, 500);
myObject1 = new Jelly(150, 200);
// myObject2 = new Jelly(550, 500);
//myObject3 = new Jelly(300, 100);
mygentleMan = new gentleMan(200, 300);
//myObject.run();
//myObject1.run();
//myObject2.run();
myCow = new Lolly(400, 250);
myCow1 = new Lolly(150, 350);
timer = millis();
}
void draw()
{
start = 0;
//because we have image mode set to center for collisions
//we have to divide the height & width of the screen by 2 for hte image to fit
image(bg, 200, 300);
if (millis() >= start + delayOne)
{
image(bg1, 200, 300);
}
//CALL FUNCTIONALITY
myObject.run();
myObject.put_in_array(0);
myObject1.run(); // this one is going top to bottom
myObject1.put_in_array(1);
// myObject2.run();
//myObject2.put_in_array(2);
// myObject3.run();
//myObject3.put_in_array(3);
myCow.run();
myCow.put_in_array(4);
myCow1.run();
myCow1.put_in_array(5);
mygentleMan.run();
//health bar
fill(161, 221, 16);
noStroke();
rect(10, 24, rX, 10);
if(rX <= 100)
{
fill(221, 59, 16);
rect(10, 24, rX, 10);
}
else
if(rX <= 200)
{
fill(221, 137, 16);
rect(10, 24, rX, 10);
}
if(rX == 5.0)
{
lost = true;
noLoop();
// lives = lives - 1;
image(over, width/2, height/3);
fill(255);
text("Your Score Is: " + timer, width/2.7, height/2);
text("Gale Force Is; " + Gale, width/2.7, height/1.8);
score = timer;
}
//For Loop detecting collisions between mygentleMan & objects
for (int i=0; i < 6; i++) {
if (xpos[i] > 150 && xpos[i] < 250 && ypos[i] > (mygentleMan.y-58) && ypos[i] < (mygentleMan.y+58))
{
// text("collision", 200, 300);
bolt = loadImage("bolt.png");
image(bolt, xpos[i], ypos[i]);
rX = rX - 1;
}
//outputting score on screen # at all times
fill(255);
text("Score: " + timer, 320, 20);
}
//timer which will be score counter essentially
timer = millis();
//text(timer, 20, 20);
//moving the man up the screen if button is pressed, if not he levitates downward
if (keyPressed)
{
mygentleMan.y -= mygentleMan.moveY;
mygentleMan.moveY += 0.4;
}
else
{
mygentleMan.y += mygentleMan.moveY;
mygentleMan.moveY += 0.2;
}
fill(255);
text("Health", 20, 20);
if(mousePressed)
{
if(timer2 > timeStamp)
{
println("tit");
mygentleMan.y = height/2;
loop();
}
}
}
//class for first objects that move into the screen
class Jelly
{
//GLOBAL VARIABLES
float x = 0;
float y = 0;
float speedX = 1.8;
float speedY = 1.8;
float speedX2 = 2.1;
float speedY2 = 2.1;
float speedX3 = 2.2;
float speedY3 = 2.2;
PImage jelly = loadImage("jelly.png");
PImage hat = loadImage("hat.png");
PImage gale = loadImage("g1.png");
PImage force = loadImage("force.png");
PImage news = loadImage("news.png");
//CONSTRUCTOR
Jelly(float _x, float _y)
{
x = _x;
y = _y;
}
//FUNCTIONS
void run()
{
display();
move();
bounce();
image(force, 330, 550);
if (millis() >= start + delayOne)
{
display();
moveFast();
bounceFast();
image(gale, 280, 560);
Gale = 1;
if (start + delayOne + display >= millis())
{
image(news, 200, 300);
}
}
if (millis() >= start +delayTwo)
{
display();
moveFaster();
bounceFaster();
image(gale, 310, 560);
Gale = 2;
if (start + delayTwo + display >= millis())
{
image(news, 200, 300);
}
}
}
void bounce()
{
if ( x > width)
{
speedX = speedX * -1; //multiply by -1 to make it bounce
}
if ( x < 0)
{
speedX = speedX * -1;
}
if ( y > height)
{
speedY = speedY * -1;
}
if ( y < 0)
{
speedY = speedY * -1;
}
}
void bounceFast()
{
if ( x > width)
{
speedX2 = speedX2 * -1; //multiply by -1 to make it bounce
}
if ( x < 0)
{
speedX2 = speedX2 * -1;
}
if ( y > height)
{
speedY2 = speedY2 * -1;
}
if ( y < 0)
{
speedY2 = speedY2 * -1;
}
}
void bounceFaster()
{
if ( x > width)
{
speedX3 = speedX3 * -1; //multiply by -1 to make it bounce
}
if ( x < 0)
{
speedX3 = speedX3 * -1;
}
if ( y > height)
{
speedY3 = speedY3 * -1;
}
if ( y < 0)
{
speedY3 = speedY3 * -1;
}
}
void move()
{
x = x + speedX;
y = y + speedY;
}
void moveFast()
{
x = x + speedX2;
y = y + speedY2;
}
void moveFaster()
{
x = x + speedX3;
y = y + speedY3;
}
void put_in_array(int a)
{
xpos[a] = x;
ypos[a] = y;
}
void display()
{
image(hat, x, y);
}
}
//class for gentleman that floats
class gentleMan
{
//GLOBAL VARIABLES
float y = 400;
float x = 400;
float moveY;
//PImage umbrella;
PImage umbrella = loadImage("dafuq.png");
PImage over = loadImage("over.png");
//CONSTRCUTOR --- PIECES OF INFO PROVDE TO BUILD CLASS -- INTIIALIZE VARIBALE
gentleMan(float _x, float _y)
{
y = _y;
x = _x;
moveY = 2;
}
//FUNCTIONS
void run()
{
display();
keyReleased();
bounce();
// collision();
}
void display()
{
image(umbrella, x, y);
}
void keyReleased()
{
mygentleMan.moveY = 4;
}
void bounce()
{
if ( y < 0)
{
y = 0;
}
if (y > height)
{
//score = millis();
lost = true;
noLoop();
// lives = lives - 1;
image(over, width/2, height/3);
text("Your Score Is: " + timer, width/2.7, height/2);
text("Gale Force Is; " + Gale, width/2.7, height/1.8);
}
}
}
class Lolly
{
//GLOBAL VARIABLES
float x = 0;
float y = 0;
float speedX = 2;
float speedY = 2;
float speedX1 = 2.1;
float speedY1 = 2.1;
float speedX2 = 2.3;
float speedY2 = 2.3;
PImage cow = loadImage("cow.png");
//CONSTRUCTOR
Lolly(float _x, float _y)
{
x = _x;
y = _y;
}
//FUNCTIONS
void run()
{
// display();
//move();
//bounce();
if (millis() >= start + delayThree)
{
display();
moveFast();
bounceFast();
}
if (millis() >= start +delayFour)
{
display();
moveFaster();
bounceFaster();
}
}
void put_in_array(int a)
{
xpos[a] = x;
ypos[a] = y;
}
void bounce()
{
if ( x > width)
{
speedX = speedX * -1; //multiply by -1 to make it bounce
}
if ( x < 0)
{
speedX = speedX * -1;
}
if ( y > height)
{
speedY = speedY * -1;
}
if ( y < 0)
{
speedY = speedY * -1;
}
}
void bounceFast()
{
if ( x > width)
{
speedX1 = speedX1 * -1; //multiply by -1 to make it bounce
}
if ( x < 0)
{
speedX1 = speedX1 * -1;
}
if ( y > height)
{
speedY1 = speedY1 * -1;
}
if ( y < 0)
{
speedY1 = speedY1 * -1;
}
}
void bounceFaster()
{
if ( x > width)
{
speedX2 = speedX2 * -1; //multiply by -1 to make it bounce
}
if ( x < 0)
{
speedX2 = speedX2 * -1;
}
if ( y > height)
{
speedY2 = speedY2 * -1;
}
if ( y < 0)
{
speedY2 = speedY2 * -1;
}
}
void move()
{
x = x + speedX;
y = y + speedY;
}
void moveFast()
{
x = x + speedX1;
y = y + speedY1;
}
void moveFaster()
{
x = x + speedX2;
y = y + speedY2;
}
void display()
{
image(cow, x, y);
}
}//end of cow class
void mousePressed()
{
}
Your question is not at all clear, but it sounds like you should be able to wrap System.currentTimeMillis() in an object that maintains a starting point and returns the offset. Something like
public class Millis
{
long start;
public Millis() { this.reset(); }
public void reset() { this.start = System.currentTimeMillis(); }
public long getMillis() { return System.currentTimeMillis() - start; }
}
You create an instance of this class at startup
Millis timer = new Millis();
then call reset() to set it back to zero at the beginning of each game. Everywhere in your code you currently have millis() you would have timer.getMillis()
Use a custom timer class
class Timer {
int savedTime; // When Timer started
int totalTime; // How long Timer should last
Timer(int tempTotalTime) {
totalTime = tempTotalTime;
}
// Starting the timer
void start() {
// When the timer starts it stores the current time in milliseconds.
savedTime = millis();
}
// The function isFinished() returns true if 5,000 ms have passed.
// The work of the timer is farmed out to this method.
boolean isFinished() {
// Check how much time has passed
int passedTime = millis()- savedTime;
if (passedTime > totalTime) {
return true;
} else {
return false;
}
}
}//end class
Then to call
firstTimer = new Timer(50000);
And then in the draw to check
if (firstTimer.isFinished()) {
//do sopemthing
//then restart timer
firstTimer.start();
}
else
{
// do soemthing else for the rest of the time....
}