的cocos2d的Android触摸精灵
问题描述:
我是新来的Cocos2D,我想知道我怎么用Java编写代码检查,看看如果我碰到一个精灵我已经尝试过这样的事情..的cocos2d的Android触摸精灵
@Override
public boolean ccTouchesEnded(MotionEvent event)
{
CGPoint location = CCDirector.sharedDirector().convertToGL(CGPoint.ccp(event.getX(), event.getY()));
if ((location.x == zom.getPosition().x) && (location.y == zom.getPosition().y))
{
CCSprite projectile = CCSprite.sprite("bullet.png");
projectile.setPosition(CGPoint.ccp(player.getPosition().x,player.getPosition().y));
addChild(projectile);
float length = (float)Math.sqrt((100 * 100) + (100 * 100));
float velocity = 100.0f/1.0f;
float realMoveDuration = length/velocity;
projectile.runAction(CCSequence.actions(
CCMoveTo.action(realMoveDuration, CGPoint.ccp(location.x, location.y)),
CCCallFuncN.action(this, "spriteMoveFinished")));
if ((projectile.getPosition().x == location.x) && (projectile.getPosition().y == location.y))
{
removeChild(projectile, true);
}
}
答
虽然我不是一个cocos2d主控制器,但它看起来像检查您的代码的逻辑是有点关闭。你想检查一下,看看触摸点是否在精灵当前区域(即((location.x >= sprite.start.x && location.x <= sprite.width) && ((location.y >= sprite.start.y && location.y <= sprite.height)
。
我认为一个更好的方法是扩展精灵类,并包含一个函数来检查一个点是否在。精灵区域(float isInSpriteArea(CGPoint point)
)这样,你可以只通过一个点一个精灵,它可以告诉你,如果它是在这种情况下,触及
答
有应该是一个最好的解决方案中使用:。
sprite.getBoundingBox.contains(x,y);
其中x和y是触摸位置的位置。
答
我希望这会帮助你。我正在使用这种方式来处理特定的触摸事件。
public boolean ccTouchesEnded(MotionEvent event) {
CGPoint location = CCDirector.sharedDirector().convertToGL(
CGPoint.ccp(event.getX(), event.getY()));
if (CGRect.containsPoint((newGame1.getBoundingBox()), location)) {
newGame();
}
return super.ccTouchesEnded(event);
}
请加这构造器
this.setIsTouchEnabled(true);
只是好奇,你的函数不返回一个布尔值,按要求。 – Raptor