android - 来回移动球

标签 android

试图让球在屏幕上来回移动(左右)。

我尝试使用 draw 函数通过 if 语句更新球的位置

x += speed_x;
y += speed_y;
canvas.drawCircle(x, y, 20, paint);
if (x == 0)
    speed_x=-1;
if (x == getHeight())
    speed_x=1;
if (y == 0)
    speed_y = -1;
if (y == getWidth())
    speed_y = 1;
invalidate();

这没有用。

 **game.java*
    import android.content.Context;
    import android.graphics.BitmapFactory;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.view.MotionEvent;
    import android.view.SurfaceHolder;
    import android.view.SurfaceView;

    import android.graphics.drawable.BitmapDrawable;
    import android.os.Handler;
    import android.util.AttributeSet;
    import android.widget.ImageView;

    public class GameWorld extends SurfaceView implements Runnable {
    boolean isRunning;
    GameObject obj;
    SurfaceHolder holder;
    Canvas canvas;
    Thread gameThread;
    Paint paint;

    private Context mContext;

    int x = -1;

    int y = -1;
    int speed_x=1, speed_y=1;

    private int xVelocity = 10;

    private int yVelocity = 5;

    private Handler h;

    private final int FRAME_RATE = 30;


    public GameWorld(Context context, AttributeSet attrs)  {

            super(context, attrs);

            mContext = context;

            h = new Handler();

    }


     private Runnable r = new Runnable() {

             @Override

             public void run() {

                     invalidate();

             }

     };




    public GameWorld(Context context){
    super(context);
    isRunning=true;
    obj=new GameObject(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),200,300);
    paint=new Paint();
    gameThread= new Thread(this);
    gameThread.start();
    holder=getHolder();
    }


    public void run(){
        while(isRunning){
            if(!holder.getSurface().isValid()){
                continue;
            }
            update();
            draw();
            }
        }

        private void update(){
            obj.update();
        }

        private void draw(){


            canvas=holder.lockCanvas();
            paint.setColor(Color.BLACK);
            paint.setStyle(Paint.Style.FILL);
            canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
            obj.draw(canvas);
               canvas.drawColor(Color.WHITE);
            x+=speed_x;
            y+=speed_y;
            canvas.drawCircle(x, y, 20, paint);
            if(x==0)
                speed_x=-1;
            if(x== getHeight())
                speed_x=1;
            if(y==0)
                speed_y=-1;
            if(y==getWidth())
                speed_y=1;
         invalidate();

            holder.unlockCanvasAndPost(canvas);

        }

        public boolean onTouchEvent(MotionEvent event){

            obj.jump();
            return super.onTouchEvent(event);
        }
    }



    **main:**



    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;

    public class MainActivity extends Activity {


        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(new GameWorld(this));
        }
    }



    **gameobject.java**

    import android.graphics.Bitmap;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;

    public class GameObject {
    int x,y;
    int velY;
    int width, height;
    boolean jump;
    Bitmap bitmap;
    final int GRAVITY =2;


    public GameObject(Bitmap bitmap, int x, int y){
        this.x=x;
        this.y=y;
        this.width=bitmap.getWidth();
        this.height=bitmap.getHeight();
        this.bitmap=bitmap;
        velY=0;
        jump=false;
    }

    public void update(){
        //handles input
        if (jump){
            velY=-30;
        }
    //add gravity
        velY+=GRAVITY;

        y+=velY;

    //POSITION
        if(y>300){
        y=300;
        velY=0;
        }
        jump=false;


    }
        public void jump(){
            jump=true;
        }
    Paint paint = new Paint();
        public void draw(Canvas canvas){
            canvas.drawBitmap(bitmap,x,y,null);
            int x=5; //ball
            boolean game = true;
        //  while(game = true)
        //  {
            int maxx = canvas.getWidth();
            if (x <= maxx)
            {
            paint.setColor(Color.WHITE);
            canvas.drawCircle(x, 305, 10, paint);
            x= (x+2);
            }
            ///else{
            //  x= (x-2);
            //  paint.setColor(Color.WHITE);
            //  canvas.drawCircle(x, 305, 10, paint);

            //  game = false;
            //}
        //  }
        }

        public void moveball()
        {
            x= (x-2);
        }


    }

最佳答案

这是我根据收到的滑动移动的球的版本

import android.app.Activity;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.view.View;

public class BouncingBallActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    View boundcingBallView = new BouncingBallView(this);

        setContentView(boundcingBallView);
    }



}

这是使球成为现实的 View

 package com.example.bouncingball;

import java.util.Formatter;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;



public class BouncingBallView extends View {

    private int xMin=0,xMax,yMin=0,yMax;
    private float ballRadius = 80,ballX = ballRadius+20, ballY= ballRadius+40,ballSpeedX=5,ballSpeedY=3,previousX,previousY;
    private RectF ballBounds;
    private Paint paint;
    private StringBuilder statusmsg = new StringBuilder();
    private Formatter formatter = new Formatter(statusmsg);


    public BouncingBallView(Context context) {
        super(context);
        ballBounds = new RectF();
        paint = new Paint();
paint.setDither(true);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setHinting(Paint.HINTING_ON);
paint.setPathEffect(new DashPathEffect(new float[] {1,1}, 0));

        paint.setTypeface(Typeface.MONOSPACE);
        paint.setTextSize(16);
        this.setFocusableInTouchMode(true);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        ballBounds.set(ballX-ballRadius , ballY-ballRadius,ballX+ballRadius,ballY+ballRadius);
        paint.setColor(Color.GREEN);        
        canvas.drawOval(ballBounds, paint);


        paint.setColor(Color.BLACK);
        canvas.drawText(statusmsg.toString(), 10, 30,paint);

        update();


        invalidate();
    }

    private void update() {

        ballX +=ballSpeedX;
        ballY+=ballSpeedY;

        if(ballX+ballRadius> yMax) {
            ballSpeedX =-ballSpeedX;
            ballX = xMax -ballRadius;
        }
        else if(ballX - ballRadius < xMin) {
            ballSpeedX = -ballSpeedX;
            ballX = xMin+ballRadius;

        }
        if(ballY + ballRadius > yMax) {
            ballSpeedY = -ballSpeedY;
            ballY = yMax-ballRadius;
        }
        else if (ballY - ballRadius < yMin) {
            ballSpeedY = -ballSpeedY;
            ballY = yMin+ballRadius;
        }

        statusmsg.delete(0, statusmsg.length());
        formatter.format("Ball@(%3.0f,%3.0f),Speed=(%2.0f,%2.0f)", ballX, ballY,ballSpeedX, ballSpeedY);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        xMax = w-1;
        yMax = h-1;

    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch(keyCode) {
        case KeyEvent.KEYCODE_DPAD_RIGHT:
            ballSpeedX++;
            break;
        case KeyEvent.KEYCODE_DPAD_LEFT:
            ballSpeedX--;
            break;
        case KeyEvent.KEYCODE_DPAD_UP:
            ballSpeedY--;
            break;
        case KeyEvent.KEYCODE_DPAD_DOWN:
            ballSpeedY++;
            break;
        case KeyEvent.KEYCODE_DPAD_CENTER:
            ballSpeedX = 0;
            ballSpeedY = 0;
            break;
        case KeyEvent.KEYCODE_A:
            float maxRadius = (xMax > yMax) ? yMax / 2* 0.9f : xMax / 2 * 0.9f;
            if(ballRadius < maxRadius)
                ballRadius*=1.05;
            break;
        case KeyEvent.KEYCODE_Z:
            if(ballRadius>20){
                ballRadius *=0.95;
            }
            break;
        }
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        float currentX=event.getX();
        float currentY = event.getY();
        float deltaX,deltaY;
        float scalingFactor = 5.0f / ((xMax > yMax) ? yMax : xMax);

        switch(event.getAction()) {
        case MotionEvent.ACTION_MOVE:
        deltaX = currentX - previousX;
        deltaY = currentY - previousY;
        ballSpeedX += deltaX*scalingFactor;
        ballSpeedY += deltaY*scalingFactor;

        }

        previousX = currentX;
        previousY = currentY;
        return true;
    }
}

关于android - 来回移动球,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23279054/

相关文章:

android - 如果从 Activity 生命周期方法内部启动,线程能够更改 ui。为什么?

java - 在多个数组上获取相同的元素值

android - 在主要 Activity 的选项卡顶部拉伸(stretch)的 fragment 约束布局

android - Flutter 中的 AndroidManifest 中缺少默认通知 channel 元数据

android - 将 Android POST 数据从 Packet Capture 应用程序保护到 Web 服务器 API

java - 扫描android中的OTG挂载点

java - Android Keystore 硬件支持的证明不适用于三星 Galaxy S8

android - GPS 不工作

android - RoboSpice 和 android 生命周期的麻烦

java - Android,从sqlite检索数据并显示在自定义列表中的正确方法