您的位置:首页 > 移动开发 > Cocos引擎

从Delphi开始学Cocos2dx-3.0[6]:拖拽一个精灵

2013-12-23 11:43 411 查看
网上随便找了 一张图,



命名成Ball.png

然后在精灵里面分配一个 TAG给它

// 添加一张精灵图片
auto sprite = TSprite::create("ball.png");

// 设置位置到正中间
sprite->setPosition(g_ClientMidPoint);

// 添加到Helloworld图层
this->addChild(sprite, 0, 1000);

放一个指针记录是否选中精灵

class THelloWorld : public TLayer
{
private:
TSprite* m_SelectSprite;
public:
...................}

在触摸的三个事件里面这样改

bool THelloWorld::onTouchBegan(TTouch* touch, TEvent* event)
{
// 清空当前被选中的精灵指针
m_SelectSprite = NULL;

// 获取点击的坐标
int x = touch->getLocation().x;
int y = touch->getLocation().y;

// 和我们的精灵比较
TSprite* sprite = (TSprite*)(this->getChildByTag(1000));
if (NULL == sprite){return false;}

// 看看位置是否在图片上
if (
(abs(x - sprite->getPositionX()) < sprite->getContentSize().width / 2) &&
(abs(y - sprite->getPositionY()) < sprite->getContentSize().height / 2)
)
{
m_SelectSprite = sprite;
}

CCLOG("THelloWorld::onTouchBegan id = %d, x = %f, y = %f", touch->getID(), touch->getLocation().x, touch->getLocation().y);
return true;
}

void THelloWorld::onTouchMoved(TTouch* touch, TEvent* event)
{
//设置精灵位置为触点位置。
if (m_SelectSprite)
{
m_SelectSprite->setPosition(touch->getLocation());
}
CCLOG("THelloWorld::onTouchMoved id = %d, x = %f, y = %f", touch->getID(), touch->getLocation().x, touch->getLocation().y);
}

void THelloWorld::onTouchEnded(TTouch* touch, TEvent* event)
{
m_SelectSprite = NULL;
CCLOG("THelloWorld::onTouchEnded id = %d, x = %f, y = %f", touch->getID(), touch->getLocation().x, touch->getLocation().y);
}

这样精灵就给拽着走了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: