我需要帮助让两个ImageViews发生碰撞,我浏览了这个网站和许多youtube视频,并认为我找到了一个解决方案来解决我的问题。我从另一个人的帖子中找到了一些代码,
how to detect when a ImageView is in collision with another ImageView?
而我只是想知道我应该将代码放在我的程序中,因为当它位于底部时我会尝试log.d来显示我是否成功检测到imageViews是否发生了碰撞并且没有显示任何内容。无论如何,这里是我的代码,我在另一个问题中使用的代码位于最底层并用作注释。如果你帮助了我,你的帮助是非常感激的,谢谢你!
Main.java
package com.example.admin.basketball;
import android.graphics.Point;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
//Layout
private RelativeLayout myLayout = null;
//Screen Size
private int screenWidth;
private int screenHeight;
//Position
private float ballDownY;
private float ballDownX;
//Initialize Class
private Handler handler = new Handler();
private Timer timer = new Timer();
//Images
private ImageView net = null;
private ImageView ball = null;
//for net movement along x-axis
float x;
float y;
//points
private int points = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLayout = (RelativeLayout) findViewById(R.id.myLayout);
//score
final TextView score = (TextView) findViewById(R.id.score);
//imageviews
net = (ImageView) findViewById(R.id.net);
ball = (ImageView) findViewById(R.id.ball);
//retrieving screen size
WindowManager wm = getWindowManager();
Display disp = wm.getDefaultDisplay();
Point size = new Point();
disp.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
//move to out of screen
ball.setX(-80.0f);
ball.setY(screenHeight + 80.0f);
//start timer
timer.schedule(new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
changePos();
}
});
}
}, 0, 20);
}
public void changePos() {
//down
ballDownY += 10;
if (ball.getY() > screenHeight) {
ballDownX = (float) Math.floor((Math.random() * (screenWidth -
ball.getWidth())));
ballDownY = -100.0f;
}
ball.setY(ballDownY);
ball.setX(ballDownX);
//make net follow finger
myLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
MainActivity.this.x = event.getX();
y = event.getY();
if (event.getAction() == MotionEvent.ACTION_MOVE) {
net.setX(MainActivity.this.x);
net.setY(y);
}
return true;
}
});
}
}
/*
private boolean viewsOverlap(ImageView net, ImageView ball) {
int[] net_coords = new int[2];
net.getLocationOnScreen(net_coords);
int net_w = net.getWidth();
int net_h = net.getHeight();
Rect net_rect = new Rect(net_coords[0], net_coords[1], net_coords[0] +
net_w, net_coords[1] + net_h);
int[] ball_coords = new int[2];
ball.getLocationOnScreen(ball_coords);
int ball_w = ball.getWidth();
int ball_h = ball.getHeight();
Rect ball_rect = new Rect(ball_coords[0], ball_coords[1], ball_coords[0]
+ ball_w, ball_coords[1] + ball_h);
return net_rect.intersect(ball_rect) || net_rect.contains(ball_rect) ||
ball_rect.contains(net_rect);
}*/
答案 0 :(得分:2)
import tensorflow as tf
import numpy as np
import sys
sys.path.insert(0, '.../Dataset/Testing/')
sys.path.insert(0, '.../Dataset/Training/')
#other files
from TestDataNormaliser import *
from TrainDataNormaliser import *
learning_rate = 0.01
trainingIteration = 10
batchSize = 100
displayStep = 1
x = tf.placeholder("float", [None, 3])
y = tf.placeholder("float", [None, 2])
#layer 1
w1 = tf.Variable(tf.truncated_normal([3, 4], stddev=0.1))
b1 = tf.Variable(tf.zeros([4]))
y1 = tf.matmul(x, w1) + b1
#layer 2
w2 = tf.Variable(tf.truncated_normal([4, 4], stddev=0.1))
b2 = tf.Variable(tf.zeros([4]))
#y2 = tf.nn.sigmoid(tf.matmul(y1, w2) + b2)
y2 = tf.matmul(y1, w2) + b2
w3 = tf.Variable(tf.truncated_normal([4, 2], stddev=0.1))
b3 = tf.Variable(tf.zeros([2]))
y3 = tf.nn.sigmoid(tf.matmul(y2, w3) + b3) #sigmoid
#output
#wO = tf.Variable(tf.truncated_normal([2, 2], stddev=0.1))
#bO = tf.Variable(tf.zeros([2]))
a = y3 #tf.nn.softmax(tf.matmul(y2, wO) + bO) #y2
a_ = tf.placeholder("float", [None, 2])
#cost function
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(a)))
#cross_entropy = -tf.reduce_sum(y*tf.log(a))
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)
#training
init = tf.global_variables_initializer() #initialises tensorflow
with tf.Session() as sess:
sess.run(init) #runs the initialiser
writer = tf.summary.FileWriter(".../Logs")
writer.add_graph(sess.graph)
merged_summary = tf.summary.merge_all()
for iteration in range(trainingIteration):
avg_cost = 0
totalBatch = int(len(trainArrayValues)/batchSize) #1000/100
#totalBatch = 10
for i in range(batchSize):
start = i
end = i + batchSize #100
xBatch = trainArrayValues[start:end]
yBatch = trainArrayLabels[start:end]
#feeding training data
sess.run(optimizer, feed_dict={x: xBatch, y: yBatch})
i += batchSize
avg_cost += sess.run(cross_entropy, feed_dict={x: xBatch, y: yBatch})/totalBatch
if iteration % displayStep == 0:
print("Iteration:", '%04d' % (iteration + 1), "cost=", "{:.9f}".format(avg_cost))
#
print("Training complete")
predictions = tf.equal(tf.argmax(a, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(predictions, "float"))
print("Accuracy:", accuracy.eval({x: testArrayValues, y: testArrayLabels}))
答案 1 :(得分:-1)
让我举个例子,说明我是如何在10行代码中实现工作冲突检测的。这不是完全相同的问题,但它可以让您了解如何基于坐标操纵对象。
// update the canvas in order to display the game action
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
int xx = 200;
int yy = 0;
if (persons != null) {
synchronized (persons) {
Iterator<Person> iterate = persons.iterator();
while (iterate.hasNext()) {
Person p = iterate.next();
if (p.getImage() != 0) {
bitmap = BitmapFactory.decodeResource(getResources(), p.getImage()); //load a character image
// Draw the visible person's appearance
if(xx > canvas.getWidth())
xx = 0;
canvas.drawBitmap(bitmap, xx , canvas.getHeight()- bitmap.getHeight() , null);
// Draw the name
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
canvas.save();
paint.setStrokeWidth(1);
paint.setColor(Color.WHITE);
paint.setTextSize(50);
canvas.drawText(p.name, (float)(xx+0.25*bitmap.getWidth()), (float) (canvas.getHeight() ), paint);
xx += bitmap.getWidth()*0.75;
}
}
}
}
canvas.save(); //Save the position of the canvas.
canvas.restore();
//Call the next frame.
invalidate();
}
}
在上面的代码中,我只检查xx
是否与其他图像数组发生冲突,然后我只是相应地更新xx
。欢迎您使用此代码查看我的open source repository。