文本从左到右填充

时间:2018-06-22 11:13:20

标签: android game-engine

enter image description here

如何开始填写类似于此屏幕的文字?我应该使用Handler并延迟每个字符吗?

背景是,我正在为Android编写类似于经典Moon Patrol的迷你游戏,现在我想为完成检查点创造奖励。

您可以在应用商店https://play.google.com/store/apps/details?id=dev.android.buggy中找到我的测试版,它的当前名称为“月球车”。该代码可根据要求提供,目前此回购是封闭源。 enter image description here

我在“ C”检查点放置了一个测试检查点,以显示我尝试的操作:

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class ParallaxView extends SurfaceView implements Runnable, SurfaceHolder.Callback {
    int bombed = 5;
    boolean waitForTimer = false;
    boolean waitForTimer2 = false;
    boolean recent = true;
    char checkpoint;
    boolean checkp = true;
    Rect fromRect1;
    Rect toRect1;
    Rect fromRect2;
    Rect toRect2;
    boolean incCheck = true;
    boolean increment = false;
    int numberOfshots = 1;
    int[] missiles = new int[200];
    int alienBombYDelta = 0;
    int alienBombXDelta = 20;
    int p = 7;
    boolean started = false;
    final int buggyXDisplacement = 50;
    boolean buggyDown = false;
    int jumpHeight = 0;
    int xbuggy2 = 0;
    boolean down2 = true;
    long lastTurn2 = System.currentTimeMillis();
    long lastTurn3 = System.currentTimeMillis();

    boolean jump = false;
    boolean shoot = false;
    int index = 0;
    int missileOffSetY = 0;
    boolean alienReset = false;
    int score = 0;
    double buggyXDistance = 0;
    double distanceDelta = 1.15;
    double retardation = 0.5;
    boolean alienFire = false;
    List<Background> backgrounds;
    int spacerocki, resID, explodeID, explodeID2, alienResID2;

    private volatile boolean running;
    private Thread gameThread = null;
    Bitmap explode, buggy, alien, explode2, spacerock;
    boolean alienexplode = false;
    TextView tvId;
    //Activity a;
    // For drawing
    private Paint paint;
    private Canvas canvas;
    private SurfaceHolder ourHolder;

    // Holds a reference to the Activity
    Context context;

    // Control the fps
    long fps = 60;

    // Screen resolution
    int screenWidth;
    int screenHeight;
    boolean bexplode = false;
    boolean brake = false;
    boolean scoring = false;

    class BuggyExploded extends TimerTask {
        public void run() {
            //Log.d("## BuggyExploded", "## BuggyExploded timer task running after 2 seconds" + buggyXDistance);
            //buggy = BitmapFactory.decodeResource(context.getResources(), context.getResources().getIdentifier("vehicle",
            //      "drawable", context.getPackageName()));
            canvas.drawBitmap(explode, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - jumpHeight, paint);

            buggyXDistance = 0;
            distanceDelta = 1.15;
            retardation = 0.5;
            jumpHeight = 0;


            waitForTimer = false;


            //canvas.drawBitmap(buggy, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - jumpHeight, paint);
        }
    }

    class SetRecent extends TimerTask {
        public void run() {
            recent = false;
        }
    }

    class ResetCheckpoint extends TimerTask {
        public void run() {
            Background.checkpoint = 'A';
        }
    }

    class SetAlienBombs extends TimerTask {
        public void run() {
            missileOffSetY = 0;
        }
    }

    class AlienBombed extends TimerTask {
        public void run() {
            alienBombXDelta = 20;
            alienBombYDelta = 0;
            alienReset = false;
            alienexplode = false;
            waitForTimer2 = false;
        }
    }

    public void surfaceCreated(SurfaceHolder holder) {
        //Canvas c = getHolder().lockCanvas();
        //draw();
        //getHolder().unlockCanvasAndPost(c);
    }

    public void surfaceDestroyed(SurfaceHolder holder3) {
        //Canvas c = getHolder().lockCanvas();
        //draw();
        //getHolder().unlockCanvasAndPost(c);
    }

    public void surfaceChanged(SurfaceHolder holder, int i1, int i2, int i3) {
        //Canvas c = getHolder().lockCanvas();
        //draw();
        //getHolder().unlockCanvasAndPost(c);
    }

    private void update() {
        // Update all the background positions
        for (Background bg : backgrounds) {
            bg.update(fps);
        }
    }

    public ParallaxView(Context c, AttributeSet a) {
        super(c, a);

        this.context = c;
        Background.checkpoint--;
        this.screenWidth = getContext().getResources().getDisplayMetrics().widthPixels;
        this.screenHeight = getContext().getResources().getDisplayMetrics().heightPixels;

        // Initialize our drawing objects
        ourHolder = getHolder();
        paint = new Paint();

        // Initialize our array list
        backgrounds = new ArrayList<>();

        //load the background data into the Background objects and
        // place them in our GameObject arraylist

        backgrounds.add(new Background(
                this.context,
                screenWidth,
                screenHeight,
                "bg", 0, 120, 50));

        backgrounds.add(new Background(
                this.context,
                screenWidth,
                screenHeight,
                "grass", 70, 110, 200));

        //To execute the task every second after 3 s.
        //Log.d("Timer", "Timer ");
        resID = context.getResources().getIdentifier("vehicle",
                "drawable", context.getPackageName());
        explodeID = context.getResources().getIdentifier("explode",
                "drawable", context.getPackageName());
        explodeID2 = context.getResources().getIdentifier("explode2",
                "drawable", context.getPackageName());
        spacerocki = context.getResources().getIdentifier("spacerock",
                "drawable", context.getPackageName());

        buggy = BitmapFactory.decodeResource(context.getResources(), resID);
        explode = BitmapFactory.decodeResource(context.getResources(), explodeID);
        explode2 = BitmapFactory.decodeResource(context.getResources(), explodeID2);
        spacerock = BitmapFactory.decodeResource(context.getResources(), spacerocki);
        alienResID2 = context.getResources().getIdentifier("right_side_hdpi",
                "drawable", context.getPackageName());
        alien = BitmapFactory.decodeResource(context.getResources(), alienResID2);
        //resume();
        //pause();
        //resume();
    }

    @Override
    public void run() {
        while (running) {
            long startFrameTime = System.currentTimeMillis();
            update();
            if (alienBombXDelta > screenWidth - 250 || alienBombXDelta < 10) { // alien ship change direction
                p = -p;
            }
            draw();
            // Calculate the fps this frame
            long timeThisFrame = System.currentTimeMillis() - startFrameTime;
            if (timeThisFrame >= 1) {
                fps = 1000 / timeThisFrame;
            }
        }
    }


    private void checkJump() {
        if (System.currentTimeMillis() - lastTurn3 >= 650) { // 650 means how long the vehicle is in the air at a jump
            // Change direction here
            jump = false;
            lastTurn3 = System.currentTimeMillis();
        }
    }


    private void checkBuggyBombed(Bitmap b1, Bitmap b2, Bitmap explode) {
        if (!recent && java.lang.Math.abs(((buggyXDisplacement + buggyXDistance) + b1.getWidth() / 2) - (alienBombXDelta + 10 + b2.getWidth() / 2)) < b1.getWidth() / 2 && java.lang.Math.abs((alienBombYDelta + screenHeight / 100 * 25 + 75 + missileOffSetY) - ((screenHeight * 0.3) - jumpHeight + b1.getHeight())) < 65) {
            bombed--;
            missileOffSetY = 0;
            checkpoint = 'A';
            canvas.drawBitmap(explode, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - jumpHeight, paint);
            recent = true;
            waitForTimer = true;
            new Timer().schedule(new BuggyExploded(), 2000);
            new Timer().schedule(new SetRecent(), 10000);
            new Timer().schedule(new ResetCheckpoint(), 1000);

        } else {
            canvas.drawText("●", alienBombXDelta + 10 + b2.getWidth() / 2, alienBombYDelta + screenHeight / 100 * 25 + 75 + missileOffSetY, paint);
            missileOffSetY = missileOffSetY + 10;

        }

    }

    private void makeShots(Bitmap b) {
        for (int i1 = 0; i1 < numberOfshots; i1++) {
            // if vertical missile hits alien
            if (java.lang.Math.abs(alienBombXDelta + 10 - 185 - buggyXDistance) * 2 < (b.getWidth() + 60) && java.lang.Math.abs(alienBombYDelta + screenHeight / 100 * 25 - (screenHeight / 100 * 95 - missiles[i1] - xbuggy2)) * 2 < (b.getHeight() + 60)) {
                missileOffSetY = 9999;
                canvas.drawBitmap(explode2, alienBombXDelta + 10, alienBombYDelta + screenHeight / 100 * 25, paint);

                new Timer().schedule(new AlienBombed(), 2000);
                waitForTimer2 = true;

                if (!alienexplode) {
                    changeText();
                }
                alienexplode = true;
            }
            if (shoot) {
                canvas.drawText("o", (float) (missiles[i1] + buggyXDistance), (float) (screenHeight * 0.7) - jumpHeight, paint); // add to y the jump height
                canvas.drawText("o", (float) (buggyXDistance + 185), screenHeight / 110 * 95 - missiles[i1] - xbuggy2, paint);
            }
            if (i1 == numberOfshots - 1 && missiles[i1] > screenWidth) {
                if (numberOfshots > 0) numberOfshots--;
                if (index > 0) index--;
            }
        }
    }

    private void updateDeltas() {
        alienBombXDelta = alienBombXDelta + p;
        if (!down2)
            alienBombYDelta++;
        else
            alienBombYDelta--;
    }

    private void changeDirections() {
        if (System.currentTimeMillis() - lastTurn2 >= 7000) {
            // Change direction here
            down2 = !down2;
            lastTurn2 = System.currentTimeMillis();
        }
    }

    private void controlVelocity() {
        if (!brake && buggyXDistance > 0) buggyXDistance = buggyXDistance + distanceDelta;
        else if (brake && buggyXDistance > 0) buggyXDistance = buggyXDistance - retardation;
    }

    TextView tvId1;

    private void drawDetails() {
        //draw a background color
    }

    private void makeShots() {
        for (int n = 0; n < numberOfshots; n++)
            missiles[n] = missiles[n] + 20;
    }

    public void changeText() {
        if (scoring) {
            ((Activity) this.getContext()).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    score++;
                    String str = "Player 1  " + String.format("%06d", score);
                    // Stuff that updates the UI
                    tvId.setText(str);
                    scoring = false;
                }
            });
        }
    }

    double lastTurn4 = System.currentTimeMillis();

    private void checkFire() {
        if (System.currentTimeMillis() - lastTurn4 >= 18500) { // 18500 means how often the alien fires
            lastTurn4 = System.currentTimeMillis();
            missileOffSetY = 0;
        }
    }

    boolean checkpointComplete = false;

    private void draw() {

        if (ourHolder.getSurface().isValid()) {
            //First we lock the area of memory we will be drawing to
            canvas = ourHolder.lockCanvas();
            if (checkpointComplete) {
                canvas.drawColor(Color.BLACK);
                paint.setTextSize(60);
                paint.setColor(Color.argb(255, 255, 255, 255));
                paint.setTextSize(60);
                canvas.drawText("CHECKPOINT COMPLETE", (float) (screenWidth * 0.5), (float) (screenHeight * 0.45), paint);

                ((Activity) this.getContext()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                checkpointComplete = false;

                            }
                        }, 3000);

                    }
                });


            } else {
                if (bombed == 0) //GAME OVER
                {
                    final int duration = Toast.LENGTH_SHORT;


                    ((Activity) this.getContext()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            final Toast toast = Toast.makeText(context, "GAME OVER!\nScore: " + score, duration);

                            toast.show();
                            Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    toast.cancel();
                                    bombed = 5;
                                    score = 0;

                                }
                            }, 3000);


                        }
                    });


                }


                if (jump && jumpHeight < 250) {
                    jumpHeight = jumpHeight + 7;
                } else if (jumpHeight > 0) {
                    jumpHeight = jumpHeight - 4;
                }
                if (shoot) {
                    xbuggy2 = xbuggy2 + 4;
                }
                checkFire();
                checkJump();
                //    drawDetails();

                if (canvas != null) canvas.drawColor(Color.argb(255, 0, 0, 0));
                // Draw the background parallax
                drawBackground(0);
                // Draw the rest of the game
                paint.setTextSize(60);
                paint.setColor(Color.argb(255, 255, 255, 255));
                checkBuggyBombed(buggy, alien, explode);
                makeShots(alien);
                changeDirections();
                if (!waitForTimer2)
                    canvas.drawBitmap(alien, alienBombXDelta + 10, alienBombYDelta + screenHeight / 100 * 25, paint);

                drawBackground(1);

                // canvas.drawText("X", (float) (50 + buggyXDistance)+buggy.getWidth()/2, (float) (screenHeight * 0.3) - jumpHeight+buggy.getHeight(), paint);
                paint.setTextSize(60);
                canvas.drawText("A    E    J    O    T    Z", (float) (screenWidth * 0.7), (float) (screenHeight * 0.15), paint);

                // Prevent buggy from moving outside horizontal screen
                if (!brake && buggyXDisplacement + buggyXDistance > screenWidth - buggy.getWidth() - 200)
                    buggyXDistance = screenWidth - buggy.getWidth() - 200;
                //Log.d("buggyXDistance", "buggyXDistance " + buggyXDistance);

                if (!waitForTimer)
                    canvas.drawBitmap(buggy, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - jumpHeight, paint);
                else if (bexplode)
                    canvas.drawBitmap(explode, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - jumpHeight, paint);

                int inc = 0;
                for (int i = 0; i < bombed; i++) {
                    canvas.drawBitmap(Bitmap.createScaledBitmap(buggy, (int) (0.75 * (buggy.getWidth() / 3)), buggy.getHeight() / 3, false), inc, 100, paint);
                    inc = inc + buggy.getWidth() / 3;
                }

                makeShots();
                updateDeltas();
                controlVelocity();

            }
            ourHolder.unlockCanvasAndPost(canvas);
        }
    }

    // Clean up our thread if the game is stopped
    public void pause() {
        running = false;
        try {
            gameThread.join();
        } catch (InterruptedException e) {
            // Error
            //e.printStackTrace();
        }
    }

    // Make a new thread and start it
    // Execution moves to our run method
    public void resume() {
        running = true;
        gameThread = new Thread(this);
        gameThread.start();
    }


    private void drawBackground(int position) {

        // Make a copy of the relevant background
        Background bg = backgrounds.get(position);

        // define what portion of images to capture and
        // what coordinates of screen to draw them at

        // For the regular bitmap
        fromRect1 = new Rect(0, 0, bg.width - bg.xClip, bg.height);
        toRect1 = new Rect(bg.xClip, bg.startY, bg.width, bg.endY);

        // For the reversed background
        fromRect2 = new Rect(bg.width - bg.xClip, 0, bg.width, bg.height);
        toRect2 = new Rect(0, bg.startY, bg.xClip, bg.endY);

//        Log.d("### bg.xClip", "bg.xClip " + bg.xClip);

        //draw the two background bitmaps
        if (!bg.reversedFirst) {

            if (canvas != null) canvas.drawBitmap(bg.bitmap, fromRect1, toRect1, paint);
            if (canvas != null) canvas.drawBitmap(bg.bitmapReversed, fromRect2, toRect2, paint);
            if (position == 1) { // && Background.count % 2 == 0) {
                if (increment) Background.checkpoint++;
                if (Background.checkpoint == 'C' &&   (buggyXDisplacement + buggyXDistance) < (bg.xClip) && java.lang.Math.abs((buggyXDisplacement + buggyXDistance) - (bg.xClip)) < buggy.getWidth()) { // && java.lang.Math.abs((alienBombYDelta + screenHeight / 100 * 25 + 75 + missileOffSetY) - ((screenHeight * 0.3) - jumpHeight )) < 65) {) checkpointComplete = true;
                    checkpointComplete=true;
                }
                increment = false;
                if (bg.xClip == bg.width) increment = true;
                if (canvas != null) canvas.drawBitmap(spacerock, fromRect1, toRect1, paint);
                paint.setTextSize(160);
                if (canvas != null)
                    canvas.drawText(Character.toString(Background.checkpoint), bg.xClip, (float) (bg.startY * 1.4), paint);
                //increment checkpoint once per what? "Background.checkpoint++;"

                ((Activity) this.getContext()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvId1.setText(Character.toString(Background.checkpoint));
                    }
                });


                if (!recent && (buggyXDisplacement + buggyXDistance) < (bg.xClip) && java.lang.Math.abs((screenHeight * 0.5) - jumpHeight - bg.startY) < 180 && java.lang.Math.abs((buggyXDisplacement + buggyXDistance) - (bg.xClip)) < buggy.getWidth()) { // && java.lang.Math.abs((alienBombYDelta + screenHeight / 100 * 25 + 75 + missileOffSetY) - ((screenHeight * 0.3) - jumpHeight )) < 65) {
                    canvas.drawBitmap(explode, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - jumpHeight, paint);
                    // Background.checkpoint = 'A';
                    bombed--;
                    recent = true;
                    waitForTimer = true;
                    bexplode = true;
                    canvas.drawBitmap(explode, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - jumpHeight, paint);


                    distanceDelta = 1.15;
                    retardation = 0.5;
                    jumpHeight = 0;

                    ((Activity) this.getContext()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    waitForTimer = false;
                                    buggyXDistance = 0;
                                }
                            }, 2000);


                        }
                    });

                    // new Timer().schedule(new BuggyExploded(), 2000);
                    new Timer().schedule(new SetRecent(), 10000);
                    new Timer().schedule(new ResetCheckpoint(), 1000);
                }
            }
        } else {
            canvas.drawBitmap(bg.bitmap, fromRect2, toRect2, paint);
            canvas.drawBitmap(bg.bitmapReversed, fromRect1, toRect1, paint);
        }
    }

    // Because we call this from onTouchEvent, this code will be executed for both
    // normal touch events and for when the system calls this using Accessibility
    @Override
    public boolean performClick() {
        super.performClick();
        launchMissile();
        return true;
    }

    protected void launchMissile() {
        missiles[index] = 350; // what does it do?
        index++;
        xbuggy2 = 0;
        shoot = true;
    }

    // event listener for when the user touches the screen
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        boolean gameOver = false;
        //if (paused) {
        //   paused = false;
        //}
        int action = MotionEventCompat.getActionMasked(event);
        int coordX = (int) event.getX();
        int coordY = (int) event.getY();
        //Log.d("coordY", "coordY " + coordY);
        if (coordX < 220 && jumpHeight == 0 && action == MotionEvent.ACTION_MOVE) {
            jump = true;
            shoot = false;
            lastTurn3 = System.currentTimeMillis();
            return true; // do nothing
        }

        if (coordX > 219 && action == MotionEvent.ACTION_DOWN) {
            numberOfshots++;
            performClick();
            return true;
        }
        return true;
    }
}
  [

2]:https://i.stack.imgur.com/3NAmp.gif

1 个答案:

答案 0 :(得分:2)

您可以按照以下代码

public void setText(final String s)
    {
    TextView tv= (TextView) tf.getView().findViewById(R.id.textview1);
    final int[] i = new int[1];
    i[0] = 0;
    final int length = s.length();
    final Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            char c= s.charAt(i[0]);
            Log.d("Strange",""+c);
            tv.append(String.valueOf(c));
            i[0]++;
        }
    };

    final Timer timer = new Timer();
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            handler.sendEmptyMessage(0);
            if (i[0] == length - 1) {
                timer.cancel();
            }
        }
    };
    timer.schedule(timerTask, 1, 500);
}

认为这一定会对您有所帮助