0
\$\begingroup\$

I'm creating an android game and I'm trying to figure out the best way to time a character position change, something like this:

public void move() {
    //this.posX += 5;
    this.posY += 5;

    if (posY < 350) {
    new Timer().schedule(new TimerTask() {
        public void run()  {
            this.move();
        }
        }, 300, 300);
    }       
}

Is this the best way? I'm using Canvas. Thanks for your time.

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

Try to stay away from using constants in your code as much as possible, mostly because when your game starts getting larger it will be easier to remember a variable named playerSpeed compared to a certain number. Not crucial but just a tip.

What is crucial however is to use delta time when u add speed to your objects, and when incrementing your timers. If you dont know what delta time is its just a quick google search away.

Another thing to keep in mind when designing for android is to use density pixels when you are working with positions on screen like posY < 350. (Again, try to find a suitable variable name for the int "350", good to get used to it)

Try something like this:

public void move() {
//this.posX += 5;
this.posY += objectSpeed*deltaTime;

if (posY < 350*dp) {
new Timer().schedule(new TimerTask() {
    public void run()  {
        this.move();
    }
    }, 300, 300); //dont know what these are but if positions add density pixels like above
}       
}

Another tip is to create ur own timers, something I like to do. You can do this when you start learning more about delta time, it will look something like this:

aiTimer+=deltaTime;
if(aiTimer >= 2.0f){ //2 seconds
doStuff();
aiTimer-=2.0f;
}
\$\endgroup\$
2
  • \$\begingroup\$ Thank you. If i call move this way i would be setting a new timer every time. Maybe it`s better to check if timer is set somehow and set it if its not? And set the timer of with cancel() when its higher than 350? \$\endgroup\$ Feb 15, 2014 at 22:08
  • \$\begingroup\$ Might not be suitable for this certain situation, it was just a tip for future use :) Dont forge to accept answer if u found it helpful \$\endgroup\$
    – Green_qaue
    Feb 15, 2014 at 22:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .