¿Cómo puedo mover una imagen de un punto a otro mediante Android Canvas?

Estoy desarrollando un juego, y en este juego tengo que mover una imagen en una lona de un punto a otro en cualquier dirección, no sólo vertical u horizontal.

¿Cómo puedo mover esa imagen de esta manera?

Echa un vistazo a esta biblioteca. Debe ayudarle con el movimiento, y creo que arrastra objetos como imagen, etc – PhysicsLayout . Aquí se puede ver moviéndose con dos direcciones – X, Y. Si desea mover incluyendo Z, sólo hay una forma sencilla de implementarlo, debe utilizar escala simple.

Si quieres algo más, hay un montón de marcos de gran alcance y bastante agradable, el medio ambiente.

Introduzca aquí la descripción de la imagen

Después de obtener una conferencia de matemáticas, resulta que esto es fácil de resolver. En primer lugar, necesitamos obtener el ángulo en el que se moverá el objetivo.

float deltaX = targetX - startX; float deltaY = targetY - startY; float angle = Math.atan2( deltaY, deltaX ); 

StartX / Y puede ser actual X / Y.

Ahora que hemos calculado el ángulo, podemos aplicarlo a las coordenadas actuales:

 currentX += speed * Math.cos(angle);//Using cos currentY += speed * Math.sin(angle);//or sin 

Para manejar los cálculos de cuánto X e Y serán aumentados por. Utilizar la velocidad como una variable personalizada si necesita tener una velocidad personalizada también. Si no necesita más velocidad, elimine la variable.

Y para mover el objeto, aplique X / Y al objeto:

 c.drawBitmap(bm, x, y, null); 

Ejemplo:

 int speed = 10; int x, y; int targetX = 100, targetY = 600; int startX = 900, startY = 100; public void render(Canvas c){ super.draw(c); float deltaX = targetX - startX; float deltaY = targetY - startY; float angle = Math.atan2( deltaY, deltaX ); x += speed * Math.cos(angle);//Using cos y += speed * Math.sin(angle);//or sin c.drawBitmap(bm, x, y, null); (...) } 

No pude entender lo que realmente quieres, pero aquí hay algo que he intentado.

  interface coordinateListener { public void currentPosition(float x,float y); } public class ImageView extends View{ int width; int height; RectF rect = new RectF(); float x=0f,y=0f; float dX,dY; float mStartX,mStartY; float mEndX,mEndY; Paint paint = new Paint(); Bitmap mBitmap; TranslateAnimation anim; View view; coordinateListener mListener; public ImageView(Context context) { super(context); init(); } public ImageView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ImageView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public void init() { view = this; } @Override protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec) { super.onMeasure(widthMeasureSpec,heightMeasureSpec); width = getMeasuredWidth(); height = getMeasuredHeight(); rect.set(0,0,width,height); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if(mBitmap!=null) { canvas.drawBitmap(mBitmap,0,0,paint); } } @Override public boolean onTouchEvent(MotionEvent event) { int action = event.getAction() & MotionEvent.ACTION_MASK; switch (action) { case MotionEvent.ACTION_DOWN: dX = this.getX() - event.getRawX(); dY = this.getY() - event.getRawY(); break; case MotionEvent.ACTION_MOVE: y = event.getRawY(); x = event.getRawX(); y += dY; x+=dX; this.setY(y); this.setX(x); mListener = (coordinateListener)getContext(); mListener.currentPosition(x,y); invalidate(); break; } return true; } public void startCoordinates(float x,float y) { mStartX = x; mStartY = y; } public void endCoordinates(float x,float y) { mEndX = x; mEndY = y; } public void startTranslation(long duration) { anim = new TranslateAnimation(mStartX,mEndX,mStartY,mEndY); anim.setDuration(duration); anim.setFillAfter(true); anim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { view.setX((int)mEndX); view.setY((int)mEndY); animation.setFillAfter(false); } @Override public void onAnimationRepeat(Animation animation) { } }); this.startAnimation(anim); } } 

Puede arrastrarlo de una posición a otra o puede usar Traducir para moverlo … así,

 view.startCoordinates(0f,0f); view.endCoordinates(500f,0f); view.startTranslation(3000); 
  • Android: Cómo comprobar si el número SMS entrante existe en el teléfono de contacto en BroadcastReceiver y el bloque es el número no existe
  • Retrofit "Autorización", "Portador" + token
  • Margen entre las etiquetas del título del eje X y del eje X en AChartEngine
  • no puede pasar por referencia para una variable booleana en android
  • Android: no parece poder usar MotionEvent.ACTION_MOVE correctamente
  • Grupo de usuarios en firebase
  • Gson, cómo deserializar matriz o cadena vacía
  • Android Resource - Array de matrices
  • Intenta invocar el método virtual 'boolean com.google.android.finsky.api.model.DfeToc.isGplusSignupEnabled ()' en una referencia de objeto nulo
  • Compruebe si la hora actual es más de una hora desde el tiempo "last_updated"
  • "Necesita usar un tema Theme.Appcompat ..." al probar ActionBarActivity, pero estoy
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.