如果这是一个复制品,并且我的google-fu很弱,很抱歉。
我的代码中有两个方法路由选项:
使用调用一组对象属性的本地方法:
/* public class Manager */
public void onTouchEvent( Event event )
{
Vec2 touch = new Vec2( event.getX(), event.getY() );
for( GameObject o : mGameObjectList )
{
if ( isColliding( touch, o ) )
o.onTouchEvent(event);
}
}
public boolean isColliding( Vec2 touch, GameObject obj )
{
if ( ( obj.mPosition[ 0 ] - obj.mScale[ 0 ] ) < touch.x && touch.x < ( obj.mPosition[ 0 ] + obj.mScale[ 0 ] ) )
{
if ( ( obj.mPosition[ 1 ] - obj.mScale[ 1 ] ) < touch.y && touch.y < ( obj.mPosition[ 1 ] + obj.mScale[ 1 ] ) )
{
return true;
}
}
return false;
}
调用对象方法,然后使用本地属性:
/* public class Manager */
public void onTouchEvent( Event event )
{
for( GameObject o : mGameObjectList )
{
o.isColliding(event);
}
}
/* public class GameObject */
public boolean isColliding( Event event )
{
// code here to get touch from event ( or maybe pass in touch? )
if ( ( mPosition[ 0 ] - mScale[ 0 ] ) < touch.x && touch.x < mPosition[ 0 ] + ( mScale[ 0 ] ) )
{
if ( ( mPosition[ 1 ] - mScale[ 1 ] ) < touch.y && touch.y < mPosition[ 1 ] + ( mScale[ 1 ] ) )
{
onTouchEvent(event)
}
}
return false;
}
哪组方法在编程上更好(优化、优雅、简单等)?
更新:修复了代码部分。对这一切我很抱歉。
发布于 2012-08-29 18:30:35
我会用GameObject::containsPoint(x, y)
方法来写这段代码。这样,它就不需要知道触摸事件,但你的触摸类也不需要知道如何计算交叉点。
编辑:
这就是我会怎么做。
/* class GameObject */
public boolean contains(int x, int y)
{
//Your use of parentheses here was really confusing!
return mPosition[0] - mScale[0] < x && x < mPosition[0] + mScale[0]
&& mPosition[1] - mScale[1] < y && y < mPosition[1] + mScale[1];
/* alternatively:
return Math.abs(x - mPosition[0]) < mScale[0]
&& Math.abs(y - mPosition[1]) < mScale[1];
*/
}
/* class Manager */
public void onTouchEvent( Event event )
{
for( GameObject o : mGameObjectList )
{
if(o.contains(event.getX(), event.getY()))
{
o.onTouchEvent(event);
}
}
}
我不确定在这里向Vec2
的转换是否有成效(或一致性)。为什么触点被提升为Vec2
,而GameObject::mPosition
却是一个数组?
https://stackoverflow.com/questions/12184204
复制相似问题