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

27 篇文章 2 订阅

网上随便找了 一张图,




命名成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);
} 

这样精灵就给拽着走了

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值