开始游戏。我有一个可移动的篮子和一个 - 现在 - stationairy苹果。在游戏的更新步骤中,我检查两者之间的碰撞。在将来,我想添加多个苹果,所以我正在寻找检测篮子和苹果x之间碰撞的最佳方法。
得到代码:
public void update() {
int basketcenterX = basket.getX() + (basket.getWidth() / 2);
int basketcenterY = basket.getY() + (basket.getHeight() / 2);
if (basketcenterX < apple.getX() + apple.getWidth() && basketcenterX > apple.getX())
if ( basketcenterY < apple.getY() + apple.getHeight() && basketcenterY > apple.getY())
{
Log.d(TAG, "Collision detected!!");
}
Log.d(TAG, "Apple Safe!");}
在模拟器中看起来相当滞后,我担心当我添加更多的apple实例时它会太慢。关于如何改进这个和/或如何改进这个以检查多个苹果的任何建议?
答案 0 :(得分:4)
您的代码有两项主要改进。
不要过度使用getter和setter。与普通的Java应用程序相比,那些在android中无法优化。只需创建像
这样的公共属性public float positionX;
直接访问它们。
您不想移动并将位图留在顶部。你想拥有它的位置,它的位置就是它的中心。因此,将您的位图包装到自定义类GameObject
或类似内容中,并预先计算中心。你只需要修改中心。
gameObjectPosition = basket.getX() + (basket.getWidth() / 2)
将位图的宽度和高度存储在GameObject
类的公共字段中,然后直接访问它们。
/**
A possible GameObject class.
**/
public class GameObject{
private Bitmap bitmap;
public float width, height;
public float positionX;
public float positionY;
public GameObject(Bitmap bitmap){
this.bitmap = bitmap;
width = bitmap.getWidth();
height = btimap.getHeight();
}
public void draw(...){
bitmap.draw(positionX-width/2, positionY-height/2);
}
}
如果您仍然关注效果,也可以预先计算width/2
和height/2
。
答案 1 :(得分:1)
同意迈克尔所说的话。也不要在模拟器上测试它,因为它对于游戏开发者来说太慢了,而是拿起设备。
答案 2 :(得分:0)
我不知道这是否更快但不是这样做(考虑迈克尔的答案):
if (basketcenterX < apple.getX() + apple.getWidth() && basketcenterX > apple.getX())
if ( basketcenterY < apple.getY() + apple.getHeight() && basketcenterY > apple.getY())
你可以使用像这样的矢量概念:
计算两点之间的矢量距离
distanceVectorX = GameObjectBasket.positionX - GameObjectApple.positionX;
distanceVectorY = GameObjectBasket.positionY - GameObjectApple.positionY;
然后计算此向量的大小,即两点之间的距离
distance = Math.sqrt(Math.pow(distanceVectorX, 2) + Math.pow(distanceVectorY, 2))
现在,您可以在设备中对此进行测试,以确定此操作是否更快。