Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7860997
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T22:31:15+00:00 2026-06-02T22:31:15+00:00

To use a SurfaceView for drawing a 2D game in Android, I use this

  • 0

To use a SurfaceView for drawing a 2D game in Android, I use this in the main activity’s onCreate():

setContentView(new GameView(this));

Which is a reference to this class:

public class GameView extends SurfaceView implements SurfaceHolder.Callback

Additionally, I have a thread with its run() function:

public void run() {
    Canvas c;
    while (_run) {
        c = null;
        try {
            c = _surfaceHolder.lockCanvas(null);
            synchronized (_surfaceHolder) {
                _panel.updatePhysics();
                _panel.onDraw(c);
            }
        }
        finally { // when exception is thrown above we may not leave the surface in an inconsistent state
            if (c != null) {
                _surfaceHolder.unlockCanvasAndPost(c);
            }
        }
    }
}

In updatePhysics() I do some calculations. They are more complex than this simple example, of course, but work the same way:

public void updatePhysics() {
    GraphicObject.Coordinates coord;
    GraphicObject.Speed speed;
    for (GraphicObject graphic : _allElements) {
        coord = graphic.getCoordinates();
        speed = graphic.getSpeed();
        coord.setX(coord.getX() + speed.getX());
        coord.setY(coord.getY() + speed.getY());
        ...
    }
}

And in onDraw(), I draw everything to the canvas:

@Override
public void onDraw(Canvas canvas) {
    canvas.drawBitmap(BITMAP, xPos, yPos, null);
    ...
}

This works fine – everything. And when I tested it on my device, it looked pretty good. But when I gave it to someone else and he did a test game, the objects were moving much faster! Why is this so? Because the thread calls updatePhysics() as often as possible which means that fast devices call this function more often?

How can I prevent this and make the game equally fast on all devices? Something like this?

private long lastRun = System.currentTimeMillis();

public void updatePhysics() {
    long millisPassed = System.currentTimeMillis()-lastRun;
    ...
    float newCoord = (coord.getX() + speed.getX()) * millisPassed / 33;
    coord.setX(newCoord);
    ...
}

Thanks for your help!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T22:31:17+00:00Added an answer on June 2, 2026 at 10:31 pm

    If you can, use the time directly to calculate all your physics. That would usually work best.

    If you have no way to calculate based on time because what you are doing that is just step based and you know that generating the next step does not take much time then you have another option.

    You create two threads. The first one advances the state at a fixed rate (and you have to be sure that this works on slow devices at that rate too). The second one takes the current state is sees and draws that. Now the second thread can be as slow as it wants because it simply skips some states (or draws the same state several times if it is faster).

    Small example below has one thread that advances some state object and replaces the reference each time so the consuming thread does not need to worry that it’s state object gets modified

    class GameState {
        private int state = 0;
    
        public GameState advanceState() {
            GameState result = new GameState();
            result.state = this.state + 1;
            return result;
        }
    }
    
    class SurfaceViewImplementation extends SurfaceView {
    
        // the current state
        volatile GameState mState = new GameState();
    
        void somewhere() {
            Thread fastProducer = new Thread(new Runnable() {
                private static final long MAX_WAIT = 1000 / 60; 
                @Override
                public void run() {
                    while (!Thread.interrupted()) {
                        long timeBefore = SystemClock.currentThreadTimeMillis();
                        GameState newState = mState.advanceState();
                        mState = newState;
                        long timeAfter = SystemClock.currentThreadTimeMillis();
                        long timeSpent = timeAfter - timeBefore;
                        SystemClock.sleep(Math.max(0, MAX_WAIT - timeSpent));
                    }
                }
            });
            fastProducer.start();
            Thread slowConsumer = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (!Thread.interrupted()) {
                        GameState currentState = mState;
                        longRunningDraw(currentState);
                    }
                }
            });
            slowConsumer.start();
        }
    }
    

    That will still fail to give you a speed independant result if the producing thread can’t run at the desired rate.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am attempting to write an android game involving a class which extends SurfaceView
In Android I use a SurfaceView to display a simple 2D game. The bitmaps
I have this structure: 1) main activity: public class mainActivity extends Activity { @Override
I have a SurfaceView which is currently drawing a series of Bitmaps. These bitmaps
I use a surfaceview to draw a pie chart in Android. In order to
In my Android activity, I create a custom view that extends SurfaceView (using MonoDroid
I built a simple game engine using SurfaceView. I use a RectF as a
I'm working on an android game, and just recently made the step to SurfaceView
This class use to draw ball but its onDraw() function not call so ball
I'm trying to modify the SurfaceView I use for doing a camera preview in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.