Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.alex.linedodger.Repository;
- import android.graphics.Canvas;
- import android.view.SurfaceHolder;
- import com.example.alex.linedodger.Constants;
- import com.example.alex.linedodger.Controller.GamePanel;
- /**
- * Created by alex on 01.03.2017.
- */
- public class MainThread extends Thread {
- private static Canvas canvas;
- private double average_FPS;
- private SurfaceHolder surfaceHolder;
- private GamePanel gamePanel;
- private boolean running;
- public MainThread(SurfaceHolder surfaceHolder, GamePanel gamePanel){
- // To be sure that the implicit constructor of [Thread] class is called
- super();
- this.surfaceHolder = surfaceHolder;
- this.gamePanel = gamePanel;
- }
- public void setRunning(boolean running){
- this.running = running;
- }
- @Override
- public void run(){
- long startTime; // when we start
- long timeMillis = 1000/ Constants.SETTINGS.MAX_FPS;
- long waitTime;
- int frameCount = 0;
- int totalTime = 0;
- int targetTime = 1000/Constants.SETTINGS.MAX_FPS;
- // Main loop
- while (running){
- startTime = System.nanoTime();
- canvas = null;
- try{
- canvas = this.surfaceHolder.lockCanvas();
- /*The synchronized keyword is all about different
- threads reading and writing to the same variables, objects and resources
- Basically: Because we use [Threads], we use synchronize to make them work on the same thing
- */
- synchronized (surfaceHolder){
- this.gamePanel.update();
- this.gamePanel.draw(canvas);
- }
- }catch (Exception e){
- // Currently we only want to se where the error is.
- e.printStackTrace();
- }finally {
- if (this.canvas != null){
- try {
- surfaceHolder.unlockCanvasAndPost(canvas);
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- }
- timeMillis = (System.nanoTime() - startTime)/1000000;
- waitTime = targetTime - timeMillis;
- try {
- // if we finished the frame earlier than the target time
- if (waitTime > 0){
- this.sleep(waitTime);
- }
- }catch (Exception e){
- e.printStackTrace();
- }
- totalTime += System.nanoTime() - startTime;
- frameCount++;
- if (frameCount == Constants.SETTINGS.MAX_FPS){
- average_FPS = 1000/((totalTime/ frameCount)/1000000);
- frameCount = 0;
- totalTime = 0;
- System.out.println(average_FPS);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement