我想编写一个点球大战应用程序,现在我已经设置了背景,并将球和守门员添加到地图中。我怎么做才能让我在屏幕上轻拍时,球跟着我在屏幕上的触摸。如何做到这一点?如何在屏幕上跟踪触球,并在我触球后进入球。
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
window.decorView.systemUiVisibility =
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
View.SYSTEM_UI_FLAG_FULLSCREEN
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/main_bg"
tools:context=".MainActivity">
<ImageView
android:id="@+id/ball"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ball"
app:layout_editor_absoluteX="150dp"
app:layout_editor_absoluteY="500dp"
tools:ignore="MissingConstraints" />
<ImageView
android:layout_width="150dp"
android:layout_height="150dp"
app:layout_editor_absoluteX="125dp"
app:layout_editor_absoluteY="300dp"
android:src="@drawable/goalkeeper"
</androidx.constraintlayout.widget.ConstraintLayout>
屏幕应用程序
我找到了我问题的答案,你需要使用onTouchListener。我的代码是这样的:
ImageView ballView;
float xDown = 0, yDown = 0;
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
ballView = findViewById(R.id.ball);
ballView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getActionMasked()) {
///пользователь просто прикоснулся к мячу
case MotionEvent.ACTION_DOWN:
xDown = motionEvent.getX();
yDown = motionEvent.getY();
break;
///пользователь водит по экрану
case MotionEvent.ACTION_MOVE:
float movedX, movedY;
movedX = motionEvent.getX();
movedY = motionEvent.getY();
float distanceX = movedX - xDown;
float distanceY = movedY - yDown;
ballView.setX(ballView.getX() + distanceX);
ballView.setY(ballView.getY() + distanceY);
break;
}
return true;
}
});