无法在画布上绘制矩形[Android Studio Game]

时间:2016-11-12 04:25:25

标签: java android canvas

所以我在网上关注如何在Android工作室制作2D游戏的复古鸡教程,我遇到了一个问题,我试图解决它,但我只是看不到找到解决方案。问题出现在他的第二个视频(https://www.youtube.com/watch?v=Rliwg0sELJo)上,他在那里运行他的代码和矩形出现在他可以移动的屏幕上。对我来说,由于某种原因,矩形不会出现在画布上,它只是一个空白的画布,即使我有与他完全相同的代码(我已经回去检查)。

有时我的应用程序有时甚至不会启动并给我这样的错误(我有最新的sdk版本和所有内容):

Cold swapped changes.
$ adb shell am start -n "com.example.ridhavraj.stardrifter/com.example.ridhavraj.stardrifter.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 3319 on device emulator-5554
W/System: ClassLoader referenced unknown path: /data/app/com.example.ridhavraj.stardrifter-2/lib/x86
I/InstantRun: Instant Run Runtime started. Android package is com.example.ridhavraj.stardrifter, real application class is null.
W/System: ClassLoader referenced unknown path: /data/app/com.example.ridhavraj.stardrifter-2/lib/x86
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1

                  [ 11-11 20:20:52.858  3319: 3343 D/         ]
                  HostConnection::get() New Host Connection established 0xaee13300, tid 3343
A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 3343 (Thread-5)

        [ 11-11 20:20:53.138  1214: 1214 W/         ]
        debuggerd: handling request: pid=3319 uid=10072 gid=10072 tid=3343
Application terminated.

以下是我从视频中制作的代码:

[GameObject Interface]

package com.example.ridhavraj.stardrifter;

import android.graphics.Canvas;

public interface GameObject {
    public void draw(Canvas canvas);
    public void update();
} 

[MainActivity Class]

package com.example.ridhavraj.stardrifter;

import android.os.Bundle;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(new GamePanel(this));
    }

}

[MainThread Class]

package com.example.ridhavraj.stardrifter;

import android.graphics.Canvas;
import android.provider.Settings;
import android.view.SurfaceHolder;

public class MainThread extends Thread{

    public static final int MAX_FPS = 30;
    private double averageFPS;
    private SurfaceHolder surfaceHolder;
    private GamePanel gamePanel;
    private boolean running;
    public static Canvas canvas;

    public void setRunning(boolean running)
    {
        this.running = running;
    }

    public MainThread(SurfaceHolder surfaceHolder, GamePanel gamePanel)
    {
        super();
        this.surfaceHolder = surfaceHolder;
        this.gamePanel = gamePanel;
    }

    @Override
    public void run()
    {
        long startTime;
        long timeMillis = 1000/MAX_FPS;
        long waitTime;
        int frameCount = 0;
        long totalTime = 0;
        long targetTime = 1000/MAX_FPS;

        while(running)
        {
            startTime = System.nanoTime();
            canvas = null;

            try
            {
                canvas = this.surfaceHolder.lockCanvas();
                synchronized (surfaceHolder)
                {
                    this.gamePanel.update();
                    this.gamePanel.draw(canvas);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            finally
            {
                if (canvas != null)
                {
                    try
                    {
                        surfaceHolder.unlockCanvasAndPost(canvas);
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }

            }

            timeMillis = (System.nanoTime()-startTime)/1000000;
            waitTime = targetTime - timeMillis;

            try
            {
                if (waitTime > 0)
                {
                    this.sleep(waitTime);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

            totalTime += System.nanoTime() - startTime;
            frameCount++;
            if (frameCount == MAX_FPS)
            {
                averageFPS = 1000/((totalTime/frameCount)/1000000);
                frameCount = 0;
                totalTime = 0;
                System.out.println(averageFPS);
            }
        }
    }

}

[GamePanel Class]

package com.example.ridhavraj.stardrifter;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class GamePanel extends SurfaceView implements SurfaceHolder.Callback {

    private MainThread thread;

    private Player player;
    private Point playerPoint;

    public GamePanel(Context context)
    {
        super(context);

        getHolder().addCallback(this);

        thread = new MainThread(getHolder(), this);

        player = new Player(new Rect(100,100,200,200), Color.rgb(255,0,0));
        playerPoint = new Point(150,150);

        setFocusable(true);
    }

    @Override
    public void surfaceChanged(SurfaceHolder Holder, int format, int width, int height)
    {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder)
    {
        thread = new MainThread(getHolder(), this);
        thread.setRunning(true);
        thread.start();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder)
    {
        boolean retry = true;
        while(true)
        {
            try
            {
                thread.setRunning(false);
                thread.join();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            retry = false;
        }
    }

    public boolean onTouchEvent(MotionEvent event)
    {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                playerPoint.set((int)event.getX(), (int)event.getY());
        }
        return true;
        //return super.onTouchEvent(event);
    }

    public void update()
    {
        player.update(playerPoint);
    }

    @Override
    public void draw(Canvas canvas)
    {
        super.draw(canvas);

        canvas.drawColor(Color.WHITE);
        player.draw(canvas);
    }
}

[玩家类]

package com.example.ridhavraj.stardrifter;

import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Canvas;
import android.graphics.Rect;

public class Player implements GameObject{

    private Rect rectangle;
    private int color;

    public Player(Rect rectangle, int Color)
    {
        this.rectangle = rectangle;
        this.color = color;
    }

    @Override
    public void draw(Canvas canvas)
    {
        Paint paint = new Paint();
        paint.setColor(color);
        canvas.drawRect(rectangle, paint);
    }

    @Override
    public void update()
    {

    }

    public void update(Point point)
    {
        //l,t,r,b
        rectangle.set(point.x-rectangle.width()/2, point.y-rectangle.height()/2, point.x+rectangle.width()/2, point.y+rectangle.height()/2);

    }
}

我不知道我做错了什么,任何帮助都会非常感激。

2 个答案:

答案 0 :(得分:1)

好吧结果伙计们,我很迟钝,球员类中有一个错字

私人矩形矩形;     private int color;

public Player(Rect rectangle, int Color [THIS SHOULD BE 'color' and not 'Color')
{
    this.rectangle = rectangle;
    this.color = color;
}

答案 1 :(得分:0)

对于 3D Rectangle(cube) 将整个代码复制到您的 CustomView 类

将其粘贴到 onDraw() 方法中
        drawCube(
                    fp.mX.toInt(), fp.mY.toInt(),
                    100 + (fp.mCx.toInt() - fp.mX.toInt()),
                    100 + fp.mCy.toInt() - fp.mY.toInt(),
                    mPaint, mCanvas!!
                )
        drawCube(
                    fp.mX.toInt(), fp.mY.toInt(),
                    100 + (fp.mCx.toInt() - fp.mX.toInt()),
                    100 + fp.mCy.toInt() - fp.mY.toInt(),
                    mStrokePaint, mCanvas!!
                )

3D Cube 函数代码

private fun drawCube(
    x: Int,
    y: Int,
    width: Int,
    height: Int,
    paint: Paint,
    canvas: Canvas
) {
    val p1 = Point(x, y)
    val p2 = Point(x, y + height)
    val p3 = Point(x + width, y + height)
    val p4 = Point(x + width, y)
    val p5 = Point(x + width / 2, y - height / 2)
    val p6 = Point(x + 3 * width / 2, y - height / 2)
    val p7 = Point(x + 3 * width / 2, y + height / 2)

    val path = Path()
    path.fillType = Path.FillType.EVEN_ODD
    path.moveTo(p1.x.toFloat(), p1.y.toFloat())
    path.lineTo(p2.x.toFloat(), p2.y.toFloat())
    path.lineTo(p3.x.toFloat(), p3.y.toFloat())
    path.lineTo(p4.x.toFloat(), p4.y.toFloat())
    path.lineTo(p1.x.toFloat(), p1.y.toFloat())
    path.lineTo(p5.x.toFloat(), p5.y.toFloat())
    path.lineTo(p6.x.toFloat(), p6.y.toFloat())
    path.lineTo(p4.x.toFloat(), p4.y.toFloat())
    path.moveTo(p3.x.toFloat(), p3.y.toFloat())
    path.lineTo(p7.x.toFloat(), p7.y.toFloat())
    path.lineTo(p6.x.toFloat(), p6.y.toFloat())
    path.lineTo(p4.x.toFloat(), p4.y.toFloat())
    path.close()
    canvas.drawPath(path, paint)

}